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