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
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
26 * \ingroup channel_drivers
28 * \todo Implement musicclass settings for IAX2 devices
31 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
32 * \addtogroup configuration_file
35 /*! \page iax.conf iax.conf
36 * \verbinclude iax.conf.sample
40 * \todo XXX The IAX2 channel driver needs its native bridge
41 * code converted to the new bridge technology scheme.
43 * \note The chan_dahdi native bridge code can be used as an
44 * example. It also appears that chan_iax2 also has a native
45 * transfer check like chan_dahdi to eliminate tromboned calls.
47 * \note The existing native bridge code is marked with the
48 * IAX2_NATIVE_BRIDGING conditional.
52 <use type="module">res_crypto</use>
53 <use type="external">crypto</use>
54 <support_level>core</support_level>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
73 #include "asterisk/paths.h"
75 #include "asterisk/lock.h"
76 #include "asterisk/frame.h"
77 #include "asterisk/channel.h"
78 #include "asterisk/module.h"
79 #include "asterisk/pbx.h"
80 #include "asterisk/sched.h"
81 #include "asterisk/io.h"
82 #include "asterisk/config.h"
83 #include "asterisk/cli.h"
84 #include "asterisk/translate.h"
85 #include "asterisk/md5.h"
86 #include "asterisk/crypto.h"
87 #include "asterisk/acl.h"
88 #include "asterisk/manager.h"
89 #include "asterisk/callerid.h"
90 #include "asterisk/app.h"
91 #include "asterisk/mwi.h"
92 #include "asterisk/astdb.h"
93 #include "asterisk/musiconhold.h"
94 #include "asterisk/features.h"
95 #include "asterisk/utils.h"
96 #include "asterisk/causes.h"
97 #include "asterisk/localtime.h"
98 #include "asterisk/dnsmgr.h"
99 #include "asterisk/devicestate.h"
100 #include "asterisk/stringfields.h"
101 #include "asterisk/linkedlists.h"
102 #include "asterisk/astobj2.h"
103 #include "asterisk/timing.h"
104 #include "asterisk/taskprocessor.h"
105 #include "asterisk/test.h"
106 #include "asterisk/security_events.h"
107 #include "asterisk/stasis_endpoints.h"
108 #include "asterisk/bridge.h"
109 #include "asterisk/stasis.h"
110 #include "asterisk/stasis_system.h"
111 #include "asterisk/stasis_channels.h"
112 #include "asterisk/format_cache.h"
113 #include "asterisk/format_compatibility.h"
114 #include "asterisk/format_cap.h"
116 #include "iax2/include/iax2.h"
117 #include "iax2/include/firmware.h"
118 #include "iax2/include/parser.h"
119 #include "iax2/include/provision.h"
120 #include "iax2/include/codec_pref.h"
121 #include "iax2/include/format_compatibility.h"
122 #include "iax2/include/netsock.h"
124 #include "jitterbuf.h"
127 <application name="IAX2Provision" language="en_US">
129 Provision a calling IAXy with a given template.
132 <parameter name="template">
133 <para>If not specified, defaults to <literal>default</literal>.</para>
137 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
138 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
139 or <literal>0</literal> on success.</para>
142 <function name="IAXPEER" language="en_US">
144 Gets IAX peer information.
147 <parameter name="peername" required="true">
149 <enum name="CURRENTCHANNEL">
150 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
151 endpoint of the current channel</para>
155 <parameter name="item">
156 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
159 <para>(default) The IP address.</para>
162 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
164 <enum name="mailbox">
165 <para>The configured mailbox.</para>
167 <enum name="context">
168 <para>The configured context.</para>
171 <para>The epoch time of the next expire.</para>
173 <enum name="dynamic">
174 <para>Is it dynamic? (yes/no).</para>
176 <enum name="callerid_name">
177 <para>The configured Caller ID name.</para>
179 <enum name="callerid_num">
180 <para>The configured Caller ID number.</para>
183 <para>The configured codecs.</para>
185 <enum name="codec[x]">
186 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
187 with <literal>0</literal>)</para>
193 <para>Gets information associated with the specified IAX2 peer.</para>
196 <ref type="function">SIPPEER</ref>
199 <function name="IAXVAR" language="en_US">
201 Sets or retrieves a remote variable.
204 <parameter name="varname" required="true" />
207 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
210 <info name="CHANNEL" language="en_US" tech="IAX">
212 <enum name="osptoken">
213 <para>R/O Get the peer's osptoken.</para>
216 <para>R/O Get the peer's ip address.</para>
218 <enum name="peername">
219 <para>R/O Get the peer's username.</para>
221 <enum name="secure_signaling">
222 <para>R/O Get the if the IAX channel is secured.</para>
224 <enum name="secure_media">
225 <para>R/O Get the if the IAX channel is secured.</para>
229 <info name="Dial_Resource" language="en_US" tech="IAX2">
230 <para>The general syntax is:</para>
231 <para><literal>Dial(IAX2/[username[:password]@]peer[:port][/exten[@context]][/options]</literal></para>
232 <para>IAX2 optionally allows modifiers to be specified after the extension.</para>
235 <para>Request auto answer (supporting equipment/configuration required)</para>
239 <manager name="IAXpeers" language="en_US">
244 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
249 <manager name="IAXpeerlist" language="en_US">
254 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
257 <para>List all the IAX peers.</para>
260 <manager name="IAXnetstats" language="en_US">
266 <para>Show IAX channels network statistics.</para>
269 <manager name="IAXregistry" language="en_US">
271 Show IAX registrations.
274 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
277 <para>Show IAX registrations.</para>
282 /* Define SCHED_MULTITHREADED to run the scheduler in a special
283 multithreaded mode. */
284 #define SCHED_MULTITHREADED
286 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
287 thread is actually doing. */
288 #define DEBUG_SCHED_MULTITHREAD
292 static int nochecksums = 0;
295 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
296 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
298 #define DEFAULT_THREAD_COUNT 10
299 #define DEFAULT_MAX_THREAD_COUNT 100
300 #define DEFAULT_RETRY_TIME 1000
301 #define MEMORY_SIZE 100
302 #define DEFAULT_DROP 3
304 #define DEBUG_SUPPORT
306 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
308 /* Sample over last 100 units to determine historic jitter */
311 static struct iax2_codec_pref prefs_global;
313 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
316 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
317 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
318 #define MAX_TRUNK_MTU 1240
320 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
321 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
323 #define DEFAULT_CONTEXT "default"
325 static char default_parkinglot[AST_MAX_CONTEXT];
327 static char language[MAX_LANGUAGE] = "";
328 static char regcontext[AST_MAX_CONTEXT] = "";
330 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
331 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
332 static int network_change_sched_id = -1;
334 static int maxauthreq = 3;
335 static int max_retries = 4;
336 static int ping_time = 21;
337 static int lagrq_time = 10;
338 static int maxjitterbuffer=1000;
339 static int resyncthreshold=1000;
340 static int maxjitterinterps=10;
341 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
343 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
345 static int trunkfreq = 20;
346 static int trunkmaxsize = MAX_TRUNKDATA;
348 static int authdebug = 0;
349 static int autokill = 0;
350 static int iaxcompat = 0;
351 static int last_authmethod = 0;
353 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
355 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
362 static int min_reg_expire;
363 static int max_reg_expire;
365 static int srvlookup = 0;
367 static struct ast_timer *timer; /* Timer for trunking */
369 static struct ast_netsock_list *netsock;
370 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
371 static int defaultsockfd = -1;
373 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
376 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
378 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
380 ~AST_FORMAT_SLIN16 & \
381 ~AST_FORMAT_SIREN7 & \
382 ~AST_FORMAT_SIREN14 & \
388 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
390 ~AST_FORMAT_G726_AAL2 & \
393 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
397 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
398 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
399 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
401 /* if a pvt has encryption setup done and is running on the call */
402 #define IAX_CALLENCRYPTED(pvt) \
403 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
405 #define IAX_DEBUGDIGEST(msg, key) do { \
407 char digest[33] = ""; \
412 for (idx = 0; idx < 16; idx++) \
413 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
415 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
418 static struct io_context *io;
419 static struct ast_sched_context *sched;
421 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
423 static int iaxdebug = 0;
425 static int iaxtrunkdebug = 0;
427 static int test_losspct = 0;
429 static int test_late = 0;
430 static int test_resync = 0;
431 static int test_jit = 0;
432 static int test_jitpct = 0;
433 #endif /* IAXTESTS */
435 static char accountcode[AST_MAX_ACCOUNT_CODE];
436 static char mohinterpret[MAX_MUSICCLASS];
437 static char mohsuggest[MAX_MUSICCLASS];
438 static int amaflags = 0;
440 static int delayreject = 0;
441 static int iax2_encryption = 0;
442 static int iax2_authmethods = 0;
444 static struct ast_flags64 globalflags = { 0 };
446 static pthread_t netthreadid = AST_PTHREADT_NULL;
449 IAX_STATE_STARTED = (1 << 0),
450 IAX_STATE_AUTHENTICATED = (1 << 1),
451 IAX_STATE_TBD = (1 << 2),
454 struct iax2_context {
455 char context[AST_MAX_CONTEXT];
456 struct iax2_context *next;
460 #define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
461 #define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
462 #define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
463 #define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
464 #define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
465 #define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
466 #define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
467 #define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
468 #define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
469 #define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
470 #define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
471 #define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
472 #define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
473 #define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
474 #define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
475 #define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
476 #define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
477 #define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
478 #define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
479 #define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
480 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
481 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
482 #define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
483 #define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
484 #define IAX_DELAYPBXSTART (uint64_t)(1LLU << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
485 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
486 #define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
487 #define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
488 #define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
489 #define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
490 #define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
491 static int global_rtautoclear = 120;
493 static int reload_config(int forced_reload);
496 * \brief Call token validation settings.
498 enum calltoken_peer_enum {
499 /*! \brief Default calltoken required unless the ip is in the ignorelist */
500 CALLTOKEN_DEFAULT = 0,
501 /*! \brief Require call token validation. */
503 /*! \brief Require call token validation after a successful registration
504 * using call token validation occurs. */
506 /*! \brief Do not require call token validation. */
511 AST_DECLARE_STRING_FIELDS(
512 AST_STRING_FIELD(name);
513 AST_STRING_FIELD(secret);
514 AST_STRING_FIELD(dbsecret);
515 AST_STRING_FIELD(accountcode);
516 AST_STRING_FIELD(mohinterpret);
517 AST_STRING_FIELD(mohsuggest);
518 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
519 AST_STRING_FIELD(language);
520 AST_STRING_FIELD(cid_num);
521 AST_STRING_FIELD(cid_name);
522 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
530 iax2_format capability;
531 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
532 int curauthreq; /*!< Current number of outstanding AUTHREQs */
533 struct iax2_codec_pref prefs;
534 struct ast_acl_list *acl;
535 struct iax2_context *contexts;
536 struct ast_variable *vars;
537 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
541 AST_DECLARE_STRING_FIELDS(
542 AST_STRING_FIELD(name);
543 AST_STRING_FIELD(username);
544 AST_STRING_FIELD(description); /*!< Description of the peer */
545 AST_STRING_FIELD(secret);
546 AST_STRING_FIELD(dbsecret);
547 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
549 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
550 AST_STRING_FIELD(context); /*!< For transfers only */
551 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
552 AST_STRING_FIELD(mailbox); /*!< Mailbox */
553 AST_STRING_FIELD(mohinterpret);
554 AST_STRING_FIELD(mohsuggest);
555 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
556 /* Suggested caller id if registering */
557 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
558 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
559 AST_STRING_FIELD(zonetag); /*!< Time Zone */
560 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
562 struct iax2_codec_pref prefs;
563 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
564 struct ast_sockaddr addr;
566 int sockfd; /*!< Socket to use for transmission */
567 struct ast_sockaddr mask;
571 /* Dynamic Registration fields */
572 struct ast_sockaddr defaddr; /*!< Default address if there is one */
573 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
574 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
576 int expire; /*!< Schedule entry for expiry */
577 int expiry; /*!< How soon to expire */
578 iax2_format capability; /*!< Capability */
581 int callno; /*!< Call number of POKE request */
582 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
583 int lastms; /*!< How long last response took (in ms), or -1 for no response */
584 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
586 int pokefreqok; /*!< How often to check if the host is up */
587 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
588 int historicms; /*!< How long recent average responses took */
589 int smoothing; /*!< Sample over how many units to determine historic ms */
590 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
592 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
594 struct ast_acl_list *acl;
595 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
597 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
600 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
602 struct iax2_trunk_peer {
605 struct ast_sockaddr addr;
606 struct timeval txtrunktime; /*!< Transmit trunktime */
607 struct timeval rxtrunktime; /*!< Receive trunktime */
608 struct timeval lasttxtime; /*!< Last transmitted trunktime */
609 struct timeval trunkact; /*!< Last trunk activity */
610 unsigned int lastsent; /*!< Last sent time */
611 /* Trunk data and length */
612 unsigned char *trunkdata;
613 unsigned int trunkdatalen;
614 unsigned int trunkdataalloc;
618 AST_LIST_ENTRY(iax2_trunk_peer) list;
621 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
624 REG_STATE_UNREGISTERED = 0,
627 REG_STATE_REGISTERED,
633 enum iax_transfer_state {
638 TRANSFER_PASSTHROUGH,
642 TRANSFER_MPASSTHROUGH,
647 struct iax2_registry {
648 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
650 char secret[80]; /*!< Password or key name in []'s */
651 int expire; /*!< Sched ID of expiration */
652 int refresh; /*!< How often to refresh */
653 enum iax_reg_state regstate;
654 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
655 int callno; /*!< Associated call number if applicable */
656 struct ast_sockaddr us; /*!< Who the server thinks we are */
657 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
658 AST_LIST_ENTRY(iax2_registry) entry;
663 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
665 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
666 #define MIN_RETRY_TIME 100
667 #define MAX_RETRY_TIME 10000
669 #define MAX_JITTER_BUFFER 50
670 #define MIN_JITTER_BUFFER 10
672 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
674 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
676 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
677 #define TS_GAP_FOR_JB_RESYNC 5000
679 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
680 #define MARK_IAX_SUBCLASS_TX 0x8000
682 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
683 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
684 static int iaxdynamicthreadcount = 0;
685 static int iaxdynamicthreadnum = 0;
686 static int iaxactivethreadcount = 0;
700 /* We use the high order bit as the validated flag, and the lower 15 as the
701 * actual call number */
702 typedef uint16_t callno_entry;
704 struct chan_iax2_pvt {
705 /*! Socket to send/receive on for this call */
707 /*! ast_callid bound to dialog */
709 /*! Last received voice format */
710 iax2_format voiceformat;
711 /*! Last received video format */
712 iax2_format videoformat;
713 /*! Last sent voice format */
714 iax2_format svoiceformat;
715 /*! Last sent video format */
716 iax2_format svideoformat;
717 /*! What we are capable of sending */
718 iax2_format capability;
719 /*! Last received timestamp */
721 /*! Last sent timestamp - never send the same timestamp twice in a single call */
722 unsigned int lastsent;
723 /*! Timestamp of the last video frame sent */
724 unsigned int lastvsent;
725 /*! Next outgoing timestamp if everything is good */
726 unsigned int nextpred;
727 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
728 int first_iax_message;
729 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
730 int last_iax_message;
731 /*! True if the last voice we transmitted was not silence/CNG */
732 unsigned int notsilenttx:1;
734 unsigned int pingtime;
735 /*! Max time for initial response */
738 struct ast_sockaddr addr;
739 /*! Actual used codec preferences */
740 struct iax2_codec_pref prefs;
741 /*! Requested codec preferences */
742 struct iax2_codec_pref rprefs;
743 /*! Our call number */
744 unsigned short callno;
745 /*! Our callno_entry entry */
746 callno_entry callno_entry;
748 unsigned short peercallno;
749 /*! Negotiated format, this is only used to remember what format was
750 chosen for an unauthenticated call so that the channel can get
751 created later using the right format */
752 iax2_format chosenformat;
753 /*! Peer selected format */
754 iax2_format peerformat;
755 /*! Peer capability */
756 iax2_format peercapability;
757 /*! timeval that we base our transmission on */
758 struct timeval offset;
759 /*! timeval that we base our delivery on */
760 struct timeval rxcore;
761 /*! The jitterbuffer */
763 /*! active jb read scheduler id */
767 /*! Error, as discovered by the manager */
769 /*! Owner if we have one */
770 struct ast_channel *owner;
771 /*! What's our state? */
772 struct ast_flags state;
773 /*! Expiry (optional) */
775 /*! Next outgoing sequence number */
776 unsigned char oseqno;
777 /*! Next sequence number they have not yet acknowledged */
778 unsigned char rseqno;
779 /*! Next incoming sequence number */
780 unsigned char iseqno;
781 /*! Last incoming sequence number we have acknowledged */
782 unsigned char aseqno;
784 AST_DECLARE_STRING_FIELDS(
786 AST_STRING_FIELD(peer);
787 /*! Default Context */
788 AST_STRING_FIELD(context);
789 /*! Caller ID if available */
790 AST_STRING_FIELD(cid_num);
791 AST_STRING_FIELD(cid_name);
792 /*! Hidden Caller ID (i.e. ANI) if appropriate */
793 AST_STRING_FIELD(ani);
795 AST_STRING_FIELD(dnid);
797 AST_STRING_FIELD(rdnis);
798 /*! Requested Extension */
799 AST_STRING_FIELD(exten);
800 /*! Expected Username */
801 AST_STRING_FIELD(username);
802 /*! Expected Secret */
803 AST_STRING_FIELD(secret);
805 AST_STRING_FIELD(challenge);
806 /*! Public keys permitted keys for incoming authentication */
807 AST_STRING_FIELD(inkeys);
808 /*! Private key for outgoing authentication */
809 AST_STRING_FIELD(outkey);
810 /*! Preferred language */
811 AST_STRING_FIELD(language);
812 /*! Hostname/peername for naming purposes */
813 AST_STRING_FIELD(host);
815 AST_STRING_FIELD(dproot);
816 AST_STRING_FIELD(accountcode);
817 AST_STRING_FIELD(mohinterpret);
818 AST_STRING_FIELD(mohsuggest);
819 /*! received OSP token */
820 AST_STRING_FIELD(osptoken);
821 /*! Default parkinglot */
822 AST_STRING_FIELD(parkinglot);
824 /*! AUTHREJ all AUTHREP frames */
826 /*! permitted authentication methods */
828 /*! permitted encryption methods */
830 /*! Encryption AES-128 Key */
831 ast_aes_encrypt_key ecx;
832 /*! Decryption AES-128 Key corresponding to ecx */
833 ast_aes_decrypt_key mydcx;
834 /*! Decryption AES-128 Key used to decrypt peer frames */
835 ast_aes_decrypt_key dcx;
836 /*! scheduler id associated with iax_key_rotate
837 * for encrypted calls*/
839 /*! 32 bytes of semi-random data */
840 unsigned char semirand[32];
841 /*! Associated registry */
842 struct iax2_registry *reg;
843 /*! Associated peer for poking */
844 struct iax2_peer *peerpoke;
849 /*! Transferring status */
850 enum iax_transfer_state transferring;
851 /*! Transfer identifier */
853 /*! Who we are IAX transferring to */
854 struct ast_sockaddr transfer;
855 /*! What's the new call number for the transfer */
856 unsigned short transfercallno;
857 /*! Transfer encrypt AES-128 Key */
858 ast_aes_encrypt_key tdcx;
860 /*! Status of knowledge of peer ADSI capability */
863 /*! Callno of native bridge peer. (Valid if nonzero) */
864 unsigned short bridgecallno;
866 int pingid; /*!< Transmit PING request */
867 int lagid; /*!< Retransmit lag request */
868 int autoid; /*!< Auto hangup for Dialplan requestor */
869 int authid; /*!< Authentication rejection ID */
870 int authfail; /*!< Reason to report failure */
871 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
877 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
878 /*! variables inherited from the user definition */
879 struct ast_variable *vars;
880 /*! variables transmitted in a NEW packet */
881 struct ast_variable *iaxvars;
882 /*! last received remote rr */
883 struct iax_rr remote_rr;
884 /*! Current base time: (just for stats) */
886 /*! Dropped frame count: (just for stats) */
888 /*! received frame count: (just for stats) */
890 /*! Destroying this call initiated. */
891 int destroy_initiated;
892 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
893 unsigned char calltoken_ie_len;
894 /*! hold all signaling frames from the pbx thread until we have a destination callno */
896 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
897 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
900 struct signaling_queue_entry {
902 AST_LIST_ENTRY(signaling_queue_entry) next;
910 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
911 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
913 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
914 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
915 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
917 struct call_number_pool {
920 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
923 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
925 /*! table of available call numbers */
926 static struct call_number_pool callno_pool;
928 /*! table of available trunk call numbers */
929 static struct call_number_pool callno_pool_trunk;
932 * \brief a list of frames that may need to be retransmitted
934 * \note The contents of this list do not need to be explicitly destroyed
935 * on module unload. This is because all active calls are destroyed, and
936 * all frames in this queue will get destroyed as a part of that process.
938 * \note Contents protected by the iaxsl[] locks
940 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
942 static struct ast_taskprocessor *transmit_processor;
944 static int randomcalltokendata;
946 static time_t max_calltoken_delay = 10;
949 * This module will get much higher performance when doing a lot of
950 * user and peer lookups if the number of buckets is increased from 1.
951 * However, to maintain old behavior for Asterisk 1.4, these are set to
952 * 1 by default. When using multiple buckets, search order through these
953 * containers is considered random, so you will not be able to depend on
954 * the order the entires are specified in iax.conf for matching order. */
956 #define MAX_PEER_BUCKETS 17
958 #define MAX_PEER_BUCKETS 563
960 static struct ao2_container *peers;
962 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
963 static struct ao2_container *users;
965 /*! Table containing peercnt objects for every ip address consuming a callno */
966 static struct ao2_container *peercnts;
968 /*! Table containing custom callno limit rules for a range of ip addresses. */
969 static struct ao2_container *callno_limits;
971 /*! Table containing ip addresses not requiring calltoken validation */
972 static struct ao2_container *calltoken_ignores;
974 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
976 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
978 static uint16_t global_maxcallno;
980 /*! Total num of call numbers allowed to be allocated without calltoken validation */
981 static uint16_t global_maxcallno_nonval;
983 static uint16_t total_nonval_callno_used = 0;
985 /*! peer connection private, keeps track of all the call numbers
986 * consumed by a single ip address */
988 /*! ip address consuming call numbers */
989 struct ast_sockaddr addr;
990 /*! Number of call numbers currently used by this ip address */
992 /*! Max call numbers allowed for this ip address */
994 /*! Specifies whether limit is set by a registration or not, if so normal
995 * limit setting rules do not apply to this address. */
999 /*! used by both callno_limits and calltoken_ignores containers */
1001 /*! ip address range for custom callno limit rule */
1003 /*! callno limit for this ip address range, only used in callno_limits container */
1005 /*! delete me marker for reloads */
1006 unsigned char delme;
1010 /*! Extension exists */
1011 CACHE_FLAG_EXISTS = (1 << 0),
1012 /*! Extension is nonexistent */
1013 CACHE_FLAG_NONEXISTENT = (1 << 1),
1014 /*! Extension can exist */
1015 CACHE_FLAG_CANEXIST = (1 << 2),
1016 /*! Waiting to hear back response */
1017 CACHE_FLAG_PENDING = (1 << 3),
1019 CACHE_FLAG_TIMEOUT = (1 << 4),
1020 /*! Request transmitted */
1021 CACHE_FLAG_TRANSMITTED = (1 << 5),
1023 CACHE_FLAG_UNKNOWN = (1 << 6),
1025 CACHE_FLAG_MATCHMORE = (1 << 7),
1028 struct iax2_dpcache {
1029 char peercontext[AST_MAX_CONTEXT];
1030 char exten[AST_MAX_EXTENSION];
1031 struct timeval orig;
1032 struct timeval expiry;
1034 unsigned short callno;
1036 AST_LIST_ENTRY(iax2_dpcache) cache_list;
1037 AST_LIST_ENTRY(iax2_dpcache) peer_list;
1040 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1042 static void reg_source_db(struct iax2_peer *p);
1043 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1044 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1046 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1047 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1048 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1050 enum iax2_thread_iostate {
1053 IAX_IOSTATE_PROCESSING,
1054 IAX_IOSTATE_SCHEDREADY,
1057 enum iax2_thread_type {
1058 IAX_THREAD_TYPE_POOL,
1059 IAX_THREAD_TYPE_DYNAMIC,
1062 struct iax2_pkt_buf {
1063 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1065 unsigned char buf[1];
1068 struct iax2_thread {
1069 AST_LIST_ENTRY(iax2_thread) list;
1070 enum iax2_thread_type type;
1071 enum iax2_thread_iostate iostate;
1072 #ifdef SCHED_MULTITHREADED
1073 void (*schedfunc)(const void *);
1074 const void *scheddata;
1076 #ifdef DEBUG_SCHED_MULTITHREAD
1082 struct ast_sockaddr ioaddr;
1083 unsigned char readbuf[4096];
1091 ast_mutex_t init_lock;
1092 ast_cond_t init_cond;
1093 /*! if this thread is processing a full frame,
1094 some information about that frame will be stored
1095 here, so we can avoid dispatching any more full
1096 frames for that callno to other threads */
1098 unsigned short callno;
1099 struct ast_sockaddr addr;
1103 /*! Queued up full frames for processing. If more full frames arrive for
1104 * a call which this thread is already processing a full frame for, they
1105 * are queued up here. */
1106 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1111 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1112 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1113 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1115 static void *iax2_process_thread(void *data);
1116 static void iax2_destroy(int callno);
1118 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1120 ast_mutex_lock(lock);
1121 ast_cond_signal(cond);
1122 ast_mutex_unlock(lock);
1126 * \brief an array of iax2 pvt structures
1128 * The container for active chan_iax2_pvt structures is implemented as an
1129 * array for extremely quick direct access to the correct pvt structure
1130 * based on the local call number. The local call number is used as the
1131 * index into the array where the associated pvt structure is stored.
1133 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1135 static ast_callid iax_pvt_callid_get(int callno)
1137 return iaxs[callno]->callid;
1140 static void iax_pvt_callid_set(int callno, ast_callid callid)
1142 iaxs[callno]->callid = callid;
1145 static void iax_pvt_callid_new(int callno)
1147 ast_callid callid = ast_create_callid();
1148 char buffer[AST_CALLID_BUFFER_LENGTH];
1149 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1150 iax_pvt_callid_set(callno, callid);
1154 * \brief Another container of iax2_pvt structures
1156 * Active IAX2 pvt structs are also stored in this container, if they are a part
1157 * of an active call where we know the remote side's call number. The reason
1158 * for this is that incoming media frames do not contain our call number. So,
1159 * instead of having to iterate the entire iaxs array, we use this container to
1160 * look up calls where the remote side is using a given call number.
1162 static struct ao2_container *iax_peercallno_pvts;
1165 * \brief chan_iax2_pvt structure locks
1167 * These locks are used when accessing a pvt structure in the iaxs array.
1168 * The index used here is the same as used in the iaxs array. It is the
1169 * local call number for the associated pvt struct.
1171 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1174 * \brief Another container of iax2_pvt structures
1176 * Active IAX2 pvt structs used during transfering a call are stored here.
1178 static struct ao2_container *iax_transfercallno_pvts;
1180 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1181 but keeps the division between trunked and non-trunked better. */
1182 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1184 /* Debug routines... */
1185 static struct ast_sockaddr debugaddr;
1187 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1190 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1191 (!ast_sockaddr_port(&debugaddr) ||
1192 ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1193 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1196 iax_showframe(f, fhi, rx, addr, datalen);
1199 iax_showframe(f, fhi, rx, addr, datalen);
1205 static void iax_debug_output(const char *data)
1208 ast_verbose("%s", data);
1211 static void iax_error_output(const char *data)
1213 ast_log(LOG_WARNING, "%s", data);
1216 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1221 va_start(args, fmt);
1222 vsnprintf(buf, sizeof(buf), fmt, args);
1225 ast_log(LOG_ERROR, "%s", buf);
1228 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1233 va_start(args, fmt);
1234 vsnprintf(buf, sizeof(buf), fmt, args);
1237 ast_log(LOG_WARNING, "%s", buf);
1240 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1245 va_start(args, fmt);
1246 vsnprintf(buf, sizeof(buf), fmt, args);
1249 ast_verbose("%s", buf);
1252 static int expire_registry(const void *data);
1253 static int iax2_answer(struct ast_channel *c);
1254 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1255 static int iax2_devicestate(const char *data);
1256 static int iax2_digit_begin(struct ast_channel *c, char digit);
1257 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1258 static int iax2_do_register(struct iax2_registry *reg);
1259 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1260 static int iax2_hangup(struct ast_channel *c);
1261 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1262 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1263 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1264 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1265 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1266 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1267 static int iax2_sendtext(struct ast_channel *c, const char *text);
1268 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1269 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1270 static int iax2_transfer(struct ast_channel *c, const char *dest);
1271 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1272 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1274 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1275 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1276 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1277 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1278 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1279 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1280 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
1281 static struct ast_frame *iax2_read(struct ast_channel *c);
1282 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1283 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1284 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1285 static void *iax2_dup_variable_datastore(void *);
1286 static void prune_peers(void);
1287 static void prune_users(void);
1288 static void iax2_free_variable_datastore(void *);
1290 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1291 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1292 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1293 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1294 static void build_rand_pad(unsigned char *buf, ssize_t len);
1295 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1296 static int replace_callno(const void *obj);
1297 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1298 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1299 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1301 static struct ast_channel_tech iax2_tech = {
1303 .description = tdesc,
1304 .properties = AST_CHAN_TP_WANTSJITTER,
1305 .requester = iax2_request,
1306 .devicestate = iax2_devicestate,
1307 .send_digit_begin = iax2_digit_begin,
1308 .send_digit_end = iax2_digit_end,
1309 .send_text = iax2_sendtext,
1310 .send_image = iax2_sendimage,
1311 .send_html = iax2_sendhtml,
1313 .hangup = iax2_hangup,
1314 .answer = iax2_answer,
1316 .write = iax2_write,
1317 .write_video = iax2_write,
1318 .indicate = iax2_indicate,
1319 .setoption = iax2_setoption,
1320 .queryoption = iax2_queryoption,
1321 .transfer = iax2_transfer,
1322 .fixup = iax2_fixup,
1323 .func_channel_read = acf_channel_read,
1328 * \brief Obtain the owner channel lock if the owner exists.
1330 * \param callno IAX2 call id.
1332 * \note Assumes the iaxsl[callno] lock is already obtained.
1335 * IMPORTANT NOTE!!! Any time this function is used, even if
1336 * iaxs[callno] was valid before calling it, it may no longer be
1337 * valid after calling it. This function may unlock and lock
1338 * the mutex associated with this callno, meaning that another
1339 * thread may grab it and destroy the call.
1341 static void iax2_lock_owner(int callno)
1344 if (!iaxs[callno] || !iaxs[callno]->owner) {
1345 /* There is no owner lock to get. */
1348 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1349 /* We got the lock */
1352 /* Avoid deadlock by pausing and trying again */
1353 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1359 * \brief Check if a control subtype is allowed on the wire.
1361 * \param subtype Control frame subtype to check if allowed to/from the wire.
1363 * \retval non-zero if allowed.
1365 static int iax2_is_control_frame_allowed(int subtype)
1367 enum ast_control_frame_type control = subtype;
1371 * Note: If we compare the enumeration type, which does not have any
1372 * negative constants, the compiler may optimize this code away.
1373 * Therefore, we must perform an integer comparison here.
1375 if (subtype == -1) {
1379 /* Default to not allowing control frames to pass. */
1383 * The switch default is not present in order to take advantage
1384 * of the compiler complaining of a missing enum case.
1388 * These control frames make sense to send/receive across the link.
1390 case AST_CONTROL_HANGUP:
1391 case AST_CONTROL_RING:
1392 case AST_CONTROL_RINGING:
1393 case AST_CONTROL_ANSWER:
1394 case AST_CONTROL_BUSY:
1395 case AST_CONTROL_TAKEOFFHOOK:
1396 case AST_CONTROL_OFFHOOK:
1397 case AST_CONTROL_CONGESTION:
1398 case AST_CONTROL_FLASH:
1399 case AST_CONTROL_WINK:
1400 case AST_CONTROL_OPTION:
1401 case AST_CONTROL_RADIO_KEY:
1402 case AST_CONTROL_RADIO_UNKEY:
1403 case AST_CONTROL_PROGRESS:
1404 case AST_CONTROL_PROCEEDING:
1405 case AST_CONTROL_HOLD:
1406 case AST_CONTROL_UNHOLD:
1407 case AST_CONTROL_VIDUPDATE:
1408 case AST_CONTROL_CONNECTED_LINE:
1409 case AST_CONTROL_REDIRECTING:
1410 case AST_CONTROL_T38_PARAMETERS:
1411 case AST_CONTROL_AOC:
1412 case AST_CONTROL_INCOMPLETE:
1413 case AST_CONTROL_MCID:
1418 * These control frames do not make sense to send/receive across the link.
1420 case _XXX_AST_CONTROL_T38:
1421 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1422 case AST_CONTROL_SRCUPDATE:
1423 /* Across an IAX link the source is still the same. */
1424 case AST_CONTROL_TRANSFER:
1425 /* A success/fail status report from calling ast_transfer() on this machine. */
1426 case AST_CONTROL_CC:
1427 /* The payload contains pointers that are valid for the sending machine only. */
1428 case AST_CONTROL_SRCCHANGE:
1429 /* Across an IAX link the source is still the same. */
1430 case AST_CONTROL_READ_ACTION:
1431 /* The action can only be done by the sending machine. */
1432 case AST_CONTROL_END_OF_Q:
1433 /* This frame would cause the call to unexpectedly hangup. */
1434 case AST_CONTROL_UPDATE_RTP_PEER:
1435 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1436 case AST_CONTROL_PVT_CAUSE_CODE:
1437 /* Intended only for the sending machine's local channel structure. */
1438 case AST_CONTROL_MASQUERADE_NOTIFY:
1439 /* Intended only for masquerades when calling ast_indicate_data(). */
1440 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1441 /* Intended only for internal stream topology manipulation. */
1442 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
1443 /* Intended only for internal stream topology change notification. */
1444 case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
1445 case AST_CONTROL_STREAM_STOP:
1446 case AST_CONTROL_STREAM_SUSPEND:
1447 case AST_CONTROL_STREAM_RESTART:
1448 case AST_CONTROL_STREAM_REVERSE:
1449 case AST_CONTROL_STREAM_FORWARD:
1450 /* None of these playback stream control frames should go across the link. */
1451 case AST_CONTROL_RECORD_CANCEL:
1452 case AST_CONTROL_RECORD_STOP:
1453 case AST_CONTROL_RECORD_SUSPEND:
1454 case AST_CONTROL_RECORD_MUTE:
1455 /* None of these media recording control frames should go across the link. */
1461 static void network_change_stasis_subscribe(void)
1463 if (!network_change_sub) {
1464 network_change_sub = stasis_subscribe(ast_system_topic(),
1465 network_change_stasis_cb, NULL);
1466 stasis_subscription_accept_message_type(network_change_sub, ast_network_change_type());
1467 stasis_subscription_set_filter(network_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1471 static void network_change_stasis_unsubscribe(void)
1473 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1476 static void acl_change_stasis_subscribe(void)
1478 if (!acl_change_sub) {
1479 acl_change_sub = stasis_subscribe(ast_security_topic(),
1480 acl_change_stasis_cb, NULL);
1481 stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
1482 stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1486 static void acl_change_stasis_unsubscribe(void)
1488 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1491 static int network_change_sched_cb(const void *data)
1493 struct iax2_registry *reg;
1494 network_change_sched_id = -1;
1495 AST_LIST_LOCK(®istrations);
1496 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1497 iax2_do_register(reg);
1499 AST_LIST_UNLOCK(®istrations);
1504 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1505 struct stasis_message *message)
1507 /* This callback is only concerned with network change messages from the system topic. */
1508 if (stasis_message_type(message) != ast_network_change_type()) {
1512 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1513 if (network_change_sched_id == -1) {
1514 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1518 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1519 struct stasis_message *message)
1521 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1525 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1529 static const struct ast_datastore_info iax2_variable_datastore_info = {
1530 .type = "IAX2_VARIABLE",
1531 .duplicate = iax2_dup_variable_datastore,
1532 .destroy = iax2_free_variable_datastore,
1535 static void *iax2_dup_variable_datastore(void *old)
1537 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1538 struct ast_var_t *oldvar, *newvar;
1540 newlist = ast_calloc(sizeof(*newlist), 1);
1542 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1546 AST_LIST_HEAD_INIT(newlist);
1547 AST_LIST_LOCK(oldlist);
1548 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1549 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1551 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1553 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1555 AST_LIST_UNLOCK(oldlist);
1559 static void iax2_free_variable_datastore(void *old)
1561 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1562 struct ast_var_t *oldvar;
1564 AST_LIST_LOCK(oldlist);
1565 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1568 AST_LIST_UNLOCK(oldlist);
1569 AST_LIST_HEAD_DESTROY(oldlist);
1574 /* WARNING: insert_idle_thread should only ever be called within the
1575 * context of an iax2_process_thread() thread.
1577 static void insert_idle_thread(struct iax2_thread *thread)
1579 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1580 AST_LIST_LOCK(&dynamic_list);
1581 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1582 AST_LIST_UNLOCK(&dynamic_list);
1584 AST_LIST_LOCK(&idle_list);
1585 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1586 AST_LIST_UNLOCK(&idle_list);
1592 static struct iax2_thread *find_idle_thread(void)
1594 struct iax2_thread *thread = NULL;
1596 /* Pop the head of the idle list off */
1597 AST_LIST_LOCK(&idle_list);
1598 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1599 AST_LIST_UNLOCK(&idle_list);
1601 /* If we popped a thread off the idle list, just return it */
1603 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1607 /* Pop the head of the dynamic list off */
1608 AST_LIST_LOCK(&dynamic_list);
1609 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1610 AST_LIST_UNLOCK(&dynamic_list);
1612 /* If we popped a thread off the dynamic list, just return it */
1614 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1618 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1619 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1622 /* Set default values */
1623 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1624 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1625 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1627 /* Initialize lock and condition */
1628 ast_mutex_init(&thread->lock);
1629 ast_cond_init(&thread->cond, NULL);
1630 ast_mutex_init(&thread->init_lock);
1631 ast_cond_init(&thread->init_cond, NULL);
1632 ast_mutex_lock(&thread->init_lock);
1634 /* Create thread and send it on it's way */
1635 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1636 ast_cond_destroy(&thread->cond);
1637 ast_mutex_destroy(&thread->lock);
1638 ast_mutex_unlock(&thread->init_lock);
1639 ast_cond_destroy(&thread->init_cond);
1640 ast_mutex_destroy(&thread->init_lock);
1645 /* this thread is not processing a full frame (since it is idle),
1646 so ensure that the field for the full frame call number is empty */
1647 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1649 /* Wait for the thread to be ready before returning it to the caller */
1650 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1652 /* Done with init_lock */
1653 ast_mutex_unlock(&thread->init_lock);
1658 #ifdef SCHED_MULTITHREADED
1659 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1661 struct iax2_thread *thread;
1662 static time_t lasterror;
1665 thread = find_idle_thread();
1666 if (thread != NULL) {
1667 thread->schedfunc = func;
1668 thread->scheddata = data;
1669 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1670 #ifdef DEBUG_SCHED_MULTITHREAD
1671 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1673 signal_condition(&thread->lock, &thread->cond);
1677 if (t != lasterror) {
1679 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1684 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1687 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1688 ast_sched_cb callback, const void *data)
1690 return ast_sched_replace(id, con, when, callback, data);
1693 static int iax2_sched_add(struct ast_sched_context *con, int when,
1694 ast_sched_cb callback, const void *data)
1696 return ast_sched_add(con, when, callback, data);
1700 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1701 * \param callno Call number to lock.
1702 * \retval 0 If call disappeared or has ongoing hangup procedure.
1703 * \retval 1 If call found and mutex is locked.
1705 static int iax2_lock_callno_unless_destroyed(int callno)
1707 ast_mutex_lock(&iaxsl[callno]);
1709 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1710 * or destroy initiated (in middle of hang up procedure. */
1711 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1712 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1713 ast_mutex_unlock(&iaxsl[callno]);
1717 /* Lock acquired, and callno is alive and kicking. */
1721 static int send_ping(const void *data);
1723 static void __send_ping(const void *data)
1725 int callno = PTR_TO_CALLNO(data);
1727 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1728 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1732 /* Mark pingid as invalid scheduler id. */
1733 iaxs[callno]->pingid = -1;
1735 /* callno is now locked. */
1736 if (iaxs[callno]->peercallno) {
1737 /* Send PING packet. */
1738 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1740 /* Schedule sending next ping. */
1741 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1744 ast_mutex_unlock(&iaxsl[callno]);
1747 static int send_ping(const void *data)
1749 #ifdef SCHED_MULTITHREADED
1750 if (schedule_action(__send_ping, data))
1757 static void encmethods_to_str(int e, struct ast_str **buf)
1759 ast_str_set(buf, 0, "(");
1760 if (e & IAX_ENCRYPT_AES128) {
1761 ast_str_append(buf, 0, "aes128");
1763 if (e & IAX_ENCRYPT_KEYROTATE) {
1764 ast_str_append(buf, 0, ",keyrotate");
1766 if (ast_str_strlen(*buf) > 1) {
1767 ast_str_append(buf, 0, ")");
1769 ast_str_set(buf, 0, "No");
1773 static int get_encrypt_methods(const char *s)
1776 if (!strcasecmp(s, "aes128"))
1777 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1778 else if (ast_true(s))
1779 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1785 static int send_lagrq(const void *data);
1787 static void __send_lagrq(const void *data)
1789 int callno = PTR_TO_CALLNO(data);
1791 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1792 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1796 /* Mark lagid as invalid scheduler id. */
1797 iaxs[callno]->lagid = -1;
1799 /* callno is now locked. */
1800 if (iaxs[callno]->peercallno) {
1801 /* Send LAGRQ packet. */
1802 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1804 /* Schedule sending next lagrq. */
1805 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1808 ast_mutex_unlock(&iaxsl[callno]);
1811 static int send_lagrq(const void *data)
1813 #ifdef SCHED_MULTITHREADED
1814 if (schedule_action(__send_lagrq, data))
1820 static unsigned char compress_subclass(iax2_format subclass)
1824 /* If it's 64 or smaller, just return it */
1825 if (subclass < IAX_FLAG_SC_LOG)
1827 /* Otherwise find its power */
1828 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1829 if (subclass & (1LL << x)) {
1831 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1837 return power | IAX_FLAG_SC_LOG;
1840 static iax2_format uncompress_subclass(unsigned char csub)
1842 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1843 if (csub & IAX_FLAG_SC_LOG) {
1844 /* special case for 'compressed' -1 */
1848 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1854 static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1857 struct ast_format *found_format = NULL;
1859 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1860 struct ast_format *pref_format;
1861 uint64_t pref_bitfield;
1863 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1864 if (!pref_bitfield) {
1868 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1870 /* The bitfield is not associated with any format. */
1873 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1879 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1880 return found_format;
1883 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1884 ao2_cleanup(found_format);
1888 static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
1890 struct ast_format_cap *cap;
1891 struct ast_format *tmpfmt;
1892 iax2_format format = 0;
1894 if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1895 iax2_format_compatibility_bitfield2cap(formats, cap);
1896 tmpfmt = codec_choose_from_prefs(pref, cap);
1902 format = ast_format_compatibility_format2bitfield(tmpfmt);
1903 ao2_ref(tmpfmt, -1);
1910 const char *iax2_getformatname(iax2_format format)
1912 struct ast_format *tmpfmt;
1914 tmpfmt = ast_format_compatibility_bitfield2format(format);
1919 return ast_format_get_name(tmpfmt);
1922 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1924 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1929 iax2_format_compatibility_bitfield2cap(format, cap);
1930 ast_format_cap_get_names(cap, codec_buf);
1933 return ast_str_buffer(*codec_buf);
1936 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1939 struct ast_format_cap *cap;
1941 /* We want to add the formats to the cap in the preferred order */
1942 cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1943 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1948 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1950 /* Adjust formats bitfield and pref list to match. */
1951 *formats = iax2_format_compatibility_cap2bitfield(cap);
1952 iax2_codec_pref_remove_missing(pref, *formats);
1954 for (i = 0; i < ast_format_cap_count(cap); i++) {
1955 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1957 iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
1967 * \note The only member of the peer passed here guaranteed to be set is the name field
1969 static int peer_hash_cb(const void *obj, const int flags)
1971 const struct iax2_peer *peer = obj;
1972 const char *name = obj;
1974 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1978 * \note The only member of the peer passed here guaranteed to be set is the name field
1980 static int peer_cmp_cb(void *obj, void *arg, int flags)
1982 struct iax2_peer *peer = obj, *peer2 = arg;
1983 const char *name = arg;
1985 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1986 CMP_MATCH | CMP_STOP : 0;
1990 * \note The only member of the user passed here guaranteed to be set is the name field
1992 static int user_hash_cb(const void *obj, const int flags)
1994 const struct iax2_user *user = obj;
1995 const char *name = obj;
1997 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2001 * \note The only member of the user passed here guaranteed to be set is the name field
2003 static int user_cmp_cb(void *obj, void *arg, int flags)
2005 struct iax2_user *user = obj, *user2 = arg;
2006 const char *name = arg;
2008 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2009 CMP_MATCH | CMP_STOP : 0;
2013 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2014 * so do not call it with a pvt lock held.
2016 static struct iax2_peer *find_peer(const char *name, int realtime)
2018 struct iax2_peer *peer = NULL;
2020 peer = ao2_find(peers, name, OBJ_KEY);
2022 /* Now go for realtime if applicable */
2023 if (!peer && realtime) {
2024 peer = realtime_peer(name, NULL);
2029 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2035 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2041 static struct iax2_user *find_user(const char *name)
2043 return ao2_find(users, name, OBJ_KEY);
2046 static inline struct iax2_user *user_unref(struct iax2_user *user)
2052 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2054 struct iax2_peer *peer = NULL;
2056 struct ao2_iterator i;
2058 i = ao2_iterator_init(peers, 0);
2059 while ((peer = ao2_iterator_next(&i))) {
2061 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2062 ast_copy_string(host, peer->name, len);
2069 ao2_iterator_destroy(&i);
2072 peer = realtime_peer(NULL, &addr);
2074 ast_copy_string(host, peer->name, len);
2083 /* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2084 static int iax2_delete_from_sched(const void* data)
2086 int sched_id = (int)(long)data;
2088 AST_SCHED_DEL(sched, sched_id);
2093 /*!\note Assumes the lock on the pvt is already held, when
2094 * iax2_destroy_helper() is called. */
2095 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2097 /* Decrement AUTHREQ count if needed */
2098 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2099 struct iax2_user *user;
2101 user = ao2_find(users, pvt->username, OBJ_KEY);
2103 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2107 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2111 /* Mark call destroy initiated flag. */
2112 pvt->destroy_initiated = 1;
2115 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2116 * Already running tasks will be terminated because of destroy_initiated.
2118 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2119 * it leads to a deadlock between the scheduler thread callback locking
2120 * the callno mutex and this thread which holds the callno mutex one or
2121 * more times. It is better to have another thread delete the scheduled
2122 * callbacks which doesn't lock the callno mutex.
2124 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2125 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2130 AST_SCHED_DEL(sched, pvt->autoid);
2131 AST_SCHED_DEL(sched, pvt->authid);
2132 AST_SCHED_DEL(sched, pvt->initid);
2133 AST_SCHED_DEL(sched, pvt->jbid);
2134 AST_SCHED_DEL(sched, pvt->keyrotateid);
2137 static void iax2_frame_free(struct iax_frame *fr)
2139 AST_SCHED_DEL(sched, fr->retrans);
2143 static int scheduled_destroy(const void *vid)
2145 unsigned short callno = PTR_TO_CALLNO(vid);
2146 ast_mutex_lock(&iaxsl[callno]);
2148 ast_debug(1, "Really destroying %d now...\n", callno);
2149 iax2_destroy(callno);
2151 ast_mutex_unlock(&iaxsl[callno]);
2155 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2158 ast_free(s->f.data.ptr);
2163 /*! \brief This function must be called once we are sure the other side has
2164 * given us a call number. All signaling is held here until that point. */
2165 static void send_signaling(struct chan_iax2_pvt *pvt)
2167 struct signaling_queue_entry *s = NULL;
2169 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2170 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2171 free_signaling_queue_entry(s);
2173 pvt->hold_signaling = 0;
2176 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2177 * we have received a destination call number. */
2178 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2180 struct signaling_queue_entry *qe;
2182 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2183 return 1; /* do not queue this frame */
2184 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2185 return -1; /* out of memory */
2188 /* copy ast_frame into our queue entry */
2190 if (qe->f.datalen) {
2191 /* if there is data in this frame copy it over as well */
2192 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2193 free_signaling_queue_entry(qe);
2196 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2198 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2203 static void pvt_destructor(void *obj)
2205 struct chan_iax2_pvt *pvt = obj;
2206 struct iax_frame *cur = NULL;
2207 struct signaling_queue_entry *s = NULL;
2209 ast_mutex_lock(&iaxsl[pvt->callno]);
2211 iax2_destroy_helper(pvt);
2213 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2214 pvt->callno_entry = 0;
2217 ast_set_flag64(pvt, IAX_ALREADYGONE);
2219 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2220 /* Cancel any pending transmissions */
2224 ast_mutex_unlock(&iaxsl[pvt->callno]);
2226 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2227 free_signaling_queue_entry(s);
2231 pvt->reg->callno = 0;
2237 ast_variables_destroy(pvt->vars);
2241 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2242 iax2_frame_free(frame.data);
2245 jb_destroy(pvt->jb);
2246 ast_string_field_free_memory(pvt);
2250 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2252 struct chan_iax2_pvt *tmp;
2255 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2264 tmp->keyrotateid = -1;
2267 if (ast_string_field_init(tmp, 32)) {
2273 tmp->prefs = prefs_global;
2275 ast_string_field_set(tmp,exten, "s");
2276 ast_string_field_set(tmp,host, host);
2279 jbconf.max_jitterbuf = maxjitterbuffer;
2280 jbconf.resync_threshold = resyncthreshold;
2281 jbconf.max_contig_interp = maxjitterinterps;
2282 jbconf.target_extra = jittertargetextra;
2283 jb_setconf(tmp->jb,&jbconf);
2285 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2287 tmp->hold_signaling = 1;
2288 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2293 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2295 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2297 size_t afdatalen = new->afdatalen;
2298 memcpy(new, fr, sizeof(*new));
2299 iax_frame_wrap(new, &fr->af);
2300 new->afdatalen = afdatalen;
2303 new->direction = DIRECTION_INGRESS;
2308 /* keep these defined in this order. They are used in find_callno to
2309 * determine whether or not a new call number should be allowed. */
2311 /* do not allow a new call number, only search ones in use for match */
2313 /* search for match first, then allow a new one to be allocated */
2315 /* do not search for match, force a new call number */
2317 /* do not search for match, force a new call number. Signifies call number
2318 * has been calltoken validated */
2319 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2322 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2324 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2325 /* This is the main host */
2326 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2327 (check_dcallno ? dcallno == cur->callno : 1) ) {
2328 /* That's us. Be sure we keep track of the peer call number */
2332 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2333 /* We're transferring */
2334 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2340 static int make_trunk(unsigned short callno, int locked)
2345 if (iaxs[callno]->oseqno) {
2346 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2349 if (callno >= TRUNK_CALL_START) {
2350 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2354 if (get_unused_callno(
2356 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2358 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2362 x = CALLNO_ENTRY_GET_CALLNO(entry);
2363 ast_mutex_lock(&iaxsl[x]);
2366 * \note We delete these before switching the slot, because if
2367 * they fire in the meantime, they will generate a warning.
2369 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2370 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2371 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2372 iaxs[x] = iaxs[callno];
2373 iaxs[x]->callno = x;
2375 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2376 * before assigning the new one */
2377 if (iaxs[x]->callno_entry) {
2380 MIN_REUSE_TIME * 1000,
2382 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2385 iaxs[x]->callno_entry = entry;
2387 iaxs[callno] = NULL;
2388 /* Update the two timers that should have been started */
2389 iaxs[x]->pingid = iax2_sched_add(sched,
2390 ping_time * 1000, send_ping, (void *)(long)x);
2391 iaxs[x]->lagid = iax2_sched_add(sched,
2392 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2395 ast_mutex_unlock(&iaxsl[callno]);
2398 ast_mutex_unlock(&iaxsl[x]);
2400 /* We moved this call from a non-trunked to a trunked call */
2401 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2406 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2408 if (!pvt->transfercallno) {
2409 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2413 ao2_link(iax_transfercallno_pvts, pvt);
2416 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2418 if (!pvt->transfercallno) {
2419 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2423 ao2_unlink(iax_transfercallno_pvts, pvt);
2425 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2427 if (!pvt->peercallno) {
2428 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2432 ao2_link(iax_peercallno_pvts, pvt);
2435 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2437 if (!pvt->peercallno) {
2438 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2442 ao2_unlink(iax_peercallno_pvts, pvt);
2445 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2447 struct addr_range *lim = obj;
2452 static int addr_range_hash_cb(const void *obj, const int flags)
2454 const struct addr_range *lim = obj;
2455 return abs(ast_sockaddr_hash(&lim->ha.addr));
2458 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2460 struct addr_range *lim1 = obj, *lim2 = arg;
2461 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2462 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2463 CMP_MATCH | CMP_STOP : 0;
2466 static int peercnt_hash_cb(const void *obj, const int flags)
2468 const struct peercnt *peercnt = obj;
2470 if (ast_sockaddr_isnull(&peercnt->addr)) {
2473 return ast_sockaddr_hash(&peercnt->addr);
2476 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2478 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2479 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2482 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2484 struct addr_range *addr_range = obj;
2485 struct ast_sockaddr *addr = arg;
2486 struct ast_sockaddr tmp_addr;
2488 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2490 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2491 return CMP_MATCH | CMP_STOP;
2499 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2501 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2503 struct addr_range *addr_range;
2504 struct iax2_peer *peer = NULL;
2505 struct iax2_user *user = NULL;
2506 /* if no username is given, check for guest accounts */
2507 const char *find = S_OR(name, "guest");
2508 int res = 1; /* required by default */
2510 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2511 /* There are only two cases in which calltoken validation is not required.
2512 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2513 * the peer definition has not set the requirecalltoken option.
2514 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2517 /* ----- Case 1 ----- */
2518 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2519 ao2_ref(addr_range, -1);
2523 /* ----- Case 2 ----- */
2524 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2525 calltoken_required = user->calltoken_required;
2526 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2527 calltoken_required = user->calltoken_required;
2528 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2529 calltoken_required = peer->calltoken_required;
2530 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2531 calltoken_required = peer->calltoken_required;
2541 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2542 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2543 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2553 * \brief set peercnt callno limit.
2556 * First looks in custom definitions. If not found, global limit
2557 * is used. Entries marked as reg already have
2558 * a custom limit set by a registration and are not modified.
2560 static void set_peercnt_limit(struct peercnt *peercnt)
2562 uint16_t limit = global_maxcallno;
2563 struct addr_range *addr_range;
2564 struct ast_sockaddr addr;
2566 ast_sockaddr_copy(&addr, &peercnt->addr);
2568 if (peercnt->reg && peercnt->limit) {
2569 return; /* this peercnt has a custom limit set by a registration */
2572 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2573 limit = addr_range->limit;
2574 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2575 ao2_ref(addr_range, -1);
2578 peercnt->limit = limit;
2583 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2585 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2587 struct peercnt *peercnt = obj;
2589 set_peercnt_limit(peercnt);
2590 ast_debug(1, "Reset limits for peercnts table\n");
2597 * \brief returns match if delme is set.
2599 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2601 struct addr_range *addr_range = obj;
2603 return addr_range->delme ? CMP_MATCH : 0;
2608 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2610 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2612 /* this function turns off and on custom callno limits set by peer registration */
2613 struct peercnt *peercnt;
2616 ast_sockaddr_copy(&tmp.addr, sockaddr);
2618 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2621 peercnt->limit = limit;
2623 set_peercnt_limit(peercnt);
2625 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2626 ao2_ref(peercnt, -1); /* decrement ref from find */
2632 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2634 * \details First searches for the address in the peercnts table. If found
2635 * the current count is incremented. If not found a new peercnt is allocated
2636 * and linked into the peercnts table with a call number count of 1.
2638 static int peercnt_add(struct ast_sockaddr *addr)
2640 struct peercnt *peercnt;
2644 ast_sockaddr_copy(&tmp.addr, addr);
2646 /* Reasoning for peercnts container lock: Two identical ip addresses
2647 * could be added by different threads at the "same time". Without the container
2648 * lock, both threads could alloc space for the same object and attempt
2649 * to link to table. With the lock, one would create the object and link
2650 * to table while the other would find the already created peercnt object
2651 * rather than creating a new one. */
2653 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2655 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2657 /* create and set defaults */
2658 ast_sockaddr_copy(&peercnt->addr, addr);
2659 set_peercnt_limit(peercnt);
2660 /* guarantees it does not go away after unlocking table
2661 * ao2_find automatically adds this */
2662 ao2_link(peercnts, peercnt);
2664 ao2_unlock(peercnts);
2668 /* check to see if the address has hit its callno limit. If not increment cur. */
2669 if (peercnt->limit > peercnt->cur) {
2671 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2672 } else { /* max num call numbers for this peer has been reached! */
2673 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2677 /* clean up locks and ref count */
2678 ao2_unlock(peercnt);
2679 ao2_unlock(peercnts);
2680 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2687 * \brief decrements a peercnts table entry
2689 static void peercnt_remove(struct peercnt *peercnt)
2691 struct ast_sockaddr addr;
2693 ast_sockaddr_copy(&addr, &peercnt->addr);
2696 * Container locked here since peercnt may be unlinked from
2697 * list. If left unlocked, peercnt_add could try and grab this
2698 * entry from the table and modify it at the "same time" this
2699 * thread attempts to unlink it.
2703 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2704 /* if this was the last connection from the peer remove it from table */
2705 if (peercnt->cur == 0) {
2706 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2708 ao2_unlock(peercnts);
2713 * \brief called by scheduler to decrement object
2715 static int peercnt_remove_cb(const void *obj)
2717 struct peercnt *peercnt = (struct peercnt *) obj;
2719 peercnt_remove(peercnt);
2720 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2727 * \brief decrements peercnts connection count, finds by addr
2729 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2731 struct peercnt *peercnt;
2734 ast_sockaddr_copy(&tmp.addr, addr);
2736 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2737 peercnt_remove(peercnt);
2738 ao2_ref(peercnt, -1); /* decrement ref from find */
2745 * \brief Create callno_limit entry based on configuration
2747 static void build_callno_limits(struct ast_variable *v)
2749 struct addr_range *addr_range = NULL;
2750 struct addr_range tmp;
2756 for (; v; v = v->next) {
2760 ha = ast_append_ha("permit", v->name, NULL, &error);
2762 /* check for valid config information */
2764 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2766 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2767 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2772 ast_copy_ha(ha, &tmp.ha);
2773 /* find or create the addr_range */
2774 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2775 ao2_lock(addr_range);
2777 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2779 return; /* out of memory */
2782 /* copy over config data into addr_range object */
2783 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2784 ast_free_ha(ha); /* cleanup the tmp ha */
2785 addr_range->limit = limit;
2786 addr_range->delme = 0;
2790 ao2_unlock(addr_range);
2792 ao2_link(callno_limits, addr_range);
2794 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2800 * \brief Create calltoken_ignores entry based on configuration
2802 static int add_calltoken_ignore(const char *addr)
2804 struct addr_range tmp;
2805 struct addr_range *addr_range = NULL;
2806 struct ast_ha *ha = NULL;
2809 if (ast_strlen_zero(addr)) {
2810 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2814 ha = ast_append_ha("permit", addr, NULL, &error);
2816 /* check for valid config information */
2818 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2822 ast_copy_ha(ha, &tmp.ha);
2823 /* find or create the addr_range */
2824 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2825 ao2_lock(addr_range);
2826 addr_range->delme = 0;
2827 ao2_unlock(addr_range);
2828 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2829 /* copy over config data into addr_range object */
2830 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2831 ao2_link(calltoken_ignores, addr_range);
2838 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2843 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2845 struct ao2_iterator i;
2846 struct peercnt *peercnt;
2847 struct ast_sockaddr addr;
2852 e->command = "iax2 show callnumber usage";
2854 "Usage: iax2 show callnumber usage [IP address]\n"
2855 " Shows current IP addresses which are consuming iax2 call numbers\n";
2860 if (a->argc < 4 || a->argc > 5)
2861 return CLI_SHOWUSAGE;
2864 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2867 i = ao2_iterator_init(peercnts, 0);
2868 while ((peercnt = ao2_iterator_next(&i))) {
2869 ast_sockaddr_copy(&addr, &peercnt->addr);
2872 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2873 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2874 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2875 ao2_ref(peercnt, -1);
2880 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2882 ao2_ref(peercnt, -1);
2884 ao2_iterator_destroy(&i);
2887 size_t pool_avail = callno_pool.available;
2888 size_t trunk_pool_avail = callno_pool_trunk.available;
2890 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2891 "Non-CallToken Validated Callno Used: %d\n",
2892 global_maxcallno_nonval,
2893 total_nonval_callno_used);
2895 ast_cli(a->fd, "Total Available Callno: %zu\n"
2896 "Regular Callno Available: %zu\n"
2897 "Trunk Callno Available: %zu\n",
2898 pool_avail + trunk_pool_avail,
2901 } else if (a->argc == 5 && !found) {
2902 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2912 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2914 struct call_number_pool *pool = NULL;
2919 case CALLNO_TYPE_NORMAL:
2920 pool = &callno_pool;
2922 case CALLNO_TYPE_TRUNK:
2923 pool = &callno_pool_trunk;
2930 /* If we fail, make sure this has a defined value */
2933 /* We lock here primarily to ensure thread safety of the
2934 * total_nonval_callno_used check and increment */
2935 ast_mutex_lock(&callno_pool_lock);
2937 /* Bail out if we don't have any available call numbers */
2938 if (!pool->available) {
2939 ast_log(LOG_WARNING, "Out of call numbers\n");
2940 ast_mutex_unlock(&callno_pool_lock);
2944 /* Only a certain number of non-validated call numbers should be allocated.
2945 * If there ever is an attack, this separates the calltoken validating users
2946 * from the non-calltoken validating users. */
2947 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2948 ast_log(LOG_WARNING,
2949 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2950 total_nonval_callno_used,
2951 global_maxcallno_nonval);
2952 ast_mutex_unlock(&callno_pool_lock);
2956 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2957 * available call numbers. The array of call numbers begins as an ordered
2958 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2959 * - let's call that x. When a call number is needed we pick a random index
2960 * into the array between 0 and x and use that as our call number. In a
2961 * typical FYD shuffle, we would swap the value that we are extracting with
2962 * the number at x, but in our case we swap and don't touch the value at x
2963 * because it is effectively invisible. We rely on the rest of the IAX2 core
2964 * to return the number to us at some point. Finally, we decrement x by 1
2965 * which establishes our new unused range.
2967 * When numbers are returned to the pool, we put them just past x and bump x
2968 * by 1 so that this number is now available for re-use. */
2970 choice = ast_random() % pool->available;
2972 *entry = pool->numbers[choice];
2973 swap = pool->numbers[pool->available - 1];
2975 pool->numbers[choice] = swap;
2979 CALLNO_ENTRY_SET_VALIDATED(*entry);
2981 total_nonval_callno_used++;
2984 ast_mutex_unlock(&callno_pool_lock);
2989 static int replace_callno(const void *obj)
2991 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2992 struct call_number_pool *pool;
2994 /* We lock here primarily to ensure thread safety of the
2995 * total_nonval_callno_used check and decrement */
2996 ast_mutex_lock(&callno_pool_lock);
2998 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2999 if (total_nonval_callno_used) {
3000 total_nonval_callno_used--;
3003 "Attempted to decrement total non calltoken validated "
3004 "callnumbers below zero. Callno is: %d\n",
3005 CALLNO_ENTRY_GET_CALLNO(entry));
3009 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
3010 pool = &callno_pool;
3012 pool = &callno_pool_trunk;
3015 ast_assert(pool->capacity > pool->available);
3017 /* This clears the validated flag */
3018 entry = CALLNO_ENTRY_GET_CALLNO(entry);
3020 pool->numbers[pool->available] = entry;
3023 ast_mutex_unlock(&callno_pool_lock);
3028 static int create_callno_pools(void)
3032 callno_pool.available = callno_pool_trunk.available = 0;
3034 /* We start at 2. 0 and 1 are reserved. */
3035 for (i = 2; i < TRUNK_CALL_START; i++) {
3036 callno_pool.numbers[callno_pool.available] = i;
3037 callno_pool.available++;
3040 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3041 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
3042 callno_pool_trunk.available++;
3045 callno_pool.capacity = callno_pool.available;
3046 callno_pool_trunk.capacity = callno_pool_trunk.available;
3048 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
3055 * \brief Schedules delayed removal of iax2_pvt call number data
3057 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3058 * available again, and the address from the previous connection must be decremented
3059 * from the peercnts table. This function schedules these operations to take place.
3061 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3064 struct peercnt *peercnt;
3067 ast_sockaddr_copy(&tmp.addr, addr);
3069 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3070 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3071 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3072 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3074 ao2_ref(peercnt, -1);
3080 MIN_REUSE_TIME * 1000,
3082 CALLNO_ENTRY_TO_PTR(entry));
3087 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3089 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3092 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3094 if (frametype != AST_FRAME_IAX) {
3098 case IAX_COMMAND_NEW:
3099 case IAX_COMMAND_REGREQ:
3100 case IAX_COMMAND_FWDOWNL:
3101 case IAX_COMMAND_REGREL:
3103 case IAX_COMMAND_POKE:
3113 * \note Calling this function while holding another pvt lock can cause a deadlock.
3115 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3119 /* this call is calltoken validated as long as it is either NEW_FORCE
3120 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3121 int validated = (new > NEW_ALLOW) ? 1 : 0;
3124 if (new <= NEW_ALLOW) {
3126 struct chan_iax2_pvt *pvt;
3127 struct chan_iax2_pvt tmp_pvt = {
3129 .peercallno = callno,
3130 .transfercallno = callno,
3132 .frames_received = check_dcallno,
3135 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3136 /* this works for finding normal call numbers not involving transfering */
3137 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3138 if (return_locked) {
3139 ast_mutex_lock(&iaxsl[pvt->callno]);
3146 /* this searches for transfer call numbers that might not get caught otherwise */
3147 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3148 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3149 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3150 if (return_locked) {
3151 ast_mutex_lock(&iaxsl[pvt->callno]);
3159 /* This will occur on the first response to a message that we initiated,
3160 * such as a PING. */
3162 ast_mutex_lock(&iaxsl[dcallno]);
3164 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3165 iaxs[dcallno]->peercallno = callno;
3167 store_by_peercallno(iaxs[dcallno]);
3168 if (!res || !return_locked) {
3169 ast_mutex_unlock(&iaxsl[dcallno]);
3174 ast_mutex_unlock(&iaxsl[dcallno]);
3177 if (!res && (new >= NEW_ALLOW)) {
3180 /* It may seem odd that we look through the peer list for a name for
3181 * this *incoming* call. Well, it is weird. However, users don't
3182 * have an IP address/port number that we can match against. So,
3183 * this is just checking for a peer that has that IP/port and
3184 * assuming that we have a user of the same name. This isn't always
3185 * correct, but it will be changed if needed after authentication. */
3186 if (!iax2_getpeername(*addr, host, sizeof(host)))
3187 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3189 if (peercnt_add(addr)) {
3190 /* This address has hit its callnumber limit. When the limit
3191 * is reached, the connection is not added to the peercnts table.*/
3195 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3196 /* since we ran out of space, remove the peercnt
3197 * entry we added earlier */
3198 peercnt_remove_by_addr(addr);
3199 ast_log(LOG_WARNING, "No more space\n");
3202 x = CALLNO_ENTRY_GET_CALLNO(entry);
3203 ast_mutex_lock(&iaxsl[x]);
3205 iaxs[x] = new_iax(addr, host);
3208 ast_debug(1, "Creating new call structure %d\n", x);
3209 iaxs[x]->callno_entry = entry;
3210 iaxs[x]->sockfd = sockfd;
3211 ast_sockaddr_copy(&iaxs[x]->addr, addr);
3212 iaxs[x]->peercallno = callno;
3213 iaxs[x]->callno = x;
3214 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3215 iaxs[x]->expiry = min_reg_expire;
3216 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3217 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3218 iaxs[x]->amaflags = amaflags;
3219 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3220 ast_string_field_set(iaxs[x], accountcode, accountcode);
3221 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3222 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3223 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3225 if (iaxs[x]->peercallno) {
3226 store_by_peercallno(iaxs[x]);
3229 ast_log(LOG_WARNING, "Out of resources\n");
3230 ast_mutex_unlock(&iaxsl[x]);
3231 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3235 ast_mutex_unlock(&iaxsl[x]);
3241 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3242 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3245 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3247 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3251 * \brief Queue a frame to a call's owning asterisk channel
3253 * \pre This function assumes that iaxsl[callno] is locked when called.
3255 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3256 * was valid before calling it, it may no longer be valid after calling it.
3257 * This function may unlock and lock the mutex associated with this callno,
3258 * meaning that another thread may grab it and destroy the call.
3260 static int iax2_queue_frame(int callno, struct ast_frame *f)
3262 iax2_lock_owner(callno);
3263 if (iaxs[callno] && iaxs[callno]->owner) {
3264 ast_queue_frame(iaxs[callno]->owner, f);
3265 ast_channel_unlock(iaxs[callno]->owner);
3271 * \brief Queue a hold frame on the ast_channel owner
3273 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3274 * is active for the given call number.
3276 * \pre Assumes lock for callno is already held.
3278 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3279 * was valid before calling it, it may no longer be valid after calling it.
3280 * This function may unlock and lock the mutex associated with this callno,
3281 * meaning that another thread may grab it and destroy the call.
3283 static int iax2_queue_hold(int callno, const char *musicclass)
3285 iax2_lock_owner(callno);
3286 if (iaxs[callno] && iaxs[callno]->owner) {
3287 ast_queue_hold(iaxs[callno]->owner, musicclass);
3288 ast_channel_unlock(iaxs[callno]->owner);
3294 * \brief Queue an unhold frame on the ast_channel owner
3296 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3297 * is active for the given call number.
3299 * \pre Assumes lock for callno is already held.
3301 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3302 * was valid before calling it, it may no longer be valid after calling it.
3303 * This function may unlock and lock the mutex associated with this callno,
3304 * meaning that another thread may grab it and destroy the call.
3306 static int iax2_queue_unhold(int callno)
3308 iax2_lock_owner(callno);
3309 if (iaxs[callno] && iaxs[callno]->owner) {
3310 ast_queue_unhold(iaxs[callno]->owner);
3311 ast_channel_unlock(iaxs[callno]->owner);
3317 * \brief Queue a hangup frame on the ast_channel owner
3319 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3320 * is active for the given call number.
3322 * \pre Assumes lock for callno is already held.
3324 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3325 * was valid before calling it, it may no longer be valid after calling it.
3326 * This function may unlock and lock the mutex associated with this callno,
3327 * meaning that another thread may grab it and destroy the call.
3329 static int iax2_queue_hangup(int callno)
3331 iax2_lock_owner(callno);
3332 if (iaxs[callno] && iaxs[callno]->owner) {
3333 ast_queue_hangup(iaxs[callno]->owner);
3334 ast_channel_unlock(iaxs[callno]->owner);
3340 * \note This function assumes that iaxsl[callno] is locked when called.
3342 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3343 * was valid before calling it, it may no longer be valid after calling it.
3344 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3345 * associated with this callno, meaning that another thread may grab it and destroy the call.
3347 static int __do_deliver(void *data)
3349 /* Just deliver the packet by using queueing. This is called by
3350 the IAX thread with the iaxsl lock held. */
3351 struct iax_frame *fr = data;
3353 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3354 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3355 iax2_queue_frame(fr->callno, &fr->af);
3356 /* Free our iax frame */
3357 iax2_frame_free(fr);
3358 /* And don't run again */
3362 static int handle_error(void)
3364 /* XXX Ideally we should figure out why an error occurred and then abort those
3365 rather than continuing to try. Unfortunately, the published interface does
3366 not seem to work XXX */
3368 struct sockaddr_in *sin;
3371 struct sock_extended_err e;
3376 m.msg_controllen = sizeof(e);
3378 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3380 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3382 if (m.msg_controllen) {
3383 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3385 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3387 ast_log(LOG_WARNING, "No address detected??\n");
3389 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3396 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3399 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3402 ast_debug(1, "Received error: %s\n", strerror(errno));
3409 static int send_packet(struct iax_frame *f)
3412 int callno = f->callno;
3414 /* Don't send if there was an error, but return error instead */
3415 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3418 /* Called with iaxsl held */
3420 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3423 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3424 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3426 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3427 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3431 ast_debug(1, "Received error: %s\n", strerror(errno));
3440 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3441 * for the given call number may disappear during its execution.
3443 static int iax2_predestroy(int callno)
3445 struct ast_channel *c = NULL;
3446 struct chan_iax2_pvt *pvt = iaxs[callno];
3451 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3452 iax2_destroy_helper(pvt);
3453 ast_set_flag64(pvt, IAX_ALREADYGONE);
3456 if ((c = pvt->owner)) {
3457 ast_channel_tech_pvt_set(c, NULL);
3458 iax2_queue_hangup(callno);
3460 ast_module_unref(ast_module_info->self);
3466 static void iax2_destroy(int callno)
3468 struct chan_iax2_pvt *pvt = NULL;
3469 struct ast_channel *owner = NULL;
3472 if ((pvt = iaxs[callno])) {
3474 /* iax2_destroy_helper gets called from this function later on. When
3475 * called twice, we get the (previously) familiar FRACK! errors in
3476 * devmode, from the scheduler. An alternative to this approach is to
3477 * reset the scheduler entries to -1 when they're deleted in
3478 * iax2_destroy_helper(). That approach was previously decided to be
3479 * "wrong" because "the memory is going to be deallocated anyway. Why
3480 * should we be resetting those values?" */
3481 iax2_destroy_helper(pvt);
3485 owner = pvt ? pvt->owner : NULL;
3488 if (ast_channel_trylock(owner)) {
3489 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3490 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3496 iaxs[callno] = NULL;
3503 /* If there's an owner, prod it to give up */
3504 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3505 * because we already hold the owner channel lock. */
3506 ast_queue_hangup(owner);
3509 if (pvt->peercallno) {
3510 remove_by_peercallno(pvt);
3513 if (pvt->transfercallno) {
3514 remove_by_transfercallno(pvt);
3524 ast_channel_unlock(owner);
3528 static int update_packet(struct iax_frame *f)
3530 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3531 struct ast_iax2_full_hdr *fh = f->data;
3532 struct ast_frame af;
3534 /* if frame is encrypted. decrypt before updating it. */
3535 if (f->encmethods) {
3536 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3538 /* Mark this as a retransmission */
3539 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3541 f->iseqno = iaxs[f->callno]->iseqno;
3542 fh->iseqno = f->iseqno;
3544 /* Now re-encrypt the frame */
3545 if (f->encmethods) {
3546 /* since this is a retransmit frame, create a new random padding
3547 * before re-encrypting. */
3548 build_rand_pad(f->semirand, sizeof(f->semirand));
3549 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3554 static int attempt_transmit(const void *data);
3555 static void __attempt_transmit(const void *data)
3557 /* Attempt to transmit the frame to the remote peer...
3558 Called without iaxsl held. */
3559 struct iax_frame *f = (struct iax_frame *)data;
3561 int callno = f->callno;
3563 /* Make sure this call is still active */
3565 ast_mutex_lock(&iaxsl[callno]);
3566 if (callno && iaxs[callno]) {
3567 if (f->retries < 0) {
3570 } else if (f->retries >= max_retries) {
3571 /* Too many attempts. Record an error. */
3573 /* Transfer timeout */
3574 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3575 } else if (f->final) {
3576 iax2_destroy(callno);
3578 if (iaxs[callno]->owner) {
3579 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3580 ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3581 ast_channel_name(iaxs[f->callno]->owner),
3583 f->af.subclass.integer,
3587 iaxs[callno]->error = ETIMEDOUT;
3588 if (iaxs[callno]->owner) {
3589 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3591 iax2_queue_frame(callno, &fr); /* XXX */
3592 /* Remember, owner could disappear */
3593 if (iaxs[callno] && iaxs[callno]->owner)
3594 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3596 if (iaxs[callno]->reg) {
3597 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3598 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3599 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3601 iax2_destroy(callno);
3606 /* Update it if it needs it */
3608 /* Attempt transmission */
3611 /* Try again later after 10 times as long */
3613 if (f->retrytime > MAX_RETRY_TIME)
3614 f->retrytime = MAX_RETRY_TIME;
3615 /* Transfer messages max out at one second */
3616 if (f->transfer && (f->retrytime > 1000))
3617 f->retrytime = 1000;
3618 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3621 /* Make sure it gets freed */
3627 /* Don't attempt delivery, just remove it from the queue */
3628 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3629 ast_mutex_unlock(&iaxsl[callno]);
3630 f->retrans = -1; /* this is safe because this is the scheduled function */
3631 /* Free the IAX frame */
3633 } else if (callno) {
3634 ast_mutex_unlock(&iaxsl[callno]);
3638 static int attempt_transmit(const void *data)
3640 #ifdef SCHED_MULTITHREADED
3641 if (schedule_action(__attempt_transmit, data))
3643 __attempt_transmit(data);
3647 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3649 struct iax2_peer *peer = NULL;
3650 struct iax2_user *user = NULL;
3651 static const char * const choices[] = { "all", NULL };
3656 e->command = "iax2 prune realtime";
3658 "Usage: iax2 prune realtime [<peername>|all]\n"
3659 " Prunes object(s) from the cache\n";
3663 cmplt = ast_cli_complete(a->word, choices, a->n);
3665 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3671 return CLI_SHOWUSAGE;
3672 if (!strcmp(a->argv[3], "all")) {
3675 ast_cli(a->fd, "Cache flushed successfully.\n");
3678 peer = find_peer(a->argv[3], 0);
3679 user = find_user(a->argv[3]);
3682 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3683 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3684 expire_registry(peer_ref(peer));
3685 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3687 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3692 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3693 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3694 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3696 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3698 ao2_unlink(users,user);
3702 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3708 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3712 e->command = "iax2 test losspct";
3714 "Usage: iax2 test losspct <percentage>\n"
3715 " For testing, throws away <percentage> percent of incoming packets\n";
3721 return CLI_SHOWUSAGE;
3723 test_losspct = atoi(a->argv[3]);
3729 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3733 e->command = "iax2 test late";
3735 "Usage: iax2 test late <ms>\n"
3736 " For testing, count the next frame as <ms> ms late\n";
3743 return CLI_SHOWUSAGE;
3745 test_late = atoi(a->argv[3]);
3750 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3754 e->command = "iax2 test resync";
3756 "Usage: iax2 test resync <ms>\n"
3757 " For testing, adjust all future frames by <ms> ms\n";
3764 return CLI_SHOWUSAGE;
3766 test_resync = atoi(a->argv[3]);
3771 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3775 e->command = "iax2 test jitter";
3777 "Usage: iax2 test jitter <ms> <pct>\n"
3778 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3779 " percentage of packets. If <pct> is not specified, adds\n"
3780 " jitter to all packets.\n";
3786 if (a->argc < 4 || a->argc > 5)
3787 return CLI_SHOWUSAGE;
3789 test_jit = atoi(a->argv[3]);
3791 test_jitpct = atoi(a->argv[4]);
3795 #endif /* IAXTESTS */
3797 /*! \brief peer_status: Report Peer status in character string */
3798 /* returns 1 if peer is online, -1 if unmonitored */
3799 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3803 if (peer->lastms < 0) {
3804 ast_copy_string(status, "UNREACHABLE", statuslen);
3805 } else if (peer->lastms > peer->maxms) {
3806 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3808 } else if (peer->lastms) {
3809 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3812 ast_copy_string(status, "UNKNOWN", statuslen);
3815 ast_copy_string(status, "Unmonitored", statuslen);
3821 /*! \brief Show one peer in detail */
3822 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3826 struct iax2_peer *peer;
3827 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3828 struct ast_str *encmethods = ast_str_alloca(256);
3829 int load_realtime = 0;
3833 e->command = "iax2 show peer";
3835 "Usage: iax2 show peer <name>\n"
3836 " Display details on specific IAX peer\n";
3840 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3845 return CLI_SHOWUSAGE;
3847 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3849 peer = find_peer(a->argv[3], load_realtime);
3851 char *str_addr, *str_defaddr;
3852 char *str_port, *str_defport;
3854 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3855 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3856 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3857 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3859 encmethods_to_str(peer->encmethods, &encmethods);
3860 ast_cli(a->fd, "\n\n");
3861 ast_cli(a->fd, " * Name : %s\n", peer->name);
3862 ast_cli(a->fd, " Description : %s\n", peer->description);
3863 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3864 ast_cli(a->fd, " Context : %s\n", peer->context);
3865 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3866 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3867 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3868 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3869 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3870 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3871 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3872 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3873 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3874 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3875 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3876 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3877 ast_cli(a->fd, " Username : %s\n", peer->username);
3878 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3880 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3881 strcpy(cbuf, "Error"); /* Safe */
3883 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3885 peer_status(peer, status, sizeof(status));
3886 ast_cli(a->fd, " Status : %s\n", status);
3887 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");
3888 ast_cli(a->fd, "\n");
3891 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3892 ast_cli(a->fd, "\n");
3898 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3901 struct iax2_peer *peer;
3903 int wordlen = strlen(word);
3904 struct ao2_iterator i;
3906 i = ao2_iterator_init(peers, 0);
3907 while ((peer = ao2_iterator_next(&i))) {
3908 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3909 && (!flags || ast_test_flag64(peer, flags))) {
3910 res = ast_strdup(peer->name);
3916 ao2_iterator_destroy(&i);
3921 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3923 struct iax_frame *cur;
3924 int cnt = 0, dead = 0, final = 0, i = 0;
3928 e->command = "iax2 show stats";
3930 "Usage: iax2 show stats\n"
3931 " Display statistics on IAX channel driver.\n";
3938 return CLI_SHOWUSAGE;
3940 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3941 ast_mutex_lock(&iaxsl[i]);
3942 AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3943 if (cur->retries < 0)
3949 ast_mutex_unlock(&iaxsl[i]);
3952 ast_cli(a->fd, " IAX Statistics\n");
3953 ast_cli(a->fd, "---------------------\n");
3954 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3955 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3956 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3957 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3959 trunk_timed = trunk_untimed = 0;
3960 if (trunk_maxmtu > trunk_nmaxmtu)
3961 trunk_nmaxmtu = trunk_maxmtu;
3966 /*! \brief Set trunk MTU from CLI */
3967 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3973 e->command = "iax2 set mtu";
3975 "Usage: iax2 set mtu <value>\n"
3976 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
3977 " zero to disable. Disabling means that the operating system\n"
3978 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
3979 " packet exceeds the UDP payload size. This is substantially\n"
3980 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3981 " greater for G.711 samples.\n";
3988 return CLI_SHOWUSAGE;
3989 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3990 mtuv = MAX_TRUNK_MTU;
3992 mtuv = atoi(a->argv[3]);
3995 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
3996 global_max_trunk_mtu = 0;
3999 if (mtuv < 172 || mtuv > 4000) {
4000 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4001 return CLI_SHOWUSAGE;
4003 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4004 global_max_trunk_mtu = mtuv;
4008 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4010 struct iax2_dpcache *dp = NULL;
4011 char tmp[1024], *pc = NULL;
4013 struct timeval now = ast_tvnow();
4017 e->command = "iax2 show cache";
4019 "Usage: iax2 show cache\n"
4020 " Display currently cached IAX Dialplan results.\n";
4026 AST_LIST_LOCK(&dpcache);
4028 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4030 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4031 s = dp->expiry.tv_sec - now.tv_sec;
4033 if (dp->flags & CACHE_FLAG_EXISTS)
4034 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4035 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4036 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4037 if (dp->flags & CACHE_FLAG_CANEXIST)
4038 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4039 if (dp->flags & CACHE_FLAG_PENDING)
4040 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4041 if (dp->flags & CACHE_FLAG_TIMEOUT)
4042 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4043 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4044 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4045 if (dp->flags & CACHE_FLAG_MATCHMORE)
4046 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4047 if (dp->flags & CACHE_FLAG_UNKNOWN)
4048 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4049 /* Trim trailing pipe */
4050 if (!ast_strlen_zero(tmp)) {
4051 tmp[strlen(tmp) - 1] = '\0';
4053 ast_copy_string(tmp, "(none)", sizeof(tmp));
4056 pc = strchr(dp->peercontext, '@');
4058 pc = dp->peercontext;
4062 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4063 if (dp->waiters[x] > -1)
4067 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4069 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4073 AST_LIST_UNLOCK(&dpcache);
4078 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4080 static void unwrap_timestamp(struct iax_frame *fr)
4082 /* Video mini frames only encode the lower 15 bits of the session
4083 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4084 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4085 const int lower_mask = (1 << ts_shift) - 1;
4086 const int upper_mask = ~lower_mask;
4087 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4089 if ( (fr->ts & upper_mask) == last_upper ) {
4090 const int x = fr->ts - iaxs[fr->callno]->last;
4091 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4093 if (x < -threshold) {
4094 /* Sudden big jump backwards in timestamp:
4095 What likely happened here is that miniframe timestamp has circled but we haven't
4096 gotten the update from the main packet. We'll just pretend that we did, and
4097 update the timestamp appropriately. */
4098 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4100 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4101 } else if (x > threshold) {
4102 /* Sudden apparent big jump forwards in timestamp:
4103 What's likely happened is this is an old miniframe belonging to the previous
4104 top 15 or 16-bit timestamp that has turned up out of order.
4105 Adjust the timestamp appropriately. */
4106 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4108 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4113 static int get_from_jb(const void *p);
4115 static void update_jbsched(struct chan_iax2_pvt *pvt)
4119 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4121 when = jb_next(pvt->jb) - when;
4124 /* XXX should really just empty until when > 0.. */
4128 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4129 CALLNO_TO_PTR(pvt->callno));
4132 static void __get_from_jb(const void *p)
4134 int callno = PTR_TO_CALLNO(p);
4135 struct chan_iax2_pvt *pvt = NULL;
4136 struct iax_frame *fr;
4141 struct timeval now = ast_tvnow();
4142 struct ast_format *voicefmt;
4144 /* Make sure we have a valid private structure before going on */
4145 ast_mutex_lock(&iaxsl[callno]);
4149 ast_mutex_unlock(&iaxsl[callno]);
4155 /* round up a millisecond since ast_sched_runq does; */
4156 /* prevents us from spinning while waiting for our now */
4157 /* to catch up with runq's now */
4158 now.tv_usec += 1000;
4160 ms = ast_tvdiff_ms(now, pvt->rxcore);
4161 if (ms >= (next = jb_next(pvt->jb))) {
4162 voicefmt = ast_format_compatibility_bitfield2format(pvt->voiceformat);
4164 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4165 * In this case, fall back to using the format negotiated during call setup,
4166 * so we don't stall the jitterbuffer completely. */
4167 voicefmt = ast_format_compatibility_bitfield2format(pvt->peerformat);
4170 /* Really shouldn't happen, but if it does, should be looked into */
4171 ast_log(LOG_WARNING, "No voice format and no peer format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4172 goto cleanup; /* Don't crash if there's no voice format */
4174 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4179 /* __do_deliver() can cause the call to disappear */
4184 struct ast_frame af = { 0, };
4186 /* create an interpolation frame */
4187 af.frametype = AST_FRAME_VOICE;
4188 af.subclass.format = voicefmt;
4189 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4190 af.src = "IAX2 JB interpolation";
4191 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4192 af.offset = AST_FRIENDLY_OFFSET;
4194 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4195 * which we'd need to malloc, and then it would free it. That seems like a drag */
4196 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4197 iax2_queue_frame(callno, &af);
4198 /* iax2_queue_frame() could cause the call to disappear */
4204 iax2_frame_free(frame.data);
4211 /* shouldn't happen */
4217 update_jbsched(pvt);
4218 ast_mutex_unlock(&iaxsl[callno]);
4221 static int get_from_jb(const void *data)
4223 #ifdef SCHED_MULTITHREADED
4224 if (schedule_action(__get_from_jb, data))
4226 __get_from_jb(data);
4231 * \note This function assumes fr->callno is locked
4233 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4234 * was valid before calling it, it may no longer be valid after calling it.
4236 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4243 * Clear fr->af.data if there is no data in the buffer. Things
4244 * like AST_CONTROL_HOLD without a suggested music class must
4245 * have a NULL pointer.
4247 if (!fr->af.datalen) {
4248 memset(&fr->af.data, 0, sizeof(fr->af.data));
4251 /* Attempt to recover wrapped timestamps */
4252 unwrap_timestamp(fr);
4254 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4255 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4256 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4259 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4261 fr->af.delivery = ast_tv(0,0);
4264 type = JB_TYPE_CONTROL;
4267 if(fr->af.frametype == AST_FRAME_VOICE) {
4268 type = JB_TYPE_VOICE;
4269 len = ast_codec_samples_count(&fr->af) / (ast_format_get_sample_rate(fr->af.subclass.format) / 1000);
4270 } else if(fr->af.frametype == AST_FRAME_CNG) {