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