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