2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
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>
31 #include <sys/signal.h>
41 #define DEFAULT_RETRY_TIME 1000
42 #define MEMORY_SIZE 100
43 #define DEFAULT_DROP 3
45 /* If you want to use the simulator, then define IAX_SIMULATOR. */
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";
55 static char context[80] = "default";
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;
63 static int netsocket = -1;
66 static pthread_mutex_t usecnt_lock = PTHREAD_MUTEX_INITIALIZER;
67 static pthread_mutex_t iaxs_lock = PTHREAD_MUTEX_INITIALIZER;
70 #define IAX_CAPABILITY_FULLBANDWIDTH 0x7FFFFFFF
72 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
73 ~AST_FORMAT_SLINEAR & \
77 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
81 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
84 static struct io_context *io;
85 static struct sched_context *sched;
87 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
89 static int iax_dropcount = DEFAULT_DROP;
91 static int use_jitterbuffer = 1;
93 static pthread_t netthreadid;
95 #define IAX_STATE_STARTED (1 << 0)
96 #define IAX_STATE_AUTHENTICATED (1 << 1)
98 #define IAX_SENSE_DENY 0
99 #define IAX_SENSE_ALLOW 1
102 /* Host access rule */
103 struct in_addr netaddr;
104 struct in_addr netmask;
110 char context[AST_MAX_EXTENSION];
111 struct iax_context *next;
119 struct iax_context *contexts;
120 struct iax_user *next;
127 struct sockaddr_in addr;
131 /* Dynamic Registration fields */
133 struct sockaddr_in defaddr;
136 struct timeval nexpire;
139 struct iax_peer *next;
142 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
143 #define MIN_RETRY_TIME 10
144 #define MAX_RETRY_TIME 10000
145 #define MAX_JITTER_BUFFER 50
147 /* If we have more than this much excess real jitter buffer, srhink it. */
148 static int max_jitter_buffer = MAX_JITTER_BUFFER;
150 struct chan_iax_pvt {
151 /* Pipes for communication. pipe[1] belongs to the
152 network thread (write), and pipe[0] belongs to the individual
155 /* Last received voice format */
157 /* Last sent voice format */
159 /* Last received timestamp */
161 /* Last sent timestamp - never send the same timestamp twice in a single call */
162 unsigned int lastsent;
164 unsigned int pingtime;
166 struct sockaddr_in addr;
167 /* Our call number */
171 /* Peer supported formats */
173 /* timeval that we base our transmission on */
174 struct timeval offset;
175 /* timeval that we base our delivery on */
176 struct timeval rxcore;
177 /* Historical delivery time */
178 int history[MEMORY_SIZE];
179 /* Current base jitterbuffer */
181 /* Current jitter measure */
185 /* Error, as discovered by the manager */
187 /* Onwer if we have one */
188 struct ast_channel *owner;
189 /* What's our state? */
191 /* Next outgoing sequence number */
192 unsigned short oseqno;
193 /* Next incoming sequence number */
194 unsigned short iseqno;
197 /* Default Context */
199 /* Caller ID if available */
203 /* Requested Extension */
204 char exten[AST_MAX_EXTENSION];
205 /* Expected Username */
207 /* Expected Secret */
209 /* permitted authentication methods */
215 struct ast_iax_frame {
216 /* Actual, isolated frame */
218 /* /Our/ call number */
220 /* Start of raw frame (outgoing only) */
222 /* Length of frame (outgoing only) */
224 /* How many retries so far? */
226 /* Outgoing relative timestamp (ms) */
228 /* How long to wait before retrying */
230 /* Are we received out of order? */
232 /* Have we been sent at all yet? */
234 /* Packet sequence number */
237 struct ast_iax_frame *next;
238 struct ast_iax_frame *prev;
241 static struct ast_iax_queue {
242 struct ast_iax_frame *head;
243 struct ast_iax_frame *tail;
245 pthread_mutex_t lock;
248 static struct ast_user_list {
249 struct iax_user *users;
250 pthread_mutex_t lock;
253 static struct ast_peer_list {
254 struct iax_peer *peers;
255 pthread_mutex_t lock;
258 /* XXX We probably should use a mutex when working with this XXX */
259 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
261 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
263 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
265 static int send_ping(void *data)
267 int callno = (long)data;
269 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
275 static int send_lagrq(void *data)
277 int callno = (long)data;
279 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
285 static unsigned char compress_subclass(int subclass)
289 /* If it's 128 or smaller, just return it */
290 if (subclass < AST_FLAG_SC_LOG)
292 /* Otherwise find its power */
293 for (x = 0; x < AST_MAX_SHIFT; x++) {
294 if (subclass & (1 << x)) {
296 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
302 return power | AST_FLAG_SC_LOG;
305 static int uncompress_subclass(unsigned char csub)
307 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
308 if (csub & AST_FLAG_SC_LOG)
309 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
314 static struct chan_iax_pvt *new_iax(void)
316 struct chan_iax_pvt *tmp;
317 tmp = malloc(sizeof(struct chan_iax_pvt));
319 memset(tmp, 0, sizeof(struct chan_iax_pvt));
320 /* On my linux system, pipe's are more than 2x as fast as socketpairs */
321 if (pipe(tmp->pipe)) {
322 ast_log(LOG_WARNING, "Unable to create pipe: %s\n", strerror(errno));
327 tmp->peercallno = -1;
328 /* strncpy(tmp->context, context, sizeof(tmp->context)); */
329 strncpy(tmp->exten, "s", sizeof(tmp->exten));
334 static int get_timelen(struct ast_frame *f)
337 switch(f->subclass) {
338 case AST_FORMAT_G723_1:
339 timelen = 30 /* XXX Not necessarily true XXX */;
342 timelen = 20 * (f->datalen / 20);
344 case AST_FORMAT_SLINEAR:
345 timelen = f->datalen / 16;
347 case AST_FORMAT_LPC10:
349 timelen += ((char *)(f->data))[7] & 0x1;
351 case AST_FORMAT_ULAW:
352 timelen = f->datalen / 8;
354 case AST_FORMAT_ADPCM:
355 timelen = f->datalen / 4;
358 ast_log(LOG_WARNING, "Don't know how to calculate timelen on %d packets\n", f->subclass);
364 static struct ast_iax_frame *iaxfrdup(struct ast_iax_frame *fr)
366 /* Malloc() a copy of a frame */
367 struct ast_iax_frame *new = malloc(sizeof(struct ast_iax_frame));
369 memcpy(new, fr, sizeof(struct ast_iax_frame));
374 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
376 /* Malloc() a copy of a frame */
377 struct ast_iax_frame *new = malloc(sizeof(struct ast_iax_frame));
379 memcpy(new, fr, sizeof(struct ast_iax_frame));
380 new->f = ast_frdup(fr->f);
381 /* Copy full header */
383 memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
384 fr->f->data - sizeof(struct ast_iax_full_hdr),
385 sizeof(struct ast_iax_full_hdr));
386 /* Grab new data pointer */
387 new->data = new->f->data - (fr->f->data - fr->data);
396 #define NEW_PREVENT 0
400 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
405 if (new <= NEW_ALLOW) {
406 /* Look for an existing connection first */
407 for (x=0;x<AST_IAX_MAX_CALLS;x++) {
409 /* Look for an exact match */
410 if ((sin->sin_port == iaxs[x]->addr.sin_port) &&
411 (sin->sin_addr.s_addr == iaxs[x]->addr.sin_addr.s_addr) &&
412 ((callno == iaxs[x]->peercallno) || /* Our expected source call number is the same */
413 ((dcallno == x) && (iaxs[x]->peercallno = -1))
414 /* We have no expected source number, and the destination is right */
422 if ((res < 0) && (new >= NEW_ALLOW)) {
423 /* Create a new one */
425 for (x = nextcallno + 1; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
427 ast_log(LOG_WARNING, "Unable to accept more calls\n");
433 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
434 iaxs[x]->addr.sin_port = sin->sin_port;
435 iaxs[x]->addr.sin_family = sin->sin_family;
436 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
437 iaxs[x]->peercallno = callno;
439 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
440 ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
441 ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
443 ast_log(LOG_DEBUG, "Out of memory\n");
450 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno);
452 static int do_deliver(void *data)
454 /* Just deliver the packet by writing it to half of the pipe. */
455 struct ast_iax_frame *fr = data;
457 if (iaxs[fr->callno]) {
458 if (fr->f->frametype == AST_FRAME_IAX) {
459 /* We have to treat some of these packets specially because
460 they're LAG measurement packets */
461 if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
462 /* If we got a queued request, build a reply and send it */
463 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
464 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1);
465 } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
466 /* This is a reply we've been given, actually measure the difference */
467 ts = calc_timestamp(iaxs[fr->callno], 0);
468 iaxs[fr->callno]->lag = ts - fr->ts;
471 ast_fr_fdwrite(iaxs[fr->callno]->pipe[1], fr->f);
474 /* Free the packet */
476 /* And our iax frame */
478 /* And don't run again */
482 static int handle_error()
484 /* XXX Ideally we should figure out why an error occured and then abort those
485 rather than continuing to try. Unfortunately, the published interface does
486 not seem to work XXX */
488 struct sockaddr_in *sin;
491 struct sock_extended_err e;
496 m.msg_controllen = sizeof(e);
498 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
500 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
502 if (m.msg_controllen) {
503 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
505 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
507 ast_log(LOG_WARNING, "No address detected??\n");
509 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
517 static int __send_packet(struct ast_iax_frame *f)
519 static int send_packet(struct ast_iax_frame *f)
524 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
525 /* Don't send if there was an error, but return error instead */
527 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
530 if (iaxs[f->callno]->error)
532 res = sendto(netsocket, f->data, f->datalen, 0, &iaxs[f->callno]->addr,
533 sizeof(iaxs[f->callno]->addr));
535 ast_log(LOG_WARNING, "Received error: %s\n", strerror(errno));
544 /* Average amount of delay in the connection */
545 static int average_delay = 0;
546 /* Permitted deviation either side of the average delay */
547 static int delay_deviation = 0;
548 /* Percent chance that a packet arrives O.K. */
549 static int reliability = 100;
551 static int iax_sim_calc_delay()
554 ms = average_delay - delay_deviation;
555 ms += ((float)(delay_deviation * 2)) * rand() / (RAND_MAX + 1.0);
558 if ((float)rand()/(RAND_MAX + 1.0) < ((float)reliability)/100)
564 static int d_send_packet(void *v)
566 struct ast_iax_frame *f = (struct ast_iax_frame *)v;
574 static int send_packet(struct ast_iax_frame *f)
576 struct ast_iax_frame *fn;
578 ms = iax_sim_calc_delay();
580 return __send_packet(f);
582 /* Make a completely independent frame, in case the other
583 is destroyed -- still doesn't make things like hangups
584 arrive if the main channel is destroyed, but close enough */
585 fn = iaxfrdup2(f, 1);
586 ast_sched_add(sched, ms, d_send_packet, fn);
587 } /* else we drop the packet */
591 static int iax_sim_set(int fd, int argc, char *argv[])
594 return RESULT_SHOWUSAGE;
595 if (!strcasecmp(argv[2], "delay"))
596 average_delay = atoi(argv[3]);
597 else if (!strcasecmp(argv[2], "deviation"))
598 delay_deviation = atoi(argv[3]);
599 else if (!strcasecmp(argv[2], "reliability"))
600 reliability = atoi(argv[3]);
602 return RESULT_SHOWUSAGE;
603 if (reliability > 100)
607 if (delay_deviation > average_delay)
608 delay_deviation = average_delay;
609 return RESULT_SUCCESS;
612 static char delay_usage[] =
613 "Usage: sim set delay <value>\n"
614 " Configure the IAX network simulator to generate average\n"
615 " delays equal to the specified value (in milliseconds).\n";
617 static char deviation_usage[] =
618 "Usage: sim set deviation <value>\n"
619 " Configures the IAX network simulator's deviation value.\n"
620 " The delays generated by the simulator will always be within\n"
621 " this value of milliseconds (postive or negative) of the \n"
624 static char reliability_usage[] =
625 "Usage: sim set reliability <value>\n"
626 " Configure the probability that a packet will be delivered.\n"
627 " The value specified is a percentage from 0 to 100\n";
629 static int iax_sim_show(int fd, int argc, char *argv[])
632 return RESULT_SHOWUSAGE;
633 ast_cli(fd, "Average Delay: %d ms\n", average_delay);
634 ast_cli(fd, "Delay Deviation: %d ms\n", delay_deviation);
635 ast_cli(fd, "Reliability: %d %\n", reliability);
636 return RESULT_SUCCESS;
639 static char sim_show_usage[] =
641 " Displays average delay, deviation, and reliability\n"
642 " used by the network simulator.\n";
644 static struct ast_cli_entry delay_cli =
645 { { "sim", "set", "delay", NULL }, iax_sim_set, "Sets simulated average delay", delay_usage };
646 static struct ast_cli_entry deviation_cli =
647 { { "sim", "set", "deviation", NULL }, iax_sim_set, "Sets simulated delay deviation", deviation_usage };
648 static struct ast_cli_entry reliability_cli =
649 { { "sim", "set", "reliability", NULL }, iax_sim_set, "Sets simulated reliability", reliability_usage };
650 static struct ast_cli_entry sim_show_cli =
651 { { "sim", "show", NULL }, iax_sim_show, "Displays simulation parameters", sim_show_usage };
655 static int attempt_transmit(void *data)
657 /* Attempt to transmit the frame to the remote peer */
659 struct ast_iax_frame *f = data;
661 /* Make sure this call is still active */
662 if (iaxs[f->callno]) {
663 if ((f->retries == -1) /* Already ACK'd */ ||
664 (f->retries >= max_retries) /* Too many attempts */) {
665 /* Record an error if we've transmitted too many times */
666 if (f->retries >= max_retries) {
667 ast_log(LOG_WARNING, "Max retries exceeded to host %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr), f->f->frametype, f->f->subclass, f->ts, f->seqno);
668 iaxs[f->callno]->error = ETIMEDOUT;
669 /* Send a bogus frame to wake up the waiting process */
670 write(iaxs[f->callno]->pipe[1], &zero, 1);
672 /* Don't attempt delivery, just remove it from the queue */
673 pthread_mutex_lock(&iaxq.lock);
675 f->prev->next = f->next;
679 f->next->prev = f->prev;
683 pthread_mutex_unlock(&iaxq.lock);
685 /* Attempt transmission */
688 /* Try again later after 10 times as long */
690 if (f->retrytime > MAX_RETRY_TIME)
691 f->retrytime = MAX_RETRY_TIME;
692 ast_sched_add(sched, f->retrytime, attempt_transmit, f);
696 /* Do not try again */
700 static int iax_set_jitter(int fd, int argc, char *argv[])
702 if ((argc != 4) && (argc != 5))
703 return RESULT_SHOWUSAGE;
705 max_jitter_buffer = atoi(argv[3]);
706 if (max_jitter_buffer < 0)
707 max_jitter_buffer = 0;
710 pthread_mutex_lock(&iaxs_lock);
711 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
712 if (iaxs[atoi(argv[3])]) {
713 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
714 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
715 iaxs[atoi(argv[3])]->jitterbuffer = 0;
717 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
719 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
720 pthread_mutex_unlock(&iaxs_lock);
723 return RESULT_SUCCESS;
726 static char jitter_usage[] =
727 "Usage: iax set jitter [callid] <value>\n"
728 " If used with a callid, it sets the jitter buffer to the given static\n"
729 "value (until its next calculation). If used without a callid, the value is used\n"
730 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
731 "buffer size is reduced.";
733 static struct ast_cli_entry cli_set_jitter =
734 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
736 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
738 static int schedule_delivery(struct ast_iax_frame *fr)
740 /* XXX FIXME: I should delay delivery with a sliding jitter buffer XXX */
742 int drops[MEMORY_SIZE];
743 int min, max=0, maxone=0,y,z, match;
744 /* ms is a measure of the "lateness" of the packet relative to the first
745 packet we received, which always has a lateness of 1. */
746 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
748 /* Rotate our history queue of "lateness". Don't worry about those initial
749 zeros because the first entry will always be zero */
750 for (x=0;x<MEMORY_SIZE - 1;x++)
751 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
752 /* Add a history entry for this one */
753 iaxs[fr->callno]->history[x] = ms;
755 /* Initialize the minimum to reasonable values. It's too much
756 work to do the same for the maximum, repeatedly */
757 min=iaxs[fr->callno]->history[0];
758 for (z=0;z < iax_dropcount + 1;z++) {
759 /* Start very pessimistic ;-) */
761 for (x=0;x<MEMORY_SIZE;x++) {
762 if (max < iaxs[fr->callno]->history[x]) {
763 /* We have a candidate new maximum value. Make
764 sure it's not in our drop list */
766 for (y=0;!match && (y<z);y++)
767 match |= (drops[y] == x);
769 /* It's not in our list, use it as the new maximum */
770 max = iaxs[fr->callno]->history[x];
776 /* On our first pass, find the minimum too */
777 if (min > iaxs[fr->callno]->history[x])
778 min = iaxs[fr->callno]->history[x];
785 /* Just for reference, keep the "jitter" value, the difference between the
786 earliest and the latest. */
787 iaxs[fr->callno]->jitter = max - min;
789 /* If our jitter buffer is too big (by a significant margin), then we slowly
790 shrink it by about 1 ms each time to avoid letting the change be perceived */
791 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
792 iaxs[fr->callno]->jitterbuffer -= 2;
795 /* Constrain our maximum jitter buffer appropriately */
796 if (max > min + maxjitterbuffer) {
798 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
799 max = min + maxjitterbuffer;
803 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
804 buffer immediately to accomodate it (and a little more). */
805 if (max > iaxs[fr->callno]->jitterbuffer)
806 iaxs[fr->callno]->jitterbuffer = max
807 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
811 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
813 /* Subtract the lateness from our jitter buffer to know how long to wait
814 before sending our packet. */
815 ms = iaxs[fr->callno]->jitterbuffer - ms;
817 if (!use_jitterbuffer)
822 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
823 /* Don't deliver it more than 4 ms late */
824 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
828 /* Free the packet */
830 /* And our iax frame */
835 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
836 ast_sched_add(sched, ms, do_deliver, fr);
841 static int iax_transmit(struct ast_iax_frame *fr)
843 /* Lock the queue and place this packet at the end */
846 /* By setting this to 0, the network thread will send it for us, and
847 queue retransmission if necessary */
849 pthread_mutex_lock(&iaxq.lock);
856 iaxq.tail->next = fr;
857 fr->prev = iaxq.tail;
861 pthread_mutex_unlock(&iaxq.lock);
862 /* Wake up the network thread */
863 pthread_kill(netthreadid, SIGURG);
869 static int iax_digit(struct ast_channel *c, char digit)
871 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
874 static int iax_sendtext(struct ast_channel *c, char *text)
877 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
878 0, 0, text, strlen(text) + 1, -1);
881 static int create_addr(struct sockaddr_in *sin, char *peer)
885 sin->sin_family = AF_INET;
886 pthread_mutex_lock(&peerl.lock);
889 if (!strcasecmp(p->name, peer)) {
890 sin->sin_addr = p->addr.sin_addr;
891 sin->sin_port = p->addr.sin_port;
896 pthread_mutex_unlock(&peerl.lock);
898 hp = gethostbyname(peer);
900 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
901 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
908 static int iax_call(struct ast_channel *c, char *dest, int timeout)
910 struct sockaddr_in sin;
916 char requeststr[256] = "";
917 char myrdest [5] = "s";
919 if ((c->state != AST_STATE_DOWN) && (c->state != AST_STATE_RESERVED)) {
920 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
923 strncpy(host, dest, sizeof(host));
925 /* If no destination extension specified, use 's' */
926 rdest = strtok(NULL, "/");
930 rcontext = strtok(NULL, "@");
932 username = strtok(NULL, "@");
934 /* Really the second argument is the host, not the username */
940 if (strtok(hname, ":")) {
942 portno = strtok(hname, ":");
944 if (create_addr(&sin, hname)) {
945 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
949 sin.sin_port = htons(atoi(portno));
951 /* Now we build our request string */
952 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr),
953 MYSNPRINTF "exten=%s;", rdest);
955 MYSNPRINTF "callerid=%s;", c->callerid);
957 MYSNPRINTF "dnid=%s;", c->dnid);
959 MYSNPRINTF "context=%s;", rcontext);
961 MYSNPRINTF "username=%s;", username);
962 MYSNPRINTF "formats=%d;", c->nativeformats);
963 MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
964 /* Trim the trailing ";" */
965 if (strlen(requeststr))
966 requeststr[strlen(requeststr) - 1] = '\0';
967 /* Transmit the string in a "NEW" request */
968 if (option_verbose > 2)
969 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
970 send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_IAX,
971 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
972 c->state = AST_STATE_RINGING;
976 static void iax_destroy(int callno)
979 struct chan_iax_pvt *pvt = iaxs[callno];
982 /* If there's an owner, prod it to give up */
983 write(pvt->pipe[1], &zero, 1);
993 static int iax_hangup(struct ast_channel *c) {
994 struct chan_iax_pvt *pvt = c->pvt->pvt;
995 /* Send the hangup unless we have had a transmission error */
997 send_command(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
998 /* Wait for the network thread to transmit our command -- of course, if
999 it doesn't, that's okay too -- the other end will find out
1000 soon enough, but it's a nicity if it can know now. */
1003 pthread_mutex_lock(&iaxs_lock);
1006 pthread_mutex_lock(&usecnt_lock);
1009 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1010 pthread_mutex_unlock(&usecnt_lock);
1011 ast_update_use_count();
1012 if (option_verbose > 2)
1013 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1014 iax_destroy(pvt->callno);
1015 pthread_mutex_unlock(&iaxs_lock);
1019 static struct ast_frame *iax_read(struct ast_channel *c)
1021 struct chan_iax_pvt *pvt = c->pvt->pvt;
1022 struct ast_frame *f;
1024 ast_log(LOG_DEBUG, "Connection closed, error: %s\n", strerror(pvt->error));
1027 f = ast_fr_fdread(pvt->pipe[0]);
1029 if ((f->frametype == AST_FRAME_CONTROL) &&
1030 (f->subclass == AST_CONTROL_ANSWER))
1031 c->state = AST_STATE_UP;
1036 static int iax_answer(struct ast_channel *c)
1038 struct chan_iax_pvt *pvt = c->pvt->pvt;
1040 ast_log(LOG_DEBUG, "Answering\n");
1041 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1044 static int iax_write(struct ast_channel *c, struct ast_frame *f);
1046 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state)
1048 struct ast_channel *tmp;
1049 tmp = ast_channel_alloc();
1051 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s:%d]/%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port), i->callno);
1053 tmp->fd = i->pipe[0];
1054 /* We can support any format by default, until we get restricted */
1055 tmp->nativeformats = iax_capability;
1057 tmp->pvt->send_digit = iax_digit;
1058 tmp->pvt->send_text = iax_sendtext;
1059 tmp->pvt->call = iax_call;
1060 tmp->pvt->hangup = iax_hangup;
1061 tmp->pvt->answer = iax_answer;
1062 tmp->pvt->read = iax_read;
1063 tmp->pvt->write = iax_write;
1064 if (strlen(i->callerid))
1065 tmp->callerid = strdup(i->callerid);
1066 if (strlen(i->dnid))
1067 tmp->dnid = strdup(i->dnid);
1068 strncpy(tmp->context, i->context, sizeof(tmp->context));
1069 strncpy(tmp->exten, i->exten, sizeof(tmp->exten));
1072 pthread_mutex_lock(&usecnt_lock);
1074 pthread_mutex_unlock(&usecnt_lock);
1075 ast_update_use_count();
1076 if (state != AST_STATE_DOWN) {
1077 if (ast_pbx_start(tmp)) {
1078 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1087 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
1091 if (!p->offset.tv_sec && !p->offset.tv_usec)
1092 gettimeofday(&p->offset, NULL);
1093 /* If the timestamp is specified, just send it as is */
1096 gettimeofday(&tv, NULL);
1097 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
1098 /* We never send the same timestamp twice, so fudge a little if we must */
1099 if (ms <= p->lastsent)
1100 ms = p->lastsent + 1;
1105 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
1107 /* Returns where in "receive time" we are */
1110 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
1111 gettimeofday(&p->rxcore, NULL);
1112 gettimeofday(&tv, NULL);
1113 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
1116 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno)
1118 /* Queue a packet for delivery on a given private structure. Use "ts" for
1119 timestamp, or calculate if ts is 0 */
1120 struct ast_iax_full_hdr *fh;
1121 struct ast_iax_mini_hdr *mh;
1122 struct ast_iax_frame *fr;
1124 unsigned int lastsent;
1125 /* Allocate an ast_iax_frame */
1126 fr = malloc(sizeof(struct ast_iax_frame));
1128 ast_log(LOG_WARNING, "Out of memory\n");
1132 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
1136 /* Isolate our frame for transmission */
1137 fr->f = ast_frdup(f);
1139 ast_log(LOG_WARNING, "Out of memory\n");
1143 if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
1144 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
1148 lastsent = pvt->lastsent;
1149 fr->ts = calc_timestamp(pvt, ts);
1151 ast_log(LOG_WARNING, "timestamp is 0?\n");
1154 fr->callno = pvt->callno;
1155 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
1156 /* High two bits of timestamp differ */ ||
1157 (fr->f->frametype != AST_FRAME_VOICE)
1158 /* or not a voice frame */ ||
1159 (fr->f->subclass != pvt->svoiceformat)
1160 /* or new voice format */ ) {
1161 /* We need a full frame */
1165 fr->seqno = pvt->oseqno++;
1166 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
1167 fh->callno = htons(fr->callno | AST_FLAG_FULL);
1168 fh->ts = htonl(fr->ts);
1169 fh->seqno = htons(fr->seqno);
1170 fh->type = fr->f->frametype & 0xFF;
1171 fh->csub = compress_subclass(fr->f->subclass);
1173 fh->subclasshigh = (fr->f->subclass & 0xFF0000) >> 16;
1174 fh->subclasslow = htons(fr->f->subclass & 0xFFFF);
1176 fh->dcallno = htons(pvt->peercallno);
1177 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
1180 /* Retry after 2x the ping time has passed */
1181 fr->retrytime = pvt->pingtime * 2;
1182 if (fr->retrytime < MIN_RETRY_TIME)
1183 fr->retrytime = MIN_RETRY_TIME;
1184 if (fr->retrytime > MAX_RETRY_TIME)
1185 fr->retrytime = MAX_RETRY_TIME;
1186 /* Acks' don't get retried */
1187 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
1189 if (f->frametype == AST_FRAME_VOICE) {
1190 pvt->svoiceformat = f->subclass;
1192 res = iax_transmit(fr);
1194 /* Mini-frames have no sequence number */
1196 /* Mini frame will do */
1197 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
1198 mh->callno = htons(fr->callno);
1199 mh->ts = htons(fr->ts & 0xFFFF);
1200 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
1203 res = iax_transmit(fr);
1210 static int iax_show_users(int fd, int argc, char *argv[])
1212 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
1213 struct iax_user *user;
1215 return RESULT_SHOWUSAGE;
1216 pthread_mutex_lock(&userl.lock);
1217 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
1218 for(user=userl.users;user;user=user->next) {
1219 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
1220 user->contexts ? user->contexts->context : context,
1221 user->ha ? "Yes" : "No");
1223 pthread_mutex_unlock(&userl.lock);
1224 return RESULT_SUCCESS;
1228 static int iax_show_peers(int fd, int argc, char *argv[])
1230 #define FORMAT2 "%-15.15s %-15.15s %-15.15s %-15.15s %s\n"
1231 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %d\n"
1232 struct iax_peer *peer;
1234 return RESULT_SHOWUSAGE;
1235 pthread_mutex_lock(&peerl.lock);
1236 ast_cli(fd, FORMAT2, "Name", "Username", "Host", "Mask", "Port");
1237 for (peer = peerl.peers;peer;peer = peer->next) {
1239 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm));
1240 ast_cli(fd, FORMAT, peer->name,
1241 peer->username ? peer->username : "(Any)",
1242 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Any)",
1244 ntohs(peer->addr.sin_port));
1246 pthread_mutex_unlock(&peerl.lock);
1247 return RESULT_SUCCESS;
1252 static int iax_show_channels(int fd, int argc, char *argv[])
1254 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
1255 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %d\n"
1258 return RESULT_SHOWUSAGE;
1259 pthread_mutex_lock(&iaxs_lock);
1260 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
1261 for (x=0;x<AST_IAX_MAX_CALLS;x++)
1263 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
1264 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
1265 iaxs[x]->callno, iaxs[x]->peercallno,
1266 iaxs[x]->oseqno, iaxs[x]->iseqno,
1269 iaxs[x]->voiceformat);
1270 pthread_mutex_unlock(&iaxs_lock);
1271 return RESULT_SUCCESS;
1276 static char show_users_usage[] =
1277 "Usage: iax show users\n"
1278 " Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
1280 static char show_channels_usage[] =
1281 "Usage: iax show channels\n"
1282 " Lists all currently active IAX channels.\n";
1284 static char show_peers_usage[] =
1285 "Usage: iax show peers\n"
1286 " Lists all known IAX peers.\n";
1288 static struct ast_cli_entry cli_show_users =
1289 { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
1290 static struct ast_cli_entry cli_show_channels =
1291 { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
1292 static struct ast_cli_entry cli_show_peers =
1293 { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
1295 static int iax_write(struct ast_channel *c, struct ast_frame *f)
1297 struct chan_iax_pvt *i = c->pvt->pvt;
1298 /* If there's an outstanding error, return failure now */
1300 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
1303 /* Don't waste bandwidth sending null frames */
1304 if (f->frametype == AST_FRAME_NULL)
1306 /* Simple, just queue for transmission */
1307 return iax_send(i, f, 0, -1);
1310 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
1314 f.subclass = command;
1315 f.datalen = datalen;
1319 f.src = __FUNCTION__;
1321 return iax_send(i, &f, ts, seqno);
1324 static int apply_context(struct iax_context *con, char *context)
1327 if (!strcmp(con->context, context))
1334 static int apply_ha(struct iax_ha *ha, struct sockaddr_in *sin)
1336 /* Start optimistic */
1337 int res = IAX_SENSE_ALLOW;
1339 /* For each rule, if this address and the netmask = the net address
1340 apply the current rule */
1341 if ((sin->sin_addr.s_addr & ha->netmask.s_addr) == (ha->netaddr.s_addr))
1348 static int iax_getformats(int callno, char *orequest)
1352 strncpy(request, orequest, sizeof(request));
1353 var = strtok(request, ";");
1355 value = strchr(var, '=');
1359 if (!strcmp(var, "formats")) {
1360 iaxs[callno]->peerformats = atoi(value);
1362 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
1364 var = strtok(NULL, ";");
1369 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
1371 /* Start pessimistic */
1375 struct iax_user *user;
1377 strncpy(request, orequest, sizeof(request));
1380 var = strtok(request, ";");
1382 value = strchr(var, '=');
1386 if (!strcmp(var, "exten"))
1387 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten));
1388 else if (!strcmp(var, "callerid"))
1389 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid));
1390 else if (!strcmp(var, "dnid"))
1391 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid));
1392 else if (!strcmp(var, "context"))
1393 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context));
1394 else if (!strcmp(var, "username"))
1395 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username));
1396 else if (!strcmp(var, "formats"))
1397 iaxs[callno]->peerformats = atoi(value);
1398 else if (!strcmp(var, "version"))
1399 version = atoi(value);
1401 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
1403 var = strtok(NULL, ";");
1405 if (version > AST_IAX_PROTO_VERSION) {
1406 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
1407 inet_ntoa(sin->sin_addr), version);
1410 pthread_mutex_lock(&userl.lock);
1411 /* Search the userlist for a compatible entry, and fill in the rest */
1414 if ((!strlen(iaxs[callno]->username) || /* No username specified */
1415 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
1416 && (apply_ha(user->ha, sin) == IAX_SENSE_ALLOW) /* Access is permitted from this IP */
1417 && (!strlen(iaxs[callno]->context) || /* No context specified */
1418 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
1419 /* We found our match (use the first) */
1421 /* Store the requested username if not specified */
1422 if (!strlen(iaxs[callno]->username))
1423 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username));
1424 /* And use the default context */
1425 if (!strlen(iaxs[callno]->context)) {
1427 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context));
1429 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context));
1431 /* Copy the secret */
1432 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret));
1433 /* And the permitted authentication methods */
1434 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods));
1440 pthread_mutex_unlock(&userl.lock);
1444 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
1446 struct ast_iax_full_hdr fh;
1447 fh.callno = htons(src | AST_FLAG_FULL);
1448 fh.dcallno = htons(dst);
1451 fh.type = AST_FRAME_IAX;
1452 fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
1454 ast_log(LOG_DEBUG, "Raw Hangup\n");
1455 return sendto(netsocket, &fh, sizeof(fh), 0, sin, sizeof(*sin));
1458 static int authenticate_request(struct chan_iax_pvt *p)
1460 char requeststr[256] = "";
1461 MYSNPRINTF "methods=%s;", p->methods);
1462 if (strstr(p->methods, "md5")) {
1463 /* Build the challenge */
1465 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
1466 MYSNPRINTF "challenge=%s;", p->challenge);
1468 MYSNPRINTF "username=%s;", p->username);
1469 if (strlen(requeststr))
1470 requeststr[strlen(requeststr) - 1] = '\0';
1471 return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
1474 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
1476 char requeststr[256] = "";
1477 char *var, *value, request[256];
1478 char md5secret[256] = "";
1479 char secret[256] = "";
1483 if (!(p->state & IAX_STATE_AUTHENTICATED))
1485 strncpy(request, orequest, sizeof(request));
1486 var = strtok(request, ";");
1488 value = strchr(var, '=');
1492 if (!strcmp(var, "secret"))
1493 strncpy(secret, value, sizeof(secret));
1494 else if (!strcmp(var, "md5secret"))
1495 strncpy(md5secret, value, sizeof(md5secret));
1497 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
1499 var = strtok(NULL, ";");
1501 if (strstr(p->methods, "md5")) {
1502 struct MD5Context md5;
1503 unsigned char digest[16];
1505 MD5Update(&md5, p->challenge, strlen(p->challenge));
1506 MD5Update(&md5, p->secret, strlen(p->secret));
1507 MD5Final(digest, &md5);
1508 /* If they support md5, authenticate with it. */
1510 MYSNPRINTF "%2.2x", digest[x]);
1511 if (!strcasecmp(requeststr, md5secret))
1513 } else if (strstr(p->methods, "plaintext")) {
1514 if (!strcmp(secret, p->secret))
1520 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest)
1522 struct iax_peer *peer;
1523 /* Start pessimistic */
1526 char methods[80] = "";
1527 char requeststr[256] = "";
1530 strncpy(request, orequest, sizeof(request));
1531 var = strtok(request, ";");
1533 value = strchr(var, '=');
1537 if (!strcmp(var, "username"))
1538 strncpy(p->username, value, sizeof(p->username));
1539 else if (!strcmp(var, "challenge"))
1540 strncpy(p->challenge, value, sizeof(p->challenge));
1541 else if (!strcmp(var, "methods"))
1542 strncpy(methods, value, sizeof(methods));
1544 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
1546 var = strtok(NULL, ";");
1548 pthread_mutex_lock(&peerl.lock);
1551 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
1552 /* No peer specified at our end, or this is the peer */
1553 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
1554 /* No username specified in peer rule, or this is the right username */
1555 && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
1556 /* No specified host, or this is our host */
1558 /* We have a match, authenticate it. */
1560 if (strstr(methods, "md5")) {
1561 struct MD5Context md5;
1562 unsigned char digest[16];
1564 MD5Update(&md5, p->challenge, strlen(p->challenge));
1565 MD5Update(&md5, peer->secret, strlen(peer->secret));
1566 MD5Final(digest, &md5);
1567 /* If they support md5, authenticate with it. */
1568 MYSNPRINTF "md5secret=");
1570 MYSNPRINTF "%2.2x", digest[x]);
1572 } else if (strstr(methods, "plaintext")) {
1573 MYSNPRINTF "secret=%s;", peer->secret);
1576 if (strlen(requeststr))
1577 requeststr[strlen(requeststr)-1] = '\0';
1579 res = send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREP, 0, requeststr, strlen(requeststr) + 1, -1);
1584 pthread_mutex_unlock(&peerl.lock);
1588 static int socket_read(int *id, int fd, short events, void *cbdata)
1590 struct sockaddr_in sin;
1592 int new = NEW_PREVENT;
1595 int len = sizeof(sin);
1597 struct ast_iax_full_hdr *fh = (struct ast_iax_full_hdr *)buf;
1598 struct ast_iax_mini_hdr *mh = (struct ast_iax_mini_hdr *)buf;
1599 struct ast_iax_frame fr, *cur;
1601 struct ast_channel *c;
1602 res = recvfrom(netsocket, buf, sizeof(buf), 0, &sin, &len);
1604 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
1608 if (res < sizeof(struct ast_iax_mini_hdr)) {
1609 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, sizeof(struct ast_iax_mini_hdr));
1612 if (ntohs(mh->callno) & AST_FLAG_FULL) {
1613 /* Get the destination call number */
1614 dcallno = ntohs(fh->dcallno);
1615 /* Retrieve the type and subclass */
1616 f.frametype = fh->type;
1617 f.subclass = uncompress_subclass(fh->csub);
1619 f.subclass = fh->subclasshigh << 16;
1620 f.subclass += ntohs(fh->subclasslow);
1622 if ((f.frametype == AST_FRAME_IAX) && (f.subclass == AST_IAX_COMMAND_NEW))
1625 pthread_mutex_lock(&iaxs_lock);
1626 fr.callno = find_callno(ntohs(mh->callno) & ~AST_FLAG_FULL, dcallno, &sin, new);
1627 if ((fr.callno < 0) || !iaxs[fr.callno]) {
1628 /* A call arrived for a non-existant destination. Unless it's an "inval"
1629 frame, reply with an inval */
1630 if (ntohs(mh->callno) & AST_FLAG_FULL) {
1631 /* We can only raw hangup control frames */
1632 if ((f.subclass != AST_IAX_COMMAND_INVAL) || (f.frametype != AST_FRAME_IAX))
1633 raw_hangup(&sin, ntohs(fh->dcallno), ntohs(mh->callno));
1635 pthread_mutex_unlock(&iaxs_lock);
1638 iaxs[fr.callno]->peercallno = ntohs(mh->callno) & ~AST_FLAG_FULL;
1639 if (ntohs(mh->callno) & AST_FLAG_FULL) {
1641 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", ntohs(fh->seqno), f.frametype, f.subclass);
1642 /* Check if it's out of order (and not an ACK or INVAL) */
1643 fr.seqno = ntohs(fh->seqno);
1644 if (iaxs[fr.callno]->iseqno != fr.seqno) {
1646 ((f.subclass != AST_IAX_COMMAND_ACK) && (f.subclass != AST_IAX_COMMAND_INVAL)) ||
1647 (f.frametype != AST_FRAME_IAX)) {
1648 /* If it's not an ACK packet, it's out of order. */
1650 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
1651 iaxs[fr.callno]->iseqno, fr.seqno, f.frametype, f.subclass);
1652 if (iaxs[fr.callno]->iseqno > fr.seqno) {
1653 /* If we've already seen it, ack it XXX There's a border condition here XXX */
1654 if ((f.frametype != AST_FRAME_IAX) ||
1655 ((f.subclass != AST_IAX_COMMAND_ACK) && (f.subclass != AST_IAX_COMMAND_INVAL))) {
1657 ast_log(LOG_DEBUG, "Acking anyway\n");
1658 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.seqno);
1661 pthread_mutex_unlock(&iaxs_lock);
1665 /* Increment unless it's an ACK */
1666 if ((f.subclass != AST_IAX_COMMAND_ACK) ||
1667 (f.frametype != AST_FRAME_IAX))
1668 iaxs[fr.callno]->iseqno++;
1671 if (res < sizeof(struct ast_iax_full_hdr)) {
1672 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, sizeof(struct ast_iax_full_hdr));
1673 pthread_mutex_unlock(&iaxs_lock);
1676 f.datalen = res - sizeof(struct ast_iax_full_hdr);
1678 f.data = buf + sizeof(struct ast_iax_full_hdr);
1681 fr.ts = ntohl(fh->ts);
1682 /* Unless this is an ACK or INVAL frame, ack it */
1683 if ((f.frametype != AST_FRAME_IAX) ||
1684 ((f.subclass != AST_IAX_COMMAND_ACK) && (f.subclass != AST_IAX_COMMAND_INVAL)))
1685 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACK, fr.ts, NULL, 0,fr.seqno);
1686 if (f.frametype == AST_FRAME_VOICE)
1687 iaxs[fr.callno]->voiceformat = f.subclass;
1688 if (f.frametype == AST_FRAME_IAX) {
1689 /* Handle the IAX pseudo frame itself */
1691 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
1692 switch(f.subclass) {
1693 case AST_IAX_COMMAND_ACK:
1694 /* Ack the packet with the given timestamp */
1695 pthread_mutex_lock(&iaxq.lock);
1696 for (cur = iaxq.head; cur ; cur = cur->next) {
1697 /* If it's our call, and our timestamp, mark -1 retries */
1698 if ((fr.callno == cur->callno) && (fr.seqno == cur->seqno))
1701 pthread_mutex_unlock(&iaxq.lock);
1703 case AST_IAX_COMMAND_NEW:
1704 ((char *)f.data)[f.datalen] = '\0';
1705 if (check_access(fr.callno, &sin, f.data, f.datalen)) {
1706 /* They're not allowed on */
1707 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "No authority found", strlen("No authority found"), -1);
1708 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s'\n", inet_ntoa(sin.sin_addr), f.data);
1709 /* XXX Not guaranteed to work, but probably does XXX */
1710 pthread_mutex_lock(&iaxq.lock);
1711 send_packet(iaxq.tail);
1712 pthread_mutex_unlock(&iaxq.lock);
1713 iax_destroy(fr.callno);
1716 if (!strlen(iaxs[fr.callno]->secret)) {
1717 /* No authentication required, let them in */
1718 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACCEPT, 0, NULL, 0, -1);
1719 if (option_verbose > 2)
1720 ast_verbose(VERBOSE_PREFIX_3 "Accepting unauthenticated call from %s, formats = %d\n", inet_ntoa(sin.sin_addr), iaxs[fr.callno]->peerformats);
1721 iaxs[fr.callno]->state |= IAX_STATE_STARTED;
1722 if(!(c = ast_iax_new(iaxs[fr.callno], AST_STATE_RING)))
1723 iax_destroy(fr.callno);
1725 c->nativeformats = iaxs[fr.callno]->peerformats;
1728 authenticate_request(iaxs[fr.callno]);
1729 iaxs[fr.callno]->state |= IAX_STATE_AUTHENTICATED;
1731 case AST_IAX_COMMAND_HANGUP:
1733 iaxs[fr.callno]->error = ENOTCONN;
1735 iax_destroy(fr.callno);
1737 case AST_IAX_COMMAND_REJECT:
1739 ((char *)f.data)[f.datalen] = '\0';
1740 ast_log(LOG_WARNING, "Call rejected by %s: %s\n", inet_ntoa(iaxs[fr.callno]->addr.sin_addr), f.data);
1741 iaxs[fr.callno]->error = EPERM;
1742 iax_destroy(fr.callno);
1744 case AST_IAX_COMMAND_ACCEPT:
1746 ((char *)f.data)[f.datalen]='\0';
1747 iax_getformats(fr.callno, (char *)f.data);
1749 iaxs[fr.callno]->peerformats = iax_capability;
1751 if (option_verbose > 2)
1752 ast_verbose(VERBOSE_PREFIX_3 "Call accepted by %s\n", inet_ntoa(iaxs[fr.callno]->addr.sin_addr));
1753 iaxs[fr.callno]->state |= IAX_STATE_STARTED;
1754 if (iaxs[fr.callno]->owner) {
1755 /* Switch us to use a compatible format */
1756 iaxs[fr.callno]->owner->nativeformats &= iaxs[fr.callno]->peerformats;
1758 if (!iaxs[fr.callno]->owner->nativeformats)
1759 iaxs[fr.callno]->owner->nativeformats = iaxs[fr.callno]->peerformats & iax_capability;
1760 if (!iaxs[fr.callno]->owner->nativeformats) {
1761 ast_log(LOG_WARNING, "Unable to negotiate a common format with the peer.");
1762 iaxs[fr.callno]->error = EBADE;
1763 iax_destroy(fr.callno);
1765 if (option_verbose > 2)
1766 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %d\n", iaxs[fr.callno]->owner->nativeformats);
1771 case AST_IAX_COMMAND_PING:
1772 /* Send back a pong packet with the original timestamp */
1773 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_PONG, fr.ts, NULL, 0, -1);
1775 case AST_IAX_COMMAND_PONG:
1776 iaxs[fr.callno]->pingtime = calc_timestamp(iaxs[fr.callno], 0) - fr.ts;
1778 case AST_IAX_COMMAND_LAGRQ:
1779 case AST_IAX_COMMAND_LAGRP:
1780 /* A little strange -- We have to actually go through the motions of
1781 delivering the packet. In the very last step, it will be properly
1782 handled by do_deliver */
1783 snprintf(src, sizeof(src), "LAGRQ-IAX/%s/%d", inet_ntoa(sin.sin_addr),fr.callno);
1789 schedule_delivery(iaxfrdup2(&fr, 0));
1791 case AST_IAX_COMMAND_AUTHREQ:
1792 ((char *)f.data)[f.datalen] = '\0';
1793 if (authenticate_reply(iaxs[fr.callno], &iaxs[fr.callno]->addr, (char *)f.data)) {
1794 ast_log(LOG_WARNING,
1795 "I don't know how to authenticate %s to %s\n",
1796 f.data, inet_ntoa(iaxs[fr.callno]->addr.sin_addr));
1797 iax_destroy(fr.callno);
1800 case AST_IAX_COMMAND_AUTHREP:
1801 ((char *)f.data)[f.datalen] = '\0';
1802 if (authenticate_verify(iaxs[fr.callno], (char *)f.data)) {
1803 ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", inet_ntoa(iaxs[fr.callno]->addr.sin_addr), iaxs[fr.callno]->username);
1804 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_REJECT, 0, "No authority found", strlen("No authority found"), -1);
1805 /* XXX Not guaranteed to work, but probably does XXX */
1806 pthread_mutex_lock(&iaxq.lock);
1807 send_packet(iaxq.tail);
1808 pthread_mutex_unlock(&iaxq.lock);
1809 iax_destroy(fr.callno);
1812 if (option_verbose > 2)
1813 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s, formats = %dn", inet_ntoa(sin.sin_addr), iaxs[fr.callno]->peerformats);
1814 /* Authentication is fine, go ahead */
1815 send_command(iaxs[fr.callno], AST_FRAME_IAX, AST_IAX_COMMAND_ACCEPT, 0, NULL, 0, -1);
1816 iaxs[fr.callno]->state |= IAX_STATE_STARTED;
1817 if(!(c = ast_iax_new(iaxs[fr.callno], AST_STATE_RING)))
1818 iax_destroy(fr.callno);
1820 c->nativeformats = iaxs[fr.callno]->peerformats;
1822 case AST_IAX_COMMAND_INVAL:
1823 iaxs[fr.callno]->error = ENOTCONN;
1824 iax_destroy(fr.callno);
1826 ast_log(LOG_DEBUG, "Destroying call %d\n", fr.callno);
1829 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr.callno, iaxs[fr.callno]->peercallno);
1831 /* Don't actually pass these frames along */
1832 pthread_mutex_unlock(&iaxs_lock);
1837 f.frametype = AST_FRAME_VOICE;
1838 if (iaxs[fr.callno]->voiceformat > 0)
1839 f.subclass = iaxs[fr.callno]->voiceformat;
1841 ast_log(LOG_WARNING, "Received mini frame before first full voice frame\n ");
1842 pthread_mutex_unlock(&iaxs_lock);
1845 f.datalen = res - sizeof(struct ast_iax_mini_hdr);
1846 if (f.datalen < 0) {
1847 ast_log(LOG_WARNING, "Datalen < 0?\n");
1848 pthread_mutex_unlock(&iaxs_lock);
1852 f.data = buf + sizeof(struct ast_iax_mini_hdr);
1855 fr.ts = (iaxs[fr.callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
1857 /* Don't pass any packets until we're started */
1858 if (!(iaxs[fr.callno]->state & IAX_STATE_STARTED)) {
1859 pthread_mutex_unlock(&iaxs_lock);
1863 snprintf(src, sizeof(src), "IAX/%s/%d", inet_ntoa(sin.sin_addr),fr.callno);
1868 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
1869 f.timelen = get_timelen(&f);
1873 /* If this is our most recent packet, use it as our basis for timestamping */
1874 if (iaxs[fr.callno]->last < fr.ts) {
1875 iaxs[fr.callno]->last = fr.ts;
1879 ast_log(LOG_DEBUG, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr.ts, iaxs[fr.callno]->last);
1882 schedule_delivery(iaxfrdup2(&fr, 0));
1883 /* Always run again */
1884 pthread_mutex_unlock(&iaxs_lock);
1888 static void free_ha(struct iax_ha *ha)
1898 static void free_context(struct iax_context *con)
1900 struct iax_context *conl;
1908 static struct ast_channel *iax_request(char *type, int format, void *data)
1913 struct sockaddr_in sin;
1916 struct ast_channel *c;
1917 strncpy(s, (char *)data, sizeof(s));
1920 st = strtok(NULL, "@");
1923 /* Populate our address from the given */
1924 if (create_addr(&sin, st)) {
1925 ast_log(LOG_WARNING, "Unable to assign address for %s\n", st);
1928 pthread_mutex_lock(&iaxs_lock);
1929 callno = find_callno(-1, -1, &sin, NEW_FORCE);
1931 ast_log(LOG_WARNING, "Unable to create call\n");
1934 c = ast_iax_new(iaxs[callno], AST_STATE_DOWN);
1936 /* Choose a format we can live with */
1937 if (c->nativeformats & format)
1938 c->nativeformats &= format;
1940 native = c->nativeformats;
1942 res = ast_translator_best_choice(&fmt, &native);
1944 ast_log(LOG_WARNING, "Unable to create translator path for %d to %d on %s\n", c->nativeformats, fmt, c->name);
1948 c->nativeformats = native;
1951 pthread_mutex_unlock(&iaxs_lock);
1955 static void *network_thread(void *ignore)
1957 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
1958 from the network, and queue them for delivery to the channels */
1960 struct ast_iax_frame *f, *freeme;
1961 /* Establish I/O callback for socket read */
1962 ast_io_add(io, netsocket, socket_read, AST_IO_IN, NULL);
1963 pthread_mutex_lock(&iaxs_lock);
1965 /* Go through the queue, sending messages which have not yet been
1966 sent, and scheduling retransmissions if appropriate */
1967 pthread_mutex_lock(&iaxq.lock);
1973 /* Send a copy immediately */
1974 if (iaxs[f->callno]) {
1977 if (f->retries < 0) {
1978 /* This is not supposed to be retransmitted */
1980 f->prev->next = f->next;
1982 iaxq.head = f->next;
1984 f->next->prev = f->prev;
1986 iaxq.tail = f->prev;
1988 /* Free the frame */
1990 /* Free the iax frame */
1993 /* We need reliable delivery. Schedule a retransmission */
1995 ast_sched_add(sched, f->retrytime, attempt_transmit, f);
2002 pthread_mutex_unlock(&iaxq.lock);
2003 pthread_mutex_unlock(&iaxs_lock);
2004 res = ast_sched_wait(sched);
2005 res = ast_io_wait(io, res);
2006 pthread_mutex_lock(&iaxs_lock);
2008 ast_sched_runq(sched);
2013 static int start_network_thread()
2015 return pthread_create(&netthreadid, NULL, network_thread, NULL);
2018 static struct iax_context *build_context(char *context)
2020 struct iax_context *con = malloc(sizeof(struct iax_context));
2022 strncpy(con->context, context, sizeof(con->context));
2028 static struct iax_ha *build_ha(char *sense, char *stuff)
2030 struct iax_ha *ha = malloc(sizeof(struct iax_ha));
2034 nm = strtok(NULL, "/");
2036 nm = "255.255.255.255";
2037 if (!inet_aton(stuff, &ha->netaddr)) {
2038 ast_log(LOG_WARNING, "%s not a valid IP\n", stuff);
2042 if (!inet_aton(nm, &ha->netmask)) {
2043 ast_log(LOG_WARNING, "%s not a valid netmask\n", nm);
2047 ha->netaddr.s_addr &= ha->netmask.s_addr;
2048 if (!strcasecmp(sense, "a")) {
2049 ha->sense = IAX_SENSE_ALLOW;
2051 ha->sense = IAX_SENSE_DENY;
2058 static struct iax_peer *build_peer(char *name, struct ast_variable *v)
2060 struct iax_peer *peer;
2063 peer = malloc(sizeof(struct iax_peer));
2065 memset(peer, 0, sizeof(struct iax_peer));
2066 strncpy(peer->name, name, sizeof(peer->name));
2067 peer->addr.sin_port = htons(AST_DEFAULT_IAX_PORTNO);
2069 if (!strcasecmp(v->name, "secret"))
2070 strncpy(peer->secret, v->value, sizeof(peer->secret));
2071 else if (!strcasecmp(v->name, "host")) {
2072 if (!strcasecmp(v->value, "dynamic")) {
2073 /* They'll register with us */
2075 memset(&peer->addr.sin_addr, 0, 4);
2078 hp = gethostbyname(v->value);
2080 memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
2082 ast_log(LOG_WARNING, "Unable to lookup '%s'\n", v->value);
2087 inet_aton("255.255.255.255", &peer->mask);
2090 else if (!strcasecmp(v->name, "mask")) {
2092 inet_aton(v->value, &peer->mask);
2093 } else if (!strcasecmp(v->name, "port"))
2094 peer->addr.sin_port = htons(atoi(v->value));
2095 else if (!strcasecmp(v->name, "username"))
2096 strncpy(peer->username, v->value, sizeof(peer->username));
2103 static struct iax_user *build_user(char *name, struct ast_variable *v)
2105 struct iax_user *user;
2106 struct iax_context *con, *conl = NULL;
2107 struct iax_ha *ha, *hal = NULL;
2108 user = (struct iax_user *)malloc(sizeof(struct iax_user));
2110 memset(user, 0, sizeof(struct iax_user));
2111 strncpy(user->name, name, sizeof(user->name));
2113 if (!strcasecmp(v->name, "context")) {
2114 con = build_context(v->value);
2119 user->contexts = con;
2122 } else if (!strcasecmp(v->name, "allow") ||
2123 !strcasecmp(v->name, "deny")) {
2124 ha = build_ha(v->name, v->value);
2132 } else if (!strcasecmp(v->name, "auth")) {
2133 strncpy(user->methods, v->value, sizeof(user->methods));
2134 } else if (!strcasecmp(v->name, "secret")) {
2135 strncpy(user->secret, v->value, sizeof(user->secret));
2146 struct ast_config *cfg;
2147 struct ast_variable *v;
2148 struct iax_user *user;
2149 struct iax_peer *peer;
2154 struct sockaddr_in sin;
2156 sin.sin_family = AF_INET;
2157 sin.sin_port = ntohs(AST_DEFAULT_IAX_PORTNO);
2158 sin.sin_addr.s_addr = INADDR_ANY;
2160 io = io_context_create();
2161 sched = sched_context_create();
2163 if (!io || !sched) {
2164 ast_log(LOG_ERROR, "Out of memory\n");
2168 pthread_mutex_init(&iaxq.lock, NULL);
2169 pthread_mutex_init(&userl.lock, NULL);
2171 ast_cli_register(&cli_show_users);
2172 ast_cli_register(&cli_show_channels);
2173 ast_cli_register(&cli_show_peers);
2174 ast_cli_register(&cli_set_jitter);
2175 #ifdef IAX_SIMULATOR
2176 ast_cli_register(&delay_cli);
2177 ast_cli_register(&deviation_cli);
2178 ast_cli_register(&reliability_cli);
2179 ast_cli_register(&sim_show_cli);
2181 cfg = ast_load(config);
2184 ast_log(LOG_ERROR, "Unable to load config %s\n", config);
2187 v = ast_variable_browse(cfg, "general");
2189 if (!strcasecmp(v->name, "port"))
2190 sin.sin_port = ntohs(atoi(v->value));
2191 else if (!strcasecmp(v->name, "pingtime"))
2192 ping_time = atoi(v->value);
2193 else if (!strcasecmp(v->name, "maxjitterbuffer"))
2194 maxjitterbuffer = atoi(v->value);
2195 else if (!strcasecmp(v->name, "maxexcessbuffer"))
2196 max_jitter_buffer = atoi(v->value);
2197 else if (!strcasecmp(v->name, "lagrqtime"))
2198 lagrq_time = atoi(v->value);
2199 else if (!strcasecmp(v->name, "dropcount"))
2200 iax_dropcount = atoi(v->value);
2201 else if (!strcasecmp(v->name, "bindaddr"))
2202 inet_aton(v->value, &sin.sin_addr);
2203 else if (!strcasecmp(v->name, "jitterbuffer"))
2204 use_jitterbuffer = ast_true(v->value);
2205 else if (!strcasecmp(v->name, "bandwidth")) {
2206 if (!strcasecmp(v->value, "low")) {
2207 iax_capability = IAX_CAPABILITY_LOWBANDWIDTH;
2208 } else if (!strcasecmp(v->value, "medium")) {
2209 iax_capability = IAX_CAPABILITY_MEDBANDWIDTH;
2210 } else if (!strcasecmp(v->value, "high")) {
2211 iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
2213 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
2214 } else if (!strcasecmp(v->name, "allow")) {
2215 format = ast_getformatbyname(v->value);
2217 ast_log(LOG_WARNING, "Cannot allow unknown format '%s'\n", v->value);
2219 iax_capability |= format;
2220 } else if (!strcasecmp(v->name, "disallow")) {
2221 format = ast_getformatbyname(v->value);
2223 ast_log(LOG_WARNING, "Cannot disallow unknown format '%s'\n", v->value);
2225 iax_capability &= ~format;
2229 cat = ast_category_browse(cfg, NULL);
2231 if (strcasecmp(cat, "general")) {
2232 utype = ast_variable_retrieve(cfg, cat, "type");
2234 if (!strcasecmp(utype, "user")) {
2235 user = build_user(cat, ast_variable_browse(cfg, cat));
2237 pthread_mutex_lock(&userl.lock);
2238 user->next = userl.users;
2240 pthread_mutex_unlock(&userl.lock);
2242 } else if (!strcasecmp(utype, "peer")) {
2243 peer = build_peer(cat, ast_variable_browse(cfg, cat));
2245 pthread_mutex_lock(&peerl.lock);
2246 peer->next = peerl.peers;
2248 pthread_mutex_unlock(&peerl.lock);
2251 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config);
2254 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
2256 cat = ast_category_browse(cfg, cat);
2259 if (ast_channel_register(type, tdesc, iax_capability, iax_request)) {
2260 ast_log(LOG_ERROR, "Unable to register channel class %s\n", type);
2265 /* Make a UDP socket */
2266 netsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
2268 if (netsocket < 0) {
2269 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
2272 if (bind(netsocket, &sin, sizeof(sin))) {
2273 ast_log(LOG_ERROR, "Unable to bind to %s port %d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2278 res = start_network_thread();
2279 if (option_verbose > 1)
2280 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening on %s port %d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2282 ast_log(LOG_ERROR, "Unable to start network thread\n");
2295 struct iax_user *user, *userlast;
2296 struct iax_peer *peer, *peerlast;
2298 /* Cancel the network thread, close the net socket */
2299 pthread_cancel(netthreadid);
2300 pthread_join(netthreadid, NULL);
2302 for (x=0;x<AST_IAX_MAX_CALLS;x++)
2305 ast_cli_unregister(&cli_show_users);
2306 ast_cli_unregister(&cli_show_channels);
2307 ast_cli_unregister(&cli_show_peers);
2308 ast_cli_unregister(&cli_set_jitter);
2309 #ifdef IAX_SIMULATOR
2310 ast_cli_unregister(&delay_cli);
2311 ast_cli_unregister(&deviation_cli);
2312 ast_cli_unregister(&reliability_cli);
2313 ast_cli_unregister(&sim_show_cli);
2315 for (user=userl.users;user;) {
2317 free_context(user->contexts);
2322 for (peer=peerl.peers;peer;) {
2333 pthread_mutex_lock(&usecnt_lock);
2335 pthread_mutex_unlock(&usecnt_lock);
2341 return ASTERISK_GPL_KEY;