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>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
34 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35 * \addtogroup configuration_file
38 /*! \page iax.conf iax.conf
39 * \verbinclude iax.conf.sample
43 * \todo XXX The IAX2 channel driver needs its native bridge
44 * code converted to the new bridge technology scheme.
46 * \note The chan_dahdi native bridge code can be used as an
47 * example. It also appears that chan_iax2 also has a native
48 * transfer check like chan_dahdi to eliminate tromboned calls.
50 * \note The existing native bridge code is marked with the
51 * IAX2_NATIVE_BRIDGING conditional.
55 <use type="external">crypto</use>
56 <support_level>core</support_level>
61 ASTERISK_REGISTER_FILE()
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
71 #include <sys/signal.h>
79 #include "asterisk/paths.h"
81 #include "asterisk/lock.h"
82 #include "asterisk/frame.h"
83 #include "asterisk/channel.h"
84 #include "asterisk/module.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/sched.h"
87 #include "asterisk/io.h"
88 #include "asterisk/config.h"
89 #include "asterisk/cli.h"
90 #include "asterisk/translate.h"
91 #include "asterisk/md5.h"
92 #include "asterisk/crypto.h"
93 #include "asterisk/acl.h"
94 #include "asterisk/manager.h"
95 #include "asterisk/callerid.h"
96 #include "asterisk/app.h"
97 #include "asterisk/astdb.h"
98 #include "asterisk/musiconhold.h"
99 #include "asterisk/features.h"
100 #include "asterisk/utils.h"
101 #include "asterisk/causes.h"
102 #include "asterisk/localtime.h"
103 #include "asterisk/dnsmgr.h"
104 #include "asterisk/devicestate.h"
105 #include "asterisk/netsock.h"
106 #include "asterisk/stringfields.h"
107 #include "asterisk/linkedlists.h"
108 #include "asterisk/astobj2.h"
109 #include "asterisk/timing.h"
110 #include "asterisk/taskprocessor.h"
111 #include "asterisk/test.h"
112 #include "asterisk/data.h"
113 #include "asterisk/security_events.h"
114 #include "asterisk/stasis_endpoints.h"
115 #include "asterisk/bridge.h"
116 #include "asterisk/stasis.h"
117 #include "asterisk/stasis_system.h"
118 #include "asterisk/stasis_channels.h"
119 #include "asterisk/format_cache.h"
120 #include "asterisk/format_compatibility.h"
121 #include "asterisk/format_cap.h"
123 #include "iax2/include/iax2.h"
124 #include "iax2/include/firmware.h"
125 #include "iax2/include/parser.h"
126 #include "iax2/include/provision.h"
127 #include "iax2/include/codec_pref.h"
128 #include "iax2/include/format_compatibility.h"
130 #include "jitterbuf.h"
133 <application name="IAX2Provision" language="en_US">
135 Provision a calling IAXy with a given template.
138 <parameter name="template">
139 <para>If not specified, defaults to <literal>default</literal>.</para>
143 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
144 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
145 or <literal>0</literal> on success.</para>
148 <function name="IAXPEER" language="en_US">
150 Gets IAX peer information.
153 <parameter name="peername" required="true">
155 <enum name="CURRENTCHANNEL">
156 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
157 endpoint of the current channel</para>
161 <parameter name="item">
162 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
165 <para>(default) The IP address.</para>
168 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
170 <enum name="mailbox">
171 <para>The configured mailbox.</para>
173 <enum name="context">
174 <para>The configured context.</para>
177 <para>The epoch time of the next expire.</para>
179 <enum name="dynamic">
180 <para>Is it dynamic? (yes/no).</para>
182 <enum name="callerid_name">
183 <para>The configured Caller ID name.</para>
185 <enum name="callerid_num">
186 <para>The configured Caller ID number.</para>
189 <para>The configured codecs.</para>
191 <enum name="codec[x]">
192 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
193 with <literal>0</literal>)</para>
199 <para>Gets information associated with the specified IAX2 peer.</para>
202 <ref type="function">SIPPEER</ref>
205 <function name="IAXVAR" language="en_US">
207 Sets or retrieves a remote variable.
210 <parameter name="varname" required="true" />
213 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
216 <manager name="IAXpeers" language="en_US">
221 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
226 <manager name="IAXpeerlist" language="en_US">
231 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
234 <para>List all the IAX peers.</para>
237 <manager name="IAXnetstats" language="en_US">
243 <para>Show IAX channels network statistics.</para>
246 <manager name="IAXregistry" language="en_US">
248 Show IAX registrations.
251 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
254 <para>Show IAX registrations.</para>
259 /* Define SCHED_MULTITHREADED to run the scheduler in a special
260 multithreaded mode. */
261 #define SCHED_MULTITHREADED
263 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
264 thread is actually doing. */
265 #define DEBUG_SCHED_MULTITHREAD
269 static int nochecksums = 0;
272 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
273 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
275 #define DEFAULT_THREAD_COUNT 10
276 #define DEFAULT_MAX_THREAD_COUNT 100
277 #define DEFAULT_RETRY_TIME 1000
278 #define MEMORY_SIZE 100
279 #define DEFAULT_DROP 3
281 #define DEBUG_SUPPORT
283 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
285 /* Sample over last 100 units to determine historic jitter */
288 static struct iax2_codec_pref prefs_global;
290 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
293 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
294 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
295 #define MAX_TRUNK_MTU 1240
297 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
298 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
300 #define DEFAULT_CONTEXT "default"
302 static char default_parkinglot[AST_MAX_CONTEXT];
304 static char language[MAX_LANGUAGE] = "";
305 static char regcontext[AST_MAX_CONTEXT] = "";
307 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
308 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
309 static int network_change_sched_id = -1;
311 static int maxauthreq = 3;
312 static int max_retries = 4;
313 static int ping_time = 21;
314 static int lagrq_time = 10;
315 static int maxjitterbuffer=1000;
316 static int resyncthreshold=1000;
317 static int maxjitterinterps=10;
318 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
320 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
322 static int trunkfreq = 20;
323 static int trunkmaxsize = MAX_TRUNKDATA;
325 static int authdebug = 0;
326 static int autokill = 0;
327 static int iaxcompat = 0;
328 static int last_authmethod = 0;
330 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
332 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
339 static int min_reg_expire;
340 static int max_reg_expire;
342 static int srvlookup = 0;
344 static struct ast_timer *timer; /* Timer for trunking */
346 static struct ast_netsock_list *netsock;
347 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
348 static int defaultsockfd = -1;
350 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
353 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
355 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
357 ~AST_FORMAT_SLIN16 & \
358 ~AST_FORMAT_SIREN7 & \
359 ~AST_FORMAT_SIREN14 & \
365 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
367 ~AST_FORMAT_G726_AAL2 & \
370 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
374 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
375 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
376 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
378 /* if a pvt has encryption setup done and is running on the call */
379 #define IAX_CALLENCRYPTED(pvt) \
380 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
382 #define IAX_DEBUGDIGEST(msg, key) do { \
384 char digest[33] = ""; \
389 for (idx = 0; idx < 16; idx++) \
390 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
392 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
395 static struct io_context *io;
396 static struct ast_sched_context *sched;
398 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
400 static int iaxdebug = 0;
402 static int iaxtrunkdebug = 0;
404 static int test_losspct = 0;
406 static int test_late = 0;
407 static int test_resync = 0;
408 static int test_jit = 0;
409 static int test_jitpct = 0;
410 #endif /* IAXTESTS */
412 static char accountcode[AST_MAX_ACCOUNT_CODE];
413 static char mohinterpret[MAX_MUSICCLASS];
414 static char mohsuggest[MAX_MUSICCLASS];
415 static int amaflags = 0;
417 static int delayreject = 0;
418 static int iax2_encryption = 0;
420 static struct ast_flags64 globalflags = { 0 };
422 static pthread_t netthreadid = AST_PTHREADT_NULL;
425 IAX_STATE_STARTED = (1 << 0),
426 IAX_STATE_AUTHENTICATED = (1 << 1),
427 IAX_STATE_TBD = (1 << 2),
430 struct iax2_context {
431 char context[AST_MAX_CONTEXT];
432 struct iax2_context *next;
436 #define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
437 #define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
438 #define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
439 #define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
440 #define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
441 #define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
442 #define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
443 #define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
444 #define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
445 #define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
446 #define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
447 #define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
448 #define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
449 #define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
450 #define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
451 #define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
452 #define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
453 #define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
454 #define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
455 #define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
456 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
457 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
458 #define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
459 #define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
460 #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 */
461 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
462 #define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
463 #define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
464 #define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
465 #define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
466 #define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
467 static int global_rtautoclear = 120;
469 static int reload_config(int forced_reload);
472 * \brief Call token validation settings.
474 enum calltoken_peer_enum {
475 /*! \brief Default calltoken required unless the ip is in the ignorelist */
476 CALLTOKEN_DEFAULT = 0,
477 /*! \brief Require call token validation. */
479 /*! \brief Require call token validation after a successful registration
480 * using call token validation occurs. */
482 /*! \brief Do not require call token validation. */
487 AST_DECLARE_STRING_FIELDS(
488 AST_STRING_FIELD(name);
489 AST_STRING_FIELD(secret);
490 AST_STRING_FIELD(dbsecret);
491 AST_STRING_FIELD(accountcode);
492 AST_STRING_FIELD(mohinterpret);
493 AST_STRING_FIELD(mohsuggest);
494 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
495 AST_STRING_FIELD(language);
496 AST_STRING_FIELD(cid_num);
497 AST_STRING_FIELD(cid_name);
498 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
506 iax2_format capability;
507 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
508 int curauthreq; /*!< Current number of outstanding AUTHREQs */
509 struct iax2_codec_pref prefs;
510 struct ast_acl_list *acl;
511 struct iax2_context *contexts;
512 struct ast_variable *vars;
513 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
517 AST_DECLARE_STRING_FIELDS(
518 AST_STRING_FIELD(name);
519 AST_STRING_FIELD(username);
520 AST_STRING_FIELD(description); /*!< Description of the peer */
521 AST_STRING_FIELD(secret);
522 AST_STRING_FIELD(dbsecret);
523 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
525 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
526 AST_STRING_FIELD(context); /*!< For transfers only */
527 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
528 AST_STRING_FIELD(mailbox); /*!< Mailbox */
529 AST_STRING_FIELD(mohinterpret);
530 AST_STRING_FIELD(mohsuggest);
531 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
532 /* Suggested caller id if registering */
533 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
534 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
535 AST_STRING_FIELD(zonetag); /*!< Time Zone */
536 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
538 struct iax2_codec_pref prefs;
539 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
540 struct ast_sockaddr addr;
542 int sockfd; /*!< Socket to use for transmission */
543 struct ast_sockaddr mask;
547 /* Dynamic Registration fields */
548 struct ast_sockaddr defaddr; /*!< Default address if there is one */
549 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
550 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
552 int expire; /*!< Schedule entry for expiry */
553 int expiry; /*!< How soon to expire */
554 iax2_format capability; /*!< Capability */
557 int callno; /*!< Call number of POKE request */
558 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
559 int lastms; /*!< How long last response took (in ms), or -1 for no response */
560 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
562 int pokefreqok; /*!< How often to check if the host is up */
563 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
564 int historicms; /*!< How long recent average responses took */
565 int smoothing; /*!< Sample over how many units to determine historic ms */
566 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
568 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
570 struct ast_acl_list *acl;
571 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
573 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
576 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
578 struct iax2_trunk_peer {
581 struct ast_sockaddr addr;
582 struct timeval txtrunktime; /*!< Transmit trunktime */
583 struct timeval rxtrunktime; /*!< Receive trunktime */
584 struct timeval lasttxtime; /*!< Last transmitted trunktime */
585 struct timeval trunkact; /*!< Last trunk activity */
586 unsigned int lastsent; /*!< Last sent time */
587 /* Trunk data and length */
588 unsigned char *trunkdata;
589 unsigned int trunkdatalen;
590 unsigned int trunkdataalloc;
594 AST_LIST_ENTRY(iax2_trunk_peer) list;
597 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
600 REG_STATE_UNREGISTERED = 0,
603 REG_STATE_REGISTERED,
609 enum iax_transfer_state {
614 TRANSFER_PASSTHROUGH,
618 TRANSFER_MPASSTHROUGH,
623 struct iax2_registry {
624 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
626 char secret[80]; /*!< Password or key name in []'s */
627 int expire; /*!< Sched ID of expiration */
628 int refresh; /*!< How often to refresh */
629 enum iax_reg_state regstate;
630 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
631 int callno; /*!< Associated call number if applicable */
632 struct ast_sockaddr us; /*!< Who the server thinks we are */
633 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
634 AST_LIST_ENTRY(iax2_registry) entry;
639 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
641 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
642 #define MIN_RETRY_TIME 100
643 #define MAX_RETRY_TIME 10000
645 #define MAX_JITTER_BUFFER 50
646 #define MIN_JITTER_BUFFER 10
648 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
650 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
652 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
653 #define TS_GAP_FOR_JB_RESYNC 5000
655 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
656 #define MARK_IAX_SUBCLASS_TX 0x8000
658 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
659 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
660 static int iaxdynamicthreadcount = 0;
661 static int iaxdynamicthreadnum = 0;
662 static int iaxactivethreadcount = 0;
676 /* We use the high order bit as the validated flag, and the lower 15 as the
677 * actual call number */
678 typedef uint16_t callno_entry;
680 struct chan_iax2_pvt {
681 /*! Socket to send/receive on for this call */
683 /*! ast_callid bound to dialog */
685 /*! Last received voice format */
686 iax2_format voiceformat;
687 /*! Last received video format */
688 iax2_format videoformat;
689 /*! Last sent voice format */
690 iax2_format svoiceformat;
691 /*! Last sent video format */
692 iax2_format svideoformat;
693 /*! What we are capable of sending */
694 iax2_format capability;
695 /*! Last received timestamp */
697 /*! Last sent timestamp - never send the same timestamp twice in a single call */
698 unsigned int lastsent;
699 /*! Timestamp of the last video frame sent */
700 unsigned int lastvsent;
701 /*! Next outgoing timestamp if everything is good */
702 unsigned int nextpred;
703 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
704 int first_iax_message;
705 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
706 int last_iax_message;
707 /*! True if the last voice we transmitted was not silence/CNG */
708 unsigned int notsilenttx:1;
710 unsigned int pingtime;
711 /*! Max time for initial response */
714 struct ast_sockaddr addr;
715 /*! Actual used codec preferences */
716 struct iax2_codec_pref prefs;
717 /*! Requested codec preferences */
718 struct iax2_codec_pref rprefs;
719 /*! Our call number */
720 unsigned short callno;
721 /*! Our callno_entry entry */
722 callno_entry callno_entry;
724 unsigned short peercallno;
725 /*! Negotiated format, this is only used to remember what format was
726 chosen for an unauthenticated call so that the channel can get
727 created later using the right format */
728 iax2_format chosenformat;
729 /*! Peer selected format */
730 iax2_format peerformat;
731 /*! Peer capability */
732 iax2_format peercapability;
733 /*! timeval that we base our transmission on */
734 struct timeval offset;
735 /*! timeval that we base our delivery on */
736 struct timeval rxcore;
737 /*! The jitterbuffer */
739 /*! active jb read scheduler id */
743 /*! Error, as discovered by the manager */
745 /*! Owner if we have one */
746 struct ast_channel *owner;
747 /*! What's our state? */
748 struct ast_flags state;
749 /*! Expiry (optional) */
751 /*! Next outgoing sequence number */
752 unsigned char oseqno;
753 /*! Next sequence number they have not yet acknowledged */
754 unsigned char rseqno;
755 /*! Next incoming sequence number */
756 unsigned char iseqno;
757 /*! Last incoming sequence number we have acknowledged */
758 unsigned char aseqno;
760 AST_DECLARE_STRING_FIELDS(
762 AST_STRING_FIELD(peer);
763 /*! Default Context */
764 AST_STRING_FIELD(context);
765 /*! Caller ID if available */
766 AST_STRING_FIELD(cid_num);
767 AST_STRING_FIELD(cid_name);
768 /*! Hidden Caller ID (i.e. ANI) if appropriate */
769 AST_STRING_FIELD(ani);
771 AST_STRING_FIELD(dnid);
773 AST_STRING_FIELD(rdnis);
774 /*! Requested Extension */
775 AST_STRING_FIELD(exten);
776 /*! Expected Username */
777 AST_STRING_FIELD(username);
778 /*! Expected Secret */
779 AST_STRING_FIELD(secret);
781 AST_STRING_FIELD(challenge);
782 /*! Public keys permitted keys for incoming authentication */
783 AST_STRING_FIELD(inkeys);
784 /*! Private key for outgoing authentication */
785 AST_STRING_FIELD(outkey);
786 /*! Preferred language */
787 AST_STRING_FIELD(language);
788 /*! Hostname/peername for naming purposes */
789 AST_STRING_FIELD(host);
791 AST_STRING_FIELD(dproot);
792 AST_STRING_FIELD(accountcode);
793 AST_STRING_FIELD(mohinterpret);
794 AST_STRING_FIELD(mohsuggest);
795 /*! received OSP token */
796 AST_STRING_FIELD(osptoken);
797 /*! Default parkinglot */
798 AST_STRING_FIELD(parkinglot);
800 /*! AUTHREJ all AUTHREP frames */
802 /*! permitted authentication methods */
804 /*! permitted encryption methods */
806 /*! Encryption AES-128 Key */
807 ast_aes_encrypt_key ecx;
808 /*! Decryption AES-128 Key corresponding to ecx */
809 ast_aes_decrypt_key mydcx;
810 /*! Decryption AES-128 Key used to decrypt peer frames */
811 ast_aes_decrypt_key dcx;
812 /*! scheduler id associated with iax_key_rotate
813 * for encrypted calls*/
815 /*! 32 bytes of semi-random data */
816 unsigned char semirand[32];
817 /*! Associated registry */
818 struct iax2_registry *reg;
819 /*! Associated peer for poking */
820 struct iax2_peer *peerpoke;
825 /*! Transferring status */
826 enum iax_transfer_state transferring;
827 /*! Transfer identifier */
829 /*! Who we are IAX transferring to */
830 struct ast_sockaddr transfer;
831 /*! What's the new call number for the transfer */
832 unsigned short transfercallno;
833 /*! Transfer encrypt AES-128 Key */
834 ast_aes_encrypt_key tdcx;
836 /*! Status of knowledge of peer ADSI capability */
839 /*! Callno of native bridge peer. (Valid if nonzero) */
840 unsigned short bridgecallno;
842 int pingid; /*!< Transmit PING request */
843 int lagid; /*!< Retransmit lag request */
844 int autoid; /*!< Auto hangup for Dialplan requestor */
845 int authid; /*!< Authentication rejection ID */
846 int authfail; /*!< Reason to report failure */
847 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
852 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
853 /*! variables inherited from the user definition */
854 struct ast_variable *vars;
855 /*! variables transmitted in a NEW packet */
856 struct ast_variable *iaxvars;
857 /*! last received remote rr */
858 struct iax_rr remote_rr;
859 /*! Current base time: (just for stats) */
861 /*! Dropped frame count: (just for stats) */
863 /*! received frame count: (just for stats) */
865 /*! Destroying this call initiated. */
866 int destroy_initiated;
867 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
868 unsigned char calltoken_ie_len;
869 /*! hold all signaling frames from the pbx thread until we have a destination callno */
871 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
872 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
875 struct signaling_queue_entry {
877 AST_LIST_ENTRY(signaling_queue_entry) next;
885 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
886 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
888 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
889 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
890 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
892 struct call_number_pool {
895 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
898 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
900 /*! table of available call numbers */
901 static struct call_number_pool callno_pool;
903 /*! table of available trunk call numbers */
904 static struct call_number_pool callno_pool_trunk;
907 * \brief a list of frames that may need to be retransmitted
909 * \note The contents of this list do not need to be explicitly destroyed
910 * on module unload. This is because all active calls are destroyed, and
911 * all frames in this queue will get destroyed as a part of that process.
913 * \note Contents protected by the iaxsl[] locks
915 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
917 static struct ast_taskprocessor *transmit_processor;
919 static int randomcalltokendata;
921 static time_t max_calltoken_delay = 10;
924 * This module will get much higher performance when doing a lot of
925 * user and peer lookups if the number of buckets is increased from 1.
926 * However, to maintain old behavior for Asterisk 1.4, these are set to
927 * 1 by default. When using multiple buckets, search order through these
928 * containers is considered random, so you will not be able to depend on
929 * the order the entires are specified in iax.conf for matching order. */
931 #define MAX_PEER_BUCKETS 17
933 #define MAX_PEER_BUCKETS 563
935 static struct ao2_container *peers;
937 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
938 static struct ao2_container *users;
940 /*! Table containing peercnt objects for every ip address consuming a callno */
941 static struct ao2_container *peercnts;
943 /*! Table containing custom callno limit rules for a range of ip addresses. */
944 static struct ao2_container *callno_limits;
946 /*! Table containing ip addresses not requiring calltoken validation */
947 static struct ao2_container *calltoken_ignores;
949 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
951 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
953 static uint16_t global_maxcallno;
955 /*! Total num of call numbers allowed to be allocated without calltoken validation */
956 static uint16_t global_maxcallno_nonval;
958 static uint16_t total_nonval_callno_used = 0;
960 /*! peer connection private, keeps track of all the call numbers
961 * consumed by a single ip address */
963 /*! ip address consuming call numbers */
964 struct ast_sockaddr addr;
965 /*! Number of call numbers currently used by this ip address */
967 /*! Max call numbers allowed for this ip address */
969 /*! Specifies whether limit is set by a registration or not, if so normal
970 * limit setting rules do not apply to this address. */
974 /*! used by both callno_limits and calltoken_ignores containers */
976 /*! ip address range for custom callno limit rule */
978 /*! callno limit for this ip address range, only used in callno_limits container */
980 /*! delete me marker for reloads */
985 /*! Extension exists */
986 CACHE_FLAG_EXISTS = (1 << 0),
987 /*! Extension is nonexistent */
988 CACHE_FLAG_NONEXISTENT = (1 << 1),
989 /*! Extension can exist */
990 CACHE_FLAG_CANEXIST = (1 << 2),
991 /*! Waiting to hear back response */
992 CACHE_FLAG_PENDING = (1 << 3),
994 CACHE_FLAG_TIMEOUT = (1 << 4),
995 /*! Request transmitted */
996 CACHE_FLAG_TRANSMITTED = (1 << 5),
998 CACHE_FLAG_UNKNOWN = (1 << 6),
1000 CACHE_FLAG_MATCHMORE = (1 << 7),
1003 struct iax2_dpcache {
1004 char peercontext[AST_MAX_CONTEXT];
1005 char exten[AST_MAX_EXTENSION];
1006 struct timeval orig;
1007 struct timeval expiry;
1009 unsigned short callno;
1011 AST_LIST_ENTRY(iax2_dpcache) cache_list;
1012 AST_LIST_ENTRY(iax2_dpcache) peer_list;
1015 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1017 static void reg_source_db(struct iax2_peer *p);
1018 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1019 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1021 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1022 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1023 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1025 enum iax2_thread_iostate {
1028 IAX_IOSTATE_PROCESSING,
1029 IAX_IOSTATE_SCHEDREADY,
1032 enum iax2_thread_type {
1033 IAX_THREAD_TYPE_POOL,
1034 IAX_THREAD_TYPE_DYNAMIC,
1037 struct iax2_pkt_buf {
1038 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1040 unsigned char buf[1];
1043 struct iax2_thread {
1044 AST_LIST_ENTRY(iax2_thread) list;
1045 enum iax2_thread_type type;
1046 enum iax2_thread_iostate iostate;
1047 #ifdef SCHED_MULTITHREADED
1048 void (*schedfunc)(const void *);
1049 const void *scheddata;
1051 #ifdef DEBUG_SCHED_MULTITHREAD
1057 struct ast_sockaddr ioaddr;
1058 unsigned char readbuf[4096];
1066 ast_mutex_t init_lock;
1067 ast_cond_t init_cond;
1068 /*! if this thread is processing a full frame,
1069 some information about that frame will be stored
1070 here, so we can avoid dispatching any more full
1071 frames for that callno to other threads */
1073 unsigned short callno;
1074 struct ast_sockaddr addr;
1078 /*! Queued up full frames for processing. If more full frames arrive for
1079 * a call which this thread is already processing a full frame for, they
1080 * are queued up here. */
1081 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1086 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1087 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1088 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1090 static void *iax2_process_thread(void *data);
1091 static void iax2_destroy(int callno);
1093 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1095 ast_mutex_lock(lock);
1096 ast_cond_signal(cond);
1097 ast_mutex_unlock(lock);
1101 * \brief an array of iax2 pvt structures
1103 * The container for active chan_iax2_pvt structures is implemented as an
1104 * array for extremely quick direct access to the correct pvt structure
1105 * based on the local call number. The local call number is used as the
1106 * index into the array where the associated pvt structure is stored.
1108 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1110 static ast_callid iax_pvt_callid_get(int callno)
1112 return iaxs[callno]->callid;
1115 static void iax_pvt_callid_set(int callno, ast_callid callid)
1117 iaxs[callno]->callid = callid;
1120 static void iax_pvt_callid_new(int callno)
1122 ast_callid callid = ast_create_callid();
1123 char buffer[AST_CALLID_BUFFER_LENGTH];
1124 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1125 iax_pvt_callid_set(callno, callid);
1129 * \brief Another container of iax2_pvt structures
1131 * Active IAX2 pvt structs are also stored in this container, if they are a part
1132 * of an active call where we know the remote side's call number. The reason
1133 * for this is that incoming media frames do not contain our call number. So,
1134 * instead of having to iterate the entire iaxs array, we use this container to
1135 * look up calls where the remote side is using a given call number.
1137 static struct ao2_container *iax_peercallno_pvts;
1140 * \brief chan_iax2_pvt structure locks
1142 * These locks are used when accessing a pvt structure in the iaxs array.
1143 * The index used here is the same as used in the iaxs array. It is the
1144 * local call number for the associated pvt struct.
1146 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1149 * * \brief Another container of iax2_pvt structures
1151 * Active IAX2 pvt stucts used during transfering a call are stored here.
1153 static struct ao2_container *iax_transfercallno_pvts;
1155 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1156 but keeps the division between trunked and non-trunked better. */
1157 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1159 /* Debug routines... */
1160 static struct ast_sockaddr debugaddr;
1162 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1165 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1166 (!ast_sockaddr_port(&debugaddr) ||
1167 ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1168 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1171 iax_showframe(f, fhi, rx, addr, datalen);
1174 iax_showframe(f, fhi, rx, addr, datalen);
1180 static void iax_debug_output(const char *data)
1183 ast_verbose("%s", data);
1186 static void iax_error_output(const char *data)
1188 ast_log(LOG_WARNING, "%s", data);
1191 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1196 va_start(args, fmt);
1197 vsnprintf(buf, sizeof(buf), fmt, args);
1200 ast_log(LOG_ERROR, "%s", buf);
1203 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1208 va_start(args, fmt);
1209 vsnprintf(buf, sizeof(buf), fmt, args);
1212 ast_log(LOG_WARNING, "%s", buf);
1215 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1220 va_start(args, fmt);
1221 vsnprintf(buf, sizeof(buf), fmt, args);
1224 ast_verbose("%s", buf);
1227 static int expire_registry(const void *data);
1228 static int iax2_answer(struct ast_channel *c);
1229 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1230 static int iax2_devicestate(const char *data);
1231 static int iax2_digit_begin(struct ast_channel *c, char digit);
1232 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1233 static int iax2_do_register(struct iax2_registry *reg);
1234 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1235 static int iax2_hangup(struct ast_channel *c);
1236 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1237 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1238 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1239 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1240 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1241 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1242 static int iax2_sendtext(struct ast_channel *c, const char *text);
1243 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1244 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1245 static int iax2_transfer(struct ast_channel *c, const char *dest);
1246 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1247 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1249 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1250 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1251 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1252 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1253 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1254 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1255 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);
1256 static struct ast_frame *iax2_read(struct ast_channel *c);
1257 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1258 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1259 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1260 static void *iax2_dup_variable_datastore(void *);
1261 static void prune_peers(void);
1262 static void prune_users(void);
1263 static void iax2_free_variable_datastore(void *);
1265 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1266 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1267 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1268 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1269 static void build_rand_pad(unsigned char *buf, ssize_t len);
1270 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1271 static int replace_callno(const void *obj);
1272 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1273 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1274 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1276 static struct ast_channel_tech iax2_tech = {
1278 .description = tdesc,
1279 .properties = AST_CHAN_TP_WANTSJITTER,
1280 .requester = iax2_request,
1281 .devicestate = iax2_devicestate,
1282 .send_digit_begin = iax2_digit_begin,
1283 .send_digit_end = iax2_digit_end,
1284 .send_text = iax2_sendtext,
1285 .send_image = iax2_sendimage,
1286 .send_html = iax2_sendhtml,
1288 .hangup = iax2_hangup,
1289 .answer = iax2_answer,
1291 .write = iax2_write,
1292 .write_video = iax2_write,
1293 .indicate = iax2_indicate,
1294 .setoption = iax2_setoption,
1295 .queryoption = iax2_queryoption,
1296 .transfer = iax2_transfer,
1297 .fixup = iax2_fixup,
1298 .func_channel_read = acf_channel_read,
1303 * \brief Obtain the owner channel lock if the owner exists.
1305 * \param callno IAX2 call id.
1307 * \note Assumes the iaxsl[callno] lock is already obtained.
1310 * IMPORTANT NOTE!!! Any time this function is used, even if
1311 * iaxs[callno] was valid before calling it, it may no longer be
1312 * valid after calling it. This function may unlock and lock
1313 * the mutex associated with this callno, meaning that another
1314 * thread may grab it and destroy the call.
1318 static void iax2_lock_owner(int callno)
1321 if (!iaxs[callno] || !iaxs[callno]->owner) {
1322 /* There is no owner lock to get. */
1325 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1326 /* We got the lock */
1329 /* Avoid deadlock by pausing and trying again */
1330 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1336 * \brief Check if a control subtype is allowed on the wire.
1338 * \param subtype Control frame subtype to check if allowed to/from the wire.
1340 * \retval non-zero if allowed.
1342 static int iax2_is_control_frame_allowed(int subtype)
1344 enum ast_control_frame_type control = subtype;
1348 * Note: If we compare the enumeration type, which does not have any
1349 * negative constants, the compiler may optimize this code away.
1350 * Therefore, we must perform an integer comparison here.
1352 if (subtype == -1) {
1356 /* Default to not allowing control frames to pass. */
1360 * The switch default is not present in order to take advantage
1361 * of the compiler complaining of a missing enum case.
1365 * These control frames make sense to send/receive across the link.
1367 case AST_CONTROL_HANGUP:
1368 case AST_CONTROL_RING:
1369 case AST_CONTROL_RINGING:
1370 case AST_CONTROL_ANSWER:
1371 case AST_CONTROL_BUSY:
1372 case AST_CONTROL_TAKEOFFHOOK:
1373 case AST_CONTROL_OFFHOOK:
1374 case AST_CONTROL_CONGESTION:
1375 case AST_CONTROL_FLASH:
1376 case AST_CONTROL_WINK:
1377 case AST_CONTROL_OPTION:
1378 case AST_CONTROL_RADIO_KEY:
1379 case AST_CONTROL_RADIO_UNKEY:
1380 case AST_CONTROL_PROGRESS:
1381 case AST_CONTROL_PROCEEDING:
1382 case AST_CONTROL_HOLD:
1383 case AST_CONTROL_UNHOLD:
1384 case AST_CONTROL_VIDUPDATE:
1385 case AST_CONTROL_CONNECTED_LINE:
1386 case AST_CONTROL_REDIRECTING:
1387 case AST_CONTROL_T38_PARAMETERS:
1388 case AST_CONTROL_AOC:
1389 case AST_CONTROL_INCOMPLETE:
1390 case AST_CONTROL_MCID:
1395 * These control frames do not make sense to send/receive across the link.
1397 case _XXX_AST_CONTROL_T38:
1398 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1399 case AST_CONTROL_SRCUPDATE:
1400 /* Across an IAX link the source is still the same. */
1401 case AST_CONTROL_TRANSFER:
1402 /* A success/fail status report from calling ast_transfer() on this machine. */
1403 case AST_CONTROL_CC:
1404 /* The payload contains pointers that are valid for the sending machine only. */
1405 case AST_CONTROL_SRCCHANGE:
1406 /* Across an IAX link the source is still the same. */
1407 case AST_CONTROL_READ_ACTION:
1408 /* The action can only be done by the sending machine. */
1409 case AST_CONTROL_END_OF_Q:
1410 /* This frame would cause the call to unexpectedly hangup. */
1411 case AST_CONTROL_UPDATE_RTP_PEER:
1412 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1413 case AST_CONTROL_PVT_CAUSE_CODE:
1414 /* Intended only for the sending machine's local channel structure. */
1415 case AST_CONTROL_MASQUERADE_NOTIFY:
1416 /* Intended only for masquerades when calling ast_indicate_data(). */
1417 case AST_CONTROL_STREAM_STOP:
1418 case AST_CONTROL_STREAM_SUSPEND:
1419 case AST_CONTROL_STREAM_RESTART:
1420 case AST_CONTROL_STREAM_REVERSE:
1421 case AST_CONTROL_STREAM_FORWARD:
1422 /* None of these playback stream control frames should go across the link. */
1423 case AST_CONTROL_RECORD_CANCEL:
1424 case AST_CONTROL_RECORD_STOP:
1425 case AST_CONTROL_RECORD_SUSPEND:
1426 case AST_CONTROL_RECORD_MUTE:
1427 /* None of these media recording control frames should go across the link. */
1433 static void network_change_stasis_subscribe(void)
1435 if (!network_change_sub) {
1436 network_change_sub = stasis_subscribe(ast_system_topic(),
1437 network_change_stasis_cb, NULL);
1441 static void network_change_stasis_unsubscribe(void)
1443 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1446 static void acl_change_stasis_subscribe(void)
1448 if (!acl_change_sub) {
1449 acl_change_sub = stasis_subscribe(ast_security_topic(),
1450 acl_change_stasis_cb, NULL);
1454 static void acl_change_stasis_unsubscribe(void)
1456 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1459 static int network_change_sched_cb(const void *data)
1461 struct iax2_registry *reg;
1462 network_change_sched_id = -1;
1463 AST_LIST_LOCK(®istrations);
1464 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1465 iax2_do_register(reg);
1467 AST_LIST_UNLOCK(®istrations);
1472 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1473 struct stasis_message *message)
1475 /* This callback is only concerned with network change messages from the system topic. */
1476 if (stasis_message_type(message) != ast_network_change_type()) {
1480 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1481 if (network_change_sched_id == -1) {
1482 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1486 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1487 struct stasis_message *message)
1489 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1493 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1497 static const struct ast_datastore_info iax2_variable_datastore_info = {
1498 .type = "IAX2_VARIABLE",
1499 .duplicate = iax2_dup_variable_datastore,
1500 .destroy = iax2_free_variable_datastore,
1503 static void *iax2_dup_variable_datastore(void *old)
1505 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1506 struct ast_var_t *oldvar, *newvar;
1508 newlist = ast_calloc(sizeof(*newlist), 1);
1510 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1514 AST_LIST_HEAD_INIT(newlist);
1515 AST_LIST_LOCK(oldlist);
1516 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1517 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1519 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1521 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1523 AST_LIST_UNLOCK(oldlist);
1527 static void iax2_free_variable_datastore(void *old)
1529 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1530 struct ast_var_t *oldvar;
1532 AST_LIST_LOCK(oldlist);
1533 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1536 AST_LIST_UNLOCK(oldlist);
1537 AST_LIST_HEAD_DESTROY(oldlist);
1542 /* WARNING: insert_idle_thread should only ever be called within the
1543 * context of an iax2_process_thread() thread.
1545 static void insert_idle_thread(struct iax2_thread *thread)
1547 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1548 AST_LIST_LOCK(&dynamic_list);
1549 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1550 AST_LIST_UNLOCK(&dynamic_list);
1552 AST_LIST_LOCK(&idle_list);
1553 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1554 AST_LIST_UNLOCK(&idle_list);
1560 static struct iax2_thread *find_idle_thread(void)
1562 struct iax2_thread *thread = NULL;
1564 /* Pop the head of the idle list off */
1565 AST_LIST_LOCK(&idle_list);
1566 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1567 AST_LIST_UNLOCK(&idle_list);
1569 /* If we popped a thread off the idle list, just return it */
1571 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1575 /* Pop the head of the dynamic list off */
1576 AST_LIST_LOCK(&dynamic_list);
1577 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1578 AST_LIST_UNLOCK(&dynamic_list);
1580 /* If we popped a thread off the dynamic list, just return it */
1582 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1586 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1587 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1590 /* Set default values */
1591 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1592 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1593 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1595 /* Initialize lock and condition */
1596 ast_mutex_init(&thread->lock);
1597 ast_cond_init(&thread->cond, NULL);
1598 ast_mutex_init(&thread->init_lock);
1599 ast_cond_init(&thread->init_cond, NULL);
1600 ast_mutex_lock(&thread->init_lock);
1602 /* Create thread and send it on it's way */
1603 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1604 ast_cond_destroy(&thread->cond);
1605 ast_mutex_destroy(&thread->lock);
1606 ast_mutex_unlock(&thread->init_lock);
1607 ast_cond_destroy(&thread->init_cond);
1608 ast_mutex_destroy(&thread->init_lock);
1613 /* this thread is not processing a full frame (since it is idle),
1614 so ensure that the field for the full frame call number is empty */
1615 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1617 /* Wait for the thread to be ready before returning it to the caller */
1618 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1620 /* Done with init_lock */
1621 ast_mutex_unlock(&thread->init_lock);
1626 #ifdef SCHED_MULTITHREADED
1627 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1629 struct iax2_thread *thread;
1630 static time_t lasterror;
1633 thread = find_idle_thread();
1634 if (thread != NULL) {
1635 thread->schedfunc = func;
1636 thread->scheddata = data;
1637 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1638 #ifdef DEBUG_SCHED_MULTITHREAD
1639 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1641 signal_condition(&thread->lock, &thread->cond);
1645 if (t != lasterror) {
1647 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1652 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1655 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1656 ast_sched_cb callback, const void *data)
1658 return ast_sched_replace(id, con, when, callback, data);
1661 static int iax2_sched_add(struct ast_sched_context *con, int when,
1662 ast_sched_cb callback, const void *data)
1664 return ast_sched_add(con, when, callback, data);
1668 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1669 * \param callno Call number to lock.
1670 * \return 0 If call disappeared or has ongoing hangup procedure. 1 If call found and mutex is locked.
1672 static int iax2_lock_callno_unless_destroyed(int callno)
1674 ast_mutex_lock(&iaxsl[callno]);
1676 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1677 * or destroy initiated (in middle of hang up procedure. */
1678 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1679 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1680 ast_mutex_unlock(&iaxsl[callno]);
1684 /* Lock acquired, and callno is alive and kicking. */
1688 static int send_ping(const void *data);
1690 static void __send_ping(const void *data)
1692 int callno = PTR_TO_CALLNO(data);
1694 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1695 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1699 /* Mark pingid as invalid scheduler id. */
1700 iaxs[callno]->pingid = -1;
1702 /* callno is now locked. */
1703 if (iaxs[callno]->peercallno) {
1704 /* Send PING packet. */
1705 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1707 /* Schedule sending next ping. */
1708 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1711 ast_mutex_unlock(&iaxsl[callno]);
1714 static int send_ping(const void *data)
1716 #ifdef SCHED_MULTITHREADED
1717 if (schedule_action(__send_ping, data))
1724 static void encmethods_to_str(int e, struct ast_str **buf)
1726 ast_str_set(buf, 0, "(");
1727 if (e & IAX_ENCRYPT_AES128) {
1728 ast_str_append(buf, 0, "aes128");
1730 if (e & IAX_ENCRYPT_KEYROTATE) {
1731 ast_str_append(buf, 0, ",keyrotate");
1733 if (ast_str_strlen(*buf) > 1) {
1734 ast_str_append(buf, 0, ")");
1736 ast_str_set(buf, 0, "No");
1740 static int get_encrypt_methods(const char *s)
1743 if (!strcasecmp(s, "aes128"))
1744 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1745 else if (ast_true(s))
1746 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1752 static int send_lagrq(const void *data);
1754 static void __send_lagrq(const void *data)
1756 int callno = PTR_TO_CALLNO(data);
1758 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1759 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1763 /* Mark lagid as invalid scheduler id. */
1764 iaxs[callno]->lagid = -1;
1766 /* callno is now locked. */
1767 if (iaxs[callno]->peercallno) {
1768 /* Send LAGRQ packet. */
1769 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1771 /* Schedule sending next lagrq. */
1772 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1775 ast_mutex_unlock(&iaxsl[callno]);
1778 static int send_lagrq(const void *data)
1780 #ifdef SCHED_MULTITHREADED
1781 if (schedule_action(__send_lagrq, data))
1787 static unsigned char compress_subclass(iax2_format subclass)
1791 /* If it's 64 or smaller, just return it */
1792 if (subclass < IAX_FLAG_SC_LOG)
1794 /* Otherwise find its power */
1795 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1796 if (subclass & (1LL << x)) {
1798 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1804 return power | IAX_FLAG_SC_LOG;
1807 static iax2_format uncompress_subclass(unsigned char csub)
1809 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1810 if (csub & IAX_FLAG_SC_LOG) {
1811 /* special case for 'compressed' -1 */
1815 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1821 static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1824 struct ast_format *found_format = NULL;
1826 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1827 struct ast_format *pref_format;
1828 uint64_t pref_bitfield;
1830 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1831 if (!pref_bitfield) {
1835 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1837 /* The bitfield is not associated with any format. */
1840 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1846 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1847 return found_format;
1850 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1851 ao2_cleanup(found_format);
1855 static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
1857 struct ast_format_cap *cap;
1858 struct ast_format *tmpfmt;
1859 iax2_format format = 0;
1861 if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1862 iax2_format_compatibility_bitfield2cap(formats, cap);
1863 tmpfmt = codec_choose_from_prefs(pref, cap);
1869 format = ast_format_compatibility_format2bitfield(tmpfmt);
1870 ao2_ref(tmpfmt, -1);
1877 const char *iax2_getformatname(iax2_format format)
1879 struct ast_format *tmpfmt;
1881 tmpfmt = ast_format_compatibility_bitfield2format(format);
1886 return ast_format_get_name(tmpfmt);
1889 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1891 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1896 iax2_format_compatibility_bitfield2cap(format, cap);
1897 ast_format_cap_get_names(cap, codec_buf);
1900 return ast_str_buffer(*codec_buf);
1903 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1906 struct ast_format_cap *cap;
1908 /* We want to add the formats to the cap in the preferred order */
1909 cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1910 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1915 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1917 /* Adjust formats bitfield and pref list to match. */
1918 *formats = iax2_format_compatibility_cap2bitfield(cap);
1919 iax2_codec_pref_remove_missing(pref, *formats);
1921 for (i = 0; i < ast_format_cap_count(cap); i++) {
1922 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1924 iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
1933 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1936 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1940 iax2_format_compatibility_bitfield2cap(formats, cap);
1941 res = ast_data_add_codecs(root, node_name, cap);
1947 * \note The only member of the peer passed here guaranteed to be set is the name field
1949 static int peer_hash_cb(const void *obj, const int flags)
1951 const struct iax2_peer *peer = obj;
1952 const char *name = obj;
1954 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1958 * \note The only member of the peer passed here guaranteed to be set is the name field
1960 static int peer_cmp_cb(void *obj, void *arg, int flags)
1962 struct iax2_peer *peer = obj, *peer2 = arg;
1963 const char *name = arg;
1965 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1966 CMP_MATCH | CMP_STOP : 0;
1970 * \note The only member of the user passed here guaranteed to be set is the name field
1972 static int user_hash_cb(const void *obj, const int flags)
1974 const struct iax2_user *user = obj;
1975 const char *name = obj;
1977 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1981 * \note The only member of the user passed here guaranteed to be set is the name field
1983 static int user_cmp_cb(void *obj, void *arg, int flags)
1985 struct iax2_user *user = obj, *user2 = arg;
1986 const char *name = arg;
1988 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1989 CMP_MATCH | CMP_STOP : 0;
1993 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1994 * so do not call it with a pvt lock held.
1996 static struct iax2_peer *find_peer(const char *name, int realtime)
1998 struct iax2_peer *peer = NULL;
2000 peer = ao2_find(peers, name, OBJ_KEY);
2002 /* Now go for realtime if applicable */
2003 if (!peer && realtime) {
2004 peer = realtime_peer(name, NULL);
2009 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2015 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2021 static struct iax2_user *find_user(const char *name)
2023 return ao2_find(users, name, OBJ_KEY);
2026 static inline struct iax2_user *user_unref(struct iax2_user *user)
2032 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2034 struct iax2_peer *peer = NULL;
2036 struct ao2_iterator i;
2038 i = ao2_iterator_init(peers, 0);
2039 while ((peer = ao2_iterator_next(&i))) {
2041 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2042 ast_copy_string(host, peer->name, len);
2049 ao2_iterator_destroy(&i);
2052 peer = realtime_peer(NULL, &addr);
2054 ast_copy_string(host, peer->name, len);
2063 /* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2064 static int iax2_delete_from_sched(const void* data)
2066 int sched_id = (int)(long)data;
2068 AST_SCHED_DEL(sched, sched_id);
2073 /*!\note Assumes the lock on the pvt is already held, when
2074 * iax2_destroy_helper() is called. */
2075 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2077 /* Decrement AUTHREQ count if needed */
2078 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2079 struct iax2_user *user;
2081 user = ao2_find(users, pvt->username, OBJ_KEY);
2083 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2087 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2091 /* Mark call destroy initiated flag. */
2092 pvt->destroy_initiated = 1;
2095 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2096 * Already running tasks will be terminated because of destroy_initiated.
2098 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2099 * it leads to a deadlock between the scheduler thread callback locking
2100 * the callno mutex and this thread which holds the callno mutex one or
2101 * more times. It is better to have another thread delete the scheduled
2102 * callbacks which doesn't lock the callno mutex.
2104 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2105 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2110 AST_SCHED_DEL(sched, pvt->autoid);
2111 AST_SCHED_DEL(sched, pvt->authid);
2112 AST_SCHED_DEL(sched, pvt->initid);
2113 AST_SCHED_DEL(sched, pvt->jbid);
2114 AST_SCHED_DEL(sched, pvt->keyrotateid);
2117 static void iax2_frame_free(struct iax_frame *fr)
2119 AST_SCHED_DEL(sched, fr->retrans);
2123 static int scheduled_destroy(const void *vid)
2125 unsigned short callno = PTR_TO_CALLNO(vid);
2126 ast_mutex_lock(&iaxsl[callno]);
2128 ast_debug(1, "Really destroying %d now...\n", callno);
2129 iax2_destroy(callno);
2131 ast_mutex_unlock(&iaxsl[callno]);
2135 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2138 ast_free(s->f.data.ptr);
2143 /*! \brief This function must be called once we are sure the other side has
2144 * given us a call number. All signaling is held here until that point. */
2145 static void send_signaling(struct chan_iax2_pvt *pvt)
2147 struct signaling_queue_entry *s = NULL;
2149 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2150 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2151 free_signaling_queue_entry(s);
2153 pvt->hold_signaling = 0;
2156 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2157 * we have received a destination call number. */
2158 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2160 struct signaling_queue_entry *qe;
2162 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2163 return 1; /* do not queue this frame */
2164 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2165 return -1; /* out of memory */
2168 /* copy ast_frame into our queue entry */
2170 if (qe->f.datalen) {
2171 /* if there is data in this frame copy it over as well */
2172 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2173 free_signaling_queue_entry(qe);
2176 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2178 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2183 static void pvt_destructor(void *obj)
2185 struct chan_iax2_pvt *pvt = obj;
2186 struct iax_frame *cur = NULL;
2187 struct signaling_queue_entry *s = NULL;
2189 ast_mutex_lock(&iaxsl[pvt->callno]);
2191 iax2_destroy_helper(pvt);
2193 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2194 pvt->callno_entry = 0;
2197 ast_set_flag64(pvt, IAX_ALREADYGONE);
2199 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2200 /* Cancel any pending transmissions */
2204 ast_mutex_unlock(&iaxsl[pvt->callno]);
2206 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2207 free_signaling_queue_entry(s);
2211 pvt->reg->callno = 0;
2217 ast_variables_destroy(pvt->vars);
2221 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2222 iax2_frame_free(frame.data);
2225 jb_destroy(pvt->jb);
2226 ast_string_field_free_memory(pvt);
2230 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2232 struct chan_iax2_pvt *tmp;
2235 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2239 if (ast_string_field_init(tmp, 32)) {
2245 tmp->prefs = prefs_global;
2251 tmp->keyrotateid = -1;
2253 ast_string_field_set(tmp,exten, "s");
2254 ast_string_field_set(tmp,host, host);
2258 jbconf.max_jitterbuf = maxjitterbuffer;
2259 jbconf.resync_threshold = resyncthreshold;
2260 jbconf.max_contig_interp = maxjitterinterps;
2261 jbconf.target_extra = jittertargetextra;
2262 jb_setconf(tmp->jb,&jbconf);
2264 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2266 tmp->hold_signaling = 1;
2267 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2272 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2274 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2276 size_t afdatalen = new->afdatalen;
2277 memcpy(new, fr, sizeof(*new));
2278 iax_frame_wrap(new, &fr->af);
2279 new->afdatalen = afdatalen;
2282 new->direction = DIRECTION_INGRESS;
2287 /* keep these defined in this order. They are used in find_callno to
2288 * determine whether or not a new call number should be allowed. */
2290 /* do not allow a new call number, only search ones in use for match */
2292 /* search for match first, then allow a new one to be allocated */
2294 /* do not search for match, force a new call number */
2296 /* do not search for match, force a new call number. Signifies call number
2297 * has been calltoken validated */
2298 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2301 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2303 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2304 /* This is the main host */
2305 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2306 (check_dcallno ? dcallno == cur->callno : 1) ) {
2307 /* That's us. Be sure we keep track of the peer call number */
2311 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2312 /* We're transferring */
2313 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2319 static int make_trunk(unsigned short callno, int locked)
2324 if (iaxs[callno]->oseqno) {
2325 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2328 if (callno >= TRUNK_CALL_START) {
2329 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2333 if (get_unused_callno(
2335 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2337 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2341 x = CALLNO_ENTRY_GET_CALLNO(entry);
2342 ast_mutex_lock(&iaxsl[x]);
2345 * \note We delete these before switching the slot, because if
2346 * they fire in the meantime, they will generate a warning.
2348 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2349 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2350 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2351 iaxs[x] = iaxs[callno];
2352 iaxs[x]->callno = x;
2354 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2355 * before assigning the new one */
2356 if (iaxs[x]->callno_entry) {
2359 MIN_REUSE_TIME * 1000,
2361 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2364 iaxs[x]->callno_entry = entry;
2366 iaxs[callno] = NULL;
2367 /* Update the two timers that should have been started */
2368 iaxs[x]->pingid = iax2_sched_add(sched,
2369 ping_time * 1000, send_ping, (void *)(long)x);
2370 iaxs[x]->lagid = iax2_sched_add(sched,
2371 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2374 ast_mutex_unlock(&iaxsl[callno]);
2377 ast_mutex_unlock(&iaxsl[x]);
2379 /* We moved this call from a non-trunked to a trunked call */
2380 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2385 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2387 if (!pvt->transfercallno) {
2388 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2392 ao2_link(iax_transfercallno_pvts, pvt);
2395 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2397 if (!pvt->transfercallno) {
2398 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2402 ao2_unlink(iax_transfercallno_pvts, pvt);
2404 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2406 if (!pvt->peercallno) {
2407 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2411 ao2_link(iax_peercallno_pvts, pvt);
2414 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2416 if (!pvt->peercallno) {
2417 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2421 ao2_unlink(iax_peercallno_pvts, pvt);
2424 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2426 struct addr_range *lim = obj;
2431 static int addr_range_hash_cb(const void *obj, const int flags)
2433 const struct addr_range *lim = obj;
2434 return abs(ast_sockaddr_hash(&lim->ha.addr));
2437 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2439 struct addr_range *lim1 = obj, *lim2 = arg;
2440 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2441 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2442 CMP_MATCH | CMP_STOP : 0;
2445 static int peercnt_hash_cb(const void *obj, const int flags)
2447 const struct peercnt *peercnt = obj;
2449 if (ast_sockaddr_isnull(&peercnt->addr)) {
2452 return ast_sockaddr_hash(&peercnt->addr);
2455 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2457 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2458 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2461 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2463 struct addr_range *addr_range = obj;
2464 struct ast_sockaddr *addr = arg;
2465 struct ast_sockaddr tmp_addr;
2467 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2469 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2470 return CMP_MATCH | CMP_STOP;
2478 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2480 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2482 struct addr_range *addr_range;
2483 struct iax2_peer *peer = NULL;
2484 struct iax2_user *user = NULL;
2485 /* if no username is given, check for guest accounts */
2486 const char *find = S_OR(name, "guest");
2487 int res = 1; /* required by default */
2489 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2490 /* There are only two cases in which calltoken validation is not required.
2491 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2492 * the peer definition has not set the requirecalltoken option.
2493 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2496 /* ----- Case 1 ----- */
2497 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2498 ao2_ref(addr_range, -1);
2502 /* ----- Case 2 ----- */
2503 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2504 calltoken_required = user->calltoken_required;
2505 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2506 calltoken_required = user->calltoken_required;
2507 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2508 calltoken_required = peer->calltoken_required;
2509 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2510 calltoken_required = peer->calltoken_required;
2520 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);
2521 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2522 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2532 * \brief set peercnt callno limit.
2535 * First looks in custom definitions. If not found, global limit
2536 * is used. Entries marked as reg already have
2537 * a custom limit set by a registration and are not modified.
2539 static void set_peercnt_limit(struct peercnt *peercnt)
2541 uint16_t limit = global_maxcallno;
2542 struct addr_range *addr_range;
2543 struct ast_sockaddr addr;
2545 ast_sockaddr_copy(&addr, &peercnt->addr);
2547 if (peercnt->reg && peercnt->limit) {
2548 return; /* this peercnt has a custom limit set by a registration */
2551 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2552 limit = addr_range->limit;
2553 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2554 ao2_ref(addr_range, -1);
2557 peercnt->limit = limit;
2562 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2564 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2566 struct peercnt *peercnt = obj;
2568 set_peercnt_limit(peercnt);
2569 ast_debug(1, "Reset limits for peercnts table\n");
2576 * \brief returns match if delme is set.
2578 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2580 struct addr_range *addr_range = obj;
2582 return addr_range->delme ? CMP_MATCH : 0;
2587 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2589 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2591 /* this function turns off and on custom callno limits set by peer registration */
2592 struct peercnt *peercnt;
2595 ast_sockaddr_copy(&tmp.addr, sockaddr);
2597 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2600 peercnt->limit = limit;
2602 set_peercnt_limit(peercnt);
2604 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2605 ao2_ref(peercnt, -1); /* decrement ref from find */
2611 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2613 * \details First searches for the address in the peercnts table. If found
2614 * the current count is incremented. If not found a new peercnt is allocated
2615 * and linked into the peercnts table with a call number count of 1.
2617 static int peercnt_add(struct ast_sockaddr *addr)
2619 struct peercnt *peercnt;
2623 ast_sockaddr_copy(&tmp.addr, addr);
2625 /* Reasoning for peercnts container lock: Two identical ip addresses
2626 * could be added by different threads at the "same time". Without the container
2627 * lock, both threads could alloc space for the same object and attempt
2628 * to link to table. With the lock, one would create the object and link
2629 * to table while the other would find the already created peercnt object
2630 * rather than creating a new one. */
2632 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2634 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2636 /* create and set defaults */
2637 ast_sockaddr_copy(&peercnt->addr, addr);
2638 set_peercnt_limit(peercnt);
2639 /* guarantees it does not go away after unlocking table
2640 * ao2_find automatically adds this */
2641 ao2_link(peercnts, peercnt);
2643 ao2_unlock(peercnts);
2647 /* check to see if the address has hit its callno limit. If not increment cur. */
2648 if (peercnt->limit > peercnt->cur) {
2650 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2651 } else { /* max num call numbers for this peer has been reached! */
2652 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2656 /* clean up locks and ref count */
2657 ao2_unlock(peercnt);
2658 ao2_unlock(peercnts);
2659 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2666 * \brief decrements a peercnts table entry
2668 static void peercnt_remove(struct peercnt *peercnt)
2670 struct ast_sockaddr addr;
2672 ast_sockaddr_copy(&addr, &peercnt->addr);
2675 * Container locked here since peercnt may be unlinked from
2676 * list. If left unlocked, peercnt_add could try and grab this
2677 * entry from the table and modify it at the "same time" this
2678 * thread attemps to unlink it.
2682 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2683 /* if this was the last connection from the peer remove it from table */
2684 if (peercnt->cur == 0) {
2685 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2687 ao2_unlock(peercnts);
2692 * \brief called by scheduler to decrement object
2694 static int peercnt_remove_cb(const void *obj)
2696 struct peercnt *peercnt = (struct peercnt *) obj;
2698 peercnt_remove(peercnt);
2699 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2706 * \brief decrements peercnts connection count, finds by addr
2708 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2710 struct peercnt *peercnt;
2713 ast_sockaddr_copy(&tmp.addr, addr);
2715 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2716 peercnt_remove(peercnt);
2717 ao2_ref(peercnt, -1); /* decrement ref from find */
2724 * \brief Create callno_limit entry based on configuration
2726 static void build_callno_limits(struct ast_variable *v)
2728 struct addr_range *addr_range = NULL;
2729 struct addr_range tmp;
2735 for (; v; v = v->next) {
2739 ha = ast_append_ha("permit", v->name, NULL, &error);
2741 /* check for valid config information */
2743 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2745 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2746 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2751 ast_copy_ha(ha, &tmp.ha);
2752 /* find or create the addr_range */
2753 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2754 ao2_lock(addr_range);
2756 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2758 return; /* out of memory */
2761 /* copy over config data into addr_range object */
2762 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2763 ast_free_ha(ha); /* cleanup the tmp ha */
2764 addr_range->limit = limit;
2765 addr_range->delme = 0;
2769 ao2_unlock(addr_range);
2771 ao2_link(callno_limits, addr_range);
2773 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2779 * \brief Create calltoken_ignores entry based on configuration
2781 static int add_calltoken_ignore(const char *addr)
2783 struct addr_range tmp;
2784 struct addr_range *addr_range = NULL;
2785 struct ast_ha *ha = NULL;
2788 if (ast_strlen_zero(addr)) {
2789 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2793 ha = ast_append_ha("permit", addr, NULL, &error);
2795 /* check for valid config information */
2797 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2801 ast_copy_ha(ha, &tmp.ha);
2802 /* find or create the addr_range */
2803 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2804 ao2_lock(addr_range);
2805 addr_range->delme = 0;
2806 ao2_unlock(addr_range);
2807 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2808 /* copy over config data into addr_range object */
2809 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2810 ao2_link(calltoken_ignores, addr_range);
2817 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2822 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2824 struct ao2_iterator i;
2825 struct peercnt *peercnt;
2826 struct ast_sockaddr addr;
2831 e->command = "iax2 show callnumber usage";
2833 "Usage: iax2 show callnumber usage [IP address]\n"
2834 " Shows current IP addresses which are consuming iax2 call numbers\n";
2839 if (a->argc < 4 || a->argc > 5)
2840 return CLI_SHOWUSAGE;
2843 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2846 i = ao2_iterator_init(peercnts, 0);
2847 while ((peercnt = ao2_iterator_next(&i))) {
2848 ast_sockaddr_copy(&addr, &peercnt->addr);
2851 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2852 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2853 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2854 ao2_ref(peercnt, -1);
2859 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2861 ao2_ref(peercnt, -1);
2863 ao2_iterator_destroy(&i);
2866 size_t pool_avail = callno_pool.available;
2867 size_t trunk_pool_avail = callno_pool_trunk.available;
2869 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2870 "Non-CallToken Validated Callno Used: %d\n",
2871 global_maxcallno_nonval,
2872 total_nonval_callno_used);
2874 ast_cli(a->fd, "Total Available Callno: %zu\n"
2875 "Regular Callno Available: %zu\n"
2876 "Trunk Callno Available: %zu\n",
2877 pool_avail + trunk_pool_avail,
2880 } else if (a->argc == 5 && !found) {
2881 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2891 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2893 struct call_number_pool *pool = NULL;
2898 case CALLNO_TYPE_NORMAL:
2899 pool = &callno_pool;
2901 case CALLNO_TYPE_TRUNK:
2902 pool = &callno_pool_trunk;
2909 /* If we fail, make sure this has a defined value */
2912 /* We lock here primarily to ensure thread safety of the
2913 * total_nonval_callno_used check and increment */
2914 ast_mutex_lock(&callno_pool_lock);
2916 /* Bail out if we don't have any available call numbers */
2917 if (!pool->available) {
2918 ast_log(LOG_WARNING, "Out of call numbers\n");
2919 ast_mutex_unlock(&callno_pool_lock);
2923 /* Only a certain number of non-validated call numbers should be allocated.
2924 * If there ever is an attack, this separates the calltoken validating users
2925 * from the non-calltoken validating users. */
2926 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2927 ast_log(LOG_WARNING,
2928 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2929 total_nonval_callno_used,
2930 global_maxcallno_nonval);
2931 ast_mutex_unlock(&callno_pool_lock);
2935 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2936 * available call numbers. The array of call numbers begins as an ordered
2937 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2938 * - let's call that x. When a call number is needed we pick a random index
2939 * into the array between 0 and x and use that as our call number. In a
2940 * typical FYD shuffle, we would swap the value that we are extracting with
2941 * the number at x, but in our case we swap and don't touch the value at x
2942 * because it is effectively invisible. We rely on the rest of the IAX2 core
2943 * to return the number to us at some point. Finally, we decrement x by 1
2944 * which establishes our new unused range.
2946 * When numbers are returned to the pool, we put them just past x and bump x
2947 * by 1 so that this number is now available for re-use. */
2949 choice = ast_random() % pool->available;
2951 *entry = pool->numbers[choice];
2952 swap = pool->numbers[pool->available - 1];
2954 pool->numbers[choice] = swap;
2958 CALLNO_ENTRY_SET_VALIDATED(*entry);
2960 total_nonval_callno_used++;
2963 ast_mutex_unlock(&callno_pool_lock);
2968 static int replace_callno(const void *obj)
2970 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2971 struct call_number_pool *pool;
2973 /* We lock here primarily to ensure thread safety of the
2974 * total_nonval_callno_used check and decrement */
2975 ast_mutex_lock(&callno_pool_lock);
2977 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2978 if (total_nonval_callno_used) {
2979 total_nonval_callno_used--;
2982 "Attempted to decrement total non calltoken validated "
2983 "callnumbers below zero. Callno is: %d\n",
2984 CALLNO_ENTRY_GET_CALLNO(entry));
2988 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2989 pool = &callno_pool;
2991 pool = &callno_pool_trunk;
2994 ast_assert(pool->capacity > pool->available);
2996 /* This clears the validated flag */
2997 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2999 pool->numbers[pool->available] = entry;
3002 ast_mutex_unlock(&callno_pool_lock);
3007 static int create_callno_pools(void)
3011 callno_pool.available = callno_pool_trunk.available = 0;
3013 /* We start at 2. 0 and 1 are reserved. */
3014 for (i = 2; i < TRUNK_CALL_START; i++) {
3015 callno_pool.numbers[callno_pool.available] = i;
3016 callno_pool.available++;
3019 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3020 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
3021 callno_pool_trunk.available++;
3024 callno_pool.capacity = callno_pool.available;
3025 callno_pool_trunk.capacity = callno_pool_trunk.available;
3027 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
3034 * \brief Schedules delayed removal of iax2_pvt call number data
3036 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3037 * available again, and the address from the previous connection must be decremented
3038 * from the peercnts table. This function schedules these operations to take place.
3040 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3043 struct peercnt *peercnt;
3046 ast_sockaddr_copy(&tmp.addr, addr);
3048 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3049 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3050 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3051 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3053 ao2_ref(peercnt, -1);
3059 MIN_REUSE_TIME * 1000,
3061 CALLNO_ENTRY_TO_PTR(entry));
3066 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3068 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3071 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3073 if (frametype != AST_FRAME_IAX) {
3077 case IAX_COMMAND_NEW:
3078 case IAX_COMMAND_REGREQ:
3079 case IAX_COMMAND_FWDOWNL:
3080 case IAX_COMMAND_REGREL:
3082 case IAX_COMMAND_POKE:
3092 * \note Calling this function while holding another pvt lock can cause a deadlock.
3094 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3098 /* this call is calltoken validated as long as it is either NEW_FORCE
3099 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3100 int validated = (new > NEW_ALLOW) ? 1 : 0;
3103 if (new <= NEW_ALLOW) {
3105 struct chan_iax2_pvt *pvt;
3106 struct chan_iax2_pvt tmp_pvt = {
3108 .peercallno = callno,
3109 .transfercallno = callno,
3111 .frames_received = check_dcallno,
3114 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3115 /* this works for finding normal call numbers not involving transfering */
3116 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3117 if (return_locked) {
3118 ast_mutex_lock(&iaxsl[pvt->callno]);
3125 /* this searches for transfer call numbers that might not get caught otherwise */
3126 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3127 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3128 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3129 if (return_locked) {
3130 ast_mutex_lock(&iaxsl[pvt->callno]);
3138 /* This will occur on the first response to a message that we initiated,
3139 * such as a PING. */
3141 ast_mutex_lock(&iaxsl[dcallno]);
3143 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3144 iaxs[dcallno]->peercallno = callno;
3146 store_by_peercallno(iaxs[dcallno]);
3147 if (!res || !return_locked) {
3148 ast_mutex_unlock(&iaxsl[dcallno]);
3153 ast_mutex_unlock(&iaxsl[dcallno]);
3156 if (!res && (new >= NEW_ALLOW)) {
3159 /* It may seem odd that we look through the peer list for a name for
3160 * this *incoming* call. Well, it is weird. However, users don't
3161 * have an IP address/port number that we can match against. So,
3162 * this is just checking for a peer that has that IP/port and
3163 * assuming that we have a user of the same name. This isn't always
3164 * correct, but it will be changed if needed after authentication. */
3165 if (!iax2_getpeername(*addr, host, sizeof(host)))
3166 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3168 if (peercnt_add(addr)) {
3169 /* This address has hit its callnumber limit. When the limit
3170 * is reached, the connection is not added to the peercnts table.*/
3174 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3175 /* since we ran out of space, remove the peercnt
3176 * entry we added earlier */
3177 peercnt_remove_by_addr(addr);
3178 ast_log(LOG_WARNING, "No more space\n");
3181 x = CALLNO_ENTRY_GET_CALLNO(entry);
3182 ast_mutex_lock(&iaxsl[x]);
3184 iaxs[x] = new_iax(addr, host);
3187 ast_debug(1, "Creating new call structure %d\n", x);
3188 iaxs[x]->callno_entry = entry;
3189 iaxs[x]->sockfd = sockfd;
3190 ast_sockaddr_copy(&iaxs[x]->addr, addr);
3191 iaxs[x]->peercallno = callno;
3192 iaxs[x]->callno = x;
3193 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3194 iaxs[x]->expiry = min_reg_expire;
3195 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3196 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3197 iaxs[x]->amaflags = amaflags;
3198 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3199 ast_string_field_set(iaxs[x], accountcode, accountcode);
3200 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3201 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3202 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3204 if (iaxs[x]->peercallno) {
3205 store_by_peercallno(iaxs[x]);
3208 ast_log(LOG_WARNING, "Out of resources\n");
3209 ast_mutex_unlock(&iaxsl[x]);
3210 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3214 ast_mutex_unlock(&iaxsl[x]);
3220 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3221 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3224 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3226 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3230 * \brief Queue a frame to a call's owning asterisk channel
3232 * \pre This function assumes that iaxsl[callno] is locked when called.
3234 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3235 * was valid before calling it, it may no longer be valid after calling it.
3236 * This function may unlock and lock the mutex associated with this callno,
3237 * meaning that another thread may grab it and destroy the call.
3239 static int iax2_queue_frame(int callno, struct ast_frame *f)
3241 iax2_lock_owner(callno);
3242 if (iaxs[callno] && iaxs[callno]->owner) {
3243 ast_queue_frame(iaxs[callno]->owner, f);
3244 ast_channel_unlock(iaxs[callno]->owner);
3250 * \brief Queue a hold frame on the ast_channel owner
3252 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3253 * is active for the given call number.
3255 * \pre Assumes lock for callno is already held.
3257 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3258 * was valid before calling it, it may no longer be valid after calling it.
3259 * This function may unlock and lock the mutex associated with this callno,
3260 * meaning that another thread may grab it and destroy the call.
3262 static int iax2_queue_hold(int callno, const char *musicclass)
3264 iax2_lock_owner(callno);
3265 if (iaxs[callno] && iaxs[callno]->owner) {
3266 ast_queue_hold(iaxs[callno]->owner, musicclass);
3267 ast_channel_unlock(iaxs[callno]->owner);
3273 * \brief Queue an unhold frame on the ast_channel owner
3275 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3276 * is active for the given call number.
3278 * \pre Assumes lock for callno is already held.
3280 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3281 * was valid before calling it, it may no longer be valid after calling it.
3282 * This function may unlock and lock the mutex associated with this callno,
3283 * meaning that another thread may grab it and destroy the call.
3285 static int iax2_queue_unhold(int callno)
3287 iax2_lock_owner(callno);
3288 if (iaxs[callno] && iaxs[callno]->owner) {
3289 ast_queue_unhold(iaxs[callno]->owner);
3290 ast_channel_unlock(iaxs[callno]->owner);
3296 * \brief Queue a hangup frame on the ast_channel owner
3298 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3299 * is active for the given call number.
3301 * \pre Assumes lock for callno is already held.
3303 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3304 * was valid before calling it, it may no longer be valid after calling it.
3305 * This function may unlock and lock the mutex associated with this callno,
3306 * meaning that another thread may grab it and destroy the call.
3308 static int iax2_queue_hangup(int callno)
3310 iax2_lock_owner(callno);
3311 if (iaxs[callno] && iaxs[callno]->owner) {
3312 ast_queue_hangup(iaxs[callno]->owner);
3313 ast_channel_unlock(iaxs[callno]->owner);
3319 * \note This function assumes that iaxsl[callno] is locked when called.
3321 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3322 * was valid before calling it, it may no longer be valid after calling it.
3323 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3324 * associated with this callno, meaning that another thread may grab it and destroy the call.
3326 static int __do_deliver(void *data)
3328 /* Just deliver the packet by using queueing. This is called by
3329 the IAX thread with the iaxsl lock held. */
3330 struct iax_frame *fr = data;
3332 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3333 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3334 iax2_queue_frame(fr->callno, &fr->af);
3335 /* Free our iax frame */
3336 iax2_frame_free(fr);
3337 /* And don't run again */
3341 static int handle_error(void)
3343 /* XXX Ideally we should figure out why an error occurred and then abort those
3344 rather than continuing to try. Unfortunately, the published interface does
3345 not seem to work XXX */
3347 struct sockaddr_in *sin;
3350 struct sock_extended_err e;
3355 m.msg_controllen = sizeof(e);
3357 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3359 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3361 if (m.msg_controllen) {
3362 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3364 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3366 ast_log(LOG_WARNING, "No address detected??\n");
3368 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3375 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3378 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3381 ast_debug(1, "Received error: %s\n", strerror(errno));
3388 static int send_packet(struct iax_frame *f)
3391 int callno = f->callno;
3393 /* Don't send if there was an error, but return error instead */
3394 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3397 /* Called with iaxsl held */
3399 ast_debug(3, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3402 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3403 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3405 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3406 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3410 ast_debug(1, "Received error: %s\n", strerror(errno));
3419 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3420 * for the given call number may disappear during its execution.
3422 static int iax2_predestroy(int callno)
3424 struct ast_channel *c = NULL;
3425 struct chan_iax2_pvt *pvt = iaxs[callno];
3430 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3431 iax2_destroy_helper(pvt);
3432 ast_set_flag64(pvt, IAX_ALREADYGONE);
3435 if ((c = pvt->owner)) {
3436 ast_channel_tech_pvt_set(c, NULL);
3437 iax2_queue_hangup(callno);
3439 ast_module_unref(ast_module_info->self);
3445 static void iax2_destroy(int callno)
3447 struct chan_iax2_pvt *pvt = NULL;
3448 struct ast_channel *owner = NULL;
3451 if ((pvt = iaxs[callno])) {
3453 /* iax2_destroy_helper gets called from this function later on. When
3454 * called twice, we get the (previously) familiar FRACK! errors in
3455 * devmode, from the scheduler. An alternative to this approach is to
3456 * reset the scheduler entries to -1 when they're deleted in
3457 * iax2_destroy_helper(). That approach was previously decided to be
3458 * "wrong" because "the memory is going to be deallocated anyway. Why
3459 * should we be resetting those values?" */
3460 iax2_destroy_helper(pvt);
3464 owner = pvt ? pvt->owner : NULL;
3467 if (ast_channel_trylock(owner)) {
3468 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3469 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3475 iaxs[callno] = NULL;
3482 /* If there's an owner, prod it to give up */
3483 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3484 * because we already hold the owner channel lock. */
3485 ast_queue_hangup(owner);
3488 if (pvt->peercallno) {
3489 remove_by_peercallno(pvt);
3492 if (pvt->transfercallno) {
3493 remove_by_transfercallno(pvt);
3503 ast_channel_unlock(owner);
3507 static int update_packet(struct iax_frame *f)
3509 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3510 struct ast_iax2_full_hdr *fh = f->data;
3511 struct ast_frame af;
3513 /* if frame is encrypted. decrypt before updating it. */
3514 if (f->encmethods) {
3515 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3517 /* Mark this as a retransmission */
3518 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3520 f->iseqno = iaxs[f->callno]->iseqno;
3521 fh->iseqno = f->iseqno;
3523 /* Now re-encrypt the frame */
3524 if (f->encmethods) {
3525 /* since this is a retransmit frame, create a new random padding
3526 * before re-encrypting. */
3527 build_rand_pad(f->semirand, sizeof(f->semirand));
3528 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3533 static int attempt_transmit(const void *data);
3534 static void __attempt_transmit(const void *data)
3536 /* Attempt to transmit the frame to the remote peer...
3537 Called without iaxsl held. */
3538 struct iax_frame *f = (struct iax_frame *)data;
3540 int callno = f->callno;
3542 /* Make sure this call is still active */
3544 ast_mutex_lock(&iaxsl[callno]);
3545 if (callno && iaxs[callno]) {
3546 if (f->retries < 0) {
3549 } else if (f->retries >= max_retries) {
3550 /* Too many attempts. Record an error. */
3552 /* Transfer timeout */
3553 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3554 } else if (f->final) {
3555 iax2_destroy(callno);
3557 if (iaxs[callno]->owner) {
3558 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3559 ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3560 ast_channel_name(iaxs[f->callno]->owner),
3562 f->af.subclass.integer,
3566 iaxs[callno]->error = ETIMEDOUT;
3567 if (iaxs[callno]->owner) {
3568 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3570 iax2_queue_frame(callno, &fr); /* XXX */
3571 /* Remember, owner could disappear */
3572 if (iaxs[callno] && iaxs[callno]->owner)
3573 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3575 if (iaxs[callno]->reg) {
3576 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3577 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3578 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3580 iax2_destroy(callno);
3585 /* Update it if it needs it */
3587 /* Attempt transmission */
3590 /* Try again later after 10 times as long */
3592 if (f->retrytime > MAX_RETRY_TIME)
3593 f->retrytime = MAX_RETRY_TIME;
3594 /* Transfer messages max out at one second */
3595 if (f->transfer && (f->retrytime > 1000))
3596 f->retrytime = 1000;
3597 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3600 /* Make sure it gets freed */
3606 /* Don't attempt delivery, just remove it from the queue */
3607 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3608 ast_mutex_unlock(&iaxsl[callno]);
3609 f->retrans = -1; /* this is safe because this is the scheduled function */
3610 /* Free the IAX frame */
3612 } else if (callno) {
3613 ast_mutex_unlock(&iaxsl[callno]);
3617 static int attempt_transmit(const void *data)
3619 #ifdef SCHED_MULTITHREADED
3620 if (schedule_action(__attempt_transmit, data))
3622 __attempt_transmit(data);
3626 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3628 struct iax2_peer *peer = NULL;
3629 struct iax2_user *user = NULL;
3630 static const char * const choices[] = { "all", NULL };
3635 e->command = "iax2 prune realtime";
3637 "Usage: iax2 prune realtime [<peername>|all]\n"
3638 " Prunes object(s) from the cache\n";
3642 cmplt = ast_cli_complete(a->word, choices, a->n);
3644 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3650 return CLI_SHOWUSAGE;
3651 if (!strcmp(a->argv[3], "all")) {
3654 ast_cli(a->fd, "Cache flushed successfully.\n");
3657 peer = find_peer(a->argv[3], 0);
3658 user = find_user(a->argv[3]);
3661 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3662 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3663 expire_registry(peer_ref(peer));
3664 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3666 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3671 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3672 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3673 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3675 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3677 ao2_unlink(users,user);
3681 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3687 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3691 e->command = "iax2 test losspct";
3693 "Usage: iax2 test losspct <percentage>\n"
3694 " For testing, throws away <percentage> percent of incoming packets\n";
3700 return CLI_SHOWUSAGE;
3702 test_losspct = atoi(a->argv[3]);
3708 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3712 e->command = "iax2 test late";
3714 "Usage: iax2 test late <ms>\n"
3715 " For testing, count the next frame as <ms> ms late\n";
3722 return CLI_SHOWUSAGE;
3724 test_late = atoi(a->argv[3]);
3729 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3733 e->command = "iax2 test resync";
3735 "Usage: iax2 test resync <ms>\n"
3736 " For testing, adjust all future frames by <ms> ms\n";
3743 return CLI_SHOWUSAGE;
3745 test_resync = atoi(a->argv[3]);
3750 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3754 e->command = "iax2 test jitter";
3756 "Usage: iax2 test jitter <ms> <pct>\n"
3757 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3758 " percentage of packets. If <pct> is not specified, adds\n"
3759 " jitter to all packets.\n";
3765 if (a->argc < 4 || a->argc > 5)
3766 return CLI_SHOWUSAGE;
3768 test_jit = atoi(a->argv[3]);
3770 test_jitpct = atoi(a->argv[4]);
3774 #endif /* IAXTESTS */