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