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