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