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