2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * Implementation of Inter-Asterisk eXchange Version 2
27 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29 #include "asterisk/lock.h"
30 #include "asterisk/frame.h"
31 #include "asterisk/channel.h"
32 #include "asterisk/logger.h"
33 #include "asterisk/module.h"
34 #include "asterisk/pbx.h"
35 #include "asterisk/sched.h"
36 #include "asterisk/io.h"
37 #include "asterisk/config.h"
38 #include "asterisk/options.h"
39 #include "asterisk/cli.h"
40 #include "asterisk/translate.h"
41 #include "asterisk/md5.h"
42 #include "asterisk/cdr.h"
43 #include "asterisk/crypto.h"
44 #include "asterisk/acl.h"
45 #include "asterisk/manager.h"
46 #include "asterisk/callerid.h"
47 #include "asterisk/app.h"
48 #include "asterisk/astdb.h"
49 #include "asterisk/musiconhold.h"
50 #include "asterisk/features.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/localtime.h"
54 #include "asterisk/aes.h"
55 #include "asterisk/dnsmgr.h"
56 #include "asterisk/devicestate.h"
57 #include "asterisk/netsock.h"
60 #include <arpa/inet.h>
62 #include <sys/socket.h>
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
67 #include <sys/signal.h>
76 #include <sys/types.h>
80 #include <sys/ioctl.h>
82 #include <linux/zaptel.h>
85 #endif /* __linux__ */
88 #include "iax2-parser.h"
89 #include "iax2-provision.h"
91 /* Define NEWJB to use the new channel independent jitterbuffer,
92 * otherwise, use the old jitterbuffer */
96 #include "../jitterbuf.h"
100 #define IPTOS_MINCOST 0x02
104 static int nochecksums = 0;
108 * Uncomment to try experimental IAX bridge optimization,
109 * designed to reduce latency when IAX calls cannot
110 * be trasnferred -- obsolete
113 /* #define BRIDGE_OPTIMIZATION */
116 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
117 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
119 #define DEFAULT_RETRY_TIME 1000
120 #define MEMORY_SIZE 100
121 #define DEFAULT_DROP 3
122 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
123 but keeps the division between trunked and non-trunked better. */
124 #define TRUNK_CALL_START 0x4000
126 #define DEBUG_SUPPORT
128 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
130 /* Sample over last 100 units to determine historic jitter */
133 static struct ast_codec_pref prefs;
135 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
136 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
137 static const char channeltype[] = "IAX2";
139 static char context[80] = "default";
141 static char language[MAX_LANGUAGE] = "";
142 static char regcontext[AST_MAX_CONTEXT] = "";
144 static int max_retries = 4;
145 static int ping_time = 20;
146 static int lagrq_time = 10;
147 static int maxtrunkcall = TRUNK_CALL_START;
148 static int maxnontrunkcall = 1;
149 static int maxjitterbuffer=1000;
151 static int resyncthreshold=1000;
152 static int maxjitterinterps=10;
154 static int jittershrinkrate=2;
155 static int trunkfreq = 20;
156 static int authdebug = 1;
157 static int autokill = 0;
158 static int iaxcompat = 0;
160 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
162 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
166 static int min_reg_expire;
167 static int max_reg_expire;
169 static int timingfd = -1; /* Timing file descriptor */
171 static struct ast_netsock_list *netsock;
172 static int defaultsockfd = -1;
175 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
177 int (*iax2_regfunk)(char *username, int onoff) = NULL;
180 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
182 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
183 ~AST_FORMAT_SLINEAR & \
187 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
191 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
195 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
196 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
197 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
199 static struct io_context *io;
200 static struct sched_context *sched;
202 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
204 static int iax2_dropcount = DEFAULT_DROP;
206 static int iaxdebug = 0;
208 static int iaxtrunkdebug = 0;
210 static int test_losspct = 0;
212 static int test_late = 0;
213 static int test_resync = 0;
214 static int test_jit = 0;
215 static int test_jitpct = 0;
216 #endif /* IAXTESTS */
218 static char accountcode[AST_MAX_ACCOUNT_CODE];
219 static int amaflags = 0;
220 static int delayreject = 0;
221 static int iax2_encryption = 0;
223 static struct ast_flags globalflags = { 0 };
225 static pthread_t netthreadid = AST_PTHREADT_NULL;
227 #define IAX_STATE_STARTED (1 << 0)
228 #define IAX_STATE_AUTHENTICATED (1 << 1)
229 #define IAX_STATE_TBD (1 << 2)
231 struct iax2_context {
232 char context[AST_MAX_CONTEXT];
233 struct iax2_context *next;
236 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
237 #define IAX_DELME (1 << 1) /* Needs to be deleted */
238 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
239 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
240 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
241 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
242 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
243 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
244 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
245 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
246 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
247 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
248 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
249 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
250 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
251 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
252 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
253 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
254 #define IAX_RTUPDATE (1 << 18) /* Send a realtime update */
255 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
256 #define IAX_FORCEJITTERBUF (1 << 20) /* Force jitterbuffer, even when bridged to a channel that can take jitter */
257 #define IAX_RTIGNOREREGEXPIRE (1 << 21)
258 #define IAX_TRUNKTIMESTAMPS (1 << 22) /* Send trunk timestamps */
260 static int global_rtautoclear = 120;
262 static int reload_config(void);
263 static int iax2_reload(int fd, int argc, char *argv[]);
272 char accountcode[AST_MAX_ACCOUNT_CODE];
273 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
274 char language[MAX_LANGUAGE];
278 char cid_num[AST_MAX_EXTENSION];
279 char cid_name[AST_MAX_EXTENSION];
280 struct ast_codec_pref prefs;
282 struct iax2_context *contexts;
283 struct iax2_user *next;
284 struct ast_variable *vars;
292 char outkey[80]; /* What key we use to talk to this peer */
293 char context[AST_MAX_CONTEXT]; /* For transfers only */
294 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
295 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
296 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
297 struct ast_codec_pref prefs;
298 struct ast_dnsmgr_entry *dnsmgr; /* DNS refresh manager */
299 struct sockaddr_in addr;
301 int sockfd; /* Socket to use for transmission */
305 /* Dynamic Registration fields */
306 struct sockaddr_in defaddr; /* Default address if there is one */
307 int authmethods; /* Authentication methods (IAX_AUTH_*) */
308 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
309 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
311 /* Suggested caller id if registering */
312 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
313 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
315 int expire; /* Schedule entry for expiry */
316 int expiry; /* How soon to expire */
317 int capability; /* Capability */
318 char zonetag[80]; /* Time Zone */
321 int callno; /* Call number of POKE request */
322 int pokeexpire; /* When to expire poke */
323 int lastms; /* How long last response took (in ms), or -1 for no response */
324 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
326 int pokefreqok; /* How often to check if the host is up */
327 int pokefreqnotok; /* How often to check when the host has been determined to be down */
328 int historicms; /* How long recent average responses took */
329 int smoothing; /* Sample over how many units to determine historic ms */
332 struct iax2_peer *next;
335 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
337 static struct iax2_trunk_peer {
340 struct sockaddr_in addr;
341 struct timeval txtrunktime; /* Transmit trunktime */
342 struct timeval rxtrunktime; /* Receive trunktime */
343 struct timeval lasttxtime; /* Last transmitted trunktime */
344 struct timeval trunkact; /* Last trunk activity */
345 unsigned int lastsent; /* Last sent time */
346 /* Trunk data and length */
347 unsigned char *trunkdata;
348 unsigned int trunkdatalen;
349 unsigned int trunkdataalloc;
350 struct iax2_trunk_peer *next;
355 AST_MUTEX_DEFINE_STATIC(tpeerlock);
357 struct iax_firmware {
358 struct iax_firmware *next;
362 struct ast_iax2_firmware_header *fwh;
366 #define REG_STATE_UNREGISTERED 0
367 #define REG_STATE_REGSENT 1
368 #define REG_STATE_AUTHSENT 2
369 #define REG_STATE_REGISTERED 3
370 #define REG_STATE_REJECTED 4
371 #define REG_STATE_TIMEOUT 5
372 #define REG_STATE_NOAUTH 6
374 #define TRANSFER_NONE 0
375 #define TRANSFER_BEGIN 1
376 #define TRANSFER_READY 2
377 #define TRANSFER_RELEASED 3
378 #define TRANSFER_PASSTHROUGH 4
380 struct iax2_registry {
381 struct sockaddr_in addr; /* Who we connect to for registration purposes */
383 char secret[80]; /* Password or key name in []'s */
385 int expire; /* Sched ID of expiration */
386 int refresh; /* How often to refresh */
388 int messages; /* Message count */
389 int callno; /* Associated call number if applicable */
390 struct sockaddr_in us; /* Who the server thinks we are */
391 struct iax2_registry *next;
394 static struct iax2_registry *registrations;
396 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
397 #define MIN_RETRY_TIME 100
398 #define MAX_RETRY_TIME 10000
400 #define MAX_JITTER_BUFFER 50
401 #define MIN_JITTER_BUFFER 10
403 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
404 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
406 #define MAX_TIMESTAMP_SKEW 160 /* maximum difference between actual and predicted ts for sending */
408 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
409 #define TS_GAP_FOR_JB_RESYNC 5000
411 /* If we have more than this much excess real jitter buffer, shrink it. */
412 static int max_jitter_buffer = MAX_JITTER_BUFFER;
413 /* If we have less than this much excess real jitter buffer, enlarge it. */
414 static int min_jitter_buffer = MIN_JITTER_BUFFER;
426 struct chan_iax2_pvt {
427 /* Socket to send/receive on for this call */
429 /* Last received voice format */
431 /* Last received voice format */
433 /* Last sent voice format */
435 /* Last sent video format */
437 /* What we are capable of sending */
439 /* Last received timestamp */
441 /* Last sent timestamp - never send the same timestamp twice in a single call */
442 unsigned int lastsent;
443 /* Next outgoing timestamp if everything is good */
444 unsigned int nextpred;
445 /* True if the last voice we transmitted was not silence/CNG */
448 unsigned int pingtime;
449 /* Max time for initial response */
452 struct sockaddr_in addr;
453 struct ast_codec_pref prefs;
454 /* Our call number */
455 unsigned short callno;
457 unsigned short peercallno;
458 /* Peer selected format */
460 /* Peer capability */
462 /* timeval that we base our transmission on */
463 struct timeval offset;
464 /* timeval that we base our delivery on */
465 struct timeval rxcore;
467 /* The jitterbuffer */
469 /* active jb read scheduler id */
472 /* Historical delivery time */
473 int history[MEMORY_SIZE];
474 /* Current base jitterbuffer */
476 /* Current jitter measure */
478 /* Historic jitter value */
483 /* Error, as discovered by the manager */
485 /* Owner if we have one */
486 struct ast_channel *owner;
487 /* What's our state? */
489 /* Expiry (optional) */
491 /* Next outgoing sequence number */
492 unsigned char oseqno;
493 /* Next sequence number they have not yet acknowledged */
494 unsigned char rseqno;
495 /* Next incoming sequence number */
496 unsigned char iseqno;
497 /* Last incoming sequence number we have acknowledged */
498 unsigned char aseqno;
501 /* Default Context */
503 /* Caller ID if available */
506 /* Hidden Caller ID (i.e. ANI) if appropriate */
510 /* Requested Extension */
511 char exten[AST_MAX_EXTENSION];
512 /* Expected Username */
514 /* Expected Secret */
516 /* permitted authentication methods */
518 /* permitted encryption methods */
522 /* Public keys permitted keys for incoming authentication */
524 /* Private key for outgoing authentication */
526 /* Encryption AES-128 Key */
528 /* Decryption AES-128 Key */
530 /* 32 bytes of semi-random data */
531 unsigned char semirand[32];
532 /* Preferred language */
533 char language[MAX_LANGUAGE];
534 /* Hostname/peername for naming purposes */
536 /* Associated registry */
537 struct iax2_registry *reg;
538 /* Associated peer for poking */
539 struct iax2_peer *peerpoke;
543 /* Transferring status */
545 /* Transfer identifier */
547 /* Who we are IAX transfering to */
548 struct sockaddr_in transfer;
549 /* What's the new call number for the transfer */
550 unsigned short transfercallno;
551 /* Transfer decrypt AES-128 Key */
552 aes_encrypt_ctx tdcx;
554 /* Status of knowledge of peer ADSI capability */
557 /* Who we are bridged to */
558 unsigned short bridgecallno;
559 unsigned int bridgesfmt;
560 struct ast_trans_pvt *bridgetrans;
562 int pingid; /* Transmit PING request */
563 int lagid; /* Retransmit lag request */
564 int autoid; /* Auto hangup for Dialplan requestor */
565 int authid; /* Authentication rejection ID */
566 int authfail; /* Reason to report failure */
567 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
571 char dproot[AST_MAX_EXTENSION];
572 char accountcode[AST_MAX_ACCOUNT_CODE];
574 struct iax2_dpcache *dpentries;
575 struct ast_variable *vars;
576 /* last received remote rr */
577 struct iax_rr remote_rr;
578 /* Current base time: (just for stats) */
580 /* Dropped frame count: (just for stats) */
582 /* received frame count: (just for stats) */
586 static struct ast_iax2_queue {
587 struct iax_frame *head;
588 struct iax_frame *tail;
593 static struct ast_user_list {
594 struct iax2_user *users;
598 static struct ast_peer_list {
599 struct iax2_peer *peers;
603 static struct ast_firmware_list {
604 struct iax_firmware *wares;
608 /* Extension exists */
609 #define CACHE_FLAG_EXISTS (1 << 0)
610 /* Extension is nonexistent */
611 #define CACHE_FLAG_NONEXISTENT (1 << 1)
612 /* Extension can exist */
613 #define CACHE_FLAG_CANEXIST (1 << 2)
614 /* Waiting to hear back response */
615 #define CACHE_FLAG_PENDING (1 << 3)
617 #define CACHE_FLAG_TIMEOUT (1 << 4)
618 /* Request transmitted */
619 #define CACHE_FLAG_TRANSMITTED (1 << 5)
621 #define CACHE_FLAG_UNKNOWN (1 << 6)
623 #define CACHE_FLAG_MATCHMORE (1 << 7)
625 static struct iax2_dpcache {
626 char peercontext[AST_MAX_CONTEXT];
627 char exten[AST_MAX_EXTENSION];
629 struct timeval expiry;
631 unsigned short callno;
633 struct iax2_dpcache *next;
634 struct iax2_dpcache *peer; /* For linking in peers */
637 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
639 static void reg_source_db(struct iax2_peer *p);
640 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
642 static void destroy_peer(struct iax2_peer *peer);
643 static int ast_cli_netstats(int fd, int limit_fmt);
645 static void iax_debug_output(const char *data)
648 ast_verbose("%s", data);
651 static void iax_error_output(const char *data)
653 ast_log(LOG_WARNING, "%s", data);
657 static void jb_error_output(const char *fmt, ...)
663 vsnprintf(buf, 1024, fmt, args);
666 ast_log(LOG_ERROR, buf);
669 static void jb_warning_output(const char *fmt, ...)
675 vsnprintf(buf, 1024, fmt, args);
678 ast_log(LOG_WARNING, buf);
681 static void jb_debug_output(const char *fmt, ...)
687 vsnprintf(buf, 1024, fmt, args);
695 /* XXX We probably should use a mutex when working with this XXX */
696 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
697 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
698 static struct timeval lastused[IAX_MAX_CALLS];
701 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
702 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
703 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
704 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
705 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
706 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
707 static void destroy_user(struct iax2_user *user);
708 static int expire_registry(void *data);
709 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
710 static int iax2_do_register(struct iax2_registry *reg);
711 static void prune_peers(void);
712 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
713 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
715 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
716 static int iax2_devicestate(void *data);
717 static int iax2_digit(struct ast_channel *c, char digit);
718 static int iax2_sendtext(struct ast_channel *c, const char *text);
719 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
720 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
721 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
722 static int iax2_hangup(struct ast_channel *c);
723 static int iax2_answer(struct ast_channel *c);
724 static struct ast_frame *iax2_read(struct ast_channel *c);
725 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
726 static int iax2_indicate(struct ast_channel *c, int condition);
727 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
728 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
729 static int iax2_transfer(struct ast_channel *c, const char *dest);
730 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
732 static const struct ast_channel_tech iax2_tech = {
734 .description = tdesc,
735 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
736 .properties = AST_CHAN_TP_WANTSJITTER,
737 .requester = iax2_request,
738 .devicestate = iax2_devicestate,
739 .send_digit = iax2_digit,
740 .send_text = iax2_sendtext,
741 .send_image = iax2_sendimage,
742 .send_html = iax2_sendhtml,
744 .hangup = iax2_hangup,
745 .answer = iax2_answer,
748 .write_video = iax2_write,
749 .indicate = iax2_indicate,
750 .setoption = iax2_setoption,
751 .bridge = iax2_bridge,
752 .transfer = iax2_transfer,
756 static int send_ping(void *data)
758 int callno = (long)data;
759 /* Ping only if it's real, not if it's bridged */
761 #ifdef BRIDGE_OPTIMIZATION
762 if (!iaxs[callno]->bridgecallno)
764 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
770 static int get_encrypt_methods(const char *s)
773 if (!strcasecmp(s, "aes128"))
774 e = IAX_ENCRYPT_AES128;
775 else if (ast_true(s))
776 e = IAX_ENCRYPT_AES128;
782 static int send_lagrq(void *data)
784 int callno = (long)data;
785 /* Ping only if it's real not if it's bridged */
787 #ifdef BRIDGE_OPTIMIZATION
788 if (!iaxs[callno]->bridgecallno)
790 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
796 static unsigned char compress_subclass(int subclass)
800 /* If it's 128 or smaller, just return it */
801 if (subclass < IAX_FLAG_SC_LOG)
803 /* Otherwise find its power */
804 for (x = 0; x < IAX_MAX_SHIFT; x++) {
805 if (subclass & (1 << x)) {
807 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
813 return power | IAX_FLAG_SC_LOG;
816 static int uncompress_subclass(unsigned char csub)
818 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
819 if (csub & IAX_FLAG_SC_LOG) {
820 /* special case for 'compressed' -1 */
824 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
830 static struct iax2_peer *find_peer(const char *name, int realtime)
832 struct iax2_peer *peer;
833 ast_mutex_lock(&peerl.lock);
834 for(peer = peerl.peers; peer; peer = peer->next) {
835 if (!strcasecmp(peer->name, name)) {
839 ast_mutex_unlock(&peerl.lock);
840 if(!peer && realtime)
841 peer = realtime_peer(name, NULL);
845 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
847 struct iax2_peer *peer;
850 ast_mutex_lock(&peerl.lock);
853 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
854 (peer->addr.sin_port == sin.sin_port)) {
855 ast_copy_string(host, peer->name, len);
862 ast_mutex_unlock(&peerl.lock);
864 peer = realtime_peer(NULL, &sin);
866 ast_copy_string(host, peer->name, len);
867 if (ast_test_flag(peer, IAX_TEMPONLY))
874 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
876 struct chan_iax2_pvt *tmp;
877 tmp = malloc(sizeof(struct chan_iax2_pvt));
879 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
883 tmp->transfercallno = 0;
884 tmp->bridgecallno = 0;
890 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
891 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
892 ast_copy_string(tmp->host, host, sizeof(tmp->host));
899 jbconf.max_jitterbuf = maxjitterbuffer;
900 jbconf.resync_threshold = resyncthreshold;
901 jbconf.max_contig_interp = maxjitterinterps;
902 jb_setconf(tmp->jb,&jbconf);
909 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
911 /* Malloc() a copy of a frame */
912 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
914 memcpy(new, fr, sizeof(struct iax_frame));
915 iax_frame_wrap(new, &fr->af);
918 new->direction = DIRECTION_INGRESS;
924 #define NEW_PREVENT 0
928 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
930 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
931 (cur->addr.sin_port == sin->sin_port)) {
932 /* This is the main host */
933 if ((cur->peercallno == callno) ||
934 ((dcallno == cur->callno) && !cur->peercallno)) {
935 /* That's us. Be sure we keep track of the peer call number */
939 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
940 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
941 /* We're transferring */
942 if (dcallno == cur->callno)
948 static void update_max_trunk(void)
950 int max = TRUNK_CALL_START;
952 /* XXX Prolly don't need locks here XXX */
953 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
958 if (option_debug && iaxdebug)
959 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
962 static void update_max_nontrunk(void)
966 /* XXX Prolly don't need locks here XXX */
967 for (x=1;x<TRUNK_CALL_START - 1; x++) {
971 maxnontrunkcall = max;
972 if (option_debug && iaxdebug)
973 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
976 static int make_trunk(unsigned short callno, int locked)
981 if (iaxs[callno]->oseqno) {
982 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
985 if (callno & TRUNK_CALL_START) {
986 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
989 gettimeofday(&now, NULL);
990 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
991 ast_mutex_lock(&iaxsl[x]);
992 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
993 iaxs[x] = iaxs[callno];
996 /* Update the two timers that should have been started */
997 if (iaxs[x]->pingid > -1)
998 ast_sched_del(sched, iaxs[x]->pingid);
999 if (iaxs[x]->lagid > -1)
1000 ast_sched_del(sched, iaxs[x]->lagid);
1001 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1002 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1004 ast_mutex_unlock(&iaxsl[callno]);
1007 ast_mutex_unlock(&iaxsl[x]);
1010 ast_mutex_unlock(&iaxsl[x]);
1012 if (x >= IAX_MAX_CALLS - 1) {
1013 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1016 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1017 /* We move this call from a non-trunked to a trunked call */
1019 update_max_nontrunk();
1023 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1028 char iabuf[INET_ADDRSTRLEN];
1030 if (new <= NEW_ALLOW) {
1031 /* Look for an existing connection first */
1032 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1033 ast_mutex_lock(&iaxsl[x]);
1035 /* Look for an exact match */
1036 if (match(sin, callno, dcallno, iaxs[x])) {
1040 ast_mutex_unlock(&iaxsl[x]);
1042 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1043 ast_mutex_lock(&iaxsl[x]);
1045 /* Look for an exact match */
1046 if (match(sin, callno, dcallno, iaxs[x])) {
1050 ast_mutex_unlock(&iaxsl[x]);
1053 if ((res < 1) && (new >= NEW_ALLOW)) {
1054 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1055 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1056 gettimeofday(&now, NULL);
1057 for (x=1;x<TRUNK_CALL_START;x++) {
1058 /* Find first unused call number that hasn't been used in a while */
1059 ast_mutex_lock(&iaxsl[x]);
1060 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1061 ast_mutex_unlock(&iaxsl[x]);
1063 /* We've still got lock held if we found a spot */
1064 if (x >= TRUNK_CALL_START) {
1065 ast_log(LOG_WARNING, "No more space\n");
1068 iaxs[x] = new_iax(sin, lockpeer, host);
1069 update_max_nontrunk();
1071 if (option_debug && iaxdebug)
1072 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1073 iaxs[x]->sockfd = sockfd;
1074 iaxs[x]->addr.sin_port = sin->sin_port;
1075 iaxs[x]->addr.sin_family = sin->sin_family;
1076 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1077 iaxs[x]->peercallno = callno;
1078 iaxs[x]->callno = x;
1079 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1080 iaxs[x]->expiry = min_reg_expire;
1081 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1082 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1083 iaxs[x]->amaflags = amaflags;
1084 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1085 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1087 ast_log(LOG_WARNING, "Out of resources\n");
1088 ast_mutex_unlock(&iaxsl[x]);
1091 ast_mutex_unlock(&iaxsl[x]);
1097 static void iax2_frame_free(struct iax_frame *fr)
1099 if (fr->retrans > -1)
1100 ast_sched_del(sched, fr->retrans);
1104 static int iax2_queue_frame(int callno, struct ast_frame *f)
1106 /* Assumes lock for callno is already held... */
1108 if (iaxs[callno] && iaxs[callno]->owner) {
1109 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1110 /* Avoid deadlock by pausing and trying again */
1111 ast_mutex_unlock(&iaxsl[callno]);
1113 ast_mutex_lock(&iaxsl[callno]);
1115 ast_queue_frame(iaxs[callno]->owner, f);
1116 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1125 static void destroy_firmware(struct iax_firmware *cur)
1127 /* Close firmware */
1129 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1135 static int try_firmware(char *s)
1138 struct iax_firmware *cur;
1143 struct ast_iax2_firmware_header *fwh, fwh2;
1144 struct MD5Context md5;
1145 unsigned char sum[16];
1146 unsigned char buf[1024];
1150 s2 = alloca(strlen(s) + 100);
1152 ast_log(LOG_WARNING, "Alloca failed!\n");
1155 last = strrchr(s, '/');
1160 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1161 res = stat(s, &stbuf);
1163 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1166 /* Make sure it's not a directory */
1167 if (S_ISDIR(stbuf.st_mode))
1169 ifd = open(s, O_RDONLY);
1171 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1174 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1176 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1180 /* Unlink our newly created file */
1183 /* Now copy the firmware into it */
1184 len = stbuf.st_size;
1187 if (chunk > sizeof(buf))
1188 chunk = sizeof(buf);
1189 res = read(ifd, buf, chunk);
1191 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1196 res = write(fd, buf, chunk);
1198 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1206 /* Return to the beginning */
1207 lseek(fd, 0, SEEK_SET);
1208 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1209 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1213 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1214 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1218 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1219 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1223 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1224 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1228 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1230 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1235 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1236 MD5Final(sum, &md5);
1237 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1238 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1239 munmap(fwh, stbuf.st_size);
1245 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1246 /* Found a candidate */
1247 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1248 /* The version we have on loaded is older, load this one instead */
1250 /* This version is no newer than what we have. Don't worry about it.
1251 We'll consider it a proper load anyhow though */
1252 munmap(fwh, stbuf.st_size);
1259 /* Allocate a new one and link it */
1260 cur = malloc(sizeof(struct iax_firmware));
1262 memset(cur, 0, sizeof(struct iax_firmware));
1264 cur->next = waresl.wares;
1270 munmap(cur->fwh, cur->mmaplen);
1276 cur->mmaplen = stbuf.st_size;
1282 static int iax_check_version(char *dev)
1285 struct iax_firmware *cur;
1286 if (dev && !ast_strlen_zero(dev)) {
1287 ast_mutex_lock(&waresl.lock);
1290 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1291 res = ntohs(cur->fwh->version);
1296 ast_mutex_unlock(&waresl.lock);
1301 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1304 unsigned int bs = desc & 0xff;
1305 unsigned int start = (desc >> 8) & 0xffffff;
1307 struct iax_firmware *cur;
1308 if (dev && !ast_strlen_zero((char *)dev) && bs) {
1310 ast_mutex_lock(&waresl.lock);
1313 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1314 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1315 if (start < ntohl(cur->fwh->datalen)) {
1316 bytes = ntohl(cur->fwh->datalen) - start;
1319 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1322 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1332 ast_mutex_unlock(&waresl.lock);
1338 static void reload_firmware(void)
1340 struct iax_firmware *cur, *curl, *curp;
1345 /* Mark all as dead */
1346 ast_mutex_lock(&waresl.lock);
1352 /* Now that we've freed them, load the new ones */
1353 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1356 while((de = readdir(fwd))) {
1357 if (de->d_name[0] != '.') {
1358 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1359 if (!try_firmware(fn)) {
1360 if (option_verbose > 1)
1361 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1367 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1369 /* Clean up leftovers */
1381 destroy_firmware(curl);
1386 ast_mutex_unlock(&waresl.lock);
1389 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1391 static int __do_deliver(void *data)
1393 /* Just deliver the packet by using queueing. This is called by
1394 the IAX thread with the iaxsl lock held. */
1395 struct iax_frame *fr = data;
1397 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1398 iax2_queue_frame(fr->callno, &fr->af);
1399 /* Free our iax frame */
1400 iax2_frame_free(fr);
1401 /* And don't run again */
1406 static int do_deliver(void *data)
1408 /* Locking version of __do_deliver */
1409 struct iax_frame *fr = data;
1410 int callno = fr->callno;
1412 ast_mutex_lock(&iaxsl[callno]);
1413 res = __do_deliver(data);
1414 ast_mutex_unlock(&iaxsl[callno]);
1419 static int handle_error(void)
1421 /* XXX Ideally we should figure out why an error occured and then abort those
1422 rather than continuing to try. Unfortunately, the published interface does
1423 not seem to work XXX */
1425 struct sockaddr_in *sin;
1428 struct sock_extended_err e;
1433 m.msg_controllen = sizeof(e);
1435 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1437 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1439 if (m.msg_controllen) {
1440 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1442 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1444 ast_log(LOG_WARNING, "No address detected??\n");
1446 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1453 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1456 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1460 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1467 static int send_packet(struct iax_frame *f)
1470 char iabuf[INET_ADDRSTRLEN];
1471 /* Called with iaxsl held */
1472 if (option_debug > 2 && iaxdebug)
1473 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));
1474 /* Don't send if there was an error, but return error instead */
1476 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1479 if (!iaxs[f->callno])
1481 if (iaxs[f->callno]->error)
1485 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, 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]->transfer,
1487 sizeof(iaxs[f->callno]->transfer));
1490 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1491 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1492 sizeof(iaxs[f->callno]->addr));
1495 if (option_debug && iaxdebug)
1496 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1504 static int iax2_predestroy(int callno)
1506 struct ast_channel *c;
1507 struct chan_iax2_pvt *pvt;
1508 ast_mutex_lock(&iaxsl[callno]);
1511 ast_mutex_unlock(&iaxsl[callno]);
1514 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1515 /* No more pings or lagrq's */
1516 if (pvt->pingid > -1)
1517 ast_sched_del(sched, pvt->pingid);
1518 if (pvt->lagid > -1)
1519 ast_sched_del(sched, pvt->lagid);
1520 if (pvt->autoid > -1)
1521 ast_sched_del(sched, pvt->autoid);
1522 if (pvt->authid > -1)
1523 ast_sched_del(sched, pvt->authid);
1524 if (pvt->initid > -1)
1525 ast_sched_del(sched, pvt->initid);
1528 ast_sched_del(sched, pvt->jbid);
1536 ast_set_flag(pvt, IAX_ALREADYGONE);
1540 c->_softhangup |= AST_SOFTHANGUP_DEV;
1542 ast_queue_hangup(c);
1544 ast_mutex_lock(&usecnt_lock);
1547 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1548 ast_mutex_unlock(&usecnt_lock);
1550 ast_mutex_unlock(&iaxsl[callno]);
1551 ast_update_use_count();
1555 static int iax2_predestroy_nolock(int callno)
1558 ast_mutex_unlock(&iaxsl[callno]);
1559 res = iax2_predestroy(callno);
1560 ast_mutex_lock(&iaxsl[callno]);
1564 static void iax2_destroy(int callno)
1566 struct chan_iax2_pvt *pvt;
1567 struct iax_frame *cur;
1568 struct ast_channel *owner;
1571 ast_mutex_lock(&iaxsl[callno]);
1573 gettimeofday(&lastused[callno], NULL);
1580 if (ast_mutex_trylock(&owner->lock)) {
1581 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1582 ast_mutex_unlock(&iaxsl[callno]);
1588 iaxs[callno] = NULL;
1592 /* No more pings or lagrq's */
1593 if (pvt->pingid > -1)
1594 ast_sched_del(sched, pvt->pingid);
1595 if (pvt->lagid > -1)
1596 ast_sched_del(sched, pvt->lagid);
1597 if (pvt->autoid > -1)
1598 ast_sched_del(sched, pvt->autoid);
1599 if (pvt->authid > -1)
1600 ast_sched_del(sched, pvt->authid);
1601 if (pvt->initid > -1)
1602 ast_sched_del(sched, pvt->initid);
1605 ast_sched_del(sched, pvt->jbid);
1613 if (pvt->bridgetrans)
1614 ast_translator_free_path(pvt->bridgetrans);
1615 pvt->bridgetrans = NULL;
1618 ast_set_flag(pvt, IAX_ALREADYGONE);
1621 /* If there's an owner, prod it to give up */
1622 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1623 ast_queue_hangup(owner);
1626 for (cur = iaxq.head; cur ; cur = cur->next) {
1627 /* Cancel any pending transmissions */
1628 if (cur->callno == pvt->callno)
1632 pvt->reg->callno = 0;
1636 ast_variables_destroy(pvt->vars);
1642 while(jb_getall(pvt->jb,&frame) == JB_OK)
1643 iax2_frame_free(frame.data);
1644 jb_destroy(pvt->jb);
1651 ast_mutex_unlock(&owner->lock);
1653 ast_mutex_unlock(&iaxsl[callno]);
1654 if (callno & 0x4000)
1657 static void iax2_destroy_nolock(int callno)
1659 /* Actually it's easier to unlock, kill it, and relock */
1660 ast_mutex_unlock(&iaxsl[callno]);
1661 iax2_destroy(callno);
1662 ast_mutex_lock(&iaxsl[callno]);
1665 static int update_packet(struct iax_frame *f)
1667 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1668 struct ast_iax2_full_hdr *fh = f->data;
1669 /* Mark this as a retransmission */
1670 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1672 f->iseqno = iaxs[f->callno]->iseqno;
1673 fh->iseqno = f->iseqno;
1677 static int attempt_transmit(void *data)
1679 /* Attempt to transmit the frame to the remote peer...
1680 Called without iaxsl held. */
1681 struct iax_frame *f = data;
1683 int callno = f->callno;
1684 char iabuf[INET_ADDRSTRLEN];
1685 /* Make sure this call is still active */
1687 ast_mutex_lock(&iaxsl[callno]);
1688 if ((f->callno) && iaxs[f->callno]) {
1689 if ((f->retries < 0) /* Already ACK'd */ ||
1690 (f->retries >= max_retries) /* Too many attempts */) {
1691 /* Record an error if we've transmitted too many times */
1692 if (f->retries >= max_retries) {
1694 /* Transfer timeout */
1695 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1696 } else if (f->final) {
1698 iax2_destroy_nolock(f->callno);
1700 if (iaxs[f->callno]->owner)
1701 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);
1702 iaxs[f->callno]->error = ETIMEDOUT;
1703 if (iaxs[f->callno]->owner) {
1704 struct ast_frame fr = { 0, };
1706 fr.frametype = AST_FRAME_CONTROL;
1707 fr.subclass = AST_CONTROL_HANGUP;
1708 iax2_queue_frame(f->callno, &fr);
1709 /* Remember, owner could disappear */
1710 if (iaxs[f->callno]->owner)
1711 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1713 if (iaxs[f->callno]->reg) {
1714 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1715 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1716 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1718 iax2_destroy_nolock(f->callno);
1725 /* Update it if it needs it */
1727 /* Attempt transmission */
1730 /* Try again later after 10 times as long */
1732 if (f->retrytime > MAX_RETRY_TIME)
1733 f->retrytime = MAX_RETRY_TIME;
1734 /* Transfer messages max out at one second */
1735 if (f->transfer && (f->retrytime > 1000))
1736 f->retrytime = 1000;
1737 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1740 /* Make sure it gets freed */
1745 ast_mutex_unlock(&iaxsl[callno]);
1746 /* Do not try again */
1748 /* Don't attempt delivery, just remove it from the queue */
1749 ast_mutex_lock(&iaxq.lock);
1751 f->prev->next = f->next;
1753 iaxq.head = f->next;
1755 f->next->prev = f->prev;
1757 iaxq.tail = f->prev;
1759 ast_mutex_unlock(&iaxq.lock);
1761 /* Free the IAX frame */
1767 static int iax2_set_jitter(int fd, int argc, char *argv[])
1770 ast_cli(fd, "sorry, this command is deprecated\n");
1771 return RESULT_SUCCESS;
1773 if ((argc != 4) && (argc != 5))
1774 return RESULT_SHOWUSAGE;
1776 max_jitter_buffer = atoi(argv[3]);
1777 if (max_jitter_buffer < 0)
1778 max_jitter_buffer = 0;
1781 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1782 if (iaxs[atoi(argv[3])]) {
1783 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1784 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1785 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1787 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1789 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1792 return RESULT_SUCCESS;
1796 static char jitter_usage[] =
1797 "Usage: iax set jitter [callid] <value>\n"
1798 " If used with a callid, it sets the jitter buffer to the given static\n"
1799 "value (until its next calculation). If used without a callid, the value is used\n"
1800 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1801 "buffer size is reduced.";
1803 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1805 struct iax2_peer *peer;
1808 return RESULT_SHOWUSAGE;
1809 if (!strcmp(argv[3],"all")) {
1811 ast_cli(fd, "OK cache is flushed.\n");
1812 } else if ((peer = find_peer(argv[3], 0))) {
1813 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1814 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1815 expire_registry(peer);
1816 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1818 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1821 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1824 return RESULT_SUCCESS;
1827 static int iax2_test_losspct(int fd, int argc, char *argv[])
1830 return RESULT_SHOWUSAGE;
1832 test_losspct = atoi(argv[3]);
1834 return RESULT_SUCCESS;
1838 static int iax2_test_late(int fd, int argc, char *argv[])
1841 return RESULT_SHOWUSAGE;
1843 test_late = atoi(argv[3]);
1845 return RESULT_SUCCESS;
1848 static int iax2_test_resync(int fd, int argc, char *argv[])
1851 return RESULT_SHOWUSAGE;
1853 test_resync = atoi(argv[3]);
1855 return RESULT_SUCCESS;
1858 static int iax2_test_jitter(int fd, int argc, char *argv[])
1860 if (argc < 4 || argc > 5)
1861 return RESULT_SHOWUSAGE;
1863 test_jit = atoi(argv[3]);
1865 test_jitpct = atoi(argv[4]);
1867 return RESULT_SUCCESS;
1869 #endif /* IAXTESTS */
1871 /*--- iax2_show_peer: Show one peer in detail ---*/
1872 static int iax2_show_peer(int fd, int argc, char *argv[])
1876 char iabuf[INET_ADDRSTRLEN];
1877 struct iax2_peer *peer;
1878 char codec_buf[512];
1879 int x = 0, codec = 0, load_realtime = 0;
1882 return RESULT_SHOWUSAGE;
1884 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1886 peer = find_peer(argv[3], load_realtime);
1889 ast_cli(fd, " * Name : %s\n", peer->name);
1890 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1891 ast_cli(fd, " Context : %s\n", peer->context);
1892 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1893 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1894 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1895 ast_cli(fd, " Expire : %d\n", peer->expire);
1896 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1897 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));
1898 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1899 ast_cli(fd, " Username : %s\n", peer->username);
1900 ast_cli(fd, " Codecs : ");
1901 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1902 ast_cli(fd, "%s\n", codec_buf);
1904 ast_cli(fd, " Codec Order : (");
1905 for(x = 0; x < 32 ; x++) {
1906 codec = ast_codec_pref_index(&peer->prefs,x);
1909 ast_cli(fd, "%s", ast_getformatname(codec));
1910 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1915 ast_cli(fd, "none");
1918 ast_cli(fd, " Status : ");
1919 if (peer->lastms < 0)
1920 ast_copy_string(status, "UNREACHABLE", sizeof(status));
1921 else if (peer->historicms > peer->maxms)
1922 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->historicms);
1923 else if (peer->historicms)
1924 snprintf(status, sizeof(status), "OK (%d ms)", peer->historicms);
1926 ast_copy_string(status, "UNKNOWN", sizeof(status));
1927 ast_cli(fd, " Qualify : every %d when OK, every %d when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, (peer->smoothing == 1) ? "On" : "Off");
1928 ast_cli(fd, "%s\n",status);
1930 if (ast_test_flag(peer, IAX_TEMPONLY))
1933 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1937 return RESULT_SUCCESS;
1940 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1943 struct iax2_peer *p;
1945 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1947 ast_mutex_lock(&peerl.lock);
1948 for(p = peerl.peers ; p ; p = p->next) {
1949 if(!strncasecmp(p->name, word, strlen(word))) {
1950 if(++which > state) {
1951 return strdup(p->name);
1955 ast_mutex_unlock(&peerl.lock);
1961 static int iax2_show_stats(int fd, int argc, char *argv[])
1963 struct iax_frame *cur;
1964 int cnt = 0, dead=0, final=0;
1966 return RESULT_SHOWUSAGE;
1967 for (cur = iaxq.head; cur ; cur = cur->next) {
1968 if (cur->retries < 0)
1974 ast_cli(fd, " IAX Statistics\n");
1975 ast_cli(fd, "---------------------\n");
1976 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1977 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1978 return RESULT_SUCCESS;
1981 static int iax2_show_cache(int fd, int argc, char *argv[])
1983 struct iax2_dpcache *dp;
1984 char tmp[1024], *pc;
1988 gettimeofday(&tv, NULL);
1989 ast_mutex_lock(&dpcache_lock);
1991 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1993 s = dp->expiry.tv_sec - tv.tv_sec;
1995 if (dp->flags & CACHE_FLAG_EXISTS)
1996 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1997 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1998 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1999 if (dp->flags & CACHE_FLAG_CANEXIST)
2000 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2001 if (dp->flags & CACHE_FLAG_PENDING)
2002 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2003 if (dp->flags & CACHE_FLAG_TIMEOUT)
2004 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2005 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2006 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2007 if (dp->flags & CACHE_FLAG_MATCHMORE)
2008 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2009 if (dp->flags & CACHE_FLAG_UNKNOWN)
2010 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2011 /* Trim trailing pipe */
2012 if (!ast_strlen_zero(tmp))
2013 tmp[strlen(tmp) - 1] = '\0';
2015 ast_copy_string(tmp, "(none)", sizeof(tmp));
2017 pc = strchr(dp->peercontext, '@');
2019 pc = dp->peercontext;
2022 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2023 if (dp->waiters[x] > -1)
2026 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2028 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2031 ast_mutex_unlock(&dpcache_lock);
2032 return RESULT_SUCCESS;
2035 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2037 #ifdef BRIDGE_OPTIMIZATION
2038 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2040 static int forward_delivery(struct iax_frame *fr)
2042 struct chan_iax2_pvt *p1, *p2;
2043 char iabuf[INET_ADDRSTRLEN];
2046 p1 = iaxs[fr->callno];
2047 p2 = iaxs[p1->bridgecallno];
2054 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2056 p1->callno, p1->peercallno,
2057 p2->callno, p2->peercallno,
2058 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2059 ntohs(p2->addr.sin_port));
2061 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2062 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2063 send full frame on timestamp wrap when doing optimized bridging
2064 (actually current code STILL doesn't)
2066 if (fr->ts + 50000 <= p1->last) {
2067 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2069 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2072 /* Send with timestamp adjusted to the origin of the outbound leg */
2073 /* But don't destroy inbound timestamp still needed later to set "last" */
2075 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2076 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2082 static void unwrap_timestamp(struct iax_frame *fr)
2086 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2087 x = fr->ts - iaxs[fr->callno]->last;
2089 /* Sudden big jump backwards in timestamp:
2090 What likely happened here is that miniframe timestamp has circled but we haven't
2091 gotten the update from the main packet. We'll just pretend that we did, and
2092 update the timestamp appropriately. */
2093 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2094 if (option_debug && iaxdebug)
2095 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2098 /* Sudden apparent big jump forwards in timestamp:
2099 What's likely happened is this is an old miniframe belonging to the previous
2100 top-16-bit timestamp that has turned up out of order.
2101 Adjust the timestamp appropriately. */
2102 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2103 if (option_debug && iaxdebug)
2104 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2110 static int get_from_jb(void *p);
2112 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2115 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2117 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2119 when = jb_next(pvt->jb) - when;
2120 /* fprintf(stderr, "when = %d\n", when); */
2122 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2125 /* XXX should really just empty until when > 0.. */
2129 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2132 static int get_from_jb(void *p) {
2133 /* make sure pvt is valid! */
2134 struct chan_iax2_pvt *pvt = p;
2135 struct iax_frame *fr;
2142 ast_mutex_lock(&iaxsl[pvt->callno]);
2143 /* fprintf(stderr, "get_from_jb called\n"); */
2146 gettimeofday(&tv,NULL);
2147 /* round up a millisecond since ast_sched_runq does; */
2148 /* prevents us from spinning while waiting for our now */
2149 /* to catch up with runq's now */
2152 now = ast_tvdiff_ms(tv, pvt->rxcore);
2154 if(now >= (next = jb_next(pvt->jb))) {
2155 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
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 = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2178 af.offset=AST_FRIENDLY_OFFSET;
2180 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2181 * which we'd need to malloc, and then it would free it. That seems like a drag */
2182 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2183 iax2_queue_frame(pvt->callno, &af);
2187 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2188 iax2_frame_free(frame.data);
2195 /* shouldn't happen */
2199 update_jbsched(pvt);
2200 ast_mutex_unlock(&iaxsl[pvt->callno]);
2205 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2206 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2207 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk)
2216 unsigned int orig_ts;
2217 int drops[MEMORY_SIZE];
2218 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2220 /* Remember current jitterbuffer so we can log any change */
2221 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2222 /* Similarly for the frame timestamp */
2227 if (option_debug && iaxdebug)
2228 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2229 fr->ts, iaxs[fr->callno]->last, updatehistory);
2232 /* Attempt to recover wrapped timestamps */
2233 unwrap_timestamp(fr);
2235 if (updatehistory) {
2238 /* Attempt to spot a change of timebase on timestamps coming from the other side
2239 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2240 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2241 for a while - in this case this code might also resync us. But that's not a bad thing.
2242 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2243 [that's why we only do this when updatehistory is true]
2245 x = fr->ts - iaxs[fr->callno]->last;
2246 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2247 if (option_debug && iaxdebug)
2248 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2249 fr->callno, fr->ts, iaxs[fr->callno]->last);
2250 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2251 iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2252 /* wipe "last" if stamps have jumped backwards */
2254 iaxs[fr->callno]->last = 0;
2255 /* should we also empty history? */
2257 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2258 frame we received. (initially the very first, but also see code just above here).
2259 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2260 Called by IAX thread, with iaxsl lock held. */
2261 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2263 /* Rotate our history queue of "lateness". Don't worry about those initial
2264 zeros because the first entry will always be zero */
2265 for (x=0;x<MEMORY_SIZE - 1;x++)
2266 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2267 /* Add a history entry for this one */
2268 iaxs[fr->callno]->history[x] = ms;
2277 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2278 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2279 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2282 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2284 fr->af.delivery = ast_tv(0,0);
2288 /* Initialize the minimum to reasonable values. It's too much
2289 work to do the same for the maximum, repeatedly */
2290 min=iaxs[fr->callno]->history[0];
2291 for (z=0;z < iax2_dropcount + 1;z++) {
2292 /* Start very optimistic ;-) */
2294 for (x=0;x<MEMORY_SIZE;x++) {
2295 if (max < iaxs[fr->callno]->history[x]) {
2296 /* We have a candidate new maximum value. Make
2297 sure it's not in our drop list */
2299 for (y=0;!match && (y<z);y++)
2300 match |= (drops[y] == x);
2302 /* It's not in our list, use it as the new maximum */
2303 max = iaxs[fr->callno]->history[x];
2309 /* On our first pass, find the minimum too */
2310 if (min > iaxs[fr->callno]->history[x])
2311 min = iaxs[fr->callno]->history[x];
2321 type = JB_TYPE_CONTROL;
2324 if(fr->af.frametype == AST_FRAME_VOICE) {
2325 type = JB_TYPE_VOICE;
2326 len = ast_codec_get_samples(&fr->af) / 8;
2327 } else if(fr->af.frametype == AST_FRAME_CNG) {
2328 type = JB_TYPE_SILENCE;
2331 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2336 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2337 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2338 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2339 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2340 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2343 /* deliver any frames in the jb */
2344 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2345 __do_deliver(frame.data);
2347 jb_reset(iaxs[fr->callno]->jb);
2349 if (iaxs[fr->callno]->jbid > -1)
2350 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2352 iaxs[fr->callno]->jbid = -1;
2354 /* deliver this frame now */
2361 /* insert into jitterbuffer */
2362 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2363 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2364 calc_rxstamp(iaxs[fr->callno],fr->ts));
2365 if (ret == JB_DROP) {
2366 iax2_frame_free(fr);
2367 } else if (ret == JB_SCHED) {
2368 update_jbsched(iaxs[fr->callno]);
2371 /* Just for reference, keep the "jitter" value, the difference between the
2372 earliest and the latest. */
2374 iaxs[fr->callno]->jitter = max - min;
2376 /* IIR filter for keeping track of historic jitter, but always increase
2377 historic jitter immediately for increase */
2379 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2380 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2382 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2383 iaxs[fr->callno]->historicjitter;
2385 /* If our jitter buffer is too big (by a significant margin), then we slowly
2386 shrink it to avoid letting the change be perceived */
2387 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2388 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2390 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2391 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2392 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2393 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2394 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2395 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2397 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2398 buffer immediately to accomodate it (and a little more). */
2399 if (max > iaxs[fr->callno]->jitterbuffer)
2400 iaxs[fr->callno]->jitterbuffer = max
2401 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2403 /* update "min", just for RRs and stats */
2404 iaxs[fr->callno]->min = min;
2406 /* Subtract the lateness from our jitter buffer to know how long to wait
2407 before sending our packet. */
2408 delay = iaxs[fr->callno]->jitterbuffer - ms;
2410 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2411 if (delay > maxjitterbuffer)
2412 delay = maxjitterbuffer;
2414 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2415 /* If frame came from trunk, also don't do any delay */
2416 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2419 if (option_debug && iaxdebug) {
2420 /* Log jitter stats for possible offline analysis */
2421 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",
2422 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2423 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2424 min, max, iaxs[fr->callno]->jitterbuffer,
2425 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2427 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2431 /* Don't deliver it more than 4 ms late */
2432 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2433 if (option_debug && iaxdebug)
2434 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2437 if (option_debug && iaxdebug)
2438 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2439 iaxs[fr->callno]->frames_dropped++;
2440 /* Free our iax frame */
2441 iax2_frame_free(fr);
2444 if (option_debug && iaxdebug)
2445 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2446 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2452 static int iax2_transmit(struct iax_frame *fr)
2454 /* Lock the queue and place this packet at the end */
2457 /* By setting this to 0, the network thread will send it for us, and
2458 queue retransmission if necessary */
2460 ast_mutex_lock(&iaxq.lock);
2467 iaxq.tail->next = fr;
2468 fr->prev = iaxq.tail;
2472 ast_mutex_unlock(&iaxq.lock);
2473 /* Wake up the network thread */
2474 pthread_kill(netthreadid, SIGURG);
2480 static int iax2_digit(struct ast_channel *c, char digit)
2482 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2485 static int iax2_sendtext(struct ast_channel *c, const char *text)
2488 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2489 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2492 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2494 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2497 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2499 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2502 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2504 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2505 ast_mutex_lock(&iaxsl[callno]);
2507 iaxs[callno]->owner = newchan;
2509 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2510 ast_mutex_unlock(&iaxsl[callno]);
2514 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2515 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2517 static void destroy_user(struct iax2_user *user);
2518 static int expire_registry(void *data);
2520 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2522 struct ast_variable *var;
2523 struct ast_variable *tmp;
2524 struct iax2_peer *peer=NULL;
2525 time_t regseconds, nowtime;
2529 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2531 char iabuf[INET_ADDRSTRLEN];
2533 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2534 sprintf(porta, "%d", ntohs(sin->sin_port));
2535 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2540 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2547 /* Make sure it's not a user only... */
2548 if (!strcasecmp(tmp->name, "type")) {
2549 if (strcasecmp(tmp->value, "friend") &&
2550 strcasecmp(tmp->value, "peer")) {
2551 /* Whoops, we weren't supposed to exist! */
2556 } else if (!strcasecmp(tmp->name, "regseconds")) {
2557 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2559 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2560 inet_aton(tmp->value, &(peer->addr.sin_addr));
2561 } else if (!strcasecmp(tmp->name, "port")) {
2562 peer->addr.sin_port = htons(atoi(tmp->value));
2563 } else if (!strcasecmp(tmp->name, "host")) {
2564 if (!strcasecmp(tmp->value, "dynamic"))
2572 ast_variables_destroy(var);
2574 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2575 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2576 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2577 if (peer->expire > -1)
2578 ast_sched_del(sched, peer->expire);
2579 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2581 ast_mutex_lock(&peerl.lock);
2582 peer->next = peerl.peers;
2584 ast_mutex_unlock(&peerl.lock);
2585 if (ast_test_flag(peer, IAX_DYNAMIC))
2586 reg_source_db(peer);
2588 ast_set_flag(peer, IAX_TEMPONLY);
2591 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2593 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2594 memset(&peer->addr, 0, sizeof(peer->addr));
2596 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2603 static struct iax2_user *realtime_user(const char *username)
2605 struct ast_variable *var;
2606 struct ast_variable *tmp;
2607 struct iax2_user *user=NULL;
2609 var = ast_load_realtime("iaxusers", "name", username, NULL);
2615 /* Make sure it's not a peer only... */
2616 if (!strcasecmp(tmp->name, "type")) {
2617 if (strcasecmp(tmp->value, "friend") &&
2618 strcasecmp(tmp->value, "user")) {
2625 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2629 ast_variables_destroy(var);
2631 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2632 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2633 ast_mutex_lock(&userl.lock);
2634 user->next = userl.users;
2636 ast_mutex_unlock(&userl.lock);
2638 ast_set_flag(user, IAX_TEMPONLY);
2644 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2648 char regseconds[20];
2652 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2653 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2654 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2655 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2658 struct create_addr_info {
2670 char context[AST_MAX_CONTEXT];
2671 char peercontext[AST_MAX_CONTEXT];
2674 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2676 struct ast_hostent ahp;
2678 struct iax2_peer *peer;
2680 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2681 cai->sockfd = defaultsockfd;
2683 sin->sin_family = AF_INET;
2685 if (!(peer = find_peer(peername, 1))) {
2688 hp = ast_gethostbyname(peername, &ahp);
2690 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2691 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2692 /* use global iax prefs for unknown peer/user */
2693 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2696 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2703 /* if the peer has no address (current or default), return failure */
2704 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2705 if (ast_test_flag(peer, IAX_TEMPONLY))
2710 /* if the peer is being monitored and is currently unreachable, return failure */
2711 if (peer->maxms && (peer->lastms > peer->maxms)) {
2712 if (ast_test_flag(peer, IAX_TEMPONLY))
2717 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2718 cai->maxtime = peer->maxms;
2719 cai->capability = peer->capability;
2720 cai->encmethods = peer->encmethods;
2721 cai->sockfd = peer->sockfd;
2722 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2723 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2724 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2725 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2726 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2727 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2728 if (ast_strlen_zero(peer->dbsecret)) {
2729 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2734 family = ast_strdupa(peer->dbsecret);
2736 key = strchr(family, '/');
2740 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2741 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2742 if (ast_test_flag(peer, IAX_TEMPONLY))
2748 if (peer->addr.sin_addr.s_addr) {
2749 sin->sin_addr = peer->addr.sin_addr;
2750 sin->sin_port = peer->addr.sin_port;
2752 sin->sin_addr = peer->defaddr.sin_addr;
2753 sin->sin_port = peer->defaddr.sin_port;
2756 if (ast_test_flag(peer, IAX_TEMPONLY))
2762 static int auto_congest(void *nothing)
2764 int callno = PTR_TO_CALLNO(nothing);
2765 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2766 ast_mutex_lock(&iaxsl[callno]);
2768 iaxs[callno]->initid = -1;
2769 iax2_queue_frame(callno, &f);
2770 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2772 ast_mutex_unlock(&iaxsl[callno]);
2776 static unsigned int iax2_datetime(char *tz)
2782 localtime_r(&t, &tm);
2783 if (!ast_strlen_zero(tz))
2784 ast_localtime(&t, &tm, tz);
2785 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2786 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2787 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2788 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2789 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2790 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2794 struct parsed_dial_string {
2806 * \brief Parses an IAX dial string into its component parts.
2807 * \param data the string to be parsed
2808 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2811 * This function parses the string and fills the structure
2812 * with pointers to its component parts. The input string
2815 * \note This function supports both plaintext passwords and RSA
2816 * key names; if the password string is formatted as '[keyname]',
2817 * then the keyname will be placed into the key field, and the
2818 * password field will be set to NULL.
2820 * \note The dial string format is:
2821 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2823 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2825 if (!data || ast_strlen_zero(data))
2828 pds->peer = strsep(&data, "/");
2829 pds->exten = strsep(&data, "/");
2830 pds->options = data;
2834 pds->exten = strsep(&data, "@");
2835 pds->context = data;
2838 if (strchr(pds->peer, '@')) {
2840 pds->username = strsep(&data, "@");
2844 if (pds->username) {
2845 data = pds->username;
2846 pds->username = strsep(&data, ":");
2847 pds->password = data;
2851 pds->peer = strsep(&data, ":");
2854 /* check for a key name wrapped in [] in the secret position, if found,
2855 move it to the key field instead
2857 if (pds->password && (pds->password[0] == '[')) {
2858 pds->key = ast_strip_quoted(pds->password, "[", "]");
2859 pds->password = NULL;
2863 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2865 struct sockaddr_in sin;
2866 char *l=NULL, *n=NULL, *tmpstr;
2867 struct iax_ie_data ied;
2868 char *defaultrdest = "s";
2869 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2870 struct parsed_dial_string pds;
2871 struct create_addr_info cai;
2873 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2874 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2878 memset(&cai, 0, sizeof(cai));
2879 cai.encmethods = iax2_encryption;
2881 memset(&pds, 0, sizeof(pds));
2882 tmpstr = ast_strdupa(dest);
2883 parse_dial_string(tmpstr, &pds);
2886 pds.exten = defaultrdest;
2888 if (create_addr(pds.peer, &sin, &cai)) {
2889 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2893 if (!pds.username && !ast_strlen_zero(cai.username))
2894 pds.username = cai.username;
2895 if (!pds.password && !ast_strlen_zero(cai.secret))
2896 pds.password = cai.secret;
2897 if (!pds.key && !ast_strlen_zero(cai.outkey))
2898 pds.key = cai.outkey;
2899 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2900 pds.context = cai.peercontext;
2902 /* Keep track of the context for outgoing calls too */
2903 ast_copy_string(c->context, cai.context, sizeof(c->context));
2906 sin.sin_port = htons(atoi(pds.port));
2909 n = c->cid.cid_name;
2911 /* Now build request */
2912 memset(&ied, 0, sizeof(ied));
2914 /* On new call, first IE MUST be IAX version of caller */
2915 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2916 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2917 if (pds.options && strchr(pds.options, 'a')) {
2918 /* Request auto answer */
2919 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2922 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2925 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2926 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2929 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2931 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2934 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2935 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2938 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2939 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2940 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2942 if (c->language && !ast_strlen_zero(c->language))
2943 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2944 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2945 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2948 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2951 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2954 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2956 ast_mutex_lock(&iaxsl[callno]);
2958 if (!ast_strlen_zero(c->context))
2959 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2962 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2964 iaxs[callno]->encmethods = cai.encmethods;
2967 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2969 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2971 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2972 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2973 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2974 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2976 if (iaxs[callno]->maxtime) {
2977 /* Initialize pingtime and auto-congest time */
2978 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2979 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2980 } else if (autokill) {
2981 iaxs[callno]->pingtime = autokill / 2;
2982 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2985 /* Transmit the string in a "NEW" request */
2986 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2988 ast_mutex_unlock(&iaxsl[callno]);
2989 ast_setstate(c, AST_STATE_RINGING);
2994 static int iax2_hangup(struct ast_channel *c)
2996 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2998 struct iax_ie_data ied;
2999 memset(&ied, 0, sizeof(ied));
3000 ast_mutex_lock(&iaxsl[callno]);
3001 if (callno && iaxs[callno]) {
3002 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3003 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3004 /* Send the hangup unless we have had a transmission error or are already gone */
3005 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3006 if (!iaxs[callno]->error && !alreadygone)
3007 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3008 /* Explicitly predestroy it */
3009 iax2_predestroy_nolock(callno);
3010 /* If we were already gone to begin with, destroy us now */
3012 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3013 iax2_destroy_nolock(callno);
3016 ast_mutex_unlock(&iaxsl[callno]);
3017 if (option_verbose > 2)
3018 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3022 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3024 struct ast_option_header *h;
3028 case AST_OPTION_TXGAIN:
3029 case AST_OPTION_RXGAIN:
3030 /* these two cannot be sent, because they require a result */
3034 h = malloc(datalen + sizeof(*h));
3036 h->flag = AST_OPTION_FLAG_REQUEST;
3037 h->option = htons(option);
3038 memcpy(h->data, data, datalen);
3039 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3040 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3041 datalen + sizeof(*h), -1);
3045 ast_log(LOG_WARNING, "Out of memory\n");
3051 static struct ast_frame *iax2_read(struct ast_channel *c)
3053 static struct ast_frame f = { AST_FRAME_NULL, };
3054 ast_log(LOG_NOTICE, "I should never be called!\n");
3058 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3061 struct iax_ie_data ied0;
3062 struct iax_ie_data ied1;
3063 unsigned int transferid = rand();
3064 memset(&ied0, 0, sizeof(ied0));
3065 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3066 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3067 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3069 memset(&ied1, 0, sizeof(ied1));
3070 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3071 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3072 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3074 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3077 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3080 iaxs[callno0]->transferring = TRANSFER_BEGIN;
3081 iaxs[callno1]->transferring = TRANSFER_BEGIN;
3085 static void lock_both(unsigned short callno0, unsigned short callno1)
3087 ast_mutex_lock(&iaxsl[callno0]);
3088 while (ast_mutex_trylock(&iaxsl[callno1])) {
3089 ast_mutex_unlock(&iaxsl[callno0]);
3091 ast_mutex_lock(&iaxsl[callno0]);
3095 static void unlock_both(unsigned short callno0, unsigned short callno1)
3097 ast_mutex_unlock(&iaxsl[callno1]);
3098 ast_mutex_unlock(&iaxsl[callno0]);
3101 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3103 struct ast_channel *cs[3];
3104 struct ast_channel *who;
3107 int transferstarted=0;
3108 struct ast_frame *f;
3109 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3110 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3111 struct timeval waittimer = {0, 0}, tv;
3113 lock_both(callno0, callno1);
3114 /* Put them in native bridge mode */
3115 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3116 iaxs[callno0]->bridgecallno = callno1;
3117 iaxs[callno1]->bridgecallno = callno0;
3119 unlock_both(callno0, callno1);
3121 /* If not, try to bridge until we can execute a transfer, if we can */
3124 for (/* ever */;;) {
3125 /* Check in case we got masqueraded into */
3126 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3127 if (option_verbose > 2)
3128 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3129 /* Remove from native mode */
3130 if (c0->type == channeltype) {
3131 ast_mutex_lock(&iaxsl[callno0]);
3132 iaxs[callno0]->bridgecallno = 0;
3133 ast_mutex_unlock(&iaxsl[callno0]);
3135 if (c1->type == channeltype) {
3136 ast_mutex_lock(&iaxsl[callno1]);
3137 iaxs[callno1]->bridgecallno = 0;
3138 ast_mutex_unlock(&iaxsl[callno1]);
3140 return AST_BRIDGE_FAILED_NOWARN;
3142 if (c0->nativeformats != c1->nativeformats) {