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