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