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