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