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