2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003 - 2005, 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/logger.h>
18 #include <asterisk/module.h>
19 #include <asterisk/pbx.h>
20 #include <asterisk/sched.h>
21 #include <asterisk/io.h>
22 #include <asterisk/config.h>
23 #include <asterisk/options.h>
24 #include <asterisk/cli.h>
25 #include <asterisk/translate.h>
26 #include <asterisk/md5.h>
27 #include <asterisk/cdr.h>
28 #include <asterisk/crypto.h>
29 #include <asterisk/acl.h>
30 #include <asterisk/manager.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/app.h>
33 #include <asterisk/astdb.h>
34 #include <asterisk/musiconhold.h>
35 #include <asterisk/features.h>
36 #include <asterisk/utils.h>
37 #include <asterisk/causes.h>
38 #include <asterisk/localtime.h>
39 #include <asterisk/aes.h>
40 #include <asterisk/dnsmgr.h>
42 #include <arpa/inet.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
58 #include <sys/types.h>
62 #include <sys/ioctl.h>
64 #include <linux/zaptel.h>
67 #endif /* __linux__ */
70 #include "iax2-parser.h"
71 #include "iax2-provision.h"
72 #include "../astconf.h"
74 /* Define NEWJB to use the new channel independent jitterbuffer,
75 * otherwise, use the old jitterbuffer */
79 #include "../jitterbuf.h"
83 #define IPTOS_MINCOST 0x02
87 static int nochecksums = 0;
91 * Uncomment to try experimental IAX bridge optimization,
92 * designed to reduce latency when IAX calls cannot
96 #define BRIDGE_OPTIMIZATION
98 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
99 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
101 #define DEFAULT_RETRY_TIME 1000
102 #define MEMORY_SIZE 100
103 #define DEFAULT_DROP 3
104 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
105 but keeps the division between trunked and non-trunked better. */
106 #define TRUNK_CALL_START 0x4000
108 #define DEBUG_SUPPORT
110 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
112 /* Sample over last 100 units to determine historic jitter */
115 static struct ast_codec_pref prefs;
117 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
118 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
119 static const char channeltype[] = "IAX2";
121 static char context[80] = "default";
123 static char language[MAX_LANGUAGE] = "";
124 static char regcontext[AST_MAX_EXTENSION] = "";
126 static int max_retries = 4;
127 static int ping_time = 20;
128 static int lagrq_time = 10;
129 static int maxtrunkcall = TRUNK_CALL_START;
130 static int maxnontrunkcall = 1;
131 static int maxjitterbuffer=1000;
132 static int jittershrinkrate=2;
133 static int trunkfreq = 20;
134 static int send_trunktimestamps = 1;
135 static int authdebug = 1;
136 static int autokill = 0;
137 static int iaxcompat = 0;
139 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
141 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
145 static int expirey = IAX_DEFAULT_REG_EXPIRE;
147 static int timingfd = -1; /* Timing file descriptor */
149 static struct ast_netsock_list netsock;
150 static int defaultsockfd = -1;
153 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
155 int (*iax2_regfunk)(char *username, int onoff) = NULL;
158 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
160 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
161 ~AST_FORMAT_SLINEAR & \
165 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
169 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
173 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
174 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
175 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
177 static struct io_context *io;
178 static struct sched_context *sched;
180 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
182 static int iax2_dropcount = DEFAULT_DROP;
184 static int iaxdebug = 0;
186 static int iaxtrunkdebug = 0;
188 static int test_losspct = 0;
190 static char accountcode[20];
191 static int amaflags = 0;
192 static int delayreject = 0;
193 static int iax2_encryption = 0;
195 static struct ast_flags globalflags = {0};
197 static pthread_t netthreadid = AST_PTHREADT_NULL;
199 #define IAX_STATE_STARTED (1 << 0)
200 #define IAX_STATE_AUTHENTICATED (1 << 1)
201 #define IAX_STATE_TBD (1 << 2)
203 struct iax2_context {
204 char context[AST_MAX_EXTENSION];
205 struct iax2_context *next;
208 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
209 #define IAX_DELME (1 << 1) /* Needs to be deleted */
210 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
211 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
212 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
213 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
214 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
215 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
216 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
217 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
218 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
219 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
220 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
221 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
222 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
223 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
224 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
225 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
226 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
227 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
228 #define IAX_FORCEJITTERBUF (1 << 20) /* Force jitterbuffer, even when bridged to a channel that can take jitter */
230 static int global_rtautoclear = 120;
232 static struct iax2_peer *realtime_peer(const char *peername);
233 static int reload_config(void);
234 static int iax2_reload(int fd, int argc, char *argv[]);
243 char accountcode[20];
244 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
245 char language[MAX_LANGUAGE];
249 char cid_num[AST_MAX_EXTENSION];
250 char cid_name[AST_MAX_EXTENSION];
251 struct ast_codec_pref prefs;
253 struct iax2_context *contexts;
254 struct iax2_user *next;
255 struct ast_variable *vars;
263 char outkey[80]; /* What key we use to talk to this peer */
264 char context[AST_MAX_EXTENSION]; /* For transfers only */
265 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
266 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
267 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
268 struct ast_codec_pref prefs;
269 struct ast_dnsmgr_entry *dnsmgr; /* DNS refresh manager */
270 struct sockaddr_in addr;
272 int sockfd; /* Socket to use for transmission */
276 /* Dynamic Registration fields */
277 struct sockaddr_in defaddr; /* Default address if there is one */
278 int authmethods; /* Authentication methods (IAX_AUTH_*) */
279 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
280 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
282 /* Suggested caller id if registering */
283 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
284 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
286 int expire; /* Schedule entry for expirey */
287 int expirey; /* How soon to expire */
288 int capability; /* Capability */
289 char zonetag[80]; /* Time Zone */
292 int callno; /* Call number of POKE request */
293 int pokeexpire; /* When to expire poke */
294 int lastms; /* How long last response took (in ms), or -1 for no response */
295 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
298 struct iax2_peer *next;
301 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
303 static struct iax2_trunk_peer {
306 struct sockaddr_in addr;
307 struct timeval txtrunktime; /* Transmit trunktime */
308 struct timeval rxtrunktime; /* Receive trunktime */
309 struct timeval lasttxtime; /* Last transmitted trunktime */
310 struct timeval trunkact; /* Last trunk activity */
311 unsigned int lastsent; /* Last sent time */
312 /* Trunk data and length */
313 unsigned char *trunkdata;
314 unsigned int trunkdatalen;
315 unsigned int trunkdataalloc;
316 struct iax2_trunk_peer *next;
321 AST_MUTEX_DEFINE_STATIC(tpeerlock);
323 struct iax_firmware {
324 struct iax_firmware *next;
328 struct ast_iax2_firmware_header *fwh;
332 #define REG_STATE_UNREGISTERED 0
333 #define REG_STATE_REGSENT 1
334 #define REG_STATE_AUTHSENT 2
335 #define REG_STATE_REGISTERED 3
336 #define REG_STATE_REJECTED 4
337 #define REG_STATE_TIMEOUT 5
338 #define REG_STATE_NOAUTH 6
340 #define TRANSFER_NONE 0
341 #define TRANSFER_BEGIN 1
342 #define TRANSFER_READY 2
343 #define TRANSFER_RELEASED 3
344 #define TRANSFER_PASSTHROUGH 4
346 struct iax2_registry {
347 struct sockaddr_in addr; /* Who we connect to for registration purposes */
349 char secret[80]; /* Password or key name in []'s */
351 int expire; /* Sched ID of expiration */
352 int refresh; /* How often to refresh */
354 int messages; /* Message count */
355 int callno; /* Associated call number if applicable */
356 struct sockaddr_in us; /* Who the server thinks we are */
357 struct iax2_registry *next;
360 static struct iax2_registry *registrations;
362 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
363 #define MIN_RETRY_TIME 100
364 #define MAX_RETRY_TIME 10000
366 #define MAX_JITTER_BUFFER 50
367 #define MIN_JITTER_BUFFER 10
369 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
370 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
372 #define MAX_TIMESTAMP_SKEW 640
374 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
375 #define TS_GAP_FOR_JB_RESYNC 5000
377 /* If we have more than this much excess real jitter buffer, shrink it. */
378 static int max_jitter_buffer = MAX_JITTER_BUFFER;
379 /* If we have less than this much excess real jitter buffer, enlarge it. */
380 static int min_jitter_buffer = MIN_JITTER_BUFFER;
392 struct chan_iax2_pvt {
393 /* Socket to send/receive on for this call */
395 /* Last received voice format */
397 /* Last received voice format */
399 /* Last sent voice format */
401 /* Last sent video format */
403 /* What we are capable of sending */
405 /* Last received timestamp */
407 /* Last sent timestamp - never send the same timestamp twice in a single call */
408 unsigned int lastsent;
409 /* Next outgoing timestamp if everything is good */
410 unsigned int nextpred;
411 /* True if the last voice we transmitted was not silence/CNG */
414 unsigned int pingtime;
415 /* Max time for initial response */
418 struct sockaddr_in addr;
419 struct ast_codec_pref prefs;
420 /* Our call number */
421 unsigned short callno;
423 unsigned short peercallno;
424 /* Peer selected format */
426 /* Peer capability */
428 /* timeval that we base our transmission on */
429 struct timeval offset;
430 /* timeval that we base our delivery on */
431 struct timeval rxcore;
433 /* The jitterbuffer */
435 /* active jb read scheduler id */
438 /* Historical delivery time */
439 int history[MEMORY_SIZE];
440 /* Current base jitterbuffer */
442 /* Current jitter measure */
444 /* Historic jitter value */
449 /* Error, as discovered by the manager */
451 /* Owner if we have one */
452 struct ast_channel *owner;
453 /* What's our state? */
455 /* Expirey (optional) */
457 /* Next outgoing sequence number */
458 unsigned char oseqno;
459 /* Next sequence number they have not yet acknowledged */
460 unsigned char rseqno;
461 /* Next incoming sequence number */
462 unsigned char iseqno;
463 /* Last incoming sequence number we have acknowledged */
464 unsigned char aseqno;
467 /* Default Context */
469 /* Caller ID if available */
472 /* Hidden Caller ID (i.e. ANI) if appropriate */
476 /* Requested Extension */
477 char exten[AST_MAX_EXTENSION];
478 /* Expected Username */
480 /* Expected Secret */
482 /* permitted authentication methods */
484 /* permitted encryption methods */
488 /* Public keys permitted keys for incoming authentication */
490 /* Private key for outgoing authentication */
492 /* Encryption AES-128 Key */
494 /* Decryption AES-128 Key */
496 /* 32 bytes of semi-random data */
498 /* Preferred language */
499 char language[MAX_LANGUAGE];
500 /* Hostname/peername for naming purposes */
502 /* Associated registry */
503 struct iax2_registry *reg;
504 /* Associated peer for poking */
505 struct iax2_peer *peerpoke;
509 /* Transferring status */
511 /* Transfer identifier */
513 /* Who we are IAX transfering to */
514 struct sockaddr_in transfer;
515 /* What's the new call number for the transfer */
516 unsigned short transfercallno;
517 /* Transfer decrypt AES-128 Key */
518 aes_encrypt_ctx tdcx;
520 /* Status of knowledge of peer ADSI capability */
523 /* Who we are bridged to */
524 unsigned short bridgecallno;
525 unsigned int bridgesfmt;
526 struct ast_trans_pvt *bridgetrans;
528 int pingid; /* Transmit PING request */
529 int lagid; /* Retransmit lag request */
530 int autoid; /* Auto hangup for Dialplan requestor */
531 int authid; /* Authentication rejection ID */
532 int authfail; /* Reason to report failure */
533 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
537 char dproot[AST_MAX_EXTENSION];
538 char accountcode[20];
540 struct iax2_dpcache *dpentries;
541 struct ast_variable *vars;
542 /* last received remote rr */
543 struct iax_rr remote_rr;
544 /* Current base time: (just for stats) */
546 /* Dropped frame count: (just for stats) */
548 /* received frame count: (just for stats) */
552 static struct ast_iax2_queue {
553 struct iax_frame *head;
554 struct iax_frame *tail;
559 static struct ast_user_list {
560 struct iax2_user *users;
564 static struct ast_peer_list {
565 struct iax2_peer *peers;
569 static struct ast_firmware_list {
570 struct iax_firmware *wares;
574 /* Extension exists */
575 #define CACHE_FLAG_EXISTS (1 << 0)
576 /* Extension is nonexistent */
577 #define CACHE_FLAG_NONEXISTENT (1 << 1)
578 /* Extension can exist */
579 #define CACHE_FLAG_CANEXIST (1 << 2)
580 /* Waiting to hear back response */
581 #define CACHE_FLAG_PENDING (1 << 3)
583 #define CACHE_FLAG_TIMEOUT (1 << 4)
584 /* Request transmitted */
585 #define CACHE_FLAG_TRANSMITTED (1 << 5)
587 #define CACHE_FLAG_UNKNOWN (1 << 6)
589 #define CACHE_FLAG_MATCHMORE (1 << 7)
591 static struct iax2_dpcache {
592 char peercontext[AST_MAX_EXTENSION];
593 char exten[AST_MAX_EXTENSION];
595 struct timeval expirey;
597 unsigned short callno;
599 struct iax2_dpcache *next;
600 struct iax2_dpcache *peer; /* For linking in peers */
603 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
605 static void destroy_peer(struct iax2_peer *peer);
607 static void iax_debug_output(const char *data)
610 ast_verbose("%s", data);
613 static void iax_error_output(const char *data)
615 ast_log(LOG_WARNING, "%s", data);
619 static void jb_error_output(const char *fmt, ...)
625 vsnprintf(buf, 1024, fmt, args);
628 ast_log(LOG_ERROR, buf);
631 static void jb_warning_output(const char *fmt, ...)
637 vsnprintf(buf, 1024, fmt, args);
640 ast_log(LOG_WARNING, buf);
643 static void jb_debug_output(const char *fmt, ...)
647 if(!iaxdebug) return;
650 vsnprintf(buf, 1024, fmt, args);
658 /* XXX We probably should use a mutex when working with this XXX */
659 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
660 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
661 static struct timeval lastused[IAX_MAX_CALLS];
664 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
665 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
666 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
667 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
668 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
669 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
670 static void destroy_user(struct iax2_user *user);
671 static int expire_registry(void *data);
672 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
673 static int iax2_do_register(struct iax2_registry *reg);
674 static void prune_peers(void);
675 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
676 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
678 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
679 static int iax2_devicestate(void *data);
680 static int iax2_digit(struct ast_channel *c, char digit);
681 static int iax2_sendtext(struct ast_channel *c, const char *text);
682 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
683 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
684 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
685 static int iax2_hangup(struct ast_channel *c);
686 static int iax2_answer(struct ast_channel *c);
687 static struct ast_frame *iax2_read(struct ast_channel *c);
688 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
689 static int iax2_indicate(struct ast_channel *c, int condition);
690 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
691 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
692 static int iax2_transfer(struct ast_channel *c, const char *dest);
693 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
695 static const struct ast_channel_tech iax2_tech = {
697 .description = tdesc,
698 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
699 .properties = AST_CHAN_TP_WANTSJITTER,
700 .requester = iax2_request,
701 .devicestate = iax2_devicestate,
702 .send_digit = iax2_digit,
703 .send_text = iax2_sendtext,
704 .send_image = iax2_sendimage,
705 .send_html = iax2_sendhtml,
707 .hangup = iax2_hangup,
708 .answer = iax2_answer,
711 .write_video = iax2_write,
712 .indicate = iax2_indicate,
713 .setoption = iax2_setoption,
714 .bridge = iax2_bridge,
715 .transfer = iax2_transfer,
719 static int send_ping(void *data)
721 int callno = (long)data;
722 /* Ping only if it's real, not if it's bridged */
724 #ifdef BRIDGE_OPTIMIZATION
725 if (!iaxs[callno]->bridgecallno)
727 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
733 static int get_encrypt_methods(const char *s)
736 if (!strcasecmp(s, "aes128"))
737 e = IAX_ENCRYPT_AES128;
738 else if (ast_true(s))
739 e = IAX_ENCRYPT_AES128;
745 static int send_lagrq(void *data)
747 int callno = (long)data;
748 /* Ping only if it's real not if it's bridged */
750 #ifdef BRIDGE_OPTIMIZATION
751 if (!iaxs[callno]->bridgecallno)
753 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
759 static unsigned char compress_subclass(int subclass)
763 /* If it's 128 or smaller, just return it */
764 if (subclass < IAX_FLAG_SC_LOG)
766 /* Otherwise find its power */
767 for (x = 0; x < IAX_MAX_SHIFT; x++) {
768 if (subclass & (1 << x)) {
770 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
776 return power | IAX_FLAG_SC_LOG;
779 static int uncompress_subclass(unsigned char csub)
781 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
782 if (csub & IAX_FLAG_SC_LOG) {
783 /* special case for 'compressed' -1 */
787 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
793 static struct iax2_peer *find_peer(const char *name, int realtime)
795 struct iax2_peer *peer;
796 ast_mutex_lock(&peerl.lock);
797 for(peer = peerl.peers; peer; peer = peer->next) {
798 if (!strcasecmp(peer->name, name)) {
802 ast_mutex_unlock(&peerl.lock);
803 if(!peer && realtime)
804 peer = realtime_peer(name);
808 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
810 struct iax2_peer *peer;
813 ast_mutex_lock(&peerl.lock);
816 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
817 (peer->addr.sin_port == sin.sin_port)) {
818 strncpy(host, peer->name, len-1);
825 ast_mutex_unlock(&peerl.lock);
829 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
831 struct chan_iax2_pvt *tmp;
832 tmp = malloc(sizeof(struct chan_iax2_pvt));
834 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
838 tmp->transfercallno = 0;
839 tmp->bridgecallno = 0;
845 /* strncpy(tmp->context, context, sizeof(tmp->context)-1); */
846 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
847 strncpy(tmp->host, host, sizeof(tmp->host)-1);
854 jbinfo.max_jitterbuf = maxjitterbuffer;
855 jb_setinfo(tmp->jb,&jbinfo);
862 static int get_samples(struct ast_frame *f)
865 switch(f->subclass) {
866 case AST_FORMAT_SPEEX:
867 samples = 160; /* XXX Not necessarily true XXX */
869 case AST_FORMAT_G723_1:
870 samples = 240 /* XXX Not necessarily true XXX */;
872 case AST_FORMAT_ILBC:
873 samples = 240 * (f->datalen / 50);
876 samples = 160 * (f->datalen / 33);
878 case AST_FORMAT_G729A:
879 samples = 160 * (f->datalen / 20);
881 case AST_FORMAT_SLINEAR:
882 samples = f->datalen / 2;
884 case AST_FORMAT_LPC10:
886 samples += (((char *)(f->data))[7] & 0x1) * 8;
888 case AST_FORMAT_ULAW:
889 samples = f->datalen;
891 case AST_FORMAT_ALAW:
892 samples = f->datalen;
894 case AST_FORMAT_ADPCM:
895 case AST_FORMAT_G726:
896 samples = f->datalen *2;
899 ast_log(LOG_WARNING, "Don't know how to calculate samples on %d packets\n", f->subclass);
904 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
906 /* Malloc() a copy of a frame */
907 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
909 memcpy(new, fr, sizeof(struct iax_frame));
910 iax_frame_wrap(new, &fr->af);
913 new->direction = DIRECTION_INGRESS;
919 #define NEW_PREVENT 0
923 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
925 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
926 (cur->addr.sin_port == sin->sin_port)) {
927 /* This is the main host */
928 if ((cur->peercallno == callno) ||
929 ((dcallno == cur->callno) && !cur->peercallno)) {
930 /* That's us. Be sure we keep track of the peer call number */
934 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
935 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
936 /* We're transferring */
937 if (dcallno == cur->callno)
943 static void update_max_trunk(void)
945 int max = TRUNK_CALL_START;
947 /* XXX Prolly don't need locks here XXX */
948 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
954 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
957 static void update_max_nontrunk(void)
961 /* XXX Prolly don't need locks here XXX */
962 for (x=1;x<TRUNK_CALL_START - 1; x++) {
966 maxnontrunkcall = max;
968 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
971 static int make_trunk(unsigned short callno, int locked)
976 if (iaxs[callno]->oseqno) {
977 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
980 if (callno & TRUNK_CALL_START) {
981 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
984 gettimeofday(&now, NULL);
985 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
986 ast_mutex_lock(&iaxsl[x]);
987 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
988 iaxs[x] = iaxs[callno];
991 /* Update the two timers that should have been started */
992 if (iaxs[x]->pingid > -1)
993 ast_sched_del(sched, iaxs[x]->pingid);
994 if (iaxs[x]->lagid > -1)
995 ast_sched_del(sched, iaxs[x]->lagid);
996 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
997 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
999 ast_mutex_unlock(&iaxsl[callno]);
1002 ast_mutex_unlock(&iaxsl[x]);
1005 ast_mutex_unlock(&iaxsl[x]);
1007 if (x >= IAX_MAX_CALLS - 1) {
1008 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1011 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1012 /* We move this call from a non-trunked to a trunked call */
1014 update_max_nontrunk();
1018 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1023 char iabuf[INET_ADDRSTRLEN];
1025 if (new <= NEW_ALLOW) {
1026 /* Look for an existing connection first */
1027 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1028 ast_mutex_lock(&iaxsl[x]);
1030 /* Look for an exact match */
1031 if (match(sin, callno, dcallno, iaxs[x])) {
1035 ast_mutex_unlock(&iaxsl[x]);
1037 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1038 ast_mutex_lock(&iaxsl[x]);
1040 /* Look for an exact match */
1041 if (match(sin, callno, dcallno, iaxs[x])) {
1045 ast_mutex_unlock(&iaxsl[x]);
1048 if ((res < 1) && (new >= NEW_ALLOW)) {
1049 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1050 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1051 gettimeofday(&now, NULL);
1052 for (x=1;x<TRUNK_CALL_START;x++) {
1053 /* Find first unused call number that hasn't been used in a while */
1054 ast_mutex_lock(&iaxsl[x]);
1055 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1056 ast_mutex_unlock(&iaxsl[x]);
1058 /* We've still got lock held if we found a spot */
1059 if (x >= TRUNK_CALL_START) {
1060 ast_log(LOG_WARNING, "No more space\n");
1063 iaxs[x] = new_iax(sin, lockpeer, host);
1064 update_max_nontrunk();
1067 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1068 iaxs[x]->sockfd = sockfd;
1069 iaxs[x]->addr.sin_port = sin->sin_port;
1070 iaxs[x]->addr.sin_family = sin->sin_family;
1071 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1072 iaxs[x]->peercallno = callno;
1073 iaxs[x]->callno = x;
1074 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1075 iaxs[x]->expirey = expirey;
1076 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1077 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1078 iaxs[x]->amaflags = amaflags;
1079 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1080 strncpy(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode)-1);
1082 ast_log(LOG_WARNING, "Out of resources\n");
1083 ast_mutex_unlock(&iaxsl[x]);
1086 ast_mutex_unlock(&iaxsl[x]);
1092 static void iax2_frame_free(struct iax_frame *fr)
1094 if (fr->retrans > -1)
1095 ast_sched_del(sched, fr->retrans);
1099 static int iax2_queue_frame(int callno, struct ast_frame *f)
1101 /* Assumes lock for callno is already held... */
1103 if (iaxs[callno] && iaxs[callno]->owner) {
1104 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1105 /* Avoid deadlock by pausing and trying again */
1106 ast_mutex_unlock(&iaxsl[callno]);
1108 ast_mutex_lock(&iaxsl[callno]);
1110 ast_queue_frame(iaxs[callno]->owner, f);
1111 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1120 static void destroy_firmware(struct iax_firmware *cur)
1122 /* Close firmware */
1124 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1130 static int try_firmware(char *s)
1133 struct iax_firmware *cur;
1138 struct ast_iax2_firmware_header *fwh, fwh2;
1139 struct MD5Context md5;
1140 unsigned char sum[16];
1141 unsigned char buf[1024];
1145 s2 = alloca(strlen(s) + 100);
1147 ast_log(LOG_WARNING, "Alloca failed!\n");
1150 last = strrchr(s, '/');
1155 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1156 res = stat(s, &stbuf);
1158 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1161 /* Make sure it's not a directory */
1162 if (S_ISDIR(stbuf.st_mode))
1164 ifd = open(s, O_RDONLY);
1166 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1169 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1171 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1175 /* Unlink our newly created file */
1178 /* Now copy the firmware into it */
1179 len = stbuf.st_size;
1182 if (chunk > sizeof(buf))
1183 chunk = sizeof(buf);
1184 res = read(ifd, buf, chunk);
1186 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1191 res = write(fd, buf, chunk);
1193 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1201 /* Return to the beginning */
1202 lseek(fd, 0, SEEK_SET);
1203 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1204 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1208 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1209 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1213 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1214 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1218 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1219 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1223 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1225 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1230 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1231 MD5Final(sum, &md5);
1232 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1233 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1234 munmap(fwh, stbuf.st_size);
1240 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1241 /* Found a candidate */
1242 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1243 /* The version we have on loaded is older, load this one instead */
1245 /* This version is no newer than what we have. Don't worry about it.
1246 We'll consider it a proper load anyhow though */
1247 munmap(fwh, stbuf.st_size);
1254 /* Allocate a new one and link it */
1255 cur = malloc(sizeof(struct iax_firmware));
1257 memset(cur, 0, sizeof(struct iax_firmware));
1259 cur->next = waresl.wares;
1265 munmap(cur->fwh, cur->mmaplen);
1271 cur->mmaplen = stbuf.st_size;
1277 static int iax_check_version(char *dev)
1280 struct iax_firmware *cur;
1281 if (dev && !ast_strlen_zero(dev)) {
1282 ast_mutex_lock(&waresl.lock);
1285 if (!strcmp(dev, cur->fwh->devname)) {
1286 res = ntohs(cur->fwh->version);
1291 ast_mutex_unlock(&waresl.lock);
1296 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1299 unsigned int bs = desc & 0xff;
1300 unsigned int start = (desc >> 8) & 0xffffff;
1302 struct iax_firmware *cur;
1303 if (dev && !ast_strlen_zero(dev) && bs) {
1305 ast_mutex_lock(&waresl.lock);
1308 if (!strcmp(dev, cur->fwh->devname)) {
1309 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1310 if (start < ntohl(cur->fwh->datalen)) {
1311 bytes = ntohl(cur->fwh->datalen) - start;
1314 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1317 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1327 ast_mutex_unlock(&waresl.lock);
1333 static void reload_firmware(void)
1335 struct iax_firmware *cur, *curl, *curp;
1340 /* Mark all as dead */
1341 ast_mutex_lock(&waresl.lock);
1347 /* Now that we've freed them, load the new ones */
1348 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1351 while((de = readdir(fwd))) {
1352 if (de->d_name[0] != '.') {
1353 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1354 if (!try_firmware(fn)) {
1355 if (option_verbose > 1)
1356 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1362 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1364 /* Clean up leftovers */
1376 destroy_firmware(curl);
1381 ast_mutex_unlock(&waresl.lock);
1384 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1386 static int __do_deliver(void *data)
1388 /* Just deliver the packet by using queueing. This is called by
1389 the IAX thread with the iaxsl lock held. */
1390 struct iax_frame *fr = data;
1392 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1393 iax2_queue_frame(fr->callno, &fr->af);
1394 /* Free our iax frame */
1395 iax2_frame_free(fr);
1396 /* And don't run again */
1401 static int do_deliver(void *data)
1403 /* Locking version of __do_deliver */
1404 struct iax_frame *fr = data;
1405 int callno = fr->callno;
1407 ast_mutex_lock(&iaxsl[callno]);
1408 res = __do_deliver(data);
1409 ast_mutex_unlock(&iaxsl[callno]);
1414 static int handle_error(void)
1416 /* XXX Ideally we should figure out why an error occured and then abort those
1417 rather than continuing to try. Unfortunately, the published interface does
1418 not seem to work XXX */
1420 struct sockaddr_in *sin;
1423 struct sock_extended_err e;
1428 m.msg_controllen = sizeof(e);
1430 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1432 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1434 if (m.msg_controllen) {
1435 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1437 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1439 ast_log(LOG_WARNING, "No address detected??\n");
1441 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1448 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1451 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1455 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1462 static int send_packet(struct iax_frame *f)
1465 char iabuf[INET_ADDRSTRLEN];
1466 /* Called with iaxsl held */
1468 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));
1469 /* Don't send if there was an error, but return error instead */
1471 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1474 if (!iaxs[f->callno])
1476 if (iaxs[f->callno]->error)
1480 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1481 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1482 sizeof(iaxs[f->callno]->transfer));
1485 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1486 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1487 sizeof(iaxs[f->callno]->addr));
1491 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1499 static int iax2_predestroy(int callno)
1501 struct ast_channel *c;
1502 struct chan_iax2_pvt *pvt;
1503 ast_mutex_lock(&iaxsl[callno]);
1506 ast_mutex_unlock(&iaxsl[callno]);
1509 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1510 /* No more pings or lagrq's */
1511 if (pvt->pingid > -1)
1512 ast_sched_del(sched, pvt->pingid);
1513 if (pvt->lagid > -1)
1514 ast_sched_del(sched, pvt->lagid);
1515 if (pvt->autoid > -1)
1516 ast_sched_del(sched, pvt->autoid);
1517 if (pvt->authid > -1)
1518 ast_sched_del(sched, pvt->authid);
1519 if (pvt->initid > -1)
1520 ast_sched_del(sched, pvt->initid);
1523 ast_sched_del(sched, pvt->jbid);
1531 ast_set_flag(pvt, IAX_ALREADYGONE);
1535 c->_softhangup |= AST_SOFTHANGUP_DEV;
1537 ast_queue_hangup(c);
1539 ast_mutex_lock(&usecnt_lock);
1542 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1543 ast_mutex_unlock(&usecnt_lock);
1545 ast_mutex_unlock(&iaxsl[callno]);
1546 ast_update_use_count();
1550 static int iax2_predestroy_nolock(int callno)
1553 ast_mutex_unlock(&iaxsl[callno]);
1554 res = iax2_predestroy(callno);
1555 ast_mutex_lock(&iaxsl[callno]);
1559 static void iax2_destroy(int callno)
1561 struct chan_iax2_pvt *pvt;
1562 struct iax_frame *cur;
1563 struct ast_channel *owner;
1566 ast_mutex_lock(&iaxsl[callno]);
1568 gettimeofday(&lastused[callno], NULL);
1575 if (ast_mutex_trylock(&owner->lock)) {
1576 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1577 ast_mutex_unlock(&iaxsl[callno]);
1583 iaxs[callno] = NULL;
1587 /* No more pings or lagrq's */
1588 if (pvt->pingid > -1)
1589 ast_sched_del(sched, pvt->pingid);
1590 if (pvt->lagid > -1)
1591 ast_sched_del(sched, pvt->lagid);
1592 if (pvt->autoid > -1)
1593 ast_sched_del(sched, pvt->autoid);
1594 if (pvt->authid > -1)
1595 ast_sched_del(sched, pvt->authid);
1596 if (pvt->initid > -1)
1597 ast_sched_del(sched, pvt->initid);
1600 ast_sched_del(sched, pvt->jbid);
1608 if (pvt->bridgetrans)
1609 ast_translator_free_path(pvt->bridgetrans);
1610 pvt->bridgetrans = NULL;
1613 ast_set_flag(pvt, IAX_ALREADYGONE);
1616 /* If there's an owner, prod it to give up */
1617 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1618 ast_queue_hangup(owner);
1621 for (cur = iaxq.head; cur ; cur = cur->next) {
1622 /* Cancel any pending transmissions */
1623 if (cur->callno == pvt->callno)
1627 pvt->reg->callno = 0;
1631 ast_variables_destroy(pvt->vars);
1637 while(jb_getall(pvt->jb,&frame) == JB_OK)
1638 iax2_frame_free(frame.data);
1639 jb_destroy(pvt->jb);
1646 ast_mutex_unlock(&owner->lock);
1648 ast_mutex_unlock(&iaxsl[callno]);
1649 if (callno & 0x4000)
1652 static void iax2_destroy_nolock(int callno)
1654 /* Actually it's easier to unlock, kill it, and relock */
1655 ast_mutex_unlock(&iaxsl[callno]);
1656 iax2_destroy(callno);
1657 ast_mutex_lock(&iaxsl[callno]);
1660 static int update_packet(struct iax_frame *f)
1662 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1663 struct ast_iax2_full_hdr *fh = f->data;
1664 /* Mark this as a retransmission */
1665 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1667 f->iseqno = iaxs[f->callno]->iseqno;
1668 fh->iseqno = f->iseqno;
1672 static int attempt_transmit(void *data)
1674 /* Attempt to transmit the frame to the remote peer...
1675 Called without iaxsl held. */
1676 struct iax_frame *f = data;
1678 int callno = f->callno;
1679 char iabuf[INET_ADDRSTRLEN];
1680 /* Make sure this call is still active */
1682 ast_mutex_lock(&iaxsl[callno]);
1683 if ((f->callno) && iaxs[f->callno]) {
1684 if ((f->retries < 0) /* Already ACK'd */ ||
1685 (f->retries >= max_retries) /* Too many attempts */) {
1686 /* Record an error if we've transmitted too many times */
1687 if (f->retries >= max_retries) {
1689 /* Transfer timeout */
1690 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1691 } else if (f->final) {
1693 iax2_destroy_nolock(f->callno);
1695 if (iaxs[f->callno]->owner)
1696 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);
1697 iaxs[f->callno]->error = ETIMEDOUT;
1698 if (iaxs[f->callno]->owner) {
1699 struct ast_frame fr = { 0, };
1701 fr.frametype = AST_FRAME_CONTROL;
1702 fr.subclass = AST_CONTROL_HANGUP;
1703 iax2_queue_frame(f->callno, &fr);
1704 /* Remember, owner could disappear */
1705 if (iaxs[f->callno]->owner)
1706 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1708 if (iaxs[f->callno]->reg) {
1709 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1710 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1711 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1713 iax2_destroy_nolock(f->callno);
1720 /* Update it if it needs it */
1722 /* Attempt transmission */
1725 /* Try again later after 10 times as long */
1727 if (f->retrytime > MAX_RETRY_TIME)
1728 f->retrytime = MAX_RETRY_TIME;
1729 /* Transfer messages max out at one second */
1730 if (f->transfer && (f->retrytime > 1000))
1731 f->retrytime = 1000;
1732 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1735 /* Make sure it gets freed */
1740 ast_mutex_unlock(&iaxsl[callno]);
1741 /* Do not try again */
1743 /* Don't attempt delivery, just remove it from the queue */
1744 ast_mutex_lock(&iaxq.lock);
1746 f->prev->next = f->next;
1748 iaxq.head = f->next;
1750 f->next->prev = f->prev;
1752 iaxq.tail = f->prev;
1754 ast_mutex_unlock(&iaxq.lock);
1756 /* Free the IAX frame */
1762 static int iax2_set_jitter(int fd, int argc, char *argv[])
1765 ast_cli(fd, "sorry, this command is deprecated\n");
1766 return RESULT_SUCCESS;
1768 if ((argc != 4) && (argc != 5))
1769 return RESULT_SHOWUSAGE;
1771 max_jitter_buffer = atoi(argv[3]);
1772 if (max_jitter_buffer < 0)
1773 max_jitter_buffer = 0;
1776 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1777 if (iaxs[atoi(argv[3])]) {
1778 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1779 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1780 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1782 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1784 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1787 return RESULT_SUCCESS;
1791 static char jitter_usage[] =
1792 "Usage: iax set jitter [callid] <value>\n"
1793 " If used with a callid, it sets the jitter buffer to the given static\n"
1794 "value (until its next calculation). If used without a callid, the value is used\n"
1795 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1796 "buffer size is reduced.";
1798 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1800 struct iax2_peer *peer;
1803 return RESULT_SHOWUSAGE;
1804 if (!strcmp(argv[3],"all")) {
1806 ast_cli(fd, "OK cache is flushed.\n");
1807 } else if ((peer = find_peer(argv[3], 0))) {
1808 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1809 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1810 expire_registry(peer);
1811 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1813 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1816 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1819 return RESULT_SUCCESS;
1822 static int iax2_test_losspct(int fd, int argc, char *argv[])
1825 return RESULT_SHOWUSAGE;
1827 test_losspct = atoi(argv[3]);
1829 return RESULT_SUCCESS;
1832 /*--- iax2_show_peer: Show one peer in detail ---*/
1833 static int iax2_show_peer(int fd, int argc, char *argv[])
1835 char status[30] = "";
1837 char iabuf[INET_ADDRSTRLEN];
1838 struct iax2_peer *peer;
1839 char codec_buf[512];
1840 int x = 0, codec = 0, load_realtime = 0;
1843 return RESULT_SHOWUSAGE;
1845 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1847 peer = find_peer(argv[3], load_realtime);
1850 ast_cli(fd, " * Name : %s\n", peer->name);
1851 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1852 ast_cli(fd, " Context : %s\n", peer->context);
1853 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1854 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1855 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1856 ast_cli(fd, " Expire : %d\n", peer->expire);
1857 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1858 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(iabuf, sizeof(iabuf), peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
1859 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1860 ast_cli(fd, " Username : %s\n", peer->username);
1861 ast_cli(fd, " Codecs : ");
1862 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1863 ast_cli(fd, "%s\n", codec_buf);
1865 ast_cli(fd, " Codec Order : (");
1866 for(x = 0; x < 32 ; x++) {
1867 codec = ast_codec_pref_index(&peer->prefs,x);
1870 ast_cli(fd, "%s", ast_getformatname(codec));
1871 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1876 ast_cli(fd, "none");
1879 ast_cli(fd, " Status : ");
1880 if (peer->lastms < 0)
1881 strncpy(status, "UNREACHABLE", sizeof(status) - 1);
1882 else if (peer->lastms > peer->maxms)
1883 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1884 else if (peer->lastms)
1885 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1887 strncpy(status, "UNKNOWN", sizeof(status) - 1);
1888 ast_cli(fd, "%s\n",status);
1890 if (ast_test_flag(peer, IAX_TEMPONLY))
1893 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1897 return RESULT_SUCCESS;
1900 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1903 struct iax2_peer *p;
1905 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1907 ast_mutex_lock(&peerl.lock);
1908 for(p = peerl.peers ; p ; p = p->next) {
1909 if(!strncasecmp(p->name, word, strlen(word))) {
1910 if(++which > state) {
1911 return strdup(p->name);
1915 ast_mutex_unlock(&peerl.lock);
1921 static int iax2_show_stats(int fd, int argc, char *argv[])
1923 struct iax_frame *cur;
1924 int cnt = 0, dead=0, final=0;
1926 return RESULT_SHOWUSAGE;
1927 for (cur = iaxq.head; cur ; cur = cur->next) {
1928 if (cur->retries < 0)
1934 ast_cli(fd, " IAX Statistics\n");
1935 ast_cli(fd, "---------------------\n");
1936 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1937 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1938 return RESULT_SUCCESS;
1941 static int iax2_show_cache(int fd, int argc, char *argv[])
1943 struct iax2_dpcache *dp;
1944 char tmp[1024] = "", *pc;
1948 gettimeofday(&tv, NULL);
1949 ast_mutex_lock(&dpcache_lock);
1951 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1953 s = dp->expirey.tv_sec - tv.tv_sec;
1955 if (dp->flags & CACHE_FLAG_EXISTS)
1956 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1957 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1958 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1959 if (dp->flags & CACHE_FLAG_CANEXIST)
1960 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1961 if (dp->flags & CACHE_FLAG_PENDING)
1962 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1963 if (dp->flags & CACHE_FLAG_TIMEOUT)
1964 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1965 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1966 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1967 if (dp->flags & CACHE_FLAG_MATCHMORE)
1968 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1969 if (dp->flags & CACHE_FLAG_UNKNOWN)
1970 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1971 /* Trim trailing pipe */
1972 if (!ast_strlen_zero(tmp))
1973 tmp[strlen(tmp) - 1] = '\0';
1975 strncpy(tmp, "(none)", sizeof(tmp) - 1);
1977 pc = strchr(dp->peercontext, '@');
1979 pc = dp->peercontext;
1982 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1983 if (dp->waiters[x] > -1)
1986 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1988 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1991 ast_mutex_unlock(&dpcache_lock);
1992 return RESULT_SUCCESS;
1995 static char show_stats_usage[] =
1996 "Usage: iax show stats\n"
1997 " Display statistics on IAX channel driver.\n";
2000 static char show_cache_usage[] =
2001 "Usage: iax show cache\n"
2002 " Display currently cached IAX Dialplan results.\n";
2004 static char show_peer_usage[] =
2005 "Usage: iax show peer <name>\n"
2006 " Display details on specific IAX peer\n";
2008 static char prune_realtime_usage[] =
2009 "Usage: iax2 prune realtime [<peername>|all]\n"
2010 " Prunes object(s) from the cache\n";
2012 static char iax2_reload_usage[] =
2013 "Usage: iax2 reload\n"
2014 " Reloads IAX configuration from iax.conf\n";
2016 static struct ast_cli_entry cli_set_jitter =
2017 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
2019 static struct ast_cli_entry cli_show_stats =
2020 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
2022 static struct ast_cli_entry cli_show_cache =
2023 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
2025 static struct ast_cli_entry cli_show_peer =
2026 { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
2028 static struct ast_cli_entry cli_prune_realtime =
2029 { { "iax2", "prune", "realtime", NULL }, iax2_prune_realtime, "Prune a cached realtime lookup", prune_realtime_usage, complete_iax2_show_peer };
2031 static struct ast_cli_entry cli_reload =
2032 { { "iax2", "reload", NULL }, iax2_reload, "Reload IAX configuration", iax2_reload_usage };
2034 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2036 #ifdef BRIDGE_OPTIMIZATION
2037 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2039 static int forward_delivery(struct iax_frame *fr)
2041 struct chan_iax2_pvt *p1, *p2;
2042 char iabuf[INET_ADDRSTRLEN];
2045 p1 = iaxs[fr->callno];
2046 p2 = iaxs[p1->bridgecallno];
2053 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2055 p1->callno, p1->peercallno,
2056 p2->callno, p2->peercallno,
2057 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2058 ntohs(p2->addr.sin_port));
2060 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2061 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2062 send full frame on timestamp wrap when doing optimized bridging
2063 (actually current code STILL doesn't)
2065 if (fr->ts + 50000 <= p1->last) {
2066 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2068 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2071 /* Send with timestamp adjusted to the origin of the outbound leg */
2072 /* But don't destroy inbound timestamp still needed later to set "last" */
2074 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2075 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2081 static void unwrap_timestamp(struct iax_frame *fr)
2085 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2086 x = fr->ts - iaxs[fr->callno]->last;
2088 /* Sudden big jump backwards in timestamp:
2089 What likely happened here is that miniframe timestamp has circled but we haven't
2090 gotten the update from the main packet. We'll just pretend that we did, and
2091 update the timestamp appropriately. */
2092 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2094 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2097 /* Sudden apparent big jump forwards in timestamp:
2098 What's likely happened is this is an old miniframe belonging to the previous
2099 top-16-bit timestamp that has turned up out of order.
2100 Adjust the timestamp appropriately. */
2101 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2103 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2109 static int get_from_jb(void *p);
2111 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2115 gettimeofday(&tv,NULL);
2117 when = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2118 (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2120 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2122 when = jb_next(pvt->jb) - when;
2123 /* fprintf(stderr, "when = %d\n", when); */
2125 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2128 /* XXX should really just empty until when > 0.. */
2132 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2135 static int get_from_jb(void *p) {
2136 /* make sure pvt is valid! */
2137 struct chan_iax2_pvt *pvt = p;
2138 struct iax_frame *fr;
2145 ast_mutex_lock(&iaxsl[pvt->callno]);
2146 /* fprintf(stderr, "get_from_jb called\n"); */
2149 gettimeofday(&tv,NULL);
2151 now = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2152 (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2154 if(now > (next = jb_next(pvt->jb))) {
2155 ret = jb_get(pvt->jb,&frame,now);
2158 /*if(frame.type == JB_TYPE_VOICE && next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2164 struct ast_frame af;
2166 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2168 /* create an interpolation frame */
2169 /*fprintf(stderr, "Making Interpolation frame\n"); */
2170 af.frametype = AST_FRAME_VOICE;
2171 af.subclass = pvt->voiceformat;
2173 af.samples = frame.ms * 8;
2175 af.src = "IAX2 JB interpolation";
2177 af.delivery.tv_sec = pvt->rxcore.tv_sec;
2178 af.delivery.tv_usec = pvt->rxcore.tv_usec;
2179 af.delivery.tv_sec += next / 1000;
2180 af.delivery.tv_usec += (next % 1000) * 1000;
2181 af.offset=AST_FRIENDLY_OFFSET;
2182 if (af.delivery.tv_usec >= 1000000) {
2183 af.delivery.tv_usec -= 1000000;
2184 af.delivery.tv_sec += 1;
2187 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2188 * which we'd need to malloc, and then it would free it. That seems like a drag */
2189 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2190 iax2_queue_frame(pvt->callno, &af);
2194 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2195 iax2_frame_free(frame.data);
2202 /* shouldn't happen */
2206 update_jbsched(pvt);
2207 ast_mutex_unlock(&iaxsl[pvt->callno]);
2212 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2213 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2214 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
2222 unsigned int orig_ts;
2223 int drops[MEMORY_SIZE];
2224 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2226 /* Remember current jitterbuffer so we can log any change */
2227 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2228 /* Similarly for the frame timestamp */
2234 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
2235 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
2238 /* Attempt to recover wrapped timestamps */
2239 unwrap_timestamp(fr);
2241 if (updatehistory) {
2243 /* Attempt to spot a change of timebase on timestamps coming from the other side
2244 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2245 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2246 for a while - in this case this code might also resync us. But that's not a bad thing.
2247 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2248 [that's why we only do this when updatehistory is true]
2250 x = fr->ts - iaxs[fr->callno]->last;
2251 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2253 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2254 fr->callno, fr->ts, iaxs[fr->callno]->last);
2255 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2256 iaxs[fr->callno]->rxcore.tv_sec = 0;
2257 iaxs[fr->callno]->rxcore.tv_usec = 0;
2258 /* wipe "last" if stamps have jumped backwards */
2260 iaxs[fr->callno]->last = 0;
2261 /* should we also empty history? */
2264 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2265 frame we received. (initially the very first, but also see code just above here).
2266 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2267 Called by IAX thread, with iaxsl lock held. */
2268 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2270 /* Rotate our history queue of "lateness". Don't worry about those initial
2271 zeros because the first entry will always be zero */
2272 for (x=0;x<MEMORY_SIZE - 1;x++)
2273 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2274 /* Add a history entry for this one */
2275 iaxs[fr->callno]->history[x] = ms;
2284 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2285 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2286 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2287 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2288 fr->af.delivery.tv_sec += fr->ts / 1000;
2289 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2290 if (fr->af.delivery.tv_usec >= 1000000) {
2291 fr->af.delivery.tv_usec -= 1000000;
2292 fr->af.delivery.tv_sec += 1;
2298 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2300 fr->af.delivery.tv_sec = 0;
2301 fr->af.delivery.tv_usec = 0;
2305 /* Initialize the minimum to reasonable values. It's too much
2306 work to do the same for the maximum, repeatedly */
2307 min=iaxs[fr->callno]->history[0];
2308 for (z=0;z < iax2_dropcount + 1;z++) {
2309 /* Start very optimistic ;-) */
2311 for (x=0;x<MEMORY_SIZE;x++) {
2312 if (max < iaxs[fr->callno]->history[x]) {
2313 /* We have a candidate new maximum value. Make
2314 sure it's not in our drop list */
2316 for (y=0;!match && (y<z);y++)
2317 match |= (drops[y] == x);
2319 /* It's not in our list, use it as the new maximum */
2320 max = iaxs[fr->callno]->history[x];
2326 /* On our first pass, find the minimum too */
2327 if (min > iaxs[fr->callno]->history[x])
2328 min = iaxs[fr->callno]->history[x];
2341 type = JB_TYPE_CONTROL;
2344 if(fr->af.frametype == AST_FRAME_VOICE) {
2345 type = JB_TYPE_VOICE;
2346 len = get_samples(&fr->af)/8;
2347 } else if(fr->af.frametype == AST_FRAME_CNG) {
2348 type = JB_TYPE_SILENCE;
2351 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2356 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2357 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2358 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2359 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2360 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2363 /* deliver any frames in the jb */
2364 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2365 __do_deliver(frame.data);
2367 jb_reset(iaxs[fr->callno]->jb);
2369 if (iaxs[fr->callno]->jbid > -1)
2370 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2372 iaxs[fr->callno]->jbid = -1;
2374 /* deliver this frame now */
2381 /* insert into jitterbuffer */
2382 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2383 if(jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2384 calc_rxstamp(iaxs[fr->callno],fr->ts)) == JB_DROP) {
2385 iax2_frame_free(fr);
2387 update_jbsched(iaxs[fr->callno]);
2389 /* Just for reference, keep the "jitter" value, the difference between the
2390 earliest and the latest. */
2392 iaxs[fr->callno]->jitter = max - min;
2394 /* IIR filter for keeping track of historic jitter, but always increase
2395 historic jitter immediately for increase */
2397 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2398 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2400 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2401 iaxs[fr->callno]->historicjitter;
2403 /* If our jitter buffer is too big (by a significant margin), then we slowly
2404 shrink it to avoid letting the change be perceived */
2405 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2406 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2408 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2409 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2410 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2411 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2412 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2413 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2415 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2416 buffer immediately to accomodate it (and a little more). */
2417 if (max > iaxs[fr->callno]->jitterbuffer)
2418 iaxs[fr->callno]->jitterbuffer = max
2419 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2421 /* update "min", just for RRs and stats */
2422 iaxs[fr->callno]->min = min;
2424 /* If the caller just wanted us to update, return now */
2428 /* Subtract the lateness from our jitter buffer to know how long to wait
2429 before sending our packet. */
2430 delay = iaxs[fr->callno]->jitterbuffer - ms;
2432 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2433 if (delay > maxjitterbuffer)
2434 delay = maxjitterbuffer;
2436 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2437 /* If frame came from trunk, also don't do any delay */
2438 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2442 /* Log jitter stats for possible offline analysis */
2443 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",
2444 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2445 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2446 min, max, iaxs[fr->callno]->jitterbuffer,
2447 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2449 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2453 /* Don't deliver it more than 4 ms late */
2454 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2456 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2460 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2461 iaxs[fr->callno]->frames_dropped++;
2462 /* Free our iax frame */
2463 iax2_frame_free(fr);
2467 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2468 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2474 static int iax2_transmit(struct iax_frame *fr)
2476 /* Lock the queue and place this packet at the end */
2479 /* By setting this to 0, the network thread will send it for us, and
2480 queue retransmission if necessary */
2482 ast_mutex_lock(&iaxq.lock);
2489 iaxq.tail->next = fr;
2490 fr->prev = iaxq.tail;
2494 ast_mutex_unlock(&iaxq.lock);
2495 /* Wake up the network thread */
2496 pthread_kill(netthreadid, SIGURG);
2502 static int iax2_digit(struct ast_channel *c, char digit)
2504 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2507 static int iax2_sendtext(struct ast_channel *c, const char *text)
2510 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2511 0, 0, text, strlen(text) + 1, -1);
2514 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2516 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2519 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2521 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2524 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2526 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2527 ast_mutex_lock(&iaxsl[callno]);
2529 iaxs[callno]->owner = newchan;
2531 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2532 ast_mutex_unlock(&iaxsl[callno]);
2536 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2537 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2539 static void destroy_user(struct iax2_user *user);
2540 static int expire_registry(void *data);
2542 static struct iax2_peer *realtime_peer(const char *peername)
2544 struct ast_variable *var;
2545 struct ast_variable *tmp;
2546 struct iax2_peer *peer=NULL;
2547 time_t regseconds, nowtime;
2549 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2551 /* Make sure it's not a user only... */
2552 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2557 if (!strcasecmp(tmp->name, "type")) {
2558 if (strcasecmp(tmp->value, "friend") &&
2559 strcasecmp(tmp->value, "peer")) {
2560 /* Whoops, we weren't supposed to exist! */
2565 } else if (!strcasecmp(tmp->name, "regseconds")) {
2566 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2568 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2569 inet_aton(tmp->value, &(peer->addr.sin_addr));
2570 } else if (!strcasecmp(tmp->name, "port")) {
2571 peer->addr.sin_port = htons(atoi(tmp->value));
2572 } else if (!strcasecmp(tmp->name, "host")) {
2573 if (!strcasecmp(tmp->value, "dynamic"))
2579 /* Add some finishing touches, addresses, etc */
2580 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2581 ast_mutex_lock(&peerl.lock);
2582 peer->next = peerl.peers;
2584 ast_mutex_unlock(&peerl.lock);
2585 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2586 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2587 if (peer->expire > -1) {
2588 ast_sched_del(sched, peer->expire);
2590 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void *)peer);
2593 ast_set_flag(peer, IAX_TEMPONLY);
2596 if (peer && dynamic) {
2598 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2599 memset(&peer->addr, 0, sizeof(peer->addr));
2601 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2605 ast_variables_destroy(var);
2610 static struct iax2_user *realtime_user(const char *username)
2612 struct ast_variable *var;
2613 struct ast_variable *tmp;
2614 struct iax2_user *user=NULL;
2615 var = ast_load_realtime("iaxusers", "name", username, NULL);
2617 /* Make sure it's not a user only... */
2618 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2620 /* Add some finishing touches, addresses, etc */
2621 if(ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2622 ast_mutex_lock(&userl.lock);
2623 user->next = userl.users;
2625 ast_mutex_unlock(&userl.lock);
2626 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2628 ast_set_flag(user, IAX_TEMPONLY);
2632 if (!strcasecmp(tmp->name, "type")) {
2633 if (strcasecmp(tmp->value, "friend") &&
2634 strcasecmp(tmp->value, "user")) {
2635 /* Whoops, we weren't supposed to exist! */
2644 ast_variables_destroy(var);
2649 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2653 char regseconds[20];
2657 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2658 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2659 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2660 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2664 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani,
2665 int *maxtime, char *peer, char *context, int *trunk,
2666 int *notransfer, int *usejitterbuf, int *forcejitterbuf, int *encmethods,
2667 char *username, int usernlen, char *secret, int seclen,
2668 int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2671 struct ast_hostent ahp; struct hostent *hp;
2672 struct iax2_peer *p;
2681 *sockfd = defaultsockfd;
2682 sin->sin_family = AF_INET;
2683 p = find_peer(peer, 1);
2686 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2687 (!p->maxms || ((p->lastms > 0) && (p->lastms <= p->maxms)))) {
2690 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2693 *sendani = ast_test_flag(p, IAX_SENDANI); /* Whether we transmit ANI */
2695 *maxtime = p->maxms; /* Max time they should take */
2697 strncpy(context, p->context, AST_MAX_EXTENSION - 1);
2699 strncpy(peercontext, p->peercontext, AST_MAX_EXTENSION - 1);
2701 *trunk = ast_test_flag(p, IAX_TRUNK);
2703 *capability = p->capability;
2705 *encmethods = p->encmethods;
2707 strncpy(username, p->username, usernlen);
2708 if (p->addr.sin_addr.s_addr) {
2709 sin->sin_addr = p->addr.sin_addr;
2710 sin->sin_port = p->addr.sin_port;
2712 sin->sin_addr = p->defaddr.sin_addr;
2713 sin->sin_port = p->defaddr.sin_port;
2716 *sockfd = p->sockfd;
2718 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2720 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2722 *forcejitterbuf = ast_test_flag(p, IAX_FORCEJITTERBUF);
2724 if (!ast_strlen_zero(p->dbsecret)) {
2725 char *family, *key=NULL;
2726 family = ast_strdupa(p->dbsecret);
2728 key = strchr(family, '/');
2734 if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2735 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2736 if (ast_test_flag(p, IAX_TEMPONLY))
2741 strncpy(secret, p->secret, seclen); /* safe */
2744 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2746 if (ast_test_flag(p, IAX_TEMPONLY))
2754 if(pref_str) { /* use global iax prefs for unknown peer/user */
2755 ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2758 hp = ast_gethostbyname(peer, &ahp);
2760 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2761 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2764 ast_log(LOG_WARNING, "No such host: %s\n", peer);
2769 if (ast_test_flag(p, IAX_TEMPONLY))
2774 static int auto_congest(void *nothing)
2776 int callno = PTR_TO_CALLNO(nothing);
2777 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2778 ast_mutex_lock(&iaxsl[callno]);
2780 iaxs[callno]->initid = -1;
2781 iax2_queue_frame(callno, &f);
2782 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2784 ast_mutex_unlock(&iaxsl[callno]);
2788 static unsigned int iax2_datetime(char *tz)
2794 localtime_r(&t, &tm);
2795 if (!ast_strlen_zero(tz))
2796 ast_localtime(&t, &tm, tz);
2797 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2798 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2799 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2800 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2801 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2802 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2806 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2808 struct sockaddr_in sin;
2813 char *secret = NULL;
2815 char *l=NULL, *n=NULL;
2816 struct iax_ie_data ied;
2817 char myrdest [5] = "s";
2818 char context[AST_MAX_EXTENSION] ="";
2819 char peercontext[AST_MAX_EXTENSION] ="";
2820 char *portno = NULL;
2822 int encmethods=iax2_encryption;
2823 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2825 char storedusern[80], storedsecret[80];
2829 memset(out_prefs,0,32);
2831 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2832 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2835 strncpy(host, dest, sizeof(host)-1);
2837 strsep(&stringp, "/");
2838 /* If no destination extension specified, use 's' */
2839 rdest = strsep(&stringp, "/");
2843 /* Check for trailing options */
2844 opts = strsep(&stringp, "/");
2849 strsep(&stringp, "@");
2850 rcontext = strsep(&stringp, "@");
2852 strsep(&stringp, "@");
2853 username = strsep(&stringp, "@");
2855 /* Really the second argument is the host, not the username */
2863 username = strsep(&stringp, ":");
2864 secret = strsep(&stringp, ":");
2867 if (strsep(&stringp, ":")) {
2869 strsep(&stringp, ":");
2870 portno = strsep(&stringp, ":");
2872 if (create_addr(&sin, NULL, NULL, NULL, hname, context, NULL, NULL, NULL, NULL, &encmethods, storedusern, sizeof(storedusern) - 1, storedsecret, sizeof(storedsecret) - 1, NULL, peercontext, tz, sizeof(tz), out_prefs, sizeof(out_prefs), NULL)) {
2873 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2876 /* Keep track of the context for outgoing calls too */
2877 strncpy(c->context, context, sizeof(c->context) - 1);
2879 sin.sin_port = htons(atoi(portno));
2882 n = c->cid.cid_name;
2883 /* Now build request */
2884 memset(&ied, 0, sizeof(ied));
2885 /* On new call, first IE MUST be IAX version of caller */
2886 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2887 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2888 if (strchr(opts, 'a')) {
2889 /* Request auto answer */
2890 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2892 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2895 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2896 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2898 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2899 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2900 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2902 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2903 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2904 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2906 if (c->language && !ast_strlen_zero(c->language))
2907 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2908 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2909 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2911 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2912 else if (strlen(peercontext))
2913 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2914 if (!username && !ast_strlen_zero(storedusern))
2915 username = storedusern;
2917 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2919 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2920 if (!secret && !ast_strlen_zero(storedsecret))
2921 secret = storedsecret;
2922 ast_mutex_lock(&iaxsl[callno]);
2923 if (!ast_strlen_zero(c->context))
2924 strncpy(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context) - 1);
2926 strncpy(iaxs[callno]->username, username, sizeof(iaxs[callno]->username)-1);
2927 iaxs[callno]->encmethods = encmethods;
2929 if (secret[0] == '[') {
2930 /* This is an RSA key, not a normal secret */
2931 strncpy(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret)-1);
2932 if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2933 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2936 strncpy(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret)-1);
2938 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2939 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2940 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2941 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2942 /* Transmit the string in a "NEW" request */
2944 /* XXX We have no equivalent XXX */
2945 if (option_verbose > 2)
2946 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2948 if (iaxs[callno]->maxtime) {
2949 /* Initialize pingtime and auto-congest time */
2950 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2951 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2952 } else if (autokill) {
2953 iaxs[callno]->pingtime = autokill / 2;
2954 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2956 send_command(iaxs[callno], AST_FRAME_IAX,
2957 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2958 ast_mutex_unlock(&iaxsl[callno]);
2959 ast_setstate(c, AST_STATE_RINGING);
2963 static int iax2_hangup(struct ast_channel *c)
2965 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2967 struct iax_ie_data ied;
2968 memset(&ied, 0, sizeof(ied));
2969 ast_mutex_lock(&iaxsl[callno]);
2970 if (callno && iaxs[callno]) {
2971 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2972 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2973 /* Send the hangup unless we have had a transmission error or are already gone */
2974 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2975 if (!iaxs[callno]->error && !alreadygone)
2976 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2977 /* Explicitly predestroy it */
2978 iax2_predestroy_nolock(callno);
2979 /* If we were already gone to begin with, destroy us now */
2981 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2982 iax2_destroy_nolock(callno);
2985 ast_mutex_unlock(&iaxsl[callno]);
2986 if (option_verbose > 2)
2987 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2991 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2993 struct ast_option_header *h;
2995 h = malloc(datalen + sizeof(struct ast_option_header));
2997 h->flag = AST_OPTION_FLAG_REQUEST;
2998 h->option = htons(option);
2999 memcpy(h->data, data, datalen);
3000 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3001 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
3005 ast_log(LOG_WARNING, "Out of memory\n");
3009 static struct ast_frame *iax2_read(struct ast_channel *c)
3011 static struct ast_frame f = { AST_FRAME_NULL, };
3012 ast_log(LOG_NOTICE, "I should never be called!\n");
3016 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3019 struct iax_ie_data ied0;
3020 struct iax_ie_data ied1;
3021 unsigned int transferid = rand();
3022 memset(&ied0, 0, sizeof(ied0));
3023 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3024 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3025 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3027 memset(&ied1, 0, sizeof(ied1));
3028 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3029 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3030 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3032 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3035 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3038 iaxs[callno0]->transferring = TRANSFER_BEGIN;
3039 iaxs[callno1]->transferring = TRANSFER_BEGIN;
3043 static void lock_both(unsigned short callno0, unsigned short callno1)
3045 ast_mutex_lock(&iaxsl[callno0]);
3046 while (ast_mutex_trylock(&iaxsl[callno1])) {
3047 ast_mutex_unlock(&iaxsl[callno0]);
3049 ast_mutex_lock(&iaxsl[callno0]);
3053 static void unlock_both(unsigned short callno0, unsigned short callno1)
3055 ast_mutex_unlock(&iaxsl[callno1]);
3056 ast_mutex_unlock(&iaxsl[callno0]);
3059 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
3061 struct ast_channel *cs[3];
3062 struct ast_channel *who;
3065 int transferstarted=0;
3066 struct ast_frame *f;
3067 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3068 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3069 struct timeval waittimer = {0, 0}, tv;
3071 lock_both(callno0, callno1);
3072 /* Put them in native bridge mode */
3073 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3074 iaxs[callno0]->bridgecallno = callno1;
3075 iaxs[callno1]->bridgecallno = callno0;
3077 unlock_both(callno0, callno1);
3079 /* If not, try to bridge until we can execute a transfer, if we can */
3082 for (/* ever */;;) {
3083 /* Check in case we got masqueraded into */