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