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