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