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