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