fix debug output (bug #4562)
[asterisk/asterisk.git] / channels / chan_iax2.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Inter-Asterisk eXchange Version 2
5  *
6  * Copyright (C) 2003 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include "asterisk.h"
15
16 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
17
18 #include "asterisk/lock.h"
19 #include "asterisk/frame.h" 
20 #include "asterisk/channel.h"
21 #include "asterisk/logger.h"
22 #include "asterisk/module.h"
23 #include "asterisk/pbx.h"
24 #include "asterisk/sched.h"
25 #include "asterisk/io.h"
26 #include "asterisk/config.h"
27 #include "asterisk/options.h"
28 #include "asterisk/cli.h"
29 #include "asterisk/translate.h"
30 #include "asterisk/md5.h"
31 #include "asterisk/cdr.h"
32 #include "asterisk/crypto.h"
33 #include "asterisk/acl.h"
34 #include "asterisk/manager.h"
35 #include "asterisk/callerid.h"
36 #include "asterisk/app.h"
37 #include "asterisk/astdb.h"
38 #include "asterisk/musiconhold.h"
39 #include "asterisk/features.h"
40 #include "asterisk/utils.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/localtime.h"
43 #include "asterisk/aes.h"
44 #include "asterisk/dnsmgr.h"
45 #include <sys/mman.h>
46 #include <arpa/inet.h>
47 #include <dirent.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
52 #include <sys/time.h>
53 #include <sys/signal.h>
54 #include <signal.h>
55 #include <stdlib.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <unistd.h>
60 #include <netdb.h>
61 #include <fcntl.h>
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <regex.h>
65 #ifdef IAX_TRUNKING
66 #include <sys/ioctl.h>
67 #ifdef __linux__
68 #include <linux/zaptel.h>
69 #else
70 #include <zaptel.h>
71 #endif /* __linux__ */
72 #endif
73 #include "iax2.h"
74 #include "iax2-parser.h"
75 #include "iax2-provision.h"
76 #include "asterisk.h"
77
78 /* Define NEWJB to use the new channel independent jitterbuffer,
79  * otherwise, use the old jitterbuffer */
80 #define NEWJB
81
82 #ifdef NEWJB
83 #include "../jitterbuf.h"
84 #endif
85
86 #ifndef IPTOS_MINCOST
87 #define IPTOS_MINCOST 0x02
88 #endif
89
90 #ifdef SO_NO_CHECK
91 static int nochecksums = 0;
92 #endif
93
94 /*
95  * Uncomment to try experimental IAX bridge optimization,
96  * designed to reduce latency when IAX calls cannot
97  * be trasnferred -- obsolete
98  */
99
100 /* #define BRIDGE_OPTIMIZATION  */
101
102
103 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
104 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
105
106 #define DEFAULT_RETRY_TIME 1000
107 #define MEMORY_SIZE 100
108 #define DEFAULT_DROP 3
109 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
110    but keeps the division between trunked and non-trunked better. */
111 #define TRUNK_CALL_START        0x4000
112
113 #define DEBUG_SUPPORT
114
115 #define MIN_REUSE_TIME          60      /* Don't reuse a call number within 60 seconds */
116
117 /* Sample over last 100 units to determine historic jitter */
118 #define GAMMA (0.01)
119
120 static struct ast_codec_pref prefs;
121
122 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
123 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
124 static const char channeltype[] = "IAX2";
125
126 static char context[80] = "default";
127
128 static char language[MAX_LANGUAGE] = "";
129 static char regcontext[AST_MAX_EXTENSION] = "";
130
131 static int max_retries = 4;
132 static int ping_time = 20;
133 static int lagrq_time = 10;
134 static int maxtrunkcall = TRUNK_CALL_START;
135 static int maxnontrunkcall = 1;
136 static int maxjitterbuffer=1000;
137 #ifdef NEWJB
138 static int resyncthreshold=1000;
139 static int maxjitterinterps=10;
140 #endif
141 static int jittershrinkrate=2;
142 static int trunkfreq = 20;
143 static int send_trunktimestamps = 1;
144 static int authdebug = 1;
145 static int autokill = 0;
146 static int iaxcompat = 0;
147
148 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
149
150 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
151
152 static int tos = 0;
153
154 static int expirey = IAX_DEFAULT_REG_EXPIRE;
155
156 static int timingfd = -1;                               /* Timing file descriptor */
157
158 static struct ast_netsock_list netsock;
159 static int defaultsockfd = -1;
160
161 static int usecnt;
162 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
163
164 int (*iax2_regfunk)(char *username, int onoff) = NULL;
165
166 /* Ethernet, etc */
167 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
168 /* T1, maybe ISDN */
169 #define IAX_CAPABILITY_MEDBANDWIDTH     (IAX_CAPABILITY_FULLBANDWIDTH & \
170                                                                         ~AST_FORMAT_SLINEAR & \
171                                                                         ~AST_FORMAT_ULAW & \
172                                                                         ~AST_FORMAT_ALAW) 
173 /* A modem */
174 #define IAX_CAPABILITY_LOWBANDWIDTH             (IAX_CAPABILITY_MEDBANDWIDTH & \
175                                                                         ~AST_FORMAT_G726 & \
176                                                                         ~AST_FORMAT_ADPCM)
177
178 #define IAX_CAPABILITY_LOWFREE          (IAX_CAPABILITY_LOWBANDWIDTH & \
179                                                                          ~AST_FORMAT_G723_1)
180
181
182 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
183 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
184 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
185
186 static  struct io_context *io;
187 static  struct sched_context *sched;
188
189 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
190
191 static int iax2_dropcount = DEFAULT_DROP;
192
193 static int iaxdebug = 0;
194
195 static int iaxtrunkdebug = 0;
196
197 static int test_losspct = 0;
198 #ifdef IAXTESTS
199 static int test_late = 0;
200 static int test_resync = 0;
201 static int test_jit = 0;
202 static int test_jitpct = 0;
203 #endif /* IAXTESTS */
204
205 static char accountcode[AST_MAX_ACCOUNT_CODE];
206 static int amaflags = 0;
207 static int delayreject = 0;
208 static int iax2_encryption = 0;
209
210 static struct ast_flags globalflags = {0};
211
212 static pthread_t netthreadid = AST_PTHREADT_NULL;
213
214 #define IAX_STATE_STARTED               (1 << 0)
215 #define IAX_STATE_AUTHENTICATED         (1 << 1)
216 #define IAX_STATE_TBD                   (1 << 2)
217
218 struct iax2_context {
219         char context[AST_MAX_EXTENSION];
220         struct iax2_context *next;
221 };
222
223 #define IAX_HASCALLERID         (1 << 0)        /* CallerID has been specified */
224 #define IAX_DELME               (1 << 1)        /* Needs to be deleted */
225 #define IAX_TEMPONLY            (1 << 2)        /* Temporary (realtime) */
226 #define IAX_TRUNK               (1 << 3)        /* Treat as a trunk */
227 #define IAX_NOTRANSFER          (1 << 4)        /* Don't native bridge */
228 #define IAX_USEJITTERBUF        (1 << 5)        /* Use jitter buffer */
229 #define IAX_DYNAMIC             (1 << 6)        /* dynamic peer */
230 #define IAX_SENDANI             (1 << 7)        /* Send ANI along with CallerID */
231 #define IAX_MESSAGEDETAIL       (1 << 8)        /* Show exact numbers */
232 #define IAX_ALREADYGONE         (1 << 9)        /* Already disconnected */
233 #define IAX_PROVISION           (1 << 10)       /* This is a provisioning request */
234 #define IAX_QUELCH              (1 << 11)       /* Whether or not we quelch audio */
235 #define IAX_ENCRYPTED           (1 << 12)       /* Whether we should assume encrypted tx/rx */
236 #define IAX_KEYPOPULATED        (1 << 13)       /* Whether we have a key populated */
237 #define IAX_CODEC_USER_FIRST    (1 << 14)       /* are we willing to let the other guy choose the codec? */
238 #define IAX_CODEC_NOPREFS       (1 << 15)       /* Force old behaviour by turning off prefs */
239 #define IAX_CODEC_NOCAP         (1 << 16)       /* only consider requested format and ignore capabilities*/
240 #define IAX_RTCACHEFRIENDS      (1 << 17)       /* let realtime stay till your reload */
241 #define IAX_RTNOUPDATE          (1 << 18)       /* Don't send a realtime update */
242 #define IAX_RTAUTOCLEAR         (1 << 19)       /* erase me on expire */ 
243 #define IAX_FORCEJITTERBUF      (1 << 20)       /* Force jitterbuffer, even when bridged to a channel that can take jitter */ 
244 #define IAX_RTIGNOREREGEXPIRE           (1 << 21)
245
246 static int global_rtautoclear = 120;
247
248 static int reload_config(void);
249 static int iax2_reload(int fd, int argc, char *argv[]);
250
251
252 struct iax2_user {
253         char name[80];
254         char secret[80];
255         char dbsecret[80];
256         int authmethods;
257         int encmethods;
258         char accountcode[AST_MAX_ACCOUNT_CODE];
259         char inkeys[80];                                /* Key(s) this user can use to authenticate to us */
260         char language[MAX_LANGUAGE];
261         int amaflags;
262         unsigned int flags;
263         int capability;
264         char cid_num[AST_MAX_EXTENSION];
265         char cid_name[AST_MAX_EXTENSION];
266         struct ast_codec_pref prefs;
267         struct ast_ha *ha;
268         struct iax2_context *contexts;
269         struct iax2_user *next;
270         struct ast_variable *vars;
271 };
272
273 struct iax2_peer {
274         char name[80];
275         char username[80];              
276         char secret[80];
277         char dbsecret[80];
278         char outkey[80];                                /* What key we use to talk to this peer */
279         char context[AST_MAX_EXTENSION];                /* For transfers only */
280         char regexten[AST_MAX_EXTENSION];               /* Extension to register (if regcontext is used) */
281         char peercontext[AST_MAX_EXTENSION];            /* Context to pass to peer */
282         char mailbox[AST_MAX_EXTENSION];                /* Mailbox */
283         struct ast_codec_pref prefs;
284         struct ast_dnsmgr_entry *dnsmgr;                /* DNS refresh manager */
285         struct sockaddr_in addr;
286         int formats;
287         int sockfd;                                     /* Socket to use for transmission */
288         struct in_addr mask;
289         unsigned int flags;
290
291         /* Dynamic Registration fields */
292         struct sockaddr_in defaddr;                     /* Default address if there is one */
293         int authmethods;                                /* Authentication methods (IAX_AUTH_*) */
294         int encmethods;                                 /* Encryption methods (IAX_ENCRYPT_*) */
295         char inkeys[80];                                /* Key(s) this peer can use to authenticate to us */
296
297         /* Suggested caller id if registering */
298         char cid_num[AST_MAX_EXTENSION];                /* Default context (for transfer really) */
299         char cid_name[AST_MAX_EXTENSION];               /* Default context (for transfer really) */
300         
301         int expire;                                     /* Schedule entry for expirey */
302         int expirey;                                    /* How soon to expire */
303         int capability;                                 /* Capability */
304         char zonetag[80];                               /* Time Zone */
305
306         /* Qualification */
307         int callno;                                     /* Call number of POKE request */
308         int pokeexpire;                                 /* When to expire poke */
309         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
310         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
311         
312         struct ast_ha *ha;
313         struct iax2_peer *next;
314 };
315
316 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
317
318 static struct iax2_trunk_peer {
319         ast_mutex_t lock;
320         int sockfd;
321         struct sockaddr_in addr;
322         struct timeval txtrunktime;             /* Transmit trunktime */
323         struct timeval rxtrunktime;             /* Receive trunktime */
324         struct timeval lasttxtime;              /* Last transmitted trunktime */
325         struct timeval trunkact;                /* Last trunk activity */
326         unsigned int lastsent;                  /* Last sent time */
327         /* Trunk data and length */
328         unsigned char *trunkdata;
329         unsigned int trunkdatalen;
330         unsigned int trunkdataalloc;
331         struct iax2_trunk_peer *next;
332         int trunkerror;
333         int calls;
334 } *tpeers = NULL;
335
336 AST_MUTEX_DEFINE_STATIC(tpeerlock);
337
338 struct iax_firmware {
339         struct iax_firmware *next;
340         int fd;
341         int mmaplen;
342         int dead;
343         struct ast_iax2_firmware_header *fwh;
344         unsigned char *buf;
345 };
346
347 #define REG_STATE_UNREGISTERED  0
348 #define REG_STATE_REGSENT       1
349 #define REG_STATE_AUTHSENT      2
350 #define REG_STATE_REGISTERED    3
351 #define REG_STATE_REJECTED      4
352 #define REG_STATE_TIMEOUT       5
353 #define REG_STATE_NOAUTH        6
354
355 #define TRANSFER_NONE           0
356 #define TRANSFER_BEGIN          1
357 #define TRANSFER_READY          2
358 #define TRANSFER_RELEASED       3
359 #define TRANSFER_PASSTHROUGH    4
360
361 struct iax2_registry {
362         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
363         char username[80];
364         char secret[80];                        /* Password or key name in []'s */
365         char random[80];
366         int expire;                             /* Sched ID of expiration */
367         int refresh;                            /* How often to refresh */
368         int regstate;
369         int messages;                           /* Message count */
370         int callno;                             /* Associated call number if applicable */
371         struct sockaddr_in us;                  /* Who the server thinks we are */
372         struct iax2_registry *next;
373 };
374
375 static struct iax2_registry *registrations;
376
377 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
378 #define MIN_RETRY_TIME  100
379 #define MAX_RETRY_TIME  10000
380
381 #define MAX_JITTER_BUFFER 50
382 #define MIN_JITTER_BUFFER 10
383
384 #define DEFAULT_TRUNKDATA       640 * 10                /* 40ms, uncompressed linear * 10 channels */
385 #define MAX_TRUNKDATA           640 * 200               /* 40ms, uncompressed linear * 200 channels */
386
387 #define MAX_TIMESTAMP_SKEW      160                     /* maximum difference between actual and predicted ts for sending */
388
389 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
390 #define TS_GAP_FOR_JB_RESYNC    5000
391
392 /* If we have more than this much excess real jitter buffer, shrink it. */
393 static int max_jitter_buffer = MAX_JITTER_BUFFER;
394 /* If we have less than this much excess real jitter buffer, enlarge it. */
395 static int min_jitter_buffer = MIN_JITTER_BUFFER;
396
397 struct iax_rr {
398         int jitter;
399         int losspct;
400         int losscnt;
401         int packets;
402         int delay;
403         int dropped;
404         int ooo;
405 };
406
407 struct chan_iax2_pvt {
408         /* Socket to send/receive on for this call */
409         int sockfd;
410         /* Last received voice format */
411         int voiceformat;
412         /* Last received voice format */
413         int videoformat;
414         /* Last sent voice format */
415         int svoiceformat;
416         /* Last sent video format */
417         int svideoformat;
418         /* What we are capable of sending */
419         int capability;
420         /* Last received timestamp */
421         unsigned int last;
422         /* Last sent timestamp - never send the same timestamp twice in a single call */
423         unsigned int lastsent;
424         /* Next outgoing timestamp if everything is good */
425         unsigned int nextpred;
426         /* True if the last voice we transmitted was not silence/CNG */
427         int notsilenttx;
428         /* Ping time */
429         unsigned int pingtime;
430         /* Max time for initial response */
431         int maxtime;
432         /* Peer Address */
433         struct sockaddr_in addr;
434         struct ast_codec_pref prefs;
435         /* Our call number */
436         unsigned short callno;
437         /* Peer callno */
438         unsigned short peercallno;
439         /* Peer selected format */
440         int peerformat;
441         /* Peer capability */
442         int peercapability;
443         /* timeval that we base our transmission on */
444         struct timeval offset;
445         /* timeval that we base our delivery on */
446         struct timeval rxcore;
447 #ifdef NEWJB
448         /* The jitterbuffer */
449         jitterbuf *jb;
450         /* active jb read scheduler id */
451         int jbid;                       
452 #else
453         /* Historical delivery time */
454         int history[MEMORY_SIZE];
455         /* Current base jitterbuffer */
456         int jitterbuffer;
457         /* Current jitter measure */
458         int jitter;
459         /* Historic jitter value */
460         int historicjitter;
461 #endif
462         /* LAG */
463         int lag;
464         /* Error, as discovered by the manager */
465         int error;
466         /* Owner if we have one */
467         struct ast_channel *owner;
468         /* What's our state? */
469         int state;
470         /* Expirey (optional) */
471         int expirey;
472         /* Next outgoing sequence number */
473         unsigned char oseqno;
474         /* Next sequence number they have not yet acknowledged */
475         unsigned char rseqno;
476         /* Next incoming sequence number */
477         unsigned char iseqno;
478         /* Last incoming sequence number we have acknowledged */
479         unsigned char aseqno;
480         /* Peer name */
481         char peer[80];
482         /* Default Context */
483         char context[80];
484         /* Caller ID if available */
485         char cid_num[80];
486         char cid_name[80];
487         /* Hidden Caller ID (i.e. ANI) if appropriate */
488         char ani[80];
489         /* DNID */
490         char dnid[80];
491         /* Requested Extension */
492         char exten[AST_MAX_EXTENSION];
493         /* Expected Username */
494         char username[80];
495         /* Expected Secret */
496         char secret[80];
497         /* permitted authentication methods */
498         int authmethods;
499         /* permitted encryption methods */
500         int encmethods;
501         /* MD5 challenge */
502         char challenge[10];
503         /* Public keys permitted keys for incoming authentication */
504         char inkeys[80];
505         /* Private key for outgoing authentication */
506         char outkey[80];
507         /* Encryption AES-128 Key */
508         aes_encrypt_ctx ecx;
509         /* Decryption AES-128 Key */
510         aes_decrypt_ctx dcx;
511         /* 32 bytes of semi-random data */
512         char semirand[32];
513         /* Preferred language */
514         char language[MAX_LANGUAGE];
515         /* Hostname/peername for naming purposes */
516         char host[80];
517         /* Associated registry */
518         struct iax2_registry *reg;
519         /* Associated peer for poking */
520         struct iax2_peer *peerpoke;
521         /* IAX_ flags */
522         unsigned int flags;
523
524         /* Transferring status */
525         int transferring;
526         /* Transfer identifier */
527         int transferid;
528         /* Who we are IAX transfering to */
529         struct sockaddr_in transfer;
530         /* What's the new call number for the transfer */
531         unsigned short transfercallno;
532         /* Transfer decrypt AES-128 Key */
533         aes_encrypt_ctx tdcx;
534
535         /* Status of knowledge of peer ADSI capability */
536         int peeradsicpe;
537         
538         /* Who we are bridged to */
539         unsigned short bridgecallno;
540         unsigned int bridgesfmt;
541         struct ast_trans_pvt *bridgetrans;
542         
543         int pingid;                     /* Transmit PING request */
544         int lagid;                      /* Retransmit lag request */
545         int autoid;                     /* Auto hangup for Dialplan requestor */
546         int authid;                     /* Authentication rejection ID */
547         int authfail;           /* Reason to report failure */
548         int initid;                     /* Initial peer auto-congest ID (based on qualified peers) */
549         int calling_ton;
550         int calling_tns;
551         int calling_pres;
552         char dproot[AST_MAX_EXTENSION];
553         char accountcode[AST_MAX_ACCOUNT_CODE];
554         int amaflags;
555         struct iax2_dpcache *dpentries;
556         struct ast_variable *vars;
557         /* last received remote rr */
558         struct iax_rr remote_rr;
559         /* Current base time: (just for stats) */
560         int min;
561         /* Dropped frame count: (just for stats) */
562         int frames_dropped;
563         /* received frame count: (just for stats) */
564         int frames_received;
565 };
566
567 static struct ast_iax2_queue {
568         struct iax_frame *head;
569         struct iax_frame *tail;
570         int count;
571         ast_mutex_t lock;
572 } iaxq;
573
574 static struct ast_user_list {
575         struct iax2_user *users;
576         ast_mutex_t lock;
577 } userl;
578
579 static struct ast_peer_list {
580         struct iax2_peer *peers;
581         ast_mutex_t lock;
582 } peerl;
583
584 static struct ast_firmware_list {
585         struct iax_firmware *wares;
586         ast_mutex_t lock;
587 } waresl;
588
589 /* Extension exists */
590 #define CACHE_FLAG_EXISTS               (1 << 0)
591 /* Extension is nonexistent */
592 #define CACHE_FLAG_NONEXISTENT  (1 << 1)
593 /* Extension can exist */
594 #define CACHE_FLAG_CANEXIST             (1 << 2)
595 /* Waiting to hear back response */
596 #define CACHE_FLAG_PENDING              (1 << 3)
597 /* Timed out */
598 #define CACHE_FLAG_TIMEOUT              (1 << 4)
599 /* Request transmitted */
600 #define CACHE_FLAG_TRANSMITTED  (1 << 5)
601 /* Timeout */
602 #define CACHE_FLAG_UNKNOWN              (1 << 6)
603 /* Matchmore */
604 #define CACHE_FLAG_MATCHMORE    (1 << 7)
605
606 static struct iax2_dpcache {
607         char peercontext[AST_MAX_EXTENSION];
608         char exten[AST_MAX_EXTENSION];
609         struct timeval orig;
610         struct timeval expirey;
611         int flags;
612         unsigned short callno;
613         int waiters[256];
614         struct iax2_dpcache *next;
615         struct iax2_dpcache *peer;      /* For linking in peers */
616 } *dpcache;
617
618 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
619
620 static void reg_source_db(struct iax2_peer *p);
621 static struct iax2_peer *realtime_peer(const char *peername);
622
623 static void destroy_peer(struct iax2_peer *peer);
624 static int ast_cli_netstats(int fd, int limit_fmt);
625
626 static void iax_debug_output(const char *data)
627 {
628         if (iaxdebug)
629                 ast_verbose("%s", data);
630 }
631
632 static void iax_error_output(const char *data)
633 {
634         ast_log(LOG_WARNING, "%s", data);
635 }
636
637 #ifdef NEWJB
638 static void jb_error_output(const char *fmt, ...)
639 {
640         va_list args;
641         char buf[1024];
642
643         va_start(args, fmt);
644         vsnprintf(buf, 1024, fmt, args);
645         va_end(args);
646
647         ast_log(LOG_ERROR, buf);
648 }
649
650 static void jb_warning_output(const char *fmt, ...)
651 {
652         va_list args;
653         char buf[1024];
654
655         va_start(args, fmt);
656         vsnprintf(buf, 1024, fmt, args);
657         va_end(args);
658
659         ast_log(LOG_WARNING, buf);
660 }
661
662 static void jb_debug_output(const char *fmt, ...)
663 {
664         va_list args;
665         char buf[1024];
666
667         va_start(args, fmt);
668         vsnprintf(buf, 1024, fmt, args);
669         va_end(args);
670
671         ast_verbose(buf);
672 }
673 #endif
674
675
676 /* XXX We probably should use a mutex when working with this XXX */
677 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
678 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
679 static struct timeval lastused[IAX_MAX_CALLS];
680
681
682 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
683 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
684 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
685 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
686 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
687 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
688 static void destroy_user(struct iax2_user *user);
689 static int expire_registry(void *data);
690 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
691 static int iax2_do_register(struct iax2_registry *reg);
692 static void prune_peers(void);
693 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
694 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
695
696 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
697 static int iax2_devicestate(void *data);
698 static int iax2_digit(struct ast_channel *c, char digit);
699 static int iax2_sendtext(struct ast_channel *c, const char *text);
700 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
701 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
702 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
703 static int iax2_hangup(struct ast_channel *c);
704 static int iax2_answer(struct ast_channel *c);
705 static struct ast_frame *iax2_read(struct ast_channel *c);
706 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
707 static int iax2_indicate(struct ast_channel *c, int condition);
708 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
709 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
710 static int iax2_transfer(struct ast_channel *c, const char *dest);
711 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
712
713 static const struct ast_channel_tech iax2_tech = {
714         .type = channeltype,
715         .description = tdesc,
716         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
717         .properties = AST_CHAN_TP_WANTSJITTER,
718         .requester = iax2_request,
719         .devicestate = iax2_devicestate,
720         .send_digit = iax2_digit,
721         .send_text = iax2_sendtext,
722         .send_image = iax2_sendimage,
723         .send_html = iax2_sendhtml,
724         .call = iax2_call,
725         .hangup = iax2_hangup,
726         .answer = iax2_answer,
727         .read = iax2_read,
728         .write = iax2_write,
729         .write_video = iax2_write,
730         .indicate = iax2_indicate,
731         .setoption = iax2_setoption,
732         .bridge = iax2_bridge,
733         .transfer = iax2_transfer,
734         .fixup = iax2_fixup,
735 };
736
737 static int send_ping(void *data)
738 {
739         int callno = (long)data;
740         /* Ping only if it's real, not if it's bridged */
741         if (iaxs[callno]) {
742 #ifdef BRIDGE_OPTIMIZATION
743                 if (!iaxs[callno]->bridgecallno)
744 #endif
745                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
746                 return 1;
747         } else
748                 return 0;
749 }
750
751 static int get_encrypt_methods(const char *s)
752 {
753         int e;
754         if (!strcasecmp(s, "aes128"))
755                 e = IAX_ENCRYPT_AES128;
756         else if (ast_true(s))
757                 e = IAX_ENCRYPT_AES128;
758         else
759                 e = 0;
760         return e;
761 }
762
763 static int send_lagrq(void *data)
764 {
765         int callno = (long)data;
766         /* Ping only if it's real not if it's bridged */
767         if (iaxs[callno]) {
768 #ifdef BRIDGE_OPTIMIZATION
769                 if (!iaxs[callno]->bridgecallno)
770 #endif          
771                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
772                 return 1;
773         } else
774                 return 0;
775 }
776
777 static unsigned char compress_subclass(int subclass)
778 {
779         int x;
780         int power=-1;
781         /* If it's 128 or smaller, just return it */
782         if (subclass < IAX_FLAG_SC_LOG)
783                 return subclass;
784         /* Otherwise find its power */
785         for (x = 0; x < IAX_MAX_SHIFT; x++) {
786                 if (subclass & (1 << x)) {
787                         if (power > -1) {
788                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
789                                 return 0;
790                         } else
791                                 power = x;
792                 }
793         }
794         return power | IAX_FLAG_SC_LOG;
795 }
796
797 static int uncompress_subclass(unsigned char csub)
798 {
799         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
800         if (csub & IAX_FLAG_SC_LOG) {
801                 /* special case for 'compressed' -1 */
802                 if (csub == 0xff)
803                         return -1;
804                 else
805                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
806         }
807         else
808                 return csub;
809 }
810
811 static struct iax2_peer *find_peer(const char *name, int realtime) 
812 {
813         struct iax2_peer *peer;
814         ast_mutex_lock(&peerl.lock);
815         for(peer = peerl.peers; peer; peer = peer->next) {
816                 if (!strcasecmp(peer->name, name)) {
817                         break;
818                 }
819         }
820         ast_mutex_unlock(&peerl.lock);
821         if(!peer && realtime)
822                 peer = realtime_peer(name);
823         return peer;
824 }
825
826 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
827 {
828         struct iax2_peer *peer;
829         int res = 0;
830         if (lockpeer)
831                 ast_mutex_lock(&peerl.lock);
832         peer = peerl.peers;
833         while(peer) {
834                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
835                                 (peer->addr.sin_port == sin.sin_port)) {
836                                         ast_copy_string(host, peer->name, len);
837                                         res = 1;
838                                         break;
839                 }
840                 peer = peer->next;
841         }
842         if (lockpeer)
843                 ast_mutex_unlock(&peerl.lock);
844         return res;
845 }
846
847 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
848 {
849         struct chan_iax2_pvt *tmp;
850         tmp = malloc(sizeof(struct chan_iax2_pvt));
851         if (tmp) {
852                 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
853                 tmp->prefs = prefs;
854                 tmp->callno = 0;
855                 tmp->peercallno = 0;
856                 tmp->transfercallno = 0;
857                 tmp->bridgecallno = 0;
858                 tmp->pingid = -1;
859                 tmp->lagid = -1;
860                 tmp->autoid = -1;
861                 tmp->authid = -1;
862                 tmp->initid = -1;
863                 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
864                 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
865                 ast_copy_string(tmp->host, host, sizeof(tmp->host));
866 #ifdef NEWJB
867                 {
868                         jb_conf jbconf;
869
870                         tmp->jb = jb_new();
871                         tmp->jbid = -1;
872                         jbconf.max_jitterbuf = maxjitterbuffer;
873                         jbconf.resync_threshold = resyncthreshold;
874                         jbconf.max_contig_interp = maxjitterinterps;
875                         jb_setconf(tmp->jb,&jbconf);
876                 }
877 #endif
878         }
879         return tmp;
880 }
881
882 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
883 {
884         /* Malloc() a copy of a frame */
885         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
886         if (new) {
887                 memcpy(new, fr, sizeof(struct iax_frame));      
888                 iax_frame_wrap(new, &fr->af);
889                 new->data = NULL;
890                 new->datalen = 0;
891                 new->direction = DIRECTION_INGRESS;
892                 new->retrans = -1;
893         }
894         return new;
895 }
896
897 #define NEW_PREVENT 0
898 #define NEW_ALLOW       1
899 #define NEW_FORCE       2
900
901 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
902 {
903         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
904                 (cur->addr.sin_port == sin->sin_port)) {
905                 /* This is the main host */
906                 if ((cur->peercallno == callno) ||
907                         ((dcallno == cur->callno) && !cur->peercallno)) {
908                         /* That's us.  Be sure we keep track of the peer call number */
909                         return 1;
910                 }
911         }
912         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
913             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
914                 /* We're transferring */
915                 if (dcallno == cur->callno)
916                         return 1;
917         }
918         return 0;
919 }
920
921 static void update_max_trunk(void)
922 {
923         int max = TRUNK_CALL_START;
924         int x;
925         /* XXX Prolly don't need locks here XXX */
926         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
927                 if (iaxs[x])
928                         max = x + 1;
929         }
930         maxtrunkcall = max;
931         if (option_debug)
932                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
933 }
934
935 static void update_max_nontrunk(void)
936 {
937         int max = 1;
938         int x;
939         /* XXX Prolly don't need locks here XXX */
940         for (x=1;x<TRUNK_CALL_START - 1; x++) {
941                 if (iaxs[x])
942                         max = x + 1;
943         }
944         maxnontrunkcall = max;
945         if (option_debug)
946                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
947 }
948
949 static int make_trunk(unsigned short callno, int locked)
950 {
951         int x;
952         int res= 0;
953         struct timeval now;
954         if (iaxs[callno]->oseqno) {
955                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
956                 return -1;
957         }
958         if (callno & TRUNK_CALL_START) {
959                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
960                 return -1;
961         }
962         gettimeofday(&now, NULL);
963         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
964                 ast_mutex_lock(&iaxsl[x]);
965                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
966                         iaxs[x] = iaxs[callno];
967                         iaxs[x]->callno = x;
968                         iaxs[callno] = NULL;
969                         /* Update the two timers that should have been started */
970                         if (iaxs[x]->pingid > -1)
971                                 ast_sched_del(sched, iaxs[x]->pingid);
972                         if (iaxs[x]->lagid > -1)
973                                 ast_sched_del(sched, iaxs[x]->lagid);
974                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
975                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
976                         if (locked)
977                                 ast_mutex_unlock(&iaxsl[callno]);
978                         res = x;
979                         if (!locked)
980                                 ast_mutex_unlock(&iaxsl[x]);
981                         break;
982                 }
983                 ast_mutex_unlock(&iaxsl[x]);
984         }
985         if (x >= IAX_MAX_CALLS - 1) {
986                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
987                 return -1;
988         }
989         ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
990         /* We move this call from a non-trunked to a trunked call */
991         update_max_trunk();
992         update_max_nontrunk();
993         return res;
994 }
995
996 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
997 {
998         int res = 0;
999         int x;
1000         struct timeval now;
1001         char iabuf[INET_ADDRSTRLEN];
1002         char host[80];
1003         if (new <= NEW_ALLOW) {
1004                 /* Look for an existing connection first */
1005                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1006                         ast_mutex_lock(&iaxsl[x]);
1007                         if (iaxs[x]) {
1008                                 /* Look for an exact match */
1009                                 if (match(sin, callno, dcallno, iaxs[x])) {
1010                                         res = x;
1011                                 }
1012                         }
1013                         ast_mutex_unlock(&iaxsl[x]);
1014                 }
1015                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1016                         ast_mutex_lock(&iaxsl[x]);
1017                         if (iaxs[x]) {
1018                                 /* Look for an exact match */
1019                                 if (match(sin, callno, dcallno, iaxs[x])) {
1020                                         res = x;
1021                                 }
1022                         }
1023                         ast_mutex_unlock(&iaxsl[x]);
1024                 }
1025         }
1026         if ((res < 1) && (new >= NEW_ALLOW)) {
1027                 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1028                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1029                 gettimeofday(&now, NULL);
1030                 for (x=1;x<TRUNK_CALL_START;x++) {
1031                         /* Find first unused call number that hasn't been used in a while */
1032                         ast_mutex_lock(&iaxsl[x]);
1033                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1034                         ast_mutex_unlock(&iaxsl[x]);
1035                 }
1036                 /* We've still got lock held if we found a spot */
1037                 if (x >= TRUNK_CALL_START) {
1038                         ast_log(LOG_WARNING, "No more space\n");
1039                         return 0;
1040                 }
1041                 iaxs[x] = new_iax(sin, lockpeer, host);
1042                 update_max_nontrunk();
1043                 if (iaxs[x]) {
1044                         if (option_debug)
1045                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1046                         iaxs[x]->sockfd = sockfd;
1047                         iaxs[x]->addr.sin_port = sin->sin_port;
1048                         iaxs[x]->addr.sin_family = sin->sin_family;
1049                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1050                         iaxs[x]->peercallno = callno;
1051                         iaxs[x]->callno = x;
1052                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1053                         iaxs[x]->expirey = expirey;
1054                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1055                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1056                         iaxs[x]->amaflags = amaflags;
1057                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);        
1058                         ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1059                 } else {
1060                         ast_log(LOG_WARNING, "Out of resources\n");
1061                         ast_mutex_unlock(&iaxsl[x]);
1062                         return 0;
1063                 }
1064                 ast_mutex_unlock(&iaxsl[x]);
1065                 res = x;
1066         }
1067         return res;
1068 }
1069
1070 static void iax2_frame_free(struct iax_frame *fr)
1071 {
1072         if (fr->retrans > -1)
1073                 ast_sched_del(sched, fr->retrans);
1074         iax_frame_free(fr);
1075 }
1076
1077 static int iax2_queue_frame(int callno, struct ast_frame *f)
1078 {
1079         /* Assumes lock for callno is already held... */
1080         for (;;) {
1081                 if (iaxs[callno] && iaxs[callno]->owner) {
1082                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1083                                 /* Avoid deadlock by pausing and trying again */
1084                                 ast_mutex_unlock(&iaxsl[callno]);
1085                                 usleep(1);
1086                                 ast_mutex_lock(&iaxsl[callno]);
1087                         } else {
1088                                 ast_queue_frame(iaxs[callno]->owner, f);
1089                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1090                                 break;
1091                         }
1092                 } else
1093                         break;
1094         }
1095         return 0;
1096 }
1097
1098 static void destroy_firmware(struct iax_firmware *cur)
1099 {
1100         /* Close firmware */
1101         if (cur->fwh) {
1102                 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1103         }
1104         close(cur->fd);
1105         free(cur);
1106 }
1107
1108 static int try_firmware(char *s)
1109 {
1110         struct stat stbuf;
1111         struct iax_firmware *cur;
1112         int ifd;
1113         int fd;
1114         int res;
1115         
1116         struct ast_iax2_firmware_header *fwh, fwh2;
1117         struct MD5Context md5;
1118         unsigned char sum[16];
1119         unsigned char buf[1024];
1120         int len, chunk;
1121         char *s2;
1122         char *last;
1123         s2 = alloca(strlen(s) + 100);
1124         if (!s2) {
1125                 ast_log(LOG_WARNING, "Alloca failed!\n");
1126                 return -1;
1127         }
1128         last = strrchr(s, '/');
1129         if (last)
1130                 last++;
1131         else
1132                 last = s;
1133         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1134         res = stat(s, &stbuf);
1135         if (res < 0) {
1136                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1137                 return -1;
1138         }
1139         /* Make sure it's not a directory */
1140         if (S_ISDIR(stbuf.st_mode))
1141                 return -1;
1142         ifd = open(s, O_RDONLY);
1143         if (ifd < 0) {
1144                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1145                 return -1;
1146         }
1147         fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1148         if (fd < 0) {
1149                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1150                 close(ifd);
1151                 return -1;
1152         }
1153         /* Unlink our newly created file */
1154         unlink(s2);
1155         
1156         /* Now copy the firmware into it */
1157         len = stbuf.st_size;
1158         while(len) {
1159                 chunk = len;
1160                 if (chunk > sizeof(buf))
1161                         chunk = sizeof(buf);
1162                 res = read(ifd, buf, chunk);
1163                 if (res != chunk) {
1164                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1165                         close(ifd);
1166                         close(fd);
1167                         return -1;
1168                 }
1169                 res = write(fd, buf, chunk);
1170                 if (res != chunk) {
1171                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1172                         close(ifd);
1173                         close(fd);
1174                         return -1;
1175                 }
1176                 len -= chunk;
1177         }
1178         close(ifd);
1179         /* Return to the beginning */
1180         lseek(fd, 0, SEEK_SET);
1181         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1182                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1183                 close(fd);
1184                 return -1;
1185         }
1186         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1187                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1188                 close(fd);
1189                 return -1;
1190         }
1191         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1192                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1193                 close(fd);
1194                 return -1;
1195         }
1196         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1197                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1198                 close(fd);
1199                 return -1;
1200         }
1201         fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1202         if (!fwh) {
1203                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1204                 close(fd);
1205                 return -1;
1206         }
1207         MD5Init(&md5);
1208         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1209         MD5Final(sum, &md5);
1210         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1211                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1212                 munmap(fwh, stbuf.st_size);
1213                 close(fd);
1214                 return -1;
1215         }
1216         cur = waresl.wares;
1217         while(cur) {
1218                 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1219                         /* Found a candidate */
1220                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1221                                 /* The version we have on loaded is older, load this one instead */
1222                                 break;
1223                         /* This version is no newer than what we have.  Don't worry about it.
1224                            We'll consider it a proper load anyhow though */
1225                         munmap(fwh, stbuf.st_size);
1226                         close(fd);
1227                         return 0;
1228                 }
1229                 cur = cur->next;
1230         }
1231         if (!cur) {
1232                 /* Allocate a new one and link it */
1233                 cur = malloc(sizeof(struct iax_firmware));
1234                 if (cur) {
1235                         memset(cur, 0, sizeof(struct iax_firmware));
1236                         cur->fd = -1;
1237                         cur->next = waresl.wares;
1238                         waresl.wares = cur;
1239                 }
1240         }
1241         if (cur) {
1242                 if (cur->fwh) {
1243                         munmap(cur->fwh, cur->mmaplen);
1244                 }
1245                 if (cur->fd > -1)
1246                         close(cur->fd);
1247                 cur->fwh = fwh;
1248                 cur->fd = fd;
1249                 cur->mmaplen = stbuf.st_size;
1250                 cur->dead = 0;
1251         }
1252         return 0;
1253 }
1254
1255 static int iax_check_version(char *dev)
1256 {
1257         int res = 0;
1258         struct iax_firmware *cur;
1259         if (dev && !ast_strlen_zero(dev)) {
1260                 ast_mutex_lock(&waresl.lock);
1261                 cur = waresl.wares;
1262                 while(cur) {
1263                         if (!strcmp(dev, cur->fwh->devname)) {
1264                                 res = ntohs(cur->fwh->version);
1265                                 break;
1266                         }
1267                         cur = cur->next;
1268                 }
1269                 ast_mutex_unlock(&waresl.lock);
1270         }
1271         return res;
1272 }
1273
1274 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1275 {
1276         int res = -1;
1277         unsigned int bs = desc & 0xff;
1278         unsigned int start = (desc >> 8) & 0xffffff;
1279         unsigned int bytes;
1280         struct iax_firmware *cur;
1281         if (dev && !ast_strlen_zero(dev) && bs) {
1282                 start *= bs;
1283                 ast_mutex_lock(&waresl.lock);
1284                 cur = waresl.wares;
1285                 while(cur) {
1286                         if (!strcmp(dev, cur->fwh->devname)) {
1287                                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1288                                 if (start < ntohl(cur->fwh->datalen)) {
1289                                         bytes = ntohl(cur->fwh->datalen) - start;
1290                                         if (bytes > bs)
1291                                                 bytes = bs;
1292                                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1293                                 } else {
1294                                         bytes = 0;
1295                                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1296                                 }
1297                                 if (bytes == bs)
1298                                         res = 0;
1299                                 else
1300                                         res = 1;
1301                                 break;
1302                         }
1303                         cur = cur->next;
1304                 }
1305                 ast_mutex_unlock(&waresl.lock);
1306         }
1307         return res;
1308 }
1309
1310
1311 static void reload_firmware(void)
1312 {
1313         struct iax_firmware *cur, *curl, *curp;
1314         DIR *fwd;
1315         struct dirent *de;
1316         char dir[256];
1317         char fn[256];
1318         /* Mark all as dead */
1319         ast_mutex_lock(&waresl.lock);
1320         cur = waresl.wares;
1321         while(cur) {
1322                 cur->dead = 1;
1323                 cur = cur->next;
1324         }
1325         /* Now that we've freed them, load the new ones */
1326         snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1327         fwd = opendir(dir);
1328         if (fwd) {
1329                 while((de = readdir(fwd))) {
1330                         if (de->d_name[0] != '.') {
1331                                 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1332                                 if (!try_firmware(fn)) {
1333                                         if (option_verbose > 1)
1334                                                 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1335                                 }
1336                         }
1337                 }
1338                 closedir(fwd);
1339         } else 
1340                 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1341
1342         /* Clean up leftovers */
1343         cur = waresl.wares;
1344         curp = NULL;
1345         while(cur) {
1346                 curl = cur;
1347                 cur = cur->next;
1348                 if (curl->dead) {
1349                         if (curp) {
1350                                 curp->next = cur;
1351                         } else {
1352                                 waresl.wares = cur;
1353                         }
1354                         destroy_firmware(curl);
1355                 } else {
1356                         curp = cur;
1357                 }
1358         }
1359         ast_mutex_unlock(&waresl.lock);
1360 }
1361
1362 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1363
1364 static int __do_deliver(void *data)
1365 {
1366         /* Just deliver the packet by using queueing.  This is called by
1367           the IAX thread with the iaxsl lock held. */
1368         struct iax_frame *fr = data;
1369         fr->retrans = -1;
1370         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1371                 iax2_queue_frame(fr->callno, &fr->af);
1372         /* Free our iax frame */
1373         iax2_frame_free(fr);
1374         /* And don't run again */
1375         return 0;
1376 }
1377
1378 #ifndef NEWJB
1379 static int do_deliver(void *data)
1380 {
1381         /* Locking version of __do_deliver */
1382         struct iax_frame *fr = data;
1383         int callno = fr->callno;
1384         int res;
1385         ast_mutex_lock(&iaxsl[callno]);
1386         res = __do_deliver(data);
1387         ast_mutex_unlock(&iaxsl[callno]);
1388         return res;
1389 }
1390 #endif /* NEWJB */
1391
1392 static int handle_error(void)
1393 {
1394         /* XXX Ideally we should figure out why an error occured and then abort those
1395            rather than continuing to try.  Unfortunately, the published interface does
1396            not seem to work XXX */
1397 #if 0
1398         struct sockaddr_in *sin;
1399         int res;
1400         struct msghdr m;
1401         struct sock_extended_err e;
1402         m.msg_name = NULL;
1403         m.msg_namelen = 0;
1404         m.msg_iov = NULL;
1405         m.msg_control = &e;
1406         m.msg_controllen = sizeof(e);
1407         m.msg_flags = 0;
1408         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1409         if (res < 0)
1410                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1411         else {
1412                 if (m.msg_controllen) {
1413                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1414                         if (sin) 
1415                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1416                         else
1417                                 ast_log(LOG_WARNING, "No address detected??\n");
1418                 } else {
1419                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1420                 }
1421         }
1422 #endif
1423         return 0;
1424 }
1425
1426 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1427 {
1428         int res;
1429         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1430                                         sizeof(*sin));
1431         if (res < 0) {
1432                 if (option_debug)
1433                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1434                 handle_error();
1435         } else
1436                 res = 0;
1437         return res;
1438 }
1439
1440 static int send_packet(struct iax_frame *f)
1441 {
1442         int res;
1443         char iabuf[INET_ADDRSTRLEN];
1444         /* Called with iaxsl held */
1445         if (option_debug > 2)
1446                 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1447         /* Don't send if there was an error, but return error instead */
1448         if (!f->callno) {
1449                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1450                 return -1;
1451         }
1452         if (!iaxs[f->callno])
1453                 return -1;
1454         if (iaxs[f->callno]->error)
1455                 return -1;
1456         if (f->transfer) {
1457                 if (iaxdebug)
1458                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1459                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1460                                         sizeof(iaxs[f->callno]->transfer));
1461         } else {
1462                 if (iaxdebug)
1463                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1464                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1465                                         sizeof(iaxs[f->callno]->addr));
1466         }
1467         if (res < 0) {
1468                 if (option_debug)
1469                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1470                 handle_error();
1471         } else
1472                 res = 0;
1473         return res;
1474 }
1475
1476
1477 static int iax2_predestroy(int callno)
1478 {
1479         struct ast_channel *c;
1480         struct chan_iax2_pvt *pvt;
1481         ast_mutex_lock(&iaxsl[callno]);
1482         pvt = iaxs[callno];
1483         if (!pvt) {
1484                 ast_mutex_unlock(&iaxsl[callno]);
1485                 return -1;
1486         }
1487         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1488                 /* No more pings or lagrq's */
1489                 if (pvt->pingid > -1)
1490                         ast_sched_del(sched, pvt->pingid);
1491                 if (pvt->lagid > -1)
1492                         ast_sched_del(sched, pvt->lagid);
1493                 if (pvt->autoid > -1)
1494                         ast_sched_del(sched, pvt->autoid);
1495                 if (pvt->authid > -1)
1496                         ast_sched_del(sched, pvt->authid);
1497                 if (pvt->initid > -1)
1498                         ast_sched_del(sched, pvt->initid);
1499 #ifdef NEWJB
1500                 if (pvt->jbid > -1)
1501                         ast_sched_del(sched, pvt->jbid);
1502                 pvt->jbid = -1;
1503 #endif
1504                 pvt->pingid = -1;
1505                 pvt->lagid = -1;
1506                 pvt->autoid = -1;
1507                 pvt->initid = -1;
1508                 pvt->authid = -1;
1509                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1510         }
1511         c = pvt->owner;
1512         if (c) {
1513                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1514                 c->tech_pvt = NULL;
1515                 ast_queue_hangup(c);
1516                 pvt->owner = NULL;
1517                 ast_mutex_lock(&usecnt_lock);
1518                 usecnt--;
1519                 if (usecnt < 0) 
1520                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1521                 ast_mutex_unlock(&usecnt_lock);
1522         }
1523         ast_mutex_unlock(&iaxsl[callno]);
1524         ast_update_use_count();
1525         return 0;
1526 }
1527
1528 static int iax2_predestroy_nolock(int callno)
1529 {
1530         int res;
1531         ast_mutex_unlock(&iaxsl[callno]);
1532         res = iax2_predestroy(callno);
1533         ast_mutex_lock(&iaxsl[callno]);
1534         return res;
1535 }
1536
1537 static void iax2_destroy(int callno)
1538 {
1539         struct chan_iax2_pvt *pvt;
1540         struct iax_frame *cur;
1541         struct ast_channel *owner;
1542
1543 retry:
1544         ast_mutex_lock(&iaxsl[callno]);
1545         pvt = iaxs[callno];
1546         gettimeofday(&lastused[callno], NULL);
1547
1548         if (pvt)
1549                 owner = pvt->owner;
1550         else
1551                 owner = NULL;
1552         if (owner) {
1553                 if (ast_mutex_trylock(&owner->lock)) {
1554                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1555                         ast_mutex_unlock(&iaxsl[callno]);
1556                         usleep(1);
1557                         goto retry;
1558                 }
1559         }
1560         if (!owner)
1561                 iaxs[callno] = NULL;
1562         if (pvt) {
1563                 if (!owner)
1564                         pvt->owner = NULL;
1565                 /* No more pings or lagrq's */
1566                 if (pvt->pingid > -1)
1567                         ast_sched_del(sched, pvt->pingid);
1568                 if (pvt->lagid > -1)
1569                         ast_sched_del(sched, pvt->lagid);
1570                 if (pvt->autoid > -1)
1571                         ast_sched_del(sched, pvt->autoid);
1572                 if (pvt->authid > -1)
1573                         ast_sched_del(sched, pvt->authid);
1574                 if (pvt->initid > -1)
1575                         ast_sched_del(sched, pvt->initid);
1576 #ifdef NEWJB
1577                 if (pvt->jbid > -1)
1578                         ast_sched_del(sched, pvt->jbid);
1579                 pvt->jbid = -1;
1580 #endif
1581                 pvt->pingid = -1;
1582                 pvt->lagid = -1;
1583                 pvt->autoid = -1;
1584                 pvt->authid = -1;
1585                 pvt->initid = -1;
1586                 if (pvt->bridgetrans)
1587                         ast_translator_free_path(pvt->bridgetrans);
1588                 pvt->bridgetrans = NULL;
1589
1590                 /* Already gone */
1591                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1592
1593                 if (owner) {
1594                         /* If there's an owner, prod it to give up */
1595                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1596                         ast_queue_hangup(owner);
1597                 }
1598
1599                 for (cur = iaxq.head; cur ; cur = cur->next) {
1600                         /* Cancel any pending transmissions */
1601                         if (cur->callno == pvt->callno) 
1602                                 cur->retries = -1;
1603                 }
1604                 if (pvt->reg) {
1605                         pvt->reg->callno = 0;
1606                 }
1607                 if (!owner) {
1608                         if (pvt->vars) {
1609                                 ast_variables_destroy(pvt->vars);
1610                                 pvt->vars = NULL;
1611                         }
1612 #ifdef NEWJB
1613                         {
1614                             jb_frame frame;
1615                             while(jb_getall(pvt->jb,&frame) == JB_OK)
1616                                 iax2_frame_free(frame.data);
1617                             jb_destroy(pvt->jb);
1618                         }
1619 #endif
1620                         free(pvt);
1621                 }
1622         }
1623         if (owner) {
1624                 ast_mutex_unlock(&owner->lock);
1625         }
1626         ast_mutex_unlock(&iaxsl[callno]);
1627         if (callno & 0x4000)
1628                 update_max_trunk();
1629 }
1630 static void iax2_destroy_nolock(int callno)
1631 {       
1632         /* Actually it's easier to unlock, kill it, and relock */
1633         ast_mutex_unlock(&iaxsl[callno]);
1634         iax2_destroy(callno);
1635         ast_mutex_lock(&iaxsl[callno]);
1636 }
1637
1638 static int update_packet(struct iax_frame *f)
1639 {
1640         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1641         struct ast_iax2_full_hdr *fh = f->data;
1642         /* Mark this as a retransmission */
1643         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1644         /* Update iseqno */
1645         f->iseqno = iaxs[f->callno]->iseqno;
1646         fh->iseqno = f->iseqno;
1647         return 0;
1648 }
1649
1650 static int attempt_transmit(void *data)
1651 {
1652         /* Attempt to transmit the frame to the remote peer...
1653            Called without iaxsl held. */
1654         struct iax_frame *f = data;
1655         int freeme=0;
1656         int callno = f->callno;
1657         char iabuf[INET_ADDRSTRLEN];
1658         /* Make sure this call is still active */
1659         if (callno) 
1660                 ast_mutex_lock(&iaxsl[callno]);
1661         if ((f->callno) && iaxs[f->callno]) {
1662                 if ((f->retries < 0) /* Already ACK'd */ ||
1663                     (f->retries >= max_retries) /* Too many attempts */) {
1664                                 /* Record an error if we've transmitted too many times */
1665                                 if (f->retries >= max_retries) {
1666                                         if (f->transfer) {
1667                                                 /* Transfer timeout */
1668                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1669                                         } else if (f->final) {
1670                                                 if (f->final) 
1671                                                         iax2_destroy_nolock(f->callno);
1672                                         } else {
1673                                                 if (iaxs[f->callno]->owner)
1674                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1675                                                 iaxs[f->callno]->error = ETIMEDOUT;
1676                                                 if (iaxs[f->callno]->owner) {
1677                                                         struct ast_frame fr = { 0, };
1678                                                         /* Hangup the fd */
1679                                                         fr.frametype = AST_FRAME_CONTROL;
1680                                                         fr.subclass = AST_CONTROL_HANGUP;
1681                                                         iax2_queue_frame(f->callno, &fr);
1682                                                         /* Remember, owner could disappear */
1683                                                         if (iaxs[f->callno]->owner)
1684                                                                 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1685                                                 } else {
1686                                                         if (iaxs[f->callno]->reg) {
1687                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1688                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1689                                                                 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1690                                                         }
1691                                                         iax2_destroy_nolock(f->callno);
1692                                                 }
1693                                         }
1694
1695                                 }
1696                                 freeme++;
1697                 } else {
1698                         /* Update it if it needs it */
1699                         update_packet(f);
1700                         /* Attempt transmission */
1701                         send_packet(f);
1702                         f->retries++;
1703                         /* Try again later after 10 times as long */
1704                         f->retrytime *= 10;
1705                         if (f->retrytime > MAX_RETRY_TIME)
1706                                 f->retrytime = MAX_RETRY_TIME;
1707                         /* Transfer messages max out at one second */
1708                         if (f->transfer && (f->retrytime > 1000))
1709                                 f->retrytime = 1000;
1710                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1711                 }
1712         } else {
1713                 /* Make sure it gets freed */
1714                 f->retries = -1;
1715                 freeme++;
1716         }
1717         if (callno)
1718                 ast_mutex_unlock(&iaxsl[callno]);
1719         /* Do not try again */
1720         if (freeme) {
1721                 /* Don't attempt delivery, just remove it from the queue */
1722                 ast_mutex_lock(&iaxq.lock);
1723                 if (f->prev) 
1724                         f->prev->next = f->next;
1725                 else
1726                         iaxq.head = f->next;
1727                 if (f->next)
1728                         f->next->prev = f->prev;
1729                 else
1730                         iaxq.tail = f->prev;
1731                 iaxq.count--;
1732                 ast_mutex_unlock(&iaxq.lock);
1733                 f->retrans = -1;
1734                 /* Free the IAX frame */
1735                 iax2_frame_free(f);
1736         }
1737         return 0;
1738 }
1739
1740 static int iax2_set_jitter(int fd, int argc, char *argv[])
1741 {
1742 #ifdef NEWJB
1743         ast_cli(fd, "sorry, this command is deprecated\n");
1744         return RESULT_SUCCESS;
1745 #else
1746         if ((argc != 4) && (argc != 5))
1747                 return RESULT_SHOWUSAGE;
1748         if (argc == 4) {
1749                 max_jitter_buffer = atoi(argv[3]);
1750                 if (max_jitter_buffer < 0)
1751                         max_jitter_buffer = 0;
1752         } else {
1753                 if (argc == 5) {
1754                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1755                                 if (iaxs[atoi(argv[3])]) {
1756                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1757                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1758                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1759                                 } else
1760                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1761                         } else
1762                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1763                 }
1764         }
1765         return RESULT_SUCCESS;
1766 #endif
1767 }
1768
1769 static char jitter_usage[] = 
1770 "Usage: iax set jitter [callid] <value>\n"
1771 "       If used with a callid, it sets the jitter buffer to the given static\n"
1772 "value (until its next calculation).  If used without a callid, the value is used\n"
1773 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1774 "buffer size is reduced.";
1775
1776 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1777 {
1778         struct iax2_peer *peer;
1779
1780         if (argc != 4)
1781         return RESULT_SHOWUSAGE;
1782         if (!strcmp(argv[3],"all")) {
1783                 reload_config();
1784                 ast_cli(fd, "OK cache is flushed.\n");
1785         } else if ((peer = find_peer(argv[3], 0))) {
1786                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1787                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1788                         expire_registry(peer);
1789                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1790                 } else {
1791                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1792                 }
1793         } else {
1794                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1795         }
1796         
1797         return RESULT_SUCCESS;
1798 }
1799
1800 static int iax2_test_losspct(int fd, int argc, char *argv[])
1801 {
1802        if (argc != 4)
1803                return RESULT_SHOWUSAGE;
1804
1805        test_losspct = atoi(argv[3]);
1806
1807        return RESULT_SUCCESS;
1808 }
1809
1810 #ifdef IAXTESTS
1811 static int iax2_test_late(int fd, int argc, char *argv[])
1812 {
1813         if (argc != 4)
1814                 return RESULT_SHOWUSAGE;
1815
1816         test_late = atoi(argv[3]);
1817
1818         return RESULT_SUCCESS;
1819 }
1820
1821 static int iax2_test_resync(int fd, int argc, char *argv[])
1822 {
1823         if (argc != 4)
1824                 return RESULT_SHOWUSAGE;
1825
1826         test_resync = atoi(argv[3]);
1827
1828         return RESULT_SUCCESS;
1829 }
1830
1831 static int iax2_test_jitter(int fd, int argc, char *argv[])
1832 {
1833         if (argc < 4 || argc > 5)
1834                 return RESULT_SHOWUSAGE;
1835
1836         test_jit = atoi(argv[3]);
1837         if (argc == 5) 
1838                 test_jitpct = atoi(argv[4]);
1839
1840         return RESULT_SUCCESS;
1841 }
1842 #endif /* IAXTESTS */
1843
1844 /*--- iax2_show_peer: Show one peer in detail ---*/
1845 static int iax2_show_peer(int fd, int argc, char *argv[])
1846 {
1847         char status[30] = "";
1848         char cbuf[256];
1849         char iabuf[INET_ADDRSTRLEN];
1850         struct iax2_peer *peer;
1851         char codec_buf[512];
1852         int x = 0, codec = 0, load_realtime = 0;
1853
1854         if (argc < 4)
1855                 return RESULT_SHOWUSAGE;
1856
1857         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1858
1859         peer = find_peer(argv[3], load_realtime);
1860         if (peer) {
1861                 ast_cli(fd,"\n\n");
1862                 ast_cli(fd, "  * Name       : %s\n", peer->name);
1863                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1864                 ast_cli(fd, "  Context      : %s\n", peer->context);
1865                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
1866                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1867                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1868                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
1869                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
1870                 ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
1871                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1872                 ast_cli(fd, "  Username     : %s\n", peer->username);
1873                 ast_cli(fd, "  Codecs       : ");
1874                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1875                 ast_cli(fd, "%s\n", codec_buf);
1876
1877                 ast_cli(fd, "  Codec Order  : (");
1878                 for(x = 0; x < 32 ; x++) {
1879                         codec = ast_codec_pref_index(&peer->prefs,x);
1880                         if(!codec)
1881                                 break;
1882                         ast_cli(fd, "%s", ast_getformatname(codec));
1883                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1884                                 ast_cli(fd, "|");
1885                 }
1886
1887                 if (!x)
1888                         ast_cli(fd, "none");
1889                 ast_cli(fd, ")\n");
1890
1891                 ast_cli(fd, "  Status       : ");
1892                 if (peer->lastms < 0)
1893                         ast_copy_string(status, "UNREACHABLE", sizeof(status));
1894                 else if (peer->lastms > peer->maxms)
1895                         snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1896                 else if (peer->lastms)
1897                         snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1898                 else
1899                         ast_copy_string(status, "UNKNOWN", sizeof(status));
1900                 ast_cli(fd, "%s\n",status);
1901                 ast_cli(fd,"\n");
1902                 if (ast_test_flag(peer, IAX_TEMPONLY))
1903                         destroy_peer(peer);
1904         } else {
1905                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1906                 ast_cli(fd,"\n");
1907         }
1908
1909         return RESULT_SUCCESS;
1910 }
1911
1912 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1913 {
1914         int which = 0;
1915         struct iax2_peer *p;
1916
1917         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1918         if(pos == 3) {
1919                 ast_mutex_lock(&peerl.lock);
1920                 for(p = peerl.peers ; p ; p = p->next) {
1921                         if(!strncasecmp(p->name, word, strlen(word))) {
1922                                 if(++which > state) {
1923                                         return strdup(p->name);
1924                                 }
1925                         }
1926                 }
1927                 ast_mutex_unlock(&peerl.lock);
1928         }
1929
1930         return NULL;
1931 }
1932
1933 static int iax2_show_stats(int fd, int argc, char *argv[])
1934 {
1935         struct iax_frame *cur;
1936         int cnt = 0, dead=0, final=0;
1937         if (argc != 3)
1938                 return RESULT_SHOWUSAGE;
1939         for (cur = iaxq.head; cur ; cur = cur->next) {
1940                 if (cur->retries < 0)
1941                         dead++;
1942                 if (cur->final)
1943                         final++;
1944                 cnt++;
1945         }
1946         ast_cli(fd, "    IAX Statistics\n");
1947         ast_cli(fd, "---------------------\n");
1948         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1949         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1950         return RESULT_SUCCESS;
1951 }
1952
1953 static int iax2_show_cache(int fd, int argc, char *argv[])
1954 {
1955         struct iax2_dpcache *dp;
1956         char tmp[1024] = "", *pc;
1957         int s;
1958         int x,y;
1959         struct timeval tv;
1960         gettimeofday(&tv, NULL);
1961         ast_mutex_lock(&dpcache_lock);
1962         dp = dpcache;
1963         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1964         while(dp) {
1965                 s = dp->expirey.tv_sec - tv.tv_sec;
1966                 tmp[0] = '\0';
1967                 if (dp->flags & CACHE_FLAG_EXISTS)
1968                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1969                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1970                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1971                 if (dp->flags & CACHE_FLAG_CANEXIST)
1972                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1973                 if (dp->flags & CACHE_FLAG_PENDING)
1974                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1975                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1976                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1977                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1978                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1979                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1980                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1981                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1982                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1983                 /* Trim trailing pipe */
1984                 if (!ast_strlen_zero(tmp))
1985                         tmp[strlen(tmp) - 1] = '\0';
1986                 else
1987                         ast_copy_string(tmp, "(none)", sizeof(tmp));
1988                 y=0;
1989                 pc = strchr(dp->peercontext, '@');
1990                 if (!pc)
1991                         pc = dp->peercontext;
1992                 else
1993                         pc++;
1994                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1995                         if (dp->waiters[x] > -1)
1996                                 y++;
1997                 if (s > 0)
1998                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1999                 else
2000                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2001                 dp = dp->next;
2002         }
2003         ast_mutex_unlock(&dpcache_lock);
2004         return RESULT_SUCCESS;
2005 }
2006
2007 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2008
2009 #ifdef BRIDGE_OPTIMIZATION
2010 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2011
2012 static int forward_delivery(struct iax_frame *fr)
2013 {
2014         struct chan_iax2_pvt *p1, *p2;
2015         char iabuf[INET_ADDRSTRLEN];
2016         int res, orig_ts;
2017
2018         p1 = iaxs[fr->callno];
2019         p2 = iaxs[p1->bridgecallno];
2020         if (!p1)
2021                 return -1;
2022         if (!p2)
2023                 return -1;
2024
2025         if (option_debug)
2026                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2027                                 fr->ts,
2028                                 p1->callno, p1->peercallno,
2029                                 p2->callno, p2->peercallno,
2030                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2031                                 ntohs(p2->addr.sin_port));
2032
2033         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2034            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2035            send full frame on timestamp wrap when doing optimized bridging
2036            (actually current code STILL doesn't)
2037         */
2038         if (fr->ts + 50000 <= p1->last) {
2039                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2040                 if (option_debug)
2041                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2042         }
2043
2044         /* Send with timestamp adjusted to the origin of the outbound leg */
2045         /* But don't destroy inbound timestamp still needed later to set "last" */
2046         orig_ts = fr->ts;
2047         fr->ts = calc_fakestamp(p1, p2, fr->ts);
2048         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2049         fr->ts = orig_ts;
2050         return res;
2051 }
2052 #endif
2053
2054 static void unwrap_timestamp(struct iax_frame *fr)
2055 {
2056         int x;
2057
2058         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2059                 x = fr->ts - iaxs[fr->callno]->last;
2060                 if (x < -50000) {
2061                         /* Sudden big jump backwards in timestamp:
2062                            What likely happened here is that miniframe timestamp has circled but we haven't
2063                            gotten the update from the main packet.  We'll just pretend that we did, and
2064                            update the timestamp appropriately. */
2065                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2066                         if (option_debug)
2067                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2068                 }
2069                 if (x > 50000) {
2070                         /* Sudden apparent big jump forwards in timestamp:
2071                            What's likely happened is this is an old miniframe belonging to the previous
2072                            top-16-bit timestamp that has turned up out of order.
2073                            Adjust the timestamp appropriately. */
2074                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2075                         if (option_debug)
2076                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2077                 }
2078         }
2079 }
2080
2081 #ifdef NEWJB
2082 static int get_from_jb(void *p);
2083
2084 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2085     int when;
2086     struct timeval tv;
2087
2088     gettimeofday(&tv,NULL);
2089
2090     when = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2091           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2092
2093     /*    fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2094
2095     when = jb_next(pvt->jb) - when;
2096     /*   fprintf(stderr, "when = %d\n", when); */
2097
2098     if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2099
2100     if(when <= 0) {
2101       /* XXX should really just empty until when > 0.. */
2102       when = 1;
2103     }
2104
2105     pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2106 }
2107
2108 static int get_from_jb(void *p) {
2109         /* make sure pvt is valid! */   
2110     struct chan_iax2_pvt *pvt = p;
2111     struct iax_frame *fr;
2112     jb_frame frame;
2113     int ret;
2114     long now;
2115     long next;
2116     struct timeval tv;
2117
2118     ast_mutex_lock(&iaxsl[pvt->callno]);
2119     /*  fprintf(stderr, "get_from_jb called\n"); */
2120     pvt->jbid = -1;
2121
2122     gettimeofday(&tv,NULL);
2123     /* round up a millisecond since ast_sched_runq does; */
2124     /* prevents us from spinning while waiting for our now */
2125     /* to catch up with runq's now */
2126     tv.tv_usec += 1000;
2127
2128     now = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2129           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2130
2131     if(now >= (next = jb_next(pvt->jb))) {
2132         ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2133         switch(ret) {
2134             case JB_OK:
2135                 /*if(frame.type == JB_TYPE_VOICE && next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2136                 fr = frame.data;
2137                 __do_deliver(fr);
2138             break;
2139             case JB_INTERP:
2140             {
2141                 struct ast_frame af;
2142
2143                 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2144
2145                 /* create an interpolation frame */
2146                 /*fprintf(stderr, "Making Interpolation frame\n"); */
2147                 af.frametype = AST_FRAME_VOICE;
2148                 af.subclass = pvt->voiceformat;
2149                 af.datalen  = 0;
2150                 af.samples  = frame.ms * 8;
2151                 af.mallocd  = 0;
2152                 af.src  = "IAX2 JB interpolation";
2153                 af.data  = NULL;
2154                 af.delivery.tv_sec = pvt->rxcore.tv_sec;
2155                 af.delivery.tv_usec = pvt->rxcore.tv_usec;
2156                 af.delivery.tv_sec += next / 1000;
2157                 af.delivery.tv_usec += (next % 1000) * 1000;
2158                 af.offset=AST_FRIENDLY_OFFSET;
2159                 if (af.delivery.tv_usec >= 1000000) {
2160                         af.delivery.tv_usec -= 1000000;
2161                         af.delivery.tv_sec += 1;
2162                 }
2163
2164                 /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2165                  * which we'd need to malloc, and then it would free it.  That seems like a drag */
2166                 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2167                         iax2_queue_frame(pvt->callno, &af);
2168             }
2169             break;
2170             case JB_DROP:
2171                 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2172                 iax2_frame_free(frame.data);
2173             break;
2174             case JB_NOFRAME:
2175             case JB_EMPTY:
2176                 /* do nothing */
2177             break;
2178             default:
2179                 /* shouldn't happen */
2180             break;
2181         }
2182     }
2183     update_jbsched(pvt);
2184     ast_mutex_unlock(&iaxsl[pvt->callno]);
2185     return 0;
2186 }
2187 #endif
2188
2189 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or 
2190  * make preprocessor swiss-cheese out of this one.  I'm not sure which is less revolting.. */
2191 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk)
2192 {
2193 #ifdef NEWJB
2194         int type, len;
2195         int ret;
2196 #else
2197         int x;
2198         int ms;
2199         int delay;
2200         unsigned int orig_ts;
2201         int drops[MEMORY_SIZE];
2202         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2203
2204         /* Remember current jitterbuffer so we can log any change */
2205         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2206         /* Similarly for the frame timestamp */
2207         orig_ts = fr->ts;
2208 #endif
2209
2210 #if 0
2211         if (option_debug)
2212                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2213                                 fr->ts, iaxs[fr->callno]->last, updatehistory);
2214 #endif
2215
2216         /* Attempt to recover wrapped timestamps */
2217         unwrap_timestamp(fr);
2218
2219         if (updatehistory) {
2220 #ifndef NEWJB
2221
2222                 /* Attempt to spot a change of timebase on timestamps coming from the other side
2223                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2224                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
2225                    for a while - in this case this code might also resync us.  But that's not a bad thing.
2226                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2227                    [that's why we only do this when updatehistory is true]
2228                 */
2229                 x = fr->ts - iaxs[fr->callno]->last;
2230                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2231                         if (option_debug)
2232                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
2233                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
2234                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2235                         iaxs[fr->callno]->rxcore.tv_sec = 0;
2236                         iaxs[fr->callno]->rxcore.tv_usec = 0;
2237                         /* wipe "last" if stamps have jumped backwards */
2238                         if (x<0)
2239                                 iaxs[fr->callno]->last = 0;
2240                         /* should we also empty history? */
2241                 }
2242                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2243                    frame we received.  (initially the very first, but also see code just above here).
2244                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
2245                    Called by IAX thread, with iaxsl lock held. */
2246                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2247         
2248                 /* Rotate our history queue of "lateness".  Don't worry about those initial
2249                    zeros because the first entry will always be zero */
2250                 for (x=0;x<MEMORY_SIZE - 1;x++) 
2251                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2252                 /* Add a history entry for this one */
2253                 iaxs[fr->callno]->history[x] = ms;
2254 #endif
2255         }
2256 #ifndef NEWJB
2257         else
2258                 ms = 0;
2259 #endif
2260
2261
2262         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2263         if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2264                 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2265                 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2266                 fr->af.delivery.tv_sec += fr->ts / 1000;
2267                 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2268                 if (fr->af.delivery.tv_usec >= 1000000) {
2269                         fr->af.delivery.tv_usec -= 1000000;
2270                         fr->af.delivery.tv_sec += 1;
2271                 }
2272         }
2273         else {
2274 #if 0
2275                 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2276 #endif
2277                 fr->af.delivery.tv_sec = 0;
2278                 fr->af.delivery.tv_usec = 0;
2279         }
2280
2281 #ifndef NEWJB
2282         /* Initialize the minimum to reasonable values.  It's too much
2283            work to do the same for the maximum, repeatedly */
2284         min=iaxs[fr->callno]->history[0];
2285         for (z=0;z < iax2_dropcount + 1;z++) {
2286                 /* Start very optimistic ;-) */
2287                 max=-999999999;
2288                 for (x=0;x<MEMORY_SIZE;x++) {
2289                         if (max < iaxs[fr->callno]->history[x]) {
2290                                 /* We have a candidate new maximum value.  Make
2291                                    sure it's not in our drop list */
2292                                 match = 0;
2293                                 for (y=0;!match && (y<z);y++)
2294                                         match |= (drops[y] == x);
2295                                 if (!match) {
2296                                         /* It's not in our list, use it as the new maximum */
2297                                         max = iaxs[fr->callno]->history[x];
2298                                         maxone = x;
2299                                 }
2300                                 
2301                         }
2302                         if (!z) {
2303                                 /* On our first pass, find the minimum too */
2304                                 if (min > iaxs[fr->callno]->history[x])
2305                                         min = iaxs[fr->callno]->history[x];
2306                         }
2307                 }
2308 #if 1
2309                 drops[z] = maxone;
2310 #endif
2311         }
2312 #endif
2313
2314 #ifdef NEWJB
2315         type = JB_TYPE_CONTROL;
2316         len = 0;
2317
2318         if(fr->af.frametype == AST_FRAME_VOICE) {
2319                 type = JB_TYPE_VOICE;
2320                 len = ast_codec_get_samples(&fr->af) / 8;
2321         } else if(fr->af.frametype == AST_FRAME_CNG) {
2322                 type = JB_TYPE_SILENCE;
2323         }
2324
2325         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2326                 __do_deliver(fr);
2327                 return 0;
2328         }
2329
2330         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2331          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2332         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2333             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2334             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2335                 jb_frame frame;
2336
2337                 /* deliver any frames in the jb */
2338                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2339                         __do_deliver(frame.data);
2340
2341                 jb_reset(iaxs[fr->callno]->jb);
2342
2343                 if (iaxs[fr->callno]->jbid > -1)
2344                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2345
2346                 iaxs[fr->callno]->jbid = -1;
2347
2348                 /* deliver this frame now */
2349                 __do_deliver(fr);
2350                 return 0;
2351
2352         }
2353
2354
2355         /* insert into jitterbuffer */
2356         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2357         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2358                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2359         if (ret == JB_DROP) {
2360                 iax2_frame_free(fr);
2361         } else if (ret == JB_SCHED) {
2362                 update_jbsched(iaxs[fr->callno]);
2363         }
2364 #else
2365         /* Just for reference, keep the "jitter" value, the difference between the
2366            earliest and the latest. */
2367         if (max >= min)
2368                 iaxs[fr->callno]->jitter = max - min;   
2369         
2370         /* IIR filter for keeping track of historic jitter, but always increase
2371            historic jitter immediately for increase */
2372         
2373         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2374                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2375         else
2376                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2377                         iaxs[fr->callno]->historicjitter;
2378
2379         /* If our jitter buffer is too big (by a significant margin), then we slowly
2380            shrink it to avoid letting the change be perceived */
2381         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2382                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2383
2384         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2385         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2386            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2387            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2388         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2389                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2390
2391         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2392            buffer immediately to accomodate it (and a little more).  */
2393         if (max > iaxs[fr->callno]->jitterbuffer)
2394                 iaxs[fr->callno]->jitterbuffer = max 
2395                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2396
2397         /* update "min", just for RRs and stats */
2398         iaxs[fr->callno]->min = min; 
2399
2400         /* Subtract the lateness from our jitter buffer to know how long to wait
2401            before sending our packet.  */
2402         delay = iaxs[fr->callno]->jitterbuffer - ms;
2403
2404         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2405         if (delay > maxjitterbuffer)
2406                 delay = maxjitterbuffer;
2407         
2408         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2409         /* If frame came from trunk, also don't do any delay */
2410         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2411                 delay = 0;
2412
2413         if (option_debug) {
2414                 /* Log jitter stats for possible offline analysis */
2415                 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
2416                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2417                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2418                                         min, max, iaxs[fr->callno]->jitterbuffer,
2419                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2420                                         ms, delay,
2421                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2422         }
2423
2424         if (delay < 1) {
2425                 /* Don't deliver it more than 4 ms late */
2426                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2427                         if (option_debug)
2428                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2429                         __do_deliver(fr);
2430                 } else {
2431                         if (option_debug)
2432                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2433                         iaxs[fr->callno]->frames_dropped++;
2434                         /* Free our iax frame */
2435                         iax2_frame_free(fr);
2436                 }
2437         } else {
2438                 if (option_debug)
2439                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2440                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2441         }
2442 #endif
2443         return 0;
2444 }
2445
2446 static int iax2_transmit(struct iax_frame *fr)
2447 {
2448         /* Lock the queue and place this packet at the end */
2449         fr->next = NULL;
2450         fr->prev = NULL;
2451         /* By setting this to 0, the network thread will send it for us, and
2452            queue retransmission if necessary */
2453         fr->sentyet = 0;
2454         ast_mutex_lock(&iaxq.lock);
2455         if (!iaxq.head) {
2456                 /* Empty queue */
2457                 iaxq.head = fr;
2458                 iaxq.tail = fr;
2459         } else {
2460                 /* Double link */
2461                 iaxq.tail->next = fr;
2462                 fr->prev = iaxq.tail;
2463                 iaxq.tail = fr;
2464         }
2465         iaxq.count++;
2466         ast_mutex_unlock(&iaxq.lock);
2467         /* Wake up the network thread */
2468         pthread_kill(netthreadid, SIGURG);
2469         return 0;
2470 }
2471
2472
2473
2474 static int iax2_digit(struct ast_channel *c, char digit)
2475 {
2476         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2477 }
2478
2479 static int iax2_sendtext(struct ast_channel *c, const char *text)
2480 {
2481         
2482         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2483                 0, 0, text, strlen(text) + 1, -1);
2484 }
2485
2486 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2487 {
2488         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2489 }
2490
2491 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2492 {
2493         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2494 }
2495
2496 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2497 {
2498         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2499         ast_mutex_lock(&iaxsl[callno]);
2500         if (iaxs[callno])
2501                 iaxs[callno]->owner = newchan;
2502         else
2503                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2504         ast_mutex_unlock(&iaxsl[callno]);
2505         return 0;
2506 }
2507
2508 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2509 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2510
2511 static void destroy_user(struct iax2_user *user);
2512 static int expire_registry(void *data);
2513
2514 static struct iax2_peer *realtime_peer(const char *peername)
2515 {
2516         struct ast_variable *var;
2517         struct ast_variable *tmp;
2518         struct iax2_peer *peer=NULL;
2519         time_t regseconds, nowtime;
2520         int dynamic=0;
2521
2522         var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2523         if (!var)
2524                 return NULL;
2525
2526         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2527         
2528         if (!peer)
2529                 return NULL;
2530
2531         tmp = var;
2532         while(tmp) {
2533                 /* Make sure it's not a user only... */
2534                 if (!strcasecmp(tmp->name, "type")) {
2535                         if (strcasecmp(tmp->value, "friend") &&
2536                             strcasecmp(tmp->value, "peer")) {
2537                                 /* Whoops, we weren't supposed to exist! */
2538                                 destroy_peer(peer);
2539                                 peer = NULL;
2540                                 break;
2541                         } 
2542                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2543                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
2544                                 regseconds = 0;
2545                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2546                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2547                 } else if (!strcasecmp(tmp->name, "port")) {
2548                         peer->addr.sin_port = htons(atoi(tmp->value));
2549                 } else if (!strcasecmp(tmp->name, "host")) {
2550                         if (!strcasecmp(tmp->value, "dynamic"))
2551                                 dynamic = 1;
2552                 }
2553                 tmp = tmp->next;
2554         }
2555         if (!peer)
2556                 return NULL;
2557
2558         ast_variables_destroy(var);
2559
2560         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2561                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2562                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2563                         if (peer->expire > -1)
2564                                 ast_sched_del(sched, peer->expire);
2565                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2566                 }
2567                 ast_mutex_lock(&peerl.lock);
2568                 peer->next = peerl.peers;
2569                 peerl.peers = peer;
2570                 ast_mutex_unlock(&peerl.lock);
2571                 if (ast_test_flag(peer, IAX_DYNAMIC))
2572                         reg_source_db(peer);
2573         } else {
2574                 ast_set_flag(peer, IAX_TEMPONLY);       
2575         }
2576
2577         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2578                 time(&nowtime);
2579                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2580                         memset(&peer->addr, 0, sizeof(peer->addr));
2581                         if (option_debug)
2582                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2583                 }
2584         }
2585
2586         return peer;
2587 }
2588
2589 static struct iax2_user *realtime_user(const char *username)
2590 {
2591         struct ast_variable *var;
2592         struct ast_variable *tmp;
2593         struct iax2_user *user=NULL;
2594
2595         var = ast_load_realtime("iaxusers", "name", username, NULL);
2596         if (!var)
2597                 return NULL;
2598
2599         tmp = var;
2600         while(tmp) {
2601                 /* Make sure it's not a peer only... */
2602                 if (!strcasecmp(tmp->name, "type")) {
2603                         if (strcasecmp(tmp->value, "friend") &&
2604                             strcasecmp(tmp->value, "user")) {
2605                                 return NULL;
2606                         } 
2607                 }
2608                 tmp = tmp->next;
2609         }
2610
2611         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2612         if (!user)
2613                 return NULL;
2614
2615         ast_variables_destroy(var);
2616
2617         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2618                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2619                 ast_mutex_lock(&userl.lock);
2620                 user->next = userl.users;
2621                 userl.users = user;
2622                 ast_mutex_unlock(&userl.lock);
2623         } else {
2624                 ast_set_flag(user, IAX_TEMPONLY);       
2625         }
2626
2627         return user;
2628 }
2629
2630 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2631 {
2632         char port[10];
2633         char ipaddr[20];
2634         char regseconds[20];
2635         time_t nowtime;
2636         
2637         time(&nowtime);
2638         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2639         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2640         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2641         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2642 }
2643
2644 struct create_addr_info {
2645         int capability;
2646         unsigned int flags;
2647         int maxtime;
2648         int encmethods;
2649         int found;
2650         int sockfd;
2651         char username[80];
2652         char secret[80];
2653         char outkey[80];
2654         char timezone[80];
2655         char prefs[32];
2656         char context[AST_MAX_EXTENSION];
2657         char peercontext[AST_MAX_EXTENSION];
2658 };
2659
2660 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2661 {
2662         struct ast_hostent ahp;
2663         struct hostent *hp;
2664         struct iax2_peer *peer;
2665
2666         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2667         cai->sockfd = defaultsockfd;
2668         cai->maxtime = 0;
2669         sin->sin_family = AF_INET;
2670
2671         if (!(peer = find_peer(peername, 1))) {
2672                 cai->found = 0;
2673
2674                 hp = ast_gethostbyname(peername, &ahp);
2675                 if (hp) {
2676                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2677                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2678                         /* use global iax prefs for unknown peer/user */
2679                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2680                         return 0;
2681                 } else {
2682                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2683                         return -1;
2684                 }
2685         }
2686
2687         cai->found = 1;
2688         
2689         /* if the peer has no address (current or default), return failure */
2690         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2691                 if (ast_test_flag(peer, IAX_TEMPONLY))
2692                         destroy_peer(peer);
2693                 return -1;
2694         }
2695
2696         /* if the peer is being monitored and is currently unreachable, return failure */
2697         if (peer->maxms && (peer->lastms > peer->maxms)) {
2698                 if (ast_test_flag(peer, IAX_TEMPONLY))
2699                         destroy_peer(peer);
2700                 return -1;
2701         }
2702
2703         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2704         cai->maxtime = peer->maxms;
2705         cai->capability = peer->capability;
2706         cai->encmethods = peer->encmethods;
2707         cai->sockfd = peer->sockfd;
2708         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2709         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2710         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2711         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2712         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2713         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2714         if (ast_strlen_zero(peer->dbsecret)) {
2715                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2716         } else {
2717                 char *family;
2718                 char *key = NULL;
2719
2720                 family = ast_strdupa(peer->dbsecret);
2721                 if (family) {
2722                         key = strchr(family, '/');
2723                         if (key)
2724                                 *key++ = '\0';
2725                 }
2726                 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2727                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2728                         if (ast_test_flag(peer, IAX_TEMPONLY))
2729                                 destroy_peer(peer);
2730                         return -1;
2731                 }
2732         }
2733
2734         if (peer->addr.sin_addr.s_addr) {
2735                 sin->sin_addr = peer->addr.sin_addr;
2736                 sin->sin_port = peer->addr.sin_port;
2737         } else {
2738                 sin->sin_addr = peer->defaddr.sin_addr;
2739                 sin->sin_port = peer->defaddr.sin_port;
2740         }
2741
2742         if (ast_test_flag(peer, IAX_TEMPONLY))
2743                 destroy_peer(peer);
2744
2745         return 0;
2746 }
2747
2748 static int auto_congest(void *nothing)
2749 {
2750         int callno = PTR_TO_CALLNO(nothing);
2751         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2752         ast_mutex_lock(&iaxsl[callno]);
2753         if (iaxs[callno]) {
2754                 iaxs[callno]->initid = -1;
2755                 iax2_queue_frame(callno, &f);
2756                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2757         }
2758         ast_mutex_unlock(&iaxsl[callno]);
2759         return 0;
2760 }
2761
2762 static unsigned int iax2_datetime(char *tz)
2763 {
2764         time_t t;
2765         struct tm tm;
2766         unsigned int tmp;
2767         time(&t);
2768         localtime_r(&t, &tm);
2769         if (!ast_strlen_zero(tz))
2770                 ast_localtime(&t, &tm, tz);
2771         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2772         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2773         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2774         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2775         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2776         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2777         return tmp;
2778 }
2779
2780 struct parsed_dial_string {
2781         char *username;
2782         char *password;
2783         char *key;
2784         char *peer;
2785         char *port;
2786         char *exten;
2787         char *context;
2788         char *options;
2789 };
2790
2791 /*!
2792  * \brief Parses an IAX dial string into its component parts.
2793  * \param data the string to be parsed
2794  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2795  * \return nothing
2796  *
2797  * This function parses the string and fills the structure
2798  * with pointers to its component parts. The input string
2799  * will be modified.
2800  *
2801  * \note This function supports both plaintext passwords and RSA
2802  * key names; if the password string is formatted as '[keyname]',
2803  * then the keyname will be placed into the key field, and the
2804  * password field will be set to NULL.
2805  *
2806  * \note The dial string format is:
2807  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2808  */
2809 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2810 {
2811         if (!data || ast_strlen_zero(data))
2812                 return;
2813
2814         pds->peer = strsep(&data, "/");
2815         pds->exten = strsep(&data, "/");
2816         pds->options = data;
2817
2818         if (pds->exten) {
2819                 data = pds->exten;
2820                 pds->exten = strsep(&data, "@");
2821                 pds->context = data;
2822         }
2823
2824         if (strchr(pds->peer, '@')) {
2825                 data = pds->peer;
2826                 pds->username = strsep(&data, "@");
2827                 pds->peer = data;
2828         }
2829
2830         if (pds->username) {
2831                 data = pds->username;
2832                 pds->username = strsep(&data, ":");
2833                 pds->password = data;
2834         }
2835
2836         data = pds->peer;
2837         pds->peer = strsep(&data, ":");
2838         pds->port = data;
2839
2840         /* check for a key name wrapped in [] in the secret position, if found,
2841            move it to the key field instead
2842         */
2843         if (pds->password && (pds->password[0] == '[')) {
2844                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2845                 pds->password = NULL;
2846         }
2847 }
2848
2849 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2850 {
2851         struct sockaddr_in sin;
2852         char *l=NULL, *n=NULL, *tmpstr;
2853         struct iax_ie_data ied;
2854         char *defaultrdest = "s";
2855         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2856         struct parsed_dial_string pds;
2857         struct create_addr_info cai;
2858
2859         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2860                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2861                 return -1;
2862         }
2863
2864         memset(&cai, 0, sizeof(cai));
2865         cai.encmethods = iax2_encryption;
2866
2867         memset(&pds, 0, sizeof(pds));
2868         tmpstr = ast_strdupa(dest);
2869         parse_dial_string(tmpstr, &pds);
2870
2871         if (!pds.exten)
2872                 pds.exten = defaultrdest;
2873
2874         if (create_addr(pds.peer, &sin, &cai)) {
2875                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2876                 return -1;
2877         }
2878
2879         if (!pds.username && !ast_strlen_zero(cai.username))
2880                 pds.username = cai.username;
2881         if (!pds.password && !ast_strlen_zero(cai.secret))
2882                 pds.password = cai.secret;
2883         if (!pds.key && !ast_strlen_zero(cai.outkey))
2884                 pds.key = cai.outkey;
2885         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2886                 pds.context = cai.peercontext;
2887
2888         /* Keep track of the context for outgoing calls too */
2889         ast_copy_string(c->context, cai.context, sizeof(c->context));
2890
2891         if (pds.port)
2892                 sin.sin_port = htons(atoi(pds.port));
2893
2894         l = c->cid.cid_num;
2895         n = c->cid.cid_name;
2896
2897         /* Now build request */ 
2898         memset(&ied, 0, sizeof(ied));
2899
2900         /* On new call, first IE MUST be IAX version of caller */
2901         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2902         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2903         if (pds.options && strchr(pds.options, 'a')) {
2904                 /* Request auto answer */
2905                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2906         }
2907
2908         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2909
2910         if (l) {
2911                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2912                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2913         } else {
2914                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2915         }
2916
2917         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2918         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2919
2920         if (n)
2921                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2922         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2923                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2924
2925         if (c->language && !ast_strlen_zero(c->language))
2926                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2927         if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2928                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2929
2930         if (pds.context)
2931                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2932
2933         if (pds.username)
2934                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2935
2936         if (cai.encmethods)
2937                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2938
2939         ast_mutex_lock(&iaxsl[callno]);
2940
2941         if (!ast_strlen_zero(c->context))
2942                 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2943
2944         if (pds.username)
2945                 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2946
2947         iaxs[callno]->encmethods = cai.encmethods;
2948
2949         if (pds.key)
2950                 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2951         if (pds.password)
2952                 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2953
2954         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2955         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2956         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2957         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2958
2959         if (iaxs[callno]->maxtime) {
2960                 /* Initialize pingtime and auto-congest time */
2961                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2962                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2963         } else if (autokill) {
2964                 iaxs[callno]->pingtime = autokill / 2;
2965                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2966         }
2967
2968         /* Transmit the string in a "NEW" request */
2969         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2970
2971         ast_mutex_unlock(&iaxsl[callno]);
2972         ast_setstate(c, AST_STATE_RINGING);
2973         
2974         return 0;
2975 }
2976
2977 static int iax2_hangup(struct ast_channel *c) 
2978 {
2979         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2980         int alreadygone;
2981         struct iax_ie_data ied;
2982         memset(&ied, 0, sizeof(ied));
2983         ast_mutex_lock(&iaxsl[callno]);
2984         if (callno && iaxs[callno]) {
2985                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2986                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2987                 /* Send the hangup unless we have had a transmission error or are already gone */
2988                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2989                 if (!iaxs[callno]->error && !alreadygone) 
2990                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2991                 /* Explicitly predestroy it */
2992                 iax2_predestroy_nolock(callno);
2993                 /* If we were already gone to begin with, destroy us now */
2994                 if (alreadygone) {
2995                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2996                         iax2_destroy_nolock(callno);
2997                 }
2998         }
2999         ast_mutex_unlock(&iaxsl[callno]);
3000         if (option_verbose > 2) 
3001                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3002         return 0;
3003 }
3004
3005 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3006 {
3007         struct ast_option_header *h;
3008         int res;
3009         h = malloc(datalen + sizeof(struct ast_option_header));
3010         if (h) {
3011                 h->flag = AST_OPTION_FLAG_REQUEST;
3012                 h->option = htons(option);
3013                 memcpy(h->data, data, datalen);
3014                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3015                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
3016                 free(h);
3017                 return res;
3018         } else 
3019                 ast_log(LOG_WARNING, "Out of memory\n");
3020         return -1;
3021 }
3022
3023 static struct ast_frame *iax2_read(struct ast_channel *c) 
3024 {
3025         static struct ast_frame f = { AST_FRAME_NULL, };
3026         ast_log(LOG_NOTICE, "I should never be called!\n");
3027         return &f;
3028 }
3029
3030 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3031 {
3032         int res;
3033         struct iax_ie_data ied0;
3034         struct iax_ie_data ied1;
3035         unsigned int transferid = rand();
3036         memset(&ied0, 0, sizeof(ied0));
3037         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3038         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3039         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3040
3041         memset(&ied1, 0, sizeof(ied1));
3042         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3043         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3044         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3045         
3046         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3047         if (res)
3048                 return -1;
3049         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3050         if (res)
3051                 return -1;
3052         iaxs[callno0]->transferring = TRANSFER_BEGIN;
3053         iaxs[callno1]->transferring = TRANSFER_BEGIN;
3054         return 0;
3055 }
3056
3057 static void lock_both(unsigned short callno0, unsigned short callno1)
3058 {
3059         ast_mutex_lock(&iaxsl[callno0]);
3060         while (ast_mutex_trylock(&iaxsl[callno1])) {
3061                 ast_mutex_unlock(&iaxsl[callno0]);
3062                 usleep(10);
3063                 ast_mutex_lock(&iaxsl[callno0]);
3064         }
3065 }
3066
3067 static void unlock_both(unsigned short callno0, unsigned short callno1)
3068 {
3069         ast_mutex_unlock(&iaxsl[callno1]);
3070         ast_mutex_unlock(&iaxsl[callno0]);
3071 }
3072
3073 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
3074 {
3075         struct ast_channel *cs[3];
3076         struct ast_channel *who;
3077         int to = -1;
3078         int res = -1;
3079         int transferstarted=0;
3080         struct ast_frame *f;
3081         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3082         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3083         struct timeval waittimer = {0, 0}, tv;
3084
3085         lock_both(callno0, callno1);
3086         /* Put them in native bridge mode */
3087         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3088                 iaxs[callno0]->bridgecallno = callno1;
3089                 iaxs[callno1]->bridgecallno = callno0;
3090         }
3091         unlock_both(callno0, callno1);
3092
3093         /* If not, try to bridge until we can execute a transfer, if we can */
3094         cs[0] = c0;
3095         cs[1] = c1;
3096         for (/* ever */;;) {
3097                 /* Check in case we got masqueraded into */
3098                 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3099                         if (option_verbose > 2)
3100                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3101                         /* Remove from native mode */
3102                         if (c0->type == channeltype) {
3103                                 ast_mutex_lock(&iaxsl[callno0]);
3104                                 iaxs[callno0]->bridgecallno = 0;
3105                                 ast_mutex_unlock(&iaxsl[callno0]);
3106                         }
3107                         if (c1->type == channeltype) {
3108                                 ast_mutex_lock(&iaxsl[callno1]);
3109                                 iaxs[callno1]->bridgecallno = 0;
3110                                 ast_mutex_unlock(&iaxsl[callno1]);
3111                         }
3112                         return -2;
3113                 }
3114                 if (c0->nativeformats != c1->nativeformats) {
3115                         if (option_verbose > 2) {
3116                                 char buf0[255];
3117                                 char buf1[255];
3118                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3119                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3120                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3121                         }
3122                         /* Remove from native mode */
3123                         lock_both(callno0, callno1);
3124                         iaxs[callno0]->bridgecallno = 0;
3125                         iaxs[callno1]->bridgecallno = 0;
3126                         unlock_both(callno0, callno1);
3127                         return -2;
3128                 }
3129                 /* check if transfered and if we really want native bridging */
3130                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) && 
3131                 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3132                         /* Try the transfer */
3133                         if (iax2_start_transfer(callno0, callno1))
3134                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3135                         transferstarted = 1;
3136                 }
3137                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3138                         /* Call has been transferred.  We're no longer involved */
3139                         gettimeofday(&tv, NULL);
3140                         if (!waittimer.tv_sec