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