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
57 #define IAX_CONF_FILE "iax1.conf"
58 /* Deprecated old configuration file */
59 #define IAX_OLD_CONF_FILE "iax.conf"
62 * Uncomment to try experimental IAX bridge optimization,
63 * designed to reduce latency when IAX calls cannot
67 #define BRIDGE_OPTIMIZATION
70 #define DEFAULT_RETRY_TIME 1000
71 #define MEMORY_SIZE 100
72 #define DEFAULT_DROP 3
76 /* Sample over last 100 units to determine historic jitter */
80 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
82 static char mydbuser[80];
83 static char mydbpass[80];
84 static char mydbhost[80];
85 static char mydbname[80];
88 static char *desc = "Inter Asterisk eXchange";
89 static char *tdesc = "Inter Asterisk eXchange Drver";
90 static char *ctype = "IAX";
91 static char *type = "IAX1";
93 static char context[80] = "default";
95 static int max_retries = 4;
96 static int ping_time = 20;
97 static int lagrq_time = 10;
98 static int nextcallno = 0;
99 static int maxjitterbuffer=3000;
101 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
103 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
105 static int netsocket = -1;
109 static int expirey = AST_DEFAULT_REG_EXPIRE;
112 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
114 int (*iax_regfunk)(char *username, int onoff) = NULL;
117 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
119 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
120 ~AST_FORMAT_SLINEAR & \
124 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
125 ~AST_FORMAT_ADPCM & \
128 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
132 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
133 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
134 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
136 static struct io_context *io;
137 static struct sched_context *sched;
139 static int iax_capability = IAX_CAPABILITY_FULLBANDWIDTH;
141 static int iax_dropcount = DEFAULT_DROP;
143 static int use_jitterbuffer = 1;
145 static int iaxdebug = 0;
147 static char accountcode[20];
148 static int amaflags = 0;
150 static pthread_t netthreadid;
152 #define IAX_STATE_STARTED (1 << 0)
153 #define IAX_STATE_AUTHENTICATED (1 << 1)
154 #define IAX_STATE_TBD (1 << 2)
157 char context[AST_MAX_EXTENSION];
158 struct iax_context *next;
165 char accountcode[20];
166 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
170 char callerid[AST_MAX_EXTENSION];
172 struct iax_context *contexts;
173 struct iax_user *next;
180 char outkey[80]; /* What key we use to talk to this peer */
181 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
182 struct sockaddr_in addr;
186 /* Dynamic Registration fields */
187 int dynamic; /* If this is a dynamic peer */
188 struct sockaddr_in defaddr; /* Default address if there is one */
190 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
193 /* Suggested caller id if registering */
194 char callerid[AST_MAX_EXTENSION];
195 /* Whether or not to send ANI */
197 int expire; /* Schedule entry for expirey */
198 int expirey; /* How soon to expire */
199 int capability; /* Capability */
200 int delme; /* I need to be deleted */
203 int callno; /* Call number of POKE request */
204 int pokeexpire; /* When to expire poke */
205 int lastms; /* How long last response took (in ms), or -1 for no response */
206 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
209 struct iax_peer *next;
212 #define REG_STATE_UNREGISTERED 0
213 #define REG_STATE_REGSENT 1
214 #define REG_STATE_AUTHSENT 2
215 #define REG_STATE_REGISTERED 3
216 #define REG_STATE_REJECTED 4
217 #define REG_STATE_TIMEOUT 5
218 #define REG_STATE_NOAUTH 6
220 #define TRANSFER_NONE 0
221 #define TRANSFER_BEGIN 1
222 #define TRANSFER_READY 2
223 #define TRANSFER_RELEASED 3
224 #define TRANSFER_PASSTHROUGH 4
226 struct iax_registry {
227 struct sockaddr_in addr; /* Who we connect to for registration purposes */
229 char secret[80]; /* Password or key name in []'s */
231 int expire; /* Sched ID of expiration */
232 int refresh; /* How often to refresh */
234 int callno; /* Associated call number if applicable */
235 struct sockaddr_in us; /* Who the server thinks we are */
236 struct iax_registry *next;
239 static struct iax_registry *registrations;
241 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
242 #define MIN_RETRY_TIME 10
243 #define MAX_RETRY_TIME 10000
244 #define MAX_JITTER_BUFFER 50
246 /* If we have more than this much excess real jitter buffer, srhink it. */
247 static int max_jitter_buffer = MAX_JITTER_BUFFER;
249 struct chan_iax_pvt {
250 /* Pipes for communication. pipe[1] belongs to the
251 network thread (write), and pipe[0] belongs to the individual
253 /* Whether or not we Quelch audio */
255 /* Last received voice format */
257 /* Last sent voice format */
259 /* What we are capable of sending */
261 /* Last received timestamp */
263 /* Last sent timestamp - never send the same timestamp twice in a single call */
264 unsigned int lastsent;
266 unsigned int pingtime;
267 /* Max time for initial response */
270 struct sockaddr_in addr;
271 /* Our call number */
275 /* Peer selected format */
277 /* Peer capability */
279 /* timeval that we base our transmission on */
280 struct timeval offset;
281 /* timeval that we base our delivery on */
282 struct timeval rxcore;
283 /* Historical delivery time */
284 int history[MEMORY_SIZE];
285 /* Current base jitterbuffer */
287 /* Current jitter measure */
289 /* Historic jitter value */
293 /* Error, as discovered by the manager */
295 /* Owner if we have one */
296 struct ast_channel *owner;
297 /* What's our state? */
299 /* Expirey (optional) */
301 /* Next outgoing sequence number */
302 unsigned short oseqno;
303 /* Next incoming sequence number */
304 unsigned short iseqno;
307 /* Default Context */
309 /* Caller ID if available */
311 /* Hidden Caller ID (i.e. ANI) if appropriate */
313 /* Whether or not ani should be transmitted in addition to Caller*ID */
317 /* Requested Extension */
318 char exten[AST_MAX_EXTENSION];
319 /* Expected Username */
321 /* Expected Secret */
323 /* permitted authentication methods */
327 /* Public keys permitted keys for incoming authentication */
329 /* Private key for outgoing authentication */
331 /* Preferred language */
333 /* Associated registry */
334 struct iax_registry *reg;
335 /* Associated peer for poking */
336 struct iax_peer *peerpoke;
338 /* Transferring status */
340 /* Already disconnected */
342 /* Who we are IAX transfering to */
343 struct sockaddr_in transfer;
344 /* What's the new call number for the transfer */
347 /* Status of knowledge of peer ADSI capability */
350 /* Who we are bridged to */
352 int pingid; /* Transmit PING request */
353 int lagid; /* Retransmit lag request */
354 int autoid; /* Auto hangup for Dialplan requestor */
355 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
356 char dproot[AST_MAX_EXTENSION];
357 char accountcode[20];
359 struct iax_dpcache *dpentries;
362 #define DIRECTION_INGRESS 1
363 #define DIRECTION_OUTGRESS 2
365 struct ast_iax_frame {
366 /* Actual, isolated frame */
368 /* /Our/ call number */
370 /* Start of raw frame (outgoing only) */
372 /* Length of frame (outgoing only) */
374 /* How many retries so far? */
376 /* Outgoing relative timestamp (ms) */
378 /* How long to wait before retrying */
380 /* Are we received out of order? */
382 /* Have we been sent at all yet? */
384 /* Packet sequence number */
386 /* Non-zero if should be sent to transfer peer */
388 /* Non-zero if this is the final message */
390 /* Ingress or outgres */
392 /* Retransmission ID */
397 struct ast_iax_frame *next;
398 struct ast_iax_frame *prev;
401 static struct ast_iax_queue {
402 struct ast_iax_frame *head;
403 struct ast_iax_frame *tail;
408 static struct ast_user_list {
409 struct iax_user *users;
413 static struct ast_peer_list {
414 struct iax_peer *peers;
418 /* Extension exists */
419 #define CACHE_FLAG_EXISTS (1 << 0)
420 /* Extension is non-existant */
421 #define CACHE_FLAG_NONEXISTANT (1 << 1)
422 /* Extension can exist */
423 #define CACHE_FLAG_CANEXIST (1 << 2)
424 /* Waiting to hear back response */
425 #define CACHE_FLAG_PENDING (1 << 3)
427 #define CACHE_FLAG_TIMEOUT (1 << 4)
428 /* Request transmitted */
429 #define CACHE_FLAG_TRANSMITTED (1 << 5)
431 #define CACHE_FLAG_UNKNOWN (1 << 6)
433 #define CACHE_FLAG_MATCHMORE (1 << 7)
435 static struct iax_dpcache {
436 char peercontext[AST_MAX_EXTENSION];
437 char exten[AST_MAX_EXTENSION];
439 struct timeval expirey;
443 struct iax_dpcache *next;
444 struct iax_dpcache *peer; /* For linking in peers */
447 static ast_mutex_t dpcache_lock;
450 static void showframe(struct ast_iax_frame *f, struct ast_iax_full_hdr *fhi, int rx, struct sockaddr_in *sin)
504 struct ast_iax_full_hdr *fh;
512 snprintf(retries, sizeof(retries), "%03d", f->retries);
514 strcpy(retries, "N/A");
517 if (!(ntohs(fh->callno) & AST_FLAG_FULL)) {
518 /* Don't mess with mini-frames */
521 if (fh->type > sizeof(frames)/sizeof(char *)) {
522 snprintf(class2, sizeof(class2), "(%d?)", fh->type);
525 class = frames[(int)fh->type];
527 if (fh->type == AST_FRAME_DTMF) {
528 sprintf(subclass2, "%c", fh->csub);
529 subclass = subclass2;
530 } else if (fh->type == AST_FRAME_IAX) {
531 if (fh->csub >= sizeof(iaxs)/sizeof(iaxs[0])) {
532 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
533 subclass = subclass2;
535 subclass = iaxs[(int)fh->csub];
537 } else if (fh->type == AST_FRAME_CONTROL) {
538 if (fh->csub > sizeof(cmds)/sizeof(char *)) {
539 snprintf(subclass2, sizeof(subclass2), "(%d?)", fh->csub);
540 subclass = subclass2;
542 subclass = cmds[(int)fh->csub];
545 snprintf(subclass2, sizeof(subclass2), "%d", fh->csub);
546 subclass = subclass2;
549 "%s-Frame Retry[%s] -- Seqno: %2.2d Type: %s Subclass: %s\n",
551 retries, ntohs(fh->seqno), class, subclass);
553 " Timestamp: %05ldms Callno: %5.5d DCall: %5.5d [%s:%d]\n",
555 (short)(ntohs(fh->callno) & ~AST_FLAG_FULL), (short) ntohs(fh->dcallno),
556 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
560 /* XXX We probably should use a mutex when working with this XXX */
561 static struct chan_iax_pvt *iaxs[AST_IAX_MAX_CALLS];
562 static ast_mutex_t iaxsl[AST_IAX_MAX_CALLS];
564 static int send_command(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
565 static int send_command_immediate(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
566 static int send_command_final(struct chan_iax_pvt *, char, int, unsigned int, char *, int, int);
567 static int send_command_transfer(struct chan_iax_pvt *, char, int, unsigned int, char *, int);
569 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts);
571 static int send_ping(void *data)
573 int callno = (long)data;
574 /* Ping only if it's real, not if it's bridged */
576 #ifdef BRIDGE_OPTIMIZATION
577 if (iaxs[callno]->bridgecallno < 0)
579 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_PING, 0, NULL, 0, -1);
585 static int send_lagrq(void *data)
587 int callno = (long)data;
588 /* Ping only if it's real not if it's bridged */
590 #ifdef BRIDGE_OPTIMIZATION
591 if (iaxs[callno]->bridgecallno < 0)
593 send_command(iaxs[callno], AST_FRAME_IAX, AST_IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
599 static unsigned char compress_subclass(int subclass)
603 /* If it's 128 or smaller, just return it */
604 if (subclass < AST_FLAG_SC_LOG)
606 /* Otherwise find its power */
607 for (x = 0; x < AST_MAX_SHIFT; x++) {
608 if (subclass & (1 << x)) {
610 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
616 return power | AST_FLAG_SC_LOG;
619 static int uncompress_subclass(unsigned char csub)
621 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
622 if (csub & AST_FLAG_SC_LOG) {
623 /* special case for 'compressed' -1 */
627 return 1 << (csub & ~AST_FLAG_SC_LOG & AST_MAX_SHIFT);
633 static struct chan_iax_pvt *new_iax(void)
635 struct chan_iax_pvt *tmp;
636 tmp = malloc(sizeof(struct chan_iax_pvt));
638 memset(tmp, 0, sizeof(struct chan_iax_pvt));
640 tmp->peercallno = -1;
641 tmp->transfercallno = -1;
642 tmp->bridgecallno = -1;
647 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
648 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
653 static int get_samples(struct ast_frame *f)
656 switch(f->subclass) {
657 case AST_FORMAT_G723_1:
658 samples = 240 /* XXX Not necessarily true XXX */;
661 samples = 160 * (f->datalen / 33);
663 case AST_FORMAT_ILBC:
664 samples = 240 * (f->datalen / 50);
666 case AST_FORMAT_G729A:
667 samples = 160 * (f->datalen / 20);
669 case AST_FORMAT_SLINEAR:
670 samples = f->datalen / 2;
672 case AST_FORMAT_LPC10:
674 samples += (((char *)(f->data))[7] & 0x1) * 8;
676 case AST_FORMAT_ULAW:
677 samples = f->datalen;
679 case AST_FORMAT_ALAW:
680 samples = f->datalen;
682 case AST_FORMAT_ADPCM:
683 samples = f->datalen *2;
685 case AST_FORMAT_SPEEX:
686 samples = (f->datalen/39)*160;
689 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
694 static int frames = 0;
695 static int iframes = 0;
696 static int oframes = 0;
698 static struct ast_iax_frame *ast_iax_frame_new(int direction)
700 struct ast_iax_frame *fr;
701 fr = malloc(sizeof(struct ast_iax_frame));
703 fr->direction = direction;
706 if (fr->direction == DIRECTION_INGRESS)
714 static void ast_iax_frame_free(struct ast_iax_frame *fr)
716 if (fr->retrans > -1)
717 ast_sched_del(sched, fr->retrans);
718 if (fr->direction == DIRECTION_INGRESS)
720 else if (fr->direction == DIRECTION_OUTGRESS)
723 ast_log(LOG_WARNING, "Attempt to double free frame detected\n");
732 static struct ast_iax_frame *iaxfrdup2(struct ast_iax_frame *fr, int ch)
734 /* Malloc() a copy of a frame */
735 struct ast_iax_frame *new = ast_iax_frame_new(DIRECTION_INGRESS);
737 memcpy(new, fr, sizeof(struct ast_iax_frame));
738 new->f = ast_frdup(fr->f);
739 /* Copy full header */
741 memcpy(new->f->data - sizeof(struct ast_iax_full_hdr),
742 fr->f->data - sizeof(struct ast_iax_full_hdr),
743 sizeof(struct ast_iax_full_hdr));
744 /* Grab new data pointer */
745 new->data = new->f->data - (fr->f->data - fr->data);
750 new->direction = DIRECTION_INGRESS;
756 #define NEW_PREVENT 0
760 static int match(struct sockaddr_in *sin, short callno, short dcallno, struct chan_iax_pvt *cur)
762 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
763 (cur->addr.sin_port == sin->sin_port)) {
764 /* This is the main host */
765 if ((cur->peercallno == callno) ||
766 ((dcallno == cur->callno) && (cur->peercallno) == -1)) {
767 /* That's us. Be sure we keep track of the peer call number */
771 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
772 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
773 /* We're transferring */
774 if (dcallno == cur->callno)
780 static int find_callno(short callno, short dcallno ,struct sockaddr_in *sin, int new)
785 if (new <= NEW_ALLOW) {
786 /* Look for an existing connection first */
787 for (x=0;(res < 0) && (x<AST_IAX_MAX_CALLS);x++) {
788 ast_mutex_lock(&iaxsl[x]);
790 /* Look for an exact match */
791 if (match(sin, callno, dcallno, iaxs[x])) {
795 ast_mutex_unlock(&iaxsl[x]);
798 if ((res < 0) && (new >= NEW_ALLOW)) {
799 /* Create a new one */
801 for (x = (nextcallno + 1) % AST_IAX_MAX_CALLS; iaxs[x] && (x != start); x = (x + 1) % AST_IAX_MAX_CALLS)
803 ast_log(LOG_WARNING, "Unable to accept more calls\n");
806 ast_mutex_lock(&iaxsl[x]);
808 ast_mutex_unlock(&iaxsl[x]);
811 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
812 iaxs[x]->addr.sin_port = sin->sin_port;
813 iaxs[x]->addr.sin_family = sin->sin_family;
814 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
815 iaxs[x]->peercallno = callno;
817 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
818 iaxs[x]->expirey = expirey;
819 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
820 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
821 iaxs[x]->amaflags = amaflags;
822 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
824 ast_log(LOG_WARNING, "Out of resources\n");
833 static int iax_queue_frame(int callno, struct ast_frame *f)
836 /* Assumes lock for callno is already held... */
839 if (!ast_mutex_trylock(&iaxsl[callno])) {
840 ast_log(LOG_WARNING, "Lock is not held on pass %d of iax_queue_frame\n", pass);
843 if (iaxs[callno] && iaxs[callno]->owner) {
844 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
845 /* Avoid deadlock by pausing and trying again */
846 ast_mutex_unlock(&iaxsl[callno]);
848 ast_mutex_lock(&iaxsl[callno]);
850 ast_queue_frame(iaxs[callno]->owner, f, 0);
851 ast_mutex_unlock(&iaxs[callno]->owner->lock);
860 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
862 static int __do_deliver(void *data)
864 /* Just deliver the packet by using queueing. This is called by
865 the IAX thread with the iaxsl lock held. */
866 struct ast_iax_frame *fr = data;
869 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
870 if (fr->f->frametype == AST_FRAME_IAX) {
871 /* We have to treat some of these packets specially because
872 they're LAG measurement packets */
873 if (fr->f->subclass == AST_IAX_COMMAND_LAGRQ) {
874 /* If we got a queued request, build a reply and send it */
875 fr->f->subclass = AST_IAX_COMMAND_LAGRP;
876 iax_send(iaxs[fr->callno], fr->f, fr->ts, -1, 0, 0, 0);
877 } else if (fr->f->subclass == AST_IAX_COMMAND_LAGRP) {
878 /* This is a reply we've been given, actually measure the difference */
879 ts = calc_timestamp(iaxs[fr->callno], 0);
880 iaxs[fr->callno]->lag = ts - fr->ts;
883 iax_queue_frame(fr->callno, fr->f);
886 /* Free the packet */
888 /* And our iax frame */
889 ast_iax_frame_free(fr);
890 /* And don't run again */
894 static int do_deliver(void *data)
896 /* Locking version of __do_deliver */
897 struct ast_iax_frame *fr = data;
898 int callno = fr->callno;
900 ast_mutex_lock(&iaxsl[callno]);
901 res = __do_deliver(data);
902 ast_mutex_unlock(&iaxsl[callno]);
906 static int handle_error(void)
908 /* XXX Ideally we should figure out why an error occured and then abort those
909 rather than continuing to try. Unfortunately, the published interface does
910 not seem to work XXX */
912 struct sockaddr_in *sin;
915 struct sock_extended_err e;
920 m.msg_controllen = sizeof(e);
922 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
924 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
926 if (m.msg_controllen) {
927 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
929 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
931 ast_log(LOG_WARNING, "No address detected??\n");
933 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
940 static int send_packet(struct ast_iax_frame *f)
943 /* Called with iaxsl held */
945 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));
946 /* Don't send if there was an error, but return error instead */
948 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
951 if (!iaxs[f->callno])
953 if (iaxs[f->callno]->error)
958 showframe(f, NULL, 0, &iaxs[f->callno]->transfer);
960 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
961 sizeof(iaxs[f->callno]->transfer));
965 showframe(f, NULL, 0, &iaxs[f->callno]->addr);
967 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
968 sizeof(iaxs[f->callno]->addr));
972 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
980 static int iax_predestroy(int callno)
982 struct ast_channel *c;
983 struct chan_iax_pvt *pvt;
984 ast_mutex_lock(&iaxsl[callno]);
987 ast_mutex_unlock(&iaxsl[callno]);
990 if (!pvt->alreadygone) {
991 /* No more pings or lagrq's */
992 if (pvt->pingid > -1)
993 ast_sched_del(sched, pvt->pingid);
995 ast_sched_del(sched, pvt->lagid);
996 if (pvt->autoid > -1)
997 ast_sched_del(sched, pvt->autoid);
998 if (pvt->initid > -1)
999 ast_sched_del(sched, pvt->initid);
1004 pvt->alreadygone = 1;
1008 c->_softhangup |= AST_SOFTHANGUP_DEV;
1011 ast_mutex_lock(&usecnt_lock);
1014 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1015 ast_mutex_unlock(&usecnt_lock);
1016 ast_update_use_count();
1018 ast_mutex_unlock(&iaxsl[callno]);
1022 static int iax_predestroy_nolock(int callno)
1025 ast_mutex_unlock(&iaxsl[callno]);
1026 res = iax_predestroy(callno);
1027 ast_mutex_lock(&iaxsl[callno]);
1031 static void iax_destroy(int callno)
1033 struct chan_iax_pvt *pvt;
1034 struct ast_iax_frame *cur;
1035 struct ast_channel *owner;
1038 ast_mutex_lock(&iaxsl[callno]);
1040 iaxs[callno] = NULL;
1047 if (ast_mutex_trylock(&owner->lock)) {
1048 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1049 ast_mutex_unlock(&iaxsl[callno]);
1056 /* No more pings or lagrq's */
1057 if (pvt->pingid > -1)
1058 ast_sched_del(sched, pvt->pingid);
1059 if (pvt->lagid > -1)
1060 ast_sched_del(sched, pvt->lagid);
1061 if (pvt->autoid > -1)
1062 ast_sched_del(sched, pvt->autoid);
1063 if (pvt->initid > -1)
1064 ast_sched_del(sched, pvt->initid);
1071 pvt->alreadygone = 1;
1074 /* If there's an owner, prod it to give up */
1075 owner->pvt->pvt = NULL;
1076 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1077 ast_queue_hangup(owner, 0);
1080 for (cur = iaxq.head; cur ; cur = cur->next) {
1081 /* Cancel any pending transmissions */
1082 if (cur->callno == pvt->callno)
1086 pvt->reg->callno = -1;
1091 ast_mutex_unlock(&owner->lock);
1093 ast_mutex_unlock(&iaxsl[callno]);
1095 static void iax_destroy_nolock(int callno)
1097 /* Actually it's easier to unlock, kill it, and relock */
1098 ast_mutex_unlock(&iaxsl[callno]);
1099 iax_destroy(callno);
1100 ast_mutex_lock(&iaxsl[callno]);
1105 static int attempt_transmit(void *data)
1107 /* Attempt to transmit the frame to the remote peer...
1108 Called without iaxsl held. */
1109 struct ast_iax_frame *f = data;
1111 int callno = f->callno;
1112 /* Make sure this call is still active */
1114 ast_mutex_lock(&iaxsl[callno]);
1115 if ((f->callno > -1) && iaxs[f->callno]) {
1116 if ((f->retries < 0) /* Already ACK'd */ ||
1117 (f->retries >= max_retries) /* Too many attempts */) {
1118 /* Record an error if we've transmitted too many times */
1119 if (f->retries >= max_retries) {
1121 /* Transfer timeout */
1122 send_command(iaxs[f->callno], AST_FRAME_IAX, AST_IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1123 } else if (f->final) {
1125 iax_destroy_nolock(f->callno);
1127 if (iaxs[f->callno]->owner)
1128 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);
1129 iaxs[f->callno]->error = ETIMEDOUT;
1130 if (iaxs[f->callno]->owner) {
1131 struct ast_frame fr = { 0, };
1133 fr.frametype = AST_FRAME_CONTROL;
1134 fr.subclass = AST_CONTROL_HANGUP;
1135 iax_queue_frame(f->callno, &fr);
1137 if (iaxs[f->callno]->reg) {
1138 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1139 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1140 iaxs[f->callno]->reg->refresh = AST_DEFAULT_REG_EXPIRE;
1142 iax_destroy_nolock(f->callno);
1149 /* Attempt transmission */
1152 /* Try again later after 10 times as long */
1154 if (f->retrytime > MAX_RETRY_TIME)
1155 f->retrytime = MAX_RETRY_TIME;
1156 /* Transfer messages max out at one second */
1157 if (f->transfer && (f->retrytime > 1000))
1158 f->retrytime = 1000;
1159 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1162 /* Make sure it gets freed */
1167 ast_mutex_unlock(&iaxsl[callno]);
1168 /* Do not try again */
1170 /* Don't attempt delivery, just remove it from the queue */
1171 ast_mutex_lock(&iaxq.lock);
1173 f->prev->next = f->next;
1175 iaxq.head = f->next;
1177 f->next->prev = f->prev;
1179 iaxq.tail = f->prev;
1181 ast_mutex_unlock(&iaxq.lock);
1182 /* Free the frame */
1185 ast_iax_frame_free(f);
1190 static int iax_set_jitter(int fd, int argc, char *argv[])
1192 if ((argc != 4) && (argc != 5))
1193 return RESULT_SHOWUSAGE;
1195 max_jitter_buffer = atoi(argv[3]);
1196 if (max_jitter_buffer < 0)
1197 max_jitter_buffer = 0;
1200 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < AST_IAX_MAX_CALLS)) {
1201 if (iaxs[atoi(argv[3])]) {
1202 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1203 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1204 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1206 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1208 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1211 return RESULT_SUCCESS;
1214 static char jitter_usage[] =
1215 "Usage: iax set jitter [callid] <value>\n"
1216 " If used with a callid, it sets the jitter buffer to the given static\n"
1217 "value (until its next calculation). If used without a callid, the value is used\n"
1218 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1219 "buffer size is reduced.";
1221 static int iax_show_stats(int fd, int argc, char *argv[])
1223 struct ast_iax_frame *cur;
1224 int cnt = 0, dead=0, final=0;
1226 return RESULT_SHOWUSAGE;
1227 for (cur = iaxq.head; cur ; cur = cur->next) {
1228 if (cur->retries < 0)
1234 ast_cli(fd, " IAX Statistics\n");
1235 ast_cli(fd, "---------------------\n");
1236 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", frames, iframes, oframes);
1237 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1238 return RESULT_SUCCESS;
1241 static int iax_show_cache(int fd, int argc, char *argv[])
1243 struct iax_dpcache *dp;
1244 char tmp[1024], *pc;
1248 gettimeofday(&tv, NULL);
1249 ast_mutex_lock(&dpcache_lock);
1251 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1253 s = dp->expirey.tv_sec - tv.tv_sec;
1255 if (dp->flags & CACHE_FLAG_EXISTS)
1256 strcat(tmp, "EXISTS|");
1257 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1258 strcat(tmp, "NONEXISTANT|");
1259 if (dp->flags & CACHE_FLAG_CANEXIST)
1260 strcat(tmp, "CANEXIST|");
1261 if (dp->flags & CACHE_FLAG_PENDING)
1262 strcat(tmp, "PENDING|");
1263 if (dp->flags & CACHE_FLAG_TIMEOUT)
1264 strcat(tmp, "TIMEOUT|");
1265 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1266 strcat(tmp, "TRANSMITTED|");
1267 if (dp->flags & CACHE_FLAG_MATCHMORE)
1268 strcat(tmp, "MATCHMORE|");
1269 if (dp->flags & CACHE_FLAG_UNKNOWN)
1270 strcat(tmp, "UNKNOWN|");
1271 /* Trim trailing pipe */
1273 tmp[strlen(tmp) - 1] = '\0';
1275 strcpy(tmp, "(none)");
1277 pc = strchr(dp->peercontext, '@');
1279 pc = dp->peercontext;
1282 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1283 if (dp->waiters[x] > -1)
1286 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1288 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1291 ast_mutex_unlock(&dpcache_lock);
1292 return RESULT_SUCCESS;
1295 static char show_stats_usage[] =
1296 "Usage: iax show stats\n"
1297 " Display statistics on IAX channel driver.\n";
1300 static char show_cache_usage[] =
1301 "Usage: iax show cache\n"
1302 " Display currently cached IAX Dialplan results.\n";
1304 static struct ast_cli_entry cli_set_jitter =
1305 { { "iax", "set", "jitter", NULL }, iax_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1307 static struct ast_cli_entry cli_show_stats =
1308 { { "iax", "show", "stats", NULL }, iax_show_stats, "Display IAX statistics", show_stats_usage };
1310 static struct ast_cli_entry cli_show_cache =
1311 { { "iax", "show", "cache", NULL }, iax_show_cache, "Display IAX cached dialplan", show_cache_usage };
1313 static unsigned int calc_rxstamp(struct chan_iax_pvt *p);
1315 #ifdef BRIDGE_OPTIMIZATION
1316 static unsigned int calc_fakestamp(struct chan_iax_pvt *from, struct chan_iax_pvt *to, unsigned int ts);
1318 static int forward_delivery(struct ast_iax_frame *fr)
1320 struct chan_iax_pvt *p1, *p2;
1321 p1 = iaxs[fr->callno];
1322 p2 = iaxs[p1->bridgecallno];
1327 /* Fix relative timestamp */
1328 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1329 /* Now just send it send on the 2nd one
1330 with adjusted timestamp */
1331 return iax_send(p2, fr->f, fr->ts, -1, 0, 0, 0);
1335 static int schedule_delivery(struct ast_iax_frame *fr, int reallydeliver)
1338 int drops[MEMORY_SIZE];
1339 int min, max=0, maxone=0,y,z, match;
1340 /* ms is a measure of the "lateness" of the packet relative to the first
1341 packet we received, which always has a lateness of 1. Called by
1342 IAX thread, with iaxsl lock held. */
1343 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1346 /* What likely happened here is that our counter has circled but we haven't
1347 gotten the update from the main packet. We'll just pretend that we did, and
1348 update the timestamp appropriately. */
1353 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1358 /* Rotate our history queue of "lateness". Don't worry about those initial
1359 zeros because the first entry will always be zero */
1360 for (x=0;x<MEMORY_SIZE - 1;x++)
1361 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1362 /* Add a history entry for this one */
1363 iaxs[fr->callno]->history[x] = ms;
1365 /* Initialize the minimum to reasonable values. It's too much
1366 work to do the same for the maximum, repeatedly */
1367 min=iaxs[fr->callno]->history[0];
1368 for (z=0;z < iax_dropcount + 1;z++) {
1369 /* Start very optimistic ;-) */
1371 for (x=0;x<MEMORY_SIZE;x++) {
1372 if (max < iaxs[fr->callno]->history[x]) {
1373 /* We have a candidate new maximum value. Make
1374 sure it's not in our drop list */
1376 for (y=0;!match && (y<z);y++)
1377 match |= (drops[y] == x);
1379 /* It's not in our list, use it as the new maximum */
1380 max = iaxs[fr->callno]->history[x];
1386 /* On our first pass, find the minimum too */
1387 if (min > iaxs[fr->callno]->history[x])
1388 min = iaxs[fr->callno]->history[x];
1395 /* Just for reference, keep the "jitter" value, the difference between the
1396 earliest and the latest. */
1397 iaxs[fr->callno]->jitter = max - min;
1399 /* IIR filter for keeping track of historic jitter, but always increase
1400 historic jitter immediately for increase */
1402 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1403 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1405 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1406 iaxs[fr->callno]->historicjitter;
1408 /* If our jitter buffer is too big (by a significant margin), then we slowly
1409 shrink it by about 1 ms each time to avoid letting the change be perceived */
1410 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1411 iaxs[fr->callno]->jitterbuffer -= 2;
1415 /* Constrain our maximum jitter buffer appropriately */
1416 if (max > min + maxjitterbuffer) {
1418 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1419 max = min + maxjitterbuffer;
1423 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1424 buffer immediately to accomodate it (and a little more). */
1425 if (max > iaxs[fr->callno]->jitterbuffer)
1426 iaxs[fr->callno]->jitterbuffer = max
1427 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1431 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1433 /* Subtract the lateness from our jitter buffer to know how long to wait
1434 before sending our packet. */
1435 ms = iaxs[fr->callno]->jitterbuffer - ms;
1437 if (!use_jitterbuffer)
1440 /* If the caller just wanted us to update, return now */
1446 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1447 /* Don't deliver it more than 4 ms late */
1448 if ((ms > -4) || (fr->f->frametype != AST_FRAME_VOICE)) {
1452 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1453 /* Free the packet */
1455 /* And our iax frame */
1456 ast_iax_frame_free(fr);
1460 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1461 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1466 static int iax_transmit(struct ast_iax_frame *fr)
1468 /* Lock the queue and place this packet at the end */
1471 /* By setting this to 0, the network thread will send it for us, and
1472 queue retransmission if necessary */
1474 ast_mutex_lock(&iaxq.lock);
1481 iaxq.tail->next = fr;
1482 fr->prev = iaxq.tail;
1486 ast_mutex_unlock(&iaxq.lock);
1487 /* Wake up the network thread */
1488 pthread_kill(netthreadid, SIGURG);
1494 static int iax_digit(struct ast_channel *c, char digit)
1496 return send_command(c->pvt->pvt, AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1499 static int iax_sendtext(struct ast_channel *c, char *text)
1502 return send_command(c->pvt->pvt, AST_FRAME_TEXT,
1503 0, 0, text, strlen(text) + 1, -1);
1506 static int iax_sendimage(struct ast_channel *c, struct ast_frame *img)
1508 return send_command(c->pvt->pvt, AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1511 static int iax_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1513 return send_command(c->pvt->pvt, AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1516 static int iax_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1518 struct chan_iax_pvt *pvt = newchan->pvt->pvt;
1519 pvt->owner = newchan;
1523 #ifdef MYSQL_FRIENDS
1525 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1527 if (mysql && (strlen(peer) < 128)) {
1531 name = alloca(strlen(peer) * 2 + 1);
1533 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1534 snprintf(query, sizeof(query), "UPDATE iax1friends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1535 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1536 ast_mutex_lock(&mysqllock);
1537 if (mysql_real_query(mysql, query, strlen(query)))
1538 ast_log(LOG_WARNING, "Unable to update database\n");
1540 ast_mutex_unlock(&mysqllock);
1544 static struct iax_peer *mysql_peer(char *peer)
1549 p = malloc(sizeof(struct iax_peer));
1550 memset(p, 0, sizeof(struct iax_peer));
1551 if (mysql && (strlen(peer) < 128)) {
1556 time_t regseconds, nowtime;
1558 MYSQL_FIELD *fields;
1560 name = alloca(strlen(peer) * 2 + 1);
1561 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1562 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1563 ast_mutex_lock(&mysqllock);
1564 mysql_query(mysql, query);
1565 if ((result = mysql_store_result(mysql))) {
1566 if ((rowval = mysql_fetch_row(result))) {
1567 numfields = mysql_num_fields(result);
1568 fields = mysql_fetch_fields(result);
1570 for (x=0;x<numfields;x++) {
1572 if (!strcasecmp(fields[x].name, "secret")) {
1573 strncpy(p->secret, rowval[x], sizeof(p->secret));
1574 } else if (!strcasecmp(fields[x].name, "context")) {
1575 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1576 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1577 inet_aton(rowval[x], &p->addr.sin_addr);
1578 } else if (!strcasecmp(fields[x].name, "port")) {
1579 if (sscanf(rowval[x], "%i", &port) != 1)
1581 p->addr.sin_port = htons(port);
1582 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1583 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1589 if ((nowtime - regseconds) > AST_DEFAULT_REG_EXPIRE)
1590 memset(&p->addr, 0, sizeof(p->addr));
1593 ast_mutex_unlock(&mysqllock);
1599 strncpy(p->name, peer, sizeof(p->name) - 1);
1603 p->capability = iax_capability;
1604 strcpy(p->methods, "md5,plaintext");
1609 static struct iax_user *mysql_user(char *user)
1612 struct iax_context *con;
1615 p = malloc(sizeof(struct iax_user));
1616 memset(p, 0, sizeof(struct iax_user));
1617 con = malloc(sizeof(struct iax_context));
1618 memset(con, 0, sizeof(struct iax_context));
1619 strcpy(con->context, "default");
1621 if (mysql && (strlen(user) < 128)) {
1626 MYSQL_FIELD *fields;
1628 name = alloca(strlen(user) * 2 + 1);
1629 mysql_real_escape_string(mysql, name, user, strlen(user));
1630 snprintf(query, sizeof(query), "SELECT * FROM iax1friends WHERE name=\"%s\"", name);
1631 ast_mutex_lock(&mysqllock);
1632 mysql_query(mysql, query);
1633 if ((result = mysql_store_result(mysql))) {
1634 if ((rowval = mysql_fetch_row(result))) {
1635 numfields = mysql_num_fields(result);
1636 fields = mysql_fetch_fields(result);
1638 for (x=0;x<numfields;x++) {
1640 if (!strcasecmp(fields[x].name, "secret")) {
1641 strncpy(p->secret, rowval[x], sizeof(p->secret));
1642 } else if (!strcasecmp(fields[x].name, "context")) {
1643 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1649 ast_mutex_unlock(&mysqllock);
1657 strncpy(p->name, user, sizeof(p->name) - 1);
1659 strcpy(p->methods, "md5,plaintext");
1663 #endif /* MYSQL_FRIENDS */
1665 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context)
1674 sin->sin_family = AF_INET;
1675 ast_mutex_lock(&peerl.lock);
1678 if (!strcasecmp(p->name, peer)) {
1683 #ifdef MYSQL_FRIENDS
1685 p = mysql_peer(peer);
1690 *capability = p->capability;
1691 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1692 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1694 *sendani = p->sendani; /* Whether we transmit ANI */
1696 *maxtime = p->maxms; /* Max time they should take */
1698 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1699 if (p->addr.sin_addr.s_addr) {
1700 sin->sin_addr = p->addr.sin_addr;
1701 sin->sin_port = p->addr.sin_port;
1703 sin->sin_addr = p->defaddr.sin_addr;
1704 sin->sin_port = p->defaddr.sin_port;
1712 ast_mutex_unlock(&peerl.lock);
1714 hp = gethostbyname(peer);
1716 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1717 sin->sin_port = htons(AST_DEFAULT_IAX_PORTNO);
1720 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1730 static int auto_congest(void *nothing)
1732 int callno = (int)(long)(nothing);
1733 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
1734 ast_mutex_lock(&iaxsl[callno]);
1736 iaxs[callno]->initid = -1;
1737 iax_queue_frame(callno, &f);
1738 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
1740 ast_mutex_unlock(&iaxsl[callno]);
1744 static int iax_call(struct ast_channel *c, char *dest, int timeout)
1746 struct sockaddr_in sin;
1751 char *secret = NULL;
1753 char requeststr[256] = "";
1754 char myrdest [5] = "s";
1755 char context[AST_MAX_EXTENSION] ="";
1756 char *portno = NULL;
1757 struct chan_iax_pvt *p = c->pvt->pvt;
1759 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
1760 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
1763 strncpy(host, dest, sizeof(host)-1);
1765 strsep(&stringp, "/");
1766 /* If no destination extension specified, use 's' */
1767 rdest = strsep(&stringp, "/");
1771 strsep(&stringp, "@");
1772 rcontext = strsep(&stringp, "@");
1774 strsep(&stringp, "@");
1775 username = strsep(&stringp, "@");
1777 /* Really the second argument is the host, not the username */
1785 username = strsep(&stringp, ":");
1786 secret = strsep(&stringp, ":");
1789 if (strsep(&stringp, ":")) {
1791 strsep(&stringp, ":");
1792 portno = strsep(&stringp, ":");
1794 if (create_addr(&sin, NULL, NULL, NULL, hname, context)) {
1795 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
1798 /* Keep track of the context for outgoing calls too */
1799 strncpy(c->context, context, sizeof(c->context) - 1);
1801 sin.sin_port = htons(atoi(portno));
1803 /* Now we build our request string */
1804 #define MYSNPRINTF snprintf(requeststr + strlen(requeststr), sizeof(requeststr) - strlen(requeststr),
1805 #define MYSNPRINTF2 snprintf(requeststr + strlen(requeststr), reqsize - strlen(requeststr),
1806 MYSNPRINTF "exten=%s;", rdest);
1808 MYSNPRINTF "callerid=%s;", c->callerid);
1809 if (p->sendani && c->ani)
1810 MYSNPRINTF "ani=%s;", c->ani);
1811 if (c->language && strlen(c->language))
1812 MYSNPRINTF "language=%s;", c->language);
1814 MYSNPRINTF "dnid=%s;", c->dnid);
1816 MYSNPRINTF "context=%s;", rcontext);
1818 MYSNPRINTF "username=%s;", username);
1820 if (secret[0] == '[') {
1821 /* This is an RSA key, not a normal secret */
1822 strncpy(p->outkey, secret + 1, sizeof(p->secret)-1);
1823 if (strlen(p->outkey)) {
1824 p->outkey[strlen(p->outkey) - 1] = '\0';
1827 strncpy(p->secret, secret, sizeof(p->secret)-1);
1829 MYSNPRINTF "formats=%d;", c->nativeformats);
1830 MYSNPRINTF "capability=%d;", p->capability);
1831 MYSNPRINTF "version=%d;", AST_IAX_PROTO_VERSION);
1832 MYSNPRINTF "adsicpe=%d;", c->adsicpe);
1833 /* Trim the trailing ";" */
1834 if (strlen(requeststr))
1835 requeststr[strlen(requeststr) - 1] = '\0';
1836 /* Transmit the string in a "NEW" request */
1837 if (option_verbose > 2)
1838 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
1840 /* Initialize pingtime and auto-congest time */
1841 p->pingtime = p->maxtime / 2;
1842 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, (void *)p->callno);
1844 send_command(p, AST_FRAME_IAX,
1845 AST_IAX_COMMAND_NEW, 0, requeststr, strlen(requeststr) + 1, -1);
1846 ast_setstate(c, AST_STATE_RINGING);
1850 static int iax_hangup(struct ast_channel *c)
1852 struct chan_iax_pvt *pvt = c->pvt->pvt;
1856 callno = pvt->callno;
1857 ast_mutex_lock(&iaxsl[callno]);
1858 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
1859 alreadygone = pvt->alreadygone;
1860 /* Send the hangup unless we have had a transmission error or are already gone */
1861 if (!pvt->error && !alreadygone)
1862 send_command_final(pvt, AST_FRAME_IAX, AST_IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
1863 /* Explicitly predestroy it */
1864 iax_predestroy_nolock(callno);
1865 /* If we were already gone to begin with, destroy us now */
1867 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
1868 iax_destroy_nolock(callno);
1870 ast_mutex_unlock(&iaxsl[callno]);
1872 if (option_verbose > 2)
1873 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
1877 static int iax_setoption(struct ast_channel *c, int option, void *data, int datalen)
1879 struct ast_option_header *h;
1881 h = malloc(datalen + sizeof(struct ast_option_header));
1883 h->flag = AST_OPTION_FLAG_REQUEST;
1884 h->option = htons(option);
1885 memcpy(h->data, data, datalen);
1886 res = send_command((struct chan_iax_pvt *)c->pvt->pvt, AST_FRAME_CONTROL,
1887 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
1891 ast_log(LOG_WARNING, "Out of memory\n");
1894 static struct ast_frame *iax_read(struct ast_channel *c)
1896 static struct ast_frame f = { AST_FRAME_NULL, };
1897 ast_log(LOG_NOTICE, "I should never be called!\n");
1901 static int iax_start_transfer(struct ast_channel *c0, struct ast_channel *c1)
1906 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1907 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1908 snprintf(req0, sizeof(req0), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p1->addr.sin_addr), ntohs(p1->addr.sin_port), p1->peercallno);
1909 snprintf(req1, sizeof(req1), "remip=%s;remport=%d;remcall=%d;", inet_ntoa(p0->addr.sin_addr), ntohs(p0->addr.sin_port), p0->peercallno);
1910 res = send_command(p0, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req0, strlen(req0) + 1, -1);
1913 res = send_command(p1, AST_FRAME_IAX, AST_IAX_COMMAND_TXREQ, 0, req1, strlen(req1) + 1, -1);
1916 p0->transferring = TRANSFER_BEGIN;
1917 p1->transferring = TRANSFER_BEGIN;
1921 static int iax_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1923 struct ast_channel *cs[3];
1924 struct ast_channel *who;
1927 int transferstarted=0;
1928 struct ast_frame *f;
1929 struct chan_iax_pvt *p0 = c0->pvt->pvt;
1930 struct chan_iax_pvt *p1 = c1->pvt->pvt;
1932 /* Put them in native bridge mode */
1933 p0->bridgecallno = p1->callno;
1934 p1->bridgecallno = p0->callno;
1936 /* If not, try to bridge until we can execute a transfer, if we can */
1939 for (/* ever */;;) {
1940 /* Check in case we got masqueraded into */
1941 if ((c0->type != type) || (c1->type != type)) {
1942 if (option_verbose > 2)
1943 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
1946 if (c0->nativeformats != c1->nativeformats) {
1947 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
1950 if (!transferstarted) {
1951 /* Try the transfer */
1952 if (iax_start_transfer(c0, c1))
1953 ast_log(LOG_WARNING, "Unable to start the transfer\n");
1954 transferstarted = 1;
1957 if ((p0->transferring == TRANSFER_RELEASED) && (p1->transferring == TRANSFER_RELEASED)) {
1958 /* Call has been transferred. We're no longer involved */
1960 c0->_softhangup |= AST_SOFTHANGUP_DEV;
1961 c1->_softhangup |= AST_SOFTHANGUP_DEV;
1968 who = ast_waitfor_n(cs, 2, &to);
1970 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
1983 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1989 if ((f->frametype == AST_FRAME_VOICE) ||
1990 (f->frametype == AST_FRAME_TEXT) ||
1991 (f->frametype == AST_FRAME_VIDEO) ||
1992 (f->frametype == AST_FRAME_IMAGE) ||
1993 (f->frametype == AST_FRAME_DTMF)) {
1994 if ((f->frametype == AST_FRAME_DTMF) &&
1995 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1997 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2000 /* Take out of conference mode */
2007 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2017 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2019 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2031 /* Swap who gets priority */
2036 p0->bridgecallno = -1;
2037 p1->bridgecallno = -1;
2041 static int iax_answer(struct ast_channel *c)
2043 struct chan_iax_pvt *pvt = c->pvt->pvt;
2045 ast_log(LOG_DEBUG, "Answering\n");
2046 return send_command(pvt, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2049 static int iax_indicate(struct ast_channel *c, int condition)
2051 struct chan_iax_pvt *pvt = c->pvt->pvt;
2053 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2054 return send_command(pvt, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2058 static int iax_write(struct ast_channel *c, struct ast_frame *f);
2060 static int iax_getpeername(struct sockaddr_in sin, char *host, int len)
2062 struct iax_peer *peer;
2064 ast_mutex_lock(&peerl.lock);
2067 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2068 (peer->addr.sin_port == sin.sin_port)) {
2069 strncpy(host, peer->name, len-1);
2075 ast_mutex_unlock(&peerl.lock);
2079 static struct ast_channel *ast_iax_new(struct chan_iax_pvt *i, int state, int capability)
2082 struct ast_channel *tmp;
2083 tmp = ast_channel_alloc(1);
2085 if (!iax_getpeername(i->addr, host, sizeof(host)))
2086 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(i->addr.sin_addr), ntohs(i->addr.sin_port));
2087 if (strlen(i->username))
2088 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s@%s]/%d", i->username, host, i->callno);
2090 snprintf(tmp->name, sizeof(tmp->name), "IAX[%s]/%d", host, i->callno);
2092 /* We can support any format by default, until we get restricted */
2093 tmp->nativeformats = capability;
2094 tmp->readformat = 0;
2095 tmp->writeformat = 0;
2097 tmp->pvt->send_digit = iax_digit;
2098 tmp->pvt->send_text = iax_sendtext;
2099 tmp->pvt->send_image = iax_sendimage;
2100 tmp->pvt->send_html = iax_sendhtml;
2101 tmp->pvt->call = iax_call;
2102 tmp->pvt->hangup = iax_hangup;
2103 tmp->pvt->answer = iax_answer;
2104 tmp->pvt->read = iax_read;
2105 tmp->pvt->write = iax_write;
2106 tmp->pvt->indicate = iax_indicate;
2107 tmp->pvt->setoption = iax_setoption;
2108 tmp->pvt->bridge = iax_bridge;
2109 if (strlen(i->callerid))
2110 tmp->callerid = strdup(i->callerid);
2112 tmp->ani = strdup(i->ani);
2113 if (strlen(i->language))
2114 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2115 if (strlen(i->dnid))
2116 tmp->dnid = strdup(i->dnid);
2117 if (strlen(i->accountcode))
2118 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2120 tmp->amaflags = i->amaflags;
2121 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2122 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2123 tmp->adsicpe = i->peeradsicpe;
2124 tmp->pvt->fixup = iax_fixup;
2126 i->capability = capability;
2127 ast_setstate(tmp, state);
2128 ast_mutex_lock(&usecnt_lock);
2130 ast_mutex_unlock(&usecnt_lock);
2131 ast_update_use_count();
2132 if (state != AST_STATE_DOWN) {
2133 if (ast_pbx_start(tmp)) {
2134 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2143 static unsigned int calc_timestamp(struct chan_iax_pvt *p, unsigned int ts)
2147 if (!p->offset.tv_sec && !p->offset.tv_usec)
2148 gettimeofday(&p->offset, NULL);
2149 /* If the timestamp is specified, just send it as is */
2152 gettimeofday(&tv, NULL);
2153 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2154 /* We never send the same timestamp twice, so fudge a little if we must */
2155 if (ms <= p->lastsent)
2156 ms = p->lastsent + 1;
2161 #ifdef BRIDGE_OPTIMIZATION
2162 static unsigned int calc_fakestamp(struct chan_iax_pvt *p1, struct chan_iax_pvt *p2, unsigned int fakets)
2165 /* Receive from p1, send to p2 */
2167 /* Setup rxcore if necessary on outgoing channel */
2168 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2169 gettimeofday(&p1->rxcore, NULL);
2171 /* Setup txcore if necessary on outgoing channel */
2172 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2173 gettimeofday(&p2->offset, NULL);
2175 /* Now, ts is the timestamp of the original packet in the orignal context.
2176 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2177 Subtracting txcore of the outgoing channel gives us what we'd expect */
2179 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p1->offset.tv_usec) / 1000;
2181 if (fakets <= p2->lastsent)
2182 fakets = p2->lastsent + 1;
2183 p2->lastsent = fakets;
2188 static unsigned int calc_rxstamp(struct chan_iax_pvt *p)
2190 /* Returns where in "receive time" we are */
2193 /* Setup rxcore if necessary */
2194 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2195 gettimeofday(&p->rxcore, NULL);
2197 gettimeofday(&tv, NULL);
2198 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2202 static int iax_send(struct chan_iax_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2204 /* Queue a packet for delivery on a given private structure. Use "ts" for
2205 timestamp, or calculate if ts is 0. Send immediately without retransmission
2206 or delayed, with retransmission */
2207 struct ast_iax_full_hdr *fh;
2208 struct ast_iax_mini_hdr *mh;
2209 struct ast_iax_frame *fr, fr2;
2211 unsigned int lastsent;
2212 /* Allocate an ast_iax_frame */
2216 fr = ast_iax_frame_new(DIRECTION_OUTGRESS);
2218 ast_log(LOG_WARNING, "Out of memory\n");
2222 ast_log(LOG_WARNING, "No private structure for packet (%d)?\n", fr->callno);
2224 ast_iax_frame_free(fr);
2227 /* Isolate our frame for transmission */
2228 fr->f = ast_frdup(f);
2231 ast_log(LOG_WARNING, "Out of memory\n");
2233 ast_iax_frame_free(fr);
2236 if (fr->f->offset < sizeof(struct ast_iax_full_hdr)) {
2237 ast_log(LOG_WARNING, "Packet from '%s' not friendly\n", fr->f->src);
2241 lastsent = pvt->lastsent;
2242 fr->ts = calc_timestamp(pvt, ts);
2244 ast_log(LOG_WARNING, "timestamp is 0?\n");
2246 ast_iax_frame_free(fr);
2249 fr->callno = pvt->callno;
2250 fr->transfer = transfer;
2252 if (((fr->ts & 0xFFFF0000L) != (lastsent & 0xFFFF0000L))
2253 /* High two bits of timestamp differ */ ||
2254 (fr->f->frametype != AST_FRAME_VOICE)
2255 /* or not a voice frame */ ||
2256 (fr->f->subclass != pvt->svoiceformat)
2257 /* or new voice format */ ) {
2258 /* We need a full frame */
2262 fr->seqno = pvt->oseqno++;
2263 fh = (struct ast_iax_full_hdr *)(fr->f->data - sizeof(struct ast_iax_full_hdr));
2264 fh->callno = htons(fr->callno | AST_FLAG_FULL);
2265 fh->ts = htonl(fr->ts);
2266 fh->seqno = htons(fr->seqno);
2267 fh->type = fr->f->frametype & 0xFF;
2268 fh->csub = compress_subclass(fr->f->subclass);
2270 fh->dcallno = htons(pvt->transfercallno);
2272 fh->dcallno = htons(pvt->peercallno);
2273 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_full_hdr);
2276 /* Retry after 2x the ping time has passed */
2277 fr->retrytime = pvt->pingtime * 2;
2278 if (fr->retrytime < MIN_RETRY_TIME)
2279 fr->retrytime = MIN_RETRY_TIME;
2280 if (fr->retrytime > MAX_RETRY_TIME)
2281 fr->retrytime = MAX_RETRY_TIME;
2282 /* Acks' don't get retried */
2283 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == AST_IAX_COMMAND_ACK))
2285 if (f->frametype == AST_FRAME_VOICE) {
2286 pvt->svoiceformat = f->subclass;
2289 res = send_packet(fr);
2292 res = iax_transmit(fr);
2294 /* Mini-frames have no sequence number */
2296 /* Mini frame will do */
2297 mh = (struct ast_iax_mini_hdr *)(fr->f->data - sizeof(struct ast_iax_mini_hdr));
2298 mh->callno = htons(fr->callno);
2299 mh->ts = htons(fr->ts & 0xFFFF);
2300 fr->datalen = fr->f->datalen + sizeof(struct ast_iax_mini_hdr);
2304 res = send_packet(fr);
2307 res = iax_transmit(fr);
2314 static int iax_show_users(int fd, int argc, char *argv[])
2316 #define FORMAT "%-15.15s %-15.15s %-15.15s %-15.15s %-5.5s\n"
2317 struct iax_user *user;
2319 return RESULT_SHOWUSAGE;
2320 ast_mutex_lock(&userl.lock);
2321 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2322 for(user=userl.users;user;user=user->next) {
2323 ast_cli(fd, FORMAT, user->name, user->secret, user->methods,
2324 user->contexts ? user->contexts->context : context,
2325 user->ha ? "Yes" : "No");
2327 ast_mutex_unlock(&userl.lock);
2328 return RESULT_SUCCESS;
2332 static int iax_show_peers(int fd, int argc, char *argv[])
2334 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2335 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-8d %-10s\n"
2336 struct iax_peer *peer;
2337 char name[256] = "";
2339 return RESULT_SHOWUSAGE;
2340 ast_mutex_lock(&peerl.lock);
2341 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2342 for (peer = peerl.peers;peer;peer = peer->next) {
2345 if (strlen(peer->username))
2346 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2348 strncpy(name, peer->name, sizeof(name) - 1);
2350 if (peer->lastms < 0)
2351 strcpy(status, "UNREACHABLE");
2352 else if (peer->lastms > peer->maxms)
2353 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2354 else if (peer->lastms)
2355 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2357 strcpy(status, "UNKNOWN");
2359 strcpy(status, "Unmonitored");
2360 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2361 ast_cli(fd, FORMAT, name,
2362 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2363 peer->dynamic ? "(D)" : "(S)",
2365 ntohs(peer->addr.sin_port), status);
2367 ast_mutex_unlock(&peerl.lock);
2368 return RESULT_SUCCESS;
2373 /* JDG: callback to display iax peers in manager */
2374 static int manager_iax_show_peers( struct mansession *s, struct message *m )
2376 char *a[] = { "iax", "show", "users" };
2378 ret = iax_show_peers( s->fd, 3, a );
2379 ast_cli( s->fd, "\r\n" );
2383 static char *regstate2str(int regstate)
2386 case REG_STATE_UNREGISTERED:
2387 return "Unregistered";
2388 case REG_STATE_REGSENT:
2389 return "Request Sent";
2390 case REG_STATE_AUTHSENT:
2391 return "Auth. Sent";
2392 case REG_STATE_REGISTERED:
2393 return "Registered";
2394 case REG_STATE_REJECTED:
2396 case REG_STATE_TIMEOUT:
2398 case REG_STATE_NOAUTH:
2399 return "No Authentication";
2405 static int iax_show_registry(int fd, int argc, char *argv[])
2407 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2408 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2409 struct iax_registry *reg;
2413 return RESULT_SHOWUSAGE;
2414 ast_mutex_lock(&peerl.lock);
2415 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2416 for (reg = registrations;reg;reg = reg->next) {
2417 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2418 if (reg->us.sin_addr.s_addr)
2419 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2421 strcpy(perceived, "<Unregistered>");
2422 ast_cli(fd, FORMAT, host,
2423 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2425 ast_mutex_unlock(&peerl.lock);
2426 return RESULT_SUCCESS;
2431 static int iax_show_channels(int fd, int argc, char *argv[])
2433 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2434 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2438 return RESULT_SHOWUSAGE;
2439 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2440 for (x=0;x<AST_IAX_MAX_CALLS;x++) {
2441 ast_mutex_lock(&iaxsl[x]);
2443 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
2444 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
2445 iaxs[x]->callno, iaxs[x]->peercallno,
2446 iaxs[x]->oseqno, iaxs[x]->iseqno,
2449 ast_getformatname(iaxs[x]->voiceformat) );
2452 ast_mutex_unlock(&iaxsl[x]);
2454 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
2455 return RESULT_SUCCESS;
2460 static int iax_do_debug(int fd, int argc, char *argv[])
2463 return RESULT_SHOWUSAGE;
2465 ast_cli(fd, "IAX Debugging Enabled\n");
2466 return RESULT_SUCCESS;
2469 static int iax_no_debug(int fd, int argc, char *argv[])
2472 return RESULT_SHOWUSAGE;
2474 ast_cli(fd, "IAX Debugging Disabled\n");
2475 return RESULT_SUCCESS;
2480 static char show_users_usage[] =
2481 "Usage: iax show users\n"
2482 " Lists all users known to the IAX (Inter-Asterisk eXchange) subsystem.\n";
2484 static char show_channels_usage[] =
2485 "Usage: iax show channels\n"
2486 " Lists all currently active IAX channels.\n";
2488 static char show_peers_usage[] =
2489 "Usage: iax show peers\n"
2490 " Lists all known IAX peers.\n";
2492 static char show_reg_usage[] =
2493 "Usage: iax show registry\n"
2494 " Lists all registration requests and status.\n";
2496 #ifdef DEBUG_SUPPORT
2498 static char debug_usage[] =
2499 "Usage: iax debug\n"
2500 " Enables dumping of IAX packets for debugging purposes\n";
2502 static char no_debug_usage[] =
2503 "Usage: iax no debug\n"
2504 " Disables dumping of IAX packets for debugging purposes\n";
2508 static struct ast_cli_entry cli_show_users =
2509 { { "iax", "show", "users", NULL }, iax_show_users, "Show defined IAX users", show_users_usage };
2510 static struct ast_cli_entry cli_show_channels =
2511 { { "iax", "show", "channels", NULL }, iax_show_channels, "Show active IAX channels", show_channels_usage };
2512 static struct ast_cli_entry cli_show_peers =
2513 { { "iax", "show", "peers", NULL }, iax_show_peers, "Show defined IAX peers", show_peers_usage };
2514 static struct ast_cli_entry cli_show_registry =
2515 { { "iax", "show", "registry", NULL }, iax_show_registry, "Show IAX registration status", show_reg_usage };
2516 static struct ast_cli_entry cli_debug =
2517 { { "iax", "debug", NULL }, iax_do_debug, "Enable IAX debugging", debug_usage };
2518 static struct ast_cli_entry cli_no_debug =
2519 { { "iax", "no", "debug", NULL }, iax_no_debug, "Disable IAX debugging", no_debug_usage };
2521 static int iax_write(struct ast_channel *c, struct ast_frame *f)
2523 struct chan_iax_pvt *i = c->pvt->pvt;
2526 /* If there's an outstanding error, return failure now */
2528 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
2531 /* If it's already gone, just return */
2534 /* Don't waste bandwidth sending null frames */
2535 if (f->frametype == AST_FRAME_NULL)
2537 /* If we're quelching voice, don't bother sending it */
2538 if ((f->frametype == AST_FRAME_VOICE) && i->quelch)
2540 /* Simple, just queue for transmission */
2541 return iax_send(i, f, 0, -1, 0, 0, 0);
2544 static int __send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
2545 int now, int transfer, int final)
2549 f.subclass = command;
2550 f.datalen = datalen;
2554 f.src = __FUNCTION__;
2556 return iax_send(i, &f, ts, seqno, now, transfer, final);
2559 static int send_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2561 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
2564 #ifdef BRIDGE_OPTIMIZATION
2565 static int forward_command(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2567 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
2571 static int send_command_final(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2573 /* It is assumed that the callno has already been locked */
2574 iax_predestroy_nolock(i->callno);
2575 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
2578 static int send_command_immediate(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
2580 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
2583 static int send_command_transfer(struct chan_iax_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
2585 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
2588 static int apply_context(struct iax_context *con, char *context)
2591 if (!strcmp(con->context, context))
2598 static int iax_getformats(int callno, char *orequest)
2603 strncpy(request, orequest, sizeof(request)-1);
2605 var = strsep(&stringp, ";");
2607 value = strchr(var, '=');
2611 if (!strcmp(var, "formats")) {
2612 iaxs[callno]->peerformat = atoi(value);
2614 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2616 var = strsep(&stringp, ";");
2622 static int check_access(int callno, struct sockaddr_in *sin, char *orequest, int requestl)
2624 /* Start pessimistic */
2628 struct iax_user *user;
2630 int gotcapability=0;
2632 strncpy(request, orequest, sizeof(request)-1);
2636 var = strsep(&stringp, ";");
2638 value = strchr(var, '=');
2642 if (!strcmp(var, "exten"))
2643 strncpy(iaxs[callno]->exten, value, sizeof(iaxs[callno]->exten)-1);
2644 else if (!strcmp(var, "callerid"))
2645 strncpy(iaxs[callno]->callerid, value, sizeof(iaxs[callno]->callerid)-1);
2646 else if (!strcmp(var, "ani"))
2647 strncpy(iaxs[callno]->ani, value, sizeof(iaxs[callno]->ani) - 1);
2648 else if (!strcmp(var, "dnid"))
2649 strncpy(iaxs[callno]->dnid, value, sizeof(iaxs[callno]->dnid)-1);
2650 else if (!strcmp(var, "context"))
2651 strncpy(iaxs[callno]->context, value, sizeof(iaxs[callno]->context)-1);
2652 else if (!strcmp(var, "language"))
2653 strncpy(iaxs[callno]->language, value, sizeof(iaxs[callno]->language)-1);
2654 else if (!strcmp(var, "username"))
2655 strncpy(iaxs[callno]->username, value, sizeof(iaxs[callno]->username)-1);
2656 else if (!strcmp(var, "formats"))
2657 iaxs[callno]->peerformat = atoi(value);
2658 else if (!strcmp(var, "adsicpe"))
2659 iaxs[callno]->peeradsicpe = atoi(value);
2660 else if (!strcmp(var, "capability")) {
2662 iaxs[callno]->peercapability = atoi(value);
2663 } else if (!strcmp(var, "version"))
2664 version = atoi(value);
2666 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2668 var = strsep(&stringp, ";");
2671 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
2672 if (version > AST_IAX_PROTO_VERSION) {
2673 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
2674 inet_ntoa(sin->sin_addr), version);
2677 ast_mutex_lock(&userl.lock);
2678 /* Search the userlist for a compatible entry, and fill in the rest */
2681 if ((!strlen(iaxs[callno]->username) || /* No username specified */
2682 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
2683 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
2684 && (!strlen(iaxs[callno]->context) || /* No context specified */
2685 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
2690 #ifdef MYSQL_FRIENDS
2691 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
2692 user = mysql_user(iaxs[callno]->username);
2693 if (user && strlen(iaxs[callno]->context) && /* No context specified */
2694 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
2696 free(user->contexts);
2702 ast_mutex_unlock(&userl.lock);
2704 /* We found our match (use the first) */
2706 /* Store the requested username if not specified */
2707 if (!strlen(iaxs[callno]->username))
2708 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
2709 /* And use the default context */
2710 if (!strlen(iaxs[callno]->context)) {
2712 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
2714 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
2716 /* Copy the secret */
2717 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
2718 /* And any input keys */
2719 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
2720 /* And the permitted authentication methods */
2721 strncpy(iaxs[callno]->methods, user->methods, sizeof(iaxs[callno]->methods)-1);
2722 /* If they have callerid, override the given caller id. Always store the ANI */
2723 if (strlen(iaxs[callno]->callerid)) {
2724 if (user->hascallerid)
2725 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
2726 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
2728 if (strlen(user->accountcode))
2729 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
2731 iaxs[callno]->amaflags = user->amaflags;
2737 static int raw_hangup(struct sockaddr_in *sin, short src, short dst)
2739 struct ast_iax_full_hdr fh;
2740 fh.callno = htons(src | AST_FLAG_FULL);
2741 fh.dcallno = htons(dst);
2744 fh.type = AST_FRAME_IAX;
2745 fh.csub = compress_subclass(AST_IAX_COMMAND_INVAL);
2749 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
2750 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
2751 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
2754 static int authenticate_request(struct chan_iax_pvt *p)
2756 char requeststr[256] = "";
2757 MYSNPRINTF "methods=%s;", p->methods);
2758 if (strstr(p->methods, "md5") || strstr(p->methods, "rsa")) {
2759 /* Build the challenge */
2760 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
2761 MYSNPRINTF "challenge=%s;", p->challenge);
2763 MYSNPRINTF "username=%s;", p->username);
2764 if (strlen(requeststr))
2765 requeststr[strlen(requeststr) - 1] = '\0';
2766 return send_command(p, AST_FRAME_IAX, AST_IAX_COMMAND_AUTHREQ, 0, requeststr, strlen(requeststr) + 1, -1);
2769 static int authenticate_verify(struct chan_iax_pvt *p, char *orequest)
2771 char requeststr[256] = "";
2772 char *var, *value, request[256];
2773 char md5secret[256] = "";
2774 char secret[256] = "";
2775 char rsasecret[256] = "";
2780 if (!(p->state & IAX_STATE_AUTHENTICATED))
2782 strncpy(request, orequest, sizeof(request)-1);
2784 var = strsep(&stringp, ";");
2786 value = strchr(var, '=');
2790 if (!strcmp(var, "secret"))
2791 strncpy(secret, value, sizeof(secret)-1);
2792 else if (!strcmp(var, "md5secret"))
2793 strncpy(md5secret, value, sizeof(md5secret)-1);
2794 else if (!strcmp(var, "rsasecret"))
2795 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2797 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2799 var = strsep(&stringp, ";");
2801 if (strstr(p->methods, "rsa") && strlen(rsasecret) && strlen(p->inkeys)) {
2802 struct ast_key *key;
2806 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));
2808 keyn = strsep(&stringp, ":");
2810 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2811 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
2815 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
2816 keyn = strsep(&stringp, ":");
2818 } else if (strstr(p->methods, "md5")) {
2819 struct MD5Context md5;
2820 unsigned char digest[16];
2822 MD5Update(&md5, p->challenge, strlen(p->challenge));
2823 MD5Update(&md5, p->secret, strlen(p->secret));
2824 MD5Final(digest, &md5);
2825 /* If they support md5, authenticate with it. */
2827 MYSNPRINTF "%2.2x", digest[x]);
2828 if (!strcasecmp(requeststr, md5secret))
2830 } else if (strstr(p->methods, "plaintext")) {
2831 if (!strcmp(secret, p->secret))
2837 static int register_verify(int callno, struct sockaddr_in *sin, char *orequest)
2840 char requeststr[256] = "";
2841 char peer[256] = "";
2842 char md5secret[256] = "";
2843 char rsasecret[256] = "";
2844 char secret[256] = "";
2846 struct ast_key *key;
2854 iaxs[callno]->state &= ~IAX_STATE_AUTHENTICATED;
2855 strcpy(iaxs[callno]->peer, "");
2858 strncpy(request, orequest, sizeof(request)-1);
2860 var = strsep(&stringp, ";");
2862 value = strchr(var, '=');
2866 if (!strcmp(var, "peer"))
2867 strncpy(peer, value, sizeof(peer)-1);
2868 else if (!strcmp(var, "md5secret"))
2869 strncpy(md5secret, value, sizeof(md5secret)-1);
2870 else if (!strcmp(var, "rsasecret"))
2871 strncpy(rsasecret, value, sizeof(rsasecret)-1);
2872 else if (!strcmp(var, "secret"))
2873 strncpy(secret, value, sizeof(secret)-1);
2874 else if (!strcmp(var, "refresh"))
2875 expire = atoi(value);
2877 ast_log(LOG_WARNING, "Unknown variable '%s' with value '%s'\n", var, value);
2879 var = strsep(&stringp, ";");
2882 if (!strlen(peer)) {
2883 ast_log(LOG_NOTICE, "Empty registration from %s\n", inet_ntoa(sin->sin_addr));
2887 for (p = peerl.peers; p ; p = p->next)
2888 if (!strcasecmp(p->name, peer))
2891 #ifdef MYSQL_FRIENDS
2893 p = mysql_peer(peer);
2896 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2901 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, inet_ntoa(sin->sin_addr));
2907 if (!ast_apply_ha(p->ha, sin)) {
2908 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2913 strncpy(iaxs[callno]->secret, p->secret, sizeof(iaxs[callno]->secret)-1);
2914 strncpy(iaxs[callno]->inkeys, p->inkeys, sizeof(iaxs[callno]->inkeys)-1);
2915 /* Check secret against what we have on file */
2916 if (strlen(rsasecret) && strstr(p->methods, "rsa") && strlen(iaxs[callno]->challenge)) {
2917 if (strlen(p->inkeys)) {
2920 strncpy(tmpkeys, p->inkeys, sizeof(tmpkeys));
2922 keyn = strsep(&stringp, ":");
2924 key = ast_key_get(keyn, AST_KEY_PUBLIC);
2925 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
2926 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2929 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
2930 keyn = strsep(&stringp, ":");
2933 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
2939 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
2944 } else if (strlen(secret) && strstr(p->methods, "plaintext")) {
2945 /* They've provided a plain text password and we support that */
2946 if (strcmp(secret, p->secret)) {
2947 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", inet_ntoa(sin->sin_addr), p->name);
2952 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2953 } else if (strlen(md5secret) && strstr(p->methods, "md5") && strlen(iaxs[callno]->challenge)) {
2954 struct MD5Context md5;
2955 unsigned char digest[16];
2957 MD5Update(&md5, iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
2958 MD5Update(&md5, p->secret, strlen(p->secret));
2959 MD5Final(digest, &md5);
2961 MYSNPRINTF "%2.2x", digest[x]);
2962 if (strcasecmp(requeststr, md5secret)) {
2963 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
2968 iaxs[callno]->state |= IAX_STATE_AUTHENTICATED;
2969 } else if (strlen(md5secret) || strlen(secret)) {
2970 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
2975 strncpy(iaxs[callno]->peer, peer, sizeof(iaxs[callno]->peer)-1);
2976 /* Choose lowest expirey number */
2977 if (expire && (expire < iaxs[callno]->expirey))
2978 iaxs[callno]->expirey = expire;
2985 static int authenticate(char *challenge, char *secret, char *keyn, char *methods, char *requeststr, int reqsize, struct sockaddr_in *sin)
2989 if (keyn && strlen(keyn)) {
2990 if (!strstr(methods, "rsa")) {
2991 if (!secret || !strlen(secret))
2992 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));
2993 } else if (!strlen(challenge)) {
2994 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", inet_ntoa(sin->sin_addr));
2997 struct ast_key *key;
2998 key = ast_key_get(keyn, AST_KEY_PRIVATE);
3000 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
3002 if (ast_sign(key, challenge, sig)) {
3003 ast_log(LOG_NOTICE, "Unable to sign challenge withy key\n");
3006 MYSNPRINTF2 "rsasecret=%s;", sig);
3013 if (res && secret && strlen(secret)) {
3014 if (strstr(methods, "md5") && strlen(challenge)) {
3015 struct MD5Context md5;
3016 unsigned char digest[16];
3018 MD5Update(&md5, challenge, strlen(challenge));
3019 MD5Update(&md5, secret, strlen(secret));
3020 MD5Final(digest, &md5);
3021 /* If they support md5, authenticate with it. */
3022 MYSNPRINTF2 "md5secret=");
3024 MYSNPRINTF2 "%2.2x", digest[x]);
3027 } else if (strstr(methods, "plaintext")) {
3028 MYSNPRINTF2 "secret=%s;", secret);
3031 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %s)\n", inet_ntoa(sin->sin_addr), methods);
3036 static int authenticate_reply(struct chan_iax_pvt *p, struct sockaddr_in *sin, char *orequest, char *override, char *okey)
3038 struct iax_peer *peer;
3039 /* Start pessimistic */
3042 char methods[80] = "";
3043 char requeststr[256] = "";
3047 strncpy(request, orequest, sizeof(request)-1);
3049 var = strsep(&stringp, ";");
3051 value = strchr(var, '=');