2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003, Digium
8 * Mark Spencer <markster@digium.com>
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 <asterisk/callerid.h>
33 #include <asterisk/app.h>
34 #include <asterisk/astdb.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/parking.h>
37 #include <asterisk/utils.h>
39 #include <arpa/inet.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
46 #include <sys/signal.h>
56 #include <sys/types.h>
59 #include <sys/ioctl.h>
60 #include <linux/zaptel.h>
63 #include <mysql/mysql.h>
66 #include "iax2-parser.h"
67 #include "../astconf.h"
70 #define IPTOS_MINCOST 0x02
74 * Uncomment to try experimental IAX bridge optimization,
75 * designed to reduce latency when IAX calls cannot
79 #define BRIDGE_OPTIMIZATION
81 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
82 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
84 #define DEFAULT_RETRY_TIME 1000
85 #define MEMORY_SIZE 100
86 #define DEFAULT_DROP 3
87 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
88 but keeps the division between trunked and non-trunked better. */
89 #define TRUNK_CALL_START 0x4000
93 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
95 /* Sample over last 100 units to determine historic jitter */
99 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
101 static char mydbuser[80];
102 static char mydbpass[80];
103 static char mydbhost[80];
104 static char mydbname[80];
106 static char *desc = "Inter Asterisk eXchange (Ver 2)";
107 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
108 static char *type = "IAX2";
110 static char context[80] = "default";
112 static char language[MAX_LANGUAGE] = "";
114 static int max_retries = 4;
115 static int ping_time = 20;
116 static int lagrq_time = 10;
117 static int maxtrunkcall = TRUNK_CALL_START;
118 static int maxnontrunkcall = 1;
119 static int maxjitterbuffer=3000;
120 static int trunkfreq = 20;
121 static int authdebug = 1;
122 static int iaxcompat = 0;
124 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
126 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
128 static int netsocket = -1;
132 static int expirey = IAX_DEFAULT_REG_EXPIRE;
134 static int timingfd = -1; /* Timing file descriptor */
137 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
139 int (*iax2_regfunk)(char *username, int onoff) = NULL;
142 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
144 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
145 ~AST_FORMAT_SLINEAR & \
149 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
153 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
157 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
158 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
159 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
161 static struct io_context *io;
162 static struct sched_context *sched;
164 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
166 static int iax2_dropcount = DEFAULT_DROP;
168 static int use_jitterbuffer = 0;
170 static int iaxdebug = 0;
172 static int iaxtrunkdebug = 0;
174 static char accountcode[20];
175 static int amaflags = 0;
176 static int globalnotransfer = 0;
178 static pthread_t netthreadid = AST_PTHREADT_NULL;
180 #define IAX_STATE_STARTED (1 << 0)
181 #define IAX_STATE_AUTHENTICATED (1 << 1)
182 #define IAX_STATE_TBD (1 << 2)
184 struct iax2_context {
185 char context[AST_MAX_EXTENSION];
186 struct iax2_context *next;
193 char accountcode[20];
194 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
195 char language[MAX_LANGUAGE];
202 char callerid[AST_MAX_EXTENSION];
204 struct iax2_context *contexts;
205 struct iax2_user *next;
213 char outkey[80]; /* What key we use to talk to this peer */
214 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
215 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
216 struct sockaddr_in addr;
220 /* Dynamic Registration fields */
221 int dynamic; /* If this is a dynamic peer */
222 struct sockaddr_in defaddr; /* Default address if there is one */
223 int authmethods; /* Authentication methods (IAX_AUTH_*) */
224 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
227 /* Suggested caller id if registering */
228 char callerid[AST_MAX_EXTENSION];
229 /* Whether or not to send ANI */
231 int expire; /* Schedule entry for expirey */
232 int expirey; /* How soon to expire */
233 int capability; /* Capability */
234 int delme; /* I need to be deleted */
235 int temponly; /* I'm only a temp */
236 int trunk; /* Treat as an IAX trunking */
239 int callno; /* Call number of POKE request */
240 int pokeexpire; /* When to expire poke */
241 int lastms; /* How long last response took (in ms), or -1 for no response */
242 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
245 struct iax2_peer *next;
249 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
251 static struct iax2_trunk_peer {
253 struct sockaddr_in addr;
254 struct timeval txtrunktime; /* Transmit trunktime */
255 struct timeval rxtrunktime; /* Receive trunktime */
256 struct timeval lasttxtime; /* Last transmitted trunktime */
257 struct timeval trunkact; /* Last trunk activity */
258 unsigned int lastsent; /* Last sent time */
259 /* Trunk data and length */
260 unsigned char *trunkdata;
261 unsigned int trunkdatalen;
262 unsigned int trunkdataalloc;
263 struct iax2_trunk_peer *next;
269 static ast_mutex_t tpeerlock = AST_MUTEX_INITIALIZER;
271 struct iax_firmware {
272 struct iax_firmware *next;
276 struct ast_iax2_firmware_header *fwh;
280 #define REG_STATE_UNREGISTERED 0
281 #define REG_STATE_REGSENT 1
282 #define REG_STATE_AUTHSENT 2
283 #define REG_STATE_REGISTERED 3
284 #define REG_STATE_REJECTED 4
285 #define REG_STATE_TIMEOUT 5
286 #define REG_STATE_NOAUTH 6
288 #define TRANSFER_NONE 0
289 #define TRANSFER_BEGIN 1
290 #define TRANSFER_READY 2
291 #define TRANSFER_RELEASED 3
292 #define TRANSFER_PASSTHROUGH 4
294 struct iax2_registry {
295 struct sockaddr_in addr; /* Who we connect to for registration purposes */
297 char secret[80]; /* Password or key name in []'s */
299 int expire; /* Sched ID of expiration */
300 int refresh; /* How often to refresh */
302 int messages; /* Message count */
303 int callno; /* Associated call number if applicable */
304 struct sockaddr_in us; /* Who the server thinks we are */
305 struct iax2_registry *next;
308 static struct iax2_registry *registrations;
310 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
311 #define MIN_RETRY_TIME 100
312 #define MAX_RETRY_TIME 10000
313 #define MAX_JITTER_BUFFER 50
315 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
316 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
318 /* If we have more than this much excess real jitter buffer, srhink it. */
319 static int max_jitter_buffer = MAX_JITTER_BUFFER;
321 struct chan_iax2_pvt {
322 /* Pipes for communication. pipe[1] belongs to the
323 network thread (write), and pipe[0] belongs to the individual
325 /* Whether or not we Quelch audio */
327 /* Last received voice format */
329 /* Last received voice format */
331 /* Last sent voice format */
333 /* Last sent video format */
335 /* What we are capable of sending */
337 /* Last received timestamp */
339 /* Last sent timestamp - never send the same timestamp twice in a single call */
340 unsigned int lastsent;
341 /* Next outgoing timestamp if everything is good */
342 unsigned int nextpred;
344 unsigned int pingtime;
345 /* Max time for initial response */
348 struct sockaddr_in addr;
349 /* Our call number */
350 unsigned short callno;
352 unsigned short peercallno;
353 /* Peer selected format */
355 /* Peer capability */
357 /* timeval that we base our transmission on */
358 struct timeval offset;
359 /* timeval that we base our delivery on */
360 struct timeval rxcore;
361 /* Historical delivery time */
362 int history[MEMORY_SIZE];
363 /* Current base jitterbuffer */
365 /* Current jitter measure */
367 /* Historic jitter value */
371 /* Error, as discovered by the manager */
373 /* Owner if we have one */
374 struct ast_channel *owner;
375 /* What's our state? */
377 /* Expirey (optional) */
379 /* Next outgoing sequence number */
380 unsigned char oseqno;
381 /* Next sequence number they have not yet acknowledged */
382 unsigned char rseqno;
383 /* Next incoming sequence number */
384 unsigned char iseqno;
385 /* Last incoming sequence number we have acknowledged */
386 unsigned char aseqno;
389 /* Default Context */
391 /* Caller ID if available */
393 /* Hidden Caller ID (i.e. ANI) if appropriate */
395 /* Whether or not ani should be transmitted in addition to Caller*ID */
397 /* Whether to request autoanswer */
401 /* Requested Extension */
402 char exten[AST_MAX_EXTENSION];
403 /* Expected Username */
405 /* Expected Secret */
407 /* permitted authentication methods */
411 /* Public keys permitted keys for incoming authentication */
413 /* Private key for outgoing authentication */
415 /* Preferred language */
416 char language[MAX_LANGUAGE];
417 /* Hostname/peername for naming purposes */
419 /* Associated registry */
420 struct iax2_registry *reg;
421 /* Associated peer for poking */
422 struct iax2_peer *peerpoke;
424 /* Transferring status */
426 /* Transfer identifier */
428 /* Already disconnected */
430 /* Who we are IAX transfering to */
431 struct sockaddr_in transfer;
432 /* What's the new call number for the transfer */
433 unsigned short transfercallno;
435 /* Status of knowledge of peer ADSI capability */
438 /* Who we are bridged to */
439 unsigned short bridgecallno;
440 unsigned int bridgesfmt;
441 struct ast_trans_pvt *bridgetrans;
443 int pingid; /* Transmit PING request */
444 int lagid; /* Retransmit lag request */
445 int autoid; /* Auto hangup for Dialplan requestor */
446 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
447 char dproot[AST_MAX_EXTENSION];
448 char accountcode[20];
450 /* This is part of a trunk interface */
452 struct iax2_dpcache *dpentries;
453 int notransfer; /* do we want native bridging */
456 static struct ast_iax2_queue {
457 struct iax_frame *head;
458 struct iax_frame *tail;
463 static struct ast_user_list {
464 struct iax2_user *users;
468 static struct ast_peer_list {
469 struct iax2_peer *peers;
473 static struct ast_firmware_list {
474 struct iax_firmware *wares;
478 /* Extension exists */
479 #define CACHE_FLAG_EXISTS (1 << 0)
480 /* Extension is non-existant */
481 #define CACHE_FLAG_NONEXISTANT (1 << 1)
482 /* Extension can exist */
483 #define CACHE_FLAG_CANEXIST (1 << 2)
484 /* Waiting to hear back response */
485 #define CACHE_FLAG_PENDING (1 << 3)
487 #define CACHE_FLAG_TIMEOUT (1 << 4)
488 /* Request transmitted */
489 #define CACHE_FLAG_TRANSMITTED (1 << 5)
491 #define CACHE_FLAG_UNKNOWN (1 << 6)
493 #define CACHE_FLAG_MATCHMORE (1 << 7)
495 static struct iax2_dpcache {
496 char peercontext[AST_MAX_EXTENSION];
497 char exten[AST_MAX_EXTENSION];
499 struct timeval expirey;
501 unsigned short callno;
503 struct iax2_dpcache *next;
504 struct iax2_dpcache *peer; /* For linking in peers */
507 static ast_mutex_t dpcache_lock;
509 static void iax_debug_output(const char *data)
515 static void iax_error_output(const char *data)
517 ast_log(LOG_WARNING, data);
520 /* XXX We probably should use a mutex when working with this XXX */
521 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
522 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
523 static struct timeval lastused[IAX_MAX_CALLS];
526 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
527 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
528 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
529 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
530 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
532 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f);
534 static int send_ping(void *data)
536 int callno = (long)data;
537 /* Ping only if it's real, not if it's bridged */
539 #ifdef BRIDGE_OPTIMIZATION
540 if (!iaxs[callno]->bridgecallno)
542 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
548 static int send_lagrq(void *data)
550 int callno = (long)data;
551 /* Ping only if it's real not if it's bridged */
553 #ifdef BRIDGE_OPTIMIZATION
554 if (!iaxs[callno]->bridgecallno)
556 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
562 static unsigned char compress_subclass(int subclass)
566 /* If it's 128 or smaller, just return it */
567 if (subclass < IAX_FLAG_SC_LOG)
569 /* Otherwise find its power */
570 for (x = 0; x < IAX_MAX_SHIFT; x++) {
571 if (subclass & (1 << x)) {
573 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
579 return power | IAX_FLAG_SC_LOG;
582 static int uncompress_subclass(unsigned char csub)
584 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
585 if (csub & IAX_FLAG_SC_LOG) {
586 /* special case for 'compressed' -1 */
590 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
596 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
598 struct iax2_peer *peer;
601 ast_mutex_lock(&peerl.lock);
604 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
605 (peer->addr.sin_port == sin.sin_port)) {
606 strncpy(host, peer->name, len-1);
613 ast_mutex_unlock(&peerl.lock);
617 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
619 struct chan_iax2_pvt *tmp;
620 tmp = malloc(sizeof(struct chan_iax2_pvt));
622 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
625 tmp->transfercallno = 0;
626 tmp->bridgecallno = 0;
631 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
632 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
633 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
634 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
639 static int get_samples(struct ast_frame *f)
642 switch(f->subclass) {
643 case AST_FORMAT_SPEEX:
644 samples = 160; /* XXX Not necessarily true XXX */
646 case AST_FORMAT_G723_1:
647 samples = 240 /* XXX Not necessarily true XXX */;
649 case AST_FORMAT_ILBC:
650 samples = 240 * (f->datalen / 50);
653 samples = 160 * (f->datalen / 33);
655 case AST_FORMAT_G729A:
656 samples = 160 * (f->datalen / 20);
658 case AST_FORMAT_SLINEAR:
659 samples = f->datalen / 2;
661 case AST_FORMAT_LPC10:
663 samples += (((char *)(f->data))[7] & 0x1) * 8;
665 case AST_FORMAT_ULAW:
666 samples = f->datalen;
668 case AST_FORMAT_ALAW:
669 samples = f->datalen;
671 case AST_FORMAT_ADPCM:
672 case AST_FORMAT_G726:
673 samples = f->datalen *2;
676 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
681 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
683 /* Malloc() a copy of a frame */
684 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
686 memcpy(new, fr, sizeof(struct iax_frame));
687 iax_frame_wrap(new, &fr->af);
690 new->direction = DIRECTION_INGRESS;
696 #define NEW_PREVENT 0
700 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
702 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
703 (cur->addr.sin_port == sin->sin_port)) {
704 /* This is the main host */
705 if ((cur->peercallno == callno) ||
706 ((dcallno == cur->callno) && !cur->peercallno)) {
707 /* That's us. Be sure we keep track of the peer call number */
711 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
712 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
713 /* We're transferring */
714 if (dcallno == cur->callno)
720 static void update_max_trunk(void)
722 int max = TRUNK_CALL_START;
724 /* XXX Prolly don't need locks here XXX */
725 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
731 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
734 static void update_max_nontrunk(void)
738 /* XXX Prolly don't need locks here XXX */
739 for (x=1;x<TRUNK_CALL_START - 1; x++) {
743 maxnontrunkcall = max;
745 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
748 static int make_trunk(unsigned short callno, int locked)
753 if (iaxs[callno]->oseqno) {
754 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
757 if (callno & TRUNK_CALL_START) {
758 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
761 gettimeofday(&now, NULL);
762 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
763 ast_mutex_lock(&iaxsl[x]);
764 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
765 iaxs[x] = iaxs[callno];
768 /* Update the two timers that should have been started */
769 if (iaxs[x]->pingid > -1)
770 ast_sched_del(sched, iaxs[x]->pingid);
771 if (iaxs[x]->lagid > -1)
772 ast_sched_del(sched, iaxs[x]->lagid);
773 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
774 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
776 ast_mutex_unlock(&iaxsl[callno]);
779 ast_mutex_unlock(&iaxsl[x]);
782 ast_mutex_unlock(&iaxsl[x]);
784 if (x >= IAX_MAX_CALLS - 1) {
785 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
788 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
789 /* We move this call from a non-trunked to a trunked call */
791 update_max_nontrunk();
795 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
800 if (new <= NEW_ALLOW) {
801 /* Look for an existing connection first */
802 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
803 ast_mutex_lock(&iaxsl[x]);
805 /* Look for an exact match */
806 if (match(sin, callno, dcallno, iaxs[x])) {
810 ast_mutex_unlock(&iaxsl[x]);
812 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
813 ast_mutex_lock(&iaxsl[x]);
815 /* Look for an exact match */
816 if (match(sin, callno, dcallno, iaxs[x])) {
820 ast_mutex_unlock(&iaxsl[x]);
823 if ((res < 1) && (new >= NEW_ALLOW)) {
824 gettimeofday(&now, NULL);
825 for (x=1;x<TRUNK_CALL_START;x++) {
826 /* Find first unused call number that hasn't been used in a while */
827 ast_mutex_lock(&iaxsl[x]);
828 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
829 ast_mutex_unlock(&iaxsl[x]);
831 /* We've still got lock held if we found a spot */
832 if (x >= TRUNK_CALL_START) {
833 ast_log(LOG_WARNING, "No more space\n");
836 iaxs[x] = new_iax(sin, lockpeer);
837 update_max_nontrunk();
840 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
841 iaxs[x]->addr.sin_port = sin->sin_port;
842 iaxs[x]->addr.sin_family = sin->sin_family;
843 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
844 iaxs[x]->peercallno = callno;
846 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
847 iaxs[x]->expirey = expirey;
848 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
849 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
850 iaxs[x]->amaflags = amaflags;
851 iaxs[x]->notransfer = globalnotransfer;
852 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
854 ast_log(LOG_WARNING, "Out of resources\n");
855 ast_mutex_unlock(&iaxsl[x]);
858 ast_mutex_unlock(&iaxsl[x]);
864 static void iax2_frame_free(struct iax_frame *fr)
866 if (fr->retrans > -1)
867 ast_sched_del(sched, fr->retrans);
871 static int iax2_queue_frame(int callno, struct ast_frame *f)
873 /* Assumes lock for callno is already held... */
875 if (iaxs[callno] && iaxs[callno]->owner) {
876 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
877 /* Avoid deadlock by pausing and trying again */
878 ast_mutex_unlock(&iaxsl[callno]);
880 ast_mutex_lock(&iaxsl[callno]);
882 ast_queue_frame(iaxs[callno]->owner, f);
883 ast_mutex_unlock(&iaxs[callno]->owner->lock);
892 static void destroy_firmware(struct iax_firmware *cur)
896 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
902 static int try_firmware(char *s)
905 struct iax_firmware *cur;
908 struct ast_iax2_firmware_header *fwh, fwh2;
909 struct MD5Context md5;
910 unsigned char sum[16];
911 res = stat(s, &stbuf);
913 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
916 /* Make sure it's not a directory */
917 if (S_ISDIR(stbuf.st_mode))
919 fd = open(s, O_RDONLY);
921 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
924 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
925 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
929 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
930 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
934 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
935 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
939 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
940 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
944 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
946 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
951 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
953 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
954 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
955 munmap(fwh, stbuf.st_size);
961 if (!strcmp(cur->fwh->devname, fwh->devname)) {
962 /* Found a candidate */
963 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
964 /* The version we have on loaded is older, load this one instead */
966 /* This version is no newer than what we have. Don't worry about it.
967 We'll consider it a proper load anyhow though */
968 munmap(fwh, stbuf.st_size);
975 /* Allocate a new one and link it */
976 cur = malloc(sizeof(struct iax_firmware));
978 memset(cur, 0, sizeof(struct iax_firmware));
980 cur->next = waresl.wares;
986 munmap(cur->fwh, cur->mmaplen);
992 cur->mmaplen = stbuf.st_size;
998 static int iax_check_version(char *dev)
1001 struct iax_firmware *cur;
1002 if (dev && !ast_strlen_zero(dev)) {
1003 ast_mutex_lock(&waresl.lock);
1006 if (!strcmp(dev, cur->fwh->devname)) {
1007 res = ntohs(cur->fwh->version);
1012 ast_mutex_unlock(&waresl.lock);
1017 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1020 unsigned int bs = desc & 0xff;
1021 unsigned int start = (desc >> 8) & 0xffffff;
1023 struct iax_firmware *cur;
1024 if (dev && !ast_strlen_zero(dev) && bs) {
1026 ast_mutex_lock(&waresl.lock);
1029 if (!strcmp(dev, cur->fwh->devname)) {
1030 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1031 if (start < ntohl(cur->fwh->datalen)) {
1032 bytes = ntohl(cur->fwh->datalen) - start;
1035 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1038 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1048 ast_mutex_unlock(&waresl.lock);
1054 static void reload_firmware(void)
1056 struct iax_firmware *cur, *curl, *curp;
1061 /* Mark all as dead */
1062 ast_mutex_lock(&waresl.lock);
1068 /* Now that we've freed them, load the new ones */
1069 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1072 while((de = readdir(fwd))) {
1073 if (de->d_name[0] != '.') {
1074 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1075 if (!try_firmware(fn)) {
1076 if (option_verbose > 1)
1077 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1083 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1085 /* Clean up leftovers */
1097 destroy_firmware(curl);
1102 ast_mutex_unlock(&waresl.lock);
1105 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1107 static int __do_deliver(void *data)
1109 /* Just deliver the packet by using queueing. This is called by
1110 the IAX thread with the iaxsl lock held. */
1111 struct iax_frame *fr = data;
1114 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
1115 if (fr->af.frametype == AST_FRAME_IAX) {
1116 /* We have to treat some of these packets specially because
1117 they're LAG measurement packets */
1118 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
1119 /* If we got a queued request, build a reply and send it */
1120 fr->af.subclass = IAX_COMMAND_LAGRP;
1121 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
1122 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
1123 /* This is a reply we've been given, actually measure the difference */
1124 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
1125 iaxs[fr->callno]->lag = ts - fr->ts;
1128 iax2_queue_frame(fr->callno, &fr->af);
1131 /* Free our iax frame */
1132 iax2_frame_free(fr);
1133 /* And don't run again */
1137 static int do_deliver(void *data)
1139 /* Locking version of __do_deliver */
1140 struct iax_frame *fr = data;
1141 int callno = fr->callno;
1143 ast_mutex_lock(&iaxsl[callno]);
1144 res = __do_deliver(data);
1145 ast_mutex_unlock(&iaxsl[callno]);
1149 static int handle_error(void)
1151 /* XXX Ideally we should figure out why an error occured and then abort those
1152 rather than continuing to try. Unfortunately, the published interface does
1153 not seem to work XXX */
1155 struct sockaddr_in *sin;
1158 struct sock_extended_err e;
1163 m.msg_controllen = sizeof(e);
1165 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1167 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1169 if (m.msg_controllen) {
1170 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1172 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
1174 ast_log(LOG_WARNING, "No address detected??\n");
1176 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1183 static int send_packet(struct iax_frame *f)
1186 /* Called with iaxsl held */
1188 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));
1189 /* Don't send if there was an error, but return error instead */
1191 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1194 if (!iaxs[f->callno])
1196 if (iaxs[f->callno]->error)
1200 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1201 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1202 sizeof(iaxs[f->callno]->transfer));
1205 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1206 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1207 sizeof(iaxs[f->callno]->addr));
1211 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1219 static int iax2_predestroy(int callno)
1221 struct ast_channel *c;
1222 struct chan_iax2_pvt *pvt;
1223 ast_mutex_lock(&iaxsl[callno]);
1226 ast_mutex_unlock(&iaxsl[callno]);
1229 if (!pvt->alreadygone) {
1230 /* No more pings or lagrq's */
1231 if (pvt->pingid > -1)
1232 ast_sched_del(sched, pvt->pingid);
1233 if (pvt->lagid > -1)
1234 ast_sched_del(sched, pvt->lagid);
1235 if (pvt->autoid > -1)
1236 ast_sched_del(sched, pvt->autoid);
1237 if (pvt->initid > -1)
1238 ast_sched_del(sched, pvt->initid);
1243 pvt->alreadygone = 1;
1247 c->_softhangup |= AST_SOFTHANGUP_DEV;
1249 ast_queue_hangup(c);
1251 ast_mutex_lock(&usecnt_lock);
1254 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1255 ast_mutex_unlock(&usecnt_lock);
1257 ast_mutex_unlock(&iaxsl[callno]);
1258 ast_update_use_count();
1262 static int iax2_predestroy_nolock(int callno)
1265 ast_mutex_unlock(&iaxsl[callno]);
1266 res = iax2_predestroy(callno);
1267 ast_mutex_lock(&iaxsl[callno]);
1271 static void iax2_destroy(int callno)
1273 struct chan_iax2_pvt *pvt;
1274 struct iax_frame *cur;
1275 struct ast_channel *owner;
1278 ast_mutex_lock(&iaxsl[callno]);
1280 gettimeofday(&lastused[callno], NULL);
1287 if (ast_mutex_trylock(&owner->lock)) {
1288 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1289 ast_mutex_unlock(&iaxsl[callno]);
1295 iaxs[callno] = NULL;
1299 /* No more pings or lagrq's */
1300 if (pvt->pingid > -1)
1301 ast_sched_del(sched, pvt->pingid);
1302 if (pvt->lagid > -1)
1303 ast_sched_del(sched, pvt->lagid);
1304 if (pvt->autoid > -1)
1305 ast_sched_del(sched, pvt->autoid);
1306 if (pvt->initid > -1)
1307 ast_sched_del(sched, pvt->initid);
1312 if (pvt->bridgetrans)
1313 ast_translator_free_path(pvt->bridgetrans);
1314 pvt->bridgetrans = NULL;
1317 pvt->alreadygone = 1;
1320 /* If there's an owner, prod it to give up */
1321 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1322 ast_queue_hangup(owner);
1325 for (cur = iaxq.head; cur ; cur = cur->next) {
1326 /* Cancel any pending transmissions */
1327 if (cur->callno == pvt->callno)
1331 pvt->reg->callno = 0;
1337 ast_mutex_unlock(&owner->lock);
1339 ast_mutex_unlock(&iaxsl[callno]);
1340 if (callno & 0x4000)
1343 static void iax2_destroy_nolock(int callno)
1345 /* Actually it's easier to unlock, kill it, and relock */
1346 ast_mutex_unlock(&iaxsl[callno]);
1347 iax2_destroy(callno);
1348 ast_mutex_lock(&iaxsl[callno]);
1351 static int update_packet(struct iax_frame *f)
1353 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1354 struct ast_iax2_full_hdr *fh = f->data;
1355 /* Mark this as a retransmission */
1356 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1358 f->iseqno = iaxs[f->callno]->iseqno;
1359 fh->iseqno = f->iseqno;
1363 static int attempt_transmit(void *data)
1365 /* Attempt to transmit the frame to the remote peer...
1366 Called without iaxsl held. */
1367 struct iax_frame *f = data;
1369 int callno = f->callno;
1370 /* Make sure this call is still active */
1372 ast_mutex_lock(&iaxsl[callno]);
1373 if ((f->callno) && iaxs[f->callno]) {
1374 if ((f->retries < 0) /* Already ACK'd */ ||
1375 (f->retries >= max_retries) /* Too many attempts */) {
1376 /* Record an error if we've transmitted too many times */
1377 if (f->retries >= max_retries) {
1379 /* Transfer timeout */
1380 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1381 } else if (f->final) {
1383 iax2_destroy_nolock(f->callno);
1385 if (iaxs[f->callno]->owner)
1386 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->af.frametype, f->af.subclass, f->ts, f->oseqno);
1387 iaxs[f->callno]->error = ETIMEDOUT;
1388 if (iaxs[f->callno]->owner) {
1389 struct ast_frame fr = { 0, };
1391 fr.frametype = AST_FRAME_CONTROL;
1392 fr.subclass = AST_CONTROL_HANGUP;
1393 iax2_queue_frame(f->callno, &fr);
1395 if (iaxs[f->callno]->reg) {
1396 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1397 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1398 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1400 iax2_destroy_nolock(f->callno);
1407 /* Update it if it needs it */
1409 /* Attempt transmission */
1412 /* Try again later after 10 times as long */
1414 if (f->retrytime > MAX_RETRY_TIME)
1415 f->retrytime = MAX_RETRY_TIME;
1416 /* Transfer messages max out at one second */
1417 if (f->transfer && (f->retrytime > 1000))
1418 f->retrytime = 1000;
1419 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1422 /* Make sure it gets freed */
1427 ast_mutex_unlock(&iaxsl[callno]);
1428 /* Do not try again */
1430 /* Don't attempt delivery, just remove it from the queue */
1431 ast_mutex_lock(&iaxq.lock);
1433 f->prev->next = f->next;
1435 iaxq.head = f->next;
1437 f->next->prev = f->prev;
1439 iaxq.tail = f->prev;
1441 ast_mutex_unlock(&iaxq.lock);
1443 /* Free the IAX frame */
1449 static int iax2_set_jitter(int fd, int argc, char *argv[])
1451 if ((argc != 4) && (argc != 5))
1452 return RESULT_SHOWUSAGE;
1454 max_jitter_buffer = atoi(argv[3]);
1455 if (max_jitter_buffer < 0)
1456 max_jitter_buffer = 0;
1459 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1460 if (iaxs[atoi(argv[3])]) {
1461 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1462 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1463 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1465 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1467 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1470 return RESULT_SUCCESS;
1473 static char jitter_usage[] =
1474 "Usage: iax set jitter [callid] <value>\n"
1475 " If used with a callid, it sets the jitter buffer to the given static\n"
1476 "value (until its next calculation). If used without a callid, the value is used\n"
1477 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1478 "buffer size is reduced.";
1480 static int iax2_show_stats(int fd, int argc, char *argv[])
1482 struct iax_frame *cur;
1483 int cnt = 0, dead=0, final=0;
1485 return RESULT_SHOWUSAGE;
1486 for (cur = iaxq.head; cur ; cur = cur->next) {
1487 if (cur->retries < 0)
1493 ast_cli(fd, " IAX Statistics\n");
1494 ast_cli(fd, "---------------------\n");
1495 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1496 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1497 return RESULT_SUCCESS;
1500 static int iax2_show_cache(int fd, int argc, char *argv[])
1502 struct iax2_dpcache *dp;
1503 char tmp[1024], *pc;
1507 gettimeofday(&tv, NULL);
1508 ast_mutex_lock(&dpcache_lock);
1510 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1512 s = dp->expirey.tv_sec - tv.tv_sec;
1514 if (dp->flags & CACHE_FLAG_EXISTS)
1515 strcat(tmp, "EXISTS|");
1516 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1517 strcat(tmp, "NONEXISTANT|");
1518 if (dp->flags & CACHE_FLAG_CANEXIST)
1519 strcat(tmp, "CANEXIST|");
1520 if (dp->flags & CACHE_FLAG_PENDING)
1521 strcat(tmp, "PENDING|");
1522 if (dp->flags & CACHE_FLAG_TIMEOUT)
1523 strcat(tmp, "TIMEOUT|");
1524 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1525 strcat(tmp, "TRANSMITTED|");
1526 if (dp->flags & CACHE_FLAG_MATCHMORE)
1527 strcat(tmp, "MATCHMORE|");
1528 if (dp->flags & CACHE_FLAG_UNKNOWN)
1529 strcat(tmp, "UNKNOWN|");
1530 /* Trim trailing pipe */
1531 if (!ast_strlen_zero(tmp))
1532 tmp[strlen(tmp) - 1] = '\0';
1534 strcpy(tmp, "(none)");
1536 pc = strchr(dp->peercontext, '@');
1538 pc = dp->peercontext;
1541 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1542 if (dp->waiters[x] > -1)
1545 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1547 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1550 ast_mutex_unlock(&dpcache_lock);
1551 return RESULT_SUCCESS;
1554 static char show_stats_usage[] =
1555 "Usage: iax show stats\n"
1556 " Display statistics on IAX channel driver.\n";
1559 static char show_cache_usage[] =
1560 "Usage: iax show cache\n"
1561 " Display currently cached IAX Dialplan results.\n";
1563 static struct ast_cli_entry cli_set_jitter =
1564 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1566 static struct ast_cli_entry cli_show_stats =
1567 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1569 static struct ast_cli_entry cli_show_cache =
1570 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1572 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1574 #ifdef BRIDGE_OPTIMIZATION
1575 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1577 static int forward_delivery(struct iax_frame *fr)
1579 struct chan_iax2_pvt *p1, *p2;
1580 p1 = iaxs[fr->callno];
1581 p2 = iaxs[p1->bridgecallno];
1586 /* Fix relative timestamp */
1587 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1588 /* Now just send it send on the 2nd one
1589 with adjusted timestamp */
1590 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1594 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1597 int drops[MEMORY_SIZE];
1598 int min, max=0, maxone=0,y,z, match;
1599 /* ms is a measure of the "lateness" of the packet relative to the first
1600 packet we received, which always has a lateness of 1. Called by
1601 IAX thread, with iaxsl lock held. */
1602 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1605 /* What likely happened here is that our counter has circled but we haven't
1606 gotten the update from the main packet. We'll just pretend that we did, and
1607 update the timestamp appropriately. */
1613 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1619 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1620 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1621 fr->af.delivery.tv_sec += fr->ts / 1000;
1622 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1623 if (fr->af.delivery.tv_usec >= 1000000) {
1624 fr->af.delivery.tv_usec -= 1000000;
1625 fr->af.delivery.tv_sec += 1;
1629 /* Rotate our history queue of "lateness". Don't worry about those initial
1630 zeros because the first entry will always be zero */
1631 if (updatehistory) {
1632 for (x=0;x<MEMORY_SIZE - 1;x++)
1633 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1634 /* Add a history entry for this one */
1635 iaxs[fr->callno]->history[x] = ms;
1638 /* Initialize the minimum to reasonable values. It's too much
1639 work to do the same for the maximum, repeatedly */
1640 min=iaxs[fr->callno]->history[0];
1641 for (z=0;z < iax2_dropcount + 1;z++) {
1642 /* Start very optimistic ;-) */
1644 for (x=0;x<MEMORY_SIZE;x++) {
1645 if (max < iaxs[fr->callno]->history[x]) {
1646 /* We have a candidate new maximum value. Make
1647 sure it's not in our drop list */
1649 for (y=0;!match && (y<z);y++)
1650 match |= (drops[y] == x);
1652 /* It's not in our list, use it as the new maximum */
1653 max = iaxs[fr->callno]->history[x];
1659 /* On our first pass, find the minimum too */
1660 if (min > iaxs[fr->callno]->history[x])
1661 min = iaxs[fr->callno]->history[x];
1668 /* Just for reference, keep the "jitter" value, the difference between the
1669 earliest and the latest. */
1670 iaxs[fr->callno]->jitter = max - min;
1672 /* IIR filter for keeping track of historic jitter, but always increase
1673 historic jitter immediately for increase */
1675 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1676 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1678 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1679 iaxs[fr->callno]->historicjitter;
1681 /* If our jitter buffer is too big (by a significant margin), then we slowly
1682 shrink it by about 1 ms each time to avoid letting the change be perceived */
1683 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1684 iaxs[fr->callno]->jitterbuffer -= 2;
1688 /* Constrain our maximum jitter buffer appropriately */
1689 if (max > min + maxjitterbuffer) {
1691 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1692 max = min + maxjitterbuffer;
1696 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1697 buffer immediately to accomodate it (and a little more). */
1698 if (max > iaxs[fr->callno]->jitterbuffer)
1699 iaxs[fr->callno]->jitterbuffer = max
1700 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1704 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1706 /* Subtract the lateness from our jitter buffer to know how long to wait
1707 before sending our packet. */
1708 ms = iaxs[fr->callno]->jitterbuffer - ms;
1710 if (!use_jitterbuffer)
1713 /* If the caller just wanted us to update, return now */
1719 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1720 /* Don't deliver it more than 4 ms late */
1721 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1725 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1726 /* Free our iax frame */
1727 iax2_frame_free(fr);
1731 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1732 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1737 static int iax2_transmit(struct iax_frame *fr)
1739 /* Lock the queue and place this packet at the end */
1742 /* By setting this to 0, the network thread will send it for us, and
1743 queue retransmission if necessary */
1745 ast_mutex_lock(&iaxq.lock);
1752 iaxq.tail->next = fr;
1753 fr->prev = iaxq.tail;
1757 ast_mutex_unlock(&iaxq.lock);
1758 /* Wake up the network thread */
1759 pthread_kill(netthreadid, SIGURG);
1765 static int iax2_digit(struct ast_channel *c, char digit)
1767 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1770 static int iax2_sendtext(struct ast_channel *c, char *text)
1773 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1774 0, 0, text, strlen(text) + 1, -1);
1777 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1779 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1782 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1784 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1787 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1789 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1790 ast_mutex_lock(&iaxsl[callno]);
1792 iaxs[callno]->owner = newchan;
1794 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1795 ast_mutex_unlock(&iaxsl[callno]);
1799 #ifdef MYSQL_FRIENDS
1801 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1803 if (mysql && (strlen(peer) < 128)) {
1807 name = alloca(strlen(peer) * 2 + 1);
1809 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1810 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1811 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1812 ast_mutex_lock(&mysqllock);
1813 if (mysql_real_query(mysql, query, strlen(query)))
1814 ast_log(LOG_WARNING, "Unable to update database\n");
1816 ast_mutex_unlock(&mysqllock);
1820 static struct iax2_peer *mysql_peer(char *peer)
1822 struct iax2_peer *p;
1825 p = malloc(sizeof(struct iax2_peer));
1826 memset(p, 0, sizeof(struct iax2_peer));
1827 if (mysql && (strlen(peer) < 128)) {
1832 time_t regseconds, nowtime;
1834 MYSQL_FIELD *fields;
1836 name = alloca(strlen(peer) * 2 + 1);
1837 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1838 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
1839 ast_mutex_lock(&mysqllock);
1840 mysql_query(mysql, query);
1841 if ((result = mysql_store_result(mysql))) {
1842 if ((rowval = mysql_fetch_row(result))) {
1843 numfields = mysql_num_fields(result);
1844 fields = mysql_fetch_fields(result);
1846 for (x=0;x<numfields;x++) {
1848 if (!strcasecmp(fields[x].name, "secret")) {
1849 strncpy(p->secret, rowval[x], sizeof(p->secret));
1850 } else if (!strcasecmp(fields[x].name, "context")) {
1851 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1852 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1853 inet_aton(rowval[x], &p->addr.sin_addr);
1854 } else if (!strcasecmp(fields[x].name, "port")) {
1855 if (sscanf(rowval[x], "%i", &port) != 1)
1857 p->addr.sin_port = htons(port);
1858 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1859 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1865 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1866 memset(&p->addr, 0, sizeof(p->addr));
1868 mysql_free_result(result);
1871 ast_mutex_unlock(&mysqllock);
1877 strncpy(p->name, peer, sizeof(p->name) - 1);
1881 p->capability = iax2_capability;
1882 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1886 static struct iax2_user *mysql_user(char *user)
1888 struct iax2_user *p;
1889 struct iax2_context *con;
1892 p = malloc(sizeof(struct iax2_user));
1893 memset(p, 0, sizeof(struct iax2_user));
1894 con = malloc(sizeof(struct iax2_context));
1895 memset(con, 0, sizeof(struct iax2_context));
1896 strcpy(con->context, "default");
1898 if (mysql && (strlen(user) < 128)) {
1903 MYSQL_FIELD *fields;
1905 name = alloca(strlen(user) * 2 + 1);
1906 mysql_real_escape_string(mysql, name, user, strlen(user));
1907 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
1908 ast_mutex_lock(&mysqllock);
1909 mysql_query(mysql, query);
1910 if ((result = mysql_store_result(mysql))) {
1911 if ((rowval = mysql_fetch_row(result))) {
1912 numfields = mysql_num_fields(result);
1913 fields = mysql_fetch_fields(result);
1915 for (x=0;x<numfields;x++) {
1917 if (!strcasecmp(fields[x].name, "secret")) {
1918 strncpy(p->secret, rowval[x], sizeof(p->secret));
1919 } else if (!strcasecmp(fields[x].name, "context")) {
1920 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1921 } else if (!strcasecmp(fields[x].name, "accountcode")) {
1922 strncpy(p->accountcode, rowval[x], sizeof(p->accountcode));
1927 mysql_free_result(result);
1930 ast_mutex_unlock(&mysqllock);
1938 strncpy(p->name, user, sizeof(p->name) - 1);
1940 p->capability = iax2_capability;
1941 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1945 #endif /* MYSQL_FRIENDS */
1947 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, char *secret, int seclen)
1949 struct ast_hostent ahp; struct hostent *hp;
1950 struct iax2_peer *p;
1958 sin->sin_family = AF_INET;
1959 ast_mutex_lock(&peerl.lock);
1962 if (!strcasecmp(p->name, peer)) {
1967 ast_mutex_unlock(&peerl.lock);
1968 #ifdef MYSQL_FRIENDS
1970 p = mysql_peer(peer);
1974 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1975 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1977 *sendani = p->sendani; /* Whether we transmit ANI */
1979 *maxtime = p->maxms; /* Max time they should take */
1981 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1985 *capability = p->capability;
1987 strncpy(secret, p->secret, seclen);
1988 if (p->addr.sin_addr.s_addr) {
1989 sin->sin_addr = p->addr.sin_addr;
1990 sin->sin_port = p->addr.sin_port;
1992 sin->sin_addr = p->defaddr.sin_addr;
1993 sin->sin_port = p->defaddr.sin_port;
1996 *notransfer=p->notransfer;
2004 hp = ast_gethostbyname(peer, &ahp);
2006 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2007 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2010 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2020 static int auto_congest(void *nothing)
2022 int callno = PTR_TO_CALLNO(nothing);
2023 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2024 ast_mutex_lock(&iaxsl[callno]);
2026 iaxs[callno]->initid = -1;
2027 iax2_queue_frame(callno, &f);
2028 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2030 ast_mutex_unlock(&iaxsl[callno]);
2034 static unsigned int iax2_datetime(void)
2040 localtime_r(&t, &tm);
2041 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2042 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2043 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2044 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2045 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2046 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2050 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2052 struct sockaddr_in sin;
2057 char *secret = NULL;
2060 char *l=NULL, *n=NULL;
2061 struct iax_ie_data ied;
2062 char myrdest [5] = "s";
2063 char context[AST_MAX_EXTENSION] ="";
2064 char *portno = NULL;
2066 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2068 char storedsecret[80];
2069 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2070 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2073 strncpy(host, dest, sizeof(host)-1);
2075 strsep(&stringp, "/");
2076 /* If no destination extension specified, use 's' */
2077 rdest = strsep(&stringp, "/");
2081 /* Check for trailing options */
2082 opts = strsep(&stringp, "/");
2087 strsep(&stringp, "@");
2088 rcontext = strsep(&stringp, "@");
2090 strsep(&stringp, "@");
2091 username = strsep(&stringp, "@");
2093 /* Really the second argument is the host, not the username */
2101 username = strsep(&stringp, ":");
2102 secret = strsep(&stringp, ":");
2105 if (strsep(&stringp, ":")) {
2107 strsep(&stringp, ":");
2108 portno = strsep(&stringp, ":");
2110 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
2111 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2114 /* Keep track of the context for outgoing calls too */
2115 strncpy(c->context, context, sizeof(c->context) - 1);
2117 sin.sin_port = htons(atoi(portno));
2120 strncpy(cid, c->callerid, sizeof(cid) - 1);
2121 ast_callerid_parse(cid, &n, &l);
2123 ast_shrink_phone_number(l);
2125 /* Now build request */
2126 memset(&ied, 0, sizeof(ied));
2127 /* On new call, first IE MUST be IAX version of caller */
2128 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2129 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2130 if (strchr(opts, 'a')) {
2131 /* Request auto answer */
2132 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2135 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2137 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2138 if (iaxs[callno]->sendani && c->ani) {
2140 strncpy(cid, c->ani, sizeof(cid) - 1);
2141 ast_callerid_parse(cid, &n, &l);
2143 ast_shrink_phone_number(l);
2144 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2147 if (c->language && !ast_strlen_zero(c->language))
2148 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2149 if (c->dnid && !ast_strlen_zero(c->dnid))
2150 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2152 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2154 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2155 if (!secret && !ast_strlen_zero(storedsecret))
2156 secret = storedsecret;
2157 ast_mutex_lock(&iaxsl[callno]);
2158 if (!ast_strlen_zero(c->context))
2159 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2161 if (secret[0] == '[') {
2162 /* This is an RSA key, not a normal secret */
2163 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2164 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2165 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2168 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2170 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2171 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2172 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2173 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2174 /* Transmit the string in a "NEW" request */
2176 /* XXX We have no equivalent XXX */
2177 if (option_verbose > 2)
2178 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2180 if (iaxs[callno]->maxtime) {
2181 /* Initialize pingtime and auto-congest time */
2182 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2183 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2185 send_command(iaxs[callno], AST_FRAME_IAX,
2186 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2187 ast_mutex_unlock(&iaxsl[callno]);
2188 ast_setstate(c, AST_STATE_RINGING);
2192 static int iax2_hangup(struct ast_channel *c)
2194 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2196 ast_mutex_lock(&iaxsl[callno]);
2197 if (callno && iaxs[callno]) {
2198 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2199 alreadygone = iaxs[callno]->alreadygone;
2200 /* Send the hangup unless we have had a transmission error or are already gone */
2201 if (!iaxs[callno]->error && !alreadygone)
2202 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2203 /* Explicitly predestroy it */
2204 iax2_predestroy_nolock(callno);
2205 /* If we were already gone to begin with, destroy us now */
2207 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2208 iax2_destroy_nolock(callno);
2211 ast_mutex_unlock(&iaxsl[callno]);
2212 if (option_verbose > 2)
2213 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2217 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2219 struct ast_option_header *h;
2221 h = malloc(datalen + sizeof(struct ast_option_header));
2223 h->flag = AST_OPTION_FLAG_REQUEST;
2224 h->option = htons(option);
2225 memcpy(h->data, data, datalen);
2226 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2227 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2231 ast_log(LOG_WARNING, "Out of memory\n");
2235 static struct ast_frame *iax2_read(struct ast_channel *c)
2237 static struct ast_frame f = { AST_FRAME_NULL, };
2238 ast_log(LOG_NOTICE, "I should never be called!\n");
2242 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2245 struct iax_ie_data ied0;
2246 struct iax_ie_data ied1;
2247 unsigned int transferid = rand();
2248 memset(&ied0, 0, sizeof(ied0));
2249 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2250 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2251 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2253 memset(&ied1, 0, sizeof(ied1));
2254 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2255 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2256 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2258 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2261 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2264 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2265 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2269 static void lock_both(unsigned short callno0, unsigned short callno1)
2271 ast_mutex_lock(&iaxsl[callno0]);
2272 while (ast_mutex_trylock(&iaxsl[callno1])) {
2273 ast_mutex_unlock(&iaxsl[callno0]);
2275 ast_mutex_lock(&iaxsl[callno0]);
2279 static void unlock_both(unsigned short callno0, unsigned short callno1)
2281 ast_mutex_unlock(&iaxsl[callno1]);
2282 ast_mutex_unlock(&iaxsl[callno0]);
2285 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2287 struct ast_channel *cs[3];
2288 struct ast_channel *who;
2291 int transferstarted=0;
2292 struct ast_frame *f;
2293 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2294 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2295 struct timeval waittimer = {0, 0}, tv;
2297 lock_both(callno0, callno1);
2298 /* Put them in native bridge mode */
2299 iaxs[callno0]->bridgecallno = callno1;
2300 iaxs[callno1]->bridgecallno = callno0;
2301 unlock_both(callno0, callno1);
2303 /* If not, try to bridge until we can execute a transfer, if we can */
2306 for (/* ever */;;) {
2307 /* Check in case we got masqueraded into */
2308 if ((c0->type != type) || (c1->type != type)) {
2309 if (option_verbose > 2)
2310 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2311 /* Remove from native mode */
2312 if (c0->type == type) {
2313 ast_mutex_lock(&iaxsl[callno0]);
2314 iaxs[callno0]->bridgecallno = 0;
2315 ast_mutex_unlock(&iaxsl[callno0]);
2317 if (c1->type == type) {
2318 ast_mutex_lock(&iaxsl[callno1]);
2319 iaxs[callno1]->bridgecallno = 0;
2320 ast_mutex_unlock(&iaxsl[callno1]);
2324 if (c0->nativeformats != c1->nativeformats) {
2325 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2326 /* Remove from native mode */
2327 lock_both(callno0, callno1);
2328 iaxs[callno0]->bridgecallno = 0;
2329 iaxs[callno1]->bridgecallno = 0;
2330 unlock_both(callno0, callno1);
2333 /* check if transfered and if we really want native bridging */
2334 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2335 /* Try the transfer */
2336 if (iax2_start_transfer(callno0, callno1))
2337 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2338 transferstarted = 1;
2340 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2341 /* Call has been transferred. We're no longer involved */
2342 gettimeofday(&tv, NULL);
2343 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2344 waittimer.tv_sec = tv.tv_sec;
2345 waittimer.tv_usec = tv.tv_usec;
2346 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2347 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2348 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2356 who = ast_waitfor_n(cs, 2, &to);
2358 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2371 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2377 if ((f->frametype == AST_FRAME_VOICE) ||
2378 (f->frametype == AST_FRAME_TEXT) ||
2379 (f->frametype == AST_FRAME_VIDEO) ||
2380 (f->frametype == AST_FRAME_IMAGE) ||
2381 (f->frametype == AST_FRAME_DTMF)) {
2382 if ((f->frametype == AST_FRAME_DTMF) &&
2383 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2385 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2388 /* Take out of conference mode */
2390 /* Remove from native mode */
2396 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2400 /* Remove from native mode */
2407 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2409 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2421 /* Swap who gets priority */
2426 lock_both(callno0, callno1);
2427 iaxs[callno0]->bridgecallno = 0;
2428 iaxs[callno1]->bridgecallno = 0;
2429 unlock_both(callno0, callno1);
2433 static int iax2_answer(struct ast_channel *c)
2435 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2437 ast_log(LOG_DEBUG, "Answering\n");
2438 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2441 static int iax2_indicate(struct ast_channel *c, int condition)
2443 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2445 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2446 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2449 static int iax2_transfer(struct ast_channel *c, char *dest)
2451 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2452 struct iax_ie_data ied;
2453 char tmp[256] = "", *context;
2454 strncpy(tmp, dest, sizeof(tmp) - 1);
2455 context = strchr(tmp, '@');
2460 memset(&ied, 0, sizeof(ied));
2461 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2463 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2465 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2466 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2470 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2472 static int iax2_getpeertrunk(struct sockaddr_in sin)
2474 struct iax2_peer *peer;
2476 ast_mutex_lock(&peerl.lock);
2479 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2480 (peer->addr.sin_port == sin.sin_port)) {
2486 ast_mutex_unlock(&peerl.lock);
2490 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2492 struct ast_channel *tmp;
2493 tmp = ast_channel_alloc(1);
2495 if (!ast_strlen_zero(i->username))
2496 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2498 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2500 /* We can support any format by default, until we get restricted */
2501 tmp->nativeformats = capability;
2502 tmp->readformat = 0;
2503 tmp->writeformat = 0;
2504 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2505 tmp->pvt->send_digit = iax2_digit;
2506 tmp->pvt->send_text = iax2_sendtext;
2507 tmp->pvt->send_image = iax2_sendimage;
2508 tmp->pvt->send_html = iax2_sendhtml;
2509 tmp->pvt->call = iax2_call;
2510 tmp->pvt->hangup = iax2_hangup;
2511 tmp->pvt->answer = iax2_answer;
2512 tmp->pvt->read = iax2_read;
2513 tmp->pvt->write = iax2_write;
2514 tmp->pvt->write_video = iax2_write;
2515 tmp->pvt->indicate = iax2_indicate;
2516 tmp->pvt->setoption = iax2_setoption;
2517 tmp->pvt->bridge = iax2_bridge;
2518 tmp->pvt->transfer = iax2_transfer;
2519 if (!ast_strlen_zero(i->callerid))
2520 tmp->callerid = strdup(i->callerid);
2521 if (!ast_strlen_zero(i->ani))
2522 tmp->ani = strdup(i->ani);
2523 if (!ast_strlen_zero(i->language))
2524 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2525 if (!ast_strlen_zero(i->dnid))
2526 tmp->dnid = strdup(i->dnid);
2527 if (!ast_strlen_zero(i->accountcode))
2528 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2530 tmp->amaflags = i->amaflags;
2531 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2532 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2533 tmp->adsicpe = i->peeradsicpe;
2534 tmp->pvt->fixup = iax2_fixup;
2536 i->capability = capability;
2537 ast_setstate(tmp, state);
2538 ast_mutex_lock(&usecnt_lock);
2540 ast_mutex_unlock(&usecnt_lock);
2541 ast_update_use_count();
2542 if (state != AST_STATE_DOWN) {
2543 if (ast_pbx_start(tmp)) {
2544 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2553 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2555 unsigned long int mssincetx; /* unsigned to handle overflows */
2558 tpeer->trunkact = *tv;
2559 mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 + (tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000;
2560 if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2561 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2562 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2563 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2564 tpeer->lastsent = 999999;
2566 /* Update last transmit time now */
2567 tpeer->lasttxtime.tv_sec = tv->tv_sec;
2568 tpeer->lasttxtime.tv_usec = tv->tv_usec;
2570 /* Calculate ms offset */
2571 ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 + (tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000;
2572 /* Predict from last value */
2573 pred = tpeer->lastsent + sampms;
2574 if (abs(ms - pred) < 640)
2577 /* We never send the same timestamp twice, so fudge a little if we must */
2578 if (ms == tpeer->lastsent)
2579 ms = tpeer->lastsent + 1;
2580 tpeer->lastsent = ms;
2584 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2586 long ms; /* NOT unsigned */
2587 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2588 /* Initialize rxcore time if appropriate */
2589 gettimeofday(&iaxs[callno]->rxcore, NULL);
2590 /* Round to nearest 20ms */
2591 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2593 /* Calculate difference between trunk and channel */
2594 ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2595 (tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2596 /* Return as the sum of trunk time and the difference between trunk and real time */
2600 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2606 struct timeval *delivery = NULL;
2608 if (f->frametype == AST_FRAME_VOICE) {
2610 delivery = &f->delivery;
2611 } else if (f->frametype == AST_FRAME_IAX) {
2615 if (!p->offset.tv_sec && !p->offset.tv_usec) {
2616 gettimeofday(&p->offset, NULL);
2617 /* Round to nearest 20ms */
2618 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2620 /* If the timestamp is specified, just send it as is */
2623 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2624 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 + (delivery->tv_usec - p->offset.tv_usec) / 1000;
2626 gettimeofday(&tv, NULL);
2627 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2631 /* On a voice frame, use predicted values if appropriate */
2632 if (abs(ms - p->nextpred) <= 640) {
2634 p->nextpred = f->samples / 8;
2639 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinkign) if appropriate unless
2640 it's a genuine frame */
2642 if (ms <= p->lastsent)
2643 ms = p->lastsent + 3;
2644 } else if (abs(ms - p->lastsent) <= 640) {
2645 ms = p->lastsent + 3;
2651 p->nextpred = p->nextpred + f->samples / 8;
2653 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2658 #ifdef BRIDGE_OPTIMIZATION
2659 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2662 /* Receive from p1, send to p2 */
2664 /* Setup rxcore if necessary on outgoing channel */
2665 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2666 gettimeofday(&p1->rxcore, NULL);
2668 /* Setup txcore if necessary on outgoing channel */
2669 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2670 gettimeofday(&p2->offset, NULL);
2672 /* Now, ts is the timestamp of the original packet in the orignal context.
2673 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2674 Subtracting txcore of the outgoing channel gives us what we'd expect */
2676 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2678 if (fakets <= p2->lastsent)
2679 fakets = p2->lastsent + 1;
2680 p2->lastsent = fakets;
2685 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2687 /* Returns where in "receive time" we are */
2690 /* Setup rxcore if necessary */
2691 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2692 gettimeofday(&p->rxcore, NULL);
2694 gettimeofday(&tv, NULL);
2695 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2699 struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2701 struct iax2_trunk_peer *tpeer;
2702 /* Finds and locks trunk peer */
2703 ast_mutex_lock(&tpeerlock);
2706 /* We don't lock here because tpeer->addr *never* changes */
2707 if (!inaddrcmp(&tpeer->addr, sin)) {
2708 ast_mutex_lock(&tpeer->lock);
2711 tpeer = tpeer->next;
2714 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2716 memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2717 ast_mutex_init(&tpeer->lock);
2718 tpeer->lastsent = 9999;
2719 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2720 gettimeofday(&tpeer->trunkact, NULL);
2721 ast_mutex_lock(&tpeer->lock);
2722 tpeer->next = tpeers;
2724 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2727 ast_mutex_unlock(&tpeerlock);
2731 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2733 struct iax2_trunk_peer *tpeer;
2735 struct ast_iax2_meta_trunk_entry *met;
2736 tpeer = find_tpeer(&pvt->addr);
2738 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2739 /* Need to reallocate space */
2740 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2741 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2743 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2744 tpeer->trunkdata = tmp;
2745 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
2747 ast_log(LOG_WARNING, "Insufficient memory to expand trunk data to %s:%d\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2748 ast_mutex_unlock(&tpeer->lock);
2752 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2753 ast_mutex_unlock(&tpeer->lock);
2758 /* Append to meta frame */
2759 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2760 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2761 /* Store call number and length in meta header */
2762 met->callno = htons(pvt->callno);
2763 met->len = htons(f->datalen);
2764 /* Advance pointers/decrease length past trunk entry header */
2765 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2766 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2767 /* Copy actual trunk data */
2768 memcpy(ptr, f->data, f->datalen);
2769 tpeer->trunkdatalen += f->datalen;
2770 if (!tpeer->firstcallno)
2771 tpeer->firstcallno = pvt->callno;
2773 ast_mutex_unlock(&tpeer->lock);
2778 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2780 /* Queue a packet for delivery on a given private structure. Use "ts" for
2781 timestamp, or calculate if ts is 0. Send immediately without retransmission
2782 or delayed, with retransmission */
2783 struct ast_iax2_full_hdr *fh;
2784 struct ast_iax2_mini_hdr *mh;
2785 struct ast_iax2_video_hdr *vh;
2787 struct iax_frame fr2;
2788 unsigned char buffer[4096];
2790 struct iax_frame *fr;
2793 unsigned int lastsent;
2797 ast_log(LOG_WARNING, "No private structure for packet?\n");
2801 lastsent = pvt->lastsent;
2803 /* Calculate actual timestamp */
2804 fts = calc_timestamp(pvt, ts, f);
2806 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2807 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2808 (f->frametype == AST_FRAME_VOICE)
2809 /* is a voice frame */ &&
2810 (f->subclass == pvt->svoiceformat)
2811 /* is the same type */ ) {
2812 /* Force immediate rather than delayed transmission */
2814 /* Mark that mini-style frame is appropriate */
2817 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2818 (f->frametype == AST_FRAME_VIDEO) &&
2819 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2823 /* Allocate an iax_frame */
2827 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2829 ast_log(LOG_WARNING, "Out of memory\n");
2832 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2833 iax_frame_wrap(fr, f);
2837 ast_log(LOG_WARNING, "timestamp is 0?\n");
2839 iax2_frame_free(fr);
2842 fr->callno = pvt->callno;
2843 fr->transfer = transfer;
2846 /* We need a full frame */
2850 fr->oseqno = pvt->oseqno++;
2851 fr->iseqno = pvt->iseqno;
2852 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2853 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2854 fh->ts = htonl(fr->ts);
2855 fh->oseqno = fr->oseqno;
2859 fh->iseqno = fr->iseqno;
2860 /* Keep track of the last thing we've acknowledged */
2862 pvt->aseqno = fr->iseqno;
2863 fh->type = fr->af.frametype & 0xFF;
2864 if (fr->af.frametype == AST_FRAME_VIDEO)
2865 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2867 fh->csub = compress_subclass(fr->af.subclass);
2869 fr->dcallno = pvt->transfercallno;
2871 fr->dcallno = pvt->peercallno;
2872 fh->dcallno = htons(fr->dcallno);
2873 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2876 /* Retry after 2x the ping time has passed */
2877 fr->retrytime = pvt->pingtime * 2;
2878 if (fr->retrytime < MIN_RETRY_TIME)
2879 fr->retrytime = MIN_RETRY_TIME;
2880 if (fr->retrytime > MAX_RETRY_TIME)
2881 fr->retrytime = MAX_RETRY_TIME;
2882 /* Acks' don't get retried */
2883 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2885 else if (f->frametype == AST_FRAME_VOICE)
2886 pvt->svoiceformat = f->subclass;
2887 else if (f->frametype == AST_FRAME_VIDEO)
2888 pvt->svideoformat = f->subclass & ~0x1;
2890 res = send_packet(fr);
2892 res = iax2_transmit(fr);
2895 iax2_trunk_queue(pvt, &fr->af);
2897 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2898 /* Video frame have no sequence number */
2901 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2903 vh->callno = htons(0x8000 | fr->callno);
2904 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2905 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2908 res = send_packet(fr);
2910 /* Mini-frames have no sequence number */
2913 /* Mini frame will do */
2914 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2915 mh->callno = htons(fr->callno);
2916 mh->ts = htons(fr->ts & 0xFFFF);
2917 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2920 res = send_packet(fr);
2928 static int iax2_show_users(int fd, int argc, char *argv[])
2930 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s\n"
2931 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s\n"
2932 struct iax2_user *user;
2935 return RESULT_SHOWUSAGE;
2936 ast_mutex_lock(&userl.lock);
2937 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2938 for(user=userl.users;user;user=user->next) {
2939 if (!ast_strlen_zero(user->secret)) {
2940 strncpy(auth,user->secret,sizeof(auth)-1);
2941 } else if (!ast_strlen_zero(user->inkeys)) {
2942 sprintf(auth,"Key: %-15.15s ",user->inkeys);
2944 strcpy(auth,"-no secret-");
2945 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
2946 user->contexts ? user->contexts->context : context,
2947 user->ha ? "Yes" : "No");
2949 ast_mutex_unlock(&userl.lock);
2950 return RESULT_SUCCESS;
2955 static int iax2_show_peers(int fd, int argc, char *argv[])
2957 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2958 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2959 struct iax2_peer *peer;
2960 char name[256] = "";
2961 int registeredonly=0;
2962 if ((argc != 3) && (argc != 4) && (argc != 5))
2963 return RESULT_SHOWUSAGE;
2965 if (!strcasecmp(argv[3], "registered")) {
2968 return RESULT_SHOWUSAGE;
2970 ast_mutex_lock(&peerl.lock);
2971 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2972 for (peer = peerl.peers;peer;peer = peer->next) {
2975 int print_line = -1;
2977 if (registeredonly && !peer->addr.sin_addr.s_addr)
2979 if (!ast_strlen_zero(peer->username))
2980 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2982 strncpy(name, peer->name, sizeof(name) - 1);
2984 if (peer->lastms < 0)
2985 strcpy(status, "UNREACHABLE");
2986 else if (peer->lastms > peer->maxms)
2987 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2988 else if (peer->lastms)
2989 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2991 strcpy(status, "UNKNOWN");
2993 strcpy(status, "Unmonitored");
2994 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2996 sprintf(srch, FORMAT, name,
2997 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2998 peer->dynamic ? "(D)" : "(S)",
3000 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
3003 if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
3005 } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
3007 } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
3015 ast_cli(fd, FORMAT, name,
3016 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
3017 peer->dynamic ? "(D)" : "(S)",
3019 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
3022 ast_mutex_unlock(&peerl.lock);
3023 return RESULT_SUCCESS;
3028 static int iax2_show_firmware(int fd, int argc, char *argv[])
3030 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
3031 #define FORMAT "%-15.15s %-15d %-15d\n"
3032 struct iax_firmware *cur;
3033 if ((argc != 3) && (argc != 4))
3034 return RESULT_SHOWUSAGE;
3035 ast_mutex_lock(&waresl.lock);
3037 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
3038 for (cur = waresl.wares;cur;cur = cur->next) {
3039 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname)))
3040 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
3041 ntohl(cur->fwh->datalen));
3043 ast_mutex_unlock(&waresl.lock);
3044 return RESULT_SUCCESS;
3049 /* JDG: callback to display iax peers in manager */
3050 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
3052 char *a[] = { "iax2", "show", "users" };
3054 ret = iax2_show_peers( s->fd, 3, a );
3055 ast_cli( s->fd, "\r\n" );
3059 static char *regstate2str(int regstate)
3062 case REG_STATE_UNREGISTERED:
3063 return "Unregistered";
3064 case REG_STATE_REGSENT:
3065 return "Request Sent";
3066 case REG_STATE_AUTHSENT:
3067 return "Auth. Sent";
3068 case REG_STATE_REGISTERED:
3069 return "Registered";
3070 case REG_STATE_REJECTED:
3072 case REG_STATE_TIMEOUT:
3074 case REG_STATE_NOAUTH:
3075 return "No Authentication";
3081 static int iax2_show_registry(int fd, int argc, char *argv[])
3083 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
3084 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
3085 struct iax2_registry *reg;
3089 return RESULT_SHOWUSAGE;
3090 ast_mutex_lock(&peerl.lock);
3091 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
3092 for (reg = registrations;reg;reg = reg->next) {
3093 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3094 if (reg->us.sin_addr.s_addr)
3095 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3097 strcpy(perceived, "<Unregistered>");
3098 ast_cli(fd, FORMAT, host,
3099 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
3101 ast_mutex_unlock(&peerl.lock);
3102 return RESULT_SUCCESS;
3107 static int iax2_show_channels(int fd, int argc, char *argv[])
3109 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
3110 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
3114 return RESULT_SHOWUSAGE;
3115 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
3116 for (x=0;x<IAX_MAX_CALLS;x++) {
3117 ast_mutex_lock(&iaxsl[x]);
3119 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
3120 !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)",
3121 iaxs[x]->callno, iaxs[x]->peercallno,
3122 iaxs[x]->oseqno, iaxs[x]->iseqno,
3125 ast_getformatname(iaxs[x]->voiceformat) );
3128 ast_mutex_unlock(&iaxsl[x]);
3130 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3131 return RESULT_SUCCESS;
3136 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3139 return RESULT_SHOWUSAGE;
3141 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3142 return RESULT_SUCCESS;
3145 static int iax2_do_debug(int fd, int argc, char *argv[])
3148 return RESULT_SHOWUSAGE;
3150 ast_cli(fd, "IAX2 Debugging Enabled\n");
3151 return RESULT_SUCCESS;
3154 static int iax2_no_debug(int fd, int argc, char *argv[])
3157 return RESULT_SHOWUSAGE;
3159 ast_cli(fd, "IAX2 Debugging Disabled\n");
3160 return RESULT_SUCCESS;
3165 static char show_users_usage[] =
3166 "Usage: iax2 show users\n"
3167 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
3169 static char show_channels_usage[] =
3170 "Usage: iax2 show channels\n"
3171 " Lists all currently active IAX channels.\n";
3173 static char show_peers_usage[] =
3174 "Usage: iax2 show peers\n"
3175 " Lists all known IAX peers.\n";
3177 static char show_firmware_usage[] =
3178 "Usage: iax2 show firmware\n"
3179 " Lists all known IAX firmware images.\n";
3181 static char show_reg_usage[] =
3182 "Usage: iax2 show registry\n"
3183 " Lists all registration requests and status.\n";
3185 static char debug_usage[] =
3186 "Usage: iax2 debug\n"
3187 " Enables dumping of IAX packets for debugging purposes\n";
3189 static char no_debug_usage[] =
3190 "Usage: iax2 no debug\n"
3191 " Disables dumping of IAX packets for debugging purposes\n";
3193 static char debug_trunk_usage[] =
3194 "Usage: iax2 trunk debug\n"
3195 " Requests current status of IAX trunking\n";
3197 static struct ast_cli_entry cli_show_users =
3198 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
3199 static struct ast_cli_entry cli_show_firmware =
3200 { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
3201 static struct ast_cli_entry cli_show_channels =
3202 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
3203 static struct ast_cli_entry cli_show_peers =
3204 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3205 static struct ast_cli_entry cli_show_peers_include =
3206 { { "iax2", "show", "peers", "include", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3207 static struct ast_cli_entry cli_show_peers_exclude =
3208 { { "iax2", "show", "peers", "exclude", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3209 static struct ast_cli_entry cli_show_peers_begin =
3210 { { "iax2", "show", "peers", "begin", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3211 static struct ast_cli_entry cli_show_registry =
3212 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
3213 static struct ast_cli_entry cli_debug =
3214 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
3215 static struct ast_cli_entry cli_trunk_debug =
3216 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
3217 static struct ast_cli_entry cli_no_debug =
3218 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
3220 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
3222 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
3224 ast_mutex_lock(&iaxsl[callno]);
3226 /* If there's an outstanding error, return failure now */
3227 if (!iaxs[callno]->error) {
3228 if (iaxs[callno]->alreadygone)
3230 /* Don't waste bandwidth sending null frames */
3231 else if (f->frametype == AST_FRAME_NULL)
3233 else if ((f->frametype == AST_FRAME_VOICE) && iaxs[callno]->quelch)
3235 else if (!(iaxs[callno]->state & IAX_STATE_STARTED))
3238 /* Simple, just queue for transmission */
3239 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
3241 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
3244 /* If it's already gone, just return */
3245 ast_mutex_unlock(&iaxsl[callno]);
3249 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
3250 int now, int transfer, int final)
3254 f.subclass = command;
3255 f.datalen = datalen;
3259 f.src = __FUNCTION__;
3261 return iax2_send(i, &f, ts, seqno, now, transfer, final);
3264 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3266 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
3269 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3272 ast_mutex_lock(&iaxsl[callno]);
3273 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
3274 ast_mutex_unlock(&iaxsl[callno]);
3278 #ifdef BRIDGE_OPTIMIZATION
3279 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3281 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
3285 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3287 /* It is assumed that the callno has already been locked */
3288 iax2_predestroy_nolock(i->callno);
3289 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
3292 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3294 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
3297 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
3299 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
3302 static int apply_context(struct iax2_context *con, char *context)
3305 if (!strcmp(con->context, context))
3313 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3315 /* Start pessimistic */
3318 struct iax2_user *user, *best = NULL;
3320 int gotcapability=0;
3323 if (ies->called_number)
3324 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
3325 if (ies->calling_number) {
3326 if (ies->calling_name)
3327 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
3329 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
3330 } else if (ies->calling_name)
3331 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
3332 if (ies->calling_ani)
3333 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
3335 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
3336 if (ies->called_context)
3337 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
3339 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
3341 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
3343 iaxs[callno]->peerformat = ies->format;
3345 iaxs[callno]->peeradsicpe = ies->adsicpe;
3346 if (ies->capability) {
3348 iaxs[callno]->peercapability = ies->capability;
3351 version = ies->version;
3353 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
3354 if (version > IAX_PROTO_VERSION) {
3355 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
3356 inet_ntoa(sin->sin_addr), version);
3359 ast_mutex_lock(&userl.lock);
3360 /* Search the userlist for a compatible entry, and fill in the rest */
3363 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
3364 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
3365 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
3366 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
3367 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
3368 if (!ast_strlen_zero(iaxs[callno]->username)) {
3369 /* Exact match, stop right now. */
3372 } else if (ast_strlen_zero(user->secret)) {
3373 /* No required authentication */
3375 /* There was host authentication and we passed, bonus! */
3376 if (bestscore < 4) {
3381 /* No host access, but no secret, either, not bad */
3382 if (bestscore < 3) {
3389 /* Authentication, but host access too, eh, it's something.. */
3390 if (bestscore < 2) {
3395 /* Authentication and no host access... This is our baseline */
3396 if (bestscore < 1) {
3405 ast_mutex_unlock(&userl.lock);
3407 #ifdef MYSQL_FRIENDS
3408 if (!user && mysql && !ast_strlen_zero(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
3409 user = mysql_user(iaxs[callno]->username);
3410 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
3411 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
3413 free(user->contexts);
3420 /* We found our match (use the first) */
3422 /* Store the requested username if not specified */
3423 if (ast_strlen_zero(iaxs[callno]->username))
3424 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
3425 /* Store whether this is a trunked call, too, of course, and move if appropriate */
3426 iaxs[callno]->trunk = user->trunk;
3427 iaxs[callno]->capability = user->capability;
3428 /* And use the default context */
3429 if (ast_strlen_zero(iaxs[callno]->context)) {
3431 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
3433 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
3435 /* Copy the secret */
3436 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
3437 /* And any input keys */
3438 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
3439 /* And the permitted authentication methods */
3440 iaxs[callno]->authmethods = user->authmethods;
3441 /* If they have callerid, override the given caller id. Always store the ANI */
3442 if (!ast_strlen_zero(iaxs[callno]->callerid)) {
3443 if (user->hascallerid)
3444 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
3445 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
3447 if (!ast_strlen_zero(user->accountcode))
3448 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
3450 iaxs[callno]->amaflags = user->amaflags;
3451 if (!ast_strlen_zero(user->language))
3452 strncpy(iaxs[callno]->language, user->language, sizeof(iaxs[callno]->language)-1);
3453 iaxs[callno]->notransfer = user->notransfer;
3456 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
3460 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
3462 struct ast_iax2_full_hdr fh;
3463 fh.scallno = htons(src | IAX_FLAG_FULL);
3464 fh.dcallno = htons(dst);
3468 fh.type = AST_FRAME_IAX;
3469 fh.csub = compress_subclass(IAX_COMMAND_INVAL);