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