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