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