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/lock.h>
15 #include <asterisk/frame.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <arpa/inet.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netinet/in_systm.h>
36 #include <netinet/ip.h>
38 #include <sys/signal.h>
48 #include <mysql/mysql.h>
54 #define IPTOS_MINCOST 0x02
58 * Uncomment to try experimental IAX bridge optimization,
59 * designed to reduce latency when IAX calls cannot
63 #define BRIDGE_OPTIMIZATION
66 #define DEFAULT_RETRY_TIME 1000
67 #define MEMORY_SIZE 100
68 #define DEFAULT_DROP 3
72 /* Sample over last 100 units to determine historic jitter */
76 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
78 static char mydbuser[80];
79 static char mydbpass[80];
80 static char mydbhost[80];
81 static char mydbname[80];
84 static char *desc = "Inter Asterisk eXchange";
85 static char *tdesc = "Inter Asterisk eXchange Drver";
86 static char *type = "IAX";
88 static char context[80] = "default";
90 static int max_retries = 4;
91 static int ping_time = 20;
92 static int lagrq_time = 10;
93 static int nextcallno = 0;
94 static int maxjitterbuffer=3000;
96 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
98 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
100 static int netsocket = -1;
104 static int expirey = AST_DEFAULT_REG_EXPIRE;
107 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
109 int (*iax_regfunk)(char *username, int onoff) = NULL;
112 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
114 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
115 ~AST_FORMAT_SLINEAR & \
119 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
120 ~AST_FORMAT_ADPCM & \
123 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
127 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
128 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
129 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
131 static struct io_context *io;
132 static struct sched_context *sched;
134 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
136 static int iax_dropcount = DEFAULT_DROP;
138 static int use_jitterbuffer = 1;
140 static int iaxdebug = 0;
142 static char accountcode[20];
143 static int amaflags = 0;
145 static pthread_t netthreadid;
147 #define IAX_STATE_STARTED (1 << 0)
148 #define IAX_STATE_AUTHENTICATED (1 << 1)
149 #define IAX_STATE_TBD (1 << 2)
152 char context[AST_MAX_EXTENSION];
153 struct iax_context *next;
160 char accountcode[20];
161 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
164 char callerid[AST_MAX_EXTENSION];
166 struct iax_context *contexts;
167 struct iax_user *next;
174 char outkey[80]; /* What key we use to talk to this peer */
175 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
176 struct sockaddr_in addr;
180 /* Dynamic Registration fields */
181 int dynamic; /* If this is a dynamic peer */
182 struct sockaddr_in defaddr; /* Default address if there is one */
184 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
187 /* Suggested caller id if registering */
188 char callerid[AST_MAX_EXTENSION];
189 /* Whether or not to send ANI */
191 int expire; /* Schedule entry for expirey */
192 int expirey; /* How soon to expire */
193 int capability; /* Capability */
194 int delme; /* I need to be deleted */
197 int callno; /* Call number of POKE request */
198 int pokeexpire; /* When to expire poke */
199 int lastms; /* How long last response took (in ms), or -1 for no response */
200 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
203 struct iax_peer *next;
206 #define REG_STATE_UNREGISTERED 0
207 #define REG_STATE_REGSENT 1
208 #define REG_STATE_AUTHSENT 2
209 #define REG_STATE_REGISTERED 3
210 #define REG_STATE_REJECTED 4
211 #define REG_STATE_TIMEOUT 5
212 #define REG_STATE_NOAUTH 6
214 #define TRANSFER_NONE 0
215 #define TRANSFER_BEGIN 1
216 #define TRANSFER_READY 2
217 #define TRANSFER_RELEASED 3
218 #define TRANSFER_PASSTHROUGH 4
220 struct iax_registry {
221 struct sockaddr_in addr; /* Who we connect to for registration purposes */
223 char secret[80]; /* Password or key name in []'s */
225 int expire; /* Sched ID of expiration */
226 int refresh; /* How often to refresh */
228 int callno; /* Associated call number if applicable */
229 struct sockaddr_in us; /* Who the server thinks we are */
230 struct iax_registry *next;
233 static struct iax_registry *registrations;
235 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
236 #define MIN_RETRY_TIME 10
237 #define MAX_RETRY_TIME 10000
238 #define MAX_JITTER_BUFFER 50
240 /* If we have more than this much excess real jitter buffer, srhink it. */
241 static int max_jitter_buffer = MAX_JITTER_BUFFER;
243 struct chan_iax_pvt {
244 /* Pipes for communication. pipe[1] belongs to the
245 network thread (write), and pipe[0] belongs to the individual
247 /* Whether or not we Quelch audio */
249 /* Last received voice format */
251 /* Last sent voice format */
253 /* What we are capable of sending */
255 /* Last received timestamp */
257 /* Last sent timestamp - never send the same timestamp twice in a single call */
258 unsigned int lastsent;
260 unsigned int pingtime;
261 /* Max time for initial response */
264 struct sockaddr_in addr;
265 /* Our call number */
269 /* Peer selected format */
271 /* Peer capability */
273 /* timeval that we base our transmission on */
274 struct timeval offset;
275 /* timeval that we base our delivery on */
276 struct timeval rxcore;
277 /* Historical delivery time */
278 int history[MEMORY_SIZE];
279 /* Current base jitterbuffer */
281 /* Current jitter measure */
283 /* Historic jitter value */
287 /* Error, as discovered by the manager */
289 /* Owner if we have one */
290 struct ast_channel *owner;
291 /* What's our state? */
293 /* Expirey (optional) */
295 /* Next outgoing sequence number */
296 unsigned short oseqno;
297 /* Next incoming sequence number */
298 unsigned short iseqno;
301 /* Default Context */
303 /* Caller ID if available */
305 /* Hidden Caller ID (i.e. ANI) if appropriate */
307 /* Whether or not ani should be transmitted in addition to Caller*ID */
311 /* Requested Extension */
312 char exten[AST_MAX_EXTENSION];
313 /* Expected Username */
315 /* Expected Secret */
317 /* permitted authentication methods */
321 /* Public keys permitted keys for incoming authentication */
323 /* Private key for outgoing authentication */
325 /* Preferred language */
327 /* Associated registry */
328 struct iax_registry *reg;
329 /* Associated peer for poking */
330 struct iax_peer *peerpoke;
332 /* Transferring status */
334 /* Already disconnected */
336 /* Who we are IAX transfering to */
337 struct sockaddr_in transfer;
338 /* What's the new call number for the transfer */
341 /* Status of knowledge of peer ADSI capability */
344 /* Who we are bridged to */
346 int pingid; /* Transmit PING request */
347 int lagid; /* Retransmit lag request */
348 int autoid; /* Auto hangup for Dialplan requestor */
349 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
350 char dproot[AST_MAX_EXTENSION];
351 char accountcode[20];
353 struct iax_dpcache *dpentries;
356 #define DIRECTION_INGRESS 1
357 #define DIRECTION_OUTGRESS 2
359 struct ast_iax_frame {
360 /* Actual, isolated frame */
362 /* /Our/ call number */
364 /* Start of raw frame (outgoing only) */
366 /* Length of frame (outgoing only) */
368 /* How many retries so far? */
370 /* Outgoing relative timestamp (ms) */
372 /* How long to wait before retrying */
374 /* Are we received out of order? */
376 /* Have we been sent at all yet? */
378 /* Packet sequence number */
380 /* Non-zero if should be sent to transfer peer */
382 /* Non-zero if this is the final message */
384 /* Ingress or outgres */
386 /* Retransmission ID */
391 struct ast_iax_frame *next;
392 struct ast_iax_frame *prev;
395 static struct ast_iax_queue {
396 struct ast_iax_frame *head;
397 struct ast_iax_frame *tail;
402 static struct ast_user_list {
403 struct iax_user *users;
407 static struct ast_peer_list {
408 struct iax_peer *peers;
412 /* Extension exists */
413 #define CACHE_FLAG_EXISTS (1 << 0)
414 /* Extension is non-existant */
415 #define CACHE_FLAG_NONEXISTANT (1 << 1)
416 /* Extension can exist */
417 #define CACHE_FLAG_CANEXIST (1 << 2)
418 /* Waiting to hear back response */
419 #define CACHE_FLAG_PENDING (1 << 3)
421 #define CACHE_FLAG_TIMEOUT (1 << 4)
422 /* Request transmitted */
423 #define CACHE_FLAG_TRANSMITTED (1 << 5)
425 #define CACHE_FLAG_UNKNOWN (1 << 6)
427 #define CACHE_FLAG_MATCHMORE (1 << 7)
429 static struct iax_dpcache {
430 char peercontext[AST_MAX_EXTENSION];
431 char exten[AST_MAX_EXTENSION];
433 struct timeval expirey;
437 struct iax_dpcache *next;
438 struct iax_dpcache *peer; /* For linking in peers */
441 static ast_mutex_t dpcache_lock;
444 static void showframe(struct ast_iax_frame *f, struct ast_iax_full_hdr *fhi, int rx, struct sockaddr_in *sin)
498 struct ast_iax_full_hdr *fh;
506 snprintf(retries, sizeof(retries), "%03d", f->retries);
508 strcpy(retries, "N/A");
511 if (!(ntohs(fh->callno) & AST_FLAG_FULL)) {
512 /* Don't mess with mini-frames */
515 if (fh->type > sizeof(frames)/sizeof(char *)) {
516 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
519 class = frames[(int)fh->type];
521 if (fh->type == AST_FRAME_DTMF) {
522 sprintf(subclass2, "%c", fh->csub);
523 subclass = subclass2;
524 } else if (fh->type == AST_FRAME_IAX) {
525 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
526 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
527 subclass = subclass2;
529 subclass = iaxs[(int)fh->csub];
531 } else if (fh->type == AST_FRAME_CONTROL) {
532 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
533 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
534 subclass = subclass2;
536 subclass = cmds[(int)fh->csub];
539 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
540 subclass = subclass2;
543 "%s-Frame Retry[%s] -- Seqno: %2.2d Type: %s Subclass: %s\n",
545 retries, ntohs(fh->seqno), class, subclass);
547 " Timestamp: %05ldms Callno: %5.5d DCall: %5.5d [%s:%d]\n",
549 (short)(ntohs(fh->callno) & ~AST_FLAG_FULL), (short) ntohs(fh->dcallno),
550 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
554 /* XXX We probably should use a mutex when working with this XXX */
555 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
556 static ast_mutex_t iaxsl[AST_IAX_MAX_CALLS];
558 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
559 static int send_command_immediate(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
560 static int send_command_final(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
561 static int send_command_transfer(struct chan_iax_pvt *, char, int, unsigned int, char *, int);
563 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
565 static int send_ping(void *data)
567 int callno = (long)data;
568 /* Ping only if it's real, not if it's bridged */
570 #ifdef BRIDGE_OPTIMIZATION
571 if (iaxs[callno]->bridgecallno < 0)
573 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
579 static int send_lagrq(void *data)
581 int callno = (long)data;
582 /* Ping only if it's real not if it's bridged */
584 #ifdef BRIDGE_OPTIMIZATION
585 if (iaxs[callno]->bridgecallno < 0)
587 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
593 static unsigned char compress_subclass(int subclass)
597 /* If it's 128 or smaller, just return it */
598 if (subclass < AST_FLAG_SC_LOG)
600 /* Otherwise find its power */
601 for (x = 0; x < AST_MAX_SHIFT; x++) {
602 if (subclass & (1 << x)) {
604 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
610 return power | AST_FLAG_SC_LOG;
613 static int uncompress_subclass(unsigned char csub)
615 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
616 if (csub & AST_FLAG_SC_LOG) {
617 /* special case for 'compressed' -1 */
621 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
627 static struct chan_iax_pvt *new_iax(void)
629 struct chan_iax_pvt *tmp;
630 tmp = malloc(sizeof(struct chan_iax_pvt));
632 memset(tmp, 0, sizeof(struct chan_iax_pvt));
634 tmp->peercallno = -1;
635 tmp->transfercallno = -1;
636 tmp->bridgecallno = -1;
641 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
642 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
647 static int get_samples(struct ast_frame *f)
650 switch(f->subclass) {
651 case AST_FORMAT_G723_1:
652 samples = 240 /* XXX Not necessarily true XXX */;
655 samples = 160 * (f->datalen / 33);
657 case AST_FORMAT_ILBC:
658 samples = 240 * (f->datalen / 50);
660 case AST_FORMAT_G729A:
661 samples = 160 * (f->datalen / 20);
663 case AST_FORMAT_SLINEAR:
664 samples = f->datalen / 2;
666 case AST_FORMAT_LPC10:
668 samples += (((char *)(f->data))[7] & 0x1) * 8;
670 case AST_FORMAT_ULAW:
671 samples = f->datalen;
673 case AST_FORMAT_ALAW:
674 samples = f->datalen;
676 case AST_FORMAT_ADPCM:
677 samples = f->datalen *2;
679 case AST_FORMAT_SPEEX:
680 samples = (f->datalen/39)*160;
683 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
688 static int frames = 0;
689 static int iframes = 0;
690 static int oframes = 0;
692 static struct ast_iax_frame *ast_iax_frame_new(int direction)
694 struct ast_iax_frame *fr;
695 fr = malloc(sizeof(struct ast_iax_frame));
697 fr->direction = direction;
700 if (fr->direction == DIRECTION_INGRESS)
708 static void ast_iax_frame_free(struct ast_iax_frame *fr)
710 if (fr->retrans > -1)
711 ast_sched_del(sched, fr->retrans);
712 if (fr->direction == DIRECTION_INGRESS)
714 else if (fr->direction == DIRECTION_OUTGRESS)
717 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
726 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
728 /* Malloc() a copy of a frame */
729 struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
731 memcpy(new, fr, sizeof(struct ast_iax_frame));
732 new->f = ast_frdup(fr->f);
733 /* Copy full header */
735 memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
736 fr->f->data - sizeof(struct ast_iax_full_hdr),
737 sizeof(struct ast_iax_full_hdr));
738 /* Grab new data pointer */
739 new->data = new->f->data - (fr->f->data - fr->data);
744 new->direction = DIRECTION_INGRESS;
750 #define NEW_PREVENT 0
754 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
756 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
757 (cur->addr.sin_port == sin->sin_port)) {
758 /* This is the main host */
759 if ((cur->peercallno == callno) ||
760 ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
761 /* That's us. Be sure we keep track of the peer call number */
765 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
766 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
767 /* We're transferring */
768 if (dcallno == cur->callno)
774 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
779 if (new <= NEW_ALLOW) {
780 /* Look for an existing connection first */
781 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
782 ast_mutex_lock(&iaxsl[x]);
784 /* Look for an exact match */
785 if (match(sin, callno, dcallno, iaxs[x])) {
789 ast_mutex_unlock(&iaxsl[x]);
792 if ((res < 0) && (new >= NEW_ALLOW)) {
793 /* Create a new one */
795 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
797 ast_log(LOG_WARNING, "Unable to accept more calls\n");
800 ast_mutex_lock(&iaxsl[x]);
802 ast_mutex_unlock(&iaxsl[x]);
805 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
806 iaxs[x]->addr.sin_port = sin->sin_port;
807 iaxs[x]->addr.sin_family = sin->sin_family;
808 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
809 iaxs[x]->peercallno = callno;
811 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
812 iaxs[x]->expirey = expirey;
813 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
814 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
815 iaxs[x]->amaflags = amaflags;
816 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
818 ast_log(LOG_WARNING, "Out of resources\n");
827 static int iax_queue_frame(int callno, struct ast_frame *f)
830 /* Assumes lock for callno is already held... */
833 if (!ast_mutex_trylock(&iaxsl[callno])) {
834 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax_queue_frame\n", pass);
837 if (iaxs[callno] && iaxs[callno]->owner) {
838 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
839 /* Avoid deadlock by pausing and trying again */
840 ast_mutex_unlock(&iaxsl[callno]);
842 ast_mutex_lock(&iaxsl[callno]);
844 ast_queue_frame(iaxs[callno]->owner, f, 0);
845 ast_mutex_unlock(&iaxs[callno]->owner->lock);
854 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
856 static int __do_deliver(void *data)
858 /* Just deliver the packet by using queueing. This is called by
859 the IAX thread with the iaxsl lock held. */
860 struct ast_iax_frame *fr = data;
863 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
864 if (fr->f->frametype == AST_FRAME_IAX) {
865 /* We have to treat some of these packets specially because
866 they're LAG measurement packets */
867 if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
868 /* If we got a queued request, build a reply and send it */
869 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
870 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
871 } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
872 /* This is a reply we've been given, actually measure the difference */
873 ts = calc_timestamp(iaxs[fr->callno], 0);
874 iaxs[fr->callno]->lag = ts - fr->ts;
877 iax_queue_frame(fr->callno, fr->f);
880 /* Free the packet */
882 /* And our iax frame */
883 ast_iax_frame_free(fr);
884 /* And don't run again */
888 static int do_deliver(void *data)
890 /* Locking version of __do_deliver */
891 struct ast_iax_frame *fr = data;
892 int callno = fr->callno;
894 ast_mutex_lock(&iaxsl[callno]);
895 res = __do_deliver(data);
896 ast_mutex_unlock(&iaxsl[callno]);
900 static int handle_error(void)
902 /* XXX Ideally we should figure out why an error occured and then abort those
903 rather than continuing to try. Unfortunately, the published interface does
904 not seem to work XXX */
906 struct sockaddr_in *sin;
909 struct sock_extended_err e;
914 m.msg_controllen = sizeof(e);
916 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
918 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
920 if (m.msg_controllen) {
921 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
923 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
925 ast_log(LOG_WARNING, "No address detected??\n");
927 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
934 static int send_packet(struct ast_iax_frame *f)
937 /* Called with iaxsl held */
939 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));
940 /* Don't send if there was an error, but return error instead */
942 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
945 if (!iaxs[f->callno])
947 if (iaxs[f->callno]->error)
952 showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
954 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
955 sizeof(iaxs[f->callno]->transfer));
959 showframe(f, NULL, 0, &iaxs[f->callno]->addr);
961 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
962 sizeof(iaxs[f->callno]->addr));
966 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
974 static int iax_predestroy(int callno)
976 struct ast_channel *c;
977 struct chan_iax_pvt *pvt;
978 ast_mutex_lock(&iaxsl[callno]);
981 ast_mutex_unlock(&iaxsl[callno]);
984 if (!pvt->alreadygone) {
985 /* No more pings or lagrq's */
986 if (pvt->pingid > -1)
987 ast_sched_del(sched, pvt->pingid);
989 ast_sched_del(sched, pvt->lagid);
990 if (pvt->autoid > -1)
991 ast_sched_del(sched, pvt->autoid);
992 if (pvt->initid > -1)
993 ast_sched_del(sched, pvt->initid);
998 pvt->alreadygone = 1;
1002 c->_softhangup |= AST_SOFTHANGUP_DEV;
1005 ast_mutex_lock(&usecnt_lock);
1008 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1009 ast_mutex_unlock(&usecnt_lock);
1010 ast_update_use_count();
1012 ast_mutex_unlock(&iaxsl[callno]);
1016 static int iax_predestroy_nolock(int callno)
1019 ast_mutex_unlock(&iaxsl[callno]);
1020 res = iax_predestroy(callno);
1021 ast_mutex_lock(&iaxsl[callno]);
1025 static void iax_destroy(int callno)
1027 struct chan_iax_pvt *pvt;
1028 struct ast_iax_frame *cur;
1029 struct ast_channel *owner;
1032 ast_mutex_lock(&iaxsl[callno]);
1034 iaxs[callno] = NULL;
1041 if (ast_mutex_trylock(&owner->lock)) {
1042 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1043 ast_mutex_unlock(&iaxsl[callno]);
1050 /* No more pings or lagrq's */
1051 if (pvt->pingid > -1)
1052 ast_sched_del(sched, pvt->pingid);
1053 if (pvt->lagid > -1)
1054 ast_sched_del(sched, pvt->lagid);
1055 if (pvt->autoid > -1)
1056 ast_sched_del(sched, pvt->autoid);
1057 if (pvt->initid > -1)
1058 ast_sched_del(sched, pvt->initid);
1065 pvt->alreadygone = 1;
1068 /* If there's an owner, prod it to give up */
1069 owner->pvt->pvt = NULL;
1070 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1071 ast_queue_hangup(owner, 0);
1074 for (cur = iaxq.head; cur ; cur = cur->next) {
1075 /* Cancel any pending transmissions */
1076 if (cur->callno == pvt->callno)
1080 pvt->reg->callno = -1;
1085 ast_mutex_unlock(&owner->lock);
1087 ast_mutex_unlock(&iaxsl[callno]);
1089 static void iax_destroy_nolock(int callno)
1091 /* Actually it's easier to unlock, kill it, and relock */
1092 ast_mutex_unlock(&iaxsl[callno]);
1093 iax_destroy(callno);
1094 ast_mutex_lock(&iaxsl[callno]);
1099 static int attempt_transmit(void *data)
1101 /* Attempt to transmit the frame to the remote peer...
1102 Called without iaxsl held. */
1103 struct ast_iax_frame *f = data;
1105 int callno = f->callno;
1106 /* Make sure this call is still active */
1108 ast_mutex_lock(&iaxsl[callno]);
1109 if ((f->callno > -1) && iaxs[f->callno]) {
1110 if ((f->retries < 0) /* Already ACK'd */ ||
1111 (f->retries >= max_retries) /* Too many attempts */) {
1112 /* Record an error if we've transmitted too many times */
1113 if (f->retries >= max_retries) {
1115 /* Transfer timeout */
1116 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1117 } else if (f->final) {
1119 iax_destroy_nolock(f->callno);
1121 if (iaxs[f->callno]->owner)
1122 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->f->frametype, f->f->subclass, f->ts, f->seqno);
1123 iaxs[f->callno]->error = ETIMEDOUT;
1124 if (iaxs[f->callno]->owner) {
1125 struct ast_frame fr = { 0, };
1127 fr.frametype = AST_FRAME_CONTROL;
1128 fr.subclass = AST_CONTROL_HANGUP;
1129 iax_queue_frame(f->callno, &fr);
1131 if (iaxs[f->callno]->reg) {
1132 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1133 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1134 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1136 iax_destroy_nolock(f->callno);
1143 /* Attempt transmission */
1146 /* Try again later after 10 times as long */
1148 if (f->retrytime > MAX_RETRY_TIME)
1149 f->retrytime = MAX_RETRY_TIME;
1150 /* Transfer messages max out at one second */
1151 if (f->transfer && (f->retrytime > 1000))
1152 f->retrytime = 1000;
1153 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1156 /* Make sure it gets freed */
1161 ast_mutex_unlock(&iaxsl[callno]);
1162 /* Do not try again */
1164 /* Don't attempt delivery, just remove it from the queue */
1165 ast_mutex_lock(&iaxq.lock);
1167 f->prev->next = f->next;
1169 iaxq.head = f->next;
1171 f->next->prev = f->prev;
1173 iaxq.tail = f->prev;
1175 ast_mutex_unlock(&iaxq.lock);
1176 /* Free the frame */
1179 ast_iax_frame_free(f);
1184 static int iax_set_jitter(int fd, int argc, char *argv[])
1186 if ((argc != 4) && (argc != 5))
1187 return RESULT_SHOWUSAGE;
1189 max_jitter_buffer = atoi(argv[3]);
1190 if (max_jitter_buffer < 0)
1191 max_jitter_buffer = 0;
1194 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1195 if (iaxs[atoi(argv[3])]) {
1196 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1197 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1198 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1200 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1202 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1205 return RESULT_SUCCESS;
1208 static char jitter_usage[] =
1209 "Usage: iax set jitter [callid] <value>\n"
1210 " If used with a callid, it sets the jitter buffer to the given static\n"
1211 "value (until its next calculation). If used without a callid, the value is used\n"
1212 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1213 "buffer size is reduced.";
1215 static int iax_show_stats(int fd, int argc, char *argv[])
1217 struct ast_iax_frame *cur;
1218 int cnt = 0, dead=0, final=0;
1220 return RESULT_SHOWUSAGE;
1221 for (cur = iaxq.head; cur ; cur = cur->next) {
1222 if (cur->retries < 0)
1228 ast_cli(fd, " IAX Statistics\n");
1229 ast_cli(fd, "---------------------\n");
1230 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1231 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1232 return RESULT_SUCCESS;
1235 static int iax_show_cache(int fd, int argc, char *argv[])
1237 struct iax_dpcache *dp;
1238 char tmp[1024], *pc;
1242 gettimeofday(&tv, NULL);
1243 ast_mutex_lock(&dpcache_lock);
1245 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1247 s = dp->expirey.tv_sec - tv.tv_sec;
1249 if (dp->flags & CACHE_FLAG_EXISTS)
1250 strcat(tmp, "EXISTS|");
1251 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1252 strcat(tmp, "NONEXISTANT|");
1253 if (dp->flags & CACHE_FLAG_CANEXIST)
1254 strcat(tmp, "CANEXIST|");
1255 if (dp->flags & CACHE_FLAG_PENDING)
1256 strcat(tmp, "PENDING|");
1257 if (dp->flags & CACHE_FLAG_TIMEOUT)
1258 strcat(tmp, "TIMEOUT|");
1259 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1260 strcat(tmp, "TRANSMITTED|");
1261 if (dp->flags & CACHE_FLAG_MATCHMORE)
1262 strcat(tmp, "MATCHMORE|");
1263 if (dp->flags & CACHE_FLAG_UNKNOWN)
1264 strcat(tmp, "UNKNOWN|");
1265 /* Trim trailing pipe */
1267 tmp[strlen(tmp) - 1] = '\0';
1269 strcpy(tmp, "(none)");
1271 pc = strchr(dp->peercontext, '@');
1273 pc = dp->peercontext;
1276 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1277 if (dp->waiters[x] > -1)
1280 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1282 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1285 ast_mutex_unlock(&dpcache_lock);
1286 return RESULT_SUCCESS;
1289 static char show_stats_usage[] =
1290 "Usage: iax show stats\n"
1291 " Display statistics on IAX channel driver.\n";
1294 static char show_cache_usage[] =
1295 "Usage: iax show cache\n"
1296 " Display currently cached IAX Dialplan results.\n";
1298 static struct ast_cli_entry cli_set_jitter =
1299 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1301 static struct ast_cli_entry cli_show_stats =
1302 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1304 static struct ast_cli_entry cli_show_cache =
1305 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1307 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1309 #ifdef BRIDGE_OPTIMIZATION
1310 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1312 static int forward_delivery(struct ast_iax_frame *fr)
1314 struct chan_iax_pvt *p1, *p2;
1315 p1 = iaxs[fr->callno];
1316 p2 = iaxs[p1->bridgecallno];
1321 /* Fix relative timestamp */
1322 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1323 /* Now just send it send on the 2nd one
1324 with adjusted timestamp */
1325 return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1329 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1332 int drops[MEMORY_SIZE];
1333 int min, max=0, maxone=0,y,z, match;
1334 /* ms is a measure of the "lateness" of the packet relative to the first
1335 packet we received, which always has a lateness of 1. Called by
1336 IAX thread, with iaxsl lock held. */
1337 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1340 /* What likely happened here is that our counter has circled but we haven't
1341 gotten the update from the main packet. We'll just pretend that we did, and
1342 update the timestamp appropriately. */
1347 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1352 /* Rotate our history queue of "lateness". Don't worry about those initial
1353 zeros because the first entry will always be zero */
1354 for (x=0;x<MEMORY_SIZE - 1;x++)
1355 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1356 /* Add a history entry for this one */
1357 iaxs[fr->callno]->history[x] = ms;
1359 /* Initialize the minimum to reasonable values. It's too much
1360 work to do the same for the maximum, repeatedly */
1361 min=iaxs[fr->callno]->history[0];
1362 for (z=0;z < iax_dropcount + 1;z++) {
1363 /* Start very optimistic ;-) */
1365 for (x=0;x<MEMORY_SIZE;x++) {
1366 if (max < iaxs[fr->callno]->history[x]) {
1367 /* We have a candidate new maximum value. Make
1368 sure it's not in our drop list */
1370 for (y=0;!match && (y<z);y++)
1371 match |= (drops[y] == x);
1373 /* It's not in our list, use it as the new maximum */
1374 max = iaxs[fr->callno]->history[x];
1380 /* On our first pass, find the minimum too */
1381 if (min > iaxs[fr->callno]->history[x])
1382 min = iaxs[fr->callno]->history[x];
1389 /* Just for reference, keep the "jitter" value, the difference between the
1390 earliest and the latest. */
1391 iaxs[fr->callno]->jitter = max - min;
1393 /* IIR filter for keeping track of historic jitter, but always increase
1394 historic jitter immediately for increase */
1396 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1397 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1399 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1400 iaxs[fr->callno]->historicjitter;
1402 /* If our jitter buffer is too big (by a significant margin), then we slowly
1403 shrink it by about 1 ms each time to avoid letting the change be perceived */
1404 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1405 iaxs[fr->callno]->jitterbuffer -= 2;
1409 /* Constrain our maximum jitter buffer appropriately */
1410 if (max > min + maxjitterbuffer) {
1412 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1413 max = min + maxjitterbuffer;
1417 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1418 buffer immediately to accomodate it (and a little more). */
1419 if (max > iaxs[fr->callno]->jitterbuffer)
1420 iaxs[fr->callno]->jitterbuffer = max
1421 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1425 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1427 /* Subtract the lateness from our jitter buffer to know how long to wait
1428 before sending our packet. */
1429 ms = iaxs[fr->callno]->jitterbuffer - ms;
1431 if (!use_jitterbuffer)
1434 /* If the caller just wanted us to update, return now */
1440 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1441 /* Don't deliver it more than 4 ms late */
1442 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1446 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1447 /* Free the packet */
1449 /* And our iax frame */
1450 ast_iax_frame_free(fr);
1454 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1455 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1460 static int iax_transmit(struct ast_iax_frame *fr)
1462 /* Lock the queue and place this packet at the end */
1465 /* By setting this to 0, the network thread will send it for us, and
1466 queue retransmission if necessary */
1468 ast_mutex_lock(&iaxq.lock);
1475 iaxq.tail->next = fr;
1476 fr->prev = iaxq.tail;
1480 ast_mutex_unlock(&iaxq.lock);
1481 /* Wake up the network thread */
1482 pthread_kill(netthreadid, SIGURG);
1488 static int iax_digit(struct ast_channel *c, char digit)
1490 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1493 static int iax_sendtext(struct ast_channel *c, char *text)
1496 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1497 0, 0, text, strlen(text) + 1, -1);
1500 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1502 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1505 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1507 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1510 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1512 struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1513 pvt->owner = newchan;
1517 #ifdef MYSQL_FRIENDS
1519 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1521 if (mysql && (strlen(peer) < 128)) {
1525 name = alloca(strlen(peer) * 2 + 1);
1527 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1528 snprintf(query, sizeof(query), "UPDATE iax1friends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1529 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1530 ast_mutex_lock(&mysqllock);
1531 if (mysql_real_query(mysql, query, strlen(query)))
1532 ast_log(LOG_WARNING, "Unable to update database\n");
1534 ast_mutex_unlock(&mysqllock);
1538 static struct iax_peer *mysql_peer(char *peer)
1543 p = malloc(sizeof(struct iax_peer));
1544 memset(p, 0, sizeof(struct iax_peer));
1545 if (mysql && (strlen(peer) < 128)) {
1550 time_t regseconds, nowtime;
1552 MYSQL_FIELD *fields;
1554 name = alloca(strlen(peer) * 2 + 1);
1555 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1556 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1557 ast_mutex_lock(&mysqllock);
1558 mysql_query(mysql, query);
1559 if ((result = mysql_store_result(mysql))) {
1560 if ((rowval = mysql_fetch_row(result))) {
1561 numfields = mysql_num_fields(result);
1562 fields = mysql_fetch_fields(result);
1564 for (x=0;x<numfields;x++) {
1566 if (!strcasecmp(fields[x].name, "secret")) {
1567 strncpy(p->secret, rowval[x], sizeof(p->secret));
1568 } else if (!strcasecmp(fields[x].name, "context")) {
1569 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1570 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1571 inet_aton(rowval[x], &p->addr.sin_addr);
1572 } else if (!strcasecmp(fields[x].name, "port")) {
1573 if (sscanf(rowval[x], "%i", &port) != 1)
1575 p->addr.sin_port = htons(port);
1576 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1577 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1583 if ((nowtime - regseconds) > AST_DEFAULT_REG_EXPIRE)
1584 memset(&p->addr, 0, sizeof(p->addr));
1587 ast_mutex_unlock(&mysqllock);
1593 strncpy(p->name, peer, sizeof(p->name) - 1);
1596 p->capability = iax_capability;
1597 strcpy(p->methods, "md5,plaintext");
1601 #endif /* MYSQL_FRIENDS */
1603 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1612 sin->sin_family = AF_INET;
1613 ast_mutex_lock(&peerl.lock);
1616 if (!strcasecmp(p->name, peer)) {
1621 #ifdef MYSQL_FRIENDS
1623 p = mysql_peer(peer);
1628 *capability = p->capability;
1629 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1630 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1632 *sendani = p->sendani; /* Whether we transmit ANI */
1634 *maxtime = p->maxms; /* Max time they should take */
1636 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1637 if (p->addr.sin_addr.s_addr) {
1638 sin->sin_addr = p->addr.sin_addr;
1639 sin->sin_port = p->addr.sin_port;
1641 sin->sin_addr = p->defaddr.sin_addr;
1642 sin->sin_port = p->defaddr.sin_port;
1650 ast_mutex_unlock(&peerl.lock);
1652 hp = gethostbyname(peer);
1654 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1655 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1658 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1668 static int auto_congest(void *nothing)
1670 int callno = (int)(long)(nothing);
1671 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1672 ast_mutex_lock(&iaxsl[callno]);
1674 iaxs[callno]->initid = -1;
1675 iax_queue_frame(callno, &f);
1676 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1678 ast_mutex_unlock(&iaxsl[callno]);
1682 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1684 struct sockaddr_in sin;
1689 char *secret = NULL;
1691 char requeststr[256] = "";
1692 char myrdest [5] = "s";
1693 char context[AST_MAX_EXTENSION] ="";
1694 char *portno = NULL;
1695 struct chan_iax_pvt *p = c->pvt->pvt;
1697 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1698 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1701 strncpy(host, dest, sizeof(host)-1);
1703 strsep(&stringp, "/");
1704 /* If no destination extension specified, use 's' */
1705 rdest = strsep(&stringp, "/");
1709 strsep(&stringp, "@");
1710 rcontext = strsep(&stringp, "@");
1712 strsep(&stringp, "@");
1713 username = strsep(&stringp, "@");
1715 /* Really the second argument is the host, not the username */
1723 username = strsep(&stringp, ":");
1724 secret = strsep(&stringp, ":");
1727 if (strsep(&stringp, ":")) {
1729 strsep(&stringp, ":");
1730 portno = strsep(&stringp, ":");
1732 if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1733 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1736 /* Keep track of the context for outgoing calls too */
1737 strncpy(c->context, context, sizeof(c->context) - 1);
1739 sin.sin_port = htons(atoi(portno));
1741 /* Now we build our request string */
1742 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr),
1743 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr),
1744 MYSNPRINTF "exten=%s;", rdest);
1746 MYSNPRINTF "callerid=%s;", c->callerid);
1747 if (p->sendani && c->ani)
1748 MYSNPRINTF "ani=%s;", c->ani);
1749 if (c->language && strlen(c->language))
1750 MYSNPRINTF "language=%s;", c->language);
1752 MYSNPRINTF "dnid=%s;", c->dnid);
1754 MYSNPRINTF "context=%s;", rcontext);
1756 MYSNPRINTF "username=%s;", username);
1758 if (secret[0] == '[') {
1759 /* This is an RSA key, not a normal secret */
1760 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1761 if (strlen(p->outkey)) {
1762 p->outkey[strlen(p->outkey) - 1] = '\0';
1765 strncpy(p->secret, secret, sizeof(p->secret)-1);
1767 MYSNPRINTF "formats=%d;", c->nativeformats);
1768 MYSNPRINTF "capability=%d;", p->capability);
1769 MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1770 MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1771 /* Trim the trailing ";" */
1772 if (strlen(requeststr))
1773 requeststr[strlen(requeststr) - 1] = '\0';
1774 /* Transmit the string in a "NEW" request */
1775 if (option_verbose > 2)
1776 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1778 /* Initialize pingtime and auto-congest time */
1779 p->pingtime = p->maxtime / 2;
1780 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1782 send_command(p, AST_FRAME_IAX,
1783 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1784 ast_setstate(c, AST_STATE_RINGING);
1788 static int iax_hangup(struct ast_channel *c)
1790 struct chan_iax_pvt *pvt = c->pvt->pvt;
1794 callno = pvt->callno;
1795 ast_mutex_lock(&iaxsl[callno]);
1796 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1797 alreadygone = pvt->alreadygone;
1798 /* Send the hangup unless we have had a transmission error or are already gone */
1799 if (!pvt->error && !alreadygone)
1800 send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1801 /* Explicitly predestroy it */
1802 iax_predestroy_nolock(callno);
1803 /* If we were already gone to begin with, destroy us now */
1805 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1806 iax_destroy_nolock(callno);
1808 ast_mutex_unlock(&iaxsl[callno]);
1810 if (option_verbose > 2)
1811 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1815 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1817 struct ast_option_header *h;
1819 h = malloc(datalen + sizeof(struct ast_option_header));
1821 h->flag = AST_OPTION_FLAG_REQUEST;
1822 h->option = htons(option);
1823 memcpy(h->data, data, datalen);
1824 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1825 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1829 ast_log(LOG_WARNING, "Out of memory\n");
1832 static struct ast_frame *iax_read(struct ast_channel *c)
1834 static struct ast_frame f = { AST_FRAME_NULL, };
1835 ast_log(LOG_NOTICE, "I should never be called!\n");
1839 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1844 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1845 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1846 snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1847 snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1848 res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1851 res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1854 p0->transferring = TRANSFER_BEGIN;
1855 p1->transferring = TRANSFER_BEGIN;
1859 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1861 struct ast_channel *cs[3];
1862 struct ast_channel *who;
1865 int transferstarted=0;
1866 struct ast_frame *f;
1867 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1868 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1870 /* Put them in native bridge mode */
1871 p0->bridgecallno = p1->callno;
1872 p1->bridgecallno = p0->callno;
1874 /* If not, try to bridge until we can execute a transfer, if we can */
1877 for (/* ever */;;) {
1878 /* Check in case we got masqueraded into */
1879 if ((c0->type != type) || (c1->type != type)) {
1880 if (option_verbose > 2)
1881 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1884 if (c0->nativeformats != c1->nativeformats) {
1885 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1888 if (!transferstarted) {
1889 /* Try the transfer */
1890 if (iax_start_transfer(c0, c1))
1891 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1892 transferstarted = 1;
1895 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1896 /* Call has been transferred. We're no longer involved */
1898 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1899 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1906 who = ast_waitfor_n(cs, 2, &to);
1917 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1923 if ((f->frametype == AST_FRAME_VOICE) ||
1924 (f->frametype == AST_FRAME_TEXT) ||
1925 (f->frametype == AST_FRAME_VIDEO) ||
1926 (f->frametype == AST_FRAME_IMAGE) ||
1927 (f->frametype == AST_FRAME_DTMF)) {
1928 if ((f->frametype == AST_FRAME_DTMF) &&
1929 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1931 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1934 /* Take out of conference mode */
1941 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1951 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1953 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1965 /* Swap who gets priority */
1970 p0->bridgecallno = -1;
1971 p1->bridgecallno = -1;
1975 static int iax_answer(struct ast_channel *c)
1977 struct chan_iax_pvt *pvt = c->pvt->pvt;
1979 ast_log(LOG_DEBUG, "Answering\n");
1980 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
1983 static int iax_indicate(struct ast_channel *c, int condition)
1985 struct chan_iax_pvt *pvt = c->pvt->pvt;
1987 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
1988 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
1992 static int iax_write(struct ast_channel *c, struct ast_frame *f);
1994 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
1996 struct iax_peer *peer;
1998 ast_mutex_lock(&peerl.lock);
2001 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2002 (peer->addr.sin_port == sin.sin_port)) {
2003 strncpy(host, peer->name, len-1);
2009 ast_mutex_unlock(&peerl.lock);
2013 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
2016 struct ast_channel *tmp;
2017 tmp = ast_channel_alloc(1);
2019 if (!iax_getpeername(i->addr, host, sizeof(host)))
2020 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2021 if (strlen(i->username))
2022 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
2024 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
2026 /* We can support any format by default, until we get restricted */
2027 tmp->nativeformats = capability;
2028 tmp->readformat = 0;
2029 tmp->writeformat = 0;
2031 tmp->pvt->send_digit = iax_digit;
2032 tmp->pvt->send_text = iax_sendtext;
2033 tmp->pvt->send_image = iax_sendimage;
2034 tmp->pvt->send_html = iax_sendhtml;
2035 tmp->pvt->call = iax_call;
2036 tmp->pvt->hangup = iax_hangup;
2037 tmp->pvt->answer = iax_answer;
2038 tmp->pvt->read = iax_read;
2039 tmp->pvt->write = iax_write;
2040 tmp->pvt->indicate = iax_indicate;
2041 tmp->pvt->setoption = iax_setoption;
2042 tmp->pvt->bridge = iax_bridge;
2043 if (strlen(i->callerid))
2044 tmp->callerid = strdup(i->callerid);
2046 tmp->ani = strdup(i->ani);
2047 if (strlen(i->language))
2048 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2049 if (strlen(i->dnid))
2050 tmp->dnid = strdup(i->dnid);
2051 if (strlen(i->accountcode))
2052 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2054 tmp->amaflags = i->amaflags;
2055 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2056 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2057 tmp->adsicpe = i->peeradsicpe;
2058 tmp->pvt->fixup = iax_fixup;
2060 i->capability = capability;
2061 ast_setstate(tmp, state);
2062 ast_mutex_lock(&usecnt_lock);
2064 ast_mutex_unlock(&usecnt_lock);
2065 ast_update_use_count();
2066 if (state != AST_STATE_DOWN) {
2067 if (ast_pbx_start(tmp)) {
2068 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2077 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
2081 if (!p->offset.tv_sec && !p->offset.tv_usec)
2082 gettimeofday(&p->offset, NULL);
2083 /* If the timestamp is specified, just send it as is */
2086 gettimeofday(&tv, NULL);
2087 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2088 /* We never send the same timestamp twice, so fudge a little if we must */
2089 if (ms <= p->lastsent)
2090 ms = p->lastsent + 1;
2095 #ifdef BRIDGE_OPTIMIZATION
2096 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
2099 /* Receive from p1, send to p2 */
2101 /* Setup rxcore if necessary on outgoing channel */
2102 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2103 gettimeofday(&p1->rxcore, NULL);
2105 /* Setup txcore if necessary on outgoing channel */
2106 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2107 gettimeofday(&p2->offset, NULL);
2109 /* Now, ts is the timestamp of the original packet in the orignal context.
2110 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2111 Subtracting txcore of the outgoing channel gives us what we'd expect */
2113 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2115 if (fakets <= p2->lastsent)
2116 fakets = p2->lastsent + 1;
2117 p2->lastsent = fakets;
2122 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2124 /* Returns where in "receive time" we are */
2127 /* Setup rxcore if necessary */
2128 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2129 gettimeofday(&p->rxcore, NULL);
2131 gettimeofday(&tv, NULL);
2132 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2136 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2138 /* Queue a packet for delivery on a given private structure. Use "ts" for
2139 timestamp, or calculate if ts is 0. Send immediately without retransmission
2140 or delayed, with retransmission */
2141 struct ast_iax_full_hdr *fh;
2142 struct ast_iax_mini_hdr *mh;
2143 struct ast_iax_frame *fr, fr2;
2145 unsigned int lastsent;
2146 /* Allocate an ast_iax_frame */
2150 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2152 ast_log(LOG_WARNING, "Out of memory\n");
2156 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2158 ast_iax_frame_free(fr);
2161 /* Isolate our frame for transmission */
2162 fr->f = ast_frdup(f);
2165 ast_log(LOG_WARNING, "Out of memory\n");
2167 ast_iax_frame_free(fr);
2170 if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2171 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2175 lastsent = pvt->lastsent;
2176 fr->ts = calc_timestamp(pvt, ts);
2178 ast_log(LOG_WARNING, "timestamp is 0?\n");
2180 ast_iax_frame_free(fr);
2183 fr->callno = pvt->callno;
2184 fr->transfer = transfer;
2186 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2187 /* High two bits of timestamp differ */ ||
2188 (fr->f->frametype != AST_FRAME_VOICE)
2189 /* or not a voice frame */ ||
2190 (fr->f->subclass != pvt->svoiceformat)
2191 /* or new voice format */ ) {
2192 /* We need a full frame */
2196 fr->seqno = pvt->oseqno++;
2197 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2198 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2199 fh->ts = htonl(fr->ts);
2200 fh->seqno = htons(fr->seqno);
2201 fh->type = fr->f->frametype & 0xFF;
2202 fh->csub = compress_subclass(fr->f->subclass);
2204 fh->dcallno = htons(pvt->transfercallno);
2206 fh->dcallno = htons(pvt->peercallno);
2207 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2210 /* Retry after 2x the ping time has passed */
2211 fr->retrytime = pvt->pingtime * 2;
2212 if (fr->retrytime < MIN_RETRY_TIME)
2213 fr->retrytime = MIN_RETRY_TIME;
2214 if (fr->retrytime > MAX_RETRY_TIME)
2215 fr->retrytime = MAX_RETRY_TIME;
2216 /* Acks' don't get retried */
2217 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2219 if (f->frametype == AST_FRAME_VOICE) {
2220 pvt->svoiceformat = f->subclass;
2223 res = send_packet(fr);
2226 res = iax_transmit(fr);
2228 /* Mini-frames have no sequence number */
2230 /* Mini frame will do */
2231 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2232 mh->callno = htons(fr->callno);
2233 mh->ts = htons(fr->ts & 0xFFFF);
2234 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2238 res = send_packet(fr);
2241 res = iax_transmit(fr);
2248 static int iax_show_users(int fd, int argc, char *argv[])
2250 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2251 struct iax_user *user;
2253 return RESULT_SHOWUSAGE;
2254 ast_mutex_lock(&userl.lock);
2255 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2256 for(user=userl.users;user;user=user->next) {
2257 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2258 user->contexts ? user->contexts->context : context,
2259 user->ha ? "Yes" : "No");
2261 ast_mutex_unlock(&userl.lock);
2262 return RESULT_SUCCESS;
2266 static int iax_show_peers(int fd, int argc, char *argv[])
2268 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2269 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2270 struct iax_peer *peer;
2271 char name[256] = "";
2273 return RESULT_SHOWUSAGE;
2274 ast_mutex_lock(&peerl.lock);
2275 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2276 for (peer = peerl.peers;peer;peer = peer->next) {
2279 if (strlen(peer->username))
2280 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2282 strncpy(name, peer->name, sizeof(name) - 1);
2284 if (peer->lastms < 0)
2285 strcpy(status, "UNREACHABLE");
2286 else if (peer->lastms > peer->maxms)
2287 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2288 else if (peer->lastms)
2289 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2291 strcpy(status, "UNKNOWN");
2293 strcpy(status, "Unmonitored");
2294 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2295 ast_cli(fd, FORMAT, name,
2296 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2297 peer->dynamic ? "(D)" : "(S)",
2299 ntohs(peer->addr.sin_port), status);
2301 ast_mutex_unlock(&peerl.lock);
2302 return RESULT_SUCCESS;
2307 /* JDG: callback to display iax peers in manager */
2308 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2310 char *a[] = { "iax", "show", "users" };
2312 ret = iax_show_peers( s->fd, 3, a );
2313 ast_cli( s->fd, "\r\n" );
2317 static char *regstate2str(int regstate)
2320 case REG_STATE_UNREGISTERED:
2321 return "Unregistered";
2322 case REG_STATE_REGSENT:
2323 return "Request Sent";
2324 case REG_STATE_AUTHSENT:
2325 return "Auth. Sent";
2326 case REG_STATE_REGISTERED:
2327 return "Registered";
2328 case REG_STATE_REJECTED:
2330 case REG_STATE_TIMEOUT:
2332 case REG_STATE_NOAUTH:
2333 return "No Authentication";
2339 static int iax_show_registry(int fd, int argc, char *argv[])
2341 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2342 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2343 struct iax_registry *reg;
2347 return RESULT_SHOWUSAGE;
2348 ast_mutex_lock(&peerl.lock);
2349 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2350 for (reg = registrations;reg;reg = reg->next) {
2351 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2352 if (reg->us.sin_addr.s_addr)
2353 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2355 strcpy(perceived, "<Unregistered>");
2356 ast_cli(fd, FORMAT, host,
2357 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2359 ast_mutex_unlock(&peerl.lock);
2360 return RESULT_SUCCESS;
2365 static int iax_show_channels(int fd, int argc, char *argv[])
2367 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2368 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2372 return RESULT_SHOWUSAGE;
2373 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2374 for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2375 ast_mutex_lock(&iaxsl[x]);
2377 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2378 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2379 iaxs[x]->callno, iaxs[x]->peercallno,
2380 iaxs[x]->oseqno, iaxs[x]->iseqno,
2383 ast_getformatname(iaxs[x]->voiceformat) );
2386 ast_mutex_unlock(&iaxsl[x]);
2388 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2389 return RESULT_SUCCESS;
2394 static int iax_do_debug(int fd, int argc, char *argv[])
2397 return RESULT_SHOWUSAGE;
2399 ast_cli(fd, "IAX Debugging Enabled\n");
2400 return RESULT_SUCCESS;
2403 static int iax_no_debug(int fd, int argc, char *argv[])
2406 return RESULT_SHOWUSAGE;
2408 ast_cli(fd, "IAX Debugging Disabled\n");
2409 return RESULT_SUCCESS;
2414 static char show_users_usage[] =
2415 "Usage: iax show users\n"
2416 " Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2418 static char show_channels_usage[] =
2419 "Usage: iax show channels\n"
2420 " Lists all currently active IAX channels.\n";
2422 static char show_peers_usage[] =
2423 "Usage: iax show peers\n"
2424 " Lists all known IAX peers.\n";
2426 static char show_reg_usage[] =
2427 "Usage: iax show registry\n"
2428 " Lists all registration requests and status.\n";
2430 #ifdef DEBUG_SUPPORT
2432 static char debug_usage[] =
2433 "Usage: iax debug\n"
2434 " Enables dumping of IAX packets for debugging purposes\n";
2436 static char no_debug_usage[] =
2437 "Usage: iax no debug\n"
2438 " Disables dumping of IAX packets for debugging purposes\n";
2442 static struct ast_cli_entry cli_show_users =
2443 { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2444 static struct ast_cli_entry cli_show_channels =
2445 { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2446 static struct ast_cli_entry cli_show_peers =
2447 { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2448 static struct ast_cli_entry cli_show_registry =
2449 { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2450 static struct ast_cli_entry cli_debug =
2451 { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2452 static struct ast_cli_entry cli_no_debug =
2453 { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2455 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2457 struct chan_iax_pvt *i = c->pvt->pvt;
2460 /* If there's an outstanding error, return failure now */
2462 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2465 /* If it's already gone, just return */
2468 /* Don't waste bandwidth sending null frames */
2469 if (f->frametype == AST_FRAME_NULL)
2471 /* If we're quelching voice, don't bother sending it */
2472 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2474 /* Simple, just queue for transmission */
2475 return iax_send(i, f, 0, -1, 0, 0, 0);
2478 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2479 int now, int transfer, int final)
2483 f.subclass = command;
2484 f.datalen = datalen;
2488 f.src = __FUNCTION__;
2490 return iax_send(i, &f, ts, seqno, now, transfer, final);
2493 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2495 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2498 #ifdef BRIDGE_OPTIMIZATION
2499 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2501 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2505 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2507 /* It is assumed that the callno has already been locked */
2508 iax_predestroy_nolock(i->callno);
2509 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2512 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2514 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2517 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2519 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2522 static int apply_context(struct iax_context *con, char *context)
2525 if (!strcmp(con->context, context))
2532 static int iax_getformats(int callno, char *orequest)
2537 strncpy(request, orequest, sizeof(request)-1);
2539 var = strsep(&stringp, ";");
2541 value = strchr(var, '=');
2545 if (!strcmp(var, "formats")) {
2546 iaxs[callno]->peerformat = atoi(value);
2548 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2550 var = strsep(&stringp, ";");
2556 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2558 /* Start pessimistic */
2562 struct iax_user *user;
2564 int gotcapability=0;
2566 strncpy(request, orequest, sizeof(request)-1);
2570 var = strsep(&stringp, ";");
2572 value = strchr(var, '=');
2576 if (!strcmp(var, "exten"))
2577 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2578 else if (!strcmp(var, "callerid"))
2579 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2580 else if (!strcmp(var, "ani"))
2581 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2582 else if (!strcmp(var, "dnid"))
2583 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2584 else if (!strcmp(var, "context"))
2585 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2586 else if (!strcmp(var, "language"))
2587 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2588 else if (!strcmp(var, "username"))
2589 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2590 else if (!strcmp(var, "formats"))
2591 iaxs[callno]->peerformat = atoi(value);
2592 else if (!strcmp(var, "adsicpe"))
2593 iaxs[callno]->peeradsicpe = atoi(value);
2594 else if (!strcmp(var, "capability")) {
2596 iaxs[callno]->peercapability = atoi(value);
2597 } else if (!strcmp(var, "version"))
2598 version = atoi(value);
2600 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2602 var = strsep(&stringp, ";");
2605 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2606 if (version > AST_IAX_PROTO_VERSION) {
2607 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2608 inet_ntoa(sin->sin_addr), version);
2611 ast_mutex_lock(&userl.lock);
2612 /* Search the userlist for a compatible entry, and fill in the rest */
2615 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2616 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2617 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2618 && (!strlen(iaxs[callno]->context) || /* No context specified */
2619 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2620 /* We found our match (use the first) */
2622 /* Store the requested username if not specified */
2623 if (!strlen(iaxs[callno]->username))
2624 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2625 /* And use the default context */
2626 if (!strlen(iaxs[callno]->context)) {
2628 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2630 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2632 /* Copy the secret */
2633 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2634 /* And any input keys */
2635 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2636 /* And the permitted authentication methods */
2637 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2638 /* If they have callerid, override the given caller id. Always store the ANI */
2639 if (strlen(iaxs[callno]->callerid)) {
2640 if (user->hascallerid)
2641 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2642 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2644 if (strlen(user->accountcode))
2645 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2647 iaxs[callno]->amaflags = user->amaflags;
2653 ast_mutex_unlock(&userl.lock);
2657 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2659 struct ast_iax_full_hdr fh;
2660 fh.callno = htons(src | AST_FLAG_FULL);
2661 fh.dcallno = htons(dst);
2664 fh.type = AST_FRAME_IAX;
2665 fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2669 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2670 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2671 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2674 static int authenticate_request(struct chan_iax_pvt *p)
2676 char requeststr[256] = "";
2677 MYSNPRINTF "methods=%s;", p->methods);
2678 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2679 /* Build the challenge */
2680 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2681 MYSNPRINTF "challenge=%s;", p->challenge);
2683 MYSNPRINTF "username=%s;", p->username);
2684 if (strlen(requeststr))
2685 requeststr[strlen(requeststr) - 1] = '\0';
2686 return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2689 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2691 char requeststr[256] = "";
2692 char *var, *value, request[256];
2693 char md5secret[256] = "";
2694 char secret[256] = "";
2695 char rsasecret[256] = "";
2700 if (!(p->state & IAX_STATE_AUTHENTICATED))
2702 strncpy(request, orequest, sizeof(request)-1);
2704 var = strsep(&stringp, ";");
2706 value = strchr(var, '=');
2710 if (!strcmp(var, "secret"))
2711 strncpy(secret, value, sizeof(secret)-1);
2712 else if (!strcmp(var, "md5secret"))
2713 strncpy(md5secret, value, sizeof(md5secret)-1);
2714 else if (!strcmp(var, "rsasecret"))
2715 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2717 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2719 var = strsep(&stringp, ";");
2721 if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2722 struct ast_key *key;
2726 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2728 keyn = strsep(&stringp, ":");
2730 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2731 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2735 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2736 keyn = strsep(&stringp, ":");
2738 } else if (strstr(p->methods, "md5")) {
2739 struct MD5Context md5;
2740 unsigned char digest[16];
2742 MD5Update(&md5, p->challenge, strlen(p->challenge));
2743 MD5Update(&md5, p->secret, strlen(p->secret));
2744 MD5Final(digest, &md5);
2745 /* If they support md5, authenticate with it. */
2747 MYSNPRINTF "%2.2x", digest[x]);
2748 if (!strcasecmp(requeststr, md5secret))
2750 } else if (strstr(p->methods, "plaintext")) {
2751 if (!strcmp(secret, p->secret))
2757 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2760 char requeststr[256] = "";
2761 char peer[256] = "";
2762 char md5secret[256] = "";
2763 char rsasecret[256] = "";
2764 char secret[256] = "";
2766 struct ast_key *key;
2774 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2775 strcpy(iaxs[callno]->peer, "");
2778 strncpy(request, orequest, sizeof(request)-1);
2780 var = strsep(&stringp, ";");
2782 value = strchr(var, '=');
2786 if (!strcmp(var, "peer"))
2787 strncpy(peer, value, sizeof(peer)-1);
2788 else if (!strcmp(var, "md5secret"))
2789 strncpy(md5secret, value, sizeof(md5secret)-1);
2790 else if (!strcmp(var, "rsasecret"))
2791 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2792 else if (!strcmp(var, "secret"))
2793 strncpy(secret, value, sizeof(secret)-1);
2794 else if (!strcmp(var, "refresh"))
2795 expire = atoi(value);
2797 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2799 var = strsep(&stringp, ";");
2802 if (!strlen(peer)) {
2803 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2807 for (p = peerl.peers; p ; p = p->next)
2808 if (!strcasecmp(p->name, peer))
2811 #ifdef MYSQL_FRIENDS
2813 p = mysql_peer(peer);
2816 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2821 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2827 if (!ast_apply_ha(p->ha, sin)) {
2828 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2833 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2834 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2835 /* Check secret against what we have on file */
2836 if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(iaxs[callno]->challenge)) {
2837 if (strlen(p->inkeys)) {
2840 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2842 keyn = strsep(&stringp, ":");
2844 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2845 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
2846 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2849 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2850 keyn = strsep(&stringp, ":");
2853 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2859 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2864 } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2865 /* They've provided a plain text password and we support that */
2866 if (strcmp(secret, p->secret)) {
2867 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2872 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2873 } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(iaxs[callno]->challenge)) {
2874 struct MD5Context md5;
2875 unsigned char digest[16];
2877 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
2878 MD5Update(&md5, p->secret, strlen(p->secret));
2879 MD5Final(digest, &md5);
2881 MYSNPRINTF "%2.2x", digest[x]);
2882 if (strcasecmp(requeststr, md5secret)) {
2883 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2888 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2889 } else if (strlen(md5secret) || strlen(secret)) {
2890 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2895 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2896 /* Choose lowest expirey number */
2897 if (expire && (expire < iaxs[callno]->expirey))
2898 iaxs[callno]->expirey = expire;
2905 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2909 if (keyn && strlen(keyn)) {
2910 if (!strstr(methods, "rsa")) {
2911 if (!secret || !strlen(secret))
2912 ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", inet_ntoa(sin->sin_addr));
2913 } else if (!strlen(challenge)) {
2914 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2917 struct ast_key *key;
2918 key = ast_key_get(keyn, AST_KEY_PRIVATE);
2920 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
2922 if (ast_sign(key, challenge, sig)) {
2923 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
2926 MYSNPRINTF2 "rsasecret=%s;", sig);
2933 if (res && secret && strlen(secret)) {
2934 if (strstr(methods, "md5") && strlen(challenge)) {
2935 struct MD5Context md5;
2936 unsigned char digest[16];
2938 MD5Update(&md5, challenge, strlen(challenge));
2939 MD5Update(&md5, secret, strlen(secret));
2940 MD5Final(digest, &md5);
2941 /* If they support md5, authenticate with it. */
2942 MYSNPRINTF2 "md5secret=");
2944 MYSNPRINTF2 "%2.2x", digest[x]);
2947 } else if (strstr(methods, "plaintext")) {
2948 MYSNPRINTF2 "secret=%s;", secret);
2951 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
2956 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
2958 struct iax_peer *peer;
2959 /* Start pessimistic */
2962 char methods[80] = "";
2963 char requeststr[256] = "";
2967 strncpy(request, orequest, sizeof(request)-1);
2969 var = strsep(&stringp, ";");
2971 value = strchr(var, '=');
2975 if (!strcmp(var, "username"))
2976 strncpy(p->username, value, sizeof(p->username)-1);
2977 else if (!strcmp(var, "challenge"))
2978 strncpy(p->challenge, value, sizeof(p->challenge)-1);
2979 else if (!strcmp(var, "methods"))
2980 strncpy(methods, value, sizeof(methods)-1);
2982 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2984 var = strsep(&stringp, ";");
2987 /* Check for override RSA authentication first */
2988 if ((override && strlen(override)) || (okey && strlen(okey))) {
2989 /* Normal password authentication */
2990 res = authenticate(p->challenge, override, okey, methods, requeststr, sizeof(requeststr), sin);
2992 ast_mutex_lock(&peerl.lock);
2995 if ((!strlen(p->peer) || !strcmp(p->peer, peer->name))
2996 /* No peer specified at our end, or this is the peer */
2997 && (!strlen(peer->username) || (!strcmp(peer->username, p->username)))
2998 /* No username specified in peer rule, or this is the right username */
2999 && (!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)))
3000 /* No specified host, or this is our host */
3002 res = authenticate(p->challenge, peer->secret, peer->outkey, methods, requeststr, sizeof(requeststr), sin);
3008 ast_mutex_unlock(&peerl.lock);
3010 if (strlen(requeststr))
3011 requeststr[strlen(requeststr)-1] = '\0';
3013 res = send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREP, 0, requeststr, strlen(requeststr) + 1, -1);
3017 static int iax_do_register(struct iax_registry *reg);
3019 static int iax_do_register_s(void *data)
3021 struct iax_registry *reg = data;
3023 iax_do_register(reg);
3027 static int try_transfer(struct chan_iax_pvt *pvt, char *orequest)
3031 char newip[256] = "";
3032 char request[256] = "";
3035 struct sockaddr_in new;
3041 strncpy(request, orequest, sizeof(request)-1);
3043 var = strsep(&stringp, ";");
3045 value = strchr(var, '=');
3049 if (!strcmp(var, "remip"))
3050 strncpy(newip, value, sizeof(newip)-1);
3051 else if (!strcmp(var, "remport"))