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