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