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