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