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