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