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