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