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>
38 #include <arpa/inet.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <netinet/in_systm.h>
43 #include <netinet/ip.h>
45 #include <sys/signal.h>
55 #include <sys/types.h>
58 #include <sys/ioctl.h>
59 #include <linux/zaptel.h>
62 #include <mysql/mysql.h>
65 #include "iax2-parser.h"
66 #include "../astconf.h"
69 #define IPTOS_MINCOST 0x02
73 * Uncomment to try experimental IAX bridge optimization,
74 * designed to reduce latency when IAX calls cannot
78 #define BRIDGE_OPTIMIZATION
80 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
81 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
83 #define DEFAULT_RETRY_TIME 1000
84 #define MEMORY_SIZE 100
85 #define DEFAULT_DROP 3
86 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
87 but keeps the division between trunked and non-trunked better. */
88 #define TRUNK_CALL_START 0x4000
92 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
94 /* Sample over last 100 units to determine historic jitter */
98 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
100 static char mydbuser[80];
101 static char mydbpass[80];
102 static char mydbhost[80];
103 static char mydbname[80];
105 static char *desc = "Inter Asterisk eXchange (Ver 2)";
106 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
107 static char *type = "IAX2";
109 static char context[80] = "default";
111 static int max_retries = 4;
112 static int ping_time = 20;
113 static int lagrq_time = 10;
114 static int maxtrunkcall = TRUNK_CALL_START;
115 static int maxnontrunkcall = 1;
116 static int maxjitterbuffer=3000;
117 static int trunkfreq = 20;
118 static int authdebug = 1;
119 static int iaxcompat = 0;
121 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
123 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
125 static int netsocket = -1;
129 static int expirey = IAX_DEFAULT_REG_EXPIRE;
131 static int timingfd = -1; /* Timing file descriptor */
134 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
136 int (*iax2_regfunk)(char *username, int onoff) = NULL;
139 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
141 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
142 ~AST_FORMAT_SLINEAR & \
146 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
150 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
154 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
155 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
156 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
158 static struct io_context *io;
159 static struct sched_context *sched;
161 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
163 static int iax2_dropcount = DEFAULT_DROP;
165 static int use_jitterbuffer = 0;
167 static int iaxdebug = 0;
169 static int iaxtrunkdebug = 0;
171 static char accountcode[20];
172 static int amaflags = 0;
173 static int notransfer = 0;
175 static pthread_t netthreadid = AST_PTHREADT_NULL;
177 #define IAX_STATE_STARTED (1 << 0)
178 #define IAX_STATE_AUTHENTICATED (1 << 1)
179 #define IAX_STATE_TBD (1 << 2)
181 struct iax2_context {
182 char context[AST_MAX_EXTENSION];
183 struct iax2_context *next;
190 char accountcode[20];
191 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
198 char callerid[AST_MAX_EXTENSION];
200 struct iax2_context *contexts;
201 struct iax2_user *next;
209 char outkey[80]; /* What key we use to talk to this peer */
210 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
211 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
212 struct sockaddr_in addr;
216 /* Dynamic Registration fields */
217 int dynamic; /* If this is a dynamic peer */
218 struct sockaddr_in defaddr; /* Default address if there is one */
219 int authmethods; /* Authentication methods (IAX_AUTH_*) */
220 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
223 /* Suggested caller id if registering */
224 char callerid[AST_MAX_EXTENSION];
225 /* Whether or not to send ANI */
227 int expire; /* Schedule entry for expirey */
228 int expirey; /* How soon to expire */
229 int capability; /* Capability */
230 int delme; /* I need to be deleted */
231 int temponly; /* I'm only a temp */
232 int trunk; /* Treat as an IAX trunking */
235 int callno; /* Call number of POKE request */
236 int pokeexpire; /* When to expire poke */
237 int lastms; /* How long last response took (in ms), or -1 for no response */
238 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
241 struct iax2_peer *next;
245 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
247 static struct iax2_trunk_peer {
249 struct sockaddr_in addr;
250 struct timeval txtrunktime; /* Transmit trunktime */
251 struct timeval rxtrunktime; /* Receive trunktime */
252 struct timeval lasttxtime; /* Last transmitted trunktime */
253 struct timeval trunkact; /* Last trunk activity */
254 unsigned int lastsent; /* Last sent time */
255 /* Trunk data and length */
256 unsigned char *trunkdata;
257 unsigned int trunkdatalen;
258 unsigned int trunkdataalloc;
259 struct iax2_trunk_peer *next;
265 static ast_mutex_t tpeerlock = AST_MUTEX_INITIALIZER;
267 struct iax_firmware {
268 struct iax_firmware *next;
272 struct ast_iax2_firmware_header *fwh;
276 #define REG_STATE_UNREGISTERED 0
277 #define REG_STATE_REGSENT 1
278 #define REG_STATE_AUTHSENT 2
279 #define REG_STATE_REGISTERED 3
280 #define REG_STATE_REJECTED 4
281 #define REG_STATE_TIMEOUT 5
282 #define REG_STATE_NOAUTH 6
284 #define TRANSFER_NONE 0
285 #define TRANSFER_BEGIN 1
286 #define TRANSFER_READY 2
287 #define TRANSFER_RELEASED 3
288 #define TRANSFER_PASSTHROUGH 4
290 struct iax2_registry {
291 struct sockaddr_in addr; /* Who we connect to for registration purposes */
293 char secret[80]; /* Password or key name in []'s */
295 int expire; /* Sched ID of expiration */
296 int refresh; /* How often to refresh */
298 int messages; /* Message count */
299 int callno; /* Associated call number if applicable */
300 struct sockaddr_in us; /* Who the server thinks we are */
301 struct iax2_registry *next;
304 static struct iax2_registry *registrations;
306 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
307 #define MIN_RETRY_TIME 100
308 #define MAX_RETRY_TIME 10000
309 #define MAX_JITTER_BUFFER 50
311 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
312 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
314 /* If we have more than this much excess real jitter buffer, srhink it. */
315 static int max_jitter_buffer = MAX_JITTER_BUFFER;
317 struct chan_iax2_pvt {
318 /* Pipes for communication. pipe[1] belongs to the
319 network thread (write), and pipe[0] belongs to the individual
321 /* Whether or not we Quelch audio */
323 /* Last received voice format */
325 /* Last received voice format */
327 /* Last sent voice format */
329 /* Last sent video format */
331 /* What we are capable of sending */
333 /* Last received timestamp */
335 /* Last sent timestamp - never send the same timestamp twice in a single call */
336 unsigned int lastsent;
337 /* Next outgoing timestamp if everything is good */
338 unsigned int nextpred;
340 unsigned int pingtime;
341 /* Max time for initial response */
344 struct sockaddr_in addr;
345 /* Our call number */
346 unsigned short callno;
348 unsigned short peercallno;
349 /* Peer selected format */
351 /* Peer capability */
353 /* timeval that we base our transmission on */
354 struct timeval offset;
355 /* timeval that we base our delivery on */
356 struct timeval rxcore;
357 /* Historical delivery time */
358 int history[MEMORY_SIZE];
359 /* Current base jitterbuffer */
361 /* Current jitter measure */
363 /* Historic jitter value */
367 /* Error, as discovered by the manager */
369 /* Owner if we have one */
370 struct ast_channel *owner;
371 /* What's our state? */
373 /* Expirey (optional) */
375 /* Next outgoing sequence number */
376 unsigned char oseqno;
377 /* Next sequence number they have not yet acknowledged */
378 unsigned char rseqno;
379 /* Next incoming sequence number */
380 unsigned char iseqno;
381 /* Last incoming sequence number we have acknowledged */
382 unsigned char aseqno;
385 /* Default Context */
387 /* Caller ID if available */
389 /* Hidden Caller ID (i.e. ANI) if appropriate */
391 /* Whether or not ani should be transmitted in addition to Caller*ID */
393 /* Whether to request autoanswer */
397 /* Requested Extension */
398 char exten[AST_MAX_EXTENSION];
399 /* Expected Username */
401 /* Expected Secret */
403 /* permitted authentication methods */
407 /* Public keys permitted keys for incoming authentication */
409 /* Private key for outgoing authentication */
411 /* Preferred language */
413 /* Hostname/peername for naming purposes */
415 /* Associated registry */
416 struct iax2_registry *reg;
417 /* Associated peer for poking */
418 struct iax2_peer *peerpoke;
420 /* Transferring status */
422 /* Transfer identifier */
424 /* Already disconnected */
426 /* Who we are IAX transfering to */
427 struct sockaddr_in transfer;
428 /* What's the new call number for the transfer */
429 unsigned short transfercallno;
431 /* Status of knowledge of peer ADSI capability */
434 /* Who we are bridged to */
435 unsigned short bridgecallno;
436 unsigned int bridgesfmt;
437 struct ast_trans_pvt *bridgetrans;
439 int pingid; /* Transmit PING request */
440 int lagid; /* Retransmit lag request */
441 int autoid; /* Auto hangup for Dialplan requestor */
442 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
443 char dproot[AST_MAX_EXTENSION];
444 char accountcode[20];
446 /* This is part of a trunk interface */
448 struct iax2_dpcache *dpentries;
449 int notransfer; /* do we want native bridging */
452 static struct ast_iax2_queue {
453 struct iax_frame *head;
454 struct iax_frame *tail;
459 static struct ast_user_list {
460 struct iax2_user *users;
464 static struct ast_peer_list {
465 struct iax2_peer *peers;
469 static struct ast_firmware_list {
470 struct iax_firmware *wares;
474 /* Extension exists */
475 #define CACHE_FLAG_EXISTS (1 << 0)
476 /* Extension is non-existant */
477 #define CACHE_FLAG_NONEXISTANT (1 << 1)
478 /* Extension can exist */
479 #define CACHE_FLAG_CANEXIST (1 << 2)
480 /* Waiting to hear back response */
481 #define CACHE_FLAG_PENDING (1 << 3)
483 #define CACHE_FLAG_TIMEOUT (1 << 4)
484 /* Request transmitted */
485 #define CACHE_FLAG_TRANSMITTED (1 << 5)
487 #define CACHE_FLAG_UNKNOWN (1 << 6)
489 #define CACHE_FLAG_MATCHMORE (1 << 7)
491 static struct iax2_dpcache {
492 char peercontext[AST_MAX_EXTENSION];
493 char exten[AST_MAX_EXTENSION];
495 struct timeval expirey;
497 unsigned short callno;
499 struct iax2_dpcache *next;
500 struct iax2_dpcache *peer; /* For linking in peers */
503 static ast_mutex_t dpcache_lock;
505 static void iax_debug_output(const char *data)
510 static void iax_error_output(const char *data)
512 ast_log(LOG_WARNING, data);
515 /* XXX We probably should use a mutex when working with this XXX */
516 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
517 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
518 static struct timeval lastused[IAX_MAX_CALLS];
521 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
522 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
523 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
524 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
525 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
527 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f);
529 static int send_ping(void *data)
531 int callno = (long)data;
532 /* Ping only if it's real, not if it's bridged */
534 #ifdef BRIDGE_OPTIMIZATION
535 if (!iaxs[callno]->bridgecallno)
537 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
543 static int send_lagrq(void *data)
545 int callno = (long)data;
546 /* Ping only if it's real not if it's bridged */
548 #ifdef BRIDGE_OPTIMIZATION
549 if (!iaxs[callno]->bridgecallno)
551 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
557 static unsigned char compress_subclass(int subclass)
561 /* If it's 128 or smaller, just return it */
562 if (subclass < IAX_FLAG_SC_LOG)
564 /* Otherwise find its power */
565 for (x = 0; x < IAX_MAX_SHIFT; x++) {
566 if (subclass & (1 << x)) {
568 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
574 return power | IAX_FLAG_SC_LOG;
577 static int uncompress_subclass(unsigned char csub)
579 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
580 if (csub & IAX_FLAG_SC_LOG) {
581 /* special case for 'compressed' -1 */
585 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
591 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
593 struct iax2_peer *peer;
596 ast_mutex_lock(&peerl.lock);
599 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
600 (peer->addr.sin_port == sin.sin_port)) {
601 strncpy(host, peer->name, len-1);
608 ast_mutex_unlock(&peerl.lock);
612 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
614 struct chan_iax2_pvt *tmp;
615 tmp = malloc(sizeof(struct chan_iax2_pvt));
617 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
620 tmp->transfercallno = 0;
621 tmp->bridgecallno = 0;
626 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
627 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
628 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
629 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
634 static int get_samples(struct ast_frame *f)
637 switch(f->subclass) {
638 case AST_FORMAT_SPEEX:
639 samples = 160; /* XXX Not necessarily true XXX */
641 case AST_FORMAT_G723_1:
642 samples = 240 /* XXX Not necessarily true XXX */;
644 case AST_FORMAT_ILBC:
645 samples = 240 * (f->datalen / 50);
648 samples = 160 * (f->datalen / 33);
650 case AST_FORMAT_G729A:
651 samples = 160 * (f->datalen / 20);
653 case AST_FORMAT_SLINEAR:
654 samples = f->datalen / 2;
656 case AST_FORMAT_LPC10:
658 samples += (((char *)(f->data))[7] & 0x1) * 8;
660 case AST_FORMAT_ULAW:
661 samples = f->datalen;
663 case AST_FORMAT_ALAW:
664 samples = f->datalen;
666 case AST_FORMAT_ADPCM:
667 case AST_FORMAT_G726:
668 samples = f->datalen *2;
671 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
676 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
678 /* Malloc() a copy of a frame */
679 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
681 memcpy(new, fr, sizeof(struct iax_frame));
682 iax_frame_wrap(new, &fr->af);
685 new->direction = DIRECTION_INGRESS;
691 #define NEW_PREVENT 0
695 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
697 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
698 (cur->addr.sin_port == sin->sin_port)) {
699 /* This is the main host */
700 if ((cur->peercallno == callno) ||
701 ((dcallno == cur->callno) && !cur->peercallno)) {
702 /* That's us. Be sure we keep track of the peer call number */
706 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
707 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
708 /* We're transferring */
709 if (dcallno == cur->callno)
715 static void update_max_trunk(void)
717 int max = TRUNK_CALL_START;
719 /* XXX Prolly don't need locks here XXX */
720 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
726 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
729 static void update_max_nontrunk(void)
733 /* XXX Prolly don't need locks here XXX */
734 for (x=1;x<TRUNK_CALL_START - 1; x++) {
738 maxnontrunkcall = max;
740 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
743 static int make_trunk(unsigned short callno, int locked)
748 if (iaxs[callno]->oseqno) {
749 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
752 if (callno & TRUNK_CALL_START) {
753 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
756 gettimeofday(&now, NULL);
757 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
758 ast_mutex_lock(&iaxsl[x]);
759 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
760 iaxs[x] = iaxs[callno];
763 /* Update the two timers that should have been started */
764 if (iaxs[x]->pingid > -1)
765 ast_sched_del(sched, iaxs[x]->pingid);
766 if (iaxs[x]->lagid > -1)
767 ast_sched_del(sched, iaxs[x]->lagid);
768 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
769 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
771 ast_mutex_unlock(&iaxsl[callno]);
774 ast_mutex_unlock(&iaxsl[x]);
777 ast_mutex_unlock(&iaxsl[x]);
779 if (x >= IAX_MAX_CALLS - 1) {
780 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
783 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
784 /* We move this call from a non-trunked to a trunked call */
786 update_max_nontrunk();
790 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
795 if (new <= NEW_ALLOW) {
796 /* Look for an existing connection first */
797 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
798 ast_mutex_lock(&iaxsl[x]);
800 /* Look for an exact match */
801 if (match(sin, callno, dcallno, iaxs[x])) {
805 ast_mutex_unlock(&iaxsl[x]);
807 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
808 ast_mutex_lock(&iaxsl[x]);
810 /* Look for an exact match */
811 if (match(sin, callno, dcallno, iaxs[x])) {
815 ast_mutex_unlock(&iaxsl[x]);
818 if ((res < 1) && (new >= NEW_ALLOW)) {
819 gettimeofday(&now, NULL);
820 for (x=1;x<TRUNK_CALL_START;x++) {
821 /* Find first unused call number that hasn't been used in a while */
822 ast_mutex_lock(&iaxsl[x]);
823 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
824 ast_mutex_unlock(&iaxsl[x]);
826 /* We've still got lock held if we found a spot */
827 if (x >= TRUNK_CALL_START) {
828 ast_log(LOG_WARNING, "No more space\n");
831 iaxs[x] = new_iax(sin, lockpeer);
832 update_max_nontrunk();
835 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
836 iaxs[x]->addr.sin_port = sin->sin_port;
837 iaxs[x]->addr.sin_family = sin->sin_family;
838 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
839 iaxs[x]->peercallno = callno;
841 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
842 iaxs[x]->expirey = expirey;
843 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
844 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
845 iaxs[x]->amaflags = amaflags;
846 iaxs[x]->notransfer = notransfer;
847 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
849 ast_log(LOG_WARNING, "Out of resources\n");
850 ast_mutex_unlock(&iaxsl[x]);
853 ast_mutex_unlock(&iaxsl[x]);
859 static void iax2_frame_free(struct iax_frame *fr)
861 if (fr->retrans > -1)
862 ast_sched_del(sched, fr->retrans);
866 static int iax2_queue_frame(int callno, struct ast_frame *f)
869 /* Assumes lock for callno is already held... */
872 if (iaxs[callno] && iaxs[callno]->owner) {
873 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
874 /* Avoid deadlock by pausing and trying again */
875 ast_mutex_unlock(&iaxsl[callno]);
877 ast_mutex_lock(&iaxsl[callno]);
879 ast_queue_frame(iaxs[callno]->owner, f);
880 ast_mutex_unlock(&iaxs[callno]->owner->lock);
889 static void destroy_firmware(struct iax_firmware *cur)
893 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
899 static int try_firmware(char *s)
902 struct iax_firmware *cur;
905 struct ast_iax2_firmware_header *fwh, fwh2;
906 struct MD5Context md5;
907 unsigned char sum[16];
908 res = stat(s, &stbuf);
910 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
913 /* Make sure it's not a directory */
914 if (S_ISDIR(stbuf.st_mode))
916 fd = open(s, O_RDONLY);
918 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
921 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
922 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
926 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
927 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
931 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
932 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
936 if (fwh2.devname[sizeof(fwh2.devname) - 1] || !strlen(fwh2.devname)) {
937 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
941 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
943 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
948 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
950 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
951 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
952 munmap(fwh, stbuf.st_size);
958 if (!strcmp(cur->fwh->devname, fwh->devname)) {
959 /* Found a candidate */
960 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
961 /* The version we have on loaded is older, load this one instead */
963 /* This version is no newer than what we have. Don't worry about it.
964 We'll consider it a proper load anyhow though */
965 munmap(fwh, stbuf.st_size);
972 /* Allocate a new one and link it */
973 cur = malloc(sizeof(struct iax_firmware));
975 memset(cur, 0, sizeof(struct iax_firmware));
977 cur->next = waresl.wares;
983 munmap(cur->fwh, cur->mmaplen);
989 cur->mmaplen = stbuf.st_size;
995 static int iax_check_version(char *dev)
998 struct iax_firmware *cur;
999 if (dev && strlen(dev)) {
1000 ast_mutex_lock(&waresl.lock);
1003 if (!strcmp(dev, cur->fwh->devname)) {
1004 res = ntohs(cur->fwh->version);
1009 ast_mutex_unlock(&waresl.lock);
1014 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1017 unsigned int bs = desc & 0xff;
1018 unsigned int start = (desc >> 8) & 0xffffff;
1020 struct iax_firmware *cur;
1021 if (dev && strlen(dev) && bs) {
1023 ast_mutex_lock(&waresl.lock);
1026 if (!strcmp(dev, cur->fwh->devname)) {
1027 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1028 if (start < ntohl(cur->fwh->datalen)) {
1029 bytes = ntohl(cur->fwh->datalen) - start;
1032 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1035 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1045 ast_mutex_unlock(&waresl.lock);
1051 static void reload_firmware(void)
1053 struct iax_firmware *cur, *curl, *curp;
1058 /* Mark all as dead */
1059 ast_mutex_lock(&waresl.lock);
1065 /* Now that we've freed them, load the new ones */
1066 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1069 while((de = readdir(fwd))) {
1070 if (de->d_name[0] != '.') {
1071 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1072 if (!try_firmware(fn)) {
1073 if (option_verbose > 1)
1074 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1080 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1082 /* Clean up leftovers */
1094 destroy_firmware(curl);
1099 ast_mutex_unlock(&waresl.lock);
1102 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1104 static int __do_deliver(void *data)
1106 /* Just deliver the packet by using queueing. This is called by
1107 the IAX thread with the iaxsl lock held. */
1108 struct iax_frame *fr = data;
1111 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
1112 if (fr->af.frametype == AST_FRAME_IAX) {
1113 /* We have to treat some of these packets specially because
1114 they're LAG measurement packets */
1115 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
1116 /* If we got a queued request, build a reply and send it */
1117 fr->af.subclass = IAX_COMMAND_LAGRP;
1118 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
1119 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
1120 /* This is a reply we've been given, actually measure the difference */
1121 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
1122 iaxs[fr->callno]->lag = ts - fr->ts;
1125 iax2_queue_frame(fr->callno, &fr->af);
1128 /* Free our iax frame */
1129 iax2_frame_free(fr);
1130 /* And don't run again */
1134 static int do_deliver(void *data)
1136 /* Locking version of __do_deliver */
1137 struct iax_frame *fr = data;
1138 int callno = fr->callno;
1140 ast_mutex_lock(&iaxsl[callno]);
1141 res = __do_deliver(data);
1142 ast_mutex_unlock(&iaxsl[callno]);
1146 static int handle_error(void)
1148 /* XXX Ideally we should figure out why an error occured and then abort those
1149 rather than continuing to try. Unfortunately, the published interface does
1150 not seem to work XXX */
1152 struct sockaddr_in *sin;
1155 struct sock_extended_err e;
1160 m.msg_controllen = sizeof(e);
1162 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1164 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1166 if (m.msg_controllen) {
1167 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1169 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
1171 ast_log(LOG_WARNING, "No address detected??\n");
1173 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1180 static int send_packet(struct iax_frame *f)
1183 /* Called with iaxsl held */
1185 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));
1186 /* Don't send if there was an error, but return error instead */
1188 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1191 if (!iaxs[f->callno])
1193 if (iaxs[f->callno]->error)
1197 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1198 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1199 sizeof(iaxs[f->callno]->transfer));
1202 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1203 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1204 sizeof(iaxs[f->callno]->addr));
1208 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1216 static int iax2_predestroy(int callno)
1218 struct ast_channel *c;
1219 struct chan_iax2_pvt *pvt;
1220 ast_mutex_lock(&iaxsl[callno]);
1223 ast_mutex_unlock(&iaxsl[callno]);
1226 if (!pvt->alreadygone) {
1227 /* No more pings or lagrq's */
1228 if (pvt->pingid > -1)
1229 ast_sched_del(sched, pvt->pingid);
1230 if (pvt->lagid > -1)
1231 ast_sched_del(sched, pvt->lagid);
1232 if (pvt->autoid > -1)
1233 ast_sched_del(sched, pvt->autoid);
1234 if (pvt->initid > -1)
1235 ast_sched_del(sched, pvt->initid);
1240 pvt->alreadygone = 1;
1244 c->_softhangup |= AST_SOFTHANGUP_DEV;
1246 ast_queue_hangup(c);
1248 ast_mutex_lock(&usecnt_lock);
1251 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1252 ast_mutex_unlock(&usecnt_lock);
1254 ast_mutex_unlock(&iaxsl[callno]);
1255 ast_update_use_count();
1259 static int iax2_predestroy_nolock(int callno)
1262 ast_mutex_unlock(&iaxsl[callno]);
1263 res = iax2_predestroy(callno);
1264 ast_mutex_lock(&iaxsl[callno]);
1268 static void iax2_destroy(int callno)
1270 struct chan_iax2_pvt *pvt;
1271 struct iax_frame *cur;
1272 struct ast_channel *owner;
1275 ast_mutex_lock(&iaxsl[callno]);
1277 gettimeofday(&lastused[callno], NULL);
1284 if (ast_mutex_trylock(&owner->lock)) {
1285 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1286 ast_mutex_unlock(&iaxsl[callno]);
1292 iaxs[callno] = NULL;
1296 /* No more pings or lagrq's */
1297 if (pvt->pingid > -1)
1298 ast_sched_del(sched, pvt->pingid);
1299 if (pvt->lagid > -1)
1300 ast_sched_del(sched, pvt->lagid);
1301 if (pvt->autoid > -1)
1302 ast_sched_del(sched, pvt->autoid);
1303 if (pvt->initid > -1)
1304 ast_sched_del(sched, pvt->initid);
1309 if (pvt->bridgetrans)
1310 ast_translator_free_path(pvt->bridgetrans);
1311 pvt->bridgetrans = NULL;
1314 pvt->alreadygone = 1;
1317 /* If there's an owner, prod it to give up */
1318 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1319 ast_queue_hangup(owner);
1322 for (cur = iaxq.head; cur ; cur = cur->next) {
1323 /* Cancel any pending transmissions */
1324 if (cur->callno == pvt->callno)
1328 pvt->reg->callno = 0;
1334 ast_mutex_unlock(&owner->lock);
1336 ast_mutex_unlock(&iaxsl[callno]);
1337 if (callno & 0x4000)
1340 static void iax2_destroy_nolock(int callno)
1342 /* Actually it's easier to unlock, kill it, and relock */
1343 ast_mutex_unlock(&iaxsl[callno]);
1344 iax2_destroy(callno);
1345 ast_mutex_lock(&iaxsl[callno]);
1348 static int update_packet(struct iax_frame *f)
1350 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1351 struct ast_iax2_full_hdr *fh = f->data;
1352 /* Mark this as a retransmission */
1353 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1355 f->iseqno = iaxs[f->callno]->iseqno;
1356 fh->iseqno = f->iseqno;
1360 static int attempt_transmit(void *data)
1362 /* Attempt to transmit the frame to the remote peer...
1363 Called without iaxsl held. */
1364 struct iax_frame *f = data;
1366 int callno = f->callno;
1367 /* Make sure this call is still active */
1369 ast_mutex_lock(&iaxsl[callno]);
1370 if ((f->callno) && iaxs[f->callno]) {
1371 if ((f->retries < 0) /* Already ACK'd */ ||
1372 (f->retries >= max_retries) /* Too many attempts */) {
1373 /* Record an error if we've transmitted too many times */
1374 if (f->retries >= max_retries) {
1376 /* Transfer timeout */
1377 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1378 } else if (f->final) {
1380 iax2_destroy_nolock(f->callno);
1382 if (iaxs[f->callno]->owner)
1383 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);
1384 iaxs[f->callno]->error = ETIMEDOUT;
1385 if (iaxs[f->callno]->owner) {
1386 struct ast_frame fr = { 0, };
1388 fr.frametype = AST_FRAME_CONTROL;
1389 fr.subclass = AST_CONTROL_HANGUP;
1390 iax2_queue_frame(f->callno, &fr);
1392 if (iaxs[f->callno]->reg) {
1393 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1394 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1395 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1397 iax2_destroy_nolock(f->callno);
1404 /* Update it if it needs it */
1406 /* Attempt transmission */
1409 /* Try again later after 10 times as long */
1411 if (f->retrytime > MAX_RETRY_TIME)
1412 f->retrytime = MAX_RETRY_TIME;
1413 /* Transfer messages max out at one second */
1414 if (f->transfer && (f->retrytime > 1000))
1415 f->retrytime = 1000;
1416 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1419 /* Make sure it gets freed */
1424 ast_mutex_unlock(&iaxsl[callno]);
1425 /* Do not try again */
1427 /* Don't attempt delivery, just remove it from the queue */
1428 ast_mutex_lock(&iaxq.lock);
1430 f->prev->next = f->next;
1432 iaxq.head = f->next;
1434 f->next->prev = f->prev;
1436 iaxq.tail = f->prev;
1438 ast_mutex_unlock(&iaxq.lock);
1440 /* Free the IAX frame */
1446 static int iax2_set_jitter(int fd, int argc, char *argv[])
1448 if ((argc != 4) && (argc != 5))
1449 return RESULT_SHOWUSAGE;
1451 max_jitter_buffer = atoi(argv[3]);
1452 if (max_jitter_buffer < 0)
1453 max_jitter_buffer = 0;
1456 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1457 if (iaxs[atoi(argv[3])]) {
1458 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1459 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1460 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1462 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1464 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1467 return RESULT_SUCCESS;
1470 static char jitter_usage[] =
1471 "Usage: iax set jitter [callid] <value>\n"
1472 " If used with a callid, it sets the jitter buffer to the given static\n"
1473 "value (until its next calculation). If used without a callid, the value is used\n"
1474 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1475 "buffer size is reduced.";
1477 static int iax2_show_stats(int fd, int argc, char *argv[])
1479 struct iax_frame *cur;
1480 int cnt = 0, dead=0, final=0;
1482 return RESULT_SHOWUSAGE;
1483 for (cur = iaxq.head; cur ; cur = cur->next) {
1484 if (cur->retries < 0)
1490 ast_cli(fd, " IAX Statistics\n");
1491 ast_cli(fd, "---------------------\n");
1492 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1493 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1494 return RESULT_SUCCESS;
1497 static int iax2_show_cache(int fd, int argc, char *argv[])
1499 struct iax2_dpcache *dp;
1500 char tmp[1024], *pc;
1504 gettimeofday(&tv, NULL);
1505 ast_mutex_lock(&dpcache_lock);
1507 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1509 s = dp->expirey.tv_sec - tv.tv_sec;
1511 if (dp->flags & CACHE_FLAG_EXISTS)
1512 strcat(tmp, "EXISTS|");
1513 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1514 strcat(tmp, "NONEXISTANT|");
1515 if (dp->flags & CACHE_FLAG_CANEXIST)
1516 strcat(tmp, "CANEXIST|");
1517 if (dp->flags & CACHE_FLAG_PENDING)
1518 strcat(tmp, "PENDING|");
1519 if (dp->flags & CACHE_FLAG_TIMEOUT)
1520 strcat(tmp, "TIMEOUT|");
1521 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1522 strcat(tmp, "TRANSMITTED|");
1523 if (dp->flags & CACHE_FLAG_MATCHMORE)
1524 strcat(tmp, "MATCHMORE|");
1525 if (dp->flags & CACHE_FLAG_UNKNOWN)
1526 strcat(tmp, "UNKNOWN|");
1527 /* Trim trailing pipe */
1529 tmp[strlen(tmp) - 1] = '\0';
1531 strcpy(tmp, "(none)");
1533 pc = strchr(dp->peercontext, '@');
1535 pc = dp->peercontext;
1538 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1539 if (dp->waiters[x] > -1)
1542 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1544 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1547 ast_mutex_unlock(&dpcache_lock);
1548 return RESULT_SUCCESS;
1551 static char show_stats_usage[] =
1552 "Usage: iax show stats\n"
1553 " Display statistics on IAX channel driver.\n";
1556 static char show_cache_usage[] =
1557 "Usage: iax show cache\n"
1558 " Display currently cached IAX Dialplan results.\n";
1560 static struct ast_cli_entry cli_set_jitter =
1561 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1563 static struct ast_cli_entry cli_show_stats =
1564 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1566 static struct ast_cli_entry cli_show_cache =
1567 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1569 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1571 #ifdef BRIDGE_OPTIMIZATION
1572 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1574 static int forward_delivery(struct iax_frame *fr)
1576 struct chan_iax2_pvt *p1, *p2;
1577 p1 = iaxs[fr->callno];
1578 p2 = iaxs[p1->bridgecallno];
1583 /* Fix relative timestamp */
1584 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1585 /* Now just send it send on the 2nd one
1586 with adjusted timestamp */
1587 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1591 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1594 int drops[MEMORY_SIZE];
1595 int min, max=0, maxone=0,y,z, match;
1596 /* ms is a measure of the "lateness" of the packet relative to the first
1597 packet we received, which always has a lateness of 1. Called by
1598 IAX thread, with iaxsl lock held. */
1599 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1602 /* What likely happened here is that our counter has circled but we haven't
1603 gotten the update from the main packet. We'll just pretend that we did, and
1604 update the timestamp appropriately. */
1610 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1616 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1617 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1618 fr->af.delivery.tv_sec += fr->ts / 1000;
1619 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1620 if (fr->af.delivery.tv_usec >= 1000000) {
1621 fr->af.delivery.tv_usec -= 1000000;
1622 fr->af.delivery.tv_sec += 1;
1626 /* Rotate our history queue of "lateness". Don't worry about those initial
1627 zeros because the first entry will always be zero */
1628 if (updatehistory) {
1629 for (x=0;x<MEMORY_SIZE - 1;x++)
1630 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1631 /* Add a history entry for this one */
1632 iaxs[fr->callno]->history[x] = ms;
1635 /* Initialize the minimum to reasonable values. It's too much
1636 work to do the same for the maximum, repeatedly */
1637 min=iaxs[fr->callno]->history[0];
1638 for (z=0;z < iax2_dropcount + 1;z++) {
1639 /* Start very optimistic ;-) */
1641 for (x=0;x<MEMORY_SIZE;x++) {
1642 if (max < iaxs[fr->callno]->history[x]) {
1643 /* We have a candidate new maximum value. Make
1644 sure it's not in our drop list */
1646 for (y=0;!match && (y<z);y++)
1647 match |= (drops[y] == x);
1649 /* It's not in our list, use it as the new maximum */
1650 max = iaxs[fr->callno]->history[x];
1656 /* On our first pass, find the minimum too */
1657 if (min > iaxs[fr->callno]->history[x])
1658 min = iaxs[fr->callno]->history[x];
1665 /* Just for reference, keep the "jitter" value, the difference between the
1666 earliest and the latest. */
1667 iaxs[fr->callno]->jitter = max - min;
1669 /* IIR filter for keeping track of historic jitter, but always increase
1670 historic jitter immediately for increase */
1672 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1673 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1675 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1676 iaxs[fr->callno]->historicjitter;
1678 /* If our jitter buffer is too big (by a significant margin), then we slowly
1679 shrink it by about 1 ms each time to avoid letting the change be perceived */
1680 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1681 iaxs[fr->callno]->jitterbuffer -= 2;
1685 /* Constrain our maximum jitter buffer appropriately */
1686 if (max > min + maxjitterbuffer) {
1688 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1689 max = min + maxjitterbuffer;
1693 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1694 buffer immediately to accomodate it (and a little more). */
1695 if (max > iaxs[fr->callno]->jitterbuffer)
1696 iaxs[fr->callno]->jitterbuffer = max
1697 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1701 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1703 /* Subtract the lateness from our jitter buffer to know how long to wait
1704 before sending our packet. */
1705 ms = iaxs[fr->callno]->jitterbuffer - ms;
1707 if (!use_jitterbuffer)
1710 /* If the caller just wanted us to update, return now */
1716 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1717 /* Don't deliver it more than 4 ms late */
1718 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1722 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1723 /* Free our iax frame */
1724 iax2_frame_free(fr);
1728 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1729 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1734 static int iax2_transmit(struct iax_frame *fr)
1736 /* Lock the queue and place this packet at the end */
1739 /* By setting this to 0, the network thread will send it for us, and
1740 queue retransmission if necessary */
1742 ast_mutex_lock(&iaxq.lock);
1749 iaxq.tail->next = fr;
1750 fr->prev = iaxq.tail;
1754 ast_mutex_unlock(&iaxq.lock);
1755 /* Wake up the network thread */
1756 pthread_kill(netthreadid, SIGURG);
1762 static int iax2_digit(struct ast_channel *c, char digit)
1764 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1767 static int iax2_sendtext(struct ast_channel *c, char *text)
1770 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1771 0, 0, text, strlen(text) + 1, -1);
1774 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1776 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1779 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1781 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1784 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1786 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1787 ast_mutex_lock(&iaxsl[callno]);
1789 iaxs[callno]->owner = newchan;
1791 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1792 ast_mutex_unlock(&iaxsl[callno]);
1796 #ifdef MYSQL_FRIENDS
1798 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1800 if (mysql && (strlen(peer) < 128)) {
1804 name = alloca(strlen(peer) * 2 + 1);
1806 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1807 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1808 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1809 ast_mutex_lock(&mysqllock);
1810 if (mysql_real_query(mysql, query, strlen(query)))
1811 ast_log(LOG_WARNING, "Unable to update database\n");
1813 ast_mutex_unlock(&mysqllock);
1817 static struct iax2_peer *mysql_peer(char *peer)
1819 struct iax2_peer *p;
1822 p = malloc(sizeof(struct iax2_peer));
1823 memset(p, 0, sizeof(struct iax2_peer));
1824 if (mysql && (strlen(peer) < 128)) {
1829 time_t regseconds, nowtime;
1831 MYSQL_FIELD *fields;
1833 name = alloca(strlen(peer) * 2 + 1);
1834 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1835 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds FROM iaxfriends WHERE name=\"%s\"", name);
1836 ast_mutex_lock(&mysqllock);
1837 mysql_query(mysql, query);
1838 if ((result = mysql_store_result(mysql))) {
1839 if ((rowval = mysql_fetch_row(result))) {
1840 numfields = mysql_num_fields(result);
1841 fields = mysql_fetch_fields(result);
1843 for (x=0;x<numfields;x++) {
1845 if (!strcasecmp(fields[x].name, "secret")) {
1846 strncpy(p->secret, rowval[x], sizeof(p->secret));
1847 } else if (!strcasecmp(fields[x].name, "context")) {
1848 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1849 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1850 inet_aton(rowval[x], &p->addr.sin_addr);
1851 } else if (!strcasecmp(fields[x].name, "port")) {
1852 if (sscanf(rowval[x], "%i", &port) != 1)
1854 p->addr.sin_port = htons(port);
1855 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1856 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1862 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1863 memset(&p->addr, 0, sizeof(p->addr));
1865 mysql_free_result(result);
1868 ast_mutex_unlock(&mysqllock);
1874 strncpy(p->name, peer, sizeof(p->name) - 1);
1878 p->capability = iax2_capability;
1879 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1883 static struct iax2_user *mysql_user(char *user)
1885 struct iax2_user *p;
1886 struct iax2_context *con;
1889 p = malloc(sizeof(struct iax2_user));
1890 memset(p, 0, sizeof(struct iax2_user));
1891 con = malloc(sizeof(struct iax2_context));
1892 memset(con, 0, sizeof(struct iax2_context));
1893 strcpy(con->context, "default");
1895 if (mysql && (strlen(user) < 128)) {
1900 MYSQL_FIELD *fields;
1902 name = alloca(strlen(user) * 2 + 1);
1903 mysql_real_escape_string(mysql, name, user, strlen(user));
1904 snprintf(query, sizeof(query), "SELECT name, secret, context, ipaddr, port, regseconds, accountcode FROM iaxfriends WHERE name=\"%s\"", name);
1905 ast_mutex_lock(&mysqllock);
1906 mysql_query(mysql, query);
1907 if ((result = mysql_store_result(mysql))) {
1908 if ((rowval = mysql_fetch_row(result))) {
1909 numfields = mysql_num_fields(result);
1910 fields = mysql_fetch_fields(result);
1912 for (x=0;x<numfields;x++) {
1914 if (!strcasecmp(fields[x].name, "secret")) {
1915 strncpy(p->secret, rowval[x], sizeof(p->secret));
1916 } else if (!strcasecmp(fields[x].name, "context")) {
1917 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1918 } else if (!strcasecmp(fields[x].name, "accountcode")) {
1919 strncpy(p->accountcode, rowval[x], sizeof(p->accountcode));
1924 mysql_free_result(result);
1927 ast_mutex_unlock(&mysqllock);
1935 strncpy(p->name, user, sizeof(p->name) - 1);
1937 p->capability = iax2_capability;
1938 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1942 #endif /* MYSQL_FRIENDS */
1944 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)
1946 struct ast_hostent ahp; struct hostent *hp;
1947 struct iax2_peer *p;
1955 sin->sin_family = AF_INET;
1956 ast_mutex_lock(&peerl.lock);
1959 if (!strcasecmp(p->name, peer)) {
1964 ast_mutex_unlock(&peerl.lock);
1965 #ifdef MYSQL_FRIENDS
1967 p = mysql_peer(peer);
1971 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1972 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1974 *sendani = p->sendani; /* Whether we transmit ANI */
1976 *maxtime = p->maxms; /* Max time they should take */
1978 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1982 *capability = p->capability;
1984 strncpy(secret, p->secret, seclen);
1985 if (p->addr.sin_addr.s_addr) {
1986 sin->sin_addr = p->addr.sin_addr;
1987 sin->sin_port = p->addr.sin_port;
1989 sin->sin_addr = p->defaddr.sin_addr;
1990 sin->sin_port = p->defaddr.sin_port;
1993 *notransfer=p->notransfer;
2001 hp = ast_gethostbyname(peer, &ahp);
2003 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2004 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2007 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2017 static int auto_congest(void *nothing)
2019 int callno = PTR_TO_CALLNO(nothing);
2020 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2021 ast_mutex_lock(&iaxsl[callno]);
2023 iaxs[callno]->initid = -1;
2024 iax2_queue_frame(callno, &f);
2025 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2027 ast_mutex_unlock(&iaxsl[callno]);
2031 static unsigned int iax2_datetime(void)
2037 localtime_r(&t, &tm);
2038 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2039 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2040 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2041 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2042 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2043 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2047 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2049 struct sockaddr_in sin;
2054 char *secret = NULL;
2057 char *l=NULL, *n=NULL;
2058 struct iax_ie_data ied;
2059 char myrdest [5] = "s";
2060 char context[AST_MAX_EXTENSION] ="";
2061 char *portno = NULL;
2063 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2065 char storedsecret[80];
2066 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2067 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2070 strncpy(host, dest, sizeof(host)-1);
2072 strsep(&stringp, "/");
2073 /* If no destination extension specified, use 's' */
2074 rdest = strsep(&stringp, "/");
2078 /* Check for trailing options */
2079 opts = strsep(&stringp, "/");
2084 strsep(&stringp, "@");
2085 rcontext = strsep(&stringp, "@");
2087 strsep(&stringp, "@");
2088 username = strsep(&stringp, "@");
2090 /* Really the second argument is the host, not the username */
2098 username = strsep(&stringp, ":");
2099 secret = strsep(&stringp, ":");
2102 if (strsep(&stringp, ":")) {
2104 strsep(&stringp, ":");
2105 portno = strsep(&stringp, ":");
2107 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
2108 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2111 /* Keep track of the context for outgoing calls too */
2112 strncpy(c->context, context, sizeof(c->context) - 1);
2114 sin.sin_port = htons(atoi(portno));
2117 strncpy(cid, c->callerid, sizeof(cid) - 1);
2118 ast_callerid_parse(cid, &n, &l);
2120 ast_shrink_phone_number(l);
2122 /* Now build request */
2123 memset(&ied, 0, sizeof(ied));
2124 /* On new call, first IE MUST be IAX version of caller */
2125 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2126 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2127 if (strchr(opts, 'a')) {
2128 /* Request auto answer */
2129 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2132 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2134 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2135 if (iaxs[callno]->sendani && c->ani) {
2137 strncpy(cid, c->ani, sizeof(cid) - 1);
2138 ast_callerid_parse(cid, &n, &l);
2140 ast_shrink_phone_number(l);
2141 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2144 if (c->language && strlen(c->language))
2145 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2146 if (c->dnid && strlen(c->dnid))
2147 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2149 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2151 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2152 if (!secret && strlen(storedsecret))
2153 secret = storedsecret;
2154 ast_mutex_lock(&iaxsl[callno]);
2155 if (strlen(c->context))
2156 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2158 if (secret[0] == '[') {
2159 /* This is an RSA key, not a normal secret */
2160 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2161 if (strlen(iaxs[callno]->outkey)) {
2162 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2165 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2167 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2168 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2169 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2170 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2171 /* Transmit the string in a "NEW" request */
2173 /* XXX We have no equivalent XXX */
2174 if (option_verbose > 2)
2175 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2177 if (iaxs[callno]->maxtime) {
2178 /* Initialize pingtime and auto-congest time */
2179 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2180 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2182 send_command(iaxs[callno], AST_FRAME_IAX,
2183 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2184 ast_mutex_unlock(&iaxsl[callno]);
2185 ast_setstate(c, AST_STATE_RINGING);
2189 static int iax2_hangup(struct ast_channel *c)
2191 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2193 ast_mutex_lock(&iaxsl[callno]);
2194 if (callno && iaxs[callno]) {
2195 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2196 alreadygone = iaxs[callno]->alreadygone;
2197 /* Send the hangup unless we have had a transmission error or are already gone */
2198 if (!iaxs[callno]->error && !alreadygone)
2199 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2200 /* Explicitly predestroy it */
2201 iax2_predestroy_nolock(callno);
2202 /* If we were already gone to begin with, destroy us now */
2204 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2205 iax2_destroy_nolock(callno);
2208 ast_mutex_unlock(&iaxsl[callno]);
2209 if (option_verbose > 2)
2210 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2214 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2216 struct ast_option_header *h;
2218 h = malloc(datalen + sizeof(struct ast_option_header));
2220 h->flag = AST_OPTION_FLAG_REQUEST;
2221 h->option = htons(option);
2222 memcpy(h->data, data, datalen);
2223 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2224 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2228 ast_log(LOG_WARNING, "Out of memory\n");
2232 static struct ast_frame *iax2_read(struct ast_channel *c)
2234 static struct ast_frame f = { AST_FRAME_NULL, };
2235 ast_log(LOG_NOTICE, "I should never be called!\n");
2239 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2242 struct iax_ie_data ied0;
2243 struct iax_ie_data ied1;
2244 unsigned int transferid = rand();
2245 memset(&ied0, 0, sizeof(ied0));
2246 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2247 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2248 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2250 memset(&ied1, 0, sizeof(ied1));
2251 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2252 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2253 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2255 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2258 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2261 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2262 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2266 static void lock_both(unsigned short callno0, unsigned short callno1)
2268 ast_mutex_lock(&iaxsl[callno0]);
2269 while (ast_mutex_trylock(&iaxsl[callno1])) {
2270 ast_mutex_unlock(&iaxsl[callno0]);
2272 ast_mutex_lock(&iaxsl[callno0]);
2276 static void unlock_both(unsigned short callno0, unsigned short callno1)
2278 ast_mutex_unlock(&iaxsl[callno1]);
2279 ast_mutex_unlock(&iaxsl[callno0]);
2282 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2284 struct ast_channel *cs[3];
2285 struct ast_channel *who;
2288 int transferstarted=0;
2289 struct ast_frame *f;
2290 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2291 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2292 struct timeval waittimer = {0, 0}, tv;
2294 lock_both(callno0, callno1);
2295 /* Put them in native bridge mode */
2296 iaxs[callno0]->bridgecallno = callno1;
2297 iaxs[callno1]->bridgecallno = callno0;
2298 unlock_both(callno0, callno1);
2300 /* If not, try to bridge until we can execute a transfer, if we can */
2303 for (/* ever */;;) {
2304 /* Check in case we got masqueraded into */
2305 if ((c0->type != type) || (c1->type != type)) {
2306 if (option_verbose > 2)
2307 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2308 /* Remove from native mode */
2309 if (c0->type == type) {
2310 ast_mutex_lock(&iaxsl[callno0]);
2311 iaxs[callno0]->bridgecallno = 0;
2312 ast_mutex_unlock(&iaxsl[callno0]);
2314 if (c1->type == type) {
2315 ast_mutex_lock(&iaxsl[callno1]);
2316 iaxs[callno1]->bridgecallno = 0;
2317 ast_mutex_unlock(&iaxsl[callno1]);
2321 if (c0->nativeformats != c1->nativeformats) {
2322 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2323 /* Remove from native mode */
2324 lock_both(callno0, callno1);
2325 iaxs[callno0]->bridgecallno = 0;
2326 iaxs[callno1]->bridgecallno = 0;
2327 unlock_both(callno0, callno1);
2330 /* check if transfered and if we really want native bridging */
2331 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2332 /* Try the transfer */
2333 if (iax2_start_transfer(callno0, callno1))
2334 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2335 transferstarted = 1;
2337 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2338 /* Call has been transferred. We're no longer involved */
2339 gettimeofday(&tv, NULL);
2340 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2341 waittimer.tv_sec = tv.tv_sec;
2342 waittimer.tv_usec = tv.tv_usec;
2343 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2344 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2345 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2353 who = ast_waitfor_n(cs, 2, &to);
2355 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2368 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2374 if ((f->frametype == AST_FRAME_VOICE) ||
2375 (f->frametype == AST_FRAME_TEXT) ||
2376 (f->frametype == AST_FRAME_VIDEO) ||
2377 (f->frametype == AST_FRAME_IMAGE) ||
2378 (f->frametype == AST_FRAME_DTMF)) {
2379 if ((f->frametype == AST_FRAME_DTMF) &&
2380 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2382 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2385 /* Take out of conference mode */
2387 /* Remove from native mode */
2393 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2397 /* Remove from native mode */
2404 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2406 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2418 /* Swap who gets priority */
2423 lock_both(callno0, callno1);
2424 iaxs[callno0]->bridgecallno = 0;
2425 iaxs[callno1]->bridgecallno = 0;
2426 unlock_both(callno0, callno1);
2430 static int iax2_answer(struct ast_channel *c)
2432 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2434 ast_log(LOG_DEBUG, "Answering\n");
2435 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2438 static int iax2_indicate(struct ast_channel *c, int condition)
2440 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2442 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2443 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2446 static int iax2_transfer(struct ast_channel *c, char *dest)
2448 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2449 struct iax_ie_data ied;
2450 char tmp[256] = "", *context;
2451 strncpy(tmp, dest, sizeof(tmp) - 1);
2452 context = strchr(tmp, '@');
2457 memset(&ied, 0, sizeof(ied));
2458 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2460 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2462 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2463 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2467 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2469 static int iax2_getpeertrunk(struct sockaddr_in sin)
2471 struct iax2_peer *peer;
2473 ast_mutex_lock(&peerl.lock);
2476 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2477 (peer->addr.sin_port == sin.sin_port)) {
2483 ast_mutex_unlock(&peerl.lock);
2487 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2489 struct ast_channel *tmp;
2490 tmp = ast_channel_alloc(1);
2492 if (strlen(i->username))
2493 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2495 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2497 /* We can support any format by default, until we get restricted */
2498 tmp->nativeformats = capability;
2499 tmp->readformat = 0;
2500 tmp->writeformat = 0;
2501 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2502 tmp->pvt->send_digit = iax2_digit;
2503 tmp->pvt->send_text = iax2_sendtext;
2504 tmp->pvt->send_image = iax2_sendimage;
2505 tmp->pvt->send_html = iax2_sendhtml;
2506 tmp->pvt->call = iax2_call;
2507 tmp->pvt->hangup = iax2_hangup;
2508 tmp->pvt->answer = iax2_answer;
2509 tmp->pvt->read = iax2_read;
2510 tmp->pvt->write = iax2_write;
2511 tmp->pvt->write_video = iax2_write;
2512 tmp->pvt->indicate = iax2_indicate;
2513 tmp->pvt->setoption = iax2_setoption;
2514 tmp->pvt->bridge = iax2_bridge;
2515 tmp->pvt->transfer = iax2_transfer;
2516 if (strlen(i->callerid))
2517 tmp->callerid = strdup(i->callerid);
2519 tmp->ani = strdup(i->ani);
2520 if (strlen(i->language))
2521 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2522 if (strlen(i->dnid))
2523 tmp->dnid = strdup(i->dnid);
2524 if (strlen(i->accountcode))
2525 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2527 tmp->amaflags = i->amaflags;
2528 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2529 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2530 tmp->adsicpe = i->peeradsicpe;
2531 tmp->pvt->fixup = iax2_fixup;
2533 i->capability = capability;
2534 ast_setstate(tmp, state);
2535 ast_mutex_lock(&usecnt_lock);
2537 ast_mutex_unlock(&usecnt_lock);
2538 ast_update_use_count();
2539 if (state != AST_STATE_DOWN) {
2540 if (ast_pbx_start(tmp)) {
2541 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2550 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2555 tpeer->trunkact = *tv;
2556 mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 + (tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000;
2557 if (mssincetx > 5000) {
2558 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2559 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2560 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2561 tpeer->lastsent = 999999;
2563 /* Update last transmit time now */
2564 tpeer->lasttxtime.tv_sec = tv->tv_sec;
2565 tpeer->lasttxtime.tv_usec = tv->tv_usec;
2567 /* Calculate ms offset */
2568 ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 + (tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000;
2569 /* Predict from last value */
2570 pred = tpeer->lastsent + sampms;
2571 if (abs(ms - pred) < 640)
2574 /* We never send the same timestamp twice, so fudge a little if we must */
2575 if (ms == tpeer->lastsent)
2576 ms = tpeer->lastsent + 1;
2577 tpeer->lastsent = ms;
2581 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2583 long ms; /* NOT unsigned */
2584 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2585 /* Initialize rxcore time if appropriate */
2586 gettimeofday(&iaxs[callno]->rxcore, NULL);
2587 /* Round to nearest 20ms */
2588 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2590 /* Calculate difference between trunk and channel */
2591 ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2592 (tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2593 /* Return as the sum of trunk time and the difference between trunk and real time */
2597 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2603 struct timeval *delivery = NULL;
2605 if (f->frametype == AST_FRAME_VOICE) {
2607 delivery = &f->delivery;
2608 } else if (f->frametype == AST_FRAME_IAX) {
2612 if (!p->offset.tv_sec && !p->offset.tv_usec) {
2613 gettimeofday(&p->offset, NULL);
2614 /* Round to nearest 20ms */
2615 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2617 /* If the timestamp is specified, just send it as is */
2620 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2621 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 + (delivery->tv_usec - p->offset.tv_usec) / 1000;
2623 gettimeofday(&tv, NULL);
2624 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2628 /* On a voice frame, use predicted values if appropriate */
2629 if (abs(ms - p->nextpred) <= 640) {
2631 p->nextpred = f->samples / 8;
2636 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinkign) if appropriate unless
2637 it's a genuine frame */
2639 if (ms <= p->lastsent)
2640 ms = p->lastsent + 3;
2641 } else if (abs(ms - p->lastsent) <= 640) {
2642 ms = p->lastsent + 3;
2648 p->nextpred = p->nextpred + f->samples / 8;
2650 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2655 #ifdef BRIDGE_OPTIMIZATION
2656 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2659 /* Receive from p1, send to p2 */
2661 /* Setup rxcore if necessary on outgoing channel */
2662 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2663 gettimeofday(&p1->rxcore, NULL);
2665 /* Setup txcore if necessary on outgoing channel */
2666 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2667 gettimeofday(&p2->offset, NULL);
2669 /* Now, ts is the timestamp of the original packet in the orignal context.
2670 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2671 Subtracting txcore of the outgoing channel gives us what we'd expect */
2673 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2675 if (fakets <= p2->lastsent)
2676 fakets = p2->lastsent + 1;
2677 p2->lastsent = fakets;
2682 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2684 /* Returns where in "receive time" we are */
2687 /* Setup rxcore if necessary */
2688 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2689 gettimeofday(&p->rxcore, NULL);
2691 gettimeofday(&tv, NULL);
2692 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2696 struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2698 struct iax2_trunk_peer *tpeer;
2699 /* Finds and locks trunk peer */
2700 ast_mutex_lock(&tpeerlock);
2703 /* We don't lock here because tpeer->addr *never* changes */
2704 if (!inaddrcmp(&tpeer->addr, sin)) {
2705 ast_mutex_lock(&tpeer->lock);
2708 tpeer = tpeer->next;
2711 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2713 memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2714 ast_mutex_init(&tpeer->lock);
2715 tpeer->lastsent = 9999;
2716 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2717 gettimeofday(&tpeer->trunkact, NULL);
2718 ast_mutex_lock(&tpeer->lock);
2719 tpeer->next = tpeers;
2721 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2724 ast_mutex_unlock(&tpeerlock);
2728 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2730 struct iax2_trunk_peer *tpeer;
2732 struct ast_iax2_meta_trunk_entry *met;
2733 tpeer = find_tpeer(&pvt->addr);
2735 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2736 /* Need to reallocate space */
2737 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2738 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2740 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2741 tpeer->trunkdata = tmp;
2742 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);
2744 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));
2745 ast_mutex_unlock(&tpeer->lock);
2749 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2750 ast_mutex_unlock(&tpeer->lock);
2755 /* Append to meta frame */
2756 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2757 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2758 /* Store call number and length in meta header */
2759 met->callno = htons(pvt->callno);
2760 met->len = htons(f->datalen);
2761 /* Advance pointers/decrease length past trunk entry header */
2762 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2763 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2764 /* Copy actual trunk data */
2765 memcpy(ptr, f->data, f->datalen);
2766 tpeer->trunkdatalen += f->datalen;
2767 if (!tpeer->firstcallno)
2768 tpeer->firstcallno = pvt->callno;
2770 ast_mutex_unlock(&tpeer->lock);
2775 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2777 /* Queue a packet for delivery on a given private structure. Use "ts" for
2778 timestamp, or calculate if ts is 0. Send immediately without retransmission
2779 or delayed, with retransmission */
2780 struct ast_iax2_full_hdr *fh;
2781 struct ast_iax2_mini_hdr *mh;
2782 struct ast_iax2_video_hdr *vh;
2784 struct iax_frame fr2;
2785 unsigned char buffer[4096];
2787 struct iax_frame *fr;
2790 unsigned int lastsent;
2794 ast_log(LOG_WARNING, "No private structure for packet?\n");
2798 lastsent = pvt->lastsent;
2800 /* Calculate actual timestamp */
2801 fts = calc_timestamp(pvt, ts, f);
2803 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2804 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2805 (f->frametype == AST_FRAME_VOICE)
2806 /* is a voice frame */ &&
2807 (f->subclass == pvt->svoiceformat)
2808 /* is the same type */ ) {
2809 /* Force immediate rather than delayed transmission */
2811 /* Mark that mini-style frame is appropriate */
2814 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2815 (f->frametype == AST_FRAME_VIDEO) &&
2816 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2820 /* Allocate an iax_frame */
2824 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2826 ast_log(LOG_WARNING, "Out of memory\n");
2829 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2830 iax_frame_wrap(fr, f);
2834 ast_log(LOG_WARNING, "timestamp is 0?\n");
2836 iax2_frame_free(fr);
2839 fr->callno = pvt->callno;
2840 fr->transfer = transfer;
2843 /* We need a full frame */
2847 fr->oseqno = pvt->oseqno++;
2848 fr->iseqno = pvt->iseqno;
2849 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2850 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2851 fh->ts = htonl(fr->ts);
2852 fh->oseqno = fr->oseqno;
2856 fh->iseqno = fr->iseqno;
2857 /* Keep track of the last thing we've acknowledged */
2859 pvt->aseqno = fr->iseqno;
2860 fh->type = fr->af.frametype & 0xFF;
2861 if (fr->af.frametype == AST_FRAME_VIDEO)
2862 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2864 fh->csub = compress_subclass(fr->af.subclass);
2866 fr->dcallno = pvt->transfercallno;
2868 fr->dcallno = pvt->peercallno;
2869 fh->dcallno = htons(fr->dcallno);
2870 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2873 /* Retry after 2x the ping time has passed */
2874 fr->retrytime = pvt->pingtime * 2;
2875 if (fr->retrytime < MIN_RETRY_TIME)
2876 fr->retrytime = MIN_RETRY_TIME;
2877 if (fr->retrytime > MAX_RETRY_TIME)
2878 fr->retrytime = MAX_RETRY_TIME;
2879 /* Acks' don't get retried */
2880 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2882 else if (f->frametype == AST_FRAME_VOICE)
2883 pvt->svoiceformat = f->subclass;
2884 else if (f->frametype == AST_FRAME_VIDEO)
2885 pvt->svideoformat = f->subclass & ~0x1;
2887 res = send_packet(fr);
2889 res = iax2_transmit(fr);
2892 iax2_trunk_queue(pvt, &fr->af);
2894 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2895 /* Video frame have no sequence number */
2898 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2900 vh->callno = htons(0x8000 | fr->callno);
2901 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2902 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2905 res = send_packet(fr);
2907 /* Mini-frames have no sequence number */
2910 /* Mini frame will do */
2911 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2912 mh->callno = htons(fr->callno);
2913 mh->ts = htons(fr->ts & 0xFFFF);
2914 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2917 res = send_packet(fr);
2925 static int iax2_show_users(int fd, int argc, char *argv[])
2927 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s\n"
2928 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s\n"
2929 struct iax2_user *user;
2932 return RESULT_SHOWUSAGE;
2933 ast_mutex_lock(&userl.lock);
2934 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2935 for(user=userl.users;user;user=user->next) {
2936 if (strlen(user->secret)) {
2937 strncpy(auth,user->secret,strlen(auth)-1);
2938 } else if (strlen(user->inkeys)) {
2939 sprintf(auth,"Key: %-15.15s ",user->inkeys);
2941 strcpy(auth,"-no secret-");
2942 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
2943 user->contexts ? user->contexts->context : context,
2944 user->ha ? "Yes" : "No");
2946 ast_mutex_unlock(&userl.lock);
2947 return RESULT_SUCCESS;
2952 static int iax2_show_peers(int fd, int argc, char *argv[])
2954 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2955 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2956 struct iax2_peer *peer;
2957 char name[256] = "";
2958 int registeredonly=0;
2959 if ((argc != 3) && (argc != 4))
2960 return RESULT_SHOWUSAGE;
2962 if (!strcasecmp(argv[3], "registered")) {
2965 return RESULT_SHOWUSAGE;
2967 ast_mutex_lock(&peerl.lock);
2968 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2969 for (peer = peerl.peers;peer;peer = peer->next) {
2972 if (registeredonly && !peer->addr.sin_addr.s_addr)
2974 if (strlen(peer->username))
2975 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2977 strncpy(name, peer->name, sizeof(name) - 1);
2979 if (peer->lastms < 0)
2980 strcpy(status, "UNREACHABLE");
2981 else if (peer->lastms > peer->maxms)
2982 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2983 else if (peer->lastms)
2984 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2986 strcpy(status, "UNKNOWN");
2988 strcpy(status, "Unmonitored");
2989 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2990 ast_cli(fd, FORMAT, name,
2991 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2992 peer->dynamic ? "(D)" : "(S)",
2994 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2996 ast_mutex_unlock(&peerl.lock);
2997 return RESULT_SUCCESS;
3002 static int iax2_show_firmware(int fd, int argc, char *argv[])
3004 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
3005 #define FORMAT "%-15.15s %-15d %-15d\n"
3006 struct iax_firmware *cur;
3007 if ((argc != 3) && (argc != 4))
3008 return RESULT_SHOWUSAGE;
3009 ast_mutex_lock(&waresl.lock);
3011 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
3012 for (cur = waresl.wares;cur;cur = cur->next) {
3013 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname)))
3014 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
3015 ntohl(cur->fwh->datalen));
3017 ast_mutex_unlock(&waresl.lock);
3018 return RESULT_SUCCESS;
3023 /* JDG: callback to display iax peers in manager */
3024 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
3026 char *a[] = { "iax2", "show", "users" };
3028 ret = iax2_show_peers( s->fd, 3, a );
3029 ast_cli( s->fd, "\r\n" );
3033 static char *regstate2str(int regstate)
3036 case REG_STATE_UNREGISTERED:
3037 return "Unregistered";
3038 case REG_STATE_REGSENT:
3039 return "Request Sent";
3040 case REG_STATE_AUTHSENT:
3041 return "Auth. Sent";
3042 case REG_STATE_REGISTERED:
3043 return "Registered";
3044 case REG_STATE_REJECTED:
3046 case REG_STATE_TIMEOUT:
3048 case REG_STATE_NOAUTH:
3049 return "No Authentication";
3055 static int iax2_show_registry(int fd, int argc, char *argv[])
3057 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
3058 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
3059 struct iax2_registry *reg;
3063 return RESULT_SHOWUSAGE;
3064 ast_mutex_lock(&peerl.lock);
3065 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
3066 for (reg = registrations;reg;reg = reg->next) {
3067 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3068 if (reg->us.sin_addr.s_addr)
3069 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
3071 strcpy(perceived, "<Unregistered>");
3072 ast_cli(fd, FORMAT, host,
3073 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
3075 ast_mutex_unlock(&peerl.lock);
3076 return RESULT_SUCCESS;
3081 static int iax2_show_channels(int fd, int argc, char *argv[])
3083 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
3084 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
3088 return RESULT_SHOWUSAGE;
3089 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
3090 for (x=0;x<IAX_MAX_CALLS;x++) {
3091 ast_mutex_lock(&iaxsl[x]);
3093 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
3094 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
3095 iaxs[x]->callno, iaxs[x]->peercallno,
3096 iaxs[x]->oseqno, iaxs[x]->iseqno,
3099 ast_getformatname(iaxs[x]->voiceformat) );
3102 ast_mutex_unlock(&iaxsl[x]);
3104 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3105 return RESULT_SUCCESS;
3110 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3113 return RESULT_SHOWUSAGE;
3115 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3116 return RESULT_SUCCESS;
3119 static int iax2_do_debug(int fd, int argc, char *argv[])
3122 return RESULT_SHOWUSAGE;
3124 ast_cli(fd, "IAX2 Debugging Enabled\n");
3125 return RESULT_SUCCESS;
3128 static int iax2_no_debug(int fd, int argc, char *argv[])
3131 return RESULT_SHOWUSAGE;
3133 ast_cli(fd, "IAX2 Debugging Disabled\n");
3134 return RESULT_SUCCESS;
3139 static char show_users_usage[] =
3140 "Usage: iax2 show users\n"
3141 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
3143 static char show_channels_usage[] =
3144 "Usage: iax2 show channels\n"
3145 " Lists all currently active IAX channels.\n";
3147 static char show_peers_usage[] =
3148 "Usage: iax2 show peers\n"
3149 " Lists all known IAX peers.\n";
3151 static char show_firmware_usage[] =
3152 "Usage: iax2 show firmware\n"
3153 " Lists all known IAX firmware images.\n";
3155 static char show_reg_usage[] =
3156 "Usage: iax2 show registry\n"
3157 " Lists all registration requests and status.\n";
3159 static char debug_usage[] =
3160 "Usage: iax2 debug\n"
3161 " Enables dumping of IAX packets for debugging purposes\n";
3163 static char no_debug_usage[] =
3164 "Usage: iax2 no debug\n"
3165 " Disables dumping of IAX packets for debugging purposes\n";
3167 static char debug_trunk_usage[] =
3168 "Usage: iax2 trunk debug\n"
3169 " Requests current status of IAX trunking\n";
3171 static struct ast_cli_entry cli_show_users =
3172 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
3173 static struct ast_cli_entry cli_show_firmware =
3174 { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
3175 static struct ast_cli_entry cli_show_channels =
3176 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
3177 static struct ast_cli_entry cli_show_peers =
3178 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3179 static struct ast_cli_entry cli_show_registry =
3180 { { "iax2", "show", "registry", NULL }, iax2_show_registry, "Show IAX registration status", show_reg_usage };
3181 static struct ast_cli_entry cli_debug =
3182 { { "iax2", "debug", NULL }, iax2_do_debug, "Enable IAX debugging", debug_usage };
3183 static struct ast_cli_entry cli_trunk_debug =
3184 { { "iax2", "trunk", "debug", NULL }, iax2_do_trunk_debug, "Request IAX trunk debug", debug_trunk_usage };
3185 static struct ast_cli_entry cli_no_debug =
3186 { { "iax2", "no", "debug", NULL }, iax2_no_debug, "Disable IAX debugging", no_debug_usage };
3188 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
3190 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
3192 ast_mutex_lock(&iaxsl[callno]);
3194 /* If there's an outstanding error, return failure now */
3195 if (!iaxs[callno]->error) {
3196 if (iaxs[callno]->alreadygone)
3198 /* Don't waste bandwidth sending null frames */
3199 else if (f->frametype == AST_FRAME_NULL)
3201 else if ((f->frametype == AST_FRAME_VOICE) && iaxs[callno]->quelch)
3203 else if (!(iaxs[callno]->state & IAX_STATE_STARTED))
3206 /* Simple, just queue for transmission */
3207 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
3209 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
3212 /* If it's already gone, just return */
3213 ast_mutex_unlock(&iaxsl[callno]);
3217 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno,
3218 int now, int transfer, int final)
3222 f.subclass = command;
3223 f.datalen = datalen;
3227 f.src = __FUNCTION__;
3229 return iax2_send(i, &f, ts, seqno, now, transfer, final);
3232 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3234 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
3237 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3240 ast_mutex_lock(&iaxsl[callno]);
3241 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
3242 ast_mutex_unlock(&iaxsl[callno]);
3246 #ifdef BRIDGE_OPTIMIZATION
3247 static int forward_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3249 return __send_command(iaxs[i->bridgecallno], type, command, ts, data, datalen, seqno, 0, 0, 0);
3253 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3255 /* It is assumed that the callno has already been locked */
3256 iax2_predestroy_nolock(i->callno);
3257 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
3260 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen, int seqno)
3262 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
3265 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, char *data, int datalen)
3267 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
3270 static int apply_context(struct iax2_context *con, char *context)
3273 if (!strcmp(con->context, context))
3281 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
3283 /* Start pessimistic */
3286 struct iax2_user *user, *best = NULL;
3288 int gotcapability=0;
3291 if (ies->called_number)
3292 strncpy(iaxs[callno]->exten, ies->called_number, sizeof(iaxs[callno]->exten) - 1);
3293 if (ies->calling_number) {
3294 if (ies->calling_name)
3295 snprintf(iaxs[callno]->callerid, sizeof(iaxs[callno]->callerid), "\"%s\" <%s>", ies->calling_name, ies->calling_number);
3297 strncpy(iaxs[callno]->callerid, ies->calling_number, sizeof(iaxs[callno]->callerid) - 1);
3298 } else if (ies->calling_name)
3299 strncpy(iaxs[callno]->callerid, ies->calling_name, sizeof(iaxs[callno]->callerid) - 1);
3300 if (ies->calling_ani)
3301 strncpy(iaxs[callno]->ani, ies->calling_ani, sizeof(iaxs[callno]->ani) - 1);
3303 strncpy(iaxs[callno]->dnid, ies->dnid, sizeof(iaxs[callno]->dnid)-1);
3304 if (ies->called_context)
3305 strncpy(iaxs[callno]->context, ies->called_context, sizeof(iaxs[callno]->context)-1);
3307 strncpy(iaxs[callno]->language, ies->language, sizeof(iaxs[callno]->language)-1);
3309 strncpy(iaxs[callno]->username, ies->username, sizeof(iaxs[callno]->username)-1);
3311 iaxs[callno]->peerformat = ies->format;
3313 iaxs[callno]->peeradsicpe = ies->adsicpe;
3314 if (ies->capability) {
3316 iaxs[callno]->peercapability = ies->capability;
3319 version = ies->version;
3321 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
3322 if (version > IAX_PROTO_VERSION) {
3323 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
3324 inet_ntoa(sin->sin_addr), version);
3327 ast_mutex_lock(&userl.lock);
3328 /* Search the userlist for a compatible entry, and fill in the rest */
3331 if ((!strlen(iaxs[callno]->username) || /* No username specified */
3332 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
3333 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
3334 && (!strlen(iaxs[callno]->context) || /* No context specified */
3335 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
3336 if (strlen(iaxs[callno]->username)) {
3337 /* Exact match, stop right now. */
3340 } else if (!strlen(user->secret)) {
3341 /* No required authentication */
3343 /* There was host authentication and we passed, bonus! */
3344 if (bestscore < 4) {
3349 /* No host access, but no secret, either, not bad */
3350 if (bestscore < 3) {
3357 /* Authentication, but host access too, eh, it's something.. */
3358 if (bestscore < 2) {
3363 /* Authentication and no host access... This is our baseline */
3364 if (bestscore < 1) {
3373 ast_mutex_unlock(&userl.lock);
3375 #ifdef MYSQL_FRIENDS
3376 if (!user && mysql && strlen(iaxs[callno]->username) && (strlen(iaxs[callno]->username) < 128)) {
3377 user = mysql_user(iaxs[callno]->username);
3378 if (user && strlen(iaxs[callno]->context) && /* No context specified */
3379 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
3381 free(user->contexts);
3388 /* We found our match (use the first) */
3390 /* Store the requested username if not specified */
3391 if (!strlen(iaxs[callno]->username))
3392 strncpy(iaxs[callno]->username, user->name, sizeof(iaxs[callno]->username)-1);
3393 /* Store whether this is a trunked call, too, of course, and move if appropriate */
3394 iaxs[callno]->trunk = user->trunk;
3395 iaxs[callno]->capability = user->capability;
3396 /* And use the default context */
3397 if (!strlen(iaxs[callno]->context)) {
3399 strncpy(iaxs[callno]->context, user->contexts->context, sizeof(iaxs[callno]->context)-1);
3401 strncpy(iaxs[callno]->context, context, sizeof(iaxs[callno]->context)-1);
3403 /* Copy the secret */
3404 strncpy(iaxs[callno]->secret, user->secret, sizeof(iaxs[callno]->secret)-1);
3405 /* And any input keys */
3406 strncpy(iaxs[callno]->inkeys, user->inkeys, sizeof(iaxs[callno]->inkeys));
3407 /* And the permitted authentication methods */
3408 iaxs[callno]->authmethods = user->authmethods;
3409 /* If they have callerid, override the given caller id. Always store the ANI */
3410 if (strlen(iaxs[callno]->callerid)) {
3411 if (user->hascallerid)
3412 strncpy(iaxs[callno]->callerid, user->callerid, sizeof(iaxs[callno]->callerid)-1);
3413 strncpy(iaxs[callno]->ani, user->callerid, sizeof(iaxs[callno]->ani)-1);
3415 if (strlen(user->accountcode))
3416 strncpy(iaxs[callno]->accountcode, user->accountcode, sizeof(iaxs[callno]->accountcode)-1);
3418 iaxs[callno]->amaflags = user->amaflags;
3419 iaxs[callno]->notransfer = user->notransfer;
3422 iaxs[callno]->trunk = iax2_getpeertrunk(*sin);
3426 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst)
3428 struct ast_iax2_full_hdr fh;
3429 fh.scallno = htons(src | IAX_FLAG_FULL);
3430 fh.dcallno = htons(dst);
3434 fh.type = AST_FRAME_IAX;
3435 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
3439 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
3440 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
3441 return sendto(netsocket, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
3444 static int authenticate_request(struct chan_iax2_pvt *p)
3446 struct iax_ie_data ied;
3447 memset(&ied, 0, sizeof(ied));
3448 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
3449 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
3450 snprintf(p->challenge, sizeof(p->challenge), "%d", rand());
3451 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
3453 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
3454 return send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
3457 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
3459 char requeststr[256] = "";
3460 char md5secret[256] = "";
3461 char secret[256] = "";
3462 char rsasecret[256] = "";
3466 if (!(p->state & IAX_STATE_AUTHENTICATED))
3469 strncpy(secret, ies->password, sizeof(secret) - 1);
3470 if (ies->md5_result)
3471 strncpy(md5secret, ies->md5_result, sizeof(md5secret)-1);
3472 if (ies->rsa_result)
3473 strncpy(rsasecret, ies->rsa_result, sizeof(rsasecret)-1);
3474 if ((p->authmethods & IAX_AUTH_RSA) && strlen(rsasecret) && strlen(p->inkeys)) {
3475 struct ast_key *key;
3479 strncpy(tmpkey, p->inkeys, sizeof(tmpkey));