Version 0.2.0 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 (ast_pthread_mutex_lock(&pvt->owner->lock)) {
895                                 ast_log(LOG_WARNING, "Unable to lock channel %s\n", pvt->owner->name);
896                         } else if (!pvt->owner || (pvt->owner->pvt->pvt != pvt)) {
897                                 ast_log(LOG_WARNING, "Something very strange happened...\n");
898                         } else {
899                                 /* If there's an owner, prod it to give up */
900                                 pvt->owner->pvt->pvt = NULL;
901                                 pvt->owner->_softhangup |= AST_SOFTHANGUP_DEV;
902                                 ast_queue_hangup(pvt->owner, 0);
903                                 ast_pthread_mutex_unlock(&pvt->owner->lock);
904                         }
905                 }
906
907                 iaxs[callno] = NULL;
908
909                 for (cur = iaxq.head; cur ; cur = cur->next) {
910                         /* Cancel any pending transmissions */
911                         if (cur->callno == pvt->callno) 
912                                 cur->retries = -1;
913                 }
914                 if (pvt->reg) {
915                         pvt->reg->callno = -1;
916                 }
917                 free(pvt);
918         }
919 }
920
921
922 static int attempt_transmit(void *data)
923 {
924         /* Attempt to transmit the frame to the remote peer */
925         struct ast_iax_frame *f = data;
926         int freeme=0;
927         /* Make sure this call is still active */
928         if ((f->callno > -1) && iaxs[f->callno]) {
929                 if ((f->retries < 0) /* Already ACK'd */ ||
930                     (f->retries >= max_retries) /* Too many attempts */) {
931                                 /* Record an error if we've transmitted too many times */
932                                 if (f->retries >= max_retries) {
933                                         if (f->transfer) {
934                                                 /* Transfer timeout */
935                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
936                                         } else if (f->final) {
937                                                 if (f->final) 
938                                                         iax_destroy(f->callno);
939                                         } else {
940                                                 if (iaxs[f->callno]->owner)
941                                                         ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->f->frametype, f->f->subclass, f->ts, f->seqno);
942                                                 iaxs[f->callno]->error = ETIMEDOUT;
943                                                 if (iaxs[f->callno]->owner) {
944                                                         /* Hangup the fd */
945                                                         ast_softhangup(iaxs[f->callno]->owner, AST_SOFTHANGUP_DEV);
946                                                         ast_queue_hangup(iaxs[f->callno]->owner, 1);
947                                                 } else {
948                                                         if (iaxs[f->callno]->reg) {
949                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
950                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
951                                                                 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
952                                                         }
953                                                         iax_destroy(f->callno);
954                                                 }
955                                         }
956
957                                 }
958                                 freeme++;
959                 } else {
960                         /* Attempt transmission */
961                         send_packet(f);
962                         f->retries++;
963                         /* Try again later after 10 times as long */
964                         f->retrytime *= 10;
965                         if (f->retrytime > MAX_RETRY_TIME)
966                                 f->retrytime = MAX_RETRY_TIME;
967                         /* Transfer messages max out at one second */
968                         if (f->transfer && (f->retrytime > 1000))
969                                 f->retrytime = 1000;
970                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
971                 }
972         } else {
973                 /* Make sure it gets freed */
974                 f->retries = -1;
975                 freeme++;
976         }
977         /* Do not try again */
978         if (freeme) {
979                 /* Don't attempt delivery, just remove it from the queue */
980                 ast_pthread_mutex_lock(&iaxq.lock);
981                 if (f->prev) 
982                         f->prev->next = f->next;
983                 else
984                         iaxq.head = f->next;
985                 if (f->next)
986                         f->next->prev = f->prev;
987                 else
988                         iaxq.tail = f->prev;
989                 iaxq.count--;
990                 ast_pthread_mutex_unlock(&iaxq.lock);
991                 /* Free the frame */
992                 ast_frfree(f->f);
993                 f->retrans = -1;
994                 ast_iax_frame_free(f);
995         }
996         return 0;
997 }
998
999 static int iax_set_jitter(int fd, int argc, char *argv[])
1000 {
1001         if ((argc != 4) && (argc != 5))
1002                 return RESULT_SHOWUSAGE;
1003         if (argc == 4) {
1004                 max_jitter_buffer = atoi(argv[3]);
1005                 if (max_jitter_buffer < 0)
1006                         max_jitter_buffer = 0;
1007         } else {
1008                 if (argc == 5) {
1009                         ast_pthread_mutex_lock(&iaxs_lock);
1010                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1011                                 if (iaxs[atoi(argv[3])]) {
1012                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1013                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1014                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1015                                 } else
1016                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1017                         } else
1018                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1019                         ast_pthread_mutex_unlock(&iaxs_lock);
1020                 }
1021         }
1022         return RESULT_SUCCESS;
1023 }
1024
1025 static char jitter_usage[] = 
1026 "Usage: iax set jitter [callid] <value>\n"
1027 "       If used with a callid, it sets the jitter buffer to the given static\n"
1028 "value (until its next calculation).  If used without a callid, the value is used\n"
1029 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1030 "buffer size is reduced.";
1031
1032 static int iax_show_stats(int fd, int argc, char *argv[])
1033 {
1034         struct ast_iax_frame *cur;
1035         int cnt = 0, dead=0, final=0;
1036         if (argc != 3)
1037                 return RESULT_SHOWUSAGE;
1038         for (cur = iaxq.head; cur ; cur = cur->next) {
1039                 if (cur->retries < 0)
1040                         dead++;
1041                 if (cur->final)
1042                         final++;
1043                 cnt++;
1044         }
1045         ast_cli(fd, "    IAX Statistics\n");
1046         ast_cli(fd, "---------------------\n");
1047         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1048         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1049         return RESULT_SUCCESS;
1050 }
1051
1052 static int iax_show_cache(int fd, int argc, char *argv[])
1053 {
1054         struct iax_dpcache *dp;
1055         char tmp[1024], *pc;
1056         int s;
1057         int x,y;
1058         struct timeval tv;
1059         gettimeofday(&tv, NULL);
1060         ast_pthread_mutex_lock(&dpcache_lock);
1061         dp = dpcache;
1062         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1063         while(dp) {
1064                 s = dp->expirey.tv_sec - tv.tv_sec;
1065                 strcpy(tmp, "");
1066                 if (dp->flags & CACHE_FLAG_EXISTS)
1067                         strcat(tmp, "EXISTS|");
1068                 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1069                         strcat(tmp, "NONEXISTANT|");
1070                 if (dp->flags & CACHE_FLAG_CANEXIST)
1071                         strcat(tmp, "CANEXIST|");
1072                 if (dp->flags & CACHE_FLAG_PENDING)
1073                         strcat(tmp, "PENDING|");
1074                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1075                         strcat(tmp, "TIMEOUT|");
1076                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1077                         strcat(tmp, "TRANSMITTED|");
1078                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1079                         strcat(tmp, "UNKNOWN|");
1080                 /* Trim trailing pipe */
1081                 if (strlen(tmp))
1082                         tmp[strlen(tmp) - 1] = '\0';
1083                 else
1084                         strcpy(tmp, "(none)");
1085                 y=0;
1086                 pc = strchr(dp->peercontext, '@');
1087                 if (!pc)
1088                         pc = dp->peercontext;
1089                 else
1090                         pc++;
1091                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1092                         if (dp->waiters[x] > -1)
1093                                 y++;
1094                 if (s > 0)
1095                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1096                 else
1097                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1098                 dp = dp->next;
1099         }
1100         ast_pthread_mutex_unlock(&dpcache_lock);
1101         return RESULT_SUCCESS;
1102 }
1103
1104 static char show_stats_usage[] =
1105 "Usage: iax show stats\n"
1106 "       Display statistics on IAX channel driver.\n";
1107
1108
1109 static char show_cache_usage[] =
1110 "Usage: iax show cache\n"
1111 "       Display currently cached IAX Dialplan results.\n";
1112
1113 static struct ast_cli_entry cli_set_jitter = 
1114 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1115
1116 static struct ast_cli_entry cli_show_stats =
1117 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1118
1119 static struct ast_cli_entry cli_show_cache =
1120 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1121
1122 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1123
1124 #ifdef BRIDGE_OPTIMIZATION
1125 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1126
1127 static int forward_delivery(struct ast_iax_frame *fr)
1128 {
1129         struct chan_iax_pvt *p1, *p2;
1130         p1 = iaxs[fr->callno];
1131         p2 = iaxs[p1->bridgecallno];
1132         if (!p1)
1133                 return -1;
1134         if (!p2)
1135                 return -1;
1136         /* Fix relative timestamp */
1137         fr->ts = calc_fakestamp(p1, p2, fr->ts);
1138         /* Now just send it send on the 2nd one 
1139            with adjusted timestamp */
1140         return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1141 }
1142 #endif
1143
1144 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1145 {
1146         int ms,x;
1147         int drops[MEMORY_SIZE];
1148         int min, max=0, maxone=0,y,z, match;
1149         /* ms is a measure of the "lateness" of the packet relative to the first
1150            packet we received, which always has a lateness of 1.  */
1151         ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1152
1153         if (ms > 32767) {
1154                 /* What likely happened here is that our counter has circled but we haven't
1155                    gotten the update from the main packet.  We'll just pretend that we did, and
1156                    update the timestamp appropriately. */
1157                 ms -= 65536;
1158         }
1159
1160         if (ms < -32768) {
1161                 /* We got this packet out of order.  Lets add 65536 to it to bring it into our new
1162                    time frame */
1163                 ms += 65536;
1164         }
1165         
1166         /* Rotate our history queue of "lateness".  Don't worry about those initial
1167            zeros because the first entry will always be zero */
1168         for (x=0;x<MEMORY_SIZE - 1;x++) 
1169                 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1170         /* Add a history entry for this one */
1171         iaxs[fr->callno]->history[x] = ms;
1172
1173         /* Initialize the minimum to reasonable values.  It's too much
1174            work to do the same for the maximum, repeatedly */
1175         min=iaxs[fr->callno]->history[0];
1176         for (z=0;z < iax_dropcount + 1;z++) {
1177                 /* Start very optimistic ;-) */
1178                 max=-999999999;
1179                 for (x=0;x<MEMORY_SIZE;x++) {
1180                         if (max < iaxs[fr->callno]->history[x]) {
1181                                 /* We have a candidate new maximum value.  Make
1182                                    sure it's not in our drop list */
1183                                 match = 0;
1184                                 for (y=0;!match && (y<z);y++)
1185                                         match |= (drops[y] == x);
1186                                 if (!match) {
1187                                         /* It's not in our list, use it as the new maximum */
1188                                         max = iaxs[fr->callno]->history[x];
1189                                         maxone = x;
1190                                 }
1191                                 
1192                         }
1193                         if (!z) {
1194                                 /* On our first pass, find the minimum too */
1195                                 if (min > iaxs[fr->callno]->history[x])
1196                                         min = iaxs[fr->callno]->history[x];
1197                         }
1198                 }
1199 #if 1
1200                 drops[z] = maxone;
1201 #endif
1202         }
1203         /* Just for reference, keep the "jitter" value, the difference between the
1204            earliest and the latest. */
1205         iaxs[fr->callno]->jitter = max - min;   
1206         
1207         /* IIR filter for keeping track of historic jitter, but always increase
1208            historic jitter immediately for increase */
1209         
1210         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1211                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1212         else
1213                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
1214                         iaxs[fr->callno]->historicjitter;
1215
1216         /* If our jitter buffer is too big (by a significant margin), then we slowly
1217            shrink it by about 1 ms each time to avoid letting the change be perceived */
1218         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1219                 iaxs[fr->callno]->jitterbuffer -= 2;
1220
1221
1222 #if 1
1223         /* Constrain our maximum jitter buffer appropriately */
1224         if (max > min + maxjitterbuffer) {
1225                 if (option_debug)
1226                         ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1227                 max = min + maxjitterbuffer;
1228         }
1229 #endif
1230
1231         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1232            buffer immediately to accomodate it (and a little more).  */
1233         if (max > iaxs[fr->callno]->jitterbuffer)
1234                 iaxs[fr->callno]->jitterbuffer = max 
1235                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1236                 
1237
1238         if (option_debug)
1239                 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1240         
1241         /* Subtract the lateness from our jitter buffer to know how long to wait
1242            before sending our packet.  */
1243         ms = iaxs[fr->callno]->jitterbuffer - ms;
1244         
1245         if (!use_jitterbuffer)
1246                 ms = 0;
1247
1248         /* If the caller just wanted us to update, return now */
1249         if (!reallydeliver)
1250                 return 0;
1251                 
1252         if (ms < 1) {
1253                 if (option_debug)
1254                         ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1255                 /* Don't deliver it more than 4 ms late */
1256                 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1257                         do_deliver(fr);
1258                 } else {
1259                         if (option_debug)
1260                                 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1261                         /* Free the packet */
1262                         ast_frfree(fr->f);
1263                         /* And our iax frame */
1264                         ast_iax_frame_free(fr);
1265                 }
1266         } else {
1267                 if (option_debug)
1268                         ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1269                 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1270         }
1271         return 0;
1272 }
1273
1274 static int iax_transmit(struct ast_iax_frame *fr)
1275 {
1276         /* Lock the queue and place this packet at the end */
1277         fr->next = NULL;
1278         fr->prev = NULL;
1279         /* By setting this to 0, the network thread will send it for us, and
1280            queue retransmission if necessary */
1281         fr->sentyet = 0;
1282         ast_pthread_mutex_lock(&iaxq.lock);
1283         if (!iaxq.head) {
1284                 /* Empty queue */
1285                 iaxq.head = fr;
1286                 iaxq.tail = fr;
1287         } else {
1288                 /* Double link */
1289                 iaxq.tail->next = fr;
1290                 fr->prev = iaxq.tail;
1291                 iaxq.tail = fr;
1292         }
1293         iaxq.count++;
1294         ast_pthread_mutex_unlock(&iaxq.lock);
1295         /* Wake up the network thread */
1296         pthread_kill(netthreadid, SIGURG);
1297         return 0;
1298 }
1299
1300
1301
1302 static int iax_digit(struct ast_channel *c, char digit)
1303 {
1304         return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1305 }
1306
1307 static int iax_sendtext(struct ast_channel *c, char *text)
1308 {
1309         
1310         return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1311                 0, 0, text, strlen(text) + 1, -1);
1312 }
1313
1314 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1315 {
1316         return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1317 }
1318
1319 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1320 {
1321         return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1322 }
1323
1324 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1325 {
1326         struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1327         pvt->owner = newchan;
1328         return 0;
1329 }
1330
1331 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, char *peer, char *context)
1332 {
1333         struct hostent *hp;
1334         struct iax_peer *p;
1335         int found=0;
1336         if (sendani)
1337                 *sendani = 0;
1338         sin->sin_family = AF_INET;
1339         ast_pthread_mutex_lock(&peerl.lock);
1340         p = peerl.peers;
1341         while(p) {
1342                 if (!strcasecmp(p->name, peer)) {
1343                         found++;
1344                         if (capability)
1345                                 *capability = p->capability;
1346                         if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
1347                                 if (sendani)
1348                                         *sendani = p->sendani;
1349                                 if (context)
1350                                         strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1351                                 if (p->addr.sin_addr.s_addr) {
1352                                         sin->sin_addr = p->addr.sin_addr;
1353                                         sin->sin_port = p->addr.sin_port;
1354                                 } else {
1355                                         sin->sin_addr = p->defaddr.sin_addr;
1356                                         sin->sin_port = p->defaddr.sin_port;
1357                                 }
1358                                 break;
1359                         }
1360                 }
1361                 p = p->next;
1362         }
1363         ast_pthread_mutex_unlock(&peerl.lock);
1364         if (!p && !found) {
1365                 hp = gethostbyname(peer);
1366                 if (hp) {
1367                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1368                         sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1369                         return 0;
1370                 } else {
1371                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1372                         return -1;
1373                 }
1374         } else if (!p)
1375                 return -1;
1376         else
1377                 return 0;
1378 }
1379 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1380 {
1381         struct sockaddr_in sin;
1382         char host[256];
1383         char *rdest;
1384         char *rcontext;
1385         char *username;
1386         char *secret = NULL;
1387         char *hname;
1388         char requeststr[256] = "";
1389         char myrdest [5] = "s";
1390         char context[AST_MAX_EXTENSION] ="";
1391         char *portno = NULL;
1392         struct chan_iax_pvt *p = c->pvt->pvt;
1393         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1394                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1395                 return -1;
1396         }
1397         strncpy(host, dest, sizeof(host)-1);
1398         strtok(host, "/");
1399         /* If no destination extension specified, use 's' */
1400         rdest = strtok(NULL, "/");
1401         if (!rdest) 
1402                 rdest = myrdest;
1403         strtok(rdest, "@");
1404         rcontext = strtok(NULL, "@");
1405         strtok(host, "@");
1406         username = strtok(NULL, "@");
1407         if (username) {
1408                 /* Really the second argument is the host, not the username */
1409                 hname = username;
1410                 username = host;
1411         } else {
1412                 hname = host;
1413         }
1414         if (username) {
1415                 username = strtok(username, ":");
1416                 secret = strtok(NULL, ":");
1417         }
1418         if (strtok(hname, ":")) {
1419                 strtok(hname, ":");
1420                 portno = strtok(hname, ":");
1421         }
1422         if (create_addr(&sin, NULL, NULL, hname, context)) {
1423                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1424                 return -1;
1425         }
1426         /* Keep track of the context for outgoing calls too */
1427         strncpy(c->context, context, sizeof(c->context) - 1);
1428         if (portno) {
1429                 sin.sin_port = htons(atoi(portno));
1430         }
1431         /* Now we build our request string */
1432 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr), 
1433 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr), 
1434         MYSNPRINTF "exten=%s;", rdest);
1435         if (c->callerid)
1436                 MYSNPRINTF "callerid=%s;", c->callerid);
1437         if (p->sendani && c->ani)
1438                 MYSNPRINTF "ani=%s;", c->ani);
1439         if (c->language && strlen(c->language))
1440                 MYSNPRINTF "language=%s;", c->language);
1441         if (c->dnid)
1442                 MYSNPRINTF "dnid=%s;", c->dnid);
1443         if (rcontext)
1444                 MYSNPRINTF "context=%s;", rcontext);
1445         if (username)
1446                 MYSNPRINTF "username=%s;", username);
1447         if (secret) {
1448                 if (secret[0] == '[') {
1449                         /* This is an RSA key, not a normal secret */
1450                         strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1451                         if (strlen(p->outkey)) {
1452                                 p->outkey[strlen(p->outkey) - 1] = '\0';
1453                         }
1454                 } else
1455                         strncpy(p->secret, secret, sizeof(p->secret)-1);
1456         }
1457         MYSNPRINTF "formats=%d;", c->nativeformats);
1458         MYSNPRINTF "capability=%d;", p->capability);
1459         MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1460         MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1461         /* Trim the trailing ";" */
1462         if (strlen(requeststr))
1463                 requeststr[strlen(requeststr) - 1] = '\0';
1464         /* Transmit the string in a "NEW" request */
1465         if (option_verbose > 2)
1466                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1467         send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_IAX,
1468                 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1469         ast_setstate(c, AST_STATE_RINGING);
1470         return 0;
1471 }
1472
1473 static int iax_predestroy(struct chan_iax_pvt *pvt)
1474 {
1475         struct ast_channel *c;
1476         if (!pvt->alreadygone) {
1477                 /* No more pings or lagrq's */
1478                 if (pvt->pingid > -1)
1479                         ast_sched_del(sched, pvt->pingid);
1480                 if (pvt->lagid > -1)
1481                         ast_sched_del(sched, pvt->lagid);
1482                 if (pvt->autoid > -1)
1483                         ast_sched_del(sched, pvt->autoid);
1484                 pvt->pingid = -1;
1485                 pvt->lagid = -1;
1486                 pvt->autoid = -1;
1487                 pvt->alreadygone = 1;
1488         }
1489         c = pvt->owner;
1490         if (c) {
1491                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1492                 c->pvt->pvt = NULL;
1493                 pvt->owner = NULL;
1494                 ast_pthread_mutex_lock(&usecnt_lock);
1495                 usecnt--;
1496                 if (usecnt < 0) 
1497                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1498                 ast_pthread_mutex_unlock(&usecnt_lock);
1499                 ast_update_use_count();
1500         }
1501         return 0;
1502 }
1503
1504 static int iax_hangup(struct ast_channel *c) 
1505 {
1506         struct chan_iax_pvt *pvt = c->pvt->pvt;
1507         int alreadygone;
1508         if (pvt) {
1509                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1510                 alreadygone = pvt->alreadygone;
1511                 /* Send the hangup unless we have had a transmission error or are already gone */
1512                 if (!pvt->error && !alreadygone) 
1513                         send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1514                 /* Explicitly predestroy it */
1515                 iax_predestroy(pvt);
1516                 /* If we were already gone to begin with, destroy us now */
1517                 if (alreadygone) {
1518                         iax_destroy(pvt->callno);
1519                 }
1520         }
1521         if (option_verbose > 2) 
1522                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1523         return 0;
1524 }
1525
1526 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1527 {
1528         struct ast_option_header *h;
1529         int res;
1530         h = malloc(datalen + sizeof(struct ast_option_header));
1531         if (h) {
1532                 h->flag = AST_OPTION_FLAG_REQUEST;
1533                 h->option = htons(option);
1534                 memcpy(h->data, data, datalen);
1535                 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1536                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1537                 free(h);
1538                 return res;
1539         } else 
1540                 ast_log(LOG_WARNING, "Out of memory\n");
1541         return -1;
1542 }
1543 static struct ast_frame *iax_read(struct ast_channel *c) 
1544 {
1545         static struct ast_frame f = { AST_FRAME_NULL, };
1546         ast_log(LOG_NOTICE, "I should never be called!\n");
1547         return &f;
1548 }
1549
1550 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1551 {
1552         int res;
1553         char req0[256];
1554         char req1[256];
1555         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1556         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1557         snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1558         snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1559         res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1560         if (res)
1561                 return -1;
1562         res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1563         if (res)
1564                 return -1;
1565         p0->transferring = TRANSFER_BEGIN;
1566         p1->transferring = TRANSFER_BEGIN;
1567         return 0;
1568 }
1569
1570 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1571 {
1572         struct ast_channel *cs[3];
1573         struct ast_channel *who;
1574         int to = -1;
1575         int res;
1576         int transferstarted=0;
1577         struct ast_frame *f;
1578         struct chan_iax_pvt *p0 = c0->pvt->pvt;
1579         struct chan_iax_pvt *p1 = c1->pvt->pvt;
1580
1581         /* Put them in native bridge mode */
1582         p0->bridgecallno = p1->callno;
1583         p1->bridgecallno = p0->callno;
1584
1585         /* If not, try to bridge until we can execute a transfer, if we can */
1586         cs[0] = c0;
1587         cs[1] = c1;
1588         for (/* ever */;;) {
1589                 /* Check in case we got masqueraded into */
1590                 if ((c0->type != type) || (c1->type != type)) {
1591                         if (option_verbose > 2)
1592                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1593                         return -2;
1594                 }
1595                 if (!transferstarted) {
1596                         /* Try the transfer */
1597                         if (iax_start_transfer(c0, c1))
1598                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1599                         transferstarted = 1;
1600                 }
1601                 
1602                 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1603                         /* Call has been transferred.  We're no longer involved */
1604                         sleep(1);
1605                         c0->_softhangup |= AST_SOFTHANGUP_DEV;
1606                         c1->_softhangup |= AST_SOFTHANGUP_DEV;
1607                         *fo = NULL;
1608                         *rc = c0;
1609                         res = 0;
1610                         break;
1611                 }
1612                 to = 1000;
1613                 who = ast_waitfor_n(cs, 2, &to);
1614                 if (!who) {
1615                         continue;
1616                 }
1617                 f = ast_read(who);
1618                 if (!f) {
1619                         *fo = NULL;
1620                         *rc = who;
1621                         res = 0;
1622                         break;
1623                 }
1624                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1625                         *fo = f;
1626                         *rc = who;
1627                         res =  0;
1628                         break;
1629                 }
1630                 if ((f->frametype == AST_FRAME_VOICE) ||
1631                         (f->frametype == AST_FRAME_TEXT) ||
1632                         (f->frametype == AST_FRAME_VIDEO) || 
1633                         (f->frametype == AST_FRAME_IMAGE) ||
1634                         (f->frametype == AST_FRAME_DTMF)) {
1635                         if ((f->frametype == AST_FRAME_DTMF) && 
1636                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1637                                 if ((who == c0)) {
1638                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1639                                                 *rc = c0;
1640                                                 *fo = f;
1641                                                 /* Take out of conference mode */
1642                                                 res = 0;
1643                                                 break;
1644                                         } else 
1645                                                 goto tackygoto;
1646                                 } else
1647                                 if ((who == c1)) {
1648                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1649                                                 *rc = c1;
1650                                                 *fo = f;
1651                                                 res =  0;
1652                                                 break;
1653                                         } else
1654                                                 goto tackygoto;
1655                                 }
1656                         } else {
1657 #if 0
1658                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1659                                 if (who == last) 
1660                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1661                                 last = who;
1662 #endif
1663 tackygoto:
1664                                 if (who == c0) 
1665                                         ast_write(c1, f);
1666                                 else 
1667                                         ast_write(c0, f);
1668                         }
1669                         ast_frfree(f);
1670                 } else
1671                         ast_frfree(f);
1672                 /* Swap who gets priority */
1673                 cs[2] = cs[0];
1674                 cs[0] = cs[1];
1675                 cs[1] = cs[2];
1676         }
1677         p0->bridgecallno = -1;
1678         p1->bridgecallno = -1;
1679         return res;
1680 }
1681
1682 static int iax_answer(struct ast_channel *c)
1683 {
1684         struct chan_iax_pvt *pvt = c->pvt->pvt;
1685         if (option_debug)
1686                 ast_log(LOG_DEBUG, "Answering\n");
1687         return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1688 }
1689
1690 static int iax_indicate(struct ast_channel *c, int condition)
1691 {
1692         struct chan_iax_pvt *pvt = c->pvt->pvt;
1693         if (option_debug)
1694                 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
1695         return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
1696 }
1697         
1698
1699 static int iax_write(struct ast_channel *c, struct ast_frame *f);
1700
1701 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
1702 {
1703         struct iax_peer *peer;
1704         int res = 0;
1705         ast_pthread_mutex_lock(&peerl.lock);
1706         peer = peerl.peers;
1707         while(peer) {
1708                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1709                                 (peer->addr.sin_port == sin.sin_port)) {
1710                                         strncpy(host, peer->name, len-1);
1711                                         res = 1;
1712                                         break;
1713                 }
1714                 peer = peer->next;
1715         }
1716         ast_pthread_mutex_unlock(&peerl.lock);
1717         return res;
1718 }
1719
1720 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
1721 {
1722         char host[256];
1723         struct ast_channel *tmp;
1724         tmp = ast_channel_alloc(1);
1725         if (tmp) {
1726                 if (!iax_getpeername(i->addr, host, sizeof(host)))
1727                         snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
1728                 if (strlen(i->username))
1729                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
1730                 else
1731                         snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
1732                 tmp->type = type;
1733                 /* We can support any format by default, until we get restricted */
1734                 tmp->nativeformats = capability;
1735                 tmp->readformat = 0;
1736                 tmp->writeformat = 0;
1737                 tmp->pvt->pvt = i;
1738                 tmp->pvt->send_digit = iax_digit;
1739                 tmp->pvt->send_text = iax_sendtext;
1740                 tmp->pvt->send_image = iax_sendimage;
1741                 tmp->pvt->send_html = iax_sendhtml;
1742                 tmp->pvt->call = iax_call;
1743                 tmp->pvt->hangup = iax_hangup;
1744                 tmp->pvt->answer = iax_answer;
1745                 tmp->pvt->read = iax_read;
1746                 tmp->pvt->write = iax_write;
1747                 tmp->pvt->indicate = iax_indicate;
1748                 tmp->pvt->setoption = iax_setoption;
1749                 tmp->pvt->bridge = iax_bridge;
1750                 if (strlen(i->callerid))
1751                         tmp->callerid = strdup(i->callerid);
1752                 if (strlen(i->ani))
1753                         tmp->ani = strdup(i->ani);
1754                 if (strlen(i->language))
1755                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1756                 if (strlen(i->dnid))
1757                         tmp->dnid = strdup(i->dnid);
1758                 if (strlen(i->accountcode))
1759                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1760                 if (i->amaflags)
1761                         tmp->amaflags = i->amaflags;
1762                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1763                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1764                 tmp->adsicpe = i->peeradsicpe;
1765                 tmp->pvt->fixup = iax_fixup;
1766                 i->owner = tmp;
1767                 i->capability = capability;
1768                 ast_setstate(tmp, state);
1769                 ast_pthread_mutex_lock(&usecnt_lock);
1770                 usecnt++;
1771                 ast_pthread_mutex_unlock(&usecnt_lock);
1772                 ast_update_use_count();
1773                 if (state != AST_STATE_DOWN) {
1774                         if (ast_pbx_start(tmp)) {
1775                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1776                                 ast_hangup(tmp);
1777                                 tmp = NULL;
1778                         }
1779                 }
1780         }
1781         return tmp;
1782 }
1783
1784 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
1785 {
1786         struct timeval tv;
1787         unsigned int ms;
1788         if (!p->offset.tv_sec && !p->offset.tv_usec)
1789                 gettimeofday(&p->offset, NULL);
1790         /* If the timestamp is specified, just send it as is */
1791         if (ts)
1792                 return ts;
1793         gettimeofday(&tv, NULL);
1794         ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
1795         /* We never send the same timestamp twice, so fudge a little if we must */
1796         if (ms <= p->lastsent)
1797                 ms = p->lastsent + 1;
1798         p->lastsent = ms;
1799         return ms;
1800 }
1801
1802 #ifdef BRIDGE_OPTIMIZATION
1803 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
1804 {
1805         int ms;
1806         /* Receive from p1, send to p2 */
1807         
1808         /* Setup rxcore if necessary on outgoing channel */
1809         if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
1810                 gettimeofday(&p1->rxcore, NULL);
1811
1812         /* Setup txcore if necessary on outgoing channel */
1813         if (!p2->offset.tv_sec && !p2->offset.tv_usec)
1814                 gettimeofday(&p2->offset, NULL);
1815         
1816         /* Now, ts is the timestamp of the original packet in the orignal context.
1817            Adding rxcore to it gives us when we would want the packet to be delivered normally.
1818            Subtracting txcore of the outgoing channel gives us what we'd expect */
1819         
1820         ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
1821         fakets += ms;
1822         if (fakets <= p2->lastsent)
1823                 fakets = p2->lastsent + 1;
1824         p2->lastsent = fakets;
1825         return fakets;
1826 }
1827 #endif
1828
1829 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
1830 {
1831         /* Returns where in "receive time" we are */
1832         struct timeval tv;
1833         unsigned int ms;
1834         /* Setup rxcore if necessary */
1835         if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
1836                 gettimeofday(&p->rxcore, NULL);
1837
1838         gettimeofday(&tv, NULL);
1839         ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
1840         return ms;
1841 }
1842
1843 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
1844 {
1845         /* Queue a packet for delivery on a given private structure.  Use "ts" for
1846            timestamp, or calculate if ts is 0.  Send immediately without retransmission
1847            or delayed, with retransmission */
1848         struct ast_iax_full_hdr *fh;
1849         struct ast_iax_mini_hdr *mh;
1850         struct ast_iax_frame *fr, fr2;
1851         int res;
1852         unsigned int lastsent;
1853         /* Allocate an ast_iax_frame */
1854         if (now)
1855                 fr = &fr2;
1856         else
1857                 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
1858         if (!fr) {
1859                 ast_log(LOG_WARNING, "Out of memory\n");
1860                 return -1;
1861         }
1862         if (!pvt) {
1863                 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
1864                 if (!now)
1865                         ast_iax_frame_free(fr);
1866                 return -1;
1867         }
1868         /* Isolate our frame for transmission */
1869         fr->f = ast_frdup(f);
1870
1871         if (!fr->f) {
1872                 ast_log(LOG_WARNING, "Out of memory\n");
1873                 if (!now)
1874                         ast_iax_frame_free(fr);
1875                 return -1;
1876         }
1877         if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
1878                 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
1879                 free(fr);
1880                 return -1;
1881         }
1882         lastsent = pvt->lastsent;
1883         fr->ts = calc_timestamp(pvt, ts);
1884         if (!fr->ts) {
1885                 ast_log(LOG_WARNING, "timestamp is 0?\n");
1886                 if (!now)
1887                         ast_iax_frame_free(fr);
1888                 return -1;
1889         }
1890         fr->callno = pvt->callno;
1891         fr->transfer = transfer;
1892         fr->final = final;
1893         if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
1894                 /* High two bits of timestamp differ */ ||
1895             (fr->f->frametype != AST_FRAME_VOICE) 
1896                 /* or not a voice frame */ || 
1897                 (fr->f->subclass != pvt->svoiceformat) 
1898                 /* or new voice format */ ) {
1899                 /* We need a full frame */
1900                 if (seqno > -1)
1901                         fr->seqno = seqno;
1902                 else
1903                         fr->seqno = pvt->oseqno++;
1904                 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
1905                 fh->callno = htons(fr->callno | AST_FLAG_FULL);
1906                 fh->ts = htonl(fr->ts);
1907                 fh->seqno = htons(fr->seqno);
1908                 fh->type = fr->f->frametype & 0xFF;
1909                 fh->csub = compress_subclass(fr->f->subclass);
1910                 if (transfer) {
1911                         fh->dcallno = htons(pvt->transfercallno);
1912                 } else
1913                         fh->dcallno = htons(pvt->peercallno);
1914                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
1915                 fr->data = fh;
1916                 fr->retries = 0;
1917                 /* Retry after 2x the ping time has passed */
1918                 fr->retrytime = pvt->pingtime * 2;
1919                 if (fr->retrytime < MIN_RETRY_TIME)
1920                         fr->retrytime = MIN_RETRY_TIME;
1921                 if (fr->retrytime > MAX_RETRY_TIME)
1922                         fr->retrytime = MAX_RETRY_TIME;
1923                 /* Acks' don't get retried */
1924                 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
1925                         fr->retries = -1;
1926                 if (f->frametype == AST_FRAME_VOICE) {
1927                         pvt->svoiceformat = f->subclass;
1928                 }
1929                 if (now) {
1930                         res = send_packet(fr);
1931                         ast_frfree(fr->f);
1932                 } else
1933                         res = iax_transmit(fr);
1934         } else {
1935                 /* Mini-frames have no sequence number */
1936                 fr->seqno = -1;
1937                 /* Mini frame will do */
1938                 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
1939                 mh->callno = htons(fr->callno);
1940                 mh->ts = htons(fr->ts & 0xFFFF);
1941                 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
1942                 fr->data = mh;
1943                 fr->retries = -1;
1944                 if (now) {
1945                         res = send_packet(fr);
1946                         ast_frfree(fr->f);
1947                 } else
1948                         res = iax_transmit(fr);
1949         }
1950         return res;
1951 }
1952
1953
1954
1955 static int iax_show_users(int fd, int argc, char *argv[])
1956 {
1957 #define FORMAT "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-5.5s\n"
1958         struct iax_user *user;
1959         if (argc != 3) 
1960                 return RESULT_SHOWUSAGE;
1961         ast_pthread_mutex_lock(&userl.lock);
1962         ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
1963         for(user=userl.users;user;user=user->next) {
1964                 ast_cli(fd, FORMAT, user->name, user->secret, user->methods, 
1965                                 user->contexts ? user->contexts->context : context,
1966                                 user->ha ? "Yes" : "No");
1967         }
1968         ast_pthread_mutex_unlock(&userl.lock);
1969         return RESULT_SUCCESS;
1970 #undef FORMAT
1971 }
1972
1973 static int iax_show_peers(int fd, int argc, char *argv[])
1974 {
1975 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s %s  %-15.15s  %s\n"
1976 #define FORMAT "%-15.15s  %-15.15s  %-15.15s %s  %-15.15s  %d\n"
1977         struct iax_peer *peer;
1978         if (argc != 3)
1979                 return RESULT_SHOWUSAGE;
1980         ast_pthread_mutex_lock(&peerl.lock);
1981         ast_cli(fd, FORMAT2, "Name", "Username", "Host", "   ", "Mask", "Port");
1982         for (peer = peerl.peers;peer;peer = peer->next) {
1983                 char nm[20];
1984                 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
1985                 ast_cli(fd, FORMAT, peer->name, 
1986                                         peer->username ? peer->username : "(Any)",
1987                                         peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
1988                                         peer->dynamic ? "(D)" : "   ",
1989                                         nm,
1990                                         ntohs(peer->addr.sin_port));
1991         }
1992         ast_pthread_mutex_unlock(&peerl.lock);
1993         return RESULT_SUCCESS;
1994 #undef FORMAT
1995 #undef FORMAT2
1996 }
1997
1998 static char *regstate2str(int regstate)
1999 {
2000         switch(regstate) {
2001         case REG_STATE_UNREGISTERED:
2002                 return "Unregistered";
2003         case REG_STATE_REGSENT:
2004                 return "Request Sent";
2005         case REG_STATE_AUTHSENT:
2006                 return "Auth. Sent";
2007         case REG_STATE_REGISTERED:
2008                 return "Registered";
2009         case REG_STATE_REJECTED:
2010                 return "Rejected";
2011         case REG_STATE_TIMEOUT:
2012                 return "Timeout";
2013         case REG_STATE_NOAUTH:
2014                 return "No Authentication";
2015         default:
2016                 return "Unknown";
2017         }
2018 }
2019
2020 static int iax_show_registry(int fd, int argc, char *argv[])
2021 {
2022 #define FORMAT2 "%-20.20s  %-10.10s  %-20.20s %8.8s  %s\n"
2023 #define FORMAT "%-20.20s  %-10.10s  %-20.20s %8d  %s\n"
2024         struct iax_registry *reg;
2025         char host[80];
2026         char perceived[80];
2027         if (argc != 3)
2028                 return RESULT_SHOWUSAGE;
2029         ast_pthread_mutex_lock(&peerl.lock);
2030         ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2031         for (reg = registrations;reg;reg = reg->next) {
2032                 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2033                 if (reg->us.sin_addr.s_addr) 
2034                         snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2035                 else
2036                         strcpy(perceived, "<Unregistered>");
2037                 ast_cli(fd, FORMAT, host, 
2038                                         reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2039         }
2040         ast_pthread_mutex_unlock(&peerl.lock);
2041         return RESULT_SUCCESS;
2042 #undef FORMAT
2043 #undef FORMAT2
2044 }
2045
2046 static int iax_show_channels(int fd, int argc, char *argv[])
2047 {
2048 #define FORMAT2 "%-15.15s  %-10.10s  %-11.11s  %-11.11s  %-7.7s  %-6.6s  %s\n"
2049 #define FORMAT  "%-15.15s  %-10.10s  %5.5d/%5.5d  %5.5d/%5.5d  %-5.5dms  %-4.4dms  %d\n"
2050         int x;
2051         if (argc != 3)
2052                 return RESULT_SHOWUSAGE;
2053         ast_pthread_mutex_lock(&iaxs_lock);
2054         ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2055         for (x=0;x<AST_IAX_MAX_CALLS;x++)
2056                 if (iaxs[x]) 
2057                         ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr), 
2058                                                 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)", 
2059                                                 iaxs[x]->callno, iaxs[x]->peercallno, 
2060                                                 iaxs[x]->oseqno, iaxs[x]->iseqno, 
2061                                                 iaxs[x]->lag,
2062                                                 iaxs[x]->jitter,
2063                                                 iaxs[x]->voiceformat);
2064         ast_pthread_mutex_unlock(&iaxs_lock);
2065         return RESULT_SUCCESS;
2066 #undef FORMAT
2067 #undef FORMAT2
2068 }
2069
2070 static int iax_do_debug(int fd, int argc, char *argv[])
2071 {
2072         if (argc != 2)
2073                 return RESULT_SHOWUSAGE;
2074         iaxdebug = 1;
2075         ast_cli(fd, "IAX Debugging Enabled\n");
2076         return RESULT_SUCCESS;
2077 }
2078
2079 static int iax_no_debug(int fd, int argc, char *argv[])
2080 {
2081         if (argc != 3)
2082                 return RESULT_SHOWUSAGE;
2083         iaxdebug = 0;
2084         ast_cli(fd, "IAX Debugging Disabled\n");
2085         return RESULT_SUCCESS;
2086 }
2087
2088
2089
2090 static char show_users_usage[] = 
2091 "Usage: iax show users\n"
2092 "       Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2093
2094 static char show_channels_usage[] = 
2095 "Usage: iax show channels\n"
2096 "       Lists all currently active IAX channels.\n";
2097
2098 static char show_peers_usage[] = 
2099 "Usage: iax show peers\n"
2100 "       Lists all known IAX peers.\n";
2101
2102 static char show_reg_usage[] =
2103 "Usage: iax show registry\n"
2104 "       Lists all registration requests and status.\n";
2105
2106 #ifdef DEBUG_SUPPORT
2107
2108 static char debug_usage[] = 
2109 "Usage: iax debug\n"
2110 "       Enables dumping of IAX packets for debugging purposes\n";
2111
2112 static char no_debug_usage[] = 
2113 "Usage: iax no debug\n"
2114 "       Disables dumping of IAX packets for debugging purposes\n";
2115
2116 #endif
2117
2118 static struct ast_cli_entry  cli_show_users = 
2119         { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2120 static struct ast_cli_entry  cli_show_channels =
2121         { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2122 static struct ast_cli_entry  cli_show_peers =
2123         { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2124 static struct ast_cli_entry  cli_show_registry =
2125         { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2126 static struct ast_cli_entry  cli_debug =
2127         { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2128 static struct ast_cli_entry  cli_no_debug =
2129         { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2130
2131 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2132 {
2133         struct chan_iax_pvt *i = c->pvt->pvt;
2134         if (!i)
2135                 return -1;
2136         /* If there's an outstanding error, return failure now */
2137         if (i->error) {
2138                 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2139                 return -1;
2140         }
2141         /* If it's already gone, just return */
2142         if (i->alreadygone)
2143                 return 0;
2144         /* Don't waste bandwidth sending null frames */
2145         if (f->frametype == AST_FRAME_NULL)
2146                 return 0;
2147         /* If we're quelching voice, don't bother sending it */
2148         if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2149                 return 0;
2150         /* Simple, just queue for transmission */
2151         return iax_send(i, f, 0, -1, 0, 0, 0);
2152 }
2153
2154 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno, 
2155                 int now, int transfer, int final)
2156 {
2157         struct ast_frame f;
2158         f.frametype = type;
2159         f.subclass = command;
2160         f.datalen = datalen;
2161         f.timelen = 0;
2162         f.mallocd = 0;
2163         f.offset = 0;
2164         f.src = __FUNCTION__;
2165         f.data = data;
2166         return iax_send(i, &f, ts, seqno, now, transfer, final);
2167 }
2168
2169 static int send_command(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, 0, 0, 0);
2172 }
2173
2174 #ifdef BRIDGE_OPTIMIZATION
2175 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2176 {
2177         return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2178 }
2179 #endif
2180
2181 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2182 {
2183         iax_predestroy(i);
2184         return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2185 }
2186
2187 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2188 {
2189         return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2190 }
2191
2192 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2193 {
2194         return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2195 }
2196
2197 static int apply_context(struct iax_context *con, char *context)
2198 {
2199         while(con) {
2200                 if (!strcmp(con->context, context))
2201                         return -1;
2202                 con = con->next;
2203         }
2204         return 0;
2205 }
2206
2207 static int iax_getformats(int callno, char *orequest)
2208 {
2209         char *var, *value;
2210         char request[256];
2211         strncpy(request, orequest, sizeof(request)-1);
2212         var = strtok(request, ";");
2213         while(var) {
2214                 value = strchr(var, '=');
2215                 if (value) {
2216                         *value='\0';
2217                         value++;
2218                         if (!strcmp(var, "formats")) {
2219                                 iaxs[callno]->peerformat = atoi(value);
2220                         } else 
2221                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2222                 }
2223                 var = strtok(NULL, ";");
2224         }
2225         return 0;
2226 }
2227
2228
2229 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2230 {
2231         /* Start pessimistic */
2232         int res = -1;
2233         int version = 1;
2234         char *var, *value;
2235         struct iax_user *user;
2236         char request[256];
2237         int gotcapability=0;
2238         strncpy(request, orequest, sizeof(request)-1);
2239         if (!iaxs[callno])
2240                 return res;
2241         var = strtok(request, ";");
2242         while(var) {
2243                 value = strchr(var, '=');
2244                 if (value) { 
2245                         *value='\0';
2246                         value++;
2247                         if (!strcmp(var, "exten")) 
2248                                 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2249                         else if (!strcmp(var, "callerid"))
2250                                 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2251                         else if (!strcmp(var, "ani"))
2252                                 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2253                         else if (!strcmp(var, "dnid"))
2254                                 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2255                         else if (!strcmp(var, "context"))
2256                                 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2257                         else if (!strcmp(var, "language"))
2258                                 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2259                         else if (!strcmp(var, "username"))
2260                                 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2261                         else if (!strcmp(var, "formats")) 
2262                                 iaxs[callno]->peerformat = atoi(value);
2263                         else if (!strcmp(var, "adsicpe"))
2264                                 iaxs[callno]->peeradsicpe = atoi(value);
2265                         else if (!strcmp(var, "capability")) {
2266                                 gotcapability = 1;
2267                                 iaxs[callno]->peercapability = atoi(value);
2268                         } else if (!strcmp(var, "version"))
2269                                 version = atoi(value);
2270                         else 
2271                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2272                 }
2273                 var = strtok(NULL, ";");
2274         }
2275         if (!gotcapability) 
2276                 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2277         if (version > AST_IAX_PROTO_VERSION) {
2278                 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n", 
2279                         inet_ntoa(sin->sin_addr), version);
2280                 return res;
2281         }
2282         ast_pthread_mutex_lock(&userl.lock);
2283         /* Search the userlist for a compatible entry, and fill in the rest */
2284         user = userl.users;
2285         while(user) {
2286                 if ((!strlen(iaxs[callno]->username) ||                         /* No username specified */
2287                         !strcmp(iaxs[callno]->username, user->name))    /* Or this username specified */
2288                         && ast_apply_ha(user->ha, sin)  /* Access is permitted from this IP */
2289                         && (!strlen(iaxs[callno]->context) ||                   /* No context specified */
2290                              apply_context(user->contexts, iaxs[callno]->context))) {                   /* Context is permitted */
2291                         /* We found our match (use the first) */
2292                         
2293                         /* Store the requested username if not specified */
2294                         if (!strlen(iaxs[callno]->username))
2295                                 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2296                         /* And use the default context */
2297                         if (!strlen(iaxs[callno]->context)) {
2298                                 if (user->contexts)
2299                                         strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2300                                 else
2301                                         strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2302                         }
2303                         /* Copy the secret */
2304                         strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2305                         /* And any input keys */
2306                         strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2307                         /* And the permitted authentication methods */
2308                         strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2309                         /* If they have callerid, override the given caller id.  Always store the ANI */
2310                         if (strlen(iaxs[callno]->callerid)) {
2311                                 if (user->hascallerid)
2312                                         strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2313                                 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2314                         }
2315                         if (strlen(user->accountcode))
2316                                 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2317                         if (user->amaflags)
2318                                 iaxs[callno]->amaflags = user->amaflags;
2319                         res = 0;
2320                         break;
2321                 }
2322                 user = user->next;      
2323         }
2324         ast_pthread_mutex_unlock(&userl.lock);
2325         return res;
2326 }
2327
2328 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2329 {
2330         struct ast_iax_full_hdr fh;
2331         fh.callno = htons(src | AST_FLAG_FULL);
2332         fh.dcallno = htons(dst);
2333         fh.ts = 0;
2334         fh.seqno = 0;
2335         fh.type = AST_FRAME_IAX;
2336         fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2337 #if 0
2338         if (option_debug)
2339 #endif  
2340                 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2341                         inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2342         return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2343 }
2344
2345 static int authenticate_request(struct chan_iax_pvt *p)
2346 {
2347         char requeststr[256] = "";
2348         MYSNPRINTF "methods=%s;", p->methods);
2349         if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2350                 /* Build the challenge */
2351                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2352                 MYSNPRINTF "challenge=%s;", p->challenge);
2353         }
2354         MYSNPRINTF "username=%s;", p->username);
2355         if (strlen(requeststr))
2356                 requeststr[strlen(requeststr) - 1] = '\0';
2357         return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2358 }
2359
2360 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2361 {
2362         char requeststr[256] = "";
2363         char *var, *value, request[256];
2364         char md5secret[256] = "";
2365         char secret[256] = "";
2366         char rsasecret[256] = "";
2367         int res = -1; 
2368         int x;
2369         
2370         if (!(p->state & IAX_STATE_AUTHENTICATED))
2371                 return res;
2372         strncpy(request, orequest, sizeof(request)-1);
2373         var = strtok(request, ";");
2374         while(var) {
2375                 value = strchr(var, '=');
2376                 if (value) { 
2377                         *value='\0';
2378                         value++;
2379                         if (!strcmp(var, "secret")) 
2380                                 strncpy(secret, value, sizeof(secret)-1);
2381                         else if (!strcmp(var, "md5secret"))
2382                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2383                         else if (!strcmp(var, "rsasecret"))
2384                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2385                         else
2386                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2387                 }
2388                 var = strtok(NULL, ";");
2389         }
2390         if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2391                 struct ast_key *key;
2392                 char *keyn;
2393                 char tmpkey[256];
2394                 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2395                 keyn = strtok(tmpkey, ":");
2396                 while(keyn) {
2397                         key = ast_key_get(keyn, AST_KEY_PUBLIC);
2398                         if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2399                                 res = 0;
2400                                 break;
2401                         } else if (!key)
2402                                 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2403                         keyn = strtok(NULL, ":");
2404                 }
2405         } else if (strstr(p->methods, "md5")) {
2406                 struct MD5Context md5;
2407                 unsigned char digest[16];
2408                 MD5Init(&md5);
2409                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2410                 MD5Update(&md5, p->secret, strlen(p->secret));
2411                 MD5Final(digest, &md5);
2412                 /* If they support md5, authenticate with it.  */
2413                 for (x=0;x<16;x++)
2414                         MYSNPRINTF "%2.2x", digest[x]);
2415                 if (!strcasecmp(requeststr, md5secret))
2416                         res = 0;
2417         } else if (strstr(p->methods, "plaintext")) {
2418                 if (!strcmp(secret, p->secret))
2419                         res = 0;
2420         }
2421         return res;
2422 }
2423
2424 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2425 {
2426         char request[256];
2427         char requeststr[256] = "";
2428         char peer[256] = "";
2429         char md5secret[256] = "";
2430         char rsasecret[256] = "";
2431         char secret[256] = "";
2432         struct iax_peer *p;
2433         struct ast_key *key;
2434         char *var;
2435         char *value;
2436         char *keyn;
2437         int x;
2438         int expire = 0;
2439
2440         iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2441         strcpy(iaxs[callno]->peer, "");
2442         if (!orequest)
2443                 return -1;
2444         strncpy(request, orequest, sizeof(request)-1);
2445         var = strtok(request, ";");
2446         while(var) {
2447                 value = strchr(var, '=');
2448                 if (value) { 
2449                         *value='\0';
2450                         value++;
2451                         if (!strcmp(var, "peer")) 
2452                                 strncpy(peer, value, sizeof(peer)-1);
2453                         else if (!strcmp(var, "md5secret"))
2454                                 strncpy(md5secret, value, sizeof(md5secret)-1);
2455                         else if (!strcmp(var, "rsasecret"))
2456                                 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2457                         else if (!strcmp(var, "secret"))
2458                                 strncpy(secret, value, sizeof(secret)-1);
2459                         else if (!strcmp(var, "refresh"))
2460                                 expire = atoi(value);
2461                         else 
2462                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2463                 }
2464                 var = strtok(NULL, ";");
2465         }
2466
2467         if (!strlen(peer)) {
2468                 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2469                 return -1;
2470         }
2471
2472         for (p = peerl.peers; p ; p = p->next) 
2473                 if (!strcasecmp(p->name, peer))
2474                         break;
2475
2476         if (!p) {
2477                 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2478                 return -1;
2479         }
2480
2481         if (!p->dynamic) {
2482                 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2483                 return -1;
2484         }
2485
2486         if (!ast_apply_ha(p->ha, sin)) {
2487                 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2488                 return -1;
2489         }
2490         strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2491         strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2492         /* Check secret against what we have on file */
2493         if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(p->challenge)) {
2494                 if (strlen(p->inkeys)) {
2495                         char tmpkeys[256];
2496                         strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2497                         keyn = strtok(tmpkeys, ":");
2498                         while(keyn) {
2499                                 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2500                                 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2501                                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2502                                         break;
2503                                 } else if (!key) 
2504                                         ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2505                                 keyn = strtok(NULL, ":");
2506                         }
2507                         if (!keyn) {
2508                                 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2509                                 return -1;
2510                         }
2511                 } else {
2512                         ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2513                         return -1;
2514                 }
2515         } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2516                 /* They've provided a plain text password and we support that */
2517                 if (strcmp(secret, p->secret)) {
2518                         ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2519                         return -1;
2520                 } else
2521                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2522         } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(p->challenge)) {
2523                 struct MD5Context md5;
2524                 unsigned char digest[16];
2525                 MD5Init(&md5);
2526                 MD5Update(&md5, p->challenge, strlen(p->challenge));
2527                 MD5Update(&md5, p->secret, strlen(p->secret));
2528                 MD5Final(digest, &md5);
2529                 for (x=0;x<16;x++)
2530                         MYSNPRINTF "%2.2x", digest[x]);
2531                 if (strcasecmp(requeststr, md5secret)) {
2532                         ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2533                         return -1;
2534                 } else
2535                         iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2536         } else if (strlen(md5secret) || strlen(secret)) {
2537                 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2538                 return -1;
2539         }
2540         strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2541         /* Choose lowest expirey number */
2542         if (expire && (expire < iaxs[callno]->expirey)) 
2543                 iaxs[callno]->expirey = expire;
2544         return 0;
2545         
2546 }
2547
2548 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2549 {
2550         int res = -1;
2551         int x;
2552         if (keyn && strlen(keyn)) {
2553                 if (!strstr(methods, "rsa")) {
2554                         if (!secret || !strlen(secret)) 
2555                                 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));
2556                 } else if (!strlen(challenge)) {
2557                         ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2558                 } else {
2559                         char sig[256];
2560                         struct ast_key *key;
2561                         key = ast_key_get(keyn, AST_KEY_PRIVATE);
2562                         if (!key) {
2563                                 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2564                         } else {
2565                                 if (ast_sign(key, challenge, sig)) {
2566                                         ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2567                                         res = -1;
2568                                 } else {
2569                                         MYSNPRINTF2 "rsasecret=%s;", sig);
2570                                         res = 0;
2571                                 }
2572                         }
2573                 }
2574         } 
2575         /* Fall back */
2576         if (res && secret && strlen(secret)) {
2577                 if (strstr(methods, "md5") && strlen(challenge)) {
2578                         struct MD5Context md5;
2579                         unsigned char digest[16];
2580                         MD5Init(&md5);
2581                         MD5Update(&md5, challenge, strlen(challenge));
2582                         MD5Update(&md5, secret, strlen(secret));
2583                         MD5Final(digest, &md5);
2584                         /* If they support md5, authenticate with it.  */
2585                         MYSNPRINTF2 "md5secret=");
2586                         for (x=0;x<16;x++)
2587                                 MYSNPRINTF2 "%2.2x", digest[x]);
2588                         MYSNPRINTF2 ";");
2589                         res = 0;
2590                 } else if (strstr(methods, "plaintext")) {
2591                         MYSNPRINTF2 "secret=%s;", secret);
2592                         res = 0;
2593                 } else
2594                         ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
2595         }
2596         return res;
2597 }
2598
2599 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
2600 {
2601         struct iax_peer *peer;
2602         /* Start pessimistic */
2603         int res = -1;
2604         char request[256];
2605         char methods[80] = "";
2606         char requeststr[256] = "";
2607         char *var, *value;
2608         
2609         strncpy(request, orequest, sizeof(request)-1);
2610         var = strtok(request, ";");
2611         while(var) {
2612                 value = strchr(var, '=');
2613                 if (value) { 
2614                         *value='\0';
2615                         value++;
2616                         if (!strcmp(var, "username")) 
2617                                 strncpy(p->username, value, sizeof(p->username)-1);
2618                         else if (!strcmp(var, "challenge"))
2619                                 strncpy(p->challenge, value, sizeof(p->challenge)-1);
2620                         else if (!strcmp(var, "methods"))
2621                                 strncpy(methods, value, sizeof(methods)-1);
2622                         else 
2623                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2624                 }
2625                 var = strtok(NULL, ";");
2626         }
2627
2628         /* Check for override RSA authentication first */
2629         if ((override && strlen(override)) || (okey && strlen(okey))) {
2630                 /* Normal password authentication */
2631                 res = authenticate(p->challenge, override, okey, methods, requeststr, sizeof(requeststr), sin);
2632         } else {
2633                 ast_pthread_mutex_lock(&peerl.lock);
2634                 peer = peerl.peers;
2635                 while(peer) {
2636                         if ((!strlen(p->peer) || !strcmp(p->peer, peer->name)) 
2637                                                                 /* No peer specified at our end, or this is the peer */
2638                          && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2639                                                                 /* No username specified in peer rule, or this is the right username */
2640                          && (!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)))
2641                                                                 /* No specified host, or this is our host */
2642                         ) {
2643                                 res = authenticate(p->challenge, peer->secret, peer->outkey, methods, requeststr, sizeof(requeststr), sin);
2644                                 if (!res)
2645                                         break;  
2646                         }
2647                         peer = peer->next;
2648                 }
2649                 ast_pthread_mutex_unlock(&peerl.lock);
2650         }
2651         if (strlen(requeststr))
2652                 requeststr[strlen(requeststr)-1] = '\0';
2653         if (!res)
2654                 res = send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREP, 0, requeststr, strlen(requeststr) + 1, -1);
2655         return res;
2656 }
2657
2658 static int iax_do_register(struct iax_registry *reg);
2659
2660 static int iax_do_register_s(void *data)
2661 {
2662         struct iax_registry *reg = data;
2663         reg->expire = -1;
2664         iax_do_register(reg);
2665         return 0;
2666 }
2667
2668 static int try_transfer(struct chan_iax_pvt *pvt, char *orequest)
2669 {
2670         int newport = 0;
2671         int newcall = 0;
2672         char newip[256] = "";
2673         char request[256] = "";
2674         char *var, *value;
2675         
2676         struct sockaddr_in new;
2677         
2678         if (!orequest)
2679                 return -1;
2680
2681         strncpy(request, orequest, sizeof(request)-1);
2682         var = strtok(request, ";");
2683         while(var) {
2684                 value = strchr(var, '=');
2685                 if (value) { 
2686                         *value='\0';
2687                         value++;
2688                         if (!strcmp(var, "remip")) 
2689                                 strncpy(newip, value, sizeof(newip)-1);
2690                         else if (!strcmp(var, "remport"))
2691                                 newport = atoi(value);
2692                         else if (!strcmp(var, "remcall"))
2693                                 newcall = atoi(value);
2694                         else 
2695                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2696                 }
2697                 var = strtok(NULL, ";");
2698         }
2699         if (!newcall || !inet_aton(newip, &new.sin_addr) || !newport) {
2700                 ast_log(LOG_WARNING, "Invalid transfer request\n");
2701                 return -1;
2702         }
2703         pvt->transfercallno = newcall;
2704         inet_aton(newip, &pvt->transfer.sin_addr);
2705         pvt->transfer.sin_port = htons(newport);
2706         pvt->transfer.sin_family = AF_INET;
2707         pvt->transferring = TRANSFER_BEGIN;
2708         send_command_transfer(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_TXCNT, 0, NULL, 0);
2709         return 0; 
2710 }
2711
2712 static int complete_dpreply(struct chan_iax_pvt *pvt, char *orequest)
2713 {
2714         char *var, *value;
2715         char request[256] = "";
2716         char exten[256] = "";
2717         int status = CACHE_FLAG_UNKNOWN;
2718         int expirey = iaxdefaultdpcache;
2719         int x;
2720         struct iax_dpcache *dp, *prev;
2721         
2722         strncpy(request, orequest, sizeof(request)-1);
2723         var = strtok(request, ";");
2724         while(var) {
2725                 value = strchr(var, '=');
2726                 if (value) { 
2727                         *value='\0';
2728                         value++;
2729                         if (!strcmp(var, "number"))
2730                                 strncpy(exten, value, sizeof(exten)-1);
2731                         else if (!strcmp(var, "status")) {
2732                                 if (!strcasecmp(value, "exists"))
2733                                         status = CACHE_FLAG_EXISTS;
2734                                 else if (!strcasecmp(value, "nonexistant"))
2735                                         status = CACHE_FLAG_NONEXISTANT;
2736                                 else if (!strcasecmp(value, "canexist"))
2737                                         status = CACHE_FLAG_CANEXIST;
2738                                 else 
2739                                         ast_log(LOG_WARNING, "Unknown status '%s'\n", value);
2740                         } else if (!strcmp(var, "expirey"))
2741                                 expirey = atoi(value);
2742                         else if (!strcmp(var, "ignorepat")) {
2743                                 /* Don' really do much with it */
2744                         } else 
2745                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2746                 }
2747                 var = strtok(NULL, ";");
2748         }
2749         ast_pthread_mutex_lock(&dpcache_lock);
2750         prev = NULL;
2751         dp = pvt->dpentries;
2752         while(dp) {
2753                 if (!strcmp(dp->exten, exten)) {
2754                         /* Let them go */
2755                         if (prev)
2756                                 prev->peer = dp->peer;
2757                         else
2758                                 pvt->dpentries = dp->peer;
2759                         dp->peer = NULL;
2760                         dp->callno = -1;
2761                         dp->expirey.tv_sec = dp->orig.tv_sec + expirey;
2762                         if (dp->flags & CACHE_FLAG_PENDING) {
2763                                 dp->flags &= ~CACHE_FLAG_PENDING;
2764                                 dp->flags |= status;
2765                         }
2766                         /* Wake up waiters */
2767                         for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2768                                 if (dp->waiters[x] > -1)
2769                                         write(dp->waiters[x], "asdf", 4);
2770                 }
2771                 prev = dp;
2772                 dp = dp->peer;
2773         }
2774         ast_pthread_mutex_unlock(&dpcache_lock);
2775         return 0;
2776 }
2777
2778 static int complete_transfer(int callno, char *orequest)
2779 {
2780         int peercallno = -1;
2781         char request[256] = "";
2782         char *var, *value;
2783         struct chan_iax_pvt *pvt = iaxs[callno];
2784         struct ast_iax_frame *cur;
2785         if (!orequest)
2786                 return -1;
2787
2788         strncpy(request, orequest, sizeof(request)-1);
2789         var = strtok(request, ";");
2790         while(var) {
2791                 value = strchr(var, '=');
2792                 if (value) { 
2793                         *value='\0';
2794                         value++;
2795                         if (!strcmp(var, "peercallno"))
2796                                 peercallno = atoi(value);
2797                         else 
2798                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2799                 }
2800                 var = strtok(NULL, ";");
2801         }
2802         if (peercallno < 0) {
2803                 ast_log(LOG_WARNING, "Invalid transfer request\n");
2804                 return -1;
2805         }
2806         memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
2807         memset(&pvt->transfer, 0, sizeof(pvt->transfer));
2808         /* Reset sequence numbers */
2809         pvt->oseqno = 0;
2810         pvt->iseqno = 0;
2811         pvt->peercallno = peercallno;
2812         pvt->transferring = TRANSFER_NONE;
2813         pvt->svoiceformat = -1;
2814         pvt->voiceformat = 0;
2815         pvt->transfercallno = -1;
2816         memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
2817         memset(&pvt->offset, 0, sizeof(pvt->offset));
2818         memset(&pvt->history, 0, sizeof(pvt->history));
2819         pvt->jitterbuffer = 0;
2820         pvt->jitter = 0;
2821         pvt->historicjitter = 0;
2822         pvt->lag = 0;
2823         pvt->last = 0;
2824         pvt->lastsent = 0;
2825         pvt->pingtime = DEFAULT_RETRY_TIME;
2826         ast_pthread_mutex_lock(&iaxq.lock);
2827         for (cur = iaxq.head; cur ; cur = cur->next) {
2828                 /* We must cancel any packets that would have been transmitted
2829                    because now we're talking to someone new.  It's okay, they
2830                    were transmitted to someone that didn't care anyway. */
2831                 if (callno == cur->callno) 
2832                         cur->retries = -1;
2833         }
2834         ast_pthread_mutex_unlock(&iaxq.lock);
2835         return 0; 
2836 }
2837
2838 static int iax_ack_registry(char *orequest, struct sockaddr_in *sin)
2839 {
2840         struct iax_registry *reg;
2841         /* Start pessimistic */
2842         char request[256] = "";
2843         char peer[256] = "";
2844         int ourport = 0;
2845         int refresh = 0;
2846         char ourip[256] = "<Unspecified>";
2847         struct sockaddr_in oldus;
2848         char *var, *value;
2849
2850         if (!orequest)
2851                 return -1;
2852
2853         strncpy(request, orequest, sizeof(request)-1);
2854         var = strtok(request, ";");
2855         while(var) {
2856                 value = strchr(var, '=');
2857                 if (value) { 
2858                         *value='\0';
2859                         value++;
2860                         if (!strcmp(var, "yourip")) 
2861                                 strncpy(ourip, value, sizeof(ourip)-1);
2862                         else if (!strcmp(var, "peer"))
2863                                 strncpy(peer, value, sizeof(peer)-1);
2864                         else if (!strcmp(var, "yourport"))
2865                                 ourport = atoi(value);
2866                         else if (!strcmp(var, "refresh"))
2867                                 refresh = atoi(value);
2868                         else if (!strcmp(var, "callerid")) {
2869                                 /* We don't really care about suggested Caller*ID, that's more for phones */
2870                         } else 
2871                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2872                 }
2873                 var = strtok(NULL, ";");
2874         }
2875         reg = registrations;
2876         while(reg) {
2877                 if (!strcasecmp(reg->username, peer)) {
2878                         memcpy(&oldus, &reg->us, sizeof(oldus));
2879                         if (memcmp(&reg->addr, sin, sizeof(&reg->addr))) {
2880                                 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", inet_ntoa(sin->sin_addr));
2881                                 return -1;
2882                         }
2883                         if (!inet_aton(ourip, &reg->us.sin_addr)) {
2884                                 ast_log(LOG_WARNING, "Registry ack from '%s' contains invalid IP '%s'\n", inet_ntoa(sin->sin_addr), ourip);
2885                                 return -1;
2886                         }
2887                         reg->us.sin_port = htons(ourport);
2888                         if (refresh && (reg->refresh < refresh)) {
2889                                 /* Refresh faster if necessary */
2890                                 reg->refresh = refresh;
2891                                 if (reg->expire > -1)
2892                                         ast_sched_del(sched, reg->expire);
2893                                 reg->expire = ast_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax_do_register_s, reg);
2894                         }
2895                         if (memcmp(&oldus, &reg->us, sizeof(oldus)) && (option_verbose > 2)) {
2896                                 snprintf(ourip, sizeof(ourip), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2897                                 ast_verbose(VERBOSE_PREFIX_3 "Registered to '%s', who sees us as %s\n", inet_ntoa(sin->sin_addr), ourip);
2898                         }
2899                         reg->regstate = REG_STATE_REGISTERED;
2900                         return 0;
2901                 }
2902                 reg = reg->next;
2903         }
2904         ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
2905         return -1;
2906 }
2907
2908 static int iax_register(char *value, int lineno)
2909 {
2910         struct iax_registry *reg;
2911         char copy[256];
2912         char *username, *hostname, *secret;
2913         char *porta;
2914         
2915         struct hostent *hp;
2916         if (!value)
2917                 return -1;
2918         strncpy(copy, value, sizeof(copy)-1);
2919         username = strtok(copy, "@");
2920         hostname = strtok(NULL, "@");
2921         if (!hostname) {
2922                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
2923                 return -1;
2924         }
2925         username = strtok(username, ":");
2926         secret = strtok(NULL, ":");
2927         hostname = strtok(hostname, ":");
2928         porta = strtok(NULL, ";");
2929         
2930         if (porta && !atoi(porta)) {
2931                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
2932                 return -1;
2933         }
2934         hp = gethostbyname(hostname);
2935         if (!hp) {
2936                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
2937                 return -1;
2938         }
2939         reg = malloc(sizeof(struct iax_registry));
2940         if (reg) {
2941                 memset(reg, 0, sizeof(struct iax_registry));
2942                 strncpy(reg->username, username, sizeof(reg->username)-1);
2943                 if (secret)
2944                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
2945                 reg->expire = -1;
2946                 reg->refresh = AST_DEFAULT_REG_EXPIRE;
2947                 reg->addr.sin_family = AF_INET;
2948                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
2949                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(AST_DEFAULT_IAX_PORTNO);
2950                 reg->next = registrations;
2951                 reg->callno = -1;
2952                 registrations = reg;
2953         } else {
2954                 ast_log(LOG_ERROR, "Out of memory\n");
2955                 return -1;
2956         }
2957         return 0;
2958 }
2959
2960 static int expire_registry(void *data)
2961 {
2962         struct iax_peer *p = data;
2963         /* Reset the address */
2964         memset(&p->addr, 0, sizeof(p->addr));
2965         /* Reset expire notice */
2966         p->expire = -1;
2967         /* Reset expirey value */
2968         p->expirey = expirey;
2969         if (regfunk)
2970                 regfunk(p->name, 0);
2971         return 0;
2972 }
2973
2974 static int update_registry(char *name, struct sockaddr_in *sin, int callno)
2975 {
2976         char requeststr[256] = "";
2977         struct iax_peer *p;
2978         for (p = peerl.peers;p;p = p->next) {
2979                 if (!strcasecmp(name, p->name)) {
2980                         if (memcmp(&p->addr, sin, sizeof(p->addr))) {
2981                                 if (regfunk)
2982                                         regfunk(p->name, 1);
2983                                 if  (option_verbose > 2)
2984                                 ast_verbose(VERBOSE_PREFIX_3 "Registered '%s' (%s) at %s:%d\n", p->name, 
2985                                         iaxs[callno]->state & IAX_STATE_AUTHENTICATED ? "AUTHENTICATED" : "UNAUTHENTICATED", inet_ntoa(sin->sin_addr), htons(sin->sin_port));
2986                         }               
2987                         /* Update the host */
2988                         memcpy(&p->addr, sin, sizeof(p->addr));
2989                         /* Setup the expirey */
2990                         if (p->expire > -1)
2991                                 ast_sched_del(sched, p->expire);
2992                         p->expire = ast_sched_add(sched, p->expirey * 1000, expire_registry, (void *)p);
2993                         MYSNPRINTF "peer=%s;yourip=%s;yourport=%d;refresh=%d;",
2994                                 p->name, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), p->expirey);
2995                         if (p->hascallerid)
2996                                 MYSNPRINTF "callerid=%s;", p->callerid);
2997                         requeststr[strlen(requeststr)-1] = '\0';
2998                         return send_command_final(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGACK, 0, requeststr, strlen(requeststr) + 1, -1);;
2999                 }
3000         }
3001         ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3002         return -1;
3003 }
3004
3005 static int registry_authrequest(char *name, int callno)
3006 {
3007         char requeststr[256] = "";
3008         struct iax_peer *p;
3009         for (p = peerl.peers;p;p = p->next) {
3010                 if (!strcasecmp(name, p->name)) {
3011                         MYSNPRINTF "methods=%s;", p->methods);
3012                         if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
3013                                 /* Build the challenge */
3014                                 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
3015                                 MYSNPRINTF "challenge=%s;", p->challenge);
3016                         }
3017                         MYSNPRINTF "peer=%s;", name);
3018                         requeststr[strlen(requeststr)-1] = '\0';
3019                         return send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGAUTH, 0, requeststr, strlen(requeststr) + 1, -1);;
3020                 }
3021         }
3022         ast_log(LOG_WARNING, "No such peer '%s'\n", name);
3023         return 0;
3024 }
3025
3026 static int registry_rerequest(char *orequest, int callno, struct sockaddr_in *sin)
3027 {
3028         struct iax_registry *reg;
3029         /* Start pessimistic */
3030         char request[256] = "";
3031         char requeststr[256] = "";
3032         char peer[256] = "";
3033         char methods[256] = "";
3034         char challenge[256] = "";
3035         char *var, *value;
3036         int res;
3037
3038         if (!orequest)
3039                 return -1;
3040
3041         strncpy(request, orequest, sizeof(request)-1);
3042         var = strtok(request, ";");
3043         while(var) {
3044                 value = strchr(var, '=');
3045                 if (value) { 
3046                         *value='\0';
3047                         value++;
3048                         if (!strcmp(var, "methods")) 
3049                                 strncpy(methods, value, sizeof(methods)-1);
3050                         else if (!strcmp(var, "peer"))
3051                                 strncpy(peer, value, sizeof(peer)-1);
3052                         else if (!strcmp(var, "challenge"))
3053                                 strncpy(challenge, value, sizeof(challenge)-1);
3054                         else 
3055                                 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
3056                 }
3057                 var = strtok(NULL, ";");
3058         }
3059         reg = registrations;
3060         while(reg) {
3061                 if (!strcasecmp(reg->username, peer)) {
3062                         if (memcmp(&reg->addr, sin, sizeof(&reg->addr))) {
3063                                 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", inet_ntoa(sin->sin_addr));
3064                                 return -1;
3065                         }
3066                         if (!strlen(reg->secret)) {
3067                                 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
3068                                 reg->regstate = REG_STATE_NOAUTH;
3069                                 return -1;
3070                         }
3071                         MYSNPRINTF "peer=%s;refresh=%d;", reg->username, reg->refresh);
3072                         if (reg->secret[0] == '[') {
3073                                 char tmpkey[256];
3074                                 strncpy(tmpkey, reg->secret + 1, sizeof(tmpkey) - 1);
3075                                 tmpkey[strlen(tmpkey) - 1] = '\0';
3076                                 res = authenticate(challenge, NULL, tmpkey, methods, requeststr, sizeof(requeststr), sin);
3077                         } else
3078                                 res = authenticate(challenge, reg->secret, NULL, methods, requeststr, sizeof(requeststr), sin);
3079                         if (!res) {
3080                                 reg->regstate = REG_STATE_AUTHSENT;
3081                                 return send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_REGREQ, 0, requeststr, strlen(requeststr) + 1, -1);
3082                         } else
3083                                 return -1;
3084                 }
3085                 reg = reg->next;
3086         }
3087         ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
3088         return -1;
3089 }
3090
3091 static int stop_stuff(int callno)
3092 {
3093                 if (iaxs[callno]->lagid > -1)
3094                         ast_sched_del(sched, iaxs[callno]->lagid);
3095                 iaxs[callno]->lagid = -1;
3096                 if (iaxs[callno]->pingid > -1)
3097                         ast_sched_del(sched, iaxs[callno]->pingid);
3098                 iaxs[callno]->pingid = -1;
3099                 if (iaxs[callno]->autoid > -1)
3100                         ast_sched_del(sched, iaxs[callno]->autoid);
3101                 iaxs[callno]->autoid = -1;
3102                 return 0;
3103 }
3104
3105 static int auto_hangup(void *nothing)
3106 {
3107         int callno = (int)(long)(nothing);
3108         if (iaxs[callno]) {
3109                 iaxs[callno]->autoid = -1;
3110                 send_command_final(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, "Timeout", strlen("Timeout") + 1, -1);
3111         }
3112         return 0;
3113 }
3114
3115 static void iax_dprequest(struct iax_dpcache *dp, int callno)
3116 {
3117         /* Auto-hangup with 30 seconds of inactivity */
3118         if (iaxs[callno]->autoid > -1)
3119                 ast_sched_del(sched, iaxs[callno]->autoid);
3120         iaxs[callno]->autoid = ast_sched_add(sched, 30000, auto_hangup, (void *)callno);
3121         send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_DPREQ, 0, dp->exten, strlen(dp->exten) + 1, -1);
3122         dp->flags |= CACHE_FLAG_TRANSMITTED;
3123 }
3124
3125 static int iax_vnak(int callno)
3126 {
3127         return send_command_immediate(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
3128 }
3129
3130 static void vnak_retransmit(int callno, int last)
3131 {
3132         struct ast_iax_frame *f;
3133         ast_pthread_mutex_lock(&iaxq.lock);
3134         f = iaxq.head;
3135         while(f) {
3136                 /* Send a copy immediately */
3137                 if ((f->callno == callno) && iaxs[f->callno] &&
3138                         (f->seqno >= last)) {
3139                         send_packet(f);
3140                 }
3141                 f = f->next;
3142         }
3143         ast_pthread_mutex_unlock(&iaxq.lock);
3144 }
3145
3146 static int socket_read(int *id, int fd, short events, void *cbdata)
3147 {
3148         struct sockaddr_in sin;
3149         int res;
3150         int new = NEW_PREVENT;
3151         char buf[4096];
3152         char src[80];
3153         int len = sizeof(sin);
3154         int dcallno = -1;
3155         struct ast_iax_full_hdr *fh = (struct ast_iax_full_hdr *)buf;
3156         struct ast_iax_mini_hdr *mh = (struct ast_iax_mini_hdr *)buf;
3157         struct ast_iax_frame fr, *cur;
3158         struct ast_frame f;
3159         struct ast_channel *c;
3160         struct iax_dpcache *dp;
3161         int format;
3162         int exists;
3163         char rel0[256];
3164         char rel1[255];
3165         char empty[32]="";              /* Safety measure */
3166         res = recvfrom(netsocket, buf, sizeof(buf), 0,(struct sockaddr *) &sin, &len);
3167         if (res < 0) {
3168                 if (errno != ECONNREFUSED)
3169                         ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
3170                 handle_error();
3171                 return 1;
3172         }
3173         if (res < sizeof(struct ast_iax_mini_hdr)) {
3174                 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, sizeof(struct ast_iax_mini_hdr));
3175                 return 1;
3176         }
3177 #ifdef DEBUG_SUPPORT
3178         if (iaxdebug)
3179                 showframe(NULL, fh, 1, &sin);
3180 #endif
3181         if (ntohs(mh->callno) & AST_FLAG_FULL) {
3182                 /* Get the destination call number */
3183                 dcallno = ntohs(fh->dcallno);
3184                 /* Retrieve the type and subclass */
3185                 f.frametype = fh->type;
3186                 f.subclass = uncompress_subclass(fh->csub);
3187 #if 0
3188                 f.subclass = fh->subclasshigh << 16;
3189                 f.subclass += ntohs(fh->subclasslow);
3190 #endif
3191                 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == AST_IAX_COMMAND_NEW) || (f.subclass == AST_IAX_COMMAND_REGREQ)))
3192                         new = NEW_ALLOW;
3193         } else {
3194                 /* Don't knwo anything about it yet */
3195                 f.frametype = AST_FRAME_NULL;
3196                 f.subclass = 0;
3197         }
3198         ast_pthread_mutex_lock(&iaxs_lock);
3199         fr.callno = find_callno(ntohs(mh->callno) & ~AST_FLAG_FULL, dcallno, &sin, new);
3200         if ((fr.callno < 0) || !iaxs[fr.callno]) {
3201                 /* A call arrived for a non-existant destination.  Unless it's an "inval"
3202                    frame, reply with an inval */
3203                 if (ntohs(mh->callno) & AST_FLAG_FULL) {
3204                         /* We can only raw hangup control frames */
3205                         if (((f.subclass != AST_IAX_COMMAND_INVAL) &&
3206                                  (f.subclass != AST_IAX_COMMAND_TXCNT) &&
3207                                  (f.subclass != AST_IAX_COMMAND_TXACC))||
3208                             (f.frametype != AST_FRAME_IAX))
3209                                 raw_hangup(&sin, ntohs(fh->dcallno), ntohs(mh->callno) & ~AST_FLAG_FULL
3210                                 );
3211                 }
3212                 ast_pthread_mutex_unlock(&iaxs_lock);
3213                 return 1;
3214         }
3215         if (((f.subclass != AST_IAX_COMMAND_TXCNT) &&
3216              (f.subclass != AST_IAX_COMMAND_TXACC)) || (f.frametype != AST_FRAME_IAX))
3217                 iaxs[fr.callno]->peercallno = (short)(ntohs(mh->callno) & ~AST_FLAG_FULL);
3218         if (ntohs(mh->callno) & AST_FLAG_FULL) {
3219                 if (option_debug)
3220                         ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", ntohs(fh->seqno), f.frametype, f.subclass);
3221                 /* Check if it's out of order (and not an ACK or INVAL) */
3222                 fr.seqno = ntohs(fh->seqno);
3223                 if ((iaxs[fr.callno]->iseqno != fr.seqno) &&
3224                         (iaxs[fr.callno]->iseqno ||
3225                                 ((f.subclass != AST_IAX_COMMAND_TXCNT) &&
3226                                 (f.subclass != AST_IAX_COMMAND_TXACC)) ||
3227                                 (f.subclass != AST_FRAME_IAX))) {
3228                         if (
3229                          ((f.subclass != AST_IAX_COMMAND_ACK) &&
3230                           (f.subclass != AST_IAX_COMMAND_INVAL) &&
3231                           (f.subclass != AST_IAX_COMMAND_TXCNT) &&
3232                           (f.subclass != AST_IAX_COMMAND_TXACC) &&
3233                           (f.subclass != AST_IAX_COMMAND_VNAK)) ||
3234                           (f.frametype != AST_FRAME_IAX)) {
3235                                 /* If it's not an ACK packet, it's out of order. */
3236                                 if (option_debug)
3237                                         ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n", 
3238                                         iaxs[fr.callno]->iseqno, fr.seqno, f.frametype, f.subclass);
3239                                 if (iaxs[fr.callno]->iseqno > fr.seqno) {
3240                                         /* If we've already seen it, ack it XXX There's a border condition here XXX */
3241                                         if ((f.frametype != AST_FRAME_IAX) || 
3242                                                         ((f.subclass != AST_IAX_COMMAND_ACK) && (f.subclass != AST_IAX_COMMAND_INVAL))) {
3243                                                 if (option_debug)
3244                                                         ast_log(LOG_DEBUG, "Acking anyway\n");
3245                                                 send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.seqno);
3246                                         }
3247                                 } else {
3248                                         /* Send a VNAK requesting retransmission */
3249                                         iax_vnak(fr.callno);
3250                                 }
3251                                 ast_pthread_mutex_unlock(&iaxs_lock);
3252                                 return 1;
3253                         }
3254                 } else {
3255                         /* Increment unless it's an ACK or VNAK */
3256                         if (((f.subclass != AST_IAX_COMMAND_ACK) &&
3257                             (f.subclass != AST_IAX_COMMAND_INVAL) &&
3258                             (f.subclass != AST_IAX_COMMAND_TXCNT) &&
3259                             (f.subclass != AST_IAX_COMMAND_TXACC) &&
3260                                 (f.subclass != AST_IAX_COMMAND_VNAK)) ||
3261                             (f.frametype != AST_FRAME_IAX))
3262                                 iaxs[fr.callno]->iseqno++;
3263                 }
3264                 /* A full frame */
3265                 if (res < sizeof(struct ast_iax_full_hdr)) {
3266                         ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, sizeof(struct ast_iax_full_hdr));
3267                         ast_pthread_mutex_unlock(&iaxs_lock);
3268                         return 1;
3269                 }
3270                 f.datalen = res - sizeof(struct ast_iax_full_hdr);
3271                 if (f.datalen)
3272                         f.data = buf + sizeof(struct ast_iax_full_hdr);
3273                 else
3274                         f.data = empty;
3275                 fr.ts = ntohl(fh->ts);
3276                 /* Unless this is an ACK or INVAL frame, ack it */
3277                 if ((f.frametype != AST_FRAME_IAX) || 
3278                          ((f.subclass != AST_IAX_COMMAND_ACK) && 
3279                           (f.subclass != AST_IAX_COMMAND_TXCNT) && 
3280                           (f.subclass != AST_IAX_COMMAND_TXACC) && 
3281                           (f.subclass != AST_IAX_COMMAND_INVAL) &&
3282                           (f.subclass != AST_IAX_COMMAND_VNAK))) 
3283                         send_command_immediate(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.seqno);
3284                 if (f.frametype == AST_FRAME_VOICE) {
3285                         if (f.subclass != iaxs[fr.callno]->voiceformat) {
3286                                         iaxs[fr.callno]->voiceformat = f.subclass;
3287                                         ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
3288                                         if (iaxs[fr.callno]->owner) {
3289                                                 int orignative;
3290                                                 ast_pthread_mutex_lock(&iaxs[fr.callno]->owner->lock);
3291                                                 orignative = iaxs[fr.callno]->owner->nativeformats;
3292                                                 iaxs[fr.callno]->owner->nativeformats = f.subclass;
3293                                                 if (iaxs[fr.callno]->owner->readformat)
3294                                                         ast_set_read_format(iaxs[fr.callno]->owner, iaxs[fr.callno]->owner->readformat);
3295                                                 iaxs[fr.callno]->owner->nativeformats = orignative;
3296                                                 ast_pthread_mutex_unlock(&iaxs[fr.callno]->owner->lock);
3297                                         }
3298                         }
3299                 }
3300                 if (f.frametype == AST_FRAME_IAX) {
3301                         /* Handle the IAX pseudo frame itself */
3302                         if (option_debug)
3303                                 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
3304                         /* Go through the motions of delivering the packet without actually doing so,
3305                            unless this is a lag request since it will be done for real */
3306                         if (f.subclass != AST_IAX_COMMAND_LAGRQ)
3307                                 schedule_delivery(&fr, 0);
3308                         switch(f.subclass) {
3309                         case AST_IAX_COMMAND_ACK:
3310                                 /* Ack the packet with the given timestamp */
3311                                 ast_pthread_mutex_lock(&iaxq.lock);
3312                                 for (cur = iaxq.head; cur ; cur = cur->next) {
3313                                         /* If it's our call, and our timestamp, mark -1 retries */
3314                                         if ((fr.callno == cur->callno) && (fr.seqno == cur->seqno)) {
3315                                                 cur->retries = -1;
3316                                                 /* Destroy call if this is the end */
3317                                                 if (cur->final) 
3318                                                         iax_destroy(fr.callno);
3319                                         }
3320                                 }
3321                                 ast_pthread_mutex_unlock(&iaxq.lock);
3322                                 break;
3323                         case AST_IAX_COMMAND_QUELCH:
3324                                 if (iaxs[fr.callno]->state & IAX_STATE_STARTED)
3325                                         iaxs[fr.callno]->quelch = 1;
3326                                 break;
3327                         case AST_IAX_COMMAND_UNQUELCH:
3328                                 if (iaxs[fr.callno]->state & IAX_STATE_STARTED)
3329                                         iaxs[fr.callno]->quelch = 0;
3330                                 break;
3331                         case AST_IAX_COMMAND_TXACC:
3332                                 if (iaxs[fr.callno]->transferring == TRANSFER_BEGIN) {
3333                                         /* Ack the packet with the given timestamp */
3334                                         ast_pthread_mutex_lock(&iaxq.lock);
3335                                         for (cur = iaxq.head; cur ; cur = cur->next) {
3336                                                 /* Cancel any outstanding txcnt's */
3337                                                 if ((fr.callno == cur->callno) && (cur->transfer))
3338                                                         cur->retries = -1;
3339                                         }
3340                                         ast_pthread_mutex_unlock(&iaxq.lock);
3341                                         snprintf(rel1, sizeof(rel1), "callno=%d;", iaxs[fr.callno]->callno);
3342                                         send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREADY, 0, rel1, strlen(rel1) + 1, -1);
3343                                         iaxs[fr.callno]->transferring = TRANSFER_READY;
3344                                 }
3345                                 break;
3346                         case AST_IAX_COMMAND_NEW:
3347                                 /* Ignore if it's already up */
3348                                 if (iaxs[fr.callno]->state & (IAX_STATE_STARTED | IAX_STATE_TBD))
3349                                         break;
3350                                 ((char *)f.data)[f.datalen] = '\0';
3351                                 if (check_access(fr.callno, &sin, f.data, f.datalen)) {
3352                                         /* They're not allowed on */
3353                                         send_command_final(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "No authority found", strlen("No authority found"), -1);
3354                                         ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s'\n", inet_ntoa(sin.sin_addr), (char *)f.data);
3355                                         break;
3356                                 }
3357                                 ast_pthread_mutex_unlock(&iaxs_lock);
3358                                 /* This might re-enter the IAX code and need the lock */
3359                                 exists = ast_exists_extension(NULL, iaxs[fr.callno]->context, iaxs[fr.callno]->exten, 1, iaxs[fr.callno]->callerid);
3360                                 ast_pthread_mutex_lock(&iaxs_lock);
3361                                 if (!strlen(iaxs[fr.callno]->secret) && !strlen(iaxs[fr.callno]->inkeys)) {
3362                                         if (strcmp(iaxs[fr.callno]->exten, "TBD") && !exists) {
3363                                                 send_command_final(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "No such context/extension", strlen("No such context/extension"), -1);
3364                                                 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);
3365                                         } else {
3366                                                 /* Select an appropriate format */
3367                                                 format = iaxs[fr.callno]->peerformat & iax_capability;
3368                                                 if (!format) {
3369                                                         format = iaxs[fr.callno]->peercapability & iax_capability;
3370                                                         if (!format) {
3371                                                                 send_command_final(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "Unable to negotiate codec", strlen("Unable to negotiate codec"), -1);
3372                                                                 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);
3373                                                         } else {
3374                                                                 /* Pick one... */
3375                                                                 format = ast_best_codec(iaxs[fr.callno]->peercapability & iax_capability);
3376                                                                 if (!format) {
3377                                                                         ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr.callno]->peercapability & iax_capability);
3378                                                                         send_command_final(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "Unable to negotiate codec", strlen("Unable to negotiate codec"), -1);
3379                                                                         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);
3380                                                                         iaxs[fr.callno]->alreadygone = 1;
3381                                                                         break;
3382                                                                 }
3383                                    &nb