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