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