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