2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, 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 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
30 * \todo Implement musicclass settings for IAX2 devices
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
90 #include "asterisk/timing.h"
93 #include "iax2-parser.h"
94 #include "iax2-provision.h"
95 #include "jitterbuf.h"
98 <application name="IAX2Provision" language="en_US">
100 Provision a calling IAXy with a given template.
103 <parameter name="template">
104 <para>If not specified, defaults to <literal>default</literal>.</para>
108 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
109 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
110 or <literal>0</literal> on success.</para>
113 <function name="IAXPEER" language="en_US">
115 Gets IAX peer information.
118 <parameter name="peername" required="true">
120 <enum name="CURRENTCHANNEL">
121 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
122 endpoint of the current channel</para>
126 <parameter name="item">
127 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
130 <para>(default) The IP address.</para>
133 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
135 <enum name="mailbox">
136 <para>The configured mailbox.</para>
138 <enum name="context">
139 <para>The configured context.</para>
142 <para>The epoch time of the next expire.</para>
144 <enum name="dynamic">
145 <para>Is it dynamic? (yes/no).</para>
147 <enum name="callerid_name">
148 <para>The configured Caller ID name.</para>
150 <enum name="callerid_num">
151 <para>The configured Caller ID number.</para>
154 <para>The configured codecs.</para>
156 <enum name="codec[x]">
157 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
158 with <literal>0</literal>)</para>
165 <ref type="function">SIPPEER</ref>
168 <function name="IAXVAR" language="en_US">
170 Sets or retrieves a remote variable.
173 <parameter name="varname" required="true" />
179 /* Define SCHED_MULTITHREADED to run the scheduler in a special
180 multithreaded mode. */
181 #define SCHED_MULTITHREADED
183 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
184 thread is actually doing. */
185 #define DEBUG_SCHED_MULTITHREAD
189 static int nochecksums = 0;
192 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
193 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
195 #define DEFAULT_THREAD_COUNT 10
196 #define DEFAULT_MAX_THREAD_COUNT 100
197 #define DEFAULT_RETRY_TIME 1000
198 #define MEMORY_SIZE 100
199 #define DEFAULT_DROP 3
201 #define DEBUG_SUPPORT
203 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
205 /* Sample over last 100 units to determine historic jitter */
208 static struct ast_codec_pref prefs;
210 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
213 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
214 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
215 #define MAX_TRUNK_MTU 1240
217 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
218 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
220 #define DEFAULT_CONTEXT "default"
222 static char default_parkinglot[AST_MAX_CONTEXT];
224 static char language[MAX_LANGUAGE] = "";
225 static char regcontext[AST_MAX_CONTEXT] = "";
227 static int maxauthreq = 3;
228 static int max_retries = 4;
229 static int ping_time = 21;
230 static int lagrq_time = 10;
231 static int maxjitterbuffer=1000;
232 static int resyncthreshold=1000;
233 static int maxjitterinterps=10;
234 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
236 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
238 static int trunkfreq = 20;
239 static int trunkmaxsize = MAX_TRUNKDATA;
241 static int authdebug = 1;
242 static int autokill = 0;
243 static int iaxcompat = 0;
244 static int last_authmethod = 0;
246 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
248 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
255 static int min_reg_expire;
256 static int max_reg_expire;
258 static int srvlookup = 0;
260 static int timingfd = -1; /* Timing file descriptor */
262 static struct ast_netsock_list *netsock;
263 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
264 static int defaultsockfd = -1;
266 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
269 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
271 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
272 ~AST_FORMAT_SLINEAR & \
277 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
279 ~AST_FORMAT_G726_AAL2 & \
282 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
286 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
287 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
288 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
290 /* if a pvt has encryption setup done and is running on the call */
291 #define IAX_CALLENCRYPTED(pvt) \
292 (ast_test_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(pvt, IAX_KEYPOPULATED))
294 #define IAX_DEBUGDIGEST(msg, key) do { \
296 char digest[33] = ""; \
301 for (idx = 0; idx < 16; idx++) \
302 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
304 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
307 static struct io_context *io;
308 static struct ast_sched_thread *sched;
310 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
312 static int iaxdebug = 0;
314 static int iaxtrunkdebug = 0;
316 static int test_losspct = 0;
318 static int test_late = 0;
319 static int test_resync = 0;
320 static int test_jit = 0;
321 static int test_jitpct = 0;
322 #endif /* IAXTESTS */
324 static char accountcode[AST_MAX_ACCOUNT_CODE];
325 static char mohinterpret[MAX_MUSICCLASS];
326 static char mohsuggest[MAX_MUSICCLASS];
327 static int amaflags = 0;
329 static int delayreject = 0;
330 static int iax2_encryption = 0;
332 static struct ast_flags globalflags = { 0 };
334 static pthread_t netthreadid = AST_PTHREADT_NULL;
337 IAX_STATE_STARTED = (1 << 0),
338 IAX_STATE_AUTHENTICATED = (1 << 1),
339 IAX_STATE_TBD = (1 << 2),
340 IAX_STATE_UNCHANGED = (1 << 3),
343 struct iax2_context {
344 char context[AST_MAX_CONTEXT];
345 struct iax2_context *next;
349 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
350 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
351 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
352 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
353 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
354 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
355 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
356 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
357 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
358 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
359 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
360 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
361 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
362 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
363 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
364 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
365 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
366 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
367 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
368 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
369 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
370 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
371 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
372 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
373 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
374 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
375 response, so that we've achieved a three-way handshake with
376 them before sending voice or anything else*/
377 IAX_ALLOWFWDOWNLOAD = (1 << 26), /*!< Allow the FWDOWNL command? */
378 IAX_IMMEDIATE = (1 << 27), /*!< Allow immediate off-hook to extension s */
379 IAX_FORCE_ENCRYPT = (1 << 28), /*!< Forces call encryption, if encryption not possible hangup */
382 static int global_rtautoclear = 120;
384 static int reload_config(void);
387 AST_DECLARE_STRING_FIELDS(
388 AST_STRING_FIELD(name);
389 AST_STRING_FIELD(secret);
390 AST_STRING_FIELD(dbsecret);
391 AST_STRING_FIELD(accountcode);
392 AST_STRING_FIELD(mohinterpret);
393 AST_STRING_FIELD(mohsuggest);
394 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
395 AST_STRING_FIELD(language);
396 AST_STRING_FIELD(cid_num);
397 AST_STRING_FIELD(cid_name);
398 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
407 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
408 int curauthreq; /*!< Current number of outstanding AUTHREQs */
409 struct ast_codec_pref prefs;
411 struct iax2_context *contexts;
412 struct ast_variable *vars;
416 AST_DECLARE_STRING_FIELDS(
417 AST_STRING_FIELD(name);
418 AST_STRING_FIELD(username);
419 AST_STRING_FIELD(secret);
420 AST_STRING_FIELD(dbsecret);
421 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
423 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
424 AST_STRING_FIELD(context); /*!< For transfers only */
425 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
426 AST_STRING_FIELD(mailbox); /*!< Mailbox */
427 AST_STRING_FIELD(mohinterpret);
428 AST_STRING_FIELD(mohsuggest);
429 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
430 /* Suggested caller id if registering */
431 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
432 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
433 AST_STRING_FIELD(zonetag); /*!< Time Zone */
434 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
436 struct ast_codec_pref prefs;
437 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
438 struct sockaddr_in addr;
440 int sockfd; /*!< Socket to use for transmission */
445 /* Dynamic Registration fields */
446 struct sockaddr_in defaddr; /*!< Default address if there is one */
447 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
448 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
450 int expire; /*!< Schedule entry for expiry */
451 int expiry; /*!< How soon to expire */
452 int capability; /*!< Capability */
455 int callno; /*!< Call number of POKE request */
456 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
457 int lastms; /*!< How long last response took (in ms), or -1 for no response */
458 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
460 int pokefreqok; /*!< How often to check if the host is up */
461 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
462 int historicms; /*!< How long recent average responses took */
463 int smoothing; /*!< Sample over how many units to determine historic ms */
465 struct ast_event_sub *mwi_event_sub;
470 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
472 struct iax2_trunk_peer {
475 struct sockaddr_in addr;
476 struct timeval txtrunktime; /*!< Transmit trunktime */
477 struct timeval rxtrunktime; /*!< Receive trunktime */
478 struct timeval lasttxtime; /*!< Last transmitted trunktime */
479 struct timeval trunkact; /*!< Last trunk activity */
480 unsigned int lastsent; /*!< Last sent time */
481 /* Trunk data and length */
482 unsigned char *trunkdata;
483 unsigned int trunkdatalen;
484 unsigned int trunkdataalloc;
488 AST_LIST_ENTRY(iax2_trunk_peer) list;
491 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
493 struct iax_firmware {
494 AST_LIST_ENTRY(iax_firmware) list;
498 struct ast_iax2_firmware_header *fwh;
503 REG_STATE_UNREGISTERED = 0,
506 REG_STATE_REGISTERED,
512 enum iax_transfer_state {
517 TRANSFER_PASSTHROUGH,
521 TRANSFER_MPASSTHROUGH,
526 struct iax2_registry {
527 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
529 char secret[80]; /*!< Password or key name in []'s */
530 int expire; /*!< Sched ID of expiration */
531 int refresh; /*!< How often to refresh */
532 enum iax_reg_state regstate;
533 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
534 int callno; /*!< Associated call number if applicable */
535 struct sockaddr_in us; /*!< Who the server thinks we are */
536 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
537 AST_LIST_ENTRY(iax2_registry) entry;
540 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
542 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
543 #define MIN_RETRY_TIME 100
544 #define MAX_RETRY_TIME 10000
546 #define MAX_JITTER_BUFFER 50
547 #define MIN_JITTER_BUFFER 10
549 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
551 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
553 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
554 #define TS_GAP_FOR_JB_RESYNC 5000
556 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
557 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
558 static int iaxdynamicthreadcount = 0;
559 static int iaxdynamicthreadnum = 0;
560 static int iaxactivethreadcount = 0;
574 struct chan_iax2_pvt {
575 /*! Socket to send/receive on for this call */
577 /*! Last received voice format */
579 /*! Last received video format */
581 /*! Last sent voice format */
583 /*! Last sent video format */
585 /*! What we are capable of sending */
587 /*! Last received timestamp */
589 /*! Last sent timestamp - never send the same timestamp twice in a single call */
590 unsigned int lastsent;
591 /*! Timestamp of the last video frame sent */
592 unsigned int lastvsent;
593 /*! Next outgoing timestamp if everything is good */
594 unsigned int nextpred;
595 /*! True if the last voice we transmitted was not silence/CNG */
596 unsigned int notsilenttx:1;
598 unsigned int pingtime;
599 /*! Max time for initial response */
602 struct sockaddr_in addr;
603 /*! Actual used codec preferences */
604 struct ast_codec_pref prefs;
605 /*! Requested codec preferences */
606 struct ast_codec_pref rprefs;
607 /*! Our call number */
608 unsigned short callno;
610 unsigned short peercallno;
611 /*! Negotiated format, this is only used to remember what format was
612 chosen for an unauthenticated call so that the channel can get
613 created later using the right format */
615 /*! Peer selected format */
617 /*! Peer capability */
619 /*! timeval that we base our transmission on */
620 struct timeval offset;
621 /*! timeval that we base our delivery on */
622 struct timeval rxcore;
623 /*! The jitterbuffer */
625 /*! active jb read scheduler id */
629 /*! Error, as discovered by the manager */
631 /*! Owner if we have one */
632 struct ast_channel *owner;
633 /*! What's our state? */
634 struct ast_flags state;
635 /*! Expiry (optional) */
637 /*! Next outgoing sequence number */
638 unsigned char oseqno;
639 /*! Next sequence number they have not yet acknowledged */
640 unsigned char rseqno;
641 /*! Next incoming sequence number */
642 unsigned char iseqno;
643 /*! Last incoming sequence number we have acknowledged */
644 unsigned char aseqno;
646 AST_DECLARE_STRING_FIELDS(
648 AST_STRING_FIELD(peer);
649 /*! Default Context */
650 AST_STRING_FIELD(context);
651 /*! Caller ID if available */
652 AST_STRING_FIELD(cid_num);
653 AST_STRING_FIELD(cid_name);
654 /*! Hidden Caller ID (i.e. ANI) if appropriate */
655 AST_STRING_FIELD(ani);
657 AST_STRING_FIELD(dnid);
659 AST_STRING_FIELD(rdnis);
660 /*! Requested Extension */
661 AST_STRING_FIELD(exten);
662 /*! Expected Username */
663 AST_STRING_FIELD(username);
664 /*! Expected Secret */
665 AST_STRING_FIELD(secret);
667 AST_STRING_FIELD(challenge);
668 /*! Public keys permitted keys for incoming authentication */
669 AST_STRING_FIELD(inkeys);
670 /*! Private key for outgoing authentication */
671 AST_STRING_FIELD(outkey);
672 /*! Preferred language */
673 AST_STRING_FIELD(language);
674 /*! Hostname/peername for naming purposes */
675 AST_STRING_FIELD(host);
677 AST_STRING_FIELD(dproot);
678 AST_STRING_FIELD(accountcode);
679 AST_STRING_FIELD(mohinterpret);
680 AST_STRING_FIELD(mohsuggest);
681 /*! received OSP token */
682 AST_STRING_FIELD(osptoken);
683 /*! Default parkinglot */
684 AST_STRING_FIELD(parkinglot);
687 /*! permitted authentication methods */
689 /*! permitted encryption methods */
691 /*! Encryption AES-128 Key */
692 ast_aes_encrypt_key ecx;
693 /*! Decryption AES-128 Key corresponding to ecx */
694 ast_aes_decrypt_key mydcx;
695 /*! Decryption AES-128 Key used to decrypt peer frames */
696 ast_aes_decrypt_key dcx;
697 /*! scheduler id associated with iax_key_rotate
698 * for encrypted calls*/
700 /*! 32 bytes of semi-random data */
701 unsigned char semirand[32];
702 /*! Associated registry */
703 struct iax2_registry *reg;
704 /*! Associated peer for poking */
705 struct iax2_peer *peerpoke;
710 /*! Transferring status */
711 enum iax_transfer_state transferring;
712 /*! Transfer identifier */
714 /*! Who we are IAX transferring to */
715 struct sockaddr_in transfer;
716 /*! What's the new call number for the transfer */
717 unsigned short transfercallno;
718 /*! Transfer encrypt AES-128 Key */
719 ast_aes_encrypt_key tdcx;
721 /*! Status of knowledge of peer ADSI capability */
724 /*! Who we are bridged to */
725 unsigned short bridgecallno;
727 int pingid; /*!< Transmit PING request */
728 int lagid; /*!< Retransmit lag request */
729 int autoid; /*!< Auto hangup for Dialplan requestor */
730 int authid; /*!< Authentication rejection ID */
731 int authfail; /*!< Reason to report failure */
732 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
737 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
738 /*! variables inherited from the user definition */
739 struct ast_variable *vars;
740 /*! variables transmitted in a NEW packet */
741 struct ast_variable *iaxvars;
742 /*! last received remote rr */
743 struct iax_rr remote_rr;
744 /*! Current base time: (just for stats) */
746 /*! Dropped frame count: (just for stats) */
748 /*! received frame count: (just for stats) */
753 * \brief a list of frames that may need to be retransmitted
755 * \note The contents of this list do not need to be explicitly destroyed
756 * on module unload. This is because all active calls are destroyed, and
757 * all frames in this queue will get destroyed as a part of that process.
759 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
762 * This module will get much higher performance when doing a lot of
763 * user and peer lookups if the number of buckets is increased from 1.
764 * However, to maintain old behavior for Asterisk 1.4, these are set to
765 * 1 by default. When using multiple buckets, search order through these
766 * containers is considered random, so you will not be able to depend on
767 * the order the entires are specified in iax.conf for matching order. */
769 #define MAX_PEER_BUCKETS 17
771 #define MAX_PEER_BUCKETS 563
773 static struct ao2_container *peers;
775 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
776 static struct ao2_container *users;
778 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
781 /*! Extension exists */
782 CACHE_FLAG_EXISTS = (1 << 0),
783 /*! Extension is nonexistent */
784 CACHE_FLAG_NONEXISTENT = (1 << 1),
785 /*! Extension can exist */
786 CACHE_FLAG_CANEXIST = (1 << 2),
787 /*! Waiting to hear back response */
788 CACHE_FLAG_PENDING = (1 << 3),
790 CACHE_FLAG_TIMEOUT = (1 << 4),
791 /*! Request transmitted */
792 CACHE_FLAG_TRANSMITTED = (1 << 5),
794 CACHE_FLAG_UNKNOWN = (1 << 6),
796 CACHE_FLAG_MATCHMORE = (1 << 7),
799 struct iax2_dpcache {
800 char peercontext[AST_MAX_CONTEXT];
801 char exten[AST_MAX_EXTENSION];
803 struct timeval expiry;
805 unsigned short callno;
807 AST_LIST_ENTRY(iax2_dpcache) cache_list;
808 AST_LIST_ENTRY(iax2_dpcache) peer_list;
811 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
813 static void reg_source_db(struct iax2_peer *p);
814 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
816 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
817 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags);
818 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
820 enum iax2_thread_iostate {
823 IAX_IOSTATE_PROCESSING,
824 IAX_IOSTATE_SCHEDREADY,
827 enum iax2_thread_type {
828 IAX_THREAD_TYPE_POOL,
829 IAX_THREAD_TYPE_DYNAMIC,
832 struct iax2_pkt_buf {
833 AST_LIST_ENTRY(iax2_pkt_buf) entry;
835 unsigned char buf[1];
839 AST_LIST_ENTRY(iax2_thread) list;
840 enum iax2_thread_type type;
841 enum iax2_thread_iostate iostate;
842 #ifdef SCHED_MULTITHREADED
843 void (*schedfunc)(const void *);
844 const void *scheddata;
846 #ifdef DEBUG_SCHED_MULTITHREAD
852 struct sockaddr_in iosin;
853 unsigned char readbuf[4096];
861 ast_mutex_t init_lock;
862 ast_cond_t init_cond;
863 /*! if this thread is processing a full frame,
864 some information about that frame will be stored
865 here, so we can avoid dispatching any more full
866 frames for that callno to other threads */
868 unsigned short callno;
869 struct sockaddr_in sin;
873 /*! Queued up full frames for processing. If more full frames arrive for
874 * a call which this thread is already processing a full frame for, they
875 * are queued up here. */
876 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
880 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
881 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
882 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
884 static void *iax2_process_thread(void *data);
885 static void iax2_destroy(int callno);
887 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
889 ast_mutex_lock(lock);
890 ast_cond_signal(cond);
891 ast_mutex_unlock(lock);
895 * \brief an array of iax2 pvt structures
897 * The container for active chan_iax2_pvt structures is implemented as an
898 * array for extremely quick direct access to the correct pvt structure
899 * based on the local call number. The local call number is used as the
900 * index into the array where the associated pvt structure is stored.
902 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
905 * \brief Another container of iax2_pvt structures
907 * Active IAX2 pvt structs are also stored in this container, if they are a part
908 * of an active call where we know the remote side's call number. The reason
909 * for this is that incoming media frames do not contain our call number. So,
910 * instead of having to iterate the entire iaxs array, we use this container to
911 * look up calls where the remote side is using a given call number.
913 static struct ao2_container *iax_peercallno_pvts;
916 * \brief chan_iax2_pvt structure locks
918 * These locks are used when accessing a pvt structure in the iaxs array.
919 * The index used here is the same as used in the iaxs array. It is the
920 * local call number for the associated pvt struct.
922 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
925 * \brief The last time a call number was used
927 * It is important to know the last time that a call number was used locally so
928 * that it is not used again too soon. The reason for this is the same as the
929 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
931 * For example, say that a call is up. Then, the remote side sends a HANGUP,
932 * which we respond to with an ACK. However, there is no way to know whether
933 * the ACK made it there successfully. If it were to get lost, the remote
934 * side may retransmit the HANGUP. If in the meantime, this call number has
935 * been reused locally, given the right set of circumstances, this retransmitted
936 * HANGUP could potentially improperly hang up the new session. So, to avoid
937 * this potential issue, we must wait a specified timeout period before reusing
938 * a local call number.
940 * The specified time that we must wait before reusing a local call number is
941 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
943 static struct timeval lastused[ARRAY_LEN(iaxs)];
946 * * \brief Another container of iax2_pvt structures
948 * Active IAX2 pvt stucts used during transfering a call are stored here.
950 static struct ao2_container *iax_transfercallno_pvts;
952 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
953 but keeps the division between trunked and non-trunked better. */
954 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
956 /* Debug routines... */
957 static struct sockaddr_in debugaddr;
959 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
962 (sin && debugaddr.sin_addr.s_addr &&
963 (!ntohs(debugaddr.sin_port) ||
964 debugaddr.sin_port == sin->sin_port) &&
965 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
967 iax_showframe(f, fhi, rx, sin, datalen);
970 iax_showframe(f, fhi, rx, sin, datalen);
976 static void iax_debug_output(const char *data)
979 ast_verbose("%s", data);
982 static void iax_error_output(const char *data)
984 ast_log(LOG_WARNING, "%s", data);
987 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
993 vsnprintf(buf, sizeof(buf), fmt, args);
996 ast_log(LOG_ERROR, "%s", buf);
999 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1004 va_start(args, fmt);
1005 vsnprintf(buf, sizeof(buf), fmt, args);
1008 ast_log(LOG_WARNING, "%s", buf);
1011 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1016 va_start(args, fmt);
1017 vsnprintf(buf, sizeof(buf), fmt, args);
1020 ast_verbose("%s", buf);
1023 static int maxtrunkcall = TRUNK_CALL_START;
1024 static int maxnontrunkcall = 1;
1026 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);
1027 static int expire_registry(const void *data);
1028 static int iax2_answer(struct ast_channel *c);
1029 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1030 static int iax2_devicestate(void *data);
1031 static int iax2_digit_begin(struct ast_channel *c, char digit);
1032 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1033 static int iax2_do_register(struct iax2_registry *reg);
1034 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1035 static int iax2_hangup(struct ast_channel *c);
1036 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1037 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1038 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
1039 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1040 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1041 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1042 static int iax2_sendtext(struct ast_channel *c, const char *text);
1043 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1044 static int iax2_transfer(struct ast_channel *c, const char *dest);
1045 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1046 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1047 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1048 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1049 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1050 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1051 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1052 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
1053 static struct ast_frame *iax2_read(struct ast_channel *c);
1054 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1055 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1056 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
1057 static void *iax2_dup_variable_datastore(void *);
1058 static void prune_peers(void);
1059 static void prune_users(void);
1060 static void iax2_free_variable_datastore(void *);
1062 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1063 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
1064 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1065 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1066 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1068 static const struct ast_channel_tech iax2_tech = {
1070 .description = tdesc,
1071 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1072 .properties = AST_CHAN_TP_WANTSJITTER,
1073 .requester = iax2_request,
1074 .devicestate = iax2_devicestate,
1075 .send_digit_begin = iax2_digit_begin,
1076 .send_digit_end = iax2_digit_end,
1077 .send_text = iax2_sendtext,
1078 .send_image = iax2_sendimage,
1079 .send_html = iax2_sendhtml,
1081 .hangup = iax2_hangup,
1082 .answer = iax2_answer,
1084 .write = iax2_write,
1085 .write_video = iax2_write,
1086 .indicate = iax2_indicate,
1087 .setoption = iax2_setoption,
1088 .bridge = iax2_bridge,
1089 .transfer = iax2_transfer,
1090 .fixup = iax2_fixup,
1091 .func_channel_read = acf_channel_read,
1092 .func_channel_write = acf_channel_write,
1095 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1097 /* The MWI subscriptions exist just so the core knows we care about those
1098 * mailboxes. However, we just grab the events out of the cache when it
1099 * is time to send MWI, since it is only sent with a REGACK. */
1102 /*! \brief Send manager event at call setup to link between Asterisk channel name
1103 and IAX2 call identifiers */
1104 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1106 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1107 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1108 pvt->owner ? pvt->owner->name : "",
1109 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1113 static struct ast_datastore_info iax2_variable_datastore_info = {
1114 .type = "IAX2_VARIABLE",
1115 .duplicate = iax2_dup_variable_datastore,
1116 .destroy = iax2_free_variable_datastore,
1119 static void *iax2_dup_variable_datastore(void *old)
1121 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1122 struct ast_var_t *oldvar, *newvar;
1124 newlist = ast_calloc(sizeof(*newlist), 1);
1126 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1130 AST_LIST_HEAD_INIT(newlist);
1131 AST_LIST_LOCK(oldlist);
1132 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1133 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1135 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1137 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1139 AST_LIST_UNLOCK(oldlist);
1143 static void iax2_free_variable_datastore(void *old)
1145 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1146 struct ast_var_t *oldvar;
1148 AST_LIST_LOCK(oldlist);
1149 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1152 AST_LIST_UNLOCK(oldlist);
1153 AST_LIST_HEAD_DESTROY(oldlist);
1158 /* WARNING: insert_idle_thread should only ever be called within the
1159 * context of an iax2_process_thread() thread.
1161 static void insert_idle_thread(struct iax2_thread *thread)
1163 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1164 AST_LIST_LOCK(&dynamic_list);
1165 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1166 AST_LIST_UNLOCK(&dynamic_list);
1168 AST_LIST_LOCK(&idle_list);
1169 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1170 AST_LIST_UNLOCK(&idle_list);
1176 static struct iax2_thread *find_idle_thread(void)
1178 struct iax2_thread *thread = NULL;
1180 /* Pop the head of the idle list off */
1181 AST_LIST_LOCK(&idle_list);
1182 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1183 AST_LIST_UNLOCK(&idle_list);
1185 /* If we popped a thread off the idle list, just return it */
1187 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1191 /* Pop the head of the dynamic list off */
1192 AST_LIST_LOCK(&dynamic_list);
1193 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1194 AST_LIST_UNLOCK(&dynamic_list);
1196 /* If we popped a thread off the dynamic list, just return it */
1198 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1202 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1203 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1206 /* Set default values */
1207 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1208 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1209 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1211 /* Initialize lock and condition */
1212 ast_mutex_init(&thread->lock);
1213 ast_cond_init(&thread->cond, NULL);
1214 ast_mutex_init(&thread->init_lock);
1215 ast_cond_init(&thread->init_cond, NULL);
1216 ast_mutex_lock(&thread->init_lock);
1218 /* Create thread and send it on it's way */
1219 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1220 ast_cond_destroy(&thread->cond);
1221 ast_mutex_destroy(&thread->lock);
1226 /* this thread is not processing a full frame (since it is idle),
1227 so ensure that the field for the full frame call number is empty */
1228 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1230 /* Wait for the thread to be ready before returning it to the caller */
1231 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1233 /* Done with init_lock */
1234 ast_mutex_unlock(&thread->init_lock);
1239 #ifdef SCHED_MULTITHREADED
1240 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1242 struct iax2_thread *thread = NULL;
1243 static time_t lasterror;
1246 thread = find_idle_thread();
1248 if (thread != NULL) {
1249 thread->schedfunc = func;
1250 thread->scheddata = data;
1251 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1252 #ifdef DEBUG_SCHED_MULTITHREAD
1253 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1255 signal_condition(&thread->lock, &thread->cond);
1260 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1265 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1268 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
1269 ast_sched_cb callback, const void *data)
1271 ast_sched_thread_del(st, id);
1273 return ast_sched_thread_add(st, when, callback, data);
1276 static int iax2_sched_add(struct ast_sched_thread *st, int when,
1277 ast_sched_cb callback, const void *data)
1279 return ast_sched_thread_add(st, when, callback, data);
1282 static int send_ping(const void *data);
1284 static void __send_ping(const void *data)
1286 int callno = (long) data;
1288 ast_mutex_lock(&iaxsl[callno]);
1291 if (iaxs[callno]->peercallno) {
1292 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1293 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1295 /* I am the schedule, so I'm allowed to do this */
1296 iaxs[callno]->pingid = -1;
1298 } else if (option_debug > 0) {
1299 ast_log(LOG_DEBUG, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno);
1302 ast_mutex_unlock(&iaxsl[callno]);
1305 static int send_ping(const void *data)
1307 #ifdef SCHED_MULTITHREADED
1308 if (schedule_action(__send_ping, data))
1315 static void encmethods_to_str(int e, struct ast_str *buf)
1317 ast_str_set(&buf, 0, "(");
1318 if (e & IAX_ENCRYPT_AES128) {
1319 ast_str_append(&buf, 0, "aes128");
1321 if (e & IAX_ENCRYPT_KEYROTATE) {
1322 ast_str_append(&buf, 0, ",keyrotate");
1324 if (ast_str_strlen(buf) > 1) {
1325 ast_str_append(&buf, 0, ")");
1327 ast_str_set(&buf, 0, "No");
1331 static int get_encrypt_methods(const char *s)
1334 if (!strcasecmp(s, "aes128"))
1335 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1336 else if (ast_true(s))
1337 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1343 static int send_lagrq(const void *data);
1345 static void __send_lagrq(const void *data)
1347 int callno = (long) data;
1349 ast_mutex_lock(&iaxsl[callno]);
1352 if (iaxs[callno]->peercallno) {
1353 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1354 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1356 /* I am the schedule, so I'm allowed to do this */
1357 iaxs[callno]->lagid = -1;
1360 ast_log(LOG_WARNING, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno);
1363 ast_mutex_unlock(&iaxsl[callno]);
1366 static int send_lagrq(const void *data)
1368 #ifdef SCHED_MULTITHREADED
1369 if (schedule_action(__send_lagrq, data))
1376 static unsigned char compress_subclass(int subclass)
1380 /* If it's 128 or smaller, just return it */
1381 if (subclass < IAX_FLAG_SC_LOG)
1383 /* Otherwise find its power */
1384 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1385 if (subclass & (1 << x)) {
1387 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1393 return power | IAX_FLAG_SC_LOG;
1396 static int uncompress_subclass(unsigned char csub)
1398 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1399 if (csub & IAX_FLAG_SC_LOG) {
1400 /* special case for 'compressed' -1 */
1404 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1411 * \note The only member of the peer passed here guaranteed to be set is the name field
1413 static int peer_hash_cb(const void *obj, const int flags)
1415 const struct iax2_peer *peer = obj;
1417 return ast_str_hash(peer->name);
1421 * \note The only member of the peer passed here guaranteed to be set is the name field
1423 static int peer_cmp_cb(void *obj, void *arg, int flags)
1425 struct iax2_peer *peer = obj, *peer2 = arg;
1427 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1431 * \note The only member of the user passed here guaranteed to be set is the name field
1433 static int user_hash_cb(const void *obj, const int flags)
1435 const struct iax2_user *user = obj;
1437 return ast_str_hash(user->name);
1441 * \note The only member of the user passed here guaranteed to be set is the name field
1443 static int user_cmp_cb(void *obj, void *arg, int flags)
1445 struct iax2_user *user = obj, *user2 = arg;
1447 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1451 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1452 * so do not call it with a pvt lock held.
1454 static struct iax2_peer *find_peer(const char *name, int realtime)
1456 struct iax2_peer *peer = NULL;
1457 struct iax2_peer tmp_peer = {
1461 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1463 /* Now go for realtime if applicable */
1464 if(!peer && realtime)
1465 peer = realtime_peer(name, NULL);
1470 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1476 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1482 static struct iax2_user *find_user(const char *name)
1484 struct iax2_user tmp_user = {
1488 return ao2_find(users, &tmp_user, OBJ_POINTER);
1490 static inline struct iax2_user *user_ref(struct iax2_user *user)
1496 static inline struct iax2_user *user_unref(struct iax2_user *user)
1502 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1504 struct iax2_peer *peer = NULL;
1506 struct ao2_iterator i;
1508 i = ao2_iterator_init(peers, 0);
1509 while ((peer = ao2_iterator_next(&i))) {
1510 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1511 (peer->addr.sin_port == sin.sin_port)) {
1512 ast_copy_string(host, peer->name, len);
1521 peer = realtime_peer(NULL, &sin);
1523 ast_copy_string(host, peer->name, len);
1532 /*!\note Assumes the lock on the pvt is already held, when
1533 * iax2_destroy_helper() is called. */
1534 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1536 /* Decrement AUTHREQ count if needed */
1537 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1538 struct iax2_user *user;
1539 struct iax2_user tmp_user = {
1540 .name = pvt->username,
1543 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1545 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1549 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1551 /* No more pings or lagrq's */
1552 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
1553 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
1554 ast_sched_thread_del(sched, pvt->autoid);
1555 ast_sched_thread_del(sched, pvt->authid);
1556 ast_sched_thread_del(sched, pvt->initid);
1557 ast_sched_thread_del(sched, pvt->jbid);
1558 ast_sched_thread_del(sched, pvt->keyrotateid);
1561 static void iax2_frame_free(struct iax_frame *fr)
1563 ast_sched_thread_del(sched, fr->retrans);
1567 static int scheduled_destroy(const void *vid)
1569 short callno = PTR_TO_CALLNO(vid);
1570 ast_mutex_lock(&iaxsl[callno]);
1573 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1575 iax2_destroy(callno);
1577 ast_mutex_unlock(&iaxsl[callno]);
1581 static void pvt_destructor(void *obj)
1583 struct chan_iax2_pvt *pvt = obj;
1584 struct iax_frame *cur = NULL;
1586 ast_mutex_lock(&iaxsl[pvt->callno]);
1587 iax2_destroy_helper(pvt);
1588 ast_mutex_unlock(&iaxsl[pvt->callno]);
1591 ast_set_flag(pvt, IAX_ALREADYGONE);
1593 AST_LIST_LOCK(&frame_queue);
1594 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1595 /* Cancel any pending transmissions */
1596 if (cur->callno == pvt->callno) {
1600 AST_LIST_UNLOCK(&frame_queue);
1603 pvt->reg->callno = 0;
1609 ast_variables_destroy(pvt->vars);
1613 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1614 iax2_frame_free(frame.data);
1617 jb_destroy(pvt->jb);
1618 ast_string_field_free_memory(pvt);
1622 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1624 struct chan_iax2_pvt *tmp;
1627 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1631 if (ast_string_field_init(tmp, 32)) {
1643 tmp->keyrotateid = -1;
1645 ast_string_field_set(tmp,exten, "s");
1646 ast_string_field_set(tmp,host, host);
1650 jbconf.max_jitterbuf = maxjitterbuffer;
1651 jbconf.resync_threshold = resyncthreshold;
1652 jbconf.max_contig_interp = maxjitterinterps;
1653 jbconf.target_extra = jittertargetextra;
1654 jb_setconf(tmp->jb,&jbconf);
1656 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1661 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1663 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1665 size_t afdatalen = new->afdatalen;
1666 memcpy(new, fr, sizeof(*new));
1667 iax_frame_wrap(new, &fr->af);
1668 new->afdatalen = afdatalen;
1671 new->direction = DIRECTION_INGRESS;
1677 #define NEW_PREVENT 0
1681 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1683 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1684 (cur->addr.sin_port == sin->sin_port)) {
1685 /* This is the main host */
1686 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1687 (check_dcallno ? dcallno == cur->callno : 1) ) {
1688 /* That's us. Be sure we keep track of the peer call number */
1692 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1693 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1694 /* We're transferring */
1695 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1701 static void update_max_trunk(void)
1703 int max = TRUNK_CALL_START;
1706 /* XXX Prolly don't need locks here XXX */
1707 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1715 ast_debug(1, "New max trunk callno is %d\n", max);
1718 static void update_max_nontrunk(void)
1722 /* XXX Prolly don't need locks here XXX */
1723 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1727 maxnontrunkcall = max;
1729 ast_debug(1, "New max nontrunk callno is %d\n", max);
1732 static int make_trunk(unsigned short callno, int locked)
1736 struct timeval now = ast_tvnow();
1737 if (iaxs[callno]->oseqno) {
1738 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1741 if (callno & TRUNK_CALL_START) {
1742 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1745 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1746 ast_mutex_lock(&iaxsl[x]);
1747 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1749 * \note We delete these before switching the slot, because if
1750 * they fire in the meantime, they will generate a warning.
1752 ast_sched_thread_del(sched, iaxs[callno]->pingid);
1753 ast_sched_thread_del(sched, iaxs[callno]->lagid);
1754 iaxs[x] = iaxs[callno];
1755 iaxs[x]->callno = x;
1756 iaxs[callno] = NULL;
1757 /* Update the two timers that should have been started */
1758 iaxs[x]->pingid = iax2_sched_add(sched,
1759 ping_time * 1000, send_ping, (void *)(long)x);
1760 iaxs[x]->lagid = iax2_sched_add(sched,
1761 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1763 ast_mutex_unlock(&iaxsl[callno]);
1766 ast_mutex_unlock(&iaxsl[x]);
1769 ast_mutex_unlock(&iaxsl[x]);
1771 if (x >= ARRAY_LEN(iaxs) - 1) {
1772 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1775 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1776 /* We move this call from a non-trunked to a trunked call */
1778 update_max_nontrunk();
1782 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
1784 if (!pvt->transfercallno) {
1785 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1789 ao2_link(iax_transfercallno_pvts, pvt);
1792 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
1794 if (!pvt->transfercallno) {
1795 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1799 ao2_unlink(iax_transfercallno_pvts, pvt);
1801 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1803 if (!pvt->peercallno) {
1804 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1808 ao2_link(iax_peercallno_pvts, pvt);
1811 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1813 if (!pvt->peercallno) {
1814 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1818 ao2_unlink(iax_peercallno_pvts, pvt);
1822 * \note Calling this function while holding another pvt lock can cause a deadlock.
1824 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1831 if (new <= NEW_ALLOW) {
1833 struct chan_iax2_pvt *pvt;
1834 struct chan_iax2_pvt tmp_pvt = {
1836 .peercallno = callno,
1837 .transfercallno = callno,
1839 .frames_received = check_dcallno,
1842 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1843 /* this works for finding normal call numbers not involving transfering */
1844 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1845 if (return_locked) {
1846 ast_mutex_lock(&iaxsl[pvt->callno]);
1853 /* this searches for transfer call numbers that might not get caught otherwise */
1854 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
1855 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.addr));
1856 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1857 if (return_locked) {
1858 ast_mutex_lock(&iaxsl[pvt->callno]);
1866 /* This will occur on the first response to a message that we initiated,
1867 * such as a PING. */
1869 ast_mutex_lock(&iaxsl[dcallno]);
1871 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1872 iaxs[dcallno]->peercallno = callno;
1874 store_by_peercallno(iaxs[dcallno]);
1875 if (!res || !return_locked) {
1876 ast_mutex_unlock(&iaxsl[dcallno]);
1881 ast_mutex_unlock(&iaxsl[dcallno]);
1884 /* If we get here, we SHOULD NOT find a call structure for this
1885 callno; if we do, it means that there is a call structure that
1886 has a peer callno but did NOT get entered into the hash table,
1889 If we find a call structure using this old, slow method, output a log
1890 message so we'll know about it. After a few months of leaving this in
1891 place, if we don't hear about people seeing these messages, we can
1892 remove this code for good.
1895 for (x = 1; !res && x < maxnontrunkcall; x++) {
1896 ast_mutex_lock(&iaxsl[x]);
1898 /* Look for an exact match */
1899 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1903 if (!res || !return_locked)
1904 ast_mutex_unlock(&iaxsl[x]);
1906 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1907 ast_mutex_lock(&iaxsl[x]);
1909 /* Look for an exact match */
1910 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1914 if (!res || !return_locked)
1915 ast_mutex_unlock(&iaxsl[x]);
1919 if (!res && (new >= NEW_ALLOW)) {
1920 int start, found = 0;
1922 /* It may seem odd that we look through the peer list for a name for
1923 * this *incoming* call. Well, it is weird. However, users don't
1924 * have an IP address/port number that we can match against. So,
1925 * this is just checking for a peer that has that IP/port and
1926 * assuming that we have a user of the same name. This isn't always
1927 * correct, but it will be changed if needed after authentication. */
1928 if (!iax2_getpeername(*sin, host, sizeof(host)))
1929 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1932 start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1933 for (x = start; 1; x++) {
1934 if (x == TRUNK_CALL_START) {
1939 /* Find first unused call number that hasn't been used in a while */
1940 ast_mutex_lock(&iaxsl[x]);
1941 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1945 ast_mutex_unlock(&iaxsl[x]);
1947 if (x == start - 1) {
1951 /* We've still got lock held if we found a spot */
1952 if (x == start - 1 && !found) {
1953 ast_log(LOG_WARNING, "No more space\n");
1956 iaxs[x] = new_iax(sin, host);
1957 update_max_nontrunk();
1960 ast_debug(1, "Creating new call structure %d\n", x);
1961 iaxs[x]->sockfd = sockfd;
1962 iaxs[x]->addr.sin_port = sin->sin_port;
1963 iaxs[x]->addr.sin_family = sin->sin_family;
1964 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1965 iaxs[x]->peercallno = callno;
1966 iaxs[x]->callno = x;
1967 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1968 iaxs[x]->expiry = min_reg_expire;
1969 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1970 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1971 iaxs[x]->amaflags = amaflags;
1972 ast_copy_flags(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT);
1973 ast_string_field_set(iaxs[x], accountcode, accountcode);
1974 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1975 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1976 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
1978 if (iaxs[x]->peercallno) {
1979 store_by_peercallno(iaxs[x]);
1982 ast_log(LOG_WARNING, "Out of resources\n");
1983 ast_mutex_unlock(&iaxsl[x]);
1987 ast_mutex_unlock(&iaxsl[x]);
1993 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1995 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1998 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2000 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2004 * \brief Queue a frame to a call's owning asterisk channel
2006 * \pre This function assumes that iaxsl[callno] is locked when called.
2008 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2009 * was valid before calling it, it may no longer be valid after calling it.
2010 * This function may unlock and lock the mutex associated with this callno,
2011 * meaning that another thread may grab it and destroy the call.
2013 static int iax2_queue_frame(int callno, struct ast_frame *f)
2016 if (iaxs[callno] && iaxs[callno]->owner) {
2017 if (ast_channel_trylock(iaxs[callno]->owner)) {
2018 /* Avoid deadlock by pausing and trying again */
2019 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2021 ast_queue_frame(iaxs[callno]->owner, f);
2022 ast_channel_unlock(iaxs[callno]->owner);
2032 * \brief Queue a hangup frame on the ast_channel owner
2034 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2035 * is active for the given call number.
2037 * \pre Assumes lock for callno is already held.
2039 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2040 * was valid before calling it, it may no longer be valid after calling it.
2041 * This function may unlock and lock the mutex associated with this callno,
2042 * meaning that another thread may grab it and destroy the call.
2044 static int iax2_queue_hangup(int callno)
2047 if (iaxs[callno] && iaxs[callno]->owner) {
2048 if (ast_channel_trylock(iaxs[callno]->owner)) {
2049 /* Avoid deadlock by pausing and trying again */
2050 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2052 ast_queue_hangup(iaxs[callno]->owner);
2053 ast_channel_unlock(iaxs[callno]->owner);
2063 * \brief Queue a control frame on the ast_channel owner
2065 * This function queues a control frame on the owner of the IAX2 pvt struct that
2066 * is active for the given call number.
2068 * \pre Assumes lock for callno is already held.
2070 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2071 * was valid before calling it, it may no longer be valid after calling it.
2072 * This function may unlock and lock the mutex associated with this callno,
2073 * meaning that another thread may grab it and destroy the call.
2075 static int iax2_queue_control_data(int callno,
2076 enum ast_control_frame_type control, const void *data, size_t datalen)
2079 if (iaxs[callno] && iaxs[callno]->owner) {
2080 if (ast_channel_trylock(iaxs[callno]->owner)) {
2081 /* Avoid deadlock by pausing and trying again */
2082 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2084 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2085 ast_channel_unlock(iaxs[callno]->owner);
2093 static void destroy_firmware(struct iax_firmware *cur)
2095 /* Close firmware */
2097 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
2103 static int try_firmware(char *s)
2106 struct iax_firmware *cur = NULL;
2107 int ifd, fd, res, len, chunk;
2108 struct ast_iax2_firmware_header *fwh, fwh2;
2109 struct MD5Context md5;
2110 unsigned char sum[16], buf[1024];
2113 if (!(s2 = alloca(strlen(s) + 100))) {
2114 ast_log(LOG_WARNING, "Alloca failed!\n");
2118 last = strrchr(s, '/');
2124 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
2126 if ((res = stat(s, &stbuf) < 0)) {
2127 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
2131 /* Make sure it's not a directory */
2132 if (S_ISDIR(stbuf.st_mode))
2134 ifd = open(s, O_RDONLY);
2136 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
2139 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
2141 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
2145 /* Unlink our newly created file */
2148 /* Now copy the firmware into it */
2149 len = stbuf.st_size;
2152 if (chunk > sizeof(buf))
2153 chunk = sizeof(buf);
2154 res = read(ifd, buf, chunk);
2156 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2161 res = write(fd, buf, chunk);
2163 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2171 /* Return to the beginning */
2172 lseek(fd, 0, SEEK_SET);
2173 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2174 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2178 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2179 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2183 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2184 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2188 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2189 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2193 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
2194 if (fwh == (void *) -1) {
2195 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
2200 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2201 MD5Final(sum, &md5);
2202 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2203 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2204 munmap((void*)fwh, stbuf.st_size);
2209 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2210 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
2211 /* Found a candidate */
2212 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
2213 /* The version we have on loaded is older, load this one instead */
2215 /* This version is no newer than what we have. Don't worry about it.
2216 We'll consider it a proper load anyhow though */
2217 munmap((void*)fwh, stbuf.st_size);
2223 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2225 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2230 munmap((void*)cur->fwh, cur->mmaplen);
2235 cur->mmaplen = stbuf.st_size;
2242 static int iax_check_version(char *dev)
2245 struct iax_firmware *cur = NULL;
2247 if (ast_strlen_zero(dev))
2250 AST_LIST_LOCK(&firmwares);
2251 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2252 if (!strcmp(dev, (char *)cur->fwh->devname)) {
2253 res = ntohs(cur->fwh->version);
2257 AST_LIST_UNLOCK(&firmwares);
2262 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2265 unsigned int bs = desc & 0xff;
2266 unsigned int start = (desc >> 8) & 0xffffff;
2268 struct iax_firmware *cur;
2270 if (ast_strlen_zero((char *)dev) || !bs)
2275 AST_LIST_LOCK(&firmwares);
2276 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2277 if (strcmp((char *)dev, (char *)cur->fwh->devname))
2279 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2280 if (start < ntohl(cur->fwh->datalen)) {
2281 bytes = ntohl(cur->fwh->datalen) - start;
2284 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2287 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2295 AST_LIST_UNLOCK(&firmwares);
2301 static void reload_firmware(int unload)
2303 struct iax_firmware *cur = NULL;
2306 char dir[256], fn[256];
2308 AST_LIST_LOCK(&firmwares);
2310 /* Mark all as dead */
2311 AST_LIST_TRAVERSE(&firmwares, cur, list)
2314 /* Now that we have marked them dead... load new ones */
2316 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2319 while((de = readdir(fwd))) {
2320 if (de->d_name[0] != '.') {
2321 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2322 if (!try_firmware(fn)) {
2323 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2329 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2332 /* Clean up leftovers */
2333 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2336 AST_LIST_REMOVE_CURRENT(list);
2337 destroy_firmware(cur);
2339 AST_LIST_TRAVERSE_SAFE_END;
2341 AST_LIST_UNLOCK(&firmwares);
2345 * \note This function assumes that iaxsl[callno] is locked when called.
2347 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2348 * was valid before calling it, it may no longer be valid after calling it.
2349 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2350 * associated with this callno, meaning that another thread may grab it and destroy the call.
2352 static int __do_deliver(void *data)
2354 /* Just deliver the packet by using queueing. This is called by
2355 the IAX thread with the iaxsl lock held. */
2356 struct iax_frame *fr = data;
2358 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2359 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2360 iax2_queue_frame(fr->callno, &fr->af);
2361 /* Free our iax frame */
2362 iax2_frame_free(fr);
2363 /* And don't run again */
2367 static int handle_error(void)
2369 /* XXX Ideally we should figure out why an error occurred and then abort those
2370 rather than continuing to try. Unfortunately, the published interface does
2371 not seem to work XXX */
2373 struct sockaddr_in *sin;
2376 struct sock_extended_err e;
2381 m.msg_controllen = sizeof(e);
2383 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2385 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2387 if (m.msg_controllen) {
2388 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2390 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2392 ast_log(LOG_WARNING, "No address detected??\n");
2394 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2401 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2404 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2407 ast_debug(1, "Received error: %s\n", strerror(errno));
2414 static int send_packet(struct iax_frame *f)
2417 int callno = f->callno;
2419 /* Don't send if there was an error, but return error instead */
2420 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2423 /* Called with iaxsl held */
2425 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
2429 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2430 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
2433 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2434 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
2438 ast_debug(1, "Received error: %s\n", strerror(errno));
2447 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2448 * for the given call number may disappear during its execution.
2450 static int iax2_predestroy(int callno)
2452 struct ast_channel *c = NULL;
2453 struct chan_iax2_pvt *pvt = iaxs[callno];
2458 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2459 iax2_destroy_helper(pvt);
2460 ast_set_flag(pvt, IAX_ALREADYGONE);
2463 if ((c = pvt->owner)) {
2465 iax2_queue_hangup(callno);
2467 ast_module_unref(ast_module_info->self);
2473 static void iax2_destroy(int callno)
2475 struct chan_iax2_pvt *pvt = NULL;
2476 struct ast_channel *owner = NULL;
2479 if ((pvt = iaxs[callno])) {
2480 iax2_destroy_helper(pvt);
2483 lastused[callno] = ast_tvnow();
2485 owner = pvt ? pvt->owner : NULL;
2488 if (ast_channel_trylock(owner)) {
2489 ast_debug(3, "Avoiding IAX destroy deadlock\n");
2490 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2496 iaxs[callno] = NULL;
2503 /* If there's an owner, prod it to give up */
2504 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2505 * because we already hold the owner channel lock. */
2506 ast_queue_hangup(owner);
2509 if (pvt->peercallno) {
2510 remove_by_peercallno(pvt);
2513 if (pvt->transfercallno) {
2514 remove_by_transfercallno(pvt);
2524 ast_channel_unlock(owner);
2527 if (callno & 0x4000) {
2532 static int update_packet(struct iax_frame *f)
2534 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2535 struct ast_iax2_full_hdr *fh = f->data;
2536 struct ast_frame af;
2538 /* if frame is encrypted. decrypt before updating it. */
2539 if (f->encmethods) {
2540 decode_frame(&f->mydcx, fh, &af, &f->datalen);
2542 /* Mark this as a retransmission */
2543 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2545 f->iseqno = iaxs[f->callno]->iseqno;
2546 fh->iseqno = f->iseqno;
2548 /* Now re-encrypt the frame */
2549 if (f->encmethods) {
2550 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
2555 static int attempt_transmit(const void *data);
2556 static void __attempt_transmit(const void *data)
2558 /* Attempt to transmit the frame to the remote peer...
2559 Called without iaxsl held. */
2560 struct iax_frame *f = (struct iax_frame *)data;
2562 int callno = f->callno;
2563 /* Make sure this call is still active */
2565 ast_mutex_lock(&iaxsl[callno]);
2566 if (callno && iaxs[callno]) {
2567 if ((f->retries < 0) /* Already ACK'd */ ||
2568 (f->retries >= max_retries) /* Too many attempts */) {
2569 /* Record an error if we've transmitted too many times */
2570 if (f->retries >= max_retries) {
2572 /* Transfer timeout */
2573 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2574 } else if (f->final) {
2575 iax2_destroy(callno);
2577 if (iaxs[callno]->owner)
2578 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2579 iaxs[callno]->error = ETIMEDOUT;
2580 if (iaxs[callno]->owner) {
2581 struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
2583 iax2_queue_frame(callno, &fr); /* XXX */
2584 /* Remember, owner could disappear */
2585 if (iaxs[callno] && iaxs[callno]->owner)
2586 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2588 if (iaxs[callno]->reg) {
2589 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2590 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2591 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2593 iax2_destroy(callno);
2600 /* Update it if it needs it */
2602 /* Attempt transmission */
2605 /* Try again later after 10 times as long */
2607 if (f->retrytime > MAX_RETRY_TIME)
2608 f->retrytime = MAX_RETRY_TIME;
2609 /* Transfer messages max out at one second */
2610 if (f->transfer && (f->retrytime > 1000))
2611 f->retrytime = 1000;
2612 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2615 /* Make sure it gets freed */
2620 ast_mutex_unlock(&iaxsl[callno]);
2621 /* Do not try again */
2623 /* Don't attempt delivery, just remove it from the queue */
2624 AST_LIST_LOCK(&frame_queue);
2625 AST_LIST_REMOVE(&frame_queue, f, list);
2626 AST_LIST_UNLOCK(&frame_queue);
2628 /* Free the IAX frame */
2633 static int attempt_transmit(const void *data)
2635 #ifdef SCHED_MULTITHREADED
2636 if (schedule_action(__attempt_transmit, data))
2638 __attempt_transmit(data);
2642 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2644 struct iax2_peer *peer = NULL;
2645 struct iax2_user *user = NULL;
2646 static char *choices[] = { "all", NULL };
2651 e->command = "iax2 prune realtime";
2653 "Usage: iax2 prune realtime [<peername>|all]\n"
2654 " Prunes object(s) from the cache\n";
2658 cmplt = ast_cli_complete(a->word, choices, a->n);
2660 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
2666 return CLI_SHOWUSAGE;
2667 if (!strcmp(a->argv[3], "all")) {
2670 ast_cli(a->fd, "Cache flushed successfully.\n");
2673 peer = find_peer(a->argv[3], 0);
2674 user = find_user(a->argv[3]);
2677 if (ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2678 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2679 expire_registry(peer_ref(peer));
2680 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2682 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2687 if (ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
2688 ast_set_flag(user, IAX_RTAUTOCLEAR);
2689 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
2691 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
2693 ao2_unlink(users,user);
2697 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
2703 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2707 e->command = "iax2 test losspct";
2709 "Usage: iax2 test losspct <percentage>\n"
2710 " For testing, throws away <percentage> percent of incoming packets\n";
2716 return CLI_SHOWUSAGE;
2718 test_losspct = atoi(a->argv[3]);
2724 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2728 e->command = "iax2 test late";
2730 "Usage: iax2 test late <ms>\n"
2731 " For testing, count the next frame as <ms> ms late\n";
2738 return CLI_SHOWUSAGE;
2740 test_late = atoi(a->argv[3]);
2745 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2749 e->command = "iax2 test resync";
2751 "Usage: iax2 test resync <ms>\n"
2752 " For testing, adjust all future frames by <ms> ms\n";
2759 return CLI_SHOWUSAGE;
2761 test_resync = atoi(a->argv[3]);
2766 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2770 e->command = "iax2 test jitter";
2772 "Usage: iax2 test jitter <ms> <pct>\n"
2773 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2774 " percentage of packets. If <pct> is not specified, adds\n"
2775 " jitter to all packets.\n";
2781 if (a->argc < 4 || a->argc > 5)
2782 return CLI_SHOWUSAGE;
2784 test_jit = atoi(a->argv[3]);
2786 test_jitpct = atoi(a->argv[4]);
2790 #endif /* IAXTESTS */
2792 /*! \brief peer_status: Report Peer status in character string */
2793 /* returns 1 if peer is online, -1 if unmonitored */
2794 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2798 if (peer->lastms < 0) {
2799 ast_copy_string(status, "UNREACHABLE", statuslen);
2800 } else if (peer->lastms > peer->maxms) {
2801 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2803 } else if (peer->lastms) {
2804 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2807 ast_copy_string(status, "UNKNOWN", statuslen);
2810 ast_copy_string(status, "Unmonitored", statuslen);
2816 /*! \brief Show one peer in detail */
2817 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2821 struct iax2_peer *peer;
2822 char codec_buf[512];
2823 struct ast_str *encmethods = ast_str_alloca(256);
2824 int x = 0, codec = 0, load_realtime = 0;
2828 e->command = "iax2 show peer";
2830 "Usage: iax2 show peer <name>\n"
2831 " Display details on specific IAX peer\n";
2835 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
2840 return CLI_SHOWUSAGE;
2842 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2844 peer = find_peer(a->argv[3], load_realtime);
2846 encmethods_to_str(peer->encmethods, encmethods);
2847 ast_cli(a->fd, "\n\n");
2848 ast_cli(a->fd, " * Name : %s\n", peer->name);
2849 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2850 ast_cli(a->fd, " Context : %s\n", peer->context);
2851 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
2852 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
2853 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2854 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
2855 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
2856 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2857 ast_cli(a->fd, " Expire : %d\n", peer->expire);
2858 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
2859 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2860 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2861 ast_cli(a->fd, " Username : %s\n", peer->username);
2862 ast_cli(a->fd, " Codecs : ");
2863 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2864 ast_cli(a->fd, "%s\n", codec_buf);
2866 ast_cli(a->fd, " Codec Order : (");
2867 for(x = 0; x < 32 ; x++) {
2868 codec = ast_codec_pref_index(&peer->prefs,x);
2871 ast_cli(a->fd, "%s", ast_getformatname(codec));
2872 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2873 ast_cli(a->fd, "|");
2877 ast_cli(a->fd, "none");
2878 ast_cli(a->fd, ")\n");
2880 ast_cli(a->fd, " Status : ");
2881 peer_status(peer, status, sizeof(status));
2882 ast_cli(a->fd, "%s\n",status);
2883 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2884 ast_cli(a->fd, "\n");
2887 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2888 ast_cli(a->fd, "\n");
2894 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags)
2897 struct iax2_peer *peer;
2899 int wordlen = strlen(word);
2900 struct ao2_iterator i;
2902 i = ao2_iterator_init(peers, 0);
2903 while ((peer = ao2_iterator_next(&i))) {
2904 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
2905 && (!flags || ast_test_flag(peer, flags))) {
2906 res = ast_strdup(peer->name);
2916 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2918 struct iax_frame *cur;
2919 int cnt = 0, dead = 0, final = 0;
2923 e->command = "iax2 show stats";
2925 "Usage: iax2 show stats\n"
2926 " Display statistics on IAX channel driver.\n";
2933 return CLI_SHOWUSAGE;
2935 AST_LIST_LOCK(&frame_queue);
2936 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2937 if (cur->retries < 0)
2943 AST_LIST_UNLOCK(&frame_queue);
2945 ast_cli(a->fd, " IAX Statistics\n");
2946 ast_cli(a->fd, "---------------------\n");
2947 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2948 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2949 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2950 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2952 trunk_timed = trunk_untimed = 0;
2953 if (trunk_maxmtu > trunk_nmaxmtu)
2954 trunk_nmaxmtu = trunk_maxmtu;
2959 /*! \brief Set trunk MTU from CLI */
2960 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2966 e->command = "iax2 set mtu";
2968 "Usage: iax2 set mtu <value>\n"
2969 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2970 " zero to disable. Disabling means that the operating system\n"
2971 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2972 " packet exceeds the UDP payload size. This is substantially\n"
2973 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2974 " greater for G.711 samples.\n";
2981 return CLI_SHOWUSAGE;
2982 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2983 mtuv = MAX_TRUNK_MTU;
2985 mtuv = atoi(a->argv[3]);
2988 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2989 global_max_trunk_mtu = 0;
2992 if (mtuv < 172 || mtuv > 4000) {
2993 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
2994 return CLI_SHOWUSAGE;
2996 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2997 global_max_trunk_mtu = mtuv;
3001 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3003 struct iax2_dpcache *dp = NULL;
3004 char tmp[1024], *pc = NULL;
3006 struct timeval now = ast_tvnow();
3010 e->command = "iax2 show cache";
3012 "Usage: iax2 show cache\n"
3013 " Display currently cached IAX Dialplan results.\n";
3019 AST_LIST_LOCK(&dpcache);
3021 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
3023 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
3024 s = dp->expiry.tv_sec - now.tv_sec;
3026 if (dp->flags & CACHE_FLAG_EXISTS)
3027 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
3028 if (dp->flags & CACHE_FLAG_NONEXISTENT)
3029 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
3030 if (dp->flags & CACHE_FLAG_CANEXIST)
3031 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
3032 if (dp->flags & CACHE_FLAG_PENDING)
3033 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
3034 if (dp->flags & CACHE_FLAG_TIMEOUT)
3035 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
3036 if (dp->flags & CACHE_FLAG_TRANSMITTED)
3037 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
3038 if (dp->flags & CACHE_FLAG_MATCHMORE)
3039 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
3040 if (dp->flags & CACHE_FLAG_UNKNOWN)
3041 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
3042 /* Trim trailing pipe */
3043 if (!ast_strlen_zero(tmp)) {
3044 tmp[strlen(tmp) - 1] = '\0';
3046 ast_copy_string(tmp, "(none)", sizeof(tmp));
3049 pc = strchr(dp->peercontext, '@');
3051 pc = dp->peercontext;
3055 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
3056 if (dp->waiters[x] > -1)
3060 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
3062 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
3066 AST_LIST_LOCK(&dpcache);
3071 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
3073 static void unwrap_timestamp(struct iax_frame *fr)
3075 /* Video mini frames only encode the lower 15 bits of the session
3076 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
3077 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
3078 const int lower_mask = (1 << ts_shift) - 1;
3079 const int upper_mask = ~lower_mask;
3080 const int last_upper = iaxs[fr->callno]->last & upper_mask;
3082 if ( (fr->ts & upper_mask) == last_upper ) {
3083 const int x = fr->ts - iaxs[fr->callno]->last;
3084 const int threshold = (ts_shift == 15) ? 25000 : 50000;
3086 if (x < -threshold) {
3087 /* Sudden big jump backwards in timestamp:
3088 What likely happened here is that miniframe timestamp has circled but we haven't
3089 gotten the update from the main packet. We'll just pretend that we did, and
3090 update the timestamp appropriately. */
3091 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
3093 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
3094 } else if (x > threshold) {
3095 /* Sudden apparent big jump forwards in timestamp:
3096 What's likely happened is this is an old miniframe belonging to the previous
3097 top 15 or 16-bit timestamp that has turned up out of order.
3098 Adjust the timestamp appropriately. */
3099 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
3101 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
3106 static int get_from_jb(const void *p);
3108 static void update_jbsched(struct chan_iax2_pvt *pvt)
3112 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
3114 when = jb_next(pvt->jb) - when;
3117 /* XXX should really just empty until when > 0.. */
3121 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
3122 CALLNO_TO_PTR(pvt->callno));
3125 static void __get_from_jb(const void *p)
3127 int callno = PTR_TO_CALLNO(p);
3128 struct chan_iax2_pvt *pvt = NULL;
3129 struct iax_frame *fr;
3134 struct timeval now = ast_tvnow();
3136 /* Make sure we have a valid private structure before going on */
3137 ast_mutex_lock(&iaxsl[callno]);
3141 ast_mutex_unlock(&iaxsl[callno]);
3147 /* round up a millisecond since ast_sched_runq does; */
3148 /* prevents us from spinning while waiting for our now */
3149 /* to catch up with runq's now */
3150 now.tv_usec += 1000;
3152 ms = ast_tvdiff_ms(now, pvt->rxcore);
3154 if(ms >= (next = jb_next(pvt->jb))) {
3155 ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));