2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003, Digium
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <asterisk/lock.h>
15 #include <asterisk/frame.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/channel_pvt.h>
18 #include <asterisk/logger.h>
19 #include <asterisk/module.h>
20 #include <asterisk/pbx.h>
21 #include <asterisk/sched.h>
22 #include <asterisk/io.h>
23 #include <asterisk/config.h>
24 #include <asterisk/options.h>
25 #include <asterisk/cli.h>
26 #include <asterisk/translate.h>
27 #include <asterisk/md5.h>
28 #include <asterisk/cdr.h>
29 #include <asterisk/crypto.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/manager.h>
32 #include <asterisk/callerid.h>
33 #include <asterisk/app.h>
34 #include <asterisk/astdb.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/parking.h>
38 #include <arpa/inet.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <netinet/in_systm.h>
43 #include <netinet/ip.h>
45 #include <sys/signal.h>
55 #include <sys/types.h>
58 #include <sys/ioctl.h>
59 #include <linux/zaptel.h>
62 #include <mysql/mysql.h>
65 #include "iax2-parser.h"
66 #include "../astconf.h"
69 #define IPTOS_MINCOST 0x02
73 * Uncomment to try experimental IAX bridge optimization,
74 * designed to reduce latency when IAX calls cannot
78 #define BRIDGE_OPTIMIZATION
80 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
81 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
83 #define DEFAULT_RETRY_TIME 1000
84 #define MEMORY_SIZE 100
85 #define DEFAULT_DROP 3
86 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
87 but keeps the division between trunked and non-trunked better. */
88 #define TRUNK_CALL_START 0x4000
92 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
94 /* Sample over last 100 units to determine historic jitter */
98 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
100 static char mydbuser[80];
101 static char mydbpass[80];
102 static char mydbhost[80];
103 static char mydbname[80];
105 static char *desc = "Inter Asterisk eXchange (Ver 2)";
106 static char *tdesc = "Inter Asterisk eXchange Driver (Ver 2)";
107 static char *type = "IAX2";
109 static char context[80] = "default";
111 static int max_retries = 4;
112 static int ping_time = 20;
113 static int lagrq_time = 10;
114 static int maxtrunkcall = TRUNK_CALL_START;
115 static int maxnontrunkcall = 1;
116 static int maxjitterbuffer=3000;
117 static int trunkfreq = 20;
118 static int authdebug = 1;
119 static int iaxcompat = 0;
121 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
123 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
125 static int netsocket = -1;
129 static int expirey = IAX_DEFAULT_REG_EXPIRE;
131 static int timingfd = -1; /* Timing file descriptor */
134 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
136 int (*iax2_regfunk)(char *username, int onoff) = NULL;
139 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
141 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
142 ~AST_FORMAT_SLINEAR & \
146 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
150 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
154 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
155 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
156 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
158 static struct io_context *io;
159 static struct sched_context *sched;
161 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
163 static int iax2_dropcount = DEFAULT_DROP;
165 static int use_jitterbuffer = 0;
167 static int iaxdebug = 0;
169 static int iaxtrunkdebug = 0;
171 static char accountcode[20];
172 static int amaflags = 0;
173 static int notransfer = 0;
175 static pthread_t netthreadid = AST_PTHREADT_NULL;
177 #define IAX_STATE_STARTED (1 << 0)
178 #define IAX_STATE_AUTHENTICATED (1 << 1)
179 #define IAX_STATE_TBD (1 << 2)
181 struct iax2_context {
182 char context[AST_MAX_EXTENSION];
183 struct iax2_context *next;
190 char accountcode[20];
191 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
198 char callerid[AST_MAX_EXTENSION];
200 struct iax2_context *contexts;
201 struct iax2_user *next;
209 char outkey[80]; /* What key we use to talk to this peer */
210 char context[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
211 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
212 struct sockaddr_in addr;
216 /* Dynamic Registration fields */
217 int dynamic; /* If this is a dynamic peer */
218 struct sockaddr_in defaddr; /* Default address if there is one */
219 int authmethods; /* Authentication methods (IAX_AUTH_*) */
220 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
223 /* Suggested caller id if registering */
224 char callerid[AST_MAX_EXTENSION];
225 /* Whether or not to send ANI */
227 int expire; /* Schedule entry for expirey */
228 int expirey; /* How soon to expire */
229 int capability; /* Capability */
230 int delme; /* I need to be deleted */
231 int temponly; /* I'm only a temp */
232 int trunk; /* Treat as an IAX trunking */
233 struct timeval txtrunktime; /* Transmit trunktime */
234 struct timeval rxtrunktime; /* Receive trunktime */
235 struct timeval lasttxtime; /* Last transmitted trunktime */
236 unsigned int lastsent; /* Last sent time */
239 int callno; /* Call number of POKE request */
240 int pokeexpire; /* When to expire poke */
241 int lastms; /* How long last response took (in ms), or -1 for no response */
242 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
245 struct iax2_peer *next;
249 struct iax_firmware {
250 struct iax_firmware *next;
254 struct ast_iax2_firmware_header *fwh;
258 #define REG_STATE_UNREGISTERED 0
259 #define REG_STATE_REGSENT 1
260 #define REG_STATE_AUTHSENT 2
261 #define REG_STATE_REGISTERED 3
262 #define REG_STATE_REJECTED 4
263 #define REG_STATE_TIMEOUT 5
264 #define REG_STATE_NOAUTH 6
266 #define TRANSFER_NONE 0
267 #define TRANSFER_BEGIN 1
268 #define TRANSFER_READY 2
269 #define TRANSFER_RELEASED 3
270 #define TRANSFER_PASSTHROUGH 4
272 struct iax2_registry {
273 struct sockaddr_in addr; /* Who we connect to for registration purposes */
275 char secret[80]; /* Password or key name in []'s */
277 int expire; /* Sched ID of expiration */
278 int refresh; /* How often to refresh */
280 int messages; /* Message count */
281 int callno; /* Associated call number if applicable */
282 struct sockaddr_in us; /* Who the server thinks we are */
283 struct iax2_registry *next;
286 static struct iax2_registry *registrations;
288 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
289 #define MIN_RETRY_TIME 100
290 #define MAX_RETRY_TIME 10000
291 #define MAX_JITTER_BUFFER 50
293 #define MAX_TRUNKDATA 640 /* 40ms, uncompressed linear */
295 /* If we have more than this much excess real jitter buffer, srhink it. */
296 static int max_jitter_buffer = MAX_JITTER_BUFFER;
298 struct chan_iax2_pvt {
299 /* Pipes for communication. pipe[1] belongs to the
300 network thread (write), and pipe[0] belongs to the individual
302 /* Whether or not we Quelch audio */
304 /* Last received voice format */
306 /* Last received voice format */
308 /* Last sent voice format */
310 /* Last sent video format */
312 /* What we are capable of sending */
314 /* Last received timestamp */
316 /* Last sent timestamp - never send the same timestamp twice in a single call */
317 unsigned int lastsent;
318 /* Next outgoing timestamp if everything is good */
319 unsigned int nextpred;
321 unsigned int pingtime;
322 /* Max time for initial response */
325 struct sockaddr_in addr;
326 /* Our call number */
327 unsigned short callno;
329 unsigned short peercallno;
330 /* Peer selected format */
332 /* Peer capability */
334 /* timeval that we base our transmission on */
335 struct timeval offset;
336 /* timeval that we base our delivery on */
337 struct timeval rxcore;
338 /* Historical delivery time */
339 int history[MEMORY_SIZE];
340 /* Current base jitterbuffer */
342 /* Current jitter measure */
344 /* Historic jitter value */
348 /* Error, as discovered by the manager */
350 /* Owner if we have one */
351 struct ast_channel *owner;
352 /* What's our state? */
354 /* Expirey (optional) */
356 /* Next outgoing sequence number */
357 unsigned char oseqno;
358 /* Next sequence number they have not yet acknowledged */
359 unsigned char rseqno;
360 /* Next incoming sequence number */
361 unsigned char iseqno;
362 /* Last incoming sequence number we have acknowledged */
363 unsigned char aseqno;
366 /* Default Context */
368 /* Caller ID if available */
370 /* Hidden Caller ID (i.e. ANI) if appropriate */
372 /* Whether or not ani should be transmitted in addition to Caller*ID */
374 /* Whether to request autoanswer */
378 /* Requested Extension */
379 char exten[AST_MAX_EXTENSION];
380 /* Expected Username */
382 /* Expected Secret */
384 /* permitted authentication methods */
388 /* Public keys permitted keys for incoming authentication */
390 /* Private key for outgoing authentication */
392 /* Preferred language */
394 /* Hostname/peername for naming purposes */
396 /* Associated registry */
397 struct iax2_registry *reg;
398 /* Associated peer for poking */
399 struct iax2_peer *peerpoke;
401 /* Transferring status */
403 /* Transfer identifier */
405 /* Already disconnected */
407 /* Who we are IAX transfering to */
408 struct sockaddr_in transfer;
409 /* What's the new call number for the transfer */
410 unsigned short transfercallno;
412 /* Status of knowledge of peer ADSI capability */
415 /* Who we are bridged to */
416 unsigned short bridgecallno;
417 unsigned int bridgesfmt;
418 struct ast_trans_pvt *bridgetrans;
420 int pingid; /* Transmit PING request */
421 int lagid; /* Retransmit lag request */
422 int autoid; /* Auto hangup for Dialplan requestor */
423 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
424 char dproot[AST_MAX_EXTENSION];
425 char accountcode[20];
427 /* This is part of a trunk interface */
429 /* Trunk data and length */
430 unsigned char trunkdata[MAX_TRUNKDATA];
431 unsigned int trunkdatalen;
433 struct iax2_dpcache *dpentries;
434 int notransfer; /* do we want native bridging */
437 static struct ast_iax2_queue {
438 struct iax_frame *head;
439 struct iax_frame *tail;
444 static struct ast_user_list {
445 struct iax2_user *users;
449 static struct ast_peer_list {
450 struct iax2_peer *peers;
454 static struct ast_firmware_list {
455 struct iax_firmware *wares;
459 /* Extension exists */
460 #define CACHE_FLAG_EXISTS (1 << 0)
461 /* Extension is non-existant */
462 #define CACHE_FLAG_NONEXISTANT (1 << 1)
463 /* Extension can exist */
464 #define CACHE_FLAG_CANEXIST (1 << 2)
465 /* Waiting to hear back response */
466 #define CACHE_FLAG_PENDING (1 << 3)
468 #define CACHE_FLAG_TIMEOUT (1 << 4)
469 /* Request transmitted */
470 #define CACHE_FLAG_TRANSMITTED (1 << 5)
472 #define CACHE_FLAG_UNKNOWN (1 << 6)
474 #define CACHE_FLAG_MATCHMORE (1 << 7)
476 static struct iax2_dpcache {
477 char peercontext[AST_MAX_EXTENSION];
478 char exten[AST_MAX_EXTENSION];
480 struct timeval expirey;
482 unsigned short callno;
484 struct iax2_dpcache *next;
485 struct iax2_dpcache *peer; /* For linking in peers */
488 static ast_mutex_t dpcache_lock;
490 static void iax_debug_output(const char *data)
495 static void iax_error_output(const char *data)
497 ast_log(LOG_WARNING, data);
500 /* XXX We probably should use a mutex when working with this XXX */
501 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
502 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
503 static struct timeval lastused[IAX_MAX_CALLS];
506 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
507 static int send_command_locked(unsigned short callno, char, int, unsigned int, char *, int, int);
508 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
509 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, char *, int, int);
510 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, char *, int);
512 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f);
514 static int send_ping(void *data)
516 int callno = (long)data;
517 /* Ping only if it's real, not if it's bridged */
519 #ifdef BRIDGE_OPTIMIZATION
520 if (!iaxs[callno]->bridgecallno)
522 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
528 static int send_lagrq(void *data)
530 int callno = (long)data;
531 /* Ping only if it's real not if it's bridged */
533 #ifdef BRIDGE_OPTIMIZATION
534 if (!iaxs[callno]->bridgecallno)
536 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
542 static unsigned char compress_subclass(int subclass)
546 /* If it's 128 or smaller, just return it */
547 if (subclass < IAX_FLAG_SC_LOG)
549 /* Otherwise find its power */
550 for (x = 0; x < IAX_MAX_SHIFT; x++) {
551 if (subclass & (1 << x)) {
553 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
559 return power | IAX_FLAG_SC_LOG;
562 static int uncompress_subclass(unsigned char csub)
564 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
565 if (csub & IAX_FLAG_SC_LOG) {
566 /* special case for 'compressed' -1 */
570 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
576 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
578 struct iax2_peer *peer;
581 ast_mutex_lock(&peerl.lock);
584 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
585 (peer->addr.sin_port == sin.sin_port)) {
586 strncpy(host, peer->name, len-1);
593 ast_mutex_unlock(&peerl.lock);
597 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer)
599 struct chan_iax2_pvt *tmp;
600 tmp = malloc(sizeof(struct chan_iax2_pvt));
602 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
605 tmp->transfercallno = 0;
606 tmp->bridgecallno = 0;
611 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
612 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
613 if (!iax2_getpeername(*sin, tmp->host, sizeof(tmp->host), lockpeer))
614 snprintf(tmp->host, sizeof(tmp->host), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
619 static int get_samples(struct ast_frame *f)
622 switch(f->subclass) {
623 case AST_FORMAT_SPEEX:
624 samples = 160; /* XXX Not necessarily true XXX */
626 case AST_FORMAT_G723_1:
627 samples = 240 /* XXX Not necessarily true XXX */;
629 case AST_FORMAT_ILBC:
630 samples = 240 * (f->datalen / 50);
633 samples = 160 * (f->datalen / 33);
635 case AST_FORMAT_G729A:
636 samples = 160 * (f->datalen / 20);
638 case AST_FORMAT_SLINEAR:
639 samples = f->datalen / 2;
641 case AST_FORMAT_LPC10:
643 samples += (((char *)(f->data))[7] & 0x1) * 8;
645 case AST_FORMAT_ULAW:
646 samples = f->datalen;
648 case AST_FORMAT_ALAW:
649 samples = f->datalen;
651 case AST_FORMAT_ADPCM:
652 case AST_FORMAT_G726:
653 samples = f->datalen *2;
656 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
661 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
663 /* Malloc() a copy of a frame */
664 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
666 memcpy(new, fr, sizeof(struct iax_frame));
667 iax_frame_wrap(new, &fr->af);
670 new->direction = DIRECTION_INGRESS;
676 #define NEW_PREVENT 0
680 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
682 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
683 (cur->addr.sin_port == sin->sin_port)) {
684 /* This is the main host */
685 if ((cur->peercallno == callno) ||
686 ((dcallno == cur->callno) && !cur->peercallno)) {
687 /* That's us. Be sure we keep track of the peer call number */
691 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
692 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
693 /* We're transferring */
694 if (dcallno == cur->callno)
700 static void update_max_trunk(void)
702 int max = TRUNK_CALL_START;
704 /* XXX Prolly don't need locks here XXX */
705 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
711 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
714 static void update_max_nontrunk(void)
718 /* XXX Prolly don't need locks here XXX */
719 for (x=1;x<TRUNK_CALL_START - 1; x++) {
723 maxnontrunkcall = max;
725 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
728 static int make_trunk(unsigned short callno, int locked)
733 if (iaxs[callno]->oseqno) {
734 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
737 if (callno & TRUNK_CALL_START) {
738 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
741 gettimeofday(&now, NULL);
742 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
743 ast_mutex_lock(&iaxsl[x]);
744 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
745 iaxs[x] = iaxs[callno];
748 /* Update the two timers that should have been started */
749 if (iaxs[x]->pingid > -1)
750 ast_sched_del(sched, iaxs[x]->pingid);
751 if (iaxs[x]->lagid > -1)
752 ast_sched_del(sched, iaxs[x]->lagid);
753 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
754 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
756 ast_mutex_unlock(&iaxsl[callno]);
759 ast_mutex_unlock(&iaxsl[x]);
762 ast_mutex_unlock(&iaxsl[x]);
764 if (x >= IAX_MAX_CALLS - 1) {
765 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
768 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
769 /* We move this call from a non-trunked to a trunked call */
771 update_max_nontrunk();
775 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer)
780 if (new <= NEW_ALLOW) {
781 /* Look for an existing connection first */
782 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
783 ast_mutex_lock(&iaxsl[x]);
785 /* Look for an exact match */
786 if (match(sin, callno, dcallno, iaxs[x])) {
790 ast_mutex_unlock(&iaxsl[x]);
792 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
793 ast_mutex_lock(&iaxsl[x]);
795 /* Look for an exact match */
796 if (match(sin, callno, dcallno, iaxs[x])) {
800 ast_mutex_unlock(&iaxsl[x]);
803 if ((res < 1) && (new >= NEW_ALLOW)) {
804 gettimeofday(&now, NULL);
805 for (x=1;x<TRUNK_CALL_START;x++) {
806 /* Find first unused call number that hasn't been used in a while */
807 ast_mutex_lock(&iaxsl[x]);
808 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
809 ast_mutex_unlock(&iaxsl[x]);
811 /* We've still got lock held if we found a spot */
812 if (x >= TRUNK_CALL_START) {
813 ast_log(LOG_WARNING, "No more space\n");
816 iaxs[x] = new_iax(sin, lockpeer);
817 ast_mutex_unlock(&iaxsl[x]);
818 update_max_nontrunk();
821 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
822 iaxs[x]->addr.sin_port = sin->sin_port;
823 iaxs[x]->addr.sin_family = sin->sin_family;
824 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
825 iaxs[x]->peercallno = callno;
827 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
828 iaxs[x]->expirey = expirey;
829 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)x);
830 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)x);
831 iaxs[x]->amaflags = amaflags;
832 iaxs[x]->notransfer = notransfer;
833 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
835 ast_log(LOG_WARNING, "Out of resources\n");
843 static void iax2_frame_free(struct iax_frame *fr)
845 if (fr->retrans > -1)
846 ast_sched_del(sched, fr->retrans);
850 static int iax2_queue_frame(int callno, struct ast_frame *f)
853 /* Assumes lock for callno is already held... */
856 if (iaxs[callno] && iaxs[callno]->owner) {
857 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
858 /* Avoid deadlock by pausing and trying again */
859 ast_mutex_unlock(&iaxsl[callno]);
861 ast_mutex_lock(&iaxsl[callno]);
863 ast_queue_frame(iaxs[callno]->owner, f);
864 ast_mutex_unlock(&iaxs[callno]->owner->lock);
873 static void destroy_firmware(struct iax_firmware *cur)
877 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
883 static int try_firmware(char *s)
886 struct iax_firmware *cur;
889 struct ast_iax2_firmware_header *fwh, fwh2;
890 struct MD5Context md5;
891 unsigned char sum[16];
892 res = stat(s, &stbuf);
894 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
897 /* Make sure it's not a directory */
898 if (S_ISDIR(stbuf.st_mode))
900 fd = open(s, O_RDONLY);
902 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
905 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
906 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
910 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
911 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
915 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
916 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
920 if (fwh2.devname[sizeof(fwh2.devname) - 1] || !strlen(fwh2.devname)) {
921 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
925 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
927 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
932 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
934 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
935 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
936 munmap(fwh, stbuf.st_size);
942 if (!strcmp(cur->fwh->devname, fwh->devname)) {
943 /* Found a candidate */
944 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
945 /* The version we have on loaded is older, load this one instead */
947 /* This version is no newer than what we have. Don't worry about it.
948 We'll consider it a proper load anyhow though */
949 munmap(fwh, stbuf.st_size);
956 /* Allocate a new one and link it */
957 cur = malloc(sizeof(struct iax_firmware));
959 memset(cur, 0, sizeof(struct iax_firmware));
961 cur->next = waresl.wares;
967 munmap(cur->fwh, cur->mmaplen);
973 cur->mmaplen = stbuf.st_size;
979 static int iax_check_version(char *dev)
982 struct iax_firmware *cur;
983 if (dev && strlen(dev)) {
984 ast_mutex_lock(&waresl.lock);
987 if (!strcmp(dev, cur->fwh->devname)) {
988 res = ntohs(cur->fwh->version);
993 ast_mutex_unlock(&waresl.lock);
998 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1001 unsigned int bs = desc & 0xff;
1002 unsigned int start = (desc >> 8) & 0xffffff;
1004 struct iax_firmware *cur;
1005 if (dev && strlen(dev) && bs) {
1007 ast_mutex_lock(&waresl.lock);
1010 if (!strcmp(dev, cur->fwh->devname)) {
1011 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1012 if (start < ntohl(cur->fwh->datalen)) {
1013 bytes = ntohl(cur->fwh->datalen) - start;
1016 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1019 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1029 ast_mutex_unlock(&waresl.lock);
1035 static void reload_firmware(void)
1037 struct iax_firmware *cur, *curl, *curp;
1042 /* Mark all as dead */
1043 ast_mutex_lock(&waresl.lock);
1049 /* Now that we've freed them, load the new ones */
1050 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1053 while((de = readdir(fwd))) {
1054 if (de->d_name[0] != '.') {
1055 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1056 if (!try_firmware(fn)) {
1057 if (option_verbose > 1)
1058 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1064 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1066 /* Clean up leftovers */
1078 destroy_firmware(curl);
1083 ast_mutex_unlock(&waresl.lock);
1086 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1088 static int __do_deliver(void *data)
1090 /* Just deliver the packet by using queueing. This is called by
1091 the IAX thread with the iaxsl lock held. */
1092 struct iax_frame *fr = data;
1095 if (iaxs[fr->callno] && !iaxs[fr->callno]->alreadygone) {
1096 if (fr->af.frametype == AST_FRAME_IAX) {
1097 /* We have to treat some of these packets specially because
1098 they're LAG measurement packets */
1099 if (fr->af.subclass == IAX_COMMAND_LAGRQ) {
1100 /* If we got a queued request, build a reply and send it */
1101 fr->af.subclass = IAX_COMMAND_LAGRP;
1102 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
1103 } else if (fr->af.subclass == IAX_COMMAND_LAGRP) {
1104 /* This is a reply we've been given, actually measure the difference */
1105 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
1106 iaxs[fr->callno]->lag = ts - fr->ts;
1109 iax2_queue_frame(fr->callno, &fr->af);
1112 /* Free our iax frame */
1113 iax2_frame_free(fr);
1114 /* And don't run again */
1118 static int do_deliver(void *data)
1120 /* Locking version of __do_deliver */
1121 struct iax_frame *fr = data;
1122 int callno = fr->callno;
1124 ast_mutex_lock(&iaxsl[callno]);
1125 res = __do_deliver(data);
1126 ast_mutex_unlock(&iaxsl[callno]);
1130 static int handle_error(void)
1132 /* XXX Ideally we should figure out why an error occured and then abort those
1133 rather than continuing to try. Unfortunately, the published interface does
1134 not seem to work XXX */
1136 struct sockaddr_in *sin;
1139 struct sock_extended_err e;
1144 m.msg_controllen = sizeof(e);
1146 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1148 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1150 if (m.msg_controllen) {
1151 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1153 ast_log(LOG_WARNING, "Receive error from %s\n", inet_ntoa(sin->sin_addr));
1155 ast_log(LOG_WARNING, "No address detected??\n");
1157 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1164 static int send_packet(struct iax_frame *f)
1167 /* Called with iaxsl held */
1169 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, inet_ntoa(iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1170 /* Don't send if there was an error, but return error instead */
1172 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1175 if (!iaxs[f->callno])
1177 if (iaxs[f->callno]->error)
1181 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1182 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1183 sizeof(iaxs[f->callno]->transfer));
1186 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1187 res = sendto(netsocket, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1188 sizeof(iaxs[f->callno]->addr));
1192 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1200 static int iax2_predestroy(int callno)
1202 struct ast_channel *c;
1203 struct chan_iax2_pvt *pvt;
1204 ast_mutex_lock(&iaxsl[callno]);
1207 ast_mutex_unlock(&iaxsl[callno]);
1210 if (!pvt->alreadygone) {
1211 /* No more pings or lagrq's */
1212 if (pvt->pingid > -1)
1213 ast_sched_del(sched, pvt->pingid);
1214 if (pvt->lagid > -1)
1215 ast_sched_del(sched, pvt->lagid);
1216 if (pvt->autoid > -1)
1217 ast_sched_del(sched, pvt->autoid);
1218 if (pvt->initid > -1)
1219 ast_sched_del(sched, pvt->initid);
1224 pvt->alreadygone = 1;
1228 c->_softhangup |= AST_SOFTHANGUP_DEV;
1230 ast_queue_hangup(c);
1232 ast_mutex_lock(&usecnt_lock);
1235 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1236 ast_mutex_unlock(&usecnt_lock);
1238 ast_mutex_unlock(&iaxsl[callno]);
1239 ast_update_use_count();
1243 static int iax2_predestroy_nolock(int callno)
1246 ast_mutex_unlock(&iaxsl[callno]);
1247 res = iax2_predestroy(callno);
1248 ast_mutex_lock(&iaxsl[callno]);
1252 static void iax2_destroy(int callno)
1254 struct chan_iax2_pvt *pvt;
1255 struct iax_frame *cur;
1256 struct ast_channel *owner;
1259 ast_mutex_lock(&iaxsl[callno]);
1261 gettimeofday(&lastused[callno], NULL);
1268 if (ast_mutex_trylock(&owner->lock)) {
1269 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1270 ast_mutex_unlock(&iaxsl[callno]);
1276 iaxs[callno] = NULL;
1280 /* No more pings or lagrq's */
1281 if (pvt->pingid > -1)
1282 ast_sched_del(sched, pvt->pingid);
1283 if (pvt->lagid > -1)
1284 ast_sched_del(sched, pvt->lagid);
1285 if (pvt->autoid > -1)
1286 ast_sched_del(sched, pvt->autoid);
1287 if (pvt->initid > -1)
1288 ast_sched_del(sched, pvt->initid);
1293 if (pvt->bridgetrans)
1294 ast_translator_free_path(pvt->bridgetrans);
1295 pvt->bridgetrans = NULL;
1298 pvt->alreadygone = 1;
1301 /* If there's an owner, prod it to give up */
1302 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1303 ast_queue_hangup(owner);
1306 for (cur = iaxq.head; cur ; cur = cur->next) {
1307 /* Cancel any pending transmissions */
1308 if (cur->callno == pvt->callno)
1312 pvt->reg->callno = 0;
1318 ast_mutex_unlock(&owner->lock);
1320 ast_mutex_unlock(&iaxsl[callno]);
1321 if (callno & 0x4000)
1324 static void iax2_destroy_nolock(int callno)
1326 /* Actually it's easier to unlock, kill it, and relock */
1327 ast_mutex_unlock(&iaxsl[callno]);
1328 iax2_destroy(callno);
1329 ast_mutex_lock(&iaxsl[callno]);
1332 static int update_packet(struct iax_frame *f)
1334 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1335 struct ast_iax2_full_hdr *fh = f->data;
1336 /* Mark this as a retransmission */
1337 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1339 f->iseqno = iaxs[f->callno]->iseqno;
1340 fh->iseqno = f->iseqno;
1344 static int attempt_transmit(void *data)
1346 /* Attempt to transmit the frame to the remote peer...
1347 Called without iaxsl held. */
1348 struct iax_frame *f = data;
1350 int callno = f->callno;
1351 /* Make sure this call is still active */
1353 ast_mutex_lock(&iaxsl[callno]);
1354 if ((f->callno) && iaxs[f->callno]) {
1355 if ((f->retries < 0) /* Already ACK'd */ ||
1356 (f->retries >= max_retries) /* Too many attempts */) {
1357 /* Record an error if we've transmitted too many times */
1358 if (f->retries >= max_retries) {
1360 /* Transfer timeout */
1361 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1362 } else if (f->final) {
1364 iax2_destroy_nolock(f->callno);
1366 if (iaxs[f->callno]->owner)
1367 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
1368 iaxs[f->callno]->error = ETIMEDOUT;
1369 if (iaxs[f->callno]->owner) {
1370 struct ast_frame fr = { 0, };
1372 fr.frametype = AST_FRAME_CONTROL;
1373 fr.subclass = AST_CONTROL_HANGUP;
1374 iax2_queue_frame(f->callno, &fr);
1376 if (iaxs[f->callno]->reg) {
1377 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1378 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1379 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1381 iax2_destroy_nolock(f->callno);
1388 /* Update it if it needs it */
1390 /* Attempt transmission */
1393 /* Try again later after 10 times as long */
1395 if (f->retrytime > MAX_RETRY_TIME)
1396 f->retrytime = MAX_RETRY_TIME;
1397 /* Transfer messages max out at one second */
1398 if (f->transfer && (f->retrytime > 1000))
1399 f->retrytime = 1000;
1400 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1403 /* Make sure it gets freed */
1408 ast_mutex_unlock(&iaxsl[callno]);
1409 /* Do not try again */
1411 /* Don't attempt delivery, just remove it from the queue */
1412 ast_mutex_lock(&iaxq.lock);
1414 f->prev->next = f->next;
1416 iaxq.head = f->next;
1418 f->next->prev = f->prev;
1420 iaxq.tail = f->prev;
1422 ast_mutex_unlock(&iaxq.lock);
1424 /* Free the IAX frame */
1430 static int iax2_set_jitter(int fd, int argc, char *argv[])
1432 if ((argc != 4) && (argc != 5))
1433 return RESULT_SHOWUSAGE;
1435 max_jitter_buffer = atoi(argv[3]);
1436 if (max_jitter_buffer < 0)
1437 max_jitter_buffer = 0;
1440 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1441 if (iaxs[atoi(argv[3])]) {
1442 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1443 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1444 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1446 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1448 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1451 return RESULT_SUCCESS;
1454 static char jitter_usage[] =
1455 "Usage: iax set jitter [callid] <value>\n"
1456 " If used with a callid, it sets the jitter buffer to the given static\n"
1457 "value (until its next calculation). If used without a callid, the value is used\n"
1458 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1459 "buffer size is reduced.";
1461 static int iax2_show_stats(int fd, int argc, char *argv[])
1463 struct iax_frame *cur;
1464 int cnt = 0, dead=0, final=0;
1466 return RESULT_SHOWUSAGE;
1467 for (cur = iaxq.head; cur ; cur = cur->next) {
1468 if (cur->retries < 0)
1474 ast_cli(fd, " IAX Statistics\n");
1475 ast_cli(fd, "---------------------\n");
1476 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1477 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1478 return RESULT_SUCCESS;
1481 static int iax2_show_cache(int fd, int argc, char *argv[])
1483 struct iax2_dpcache *dp;
1484 char tmp[1024], *pc;
1488 gettimeofday(&tv, NULL);
1489 ast_mutex_lock(&dpcache_lock);
1491 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1493 s = dp->expirey.tv_sec - tv.tv_sec;
1495 if (dp->flags & CACHE_FLAG_EXISTS)
1496 strcat(tmp, "EXISTS|");
1497 if (dp->flags & CACHE_FLAG_NONEXISTANT)
1498 strcat(tmp, "NONEXISTANT|");
1499 if (dp->flags & CACHE_FLAG_CANEXIST)
1500 strcat(tmp, "CANEXIST|");
1501 if (dp->flags & CACHE_FLAG_PENDING)
1502 strcat(tmp, "PENDING|");
1503 if (dp->flags & CACHE_FLAG_TIMEOUT)
1504 strcat(tmp, "TIMEOUT|");
1505 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1506 strcat(tmp, "TRANSMITTED|");
1507 if (dp->flags & CACHE_FLAG_MATCHMORE)
1508 strcat(tmp, "MATCHMORE|");
1509 if (dp->flags & CACHE_FLAG_UNKNOWN)
1510 strcat(tmp, "UNKNOWN|");
1511 /* Trim trailing pipe */
1513 tmp[strlen(tmp) - 1] = '\0';
1515 strcpy(tmp, "(none)");
1517 pc = strchr(dp->peercontext, '@');
1519 pc = dp->peercontext;
1522 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1523 if (dp->waiters[x] > -1)
1526 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1528 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1531 ast_mutex_unlock(&dpcache_lock);
1532 return RESULT_SUCCESS;
1535 static char show_stats_usage[] =
1536 "Usage: iax show stats\n"
1537 " Display statistics on IAX channel driver.\n";
1540 static char show_cache_usage[] =
1541 "Usage: iax show cache\n"
1542 " Display currently cached IAX Dialplan results.\n";
1544 static struct ast_cli_entry cli_set_jitter =
1545 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1547 static struct ast_cli_entry cli_show_stats =
1548 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1550 static struct ast_cli_entry cli_show_cache =
1551 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1553 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p);
1555 #ifdef BRIDGE_OPTIMIZATION
1556 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1558 static int forward_delivery(struct iax_frame *fr)
1560 struct chan_iax2_pvt *p1, *p2;
1561 p1 = iaxs[fr->callno];
1562 p2 = iaxs[p1->bridgecallno];
1567 /* Fix relative timestamp */
1568 fr->ts = calc_fakestamp(p1, p2, fr->ts);
1569 /* Now just send it send on the 2nd one
1570 with adjusted timestamp */
1571 return iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
1575 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory)
1578 int drops[MEMORY_SIZE];
1579 int min, max=0, maxone=0,y,z, match;
1580 /* ms is a measure of the "lateness" of the packet relative to the first
1581 packet we received, which always has a lateness of 1. Called by
1582 IAX thread, with iaxsl lock held. */
1583 ms = calc_rxstamp(iaxs[fr->callno]) - fr->ts;
1586 /* What likely happened here is that our counter has circled but we haven't
1587 gotten the update from the main packet. We'll just pretend that we did, and
1588 update the timestamp appropriately. */
1594 /* We got this packet out of order. Lets add 65536 to it to bring it into our new
1600 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
1601 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
1602 fr->af.delivery.tv_sec += fr->ts / 1000;
1603 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
1604 if (fr->af.delivery.tv_usec >= 1000000) {
1605 fr->af.delivery.tv_usec -= 1000000;
1606 fr->af.delivery.tv_sec += 1;
1610 /* Rotate our history queue of "lateness". Don't worry about those initial
1611 zeros because the first entry will always be zero */
1612 if (updatehistory) {
1613 for (x=0;x<MEMORY_SIZE - 1;x++)
1614 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
1615 /* Add a history entry for this one */
1616 iaxs[fr->callno]->history[x] = ms;
1619 /* Initialize the minimum to reasonable values. It's too much
1620 work to do the same for the maximum, repeatedly */
1621 min=iaxs[fr->callno]->history[0];
1622 for (z=0;z < iax2_dropcount + 1;z++) {
1623 /* Start very optimistic ;-) */
1625 for (x=0;x<MEMORY_SIZE;x++) {
1626 if (max < iaxs[fr->callno]->history[x]) {
1627 /* We have a candidate new maximum value. Make
1628 sure it's not in our drop list */
1630 for (y=0;!match && (y<z);y++)
1631 match |= (drops[y] == x);
1633 /* It's not in our list, use it as the new maximum */
1634 max = iaxs[fr->callno]->history[x];
1640 /* On our first pass, find the minimum too */
1641 if (min > iaxs[fr->callno]->history[x])
1642 min = iaxs[fr->callno]->history[x];
1649 /* Just for reference, keep the "jitter" value, the difference between the
1650 earliest and the latest. */
1651 iaxs[fr->callno]->jitter = max - min;
1653 /* IIR filter for keeping track of historic jitter, but always increase
1654 historic jitter immediately for increase */
1656 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
1657 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
1659 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
1660 iaxs[fr->callno]->historicjitter;
1662 /* If our jitter buffer is too big (by a significant margin), then we slowly
1663 shrink it by about 1 ms each time to avoid letting the change be perceived */
1664 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
1665 iaxs[fr->callno]->jitterbuffer -= 2;
1669 /* Constrain our maximum jitter buffer appropriately */
1670 if (max > min + maxjitterbuffer) {
1672 ast_log(LOG_DEBUG, "Constraining buffer from %d to %d + %d\n", max, min , maxjitterbuffer);
1673 max = min + maxjitterbuffer;
1677 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
1678 buffer immediately to accomodate it (and a little more). */
1679 if (max > iaxs[fr->callno]->jitterbuffer)
1680 iaxs[fr->callno]->jitterbuffer = max
1681 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
1685 ast_log(LOG_DEBUG, "min = %d, max = %d, jb = %d, lateness = %d\n", min, max, iaxs[fr->callno]->jitterbuffer, ms);
1687 /* Subtract the lateness from our jitter buffer to know how long to wait
1688 before sending our packet. */
1689 ms = iaxs[fr->callno]->jitterbuffer - ms;
1691 if (!use_jitterbuffer)
1694 /* If the caller just wanted us to update, return now */
1700 ast_log(LOG_DEBUG, "Calculated ms is %d\n", ms);
1701 /* Don't deliver it more than 4 ms late */
1702 if ((ms > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
1706 ast_log(LOG_DEBUG, "Dropping voice packet since %d ms is, too old\n", ms);
1707 /* Free our iax frame */
1708 iax2_frame_free(fr);
1712 ast_log(LOG_DEBUG, "Scheduling delivery in %d ms\n", ms);
1713 fr->retrans = ast_sched_add(sched, ms, do_deliver, fr);
1718 static int iax2_transmit(struct iax_frame *fr)
1720 /* Lock the queue and place this packet at the end */
1723 /* By setting this to 0, the network thread will send it for us, and
1724 queue retransmission if necessary */
1726 ast_mutex_lock(&iaxq.lock);
1733 iaxq.tail->next = fr;
1734 fr->prev = iaxq.tail;
1738 ast_mutex_unlock(&iaxq.lock);
1739 /* Wake up the network thread */
1740 pthread_kill(netthreadid, SIGURG);
1746 static int iax2_digit(struct ast_channel *c, char digit)
1748 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
1751 static int iax2_sendtext(struct ast_channel *c, char *text)
1754 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_TEXT,
1755 0, 0, text, strlen(text) + 1, -1);
1758 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
1760 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
1763 static int iax2_sendhtml(struct ast_channel *c, int subclass, char *data, int datalen)
1765 return send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
1768 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
1770 unsigned short callno = PTR_TO_CALLNO(newchan->pvt->pvt);
1771 ast_mutex_lock(&iaxsl[callno]);
1773 iaxs[callno]->owner = newchan;
1775 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
1776 ast_mutex_unlock(&iaxsl[callno]);
1780 #ifdef MYSQL_FRIENDS
1782 static void mysql_update_peer(char *peer, struct sockaddr_in *sin)
1784 if (mysql && (strlen(peer) < 128)) {
1788 name = alloca(strlen(peer) * 2 + 1);
1790 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1791 snprintf(query, sizeof(query), "UPDATE iaxfriends SET ipaddr=\"%s\", port=\"%d\", regseconds=\"%ld\" WHERE name=\"%s\"",
1792 inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), nowtime, name);
1793 ast_mutex_lock(&mysqllock);
1794 if (mysql_real_query(mysql, query, strlen(query)))
1795 ast_log(LOG_WARNING, "Unable to update database\n");
1797 ast_mutex_unlock(&mysqllock);
1801 static struct iax2_peer *mysql_peer(char *peer)
1803 struct iax2_peer *p;
1806 p = malloc(sizeof(struct iax2_peer));
1807 memset(p, 0, sizeof(struct iax2_peer));
1808 if (mysql && (strlen(peer) < 128)) {
1813 time_t regseconds, nowtime;
1815 MYSQL_FIELD *fields;
1817 name = alloca(strlen(peer) * 2 + 1);
1818 mysql_real_escape_string(mysql, name, peer, strlen(peer));
1819 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1820 ast_mutex_lock(&mysqllock);
1821 mysql_query(mysql, query);
1822 if ((result = mysql_store_result(mysql))) {
1823 if ((rowval = mysql_fetch_row(result))) {
1824 numfields = mysql_num_fields(result);
1825 fields = mysql_fetch_fields(result);
1827 for (x=0;x<numfields;x++) {
1829 if (!strcasecmp(fields[x].name, "secret")) {
1830 strncpy(p->secret, rowval[x], sizeof(p->secret));
1831 } else if (!strcasecmp(fields[x].name, "context")) {
1832 strncpy(p->context, rowval[x], sizeof(p->context) - 1);
1833 } else if (!strcasecmp(fields[x].name, "ipaddr")) {
1834 inet_aton(rowval[x], &p->addr.sin_addr);
1835 } else if (!strcasecmp(fields[x].name, "port")) {
1836 if (sscanf(rowval[x], "%i", &port) != 1)
1838 p->addr.sin_port = htons(port);
1839 } else if (!strcasecmp(fields[x].name, "regseconds")) {
1840 if (sscanf(rowval[x], "%li", ®seconds) != 1)
1846 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE)
1847 memset(&p->addr, 0, sizeof(p->addr));
1849 mysql_free_result(result);
1852 ast_mutex_unlock(&mysqllock);
1858 strncpy(p->name, peer, sizeof(p->name) - 1);
1862 p->capability = iax2_capability;
1863 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1867 static struct iax2_user *mysql_user(char *user)
1869 struct iax2_user *p;
1870 struct iax2_context *con;
1873 p = malloc(sizeof(struct iax2_user));
1874 memset(p, 0, sizeof(struct iax2_user));
1875 con = malloc(sizeof(struct iax2_context));
1876 memset(con, 0, sizeof(struct iax2_context));
1877 strcpy(con->context, "default");
1879 if (mysql && (strlen(user) < 128)) {
1884 MYSQL_FIELD *fields;
1886 name = alloca(strlen(user) * 2 + 1);
1887 mysql_real_escape_string(mysql, name, user, strlen(user));
1888 snprintf(query, sizeof(query), "SELECT * FROM iaxfriends WHERE name=\"%s\"", name);
1889 ast_mutex_lock(&mysqllock);
1890 mysql_query(mysql, query);
1891 if ((result = mysql_store_result(mysql))) {
1892 if ((rowval = mysql_fetch_row(result))) {
1893 numfields = mysql_num_fields(result);
1894 fields = mysql_fetch_fields(result);
1896 for (x=0;x<numfields;x++) {
1898 if (!strcasecmp(fields[x].name, "secret")) {
1899 strncpy(p->secret, rowval[x], sizeof(p->secret));
1900 } else if (!strcasecmp(fields[x].name, "context")) {
1901 strncpy(p->contexts->context, rowval[x], sizeof(p->contexts->context) - 1);
1906 mysql_free_result(result);
1909 ast_mutex_unlock(&mysqllock);
1917 strncpy(p->name, user, sizeof(p->name) - 1);
1919 p->capability = iax2_capability;
1920 p->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
1924 #endif /* MYSQL_FRIENDS */
1926 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, int *maxtime, char *peer, char *context, int *trunk, int *notransfer, char *secret, int seclen)
1928 struct ast_hostent ahp; struct hostent *hp;
1929 struct iax2_peer *p;
1937 sin->sin_family = AF_INET;
1938 ast_mutex_lock(&peerl.lock);
1941 if (!strcasecmp(p->name, peer)) {
1946 ast_mutex_unlock(&peerl.lock);
1947 #ifdef MYSQL_FRIENDS
1949 p = mysql_peer(peer);
1953 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
1954 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
1956 *sendani = p->sendani; /* Whether we transmit ANI */
1958 *maxtime = p->maxms; /* Max time they should take */
1960 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
1964 *capability = p->capability;
1966 strncpy(secret, p->secret, seclen);
1967 if (p->addr.sin_addr.s_addr) {
1968 sin->sin_addr = p->addr.sin_addr;
1969 sin->sin_port = p->addr.sin_port;
1971 sin->sin_addr = p->defaddr.sin_addr;
1972 sin->sin_port = p->defaddr.sin_port;
1975 *notransfer=p->notransfer;
1983 hp = ast_gethostbyname(peer, &ahp);
1985 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
1986 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
1989 ast_log(LOG_WARNING, "No such host: %s\n", peer);
1999 static int auto_congest(void *nothing)
2001 int callno = PTR_TO_CALLNO(nothing);
2002 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2003 ast_mutex_lock(&iaxsl[callno]);
2005 iaxs[callno]->initid = -1;
2006 iax2_queue_frame(callno, &f);
2007 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2009 ast_mutex_unlock(&iaxsl[callno]);
2013 static unsigned int iax2_datetime(void)
2019 localtime_r(&t, &tm);
2020 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2021 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2022 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2023 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2024 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2025 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2029 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2031 struct sockaddr_in sin;
2036 char *secret = NULL;
2039 char *l=NULL, *n=NULL;
2040 struct iax_ie_data ied;
2041 char myrdest [5] = "s";
2042 char context[AST_MAX_EXTENSION] ="";
2043 char *portno = NULL;
2045 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2047 char storedsecret[80];
2048 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2049 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2052 strncpy(host, dest, sizeof(host)-1);
2054 strsep(&stringp, "/");
2055 /* If no destination extension specified, use 's' */
2056 rdest = strsep(&stringp, "/");
2060 /* Check for trailing options */
2061 opts = strsep(&stringp, "/");
2066 strsep(&stringp, "@");
2067 rcontext = strsep(&stringp, "@");
2069 strsep(&stringp, "@");
2070 username = strsep(&stringp, "@");
2072 /* Really the second argument is the host, not the username */
2080 username = strsep(&stringp, ":");
2081 secret = strsep(&stringp, ":");
2084 if (strsep(&stringp, ":")) {
2086 strsep(&stringp, ":");
2087 portno = strsep(&stringp, ":");
2089 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, storedsecret, sizeof(storedsecret) - 1)) {
2090 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2093 /* Keep track of the context for outgoing calls too */
2094 strncpy(c->context, context, sizeof(c->context) - 1);
2096 sin.sin_port = htons(atoi(portno));
2099 strncpy(cid, c->callerid, sizeof(cid) - 1);
2100 ast_callerid_parse(cid, &n, &l);
2102 ast_shrink_phone_number(l);
2104 /* Now build request */
2105 memset(&ied, 0, sizeof(ied));
2106 /* On new call, first IE MUST be IAX version of caller */
2107 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2108 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2109 if (strchr(opts, 'a')) {
2110 /* Request auto answer */
2111 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2114 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2116 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2117 if (iaxs[callno]->sendani && c->ani) {
2119 strncpy(cid, c->ani, sizeof(cid) - 1);
2120 ast_callerid_parse(cid, &n, &l);
2122 ast_shrink_phone_number(l);
2123 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, l);
2126 if (c->language && strlen(c->language))
2127 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2128 if (c->dnid && strlen(c->dnid))
2129 iax_ie_append_str(&ied, IAX_IE_DNID, c->dnid);
2131 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2133 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2134 if (!secret && strlen(storedsecret))
2135 secret = storedsecret;
2136 ast_mutex_lock(&iaxsl[callno]);
2137 if (strlen(c->context))
2138 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2140 if (secret[0] == '[') {
2141 /* This is an RSA key, not a normal secret */
2142 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2143 if (strlen(iaxs[callno]->outkey)) {
2144 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2147 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2149 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2150 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2151 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2152 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime());
2153 /* Transmit the string in a "NEW" request */
2155 /* XXX We have no equivalent XXX */
2156 if (option_verbose > 2)
2157 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2159 if (iaxs[callno]->maxtime) {
2160 /* Initialize pingtime and auto-congest time */
2161 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2162 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2164 send_command(iaxs[callno], AST_FRAME_IAX,
2165 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2166 ast_mutex_unlock(&iaxsl[callno]);
2167 ast_setstate(c, AST_STATE_RINGING);
2171 static int iax2_hangup(struct ast_channel *c)
2173 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2175 ast_mutex_lock(&iaxsl[callno]);
2176 if (callno && iaxs[callno]) {
2177 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2178 alreadygone = iaxs[callno]->alreadygone;
2179 /* Send the hangup unless we have had a transmission error or are already gone */
2180 if (!iaxs[callno]->error && !alreadygone)
2181 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, NULL, 0, -1);
2182 /* Explicitly predestroy it */
2183 iax2_predestroy_nolock(callno);
2184 /* If we were already gone to begin with, destroy us now */
2186 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2187 iax2_destroy_nolock(callno);
2190 ast_mutex_unlock(&iaxsl[callno]);
2191 if (option_verbose > 2)
2192 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2196 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2198 struct ast_option_header *h;
2200 h = malloc(datalen + sizeof(struct ast_option_header));
2202 h->flag = AST_OPTION_FLAG_REQUEST;
2203 h->option = htons(option);
2204 memcpy(h->data, data, datalen);
2205 res = send_command_locked(PTR_TO_CALLNO(c->pvt->pvt), AST_FRAME_CONTROL,
2206 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2210 ast_log(LOG_WARNING, "Out of memory\n");
2214 static struct ast_frame *iax2_read(struct ast_channel *c)
2216 static struct ast_frame f = { AST_FRAME_NULL, };
2217 ast_log(LOG_NOTICE, "I should never be called!\n");
2221 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2224 struct iax_ie_data ied0;
2225 struct iax_ie_data ied1;
2226 unsigned int transferid = rand();
2227 memset(&ied0, 0, sizeof(ied0));
2228 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2229 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2230 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2232 memset(&ied1, 0, sizeof(ied1));
2233 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2234 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2235 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2237 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2240 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
2243 iaxs[callno0]->transferring = TRANSFER_BEGIN;
2244 iaxs[callno1]->transferring = TRANSFER_BEGIN;
2248 static void lock_both(unsigned short callno0, unsigned short callno1)
2250 ast_mutex_lock(&iaxsl[callno0]);
2251 while (ast_mutex_trylock(&iaxsl[callno1])) {
2252 ast_mutex_unlock(&iaxsl[callno0]);
2254 ast_mutex_lock(&iaxsl[callno0]);
2258 static void unlock_both(unsigned short callno0, unsigned short callno1)
2260 ast_mutex_unlock(&iaxsl[callno1]);
2261 ast_mutex_unlock(&iaxsl[callno0]);
2264 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2266 struct ast_channel *cs[3];
2267 struct ast_channel *who;
2270 int transferstarted=0;
2271 struct ast_frame *f;
2272 unsigned short callno0 = PTR_TO_CALLNO(c0->pvt->pvt);
2273 unsigned short callno1 = PTR_TO_CALLNO(c1->pvt->pvt);
2274 struct timeval waittimer = {0, 0}, tv;
2276 lock_both(callno0, callno1);
2277 /* Put them in native bridge mode */
2278 iaxs[callno0]->bridgecallno = callno1;
2279 iaxs[callno1]->bridgecallno = callno0;
2280 unlock_both(callno0, callno1);
2282 /* If not, try to bridge until we can execute a transfer, if we can */
2285 for (/* ever */;;) {
2286 /* Check in case we got masqueraded into */
2287 if ((c0->type != type) || (c1->type != type)) {
2288 if (option_verbose > 2)
2289 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
2290 /* Remove from native mode */
2291 if (c0->type == type) {
2292 ast_mutex_lock(&iaxsl[callno0]);
2293 iaxs[callno0]->bridgecallno = 0;
2294 ast_mutex_unlock(&iaxsl[callno0]);
2296 if (c1->type == type) {
2297 ast_mutex_lock(&iaxsl[callno1]);
2298 iaxs[callno1]->bridgecallno = 0;
2299 ast_mutex_unlock(&iaxsl[callno1]);
2303 if (c0->nativeformats != c1->nativeformats) {
2304 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs, can't native bridge...\n");
2305 /* Remove from native mode */
2306 lock_both(callno0, callno1);
2307 iaxs[callno0]->bridgecallno = 0;
2308 iaxs[callno1]->bridgecallno = 0;
2309 unlock_both(callno0, callno1);
2312 /* check if transfered and if we really want native bridging */
2313 if (!transferstarted && !iaxs[callno0]->notransfer && !iaxs[callno1]->notransfer) {
2314 /* Try the transfer */
2315 if (iax2_start_transfer(callno0, callno1))
2316 ast_log(LOG_WARNING, "Unable to start the transfer\n");
2317 transferstarted = 1;
2319 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
2320 /* Call has been transferred. We're no longer involved */
2321 gettimeofday(&tv, NULL);
2322 if (!waittimer.tv_sec && !waittimer.tv_usec) {
2323 waittimer.tv_sec = tv.tv_sec;
2324 waittimer.tv_usec = tv.tv_usec;
2325 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
2326 c0->_softhangup |= AST_SOFTHANGUP_DEV;
2327 c1->_softhangup |= AST_SOFTHANGUP_DEV;
2335 who = ast_waitfor_n(cs, 2, &to);
2337 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
2350 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2356 if ((f->frametype == AST_FRAME_VOICE) ||
2357 (f->frametype == AST_FRAME_TEXT) ||
2358 (f->frametype == AST_FRAME_VIDEO) ||
2359 (f->frametype == AST_FRAME_IMAGE) ||
2360 (f->frametype == AST_FRAME_DTMF)) {
2361 if ((f->frametype == AST_FRAME_DTMF) &&
2362 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2364 if ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2367 /* Take out of conference mode */
2369 /* Remove from native mode */
2375 if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2379 /* Remove from native mode */
2386 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2388 ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2400 /* Swap who gets priority */
2405 lock_both(callno0, callno1);
2406 iaxs[callno0]->bridgecallno = 0;
2407 iaxs[callno1]->bridgecallno = 0;
2408 unlock_both(callno0, callno1);
2412 static int iax2_answer(struct ast_channel *c)
2414 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2416 ast_log(LOG_DEBUG, "Answering\n");
2417 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
2420 static int iax2_indicate(struct ast_channel *c, int condition)
2422 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2424 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
2425 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, NULL, 0, -1);
2428 static int iax2_transfer(struct ast_channel *c, char *dest)
2430 unsigned short callno = PTR_TO_CALLNO(c->pvt->pvt);
2431 struct iax_ie_data ied;
2432 char tmp[256] = "", *context;
2433 strncpy(tmp, dest, sizeof(tmp) - 1);
2434 context = strchr(tmp, '@');
2439 memset(&ied, 0, sizeof(ied));
2440 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
2442 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
2444 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
2445 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
2449 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
2451 static int iax2_getpeertrunk(struct sockaddr_in sin)
2453 struct iax2_peer *peer;
2455 ast_mutex_lock(&peerl.lock);
2458 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
2459 (peer->addr.sin_port == sin.sin_port)) {
2465 ast_mutex_unlock(&peerl.lock);
2469 static struct ast_channel *ast_iax2_new(struct chan_iax2_pvt *i, int state, int capability)
2471 struct ast_channel *tmp;
2472 tmp = ast_channel_alloc(1);
2474 if (strlen(i->username))
2475 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s@%s]/%d", i->username, i->host, i->callno);
2477 snprintf(tmp->name, sizeof(tmp->name), "IAX2[%s]/%d", i->host, i->callno);
2479 /* We can support any format by default, until we get restricted */
2480 tmp->nativeformats = capability;
2481 tmp->readformat = 0;
2482 tmp->writeformat = 0;
2483 tmp->pvt->pvt = CALLNO_TO_PTR(i->callno);
2484 tmp->pvt->send_digit = iax2_digit;
2485 tmp->pvt->send_text = iax2_sendtext;
2486 tmp->pvt->send_image = iax2_sendimage;
2487 tmp->pvt->send_html = iax2_sendhtml;
2488 tmp->pvt->call = iax2_call;
2489 tmp->pvt->hangup = iax2_hangup;
2490 tmp->pvt->answer = iax2_answer;
2491 tmp->pvt->read = iax2_read;
2492 tmp->pvt->write = iax2_write;
2493 tmp->pvt->write_video = iax2_write;
2494 tmp->pvt->indicate = iax2_indicate;
2495 tmp->pvt->setoption = iax2_setoption;
2496 tmp->pvt->bridge = iax2_bridge;
2497 tmp->pvt->transfer = iax2_transfer;
2498 if (strlen(i->callerid))
2499 tmp->callerid = strdup(i->callerid);
2501 tmp->ani = strdup(i->ani);
2502 if (strlen(i->language))
2503 strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2504 if (strlen(i->dnid))
2505 tmp->dnid = strdup(i->dnid);
2506 if (strlen(i->accountcode))
2507 strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2509 tmp->amaflags = i->amaflags;
2510 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2511 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2512 tmp->adsicpe = i->peeradsicpe;
2513 tmp->pvt->fixup = iax2_fixup;
2515 i->capability = capability;
2516 ast_setstate(tmp, state);
2517 ast_mutex_lock(&usecnt_lock);
2519 ast_mutex_unlock(&usecnt_lock);
2520 ast_update_use_count();
2521 if (state != AST_STATE_DOWN) {
2522 if (ast_pbx_start(tmp)) {
2523 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2532 static unsigned int calc_txpeerstamp(struct iax2_peer *peer)
2535 unsigned int mssincetx;
2537 gettimeofday(&tv, NULL);
2538 mssincetx = (tv.tv_sec - peer->lasttxtime.tv_sec) * 1000 + (tv.tv_usec - peer->lasttxtime.tv_usec) / 1000;
2539 if (mssincetx > 5000) {
2540 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
2541 peer->txtrunktime.tv_sec = tv.tv_sec;
2542 peer->txtrunktime.tv_usec = tv.tv_usec;
2544 /* Update last transmit time now */
2545 peer->lasttxtime.tv_sec = tv.tv_sec;
2546 peer->lasttxtime.tv_usec = tv.tv_usec;
2548 /* Calculate ms offset */
2549 ms = (tv.tv_sec - peer->txtrunktime.tv_sec) * 1000 + (tv.tv_usec - peer->txtrunktime.tv_usec) / 1000;
2551 /* We never send the same timestamp twice, so fudge a little if we must */
2552 if (ms == peer->lastsent)
2553 ms = peer->lastsent + 1;
2554 peer->lastsent = ms;
2558 static unsigned int fix_peerts(struct iax2_peer *peer, int callno, unsigned int ts)
2560 long ms; /* NOT unsigned */
2561 if (!iaxs[callno]->rxcore.tv_sec && !iaxs[callno]->rxcore.tv_usec) {
2562 /* Initialize rxcore time if appropriate */
2563 gettimeofday(&iaxs[callno]->rxcore, NULL);
2564 /* Round to nearest 20ms */
2565 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
2567 /* Calculate difference between trunk and channel */
2568 ms = (peer->rxtrunktime.tv_sec - iaxs[callno]->rxcore.tv_sec) * 1000 +
2569 (peer->rxtrunktime.tv_usec - iaxs[callno]->rxcore.tv_usec) / 1000;
2570 /* Return as the sum of trunk time and the difference between trunk and real time */
2574 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
2580 struct timeval *delivery = NULL;
2582 if (f->frametype == AST_FRAME_VOICE) {
2584 delivery = &f->delivery;
2585 } else if (f->frametype == AST_FRAME_IAX) {
2589 if (!p->offset.tv_sec && !p->offset.tv_usec) {
2590 gettimeofday(&p->offset, NULL);
2591 /* Round to nearest 20ms */
2592 p->offset.tv_usec -= p->offset.tv_usec % 20000;
2594 /* If the timestamp is specified, just send it as is */
2597 if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
2598 ms = (delivery->tv_sec - p->offset.tv_sec) * 1000 + (delivery->tv_usec - p->offset.tv_usec) / 1000;
2600 gettimeofday(&tv, NULL);
2601 ms = (tv.tv_sec - p->offset.tv_sec) * 1000 + (tv.tv_usec - p->offset.tv_usec) / 1000;
2605 /* On a voice frame, use predicted values if appropriate */
2606 if (abs(ms - p->nextpred) <= 640) {
2608 p->nextpred = f->samples / 8;
2613 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinkign) if appropriate unless
2614 it's a genuine frame */
2616 if (ms <= p->lastsent)
2617 ms = p->lastsent + 3;
2618 } else if (abs(ms - p->lastsent) <= 640) {
2619 ms = p->lastsent + 3;
2625 p->nextpred = p->nextpred + f->samples / 8;
2627 printf("TS: %s - %dms\n", voice ? "Audio" : "Control", ms);
2632 #ifdef BRIDGE_OPTIMIZATION
2633 static unsigned int calc_fakestamp(struct chan_iax2_pvt *p1, struct chan_iax2_pvt *p2, unsigned int fakets)
2636 /* Receive from p1, send to p2 */
2638 /* Setup rxcore if necessary on outgoing channel */
2639 if (!p1->rxcore.tv_sec && !p1->rxcore.tv_usec)
2640 gettimeofday(&p1->rxcore, NULL);
2642 /* Setup txcore if necessary on outgoing channel */
2643 if (!p2->offset.tv_sec && !p2->offset.tv_usec)
2644 gettimeofday(&p2->offset, NULL);
2646 /* Now, ts is the timestamp of the original packet in the orignal context.
2647 Adding rxcore to it gives us when we would want the packet to be delivered normally.
2648 Subtracting txcore of the outgoing channel gives us what we'd expect */
2650 ms = (p1->rxcore.tv_sec - p2->offset.tv_sec) * 1000 + (p1->rxcore.tv_usec - p2->offset.tv_usec) / 1000;
2652 if (fakets <= p2->lastsent)
2653 fakets = p2->lastsent + 1;
2654 p2->lastsent = fakets;
2659 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p)
2661 /* Returns where in "receive time" we are */
2664 /* Setup rxcore if necessary */
2665 if (!p->rxcore.tv_sec && !p->rxcore.tv_usec)
2666 gettimeofday(&p->rxcore, NULL);
2668 gettimeofday(&tv, NULL);
2669 ms = (tv.tv_sec - p->rxcore.tv_sec) * 1000 + (tv.tv_usec - p->rxcore.tv_usec) / 1000;
2673 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
2675 /* Queue a packet for delivery on a given private structure. Use "ts" for
2676 timestamp, or calculate if ts is 0. Send immediately without retransmission
2677 or delayed, with retransmission */
2678 struct ast_iax2_full_hdr *fh;
2679 struct ast_iax2_mini_hdr *mh;
2680 struct ast_iax2_video_hdr *vh;
2682 struct iax_frame fr2;
2683 unsigned char buffer[4096];
2685 struct iax_frame *fr;
2688 unsigned int lastsent;
2692 ast_log(LOG_WARNING, "No private structure for packet?\n");
2696 lastsent = pvt->lastsent;
2698 /* Calculate actual timestamp */
2699 fts = calc_timestamp(pvt, ts, f);
2701 if ((pvt->trunk || ((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)))
2702 /* High two bits are the same on timestamp, or sending on a trunk */ &&
2703 (f->frametype == AST_FRAME_VOICE)
2704 /* is a voice frame */ &&
2705 (f->subclass == pvt->svoiceformat)
2706 /* is the same type */ ) {
2707 /* Force immediate rather than delayed transmission */
2709 /* Mark that mini-style frame is appropriate */
2712 if (((fts & 0xFFFF8000L) == (lastsent & 0xFFFF8000L)) &&
2713 (f->frametype == AST_FRAME_VIDEO) &&
2714 ((f->subclass & ~0x1) == pvt->svideoformat)) {
2718 /* Allocate an iax_frame */
2722 fr = iax_frame_new(DIRECTION_OUTGRESS, f->datalen);
2724 ast_log(LOG_WARNING, "Out of memory\n");
2727 /* Copy our prospective frame into our immediate or retransmitted wrapper */
2728 iax_frame_wrap(fr, f);
2732 ast_log(LOG_WARNING, "timestamp is 0?\n");
2734 iax2_frame_free(fr);
2737 fr->callno = pvt->callno;
2738 fr->transfer = transfer;
2741 /* We need a full frame */
2745 fr->oseqno = pvt->oseqno++;
2746 fr->iseqno = pvt->iseqno;
2747 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
2748 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
2749 fh->ts = htonl(fr->ts);
2750 fh->oseqno = fr->oseqno;
2754 fh->iseqno = fr->iseqno;
2755 /* Keep track of the last thing we've acknowledged */
2757 pvt->aseqno = fr->iseqno;
2758 fh->type = fr->af.frametype & 0xFF;
2759 if (fr->af.frametype == AST_FRAME_VIDEO)
2760 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
2762 fh->csub = compress_subclass(fr->af.subclass);
2764 fr->dcallno = pvt->transfercallno;
2766 fr->dcallno = pvt->peercallno;
2767 fh->dcallno = htons(fr->dcallno);
2768 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
2771 /* Retry after 2x the ping time has passed */
2772 fr->retrytime = pvt->pingtime * 2;
2773 if (fr->retrytime < MIN_RETRY_TIME)
2774 fr->retrytime = MIN_RETRY_TIME;
2775 if (fr->retrytime > MAX_RETRY_TIME)
2776 fr->retrytime = MAX_RETRY_TIME;
2777 /* Acks' don't get retried */
2778 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
2780 else if (f->frametype == AST_FRAME_VOICE)
2781 pvt->svoiceformat = f->subclass;
2782 else if (f->frametype == AST_FRAME_VIDEO)
2783 pvt->svideoformat = f->subclass & ~0x1;
2785 res = send_packet(fr);
2787 res = iax2_transmit(fr);
2790 /* Queue for transmission in a meta frame */
2791 if ((sizeof(pvt->trunkdata) - pvt->trunkdatalen) >= fr->af.datalen) {
2792 memcpy(pvt->trunkdata + pvt->trunkdatalen, fr->af.data, fr->af.datalen);
2793 pvt->trunkdatalen += fr->af.datalen;
2795 pvt->trunkerror = 0;
2797 if (!pvt->trunkerror)
2798 ast_log(LOG_WARNING, "Out of trunk data space on call number %d, dropping\n", pvt->callno);
2799 pvt->trunkerror = 1;
2802 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
2803 /* Video frame have no sequence number */
2806 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
2808 vh->callno = htons(0x8000 | fr->callno);
2809 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
2810 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
2813 res = send_packet(fr);
2815 /* Mini-frames have no sequence number */
2818 /* Mini frame will do */
2819 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
2820 mh->callno = htons(fr->callno);
2821 mh->ts = htons(fr->ts & 0xFFFF);
2822 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
2825 res = send_packet(fr);
2833 static int iax2_show_users(int fd, int argc, char *argv[])
2835 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s\n"
2836 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s\n"
2837 struct iax2_user *user;
2840 return RESULT_SHOWUSAGE;
2841 ast_mutex_lock(&userl.lock);
2842 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C");
2843 for(user=userl.users;user;user=user->next) {
2844 if (strlen(user->secret)) {
2845 strncpy(auth,user->secret,strlen(auth)-1);
2846 } else if (strlen(user->inkeys)) {
2847 sprintf(auth,"Key: %-15.15s ",user->inkeys);
2849 strcpy(auth,"-no secret-");
2850 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
2851 user->contexts ? user->contexts->context : context,
2852 user->ha ? "Yes" : "No");
2854 ast_mutex_unlock(&userl.lock);
2855 return RESULT_SUCCESS;
2860 static int iax2_show_peers(int fd, int argc, char *argv[])
2862 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %-10s\n"
2863 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %-10s\n"
2864 struct iax2_peer *peer;
2865 char name[256] = "";
2866 int registeredonly=0;
2867 if ((argc != 3) && (argc != 4))
2868 return RESULT_SHOWUSAGE;
2870 if (!strcasecmp(argv[3], "registered")) {
2873 return RESULT_SHOWUSAGE;
2875 ast_mutex_lock(&peerl.lock);
2876 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", "Status");
2877 for (peer = peerl.peers;peer;peer = peer->next) {
2880 if (registeredonly && !peer->addr.sin_addr.s_addr)
2882 if (strlen(peer->username))
2883 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
2885 strncpy(name, peer->name, sizeof(name) - 1);
2887 if (peer->lastms < 0)
2888 strcpy(status, "UNREACHABLE");
2889 else if (peer->lastms > peer->maxms)
2890 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
2891 else if (peer->lastms)
2892 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
2894 strcpy(status, "UNKNOWN");
2896 strcpy(status, "Unmonitored");
2897 strncpy(nm, inet_ntoa(peer->mask), sizeof(nm)-1);
2898 ast_cli(fd, FORMAT, name,
2899 peer->addr.sin_addr.s_addr ? inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
2900 peer->dynamic ? "(D)" : "(S)",
2902 ntohs(peer->addr.sin_port), peer->trunk ? "(T)" : " ", status);
2904 ast_mutex_unlock(&peerl.lock);
2905 return RESULT_SUCCESS;
2910 static int iax2_show_firmware(int fd, int argc, char *argv[])
2912 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
2913 #define FORMAT "%-15.15s %-15d %-15d\n"
2914 struct iax_firmware *cur;
2915 if ((argc != 3) && (argc != 4))
2916 return RESULT_SHOWUSAGE;
2917 ast_mutex_lock(&waresl.lock);
2919 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
2920 for (cur = waresl.wares;cur;cur = cur->next) {
2921 if ((argc == 3) || (!strcasecmp(argv[3], cur->fwh->devname)))
2922 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
2923 ntohl(cur->fwh->datalen));
2925 ast_mutex_unlock(&waresl.lock);
2926 return RESULT_SUCCESS;
2931 /* JDG: callback to display iax peers in manager */
2932 static int manager_iax2_show_peers( struct mansession *s, struct message *m )
2934 char *a[] = { "iax2", "show", "users" };
2936 ret = iax2_show_peers( s->fd, 3, a );
2937 ast_cli( s->fd, "\r\n" );
2941 static char *regstate2str(int regstate)
2944 case REG_STATE_UNREGISTERED:
2945 return "Unregistered";
2946 case REG_STATE_REGSENT:
2947 return "Request Sent";
2948 case REG_STATE_AUTHSENT:
2949 return "Auth. Sent";
2950 case REG_STATE_REGISTERED:
2951 return "Registered";
2952 case REG_STATE_REJECTED:
2954 case REG_STATE_TIMEOUT:
2956 case REG_STATE_NOAUTH:
2957 return "No Authentication";
2963 static int iax2_show_registry(int fd, int argc, char *argv[])
2965 #define FORMAT2 "%-20.20s %-10.10s %-20.20s %8.8s %s\n"
2966 #define FORMAT "%-20.20s %-10.10s %-20.20s %8d %s\n"
2967 struct iax2_registry *reg;
2971 return RESULT_SHOWUSAGE;
2972 ast_mutex_lock(&peerl.lock);
2973 ast_cli(fd, FORMAT2, "Host", "Username", "Perceived", "Refresh", "State");
2974 for (reg = registrations;reg;reg = reg->next) {
2975 snprintf(host, sizeof(host), "%s:%d", inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
2976 if (reg->us.sin_addr.s_addr)
2977 snprintf(perceived, sizeof(perceived), "%s:%d", inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
2979 strcpy(perceived, "<Unregistered>");
2980 ast_cli(fd, FORMAT, host,
2981 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
2983 ast_mutex_unlock(&peerl.lock);
2984 return RESULT_SUCCESS;
2989 static int iax2_show_channels(int fd, int argc, char *argv[])
2991 #define FORMAT2 "%-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %s\n"
2992 #define FORMAT "%-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-6.6s\n"
2996 return RESULT_SHOWUSAGE;
2997 ast_cli(fd, FORMAT2, "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "Format");
2998 for (x=0;x<IAX_MAX_CALLS;x++) {
2999 ast_mutex_lock(&iaxsl[x]);
3001 ast_cli(fd, FORMAT, inet_ntoa(iaxs[x]->addr.sin_addr),
3002 strlen(iaxs[x]->username) ? iaxs[x]->username : "(None)",
3003 iaxs[x]->callno, iaxs[x]->peercallno,
3004 iaxs[x]->oseqno, iaxs[x]->iseqno,
3007 ast_getformatname(iaxs[x]->voiceformat) );
3010 ast_mutex_unlock(&iaxsl[x]);
3012 ast_cli(fd, "%d active IAX channel(s)\n", numchans);
3013 return RESULT_SUCCESS;
3018 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
3021 return RESULT_SHOWUSAGE;
3023 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
3024 return RESULT_SUCCESS;
3027 static int iax2_do_debug(int fd, int argc, char *argv[])
3030 return RESULT_SHOWUSAGE;
3032 ast_cli(fd, "IAX2 Debugging Enabled\n");
3033 return RESULT_SUCCESS;
3036 static int iax2_no_debug(int fd, int argc, char *argv[])
3039 return RESULT_SHOWUSAGE;
3041 ast_cli(fd, "IAX2 Debugging Disabled\n");
3042 return RESULT_SUCCESS;