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