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