2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003-2004, Digium, Inc.
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/features.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>
55 #include <sys/types.h>
58 #include <sys/ioctl.h>
60 #include <linux/zaptel.h>
63 #endif /* __linux__ */
66 #include "iax2-parser.h"
67 #include "iax2-provision.h"
68 #include "../astconf.h"
71 #define IPTOS_MINCOST 0x02
75 * Uncomment to try experimental IAX bridge optimization,
76 * designed to reduce latency when IAX calls cannot
80 #define BRIDGE_OPTIMIZATION
82 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
83 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
85 #define DEFAULT_RETRY_TIME 1000
86 #define MEMORY_SIZE 100
87 #define DEFAULT_DROP 3
88 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
89 but keeps the division between trunked and non-trunked better. */
90 #define TRUNK_CALL_START 0x4000
94 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
96 /* Sample over last 100 units to determine historic jitter */
99 static char *desc = "Inter Asterisk eXchange (Ver 2)";
100 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
101 static char *type = "IAX2";
103 static char context[80] = "default";
105 static char language[MAX_LANGUAGE] = "";
106 static char regcontext[AST_MAX_EXTENSION] = "";
108 static int max_retries = 4;
109 static int ping_time = 20;
110 static int lagrq_time = 10;
111 static int maxtrunkcall = TRUNK_CALL_START;
112 static int maxnontrunkcall = 1;
113 static int maxjitterbuffer=1000;
114 static int jittershrinkrate=2;
115 static int trunkfreq = 20;
116 static int authdebug = 1;
117 static int autokill = 0;
118 static int iaxcompat = 0;
120 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
122 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
124 static int netsocket = -1;
128 static int expirey = IAX_DEFAULT_REG_EXPIRE;
130 static int timingfd = -1; /* Timing file descriptor */
133 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
135 int (*iax2_regfunk)(char *username, int onoff) = NULL;
138 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
140 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
141 ~AST_FORMAT_SLINEAR & \
145 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
149 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
153 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
154 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
155 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
157 static struct io_context *io;
158 static struct sched_context *sched;
160 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
162 static int iax2_dropcount = DEFAULT_DROP;
164 static int globalusejitterbuf = 0;
166 static int iaxdebug = 0;
168 static int iaxtrunkdebug = 0;
170 static char accountcode[20];
171 static int amaflags = 0;
172 static int globalnotransfer = 0;
173 static int delayreject = 0;
174 static int globalmessagedetail = 0;
176 static pthread_t netthreadid = AST_PTHREADT_NULL;
178 #define IAX_STATE_STARTED (1 << 0)
179 #define IAX_STATE_AUTHENTICATED (1 << 1)
180 #define IAX_STATE_TBD (1 << 2)
182 struct iax2_context {
183 char context[AST_MAX_EXTENSION];
184 struct iax2_context *next;
192 char accountcode[20];
193 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
194 char language[MAX_LANGUAGE];
201 char cid_num[AST_MAX_EXTENSION];
202 char cid_name[AST_MAX_EXTENSION];
204 struct iax2_context *contexts;
205 struct iax2_user *next;
215 char outkey[80]; /* What key we use to talk to this peer */
216 char context[AST_MAX_EXTENSION]; /* For transfers only */
217 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
218 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
219 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
220 struct sockaddr_in addr;
224 /* Dynamic Registration fields */
225 int dynamic; /* If this is a dynamic peer */
226 struct sockaddr_in defaddr; /* Default address if there is one */
227 int authmethods; /* Authentication methods (IAX_AUTH_*) */
228 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
231 /* Suggested caller id if registering */
232 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
233 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
234 /* Whether or not to send ANI */
236 int expire; /* Schedule entry for expirey */
237 int expirey; /* How soon to expire */
238 int capability; /* Capability */
239 int delme; /* I need to be deleted */
240 int temponly; /* I'm only a temp */
241 int trunk; /* Treat as an IAX trunking */
242 int messagedetail; /* Show exact numbers? */
245 int callno; /* Call number of POKE request */
246 int pokeexpire; /* When to expire poke */
247 int lastms; /* How long last response took (in ms), or -1 for no response */
248 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
251 struct iax2_peer *next;
256 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
258 static struct iax2_trunk_peer {
260 struct sockaddr_in addr;
261 struct timeval txtrunktime; /* Transmit trunktime */
262 struct timeval rxtrunktime; /* Receive trunktime */
263 struct timeval lasttxtime; /* Last transmitted trunktime */
264 struct timeval trunkact; /* Last trunk activity */
265 unsigned int lastsent; /* Last sent time */
266 /* Trunk data and length */
267 unsigned char *trunkdata;
268 unsigned int trunkdatalen;
269 unsigned int trunkdataalloc;
270 struct iax2_trunk_peer *next;
275 AST_MUTEX_DEFINE_STATIC(tpeerlock);
277 struct iax_firmware {
278 struct iax_firmware *next;
282 struct ast_iax2_firmware_header *fwh;
286 #define REG_STATE_UNREGISTERED 0
287 #define REG_STATE_REGSENT 1
288 #define REG_STATE_AUTHSENT 2
289 #define REG_STATE_REGISTERED 3
290 #define REG_STATE_REJECTED 4
291 #define REG_STATE_TIMEOUT 5
292 #define REG_STATE_NOAUTH 6
294 #define TRANSFER_NONE 0
295 #define TRANSFER_BEGIN 1
296 #define TRANSFER_READY 2
297 #define TRANSFER_RELEASED 3
298 #define TRANSFER_PASSTHROUGH 4
300 struct iax2_registry {
301 struct sockaddr_in addr; /* Who we connect to for registration purposes */
303 char secret[80]; /* Password or key name in []'s */
305 int expire; /* Sched ID of expiration */
306 int refresh; /* How often to refresh */
308 int messages; /* Message count */
309 int callno; /* Associated call number if applicable */
310 struct sockaddr_in us; /* Who the server thinks we are */
311 struct iax2_registry *next;
314 static struct iax2_registry *registrations;
316 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
317 #define MIN_RETRY_TIME 100
318 #define MAX_RETRY_TIME 10000
320 #define MAX_JITTER_BUFFER 50
321 #define MIN_JITTER_BUFFER 10
323 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
324 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
326 #define MAX_TIMESTAMP_SKEW 640
328 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
329 #define TS_GAP_FOR_JB_RESYNC 5000
331 /* If we have more than this much excess real jitter buffer, shrink it. */
332 static int max_jitter_buffer = MAX_JITTER_BUFFER;
333 /* If we have less than this much excess real jitter buffer, enlarge it. */
334 static int min_jitter_buffer = MIN_JITTER_BUFFER;
336 struct chan_iax2_pvt {
337 /* Pipes for communication. pipe[1] belongs to the
338 network thread (write), and pipe[0] belongs to the individual
340 /* Whether or not we Quelch audio */
342 /* Last received voice format */
344 /* Last received voice format */
346 /* Last sent voice format */
348 /* Last sent video format */
350 /* What we are capable of sending */
352 /* Last received timestamp */
354 /* Last sent timestamp - never send the same timestamp twice in a single call */
355 unsigned int lastsent;
356 /* Next outgoing timestamp if everything is good */
357 unsigned int nextpred;
359 unsigned int pingtime;
360 /* Max time for initial response */
363 struct sockaddr_in addr;
364 /* Our call number */
365 unsigned short callno;
367 unsigned short peercallno;
368 /* Peer selected format */
370 /* Peer capability */
372 /* timeval that we base our transmission on */
373 struct timeval offset;
374 /* timeval that we base our delivery on */
375 struct timeval rxcore;
376 /* Historical delivery time */
377 int history[MEMORY_SIZE];
378 /* Current base jitterbuffer */
380 /* Current jitter measure */
382 /* Historic jitter value */
386 /* Error, as discovered by the manager */
388 /* Owner if we have one */
389 struct ast_channel *owner;
390 /* What's our state? */
392 /* Expirey (optional) */
394 /* Next outgoing sequence number */
395 unsigned char oseqno;
396 /* Next sequence number they have not yet acknowledged */
397 unsigned char rseqno;
398 /* Next incoming sequence number */
399 unsigned char iseqno;
400 /* Last incoming sequence number we have acknowledged */
401 unsigned char aseqno;
404 /* Default Context */
406 /* Caller ID if available */
409 /* Hidden Caller ID (i.e. ANI) if appropriate */
411 /* Whether or not ani should be transmitted in addition to Caller*ID */
413 /* Whether to request autoanswer */
417 /* Requested Extension */
418 char exten[AST_MAX_EXTENSION];
419 /* Expected Username */
421 /* Expected Secret */
423 /* permitted authentication methods */
427 /* Public keys permitted keys for incoming authentication */
429 /* Private key for outgoing authentication */
431 /* Preferred language */
432 char language[MAX_LANGUAGE];
433 /* Hostname/peername for naming purposes */
435 /* Associated registry */
436 struct iax2_registry *reg;
437 /* Associated peer for poking */
438 struct iax2_peer *peerpoke;
440 /* Transferring status */
442 /* Transfer identifier */
444 /* Already disconnected */
446 /* Who we are IAX transfering to */
447 struct sockaddr_in transfer;
448 /* What's the new call number for the transfer */
449 unsigned short transfercallno;
451 /* Status of knowledge of peer ADSI capability */
454 /* Who we are bridged to */
455 unsigned short bridgecallno;
456 unsigned int bridgesfmt;
457 struct ast_trans_pvt *bridgetrans;
459 /* If this is a provisioning request */
462 int pingid; /* Transmit PING request */
463 int lagid; /* Retransmit lag request */
464 int autoid; /* Auto hangup for Dialplan requestor */
465 int authid; /* Authentication rejection ID */
466 int authfail; /* Reason to report failure */
467 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
471 char dproot[AST_MAX_EXTENSION];
472 char accountcode[20];
474 /* This is part of a trunk interface */
476 struct iax2_dpcache *dpentries;
477 int notransfer; /* do we want native bridging */
478 int usejitterbuf; /* use jitter buffer on this channel? */
481 static struct ast_iax2_queue {
482 struct iax_frame *head;
483 struct iax_frame *tail;
488 static struct ast_user_list {
489 struct iax2_user *users;
493 static struct ast_peer_list {
494 struct iax2_peer *peers;
498 static struct ast_firmware_list {
499 struct iax_firmware *wares;
503 /* Extension exists */
504 #define CACHE_FLAG_EXISTS (1 << 0)
505 /* Extension is non-existant */
506 #define CACHE_FLAG_NONEXISTANT (1 << 1)
507 /* Extension can exist */
508 #define CACHE_FLAG_CANEXIST (1 << 2)
509 /* Waiting to hear back response */
510 #define CACHE_FLAG_PENDING (1 << 3)
512 #define CACHE_FLAG_TIMEOUT (1 << 4)
513 /* Request transmitted */
514 #define CACHE_FLAG_TRANSMITTED (1 << 5)
516 #define CACHE_FLAG_UNKNOWN (1 << 6)
518 #define CACHE_FLAG_MATCHMORE (1 << 7)
520 static struct iax2_dpcache {
521 char peercontext[AST_MAX_EXTENSION];
522 char exten[AST_MAX_EXTENSION];
524 struct timeval expirey;
526 unsigned short callno;
528 struct iax2_dpcache *next;
529 struct iax2_dpcache *peer; /* For linking in peers */
532 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
534 static void iax_debug_output(const char *data)
540 static void iax_error_output(const char *data)
542 ast_log(LOG_WARNING, data);
545 /* XXX We probably should use a mutex when working with this XXX */
546 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
547 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
548 static struct timeval lastused[IAX_MAX_CALLS];
551 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
552 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
553 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
554 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
555 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
557 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f);
559 static int send_ping(void *data)
561 int callno = (long)data;
562 /* Ping only if it's real, not if it's bridged */
564 #ifdef BRIDGE_OPTIMIZATION
565 if (!iaxs[callno]->bridgecallno)
567 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
573 static int send_lagrq(void *data)
575 int callno = (long)data;
576 /* Ping only if it's real not if it's bridged */
578 #ifdef BRIDGE_OPTIMIZATION
579 if (!iaxs[callno]->bridgecallno)
581 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
587 static unsigned char compress_subclass(int subclass)
591 /* If it's 128 or smaller, just return it */
592 if (subclass < IAX_FLAG_SC_LOG)
594 /* Otherwise find its power */
595 for (x = 0; x < IAX_MAX_SHIFT; x++) {
596 if (subclass & (1 << x)) {
598 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
604 return power | IAX_FLAG_SC_LOG;
607 static int uncompress_subclass(unsigned char csub)
609 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
610 if (csub & IAX_FLAG_SC_LOG) {
611 /* special case for 'compressed' -1 */
615 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
621 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
623 struct iax2_peer *peer;
626 ast_mutex_lock(&peerl.lock);
629 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
630 (peer->addr.sin_port == sin.sin_port)) {
631 strncpy(host, peer->name, len-1);
638 ast_mutex_unlock(&peerl.lock);
642 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
644 struct chan_iax2_pvt *tmp;
645 char iabuf[INET_ADDRSTRLEN];
646 tmp = malloc(sizeof(struct chan_iax2_pvt));
648 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
651 tmp->transfercallno = 0;
652 tmp->bridgecallno = 0;
658 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
659 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
660 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
661 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
666 static int get_samples(struct ast_frame *f)
669 switch(f->subclass) {
670 case AST_FORMAT_SPEEX:
671 samples = 160; /* XXX Not necessarily true XXX */
673 case AST_FORMAT_G723_1:
674 samples = 240 /* XXX Not necessarily true XXX */;
676 case AST_FORMAT_ILBC:
677 samples = 240 * (f->datalen / 50);
680 samples = 160 * (f->datalen / 33);
682 case AST_FORMAT_G729A:
683 samples = 160 * (f->datalen / 20);
685 case AST_FORMAT_SLINEAR:
686 samples = f->datalen / 2;
688 case AST_FORMAT_LPC10:
690 samples += (((char *)(f->data))[7] & 0x1) * 8;
692 case AST_FORMAT_ULAW:
693 samples = f->datalen;
695 case AST_FORMAT_ALAW:
696 samples = f->datalen;
698 case AST_FORMAT_ADPCM:
699 case AST_FORMAT_G726:
700 samples = f->datalen *2;
703 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
708 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
710 /* Malloc() a copy of a frame */
711 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
713 memcpy(new, fr, sizeof(struct iax_frame));
714 iax_frame_wrap(new, &fr->af);
717 new->direction = DIRECTION_INGRESS;
723 #define NEW_PREVENT 0
727 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
729 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
730 (cur->addr.sin_port == sin->sin_port)) {
731 /* This is the main host */
732 if ((cur->peercallno == callno) ||
733 ((dcallno == cur->callno) && !cur->peercallno)) {
734 /* That's us. Be sure we keep track of the peer call number */
738 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
739 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
740 /* We're transferring */
741 if (dcallno == cur->callno)
747 static void update_max_trunk(void)
749 int max = TRUNK_CALL_START;
751 /* XXX Prolly don't need locks here XXX */
752 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
758 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
761 static void update_max_nontrunk(void)
765 /* XXX Prolly don't need locks here XXX */
766 for (x=1;x<TRUNK_CALL_START - 1; x++) {
770 maxnontrunkcall = max;
772 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
775 static int make_trunk(unsigned short callno, int locked)
780 if (iaxs[callno]->oseqno) {
781 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
784 if (callno & TRUNK_CALL_START) {
785 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
788 gettimeofday(&now, NULL);
789 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
790 ast_mutex_lock(&iaxsl[x]);
791 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
792 iaxs[x] = iaxs[callno];
795 /* Update the two timers that should have been started */
796 if (iaxs[x]->pingid > -1)
797 ast_sched_del(sched, iaxs[x]->pingid);
798 if (iaxs[x]->lagid > -1)
799 ast_sched_del(sched, iaxs[x]->lagid);
800 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
801 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
803 ast_mutex_unlock(&iaxsl[callno]);
806 ast_mutex_unlock(&iaxsl[x]);
809 ast_mutex_unlock(&iaxsl[x]);
811 if (x >= IAX_MAX_CALLS - 1) {
812 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
815 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
816 /* We move this call from a non-trunked to a trunked call */
818 update_max_nontrunk();
822 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
827 if (new <= NEW_ALLOW) {
828 /* Look for an existing connection first */
829 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
830 ast_mutex_lock(&iaxsl[x]);
832 /* Look for an exact match */
833 if (match(sin, callno, dcallno, iaxs[x])) {
837 ast_mutex_unlock(&iaxsl[x]);
839 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
840 ast_mutex_lock(&iaxsl[x]);
842 /* Look for an exact match */
843 if (match(sin, callno, dcallno, iaxs[x])) {
847 ast_mutex_unlock(&iaxsl[x]);
850 if ((res < 1) && (new >= NEW_ALLOW)) {
851 gettimeofday(&now, NULL);
852 for (x=1;x<TRUNK_CALL_START;x++) {
853 /* Find first unused call number that hasn't been used in a while */
854 ast_mutex_lock(&iaxsl[x]);
855 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
856 ast_mutex_unlock(&iaxsl[x]);
858 /* We've still got lock held if we found a spot */
859 if (x >= TRUNK_CALL_START) {
860 ast_log(LOG_WARNING, "No more space\n");
863 iaxs[x] = new_iax(sin, lockpeer);
864 update_max_nontrunk();
867 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
868 iaxs[x]->addr.sin_port = sin->sin_port;
869 iaxs[x]->addr.sin_family = sin->sin_family;
870 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
871 iaxs[x]->peercallno = callno;
873 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
874 iaxs[x]->expirey = expirey;
875 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
876 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
877 iaxs[x]->amaflags = amaflags;
878 iaxs[x]->notransfer = globalnotransfer;
879 iaxs[x]->usejitterbuf = globalusejitterbuf;
880 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
882 ast_log(LOG_WARNING, "Out of resources\n");
883 ast_mutex_unlock(&iaxsl[x]);
886 ast_mutex_unlock(&iaxsl[x]);
892 static void iax2_frame_free(struct iax_frame *fr)
894 if (fr->retrans > -1)
895 ast_sched_del(sched, fr->retrans);
899 static int iax2_queue_frame(int callno, struct ast_frame *f)
901 /* Assumes lock for callno is already held... */
903 if (iaxs[callno] && iaxs[callno]->owner) {
904 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
905 /* Avoid deadlock by pausing and trying again */
906 ast_mutex_unlock(&iaxsl[callno]);
908 ast_mutex_lock(&iaxsl[callno]);
910 ast_queue_frame(iaxs[callno]->owner, f);
911 ast_mutex_unlock(&iaxs[callno]->owner->lock);
920 static void destroy_firmware(struct iax_firmware *cur)
924 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
930 static int try_firmware(char *s)
933 struct iax_firmware *cur;
938 struct ast_iax2_firmware_header *fwh, fwh2;
939 struct MD5Context md5;
940 unsigned char sum[16];
941 unsigned char buf[1024];
945 s2 = alloca(strlen(s) + 100);
947 ast_log(LOG_WARNING, "Alloca failed!\n");
950 last = strrchr(s, '/');
955 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
956 res = stat(s, &stbuf);
958 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
961 /* Make sure it's not a directory */
962 if (S_ISDIR(stbuf.st_mode))
964 ifd = open(s, O_RDONLY);
966 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
969 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
971 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
975 /* Unlink our newly created file */
978 /* Now copy the firmware into it */
982 if (chunk > sizeof(buf))
984 res = read(ifd, buf, chunk);
986 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
991 res = write(fd, buf, chunk);
993 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1001 /* Return to the beginning */
1002 lseek(fd, 0, SEEK_SET);
1003 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1004 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1008 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1009 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1013 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1014 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1018 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1019 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1023 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1025 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1030 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1031 MD5Final(sum, &md5);
1032 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1033 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1034 munmap(fwh, stbuf.st_size);
1040 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1041 /* Found a candidate */
1042 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1043 /* The version we have on loaded is older, load this one instead */
1045 /* This version is no newer than what we have. Don't worry about it.
1046 We'll consider it a proper load anyhow though */
1047 munmap(fwh, stbuf.st_size);
1054 /* Allocate a new one and link it */
1055 cur = malloc(sizeof(struct iax_firmware));
1057 memset(cur, 0, sizeof(struct iax_firmware));
1059 cur->next = waresl.wares;
1065 munmap(cur->fwh, cur->mmaplen);
1071 cur->mmaplen = stbuf.st_size;
1077 static int iax_check_version(char *dev)
1080 struct iax_firmware *cur;
1081 if (dev && !ast_strlen_zero(dev)) {
1082 ast_mutex_lock(&waresl.lock);
1085 if (!strcmp(dev, cur->fwh->devname)) {
1086 res = ntohs(cur->fwh->version);
1091 ast_mutex_unlock(&waresl.lock);
1096 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1099 unsigned int bs = desc & 0xff;
1100 unsigned int start = (desc >> 8) & 0xffffff;
1102 struct iax_firmware *cur;
1103 if (dev && !ast_strlen_zero(dev) && bs) {
1105 ast_mutex_lock(&waresl.lock);
1108 if (!strcmp(dev, cur->fwh->devname)) {
1109 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1110 if (start < ntohl(cur->fwh->datalen)) {
1111 bytes = ntohl(cur->fwh->datalen) - start;
1114 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1117 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1127 ast_mutex_unlock(&waresl.lock);
1133 static void reload_firmware(void)
1135 struct iax_firmware *cur, *curl, *curp;
1140 /* Mark all as dead */
1141 ast_mutex_lock(&waresl.lock);
1147 /* Now that we've freed them, load the new ones */
1148 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1151 while((de = readdir(fwd))) {
1152 if (de->d_name[0] != '.') {
1153 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1154 if (!try_firmware(fn)) {
1155 if (option_verbose > 1)
1156 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1162 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1164 /* Clean up leftovers */
1176 destroy_firmware(curl);
1181 ast_mutex_unlock(&waresl.lock);
1184 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1186 static int __do_deliver(void *data)
1188 /* Just deliver the packet by using queueing. This is called by
1189 the IAX thread with the iaxsl lock held. */
1190 struct iax_frame *fr = data;
1192 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone)
1193 iax2_queue_frame(fr->callno, &fr->af);
1194 /* Free our iax frame */
1195 iax2_frame_free(fr);
1196 /* And don't run again */
1200 static int do_deliver(void *data)
1202 /* Locking version of __do_deliver */
1203 struct iax_frame *fr = data;
1204 int callno = fr->callno;
1206 ast_mutex_lock(&iaxsl[callno]);
1207 res = __do_deliver(data);
1208 ast_mutex_unlock(&iaxsl[callno]);
1212 static int handle_error(void)
1214 /* XXX Ideally we should figure out why an error occured and then abort those
1215 rather than continuing to try. Unfortunately, the published interface does
1216 not seem to work XXX */
1218 struct sockaddr_in *sin;
1221 struct sock_extended_err e;
1226 m.msg_controllen = sizeof(e);
1228 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1230 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1232 if (m.msg_controllen) {
1233 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1235 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1237 ast_log(LOG_WARNING, "No address detected??\n");
1239 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1246 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin)
1249 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)sin,
1253 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1260 static int send_packet(struct iax_frame *f)
1263 char iabuf[INET_ADDRSTRLEN];
1264 /* Called with iaxsl held */
1266 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1267 /* Don't send if there was an error, but return error instead */
1269 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1272 if (!iaxs[f->callno])
1274 if (iaxs[f->callno]->error)
1278 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1279 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1280 sizeof(iaxs[f->callno]->transfer));
1283 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1284 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1285 sizeof(iaxs[f->callno]->addr));
1289 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1297 static int iax2_predestroy(int callno)
1299 struct ast_channel *c;
1300 struct chan_iax2_pvt *pvt;
1301 ast_mutex_lock(&iaxsl[callno]);
1304 ast_mutex_unlock(&iaxsl[callno]);
1307 if (!pvt->alreadygone) {
1308 /* No more pings or lagrq's */
1309 if (pvt->pingid > -1)
1310 ast_sched_del(sched, pvt->pingid);
1311 if (pvt->lagid > -1)
1312 ast_sched_del(sched, pvt->lagid);
1313 if (pvt->autoid > -1)
1314 ast_sched_del(sched, pvt->autoid);
1315 if (pvt->authid > -1)
1316 ast_sched_del(sched, pvt->authid);
1317 if (pvt->initid > -1)
1318 ast_sched_del(sched, pvt->initid);
1324 pvt->alreadygone = 1;
1328 c->_softhangup |= AST_SOFTHANGUP_DEV;
1330 ast_queue_hangup(c);
1332 ast_mutex_lock(&usecnt_lock);
1335 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1336 ast_mutex_unlock(&usecnt_lock);
1338 ast_mutex_unlock(&iaxsl[callno]);
1339 ast_update_use_count();
1343 static int iax2_predestroy_nolock(int callno)
1346 ast_mutex_unlock(&iaxsl[callno]);
1347 res = iax2_predestroy(callno);
1348 ast_mutex_lock(&iaxsl[callno]);
1352 static void iax2_destroy(int callno)
1354 struct chan_iax2_pvt *pvt;
1355 struct iax_frame *cur;
1356 struct ast_channel *owner;
1359 ast_mutex_lock(&iaxsl[callno]);
1361 gettimeofday(&lastused[callno], NULL);
1368 if (ast_mutex_trylock(&owner->lock)) {
1369 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1370 ast_mutex_unlock(&iaxsl[callno]);
1376 iaxs[callno] = NULL;
1380 /* No more pings or lagrq's */
1381 if (pvt->pingid > -1)
1382 ast_sched_del(sched, pvt->pingid);
1383 if (pvt->lagid > -1)
1384 ast_sched_del(sched, pvt->lagid);
1385 if (pvt->autoid > -1)
1386 ast_sched_del(sched, pvt->autoid);
1387 if (pvt->authid > -1)
1388 ast_sched_del(sched, pvt->authid);
1389 if (pvt->initid > -1)
1390 ast_sched_del(sched, pvt->initid);
1396 if (pvt->bridgetrans)
1397 ast_translator_free_path(pvt->bridgetrans);
1398 pvt->bridgetrans = NULL;
1401 pvt->alreadygone = 1;
1404 /* If there's an owner, prod it to give up */
1405 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1406 ast_queue_hangup(owner);
1409 for (cur = iaxq.head; cur ; cur = cur->next) {
1410 /* Cancel any pending transmissions */
1411 if (cur->callno == pvt->callno)
1415 pvt->reg->callno = 0;
1421 ast_mutex_unlock(&owner->lock);
1423 ast_mutex_unlock(&iaxsl[callno]);
1424 if (callno & 0x4000)
1427 static void iax2_destroy_nolock(int callno)
1429 /* Actually it's easier to unlock, kill it, and relock */
1430 ast_mutex_unlock(&iaxsl[callno]);
1431 iax2_destroy(callno);
1432 ast_mutex_lock(&iaxsl[callno]);
1435 static int update_packet(struct iax_frame *f)
1437 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1438 struct ast_iax2_full_hdr *fh = f->data;
1439 /* Mark this as a retransmission */
1440 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1442 f->iseqno = iaxs[f->callno]->iseqno;
1443 fh->iseqno = f->iseqno;
1447 static int attempt_transmit(void *data)
1449 /* Attempt to transmit the frame to the remote peer...
1450 Called without iaxsl held. */
1451 struct iax_frame *f = data;
1453 int callno = f->callno;
1454 char iabuf[INET_ADDRSTRLEN];
1455 /* Make sure this call is still active */
1457 ast_mutex_lock(&iaxsl[callno]);
1458 if ((f->callno) && iaxs[f->callno]) {
1459 if ((f->retries < 0) /* Already ACK'd */ ||
1460 (f->retries >= max_retries) /* Too many attempts */) {
1461 /* Record an error if we've transmitted too many times */
1462 if (f->retries >= max_retries) {
1464 /* Transfer timeout */
1465 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1466 } else if (f->final) {
1468 iax2_destroy_nolock(f->callno);
1470 if (iaxs[f->callno]->owner)
1471 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1472 iaxs[f->callno]->error = ETIMEDOUT;
1473 if (iaxs[f->callno]->owner) {
1474 struct ast_frame fr = { 0, };
1476 fr.frametype = AST_FRAME_CONTROL;
1477 fr.subclass = AST_CONTROL_HANGUP;
1478 iax2_queue_frame(f->callno, &fr);
1480 if (iaxs[f->callno]->reg) {
1481 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1482 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1483 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1485 iax2_destroy_nolock(f->callno);
1492 /* Update it if it needs it */
1494 /* Attempt transmission */
1497 /* Try again later after 10 times as long */
1499 if (f->retrytime > MAX_RETRY_TIME)
1500 f->retrytime = MAX_RETRY_TIME;
1501 /* Transfer messages max out at one second */
1502 if (f->transfer && (f->retrytime > 1000))
1503 f->retrytime = 1000;
1504 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1507 /* Make sure it gets freed */
1512 ast_mutex_unlock(&iaxsl[callno]);
1513 /* Do not try again */
1515 /* Don't attempt delivery, just remove it from the queue */
1516 ast_mutex_lock(&iaxq.lock);
1518 f->prev->next = f->next;
1520 iaxq.head = f->next;
1522 f->next->prev = f->prev;
1524 iaxq.tail = f->prev;
1526 ast_mutex_unlock(&iaxq.lock);
1528 /* Free the IAX frame */
1534 static int iax2_set_jitter(int fd, int argc, char *argv[])
1536 if ((argc != 4) && (argc != 5))
1537 return RESULT_SHOWUSAGE;
1539 max_jitter_buffer = atoi(argv[3]);
1540 if (max_jitter_buffer < 0)
1541 max_jitter_buffer = 0;
1544 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1545 if (iaxs[atoi(argv[3])]) {
1546 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1547 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1548 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1550 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1552 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1555 return RESULT_SUCCESS;
1558 static char jitter_usage[] =
1559 "Usage: iax set jitter [callid] <value>\n"
1560 " If used with a callid, it sets the jitter buffer to the given static\n"
1561 "value (until its next calculation). If used without a callid, the value is used\n"
1562 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1563 "buffer size is reduced.";
1565 static int iax2_show_stats(int fd, int argc, char *argv[])
1567 struct iax_frame *cur;
1568 int cnt = 0, dead=0, final=0;
1570 return RESULT_SHOWUSAGE;
1571 for (cur = iaxq.head; cur ; cur = cur->next) {
1572 if (cur->retries < 0)
1578 ast_cli(fd, " IAX Statistics\n");
1579 ast_cli(fd, "---------------------\n");
1580 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1581 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1582 return RESULT_SUCCESS;
1585 static int iax2_show_cache(int fd, int argc, char *argv[])
1587 struct iax2_dpcache *dp;
1588 char tmp[1024] = "", *pc;
1592 gettimeofday(&tv, NULL);
1593 ast_mutex_lock(&dpcache_lock);
1595 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1597 s = dp->expirey.tv_sec - tv.tv_sec;
1599 if (dp->flags & CACHE_FLAG_EXISTS)
1600 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1601 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1602 strncat(tmp, "NONEXISTANT|", sizeof(tmp) - strlen(tmp) - 1);
1603 if (dp->flags & CACHE_FLAG_CANEXIST)
1604 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1605 if (dp->flags & CACHE_FLAG_PENDING)
1606 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1607 if (dp->flags & CACHE_FLAG_TIMEOUT)
1608 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1609 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1610 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1611 if (dp->flags & CACHE_FLAG_MATCHMORE)
1612 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1613 if (dp->flags & CACHE_FLAG_UNKNOWN)
1614 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1615 /* Trim trailing pipe */
1616 if (!ast_strlen_zero(tmp))
1617 tmp[strlen(tmp) - 1] = '\0';
1619 strncpy(tmp, "(none)", sizeof(tmp) - 1);
1621 pc = strchr(dp->peercontext, '@');
1623 pc = dp->peercontext;
1626 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1627 if (dp->waiters[x] > -1)
1630 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1632 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1635 ast_mutex_unlock(&dpcache_lock);
1636 return RESULT_SUCCESS;
1639 static char show_stats_usage[] =
1640 "Usage: iax show stats\n"
1641 " Display statistics on IAX channel driver.\n";
1644 static char show_cache_usage[] =
1645 "Usage: iax show cache\n"
1646 " Display currently cached IAX Dialplan results.\n";
1648 static struct ast_cli_entry cli_set_jitter =
1649 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1651 static struct ast_cli_entry cli_show_stats =
1652 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1654 static struct ast_cli_entry cli_show_cache =
1655 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1658 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1660 #ifdef BRIDGE_OPTIMIZATION
1661 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1663 static int forward_delivery(struct iax_frame *fr)
1665 struct chan_iax2_pvt *p1, *p2;
1666 char iabuf[INET_ADDRSTRLEN];
1669 p1 = iaxs[fr->callno];
1670 p2 = iaxs[p1->bridgecallno];
1677 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
1679 p1->callno, p1->peercallno,
1680 p2->callno, p2->peercallno,
1681 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
1682 ntohs(p2->addr.sin_port));
1684 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
1685 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
1686 send full frame on timestamp wrap when doing optimized bridging
1687 (actually current code STILL doesn't)
1689 if (fr->ts + 50000 <= p1->last) {
1690 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1692 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
1695 /* Send with timestamp adjusted to the origin of the outbound leg */
1696 /* But don't destroy inbound timestamp still needed later to set "last" */
1698 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1699 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1705 static void unwrap_timestamp(struct iax_frame *fr)
1709 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
1710 x = fr->ts - iaxs[fr->callno]->last;
1712 /* Sudden big jump backwards in timestamp:
1713 What likely happened here is that miniframe timestamp has circled but we haven't
1714 gotten the update from the main packet. We'll just pretend that we did, and
1715 update the timestamp appropriately. */
1716 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
1718 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
1721 /* Sudden apparent big jump forwards in timestamp:
1722 What's likely happened is this is an old miniframe belonging to the previous
1723 top-16-bit timestamp that has turned up out of order.
1724 Adjust the timestamp appropriately. */
1725 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
1727 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
1732 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
1736 unsigned int orig_ts;
1737 int drops[MEMORY_SIZE];
1738 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
1740 /* Remember current jitterbuffer so we can log any change */
1741 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
1742 /* Similarly for the frame timestamp */
1747 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
1748 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
1751 /* Attempt to recover wrapped timestamps */
1752 unwrap_timestamp(fr);
1754 if (updatehistory) {
1756 /* Attempt to spot a change of timebase on timestamps coming from the other side
1757 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
1758 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
1759 for a while - in this case this code might also resync us. But that's not a bad thing.
1760 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
1761 [that's why we only do this when updatehistory is true]
1763 x = fr->ts - iaxs[fr->callno]->last;
1764 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
1766 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
1767 fr->callno, fr->ts, iaxs[fr->callno]->last);
1768 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
1769 iaxs[fr->callno]->rxcore.tv_sec = 0;
1770 iaxs[fr->callno]->rxcore.tv_usec = 0;
1771 /* wipe "last" if stamps have jumped backwards */
1773 iaxs[fr->callno]->last = 0;
1774 /* should we also empty history? */
1777 /* ms is a measure of the "lateness" of the frame relative to the "reference"
1778 frame we received. (initially the very first, but also see code just above here).
1779 Understand that "ms" can easily be -ve if lag improves since the reference frame.
1780 Called by IAX thread, with iaxsl lock held. */
1781 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
1783 /* Rotate our history queue of "lateness". Don't worry about those initial
1784 zeros because the first entry will always be zero */
1785 for (x=0;x<MEMORY_SIZE - 1;x++)
1786 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1787 /* Add a history entry for this one */
1788 iaxs[fr->callno]->history[x] = ms;
1794 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
1795 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
1796 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1797 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1798 fr->af.delivery.tv_sec += fr->ts / 1000;
1799 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1800 if (fr->af.delivery.tv_usec >= 1000000) {
1801 fr->af.delivery.tv_usec -= 1000000;
1802 fr->af.delivery.tv_sec += 1;
1808 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
1810 fr->af.delivery.tv_sec = 0;
1811 fr->af.delivery.tv_usec = 0;
1814 /* Initialize the minimum to reasonable values. It's too much
1815 work to do the same for the maximum, repeatedly */
1816 min=iaxs[fr->callno]->history[0];
1817 for (z=0;z < iax2_dropcount + 1;z++) {
1818 /* Start very optimistic ;-) */
1820 for (x=0;x<MEMORY_SIZE;x++) {
1821 if (max < iaxs[fr->callno]->history[x]) {
1822 /* We have a candidate new maximum value. Make
1823 sure it's not in our drop list */
1825 for (y=0;!match && (y<z);y++)
1826 match |= (drops[y] == x);
1828 /* It's not in our list, use it as the new maximum */
1829 max = iaxs[fr->callno]->history[x];
1835 /* On our first pass, find the minimum too */
1836 if (min > iaxs[fr->callno]->history[x])
1837 min = iaxs[fr->callno]->history[x];
1844 /* Just for reference, keep the "jitter" value, the difference between the
1845 earliest and the latest. */
1847 iaxs[fr->callno]->jitter = max - min;
1849 /* IIR filter for keeping track of historic jitter, but always increase
1850 historic jitter immediately for increase */
1852 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1853 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1855 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1856 iaxs[fr->callno]->historicjitter;
1858 /* If our jitter buffer is too big (by a significant margin), then we slowly
1859 shrink it to avoid letting the change be perceived */
1860 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1861 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
1863 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
1864 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
1865 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
1866 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
1867 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
1868 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
1870 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1871 buffer immediately to accomodate it (and a little more). */
1872 if (max > iaxs[fr->callno]->jitterbuffer)
1873 iaxs[fr->callno]->jitterbuffer = max
1874 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1876 /* If the caller just wanted us to update, return now */
1880 /* Subtract the lateness from our jitter buffer to know how long to wait
1881 before sending our packet. */
1882 delay = iaxs[fr->callno]->jitterbuffer - ms;
1884 /* Whatever happens, no frame waits longer than maxjitterbuffer */
1885 if (delay > maxjitterbuffer)
1886 delay = maxjitterbuffer;
1888 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
1889 /* If frame came from trunk, also don't do any delay */
1890 if ( (!iaxs[fr->callno]->usejitterbuf) || fromtrunk )
1894 /* Log jitter stats for possible offline analysis */
1895 ast_log(LOG_DEBUG, "Jitter: call=%d ts=%d orig=%d last=%d %s: min=%d max=%d jb=%d %+d lateness=%d jbdelay=%d jitter=%d historic=%d\n",
1896 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
1897 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
1898 min, max, iaxs[fr->callno]->jitterbuffer,
1899 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
1901 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
1905 /* Don't deliver it more than 4 ms late */
1906 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1908 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
1912 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
1913 /* Free our iax frame */
1914 iax2_frame_free(fr);
1918 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
1919 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
1924 static int iax2_transmit(struct iax_frame *fr)
1926 /* Lock the queue and place this packet at the end */
1929 /* By setting this to 0, the network thread will send it for us, and
1930 queue retransmission if necessary */
1932 ast_mutex_lock(&iaxq.lock);
1939 iaxq.tail->next = fr;
1940 fr->prev = iaxq.tail;
1944 ast_mutex_unlock(&iaxq.lock);
1945 /* Wake up the network thread */
1946 pthread_kill(netthreadid, SIGURG);
1952 static int iax2_digit(struct ast_channel *c, char digit)
1954 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1957 static int iax2_sendtext(struct ast_channel *c, char *text)
1960 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1961 0, 0, text, strlen(text) + 1, -1);
1964 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1966 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1969 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1971 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1974 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1976 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1977 ast_mutex_lock(&iaxsl[callno]);
1979 iaxs[callno]->owner = newchan;
1981 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1982 ast_mutex_unlock(&iaxsl[callno]);
1986 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
1987 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
1989 static void destroy_user(struct iax2_user *user);
1990 static void destroy_peer(struct iax2_peer *peer);
1992 static struct iax2_peer *realtime_peer(const char *peername)
1994 struct ast_variable *var;
1995 struct ast_variable *tmp;
1996 struct iax2_peer *peer=NULL;
1997 time_t regseconds, nowtime;
1999 var = ast_load_realtime("iaxfriends", "name", peername, NULL);
2001 /* Make sure it's not a user only... */
2002 peer = build_peer(peername, var, 1);
2004 /* Add some finishing touches, addresses, etc */
2008 if (!strcasecmp(tmp->name, "type")) {
2009 if (strcasecmp(tmp->value, "friend") &&
2010 strcasecmp(tmp->value, "peer")) {
2011 /* Whoops, we weren't supposed to exist! */
2016 } else if (!strcasecmp(tmp->name, "regseconds")) {
2017 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2019 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2020 inet_aton(tmp->value, &(peer->addr.sin_addr));
2021 } else if (!strcasecmp(tmp->name, "port")) {
2022 peer->addr.sin_port = htons(atoi(tmp->value));
2023 } else if (!strcasecmp(tmp->name, "host")) {
2024 if (!strcasecmp(tmp->value, "dynamic"))
2029 if (peer && dynamic) {
2031 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2032 memset(&peer->addr, 0, sizeof(peer->addr));
2034 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2038 ast_destroy_realtime(var);
2043 static struct iax2_user *realtime_user(const char *username)
2045 struct ast_variable *var;
2046 struct ast_variable *tmp;
2047 struct iax2_user *user=NULL;
2048 var = ast_load_realtime("iaxfriends", "name", username, NULL);
2050 /* Make sure it's not a user only... */
2051 user = build_user(username, var, 1);
2053 /* Add some finishing touches, addresses, etc */
2057 if (!strcasecmp(tmp->name, "type")) {
2058 if (strcasecmp(tmp->value, "friend") &&
2059 strcasecmp(tmp->value, "user")) {
2060 /* Whoops, we weren't supposed to exist! */
2069 ast_destroy_realtime(var);
2074 static void realtime_update(const char *peername, struct sockaddr_in *sin)
2078 char regseconds[20];
2082 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2083 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2084 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2085 ast_update_realtime("iaxfriends", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2089 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, int *usejitterbuf, char *username, int usernlen, char *secret, int seclen, int *ofound, char *peercontext)
2091 struct ast_hostent ahp; struct hostent *hp;
2092 struct iax2_peer *p;
2100 sin->sin_family = AF_INET;
2101 ast_mutex_lock(&peerl.lock);
2104 if (!strcasecmp(p->name, peer)) {
2109 ast_mutex_unlock(&peerl.lock);
2111 p = realtime_peer(peer);
2114 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2115 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
2117 *sendani = p->sendani; /* Whether we transmit ANI */
2119 *maxtime = p->maxms; /* Max time they should take */
2121 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2123 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2127 *capability = p->capability;
2129 strncpy(username, p->username, usernlen);
2130 if (p->addr.sin_addr.s_addr) {
2131 sin->sin_addr = p->addr.sin_addr;
2132 sin->sin_port = p->addr.sin_port;
2134 sin->sin_addr = p->defaddr.sin_addr;
2135 sin->sin_port = p->defaddr.sin_port;
2138 *notransfer=p->notransfer;
2140 *usejitterbuf=p->usejitterbuf;
2142 if (!ast_strlen_zero(p->dbsecret)) {
2143 char *family, *key=NULL;
2144 family = ast_strdupa(p->dbsecret);
2146 key = strchr(family, '/');
2152 if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2153 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2159 strncpy(secret, p->secret, seclen); /* safe */
2170 hp = ast_gethostbyname(peer, &ahp);
2172 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2173 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2176 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2186 static int auto_congest(void *nothing)
2188 int callno = PTR_TO_CALLNO(nothing);
2189 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2190 ast_mutex_lock(&iaxsl[callno]);
2192 iaxs[callno]->initid = -1;
2193 iax2_queue_frame(callno, &f);
2194 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2196 ast_mutex_unlock(&iaxsl[callno]);
2200 static unsigned int iax2_datetime(void)
2206 localtime_r(&t, &tm);
2207 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2208 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2209 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2210 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2211 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2212 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2216 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2218 struct sockaddr_in sin;
2223 char *secret = NULL;
2225 char *l=NULL, *n=NULL;
2226 struct iax_ie_data ied;
2227 char myrdest [5] = "s";
2228 char context[AST_MAX_EXTENSION] ="";
2229 char peercontext[AST_MAX_EXTENSION] ="";
2230 char *portno = NULL;
2232 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2234 char storedusern[80], storedsecret[80];
2235 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2236 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2239 strncpy(host, dest, sizeof(host)-1);
2241 strsep(&stringp, "/");
2242 /* If no destination extension specified, use 's' */
2243 rdest = strsep(&stringp, "/");
2247 /* Check for trailing options */
2248 opts = strsep(&stringp, "/");
2253 strsep(&stringp, "@");
2254 rcontext = strsep(&stringp, "@");
2256 strsep(&stringp, "@");
2257 username = strsep(&stringp, "@");
2259 /* Really the second argument is the host, not the username */
2267 username = strsep(&stringp, ":");
2268 secret = strsep(&stringp, ":");
2271 if (strsep(&stringp, ":")) {
2273 strsep(&stringp, ":");
2274 portno = strsep(&stringp, ":");
2276 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, NULL, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext)) {
2277 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2280 /* Keep track of the context for outgoing calls too */
2281 strncpy(c->context, context, sizeof(c->context) - 1);
2283 sin.sin_port = htons(atoi(portno));
2286 n = c->cid.cid_name;
2287 /* Now build request */
2288 memset(&ied, 0, sizeof(ied));
2289 /* On new call, first IE MUST be IAX version of caller */
2290 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2291 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2292 if (strchr(opts, 'a')) {
2293 /* Request auto answer */
2294 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2297 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2298 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2300 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2301 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2302 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2304 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2305 if (iaxs[callno]->sendani && c->cid.cid_ani) {
2306 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2308 if (c->language && !ast_strlen_zero(c->language))
2309 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2310 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2311 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2313 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2314 else if (strlen(peercontext))
2315 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2316 if (!username && !ast_strlen_zero(storedusern))
2317 username = storedusern;
2319 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2320 if (!secret && !ast_strlen_zero(storedsecret))
2321 secret = storedsecret;
2322 ast_mutex_lock(&iaxsl[callno]);
2323 if (!ast_strlen_zero(c->context))
2324 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2326 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2328 if (secret[0] == '[') {
2329 /* This is an RSA key, not a normal secret */
2330 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2331 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2332 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2335 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2337 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2338 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2339 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2340 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2341 /* Transmit the string in a "NEW" request */
2343 /* XXX We have no equivalent XXX */
2344 if (option_verbose > 2)
2345 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2347 if (iaxs[callno]->maxtime) {
2348 /* Initialize pingtime and auto-congest time */
2349 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2350 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2351 } else if (autokill) {
2352 iaxs[callno]->pingtime = autokill / 2;
2353 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2355 send_command(iaxs[callno], AST_FRAME_IAX,
2356 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2357 ast_mutex_unlock(&iaxsl[callno]);
2358 ast_setstate(c, AST_STATE_RINGING);
2362 static int iax2_hangup(struct ast_channel *c)
2364 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2366 ast_mutex_lock(&iaxsl[callno]);
2367 if (callno && iaxs[callno]) {
2368 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2369 alreadygone = iaxs[callno]->alreadygone;
2370 /* Send the hangup unless we have had a transmission error or are already gone */
2371 if (!iaxs[callno]->error && !alreadygone)
2372 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2373 /* Explicitly predestroy it */
2374 iax2_predestroy_nolock(callno);
2375 /* If we were already gone to begin with, destroy us now */
2377 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2378 iax2_destroy_nolock(callno);
2381 ast_mutex_unlock(&iaxsl[callno]);
2382 if (option_verbose > 2)
2383 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2387 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2389 struct ast_option_header *h;
2391 h = malloc(datalen + sizeof(struct ast_option_header));
2393 h->flag = AST_OPTION_FLAG_REQUEST;
2394 h->option = htons(option);
2395 memcpy(h->data, data, datalen);
2396 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2397 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2401 ast_log(LOG_WARNING, "Out of memory\n");
2405 static struct ast_frame *iax2_read(struct ast_channel *c)
2407 static struct ast_frame f = { AST_FRAME_NULL, };
2408 ast_log(LOG_NOTICE, "I should never be called!\n");
2412 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2415 struct iax_ie_data ied0;
2416 struct iax_ie_data ied1;
2417 unsigned int transferid = rand();
2418 memset(&ied0, 0, sizeof(ied0));
2419 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2420 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2421 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2423 memset(&ied1, 0, sizeof(ied1));
2424 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2425 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2426 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2428 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2431 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2434 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2435 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2439 static void lock_both(unsigned short callno0, unsigned short callno1)
2441 ast_mutex_lock(&iaxsl[callno0]);
2442 while (ast_mutex_trylock(&iaxsl[callno1])) {
2443 ast_mutex_unlock(&iaxsl[callno0]);
2445 ast_mutex_lock(&iaxsl[callno0]);
2449 static void unlock_both(unsigned short callno0, unsigned short callno1)
2451 ast_mutex_unlock(&iaxsl[callno1]);
2452 ast_mutex_unlock(&iaxsl[callno0]);
2455 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2457 struct ast_channel *cs[3];
2458 struct ast_channel *who;
2461 int transferstarted=0;
2462 struct ast_frame *f;
2463 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2464 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2465 struct timeval waittimer = {0, 0}, tv;
2467 lock_both(callno0, callno1);
2468 /* Put them in native bridge mode */
2469 iaxs[callno0]->bridgecallno = callno1;
2470 iaxs[callno1]->bridgecallno = callno0;
2471 unlock_both(callno0, callno1);
2473 /* If not, try to bridge until we can execute a transfer, if we can */
2476 for (/* ever */;;) {
2477 /* Check in case we got masqueraded into */
2478 if ((c0->type != type) || (c1->type != type)) {
2479 if (option_verbose > 2)
2480 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2481 /* Remove from native mode */
2482 if (c0->type == type) {
2483 ast_mutex_lock(&iaxsl[callno0]);
2484 iaxs[callno0]->bridgecallno = 0;
2485 ast_mutex_unlock(&iaxsl[callno0]);
2487 if (c1->type == type) {
2488 ast_mutex_lock(&iaxsl[callno1]);
2489 iaxs[callno1]->bridgecallno = 0;
2490 ast_mutex_unlock(&iaxsl[callno1]);
2494 if (c0->nativeformats != c1->nativeformats) {
2495 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2496 /* Remove from native mode */
2497 lock_both(callno0, callno1);
2498 iaxs[callno0]->bridgecallno = 0;
2499 iaxs[callno1]->bridgecallno = 0;
2500 unlock_both(callno0, callno1);
2503 /* check if transfered and if we really want native bridging */
2504 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2505 /* Try the transfer */
2506 if (iax2_start_transfer(callno0, callno1))
2507 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2508 transferstarted = 1;
2510 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2511 /* Call has been transferred. We're no longer involved */
2512 gettimeofday(&tv, NULL);
2513 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2514 waittimer.tv_sec = tv.tv_sec;
2515 waittimer.tv_usec = tv.tv_usec;
2516 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2517 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2518 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2526 who = ast_waitfor_n(cs, 2, &to);
2528 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2541 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2547 if ((f->frametype == AST_FRAME_VOICE) ||
2548 (f->frametype == AST_FRAME_TEXT) ||
2549 (f->frametype == AST_FRAME_VIDEO) ||
2550 (f->frametype == AST_FRAME_IMAGE) ||
2551 (f->frametype == AST_FRAME_DTMF)) {
2552 if ((f->frametype == AST_FRAME_DTMF) &&
2553 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2555 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2558 /* Take out of conference mode */
2560 /* Remove from native mode */
2566 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2570 /* Remove from native mode */
2577 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2579 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2591 /* Swap who gets priority */
2596 lock_both(callno0, callno1);
2598 iaxs[callno0]->bridgecallno = 0;
2600 iaxs[callno1]->bridgecallno = 0;
2601 unlock_both(callno0, callno1);
2605 static int iax2_answer(struct ast_channel *c)
2607 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2609 ast_log(LOG_DEBUG, "Answering\n");
2610 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2613 static int iax2_indicate(struct ast_channel *c, int condition)
2615 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2617 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2618 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2621 static int iax2_transfer(struct ast_channel *c, char *dest)
2623 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2624 struct iax_ie_data ied;
2625 char tmp[256] = "", *context;
2626 strncpy(tmp, dest, sizeof(tmp) - 1);
2627 context = strchr(tmp, '@');
2632 memset(&ied, 0, sizeof(ied));
2633 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2635 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2637 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2638 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2642 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2644 static int iax2_getpeertrunk(struct sockaddr_in sin)
2646 struct iax2_peer *peer;
2648 ast_mutex_lock(&peerl.lock);
2651 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2652 (peer->addr.sin_port == sin.sin_port)) {
2658 ast_mutex_unlock(&peerl.lock);
2662 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
2664 struct ast_channel *tmp;
2665 struct chan_iax2_pvt *i;
2666 /* Don't hold call lock */
2667 ast_mutex_unlock(&iaxsl[callno]);
2668 tmp = ast_channel_alloc(1);
2669 ast_mutex_lock(&iaxsl[callno]);
2672 if (!ast_strlen_zero(i->username))
2673 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s@%s/%d", i->username, i->host, i->callno);
2675 snprintf(tmp->name, sizeof(tmp->name), "IAX2/%s/%d", i->host, i->callno);
2677 /* We can support any format by default, until we get restricted */
2678 tmp->nativeformats = capability;
2679 tmp->readformat = 0;
2680 tmp->writeformat = 0;
2681 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2682 tmp->pvt->send_digit = iax2_digit;
2683 tmp->pvt->send_text = iax2_sendtext;
2684 tmp->pvt->send_image = iax2_sendimage;
2685 tmp->pvt->send_html = iax2_sendhtml;
2686 tmp->pvt->call = iax2_call;
2687 tmp->pvt->hangup = iax2_hangup;
2688 tmp->pvt->answer = iax2_answer;
2689 tmp->pvt->read = iax2_read;
2690 tmp->pvt->write = iax2_write;
2691 tmp->pvt->write_video = iax2_write;
2692 tmp->pvt->indicate = iax2_indicate;
2693 tmp->pvt->setoption = iax2_setoption;
2694 tmp->pvt->bridge = iax2_bridge;
2695 tmp->pvt->transfer = iax2_transfer;
2696 if (!ast_strlen_zero(i->cid_num))
2697 tmp->cid.cid_num = strdup(i->cid_num);
2698 if (!ast_strlen_zero(i->cid_name))
2699 tmp->cid.cid_name = strdup(i->cid_name);
2700 if (!ast_strlen_zero(i->ani))
2701 tmp->cid.cid_ani = strdup(i->ani);
2702 if (!ast_strlen_zero(i->language))
2703 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2704 if (!ast_strlen_zero(i->dnid))
2705 tmp->cid.cid_dnid = strdup(i->dnid);
2706 tmp->cid.cid_pres = i->calling_pres;
2707 tmp->cid.cid_ton = i->calling_ton;
2708 tmp->cid.cid_tns = i->calling_tns;
2709 if (!ast_strlen_zero(i->accountcode))
2710 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2712 tmp->amaflags = i->amaflags;
2713 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2714 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2715 tmp->adsicpe = i->peeradsicpe;
2716 tmp->pvt->fixup = iax2_fixup;
2718 i->capability = capability;
2719 ast_setstate(tmp, state);
2720 ast_mutex_lock(&usecnt_lock);
2722 ast_mutex_unlock(&usecnt_lock);
2723 ast_update_use_count();
2724 if (state != AST_STATE_DOWN) {
2725 if (ast_pbx_start(tmp)) {
2726 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2735 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
2737 unsigned long int mssincetx; /* unsigned to handle overflows */
2740 tpeer->trunkact = *tv;
2741 mssincetx = (tv->tv_sec - tpeer->lasttxtime.tv_sec) * 1000 +
2742 (1000000 + tv->tv_usec - tpeer->lasttxtime.tv_usec) / 1000 - 1000;
2743 if (mssincetx > 5000 || (!tpeer->txtrunktime.tv_sec && !tpeer->txtrunktime.tv_usec)) {
2744 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2745 tpeer->txtrunktime.tv_sec = tv->tv_sec;
2746 tpeer->txtrunktime.tv_usec = tv->tv_usec;
2747 tpeer->lastsent = 999999;
2749 /* Update last transmit time now */
2750 tpeer->lasttxtime.tv_sec = tv->tv_sec;
2751 tpeer->lasttxtime.tv_usec = tv->tv_usec;
2753 /* Calculate ms offset */
2754 ms = (tv->tv_sec - tpeer->txtrunktime.tv_sec) * 1000 +
2755 (1000000 + tv->tv_usec - tpeer->txtrunktime.tv_usec) / 1000 - 1000;
2756 /* Predict from last value */
2757 pred = tpeer->lastsent + sampms;
2758 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
2761 /* We never send the same timestamp twice, so fudge a little if we must */
2762 if (ms == tpeer->lastsent)
2763 ms = tpeer->lastsent + 1;
2764 tpeer->lastsent = ms;
2768 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
2770 long ms; /* NOT unsigned */
2771 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2772 /* Initialize rxcore time if appropriate */
2773 gettimeofday(&iaxs[callno]->rxcore, NULL);
2774 /* Round to nearest 20ms so traces look pretty */
2775 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2777 /* Calculate difference between trunk and channel */
2778 ms = (tv->tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2779 (1000000 + tv->tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000 - 1000;
2780 /* Return as the sum of trunk time and the difference between trunk and real time */
2784 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2790 struct timeval *delivery = NULL;
2792 /* What sort of frame do we have?: voice is self-explanatory
2793 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
2794 non-genuine frames are CONTROL frames [ringing etc], DTMF
2795 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
2796 the others need a timestamp slaved to the voice frames so that they go in sequence
2799 if (f->frametype == AST_FRAME_VOICE) {
2801 delivery = &f->delivery;
2802 } else if (f->frametype == AST_FRAME_IAX) {
2806 if (!p->offset.tv_sec && !p->offset.tv_usec) {
2807 gettimeofday(&p->offset, NULL);
2808 /* Round to nearest 20ms for nice looking traces */
2809 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2811 /* If the timestamp is specified, just send it as is */
2814 /* If we have a time that the frame arrived, always use it to make our timestamp */
2815 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2816 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 +
2817 (1000000 + delivery->tv_usec - p->offset.tv_usec) / 1000 - 1000;
2819 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
2821 gettimeofday(&tv, NULL);
2822 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 +
2823 (1000000 + tv.tv_usec - p->offset.tv_usec) / 1000 - 1000;
2827 /* On a voice frame, use predicted values if appropriate */
2828 if (abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
2830 p->nextpred = ms; /*f->samples / 8;*/
2831 if (p->nextpred <= p->lastsent)
2832 p->nextpred = p->lastsent + 3;
2838 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
2839 it's a genuine frame */
2841 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
2842 if (ms <= p->lastsent)
2843 ms = p->lastsent + 3;
2844 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
2845 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
2846 ms = p->lastsent + 3;
2852 p->nextpred = p->nextpred + f->samples / 8;
2854 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2859 #ifdef BRIDGE_OPTIMIZATION
2860 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2863 /* Receive from p1, send to p2 */
2865 /* Setup rxcore if necessary on outgoing channel */
2866 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2867 gettimeofday(&p1->rxcore, NULL);
2869 /* Setup txcore if necessary on outgoing channel */
2870 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2871 gettimeofday(&p2->offset, NULL);
2873 /* Now, ts is the timestamp of the original packet in the orignal context.
2874 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2875 Subtracting txcore of the outgoing channel gives us what we'd expect */
2877 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 +
2878 (1000000 + p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000 - 1000;
2881 /* FIXME? SLD would rather remove this and leave it to the end system to deal with */
2882 if (fakets <= p2->lastsent)
2883 fakets = p2->lastsent + 1;
2884 p2->lastsent = fakets;
2889 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
2891 /* Returns where in "receive time" we are. That is, how many ms
2892 since we received (or would have received) the frame with timestamp 0 */
2895 /* Setup rxcore if necessary */
2896 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec) {
2897 gettimeofday(&p->rxcore, NULL);
2899 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
2900 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
2901 p->rxcore.tv_sec -= offset / 1000;
2902 p->rxcore.tv_usec -= (offset % 1000) * 1000;
2903 if (p->rxcore.tv_usec < 0) {
2904 p->rxcore.tv_usec += 1000000;
2905 p->rxcore.tv_sec -= 1;
2909 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
2910 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
2914 gettimeofday(&tv, NULL);
2915 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 +
2916 (1000000 + tv.tv_usec - p->rxcore.tv_usec) / 1000 - 1000;
2920 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin)
2922 struct iax2_trunk_peer *tpeer;
2923 char iabuf[INET_ADDRSTRLEN];
2924 /* Finds and locks trunk peer */
2925 ast_mutex_lock(&tpeerlock);
2928 /* We don't lock here because tpeer->addr *never* changes */
2929 if (!inaddrcmp(&tpeer->addr, sin)) {
2930 ast_mutex_lock(&tpeer->lock);
2933 tpeer = tpeer->next;
2936 tpeer = malloc(sizeof(struct iax2_trunk_peer));
2938 memset(tpeer, 0, sizeof(struct iax2_trunk_peer));
2939 ast_mutex_init(&tpeer->lock);
2940 tpeer->lastsent = 9999;
2941 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
2942 gettimeofday(&tpeer->trunkact, NULL);
2943 ast_mutex_lock(&tpeer->lock);
2944 tpeer->next = tpeers;
2946 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2949 ast_mutex_unlock(&tpeerlock);
2953 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2955 struct iax2_trunk_peer *tpeer;
2957 struct ast_iax2_meta_trunk_entry *met;
2958 char iabuf[INET_ADDRSTRLEN];
2959 tpeer = find_tpeer(&pvt->addr);
2961 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
2962 /* Need to reallocate space */
2963 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
2964 tmp = realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE);
2966 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
2967 tpeer->trunkdata = tmp;
2968 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
2970 ast_log(LOG_WARNING, "Insufficient memory to expand trunk data to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2971 ast_mutex_unlock(&tpeer->lock);
2975 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
2976 ast_mutex_unlock(&tpeer->lock);
2981 /* Append to meta frame */
2982 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
2983 met = (struct ast_iax2_meta_trunk_entry *)ptr;
2984 /* Store call number and length in meta header */
2985 met->callno = htons(pvt->callno);
2986 met->len = htons(f->datalen);
2987 /* Advance pointers/decrease length past trunk entry header */
2988 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
2989 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
2990 /* Copy actual trunk data */
2991 memcpy(ptr, f->data, f->datalen);
2992 tpeer->trunkdatalen += f->datalen;
2994 ast_mutex_unlock(&tpeer->lock);
2999 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
3001 /* Queue a packet for delivery on a given private structure. Use "ts" for
3002 timestamp, or calculate if ts is 0. Send immediately without retransmission
3003 or delayed, with retransmission */
3004 struct ast_iax2_full_hdr *fh;
3005 struct ast_iax2_mini_hdr *mh;
3006 struct ast_iax2_video_hdr *vh;
3008 struct iax_frame fr2;
3009 unsigned char buffer[4096];
3011 struct iax_frame *fr;
3014 unsigned int lastsent;
3018 ast_log(LOG_WARNING, "No private structure for packet?\n");
3022 lastsent = pvt->lastsent;
3024 /* Calculate actual timestamp */
3025 fts = calc_timestamp(pvt, ts, f);
3027 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
3028 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
3029 (f->frametype == AST_FRAME_VOICE)
3030 /* is a voice frame */ &&
3031 (f->subclass == pvt->svoiceformat)
3032 /* is the same type */ ) {
3033 /* Force immediate rather than delayed transmission */
3035 /* Mark that mini-style frame is appropriate */
3038 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
3039 (f->frametype == AST_FRAME_VIDEO) &&
3040 ((f->subclass & ~0x1) == pvt->svideoformat)) {
3044 /* Allocate an iax_frame */
3048 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
3050 ast_log(LOG_WARNING, "Out of memory\n");
3053 /* Copy our prospective frame into our immediate or retransmitted wrapper */
3054 iax_frame_wrap(fr, f);
3057 fr->callno = pvt->callno;
3058 fr->transfer = transfer;
3061 /* We need a full frame */
3065 fr->oseqno = pvt->oseqno++;
3066 fr->iseqno = pvt->iseqno;
3067 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
3068 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
3069 fh->ts = htonl(fr->ts);
3070 fh->oseqno = fr->oseqno;
3074 fh->iseqno = fr->iseqno;
3075 /* Keep track of the last thing we've acknowledged */
3077 pvt->aseqno = fr->iseqno;
3078 fh->type = fr->af.frametype & 0xFF;
3079 if (fr->af.frametype == AST_FRAME_VIDEO)
3080 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
3082 fh->csub = compress_subclass(fr->af.subclass);
3084 fr->dcallno = pvt->transfercallno;
3086 fr->dcallno = pvt->peercallno;
3087 fh->dcallno = htons(fr->dcallno);
3088 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
3091 /* Retry after 2x the ping time has passed */
3092 fr->retrytime = pvt->pingtime * 2;
3093 if (fr->retrytime < MIN_RETRY_TIME)
3094 fr->retrytime = MIN_RETRY_TIME;
3095 if (fr->retrytime > MAX_RETRY_TIME)
3096 fr->retrytime = MAX_RETRY_TIME;
3097 /* Acks' don't get retried */
3098 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
3100 else if (f->frametype == AST_FRAME_VOICE)
3101 pvt->svoiceformat = f->subclass;
3102 else if (f->frametype == AST_FRAME_VIDEO)
3103 pvt->svideoformat = f->subclass & ~0x1;
3105 res = send_packet(fr);
3107 res = iax2_transmit(fr);
3110 iax2_trunk_queue(pvt, &fr->af);
3112 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
3113 /* Video frame have no sequence number */
3116 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
3118 vh->callno = htons(0x8000 | fr->callno);
3119 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
3120 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
3123 res = send_packet(fr);
3125 /* Mini-frames have no sequence number */
3128 /* Mini frame will do */
3129 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
3130 mh->callno = htons(fr->callno);
3131 mh->ts = htons(fr->ts & 0xFFFF);
3132 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
3135 res = send_packet(fr);
3143 static int iax2_show_users(int fd, int argc, char *argv[])
3145 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s\n"
3146 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s\n"
3147 struct iax2_user *user;
3150 return RESULT_SHOWUSAGE;
3151 ast_mutex_lock(&userl.lock);
3152 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
3153 for(user=userl.users;user;user=user->next) {
3154 if (!ast_strlen_zero(user->secret)) {
3155 strncpy(auth,user->secret,sizeof(auth)-1);
3156 } else if (!ast_strlen_zero(user->inkeys)) {
3157 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
3159 strncpy(auth, "-no secret-", sizeof(auth) - 1);
3160 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
3161 user->contexts ? user->contexts->context : context,
3162 user->ha ? "Yes" : "No");
3164 ast_mutex_unlock(&userl.lock);
3165 return RESULT_SUCCESS;
3170 static int iax2_show_peers(int fd, int argc, char *argv[])
3172 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
3173 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
3174 struct iax2_peer *peer;
3175 char name[256] = "";
3176 char iabuf[INET_ADDRSTRLEN];
3177 int registeredonly=0;
3178 if ((argc != 3) && (argc != 4) && (argc != 5))
3179 return RESULT_SHOWUSAGE;
3181 if (!strcasecmp(argv[3], "registered")) {
3184 return RESULT_SHOWUSAGE;
3186 ast_mutex_lock(&peerl.lock);
3187 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
3188 for (peer = peerl.peers;peer;peer = peer->next) {
3190 char status[20] = "";
3191 int print_line = -1;
3192 char srch[2000] = "";
3193 if (registeredonly && !peer->addr.sin_addr.s_addr)
3195 if (!ast_strlen_zero(peer->username))
3196 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
3198 strncpy(name, peer->name, sizeof(name) - 1);
3200 if (peer->lastms < 0)
3201 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
3202 else if (peer->lastms > peer->maxms)
3203 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
3204 else if (peer->lastms)
3205 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
3207 strncpy(status, "UNKNOWN", sizeof(status) - 1);
3209 strncpy(status, "Unmonitored", sizeof(status) - 1);
3210 strncpy(nm, ast_inet_ntoa(iabuf, sizeof(iabuf), peer->mask), sizeof(nm)-1);
3212 snprintf(srch, sizeof(srch), FORMAT, name,
3213 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3214 peer->dynamic ? "(D)" : "(S)",
3216 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
3219 if (!strcasecmp(argv[3],"include") && strstr(srch,argv[4])) {
3221 } else if (!strcasecmp(argv[3],"exclude") && !strstr(srch,argv[4])) {
3223 } else if (!strcasecmp(argv[3],"begin") && !strncasecmp(srch,argv[4],strlen(argv[4]))) {
3231 ast_cli(fd, FORMAT, name,
3232 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)",
3233 peer->dynamic ? "(D)" : "(S)",
3235 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
3238 ast_mutex_unlock(&peerl.lock);
3239 return RESULT_SUCCESS;
3244 static int iax2_show_firmware(int fd, int argc, char *argv[])
3246 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
3247 #define FORMAT "%-15.15s %-15d %-15d\n"
3248 struct iax_firmware *cur;
3249 if ((argc != 3) && (argc != 4))
3250 return RESULT_SHOWUSAGE;
3251 ast_mutex_lock(&waresl.lock);
3253 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
3254 for (cur = waresl.wares;cur;cur = cur->next) {
3255 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname)))
3256 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
3257 ntohl(cur->fwh->datalen));
3259 ast_mutex_unlock(&waresl.lock);
3260 return RESULT_SUCCESS;
3265 /* JDG: callback to display iax peers in manager */
3266 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
3268 char *a[] = { "iax2", "show", "users" };
3270 ret = iax2_show_peers( s->fd, 3, a );
3271 ast_cli( s->fd, "\r\n" );
3275 static char *regstate2str(int regstate)
3278 case REG_STATE_UNREGISTERED:
3279 return "Unregistered";
3280 case REG_STATE_REGSENT:
3281 return "Request Sent";
3282 case REG_STATE_AUTHSENT:
3283 return "Auth. Sent";
3284 case REG_STATE_REGISTERED:
3285 return "Registered";
3286 case REG_STATE_REJECTED:
3288 case REG_STATE_TIMEOUT:
3290 case REG_STATE_NOAUTH:
3291 return "No Authentication";
3297 static int iax2_show_registry(int fd, int argc, char *argv[])
3299 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
3300 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
3301 struct iax2_registry *reg;
3303 char perceived[80] = "";
3304 char iabuf[INET_ADDRSTRLEN];
3306 return RESULT_SHOWUSAGE;
3307 ast_mutex_lock(&peerl.lock);
3308 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
3309 for (reg = registrations;reg;reg = reg->next) {
3310 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->addr.sin_addr), ntohs(reg->addr.sin_port));
3311 if (reg->us.sin_addr.s_addr)
3312 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), reg->us.sin_addr), ntohs(reg->us.sin_port));
3314 strncpy(perceived, "<Unregistered>", sizeof(perceived) - 1);
3315 ast_cli(fd, FORMAT, host,
3316 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
3318 ast_mutex_unlock(&peerl.lock);
3319 return RESULT_SUCCESS;
3324 static int jitterbufsize(struct chan_iax2_pvt *pvt) {
3327 for (i=0; i<MEMORY_SIZE; i++) {
3328 if (pvt->history[i] < min)
3329 min = pvt->history[i];
3331 if (pvt->jitterbuffer - min > maxjitterbuffer)
3332 return maxjitterbuffer;
3334 return pvt->jitterbuffer - min;
3337 static int iax2_show_channels(int fd, int argc, char *argv[])
3339 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
3340 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
3341 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
3344 char iabuf[INET_ADDRSTRLEN];
3346 return RESULT_SHOWUSAGE;
3347 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
3348 for (x=0;x<IAX_MAX_CALLS;x++) {
3349 ast_mutex_lock(&iaxsl[x]);
3351 #ifdef BRIDGE_OPTIMIZATION
3352 if (iaxs[x]->bridgecallno)
3353 ast_cli(fd, FORMATB,
3354 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
3355 ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr),
3356 !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)",
3357 iaxs[x]->callno, iaxs[x]->peercallno,
3358 iaxs[x]->oseqno, iaxs[x]->iseqno,
3359 iaxs[x]->bridgecallno );
3363 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
3364 ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[x]->addr.sin_addr),
3365 !ast_strlen_zero(iaxs[x]->username) ? iaxs[x]->username : "(None)",
3366 iaxs[x]->callno, iaxs[x]->peercallno,
3367 iaxs[x]->oseqno, iaxs[x]->iseqno,
3370 iaxs[x]->usejitterbuf ? jitterbufsize(iaxs[x]) : 0,
3371 ast_getformatname(iaxs[x]->voiceformat) );
3374 ast_mutex_unlock(&iaxsl[x]);
3376 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3377 return RESULT_SUCCESS;
3382 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3385 return RESULT_SHOWUSAGE;
3387 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3388 return RESULT_SUCCESS;
3391 static int iax2_do_debug(int fd, int argc, char *argv[])
3394 return RESULT_SHOWUSAGE;
3396 ast_cli(fd, "IAX2 Debugging Enabled\n");
3397 return RESULT_SUCCESS;
3400 static int iax2_no_debug(int fd, int argc, char *argv[])
3403 return RESULT_SHOWUSAGE;
3405 ast_cli(fd, "IAX2 Debugging Disabled\n");
3406 return RESULT_SUCCESS;
3411 static char show_users_usage[] =
3412 "Usage: iax2 show users\n"
3413 " Lists all users known to the IAX (Inter-Asterisk eXchange rev 2) subsystem.\n";
3415 static char show_channels_usage[] =
3416 "Usage: iax2 show channels\n"
3417 " Lists all currently active IAX channels.\n";
3419 static char show_peers_usage[] =
3420 "Usage: iax2 show peers\n"
3421 " Lists all known IAX peers.\n";
3423 static char show_firmware_usage[] =
3424 "Usage: iax2 show firmware\n"
3425 " Lists all known IAX firmware images.\n";
3427 static char show_reg_usage[] =
3428 "Usage: iax2 show registry\n"
3429 " Lists all registration requests and status.\n";
3431 static char debug_usage[] =
3432 "Usage: iax2 debug\n"
3433 " Enables dumping of IAX packets for debugging purposes\n";
3435 static char no_debug_usage[] =
3436 "Usage: iax2 no debug\n"
3437 " Disables dumping of IAX packets for debugging purposes\n";
3439 static char debug_trunk_usage[] =
3440 "Usage: iax2 trunk debug\n"
3441 " Requests current status of IAX trunking\n";
3443 static struct ast_cli_entry cli_show_users =
3444 { { "iax2", "show", "users", NULL }, iax2_show_users, "Show defined IAX users", show_users_usage };
3445 static struct ast_cli_entry cli_show_firmware =
3446 { { "iax2", "show", "firmware", NULL }, iax2_show_firmware, "Show available IAX firmwares", show_firmware_usage };
3447 static struct ast_cli_entry cli_show_channels =
3448 { { "iax2", "show", "channels", NULL }, iax2_show_channels, "Show active IAX channels", show_channels_usage };
3449 static struct ast_cli_entry cli_show_peers =
3450 { { "iax2", "show", "peers", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };
3451 static struct ast_cli_entry cli_show_peers_include =
3452 { { "iax2", "show", "peers", "include", NULL }, iax2_show_peers, "Show defined IAX peers", show_peers_usage };