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_FILE_VERSION(__FILE__, "$Revision$")
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/netsock2.h"
114 #include "asterisk/security_events.h"
115 #include "asterisk/stasis_endpoints.h"
116 #include "asterisk/bridge.h"
117 #include "asterisk/stasis.h"
118 #include "asterisk/stasis_system.h"
120 #include "iax2/include/iax2.h"
121 #include "iax2/include/firmware.h"
122 #include "iax2/include/parser.h"
123 #include "iax2/include/provision.h"
124 #include "jitterbuf.h"
127 <application name="IAX2Provision" language="en_US">
129 Provision a calling IAXy with a given template.
132 <parameter name="template">
133 <para>If not specified, defaults to <literal>default</literal>.</para>
137 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
138 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
139 or <literal>0</literal> on success.</para>
142 <function name="IAXPEER" language="en_US">
144 Gets IAX peer information.
147 <parameter name="peername" required="true">
149 <enum name="CURRENTCHANNEL">
150 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
151 endpoint of the current channel</para>
155 <parameter name="item">
156 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
159 <para>(default) The IP address.</para>
162 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
164 <enum name="mailbox">
165 <para>The configured mailbox.</para>
167 <enum name="context">
168 <para>The configured context.</para>
171 <para>The epoch time of the next expire.</para>
173 <enum name="dynamic">
174 <para>Is it dynamic? (yes/no).</para>
176 <enum name="callerid_name">
177 <para>The configured Caller ID name.</para>
179 <enum name="callerid_num">
180 <para>The configured Caller ID number.</para>
183 <para>The configured codecs.</para>
185 <enum name="codec[x]">
186 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
187 with <literal>0</literal>)</para>
193 <para>Gets information associated with the specified IAX2 peer.</para>
196 <ref type="function">SIPPEER</ref>
199 <function name="IAXVAR" language="en_US">
201 Sets or retrieves a remote variable.
204 <parameter name="varname" required="true" />
207 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
210 <manager name="IAXpeers" language="en_US">
215 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
220 <manager name="IAXpeerlist" language="en_US">
225 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
228 <para>List all the IAX peers.</para>
231 <manager name="IAXnetstats" language="en_US">
237 <para>Show IAX channels network statistics.</para>
240 <manager name="IAXregistry" language="en_US">
242 Show IAX registrations.
245 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
248 <para>Show IAX registrations.</para>
253 /* Define SCHED_MULTITHREADED to run the scheduler in a special
254 multithreaded mode. */
255 #define SCHED_MULTITHREADED
257 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
258 thread is actually doing. */
259 #define DEBUG_SCHED_MULTITHREAD
263 static int nochecksums = 0;
266 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
267 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
269 #define DEFAULT_THREAD_COUNT 10
270 #define DEFAULT_MAX_THREAD_COUNT 100
271 #define DEFAULT_RETRY_TIME 1000
272 #define MEMORY_SIZE 100
273 #define DEFAULT_DROP 3
275 #define DEBUG_SUPPORT
277 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
279 /* Sample over last 100 units to determine historic jitter */
282 static struct ast_codec_pref prefs;
284 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
287 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
288 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
289 #define MAX_TRUNK_MTU 1240
291 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
292 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
294 #define DEFAULT_CONTEXT "default"
296 static char default_parkinglot[AST_MAX_CONTEXT];
298 static char language[MAX_LANGUAGE] = "";
299 static char regcontext[AST_MAX_CONTEXT] = "";
301 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
302 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
303 static int network_change_sched_id = -1;
305 static int maxauthreq = 3;
306 static int max_retries = 4;
307 static int ping_time = 21;
308 static int lagrq_time = 10;
309 static int maxjitterbuffer=1000;
310 static int resyncthreshold=1000;
311 static int maxjitterinterps=10;
312 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
314 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
316 static int trunkfreq = 20;
317 static int trunkmaxsize = MAX_TRUNKDATA;
319 static int authdebug = 0;
320 static int autokill = 0;
321 static int iaxcompat = 0;
322 static int last_authmethod = 0;
324 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
326 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
333 static int min_reg_expire;
334 static int max_reg_expire;
336 static int srvlookup = 0;
338 static struct ast_timer *timer; /* Timer for trunking */
340 static struct ast_netsock_list *netsock;
341 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
342 static int defaultsockfd = -1;
344 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
347 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
349 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
350 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
351 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
352 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
353 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
354 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
355 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
356 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
357 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
359 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
360 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
361 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
362 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
364 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
365 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
368 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
369 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
370 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
372 /* if a pvt has encryption setup done and is running on the call */
373 #define IAX_CALLENCRYPTED(pvt) \
374 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
376 #define IAX_DEBUGDIGEST(msg, key) do { \
378 char digest[33] = ""; \
383 for (idx = 0; idx < 16; idx++) \
384 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
386 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
389 static struct io_context *io;
390 static struct ast_sched_context *sched;
392 #define DONT_RESCHEDULE -2
394 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
396 static int iaxdebug = 0;
398 static int iaxtrunkdebug = 0;
400 static int test_losspct = 0;
402 static int test_late = 0;
403 static int test_resync = 0;
404 static int test_jit = 0;
405 static int test_jitpct = 0;
406 #endif /* IAXTESTS */
408 static char accountcode[AST_MAX_ACCOUNT_CODE];
409 static char mohinterpret[MAX_MUSICCLASS];
410 static char mohsuggest[MAX_MUSICCLASS];
411 static int amaflags = 0;
413 static int delayreject = 0;
414 static int iax2_encryption = 0;
416 static struct ast_flags64 globalflags = { 0 };
418 static pthread_t netthreadid = AST_PTHREADT_NULL;
421 IAX_STATE_STARTED = (1 << 0),
422 IAX_STATE_AUTHENTICATED = (1 << 1),
423 IAX_STATE_TBD = (1 << 2),
426 struct iax2_context {
427 char context[AST_MAX_CONTEXT];
428 struct iax2_context *next;
432 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
433 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
434 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
435 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
436 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
437 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
438 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
439 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
440 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
441 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
442 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
443 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
444 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
445 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
446 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
447 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
448 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
449 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
450 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
451 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
452 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
453 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
454 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
455 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
456 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
457 #define IAX_DELAYPBXSTART (uint64_t)(1 << 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 */
458 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
459 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
460 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
461 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
462 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
463 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
464 static int global_rtautoclear = 120;
466 static int reload_config(int forced_reload);
469 * \brief Call token validation settings.
471 enum calltoken_peer_enum {
472 /*! \brief Default calltoken required unless the ip is in the ignorelist */
473 CALLTOKEN_DEFAULT = 0,
474 /*! \brief Require call token validation. */
476 /*! \brief Require call token validation after a successful registration
477 * using call token validation occurs. */
479 /*! \brief Do not require call token validation. */
484 AST_DECLARE_STRING_FIELDS(
485 AST_STRING_FIELD(name);
486 AST_STRING_FIELD(secret);
487 AST_STRING_FIELD(dbsecret);
488 AST_STRING_FIELD(accountcode);
489 AST_STRING_FIELD(mohinterpret);
490 AST_STRING_FIELD(mohsuggest);
491 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
492 AST_STRING_FIELD(language);
493 AST_STRING_FIELD(cid_num);
494 AST_STRING_FIELD(cid_name);
495 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
503 iax2_format capability;
504 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
505 int curauthreq; /*!< Current number of outstanding AUTHREQs */
506 struct ast_codec_pref prefs;
507 struct ast_acl_list *acl;
508 struct iax2_context *contexts;
509 struct ast_variable *vars;
510 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
514 AST_DECLARE_STRING_FIELDS(
515 AST_STRING_FIELD(name);
516 AST_STRING_FIELD(username);
517 AST_STRING_FIELD(description); /*!< Description of the peer */
518 AST_STRING_FIELD(secret);
519 AST_STRING_FIELD(dbsecret);
520 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
522 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
523 AST_STRING_FIELD(context); /*!< For transfers only */
524 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
525 AST_STRING_FIELD(mailbox); /*!< Mailbox */
526 AST_STRING_FIELD(mohinterpret);
527 AST_STRING_FIELD(mohsuggest);
528 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
529 /* Suggested caller id if registering */
530 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
531 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
532 AST_STRING_FIELD(zonetag); /*!< Time Zone */
533 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
535 struct ast_codec_pref prefs;
536 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
537 struct ast_sockaddr addr;
539 int sockfd; /*!< Socket to use for transmission */
544 /* Dynamic Registration fields */
545 struct sockaddr_in defaddr; /*!< Default address if there is one */
546 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
547 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
549 int expire; /*!< Schedule entry for expiry */
550 int expiry; /*!< How soon to expire */
551 iax2_format capability; /*!< Capability */
554 int callno; /*!< Call number of POKE request */
555 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
556 int lastms; /*!< How long last response took (in ms), or -1 for no response */
557 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
559 int pokefreqok; /*!< How often to check if the host is up */
560 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
561 int historicms; /*!< How long recent average responses took */
562 int smoothing; /*!< Sample over how many units to determine historic ms */
563 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
565 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
567 struct ast_acl_list *acl;
568 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
570 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
573 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
575 struct iax2_trunk_peer {
578 struct sockaddr_in addr;
579 struct timeval txtrunktime; /*!< Transmit trunktime */
580 struct timeval rxtrunktime; /*!< Receive trunktime */
581 struct timeval lasttxtime; /*!< Last transmitted trunktime */
582 struct timeval trunkact; /*!< Last trunk activity */
583 unsigned int lastsent; /*!< Last sent time */
584 /* Trunk data and length */
585 unsigned char *trunkdata;
586 unsigned int trunkdatalen;
587 unsigned int trunkdataalloc;
591 AST_LIST_ENTRY(iax2_trunk_peer) list;
594 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
597 REG_STATE_UNREGISTERED = 0,
600 REG_STATE_REGISTERED,
606 enum iax_transfer_state {
611 TRANSFER_PASSTHROUGH,
615 TRANSFER_MPASSTHROUGH,
620 struct iax2_registry {
621 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
623 char secret[80]; /*!< Password or key name in []'s */
624 int expire; /*!< Sched ID of expiration */
625 int refresh; /*!< How often to refresh */
626 enum iax_reg_state regstate;
627 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
628 int callno; /*!< Associated call number if applicable */
629 struct sockaddr_in us; /*!< Who the server thinks we are */
630 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
631 AST_LIST_ENTRY(iax2_registry) entry;
634 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
636 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
637 #define MIN_RETRY_TIME 100
638 #define MAX_RETRY_TIME 10000
640 #define MAX_JITTER_BUFFER 50
641 #define MIN_JITTER_BUFFER 10
643 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
645 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
647 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
648 #define TS_GAP_FOR_JB_RESYNC 5000
650 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
651 #define MARK_IAX_SUBCLASS_TX 0x8000
653 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
654 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
655 static int iaxdynamicthreadcount = 0;
656 static int iaxdynamicthreadnum = 0;
657 static int iaxactivethreadcount = 0;
671 /* We use the high order bit as the validated flag, and the lower 15 as the
672 * actual call number */
673 typedef uint16_t callno_entry;
675 struct chan_iax2_pvt {
676 /*! Socket to send/receive on for this call */
678 /*! ast_callid bound to dialog */
679 struct ast_callid *callid;
680 /*! Last received voice format */
681 iax2_format voiceformat;
682 /*! Last received video format */
683 iax2_format videoformat;
684 /*! Last sent voice format */
685 iax2_format svoiceformat;
686 /*! Last sent video format */
687 iax2_format svideoformat;
688 /*! What we are capable of sending */
689 iax2_format capability;
690 /*! Last received timestamp */
692 /*! Last sent timestamp - never send the same timestamp twice in a single call */
693 unsigned int lastsent;
694 /*! Timestamp of the last video frame sent */
695 unsigned int lastvsent;
696 /*! Next outgoing timestamp if everything is good */
697 unsigned int nextpred;
698 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
699 int first_iax_message;
700 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
701 int last_iax_message;
702 /*! True if the last voice we transmitted was not silence/CNG */
703 unsigned int notsilenttx:1;
705 unsigned int pingtime;
706 /*! Max time for initial response */
709 struct sockaddr_in addr;
710 /*! Actual used codec preferences */
711 struct ast_codec_pref prefs;
712 /*! Requested codec preferences */
713 struct ast_codec_pref rprefs;
714 /*! Our call number */
715 unsigned short callno;
716 /*! Our callno_entry entry */
717 callno_entry callno_entry;
719 unsigned short peercallno;
720 /*! Negotiated format, this is only used to remember what format was
721 chosen for an unauthenticated call so that the channel can get
722 created later using the right format */
723 iax2_format chosenformat;
724 /*! Peer selected format */
725 iax2_format peerformat;
726 /*! Peer capability */
727 iax2_format peercapability;
728 /*! timeval that we base our transmission on */
729 struct timeval offset;
730 /*! timeval that we base our delivery on */
731 struct timeval rxcore;
732 /*! The jitterbuffer */
734 /*! active jb read scheduler id */
738 /*! Error, as discovered by the manager */
740 /*! Owner if we have one */
741 struct ast_channel *owner;
742 /*! What's our state? */
743 struct ast_flags state;
744 /*! Expiry (optional) */
746 /*! Next outgoing sequence number */
747 unsigned char oseqno;
748 /*! Next sequence number they have not yet acknowledged */
749 unsigned char rseqno;
750 /*! Next incoming sequence number */
751 unsigned char iseqno;
752 /*! Last incoming sequence number we have acknowledged */
753 unsigned char aseqno;
755 AST_DECLARE_STRING_FIELDS(
757 AST_STRING_FIELD(peer);
758 /*! Default Context */
759 AST_STRING_FIELD(context);
760 /*! Caller ID if available */
761 AST_STRING_FIELD(cid_num);
762 AST_STRING_FIELD(cid_name);
763 /*! Hidden Caller ID (i.e. ANI) if appropriate */
764 AST_STRING_FIELD(ani);
766 AST_STRING_FIELD(dnid);
768 AST_STRING_FIELD(rdnis);
769 /*! Requested Extension */
770 AST_STRING_FIELD(exten);
771 /*! Expected Username */
772 AST_STRING_FIELD(username);
773 /*! Expected Secret */
774 AST_STRING_FIELD(secret);
776 AST_STRING_FIELD(challenge);
777 /*! Public keys permitted keys for incoming authentication */
778 AST_STRING_FIELD(inkeys);
779 /*! Private key for outgoing authentication */
780 AST_STRING_FIELD(outkey);
781 /*! Preferred language */
782 AST_STRING_FIELD(language);
783 /*! Hostname/peername for naming purposes */
784 AST_STRING_FIELD(host);
786 AST_STRING_FIELD(dproot);
787 AST_STRING_FIELD(accountcode);
788 AST_STRING_FIELD(mohinterpret);
789 AST_STRING_FIELD(mohsuggest);
790 /*! received OSP token */
791 AST_STRING_FIELD(osptoken);
792 /*! Default parkinglot */
793 AST_STRING_FIELD(parkinglot);
795 /*! AUTHREJ all AUTHREP frames */
797 /*! permitted authentication methods */
799 /*! permitted encryption methods */
801 /*! Encryption AES-128 Key */
802 ast_aes_encrypt_key ecx;
803 /*! Decryption AES-128 Key corresponding to ecx */
804 ast_aes_decrypt_key mydcx;
805 /*! Decryption AES-128 Key used to decrypt peer frames */
806 ast_aes_decrypt_key dcx;
807 /*! scheduler id associated with iax_key_rotate
808 * for encrypted calls*/
810 /*! 32 bytes of semi-random data */
811 unsigned char semirand[32];
812 /*! Associated registry */
813 struct iax2_registry *reg;
814 /*! Associated peer for poking */
815 struct iax2_peer *peerpoke;
820 /*! Transferring status */
821 enum iax_transfer_state transferring;
822 /*! Transfer identifier */
824 /*! Who we are IAX transferring to */
825 struct sockaddr_in transfer;
826 /*! What's the new call number for the transfer */
827 unsigned short transfercallno;
828 /*! Transfer encrypt AES-128 Key */
829 ast_aes_encrypt_key tdcx;
831 /*! Status of knowledge of peer ADSI capability */
834 /*! Callno of native bridge peer. (Valid if nonzero) */
835 unsigned short bridgecallno;
837 int pingid; /*!< Transmit PING request */
838 int lagid; /*!< Retransmit lag request */
839 int autoid; /*!< Auto hangup for Dialplan requestor */
840 int authid; /*!< Authentication rejection ID */
841 int authfail; /*!< Reason to report failure */
842 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
847 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
848 /*! variables inherited from the user definition */
849 struct ast_variable *vars;
850 /*! variables transmitted in a NEW packet */
851 struct ast_variable *iaxvars;
852 /*! last received remote rr */
853 struct iax_rr remote_rr;
854 /*! Current base time: (just for stats) */
856 /*! Dropped frame count: (just for stats) */
858 /*! received frame count: (just for stats) */
860 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
861 unsigned char calltoken_ie_len;
862 /*! hold all signaling frames from the pbx thread until we have a destination callno */
864 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
865 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
868 struct signaling_queue_entry {
870 AST_LIST_ENTRY(signaling_queue_entry) next;
878 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
879 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
881 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
882 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
883 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
885 struct call_number_pool {
888 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
891 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
893 /*! table of available call numbers */
894 static struct call_number_pool callno_pool;
896 /*! table of available trunk call numbers */
897 static struct call_number_pool callno_pool_trunk;
900 * \brief a list of frames that may need to be retransmitted
902 * \note The contents of this list do not need to be explicitly destroyed
903 * on module unload. This is because all active calls are destroyed, and
904 * all frames in this queue will get destroyed as a part of that process.
906 * \note Contents protected by the iaxsl[] locks
908 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
910 static struct ast_taskprocessor *transmit_processor;
912 static int randomcalltokendata;
914 static const time_t MAX_CALLTOKEN_DELAY = 10;
917 * This module will get much higher performance when doing a lot of
918 * user and peer lookups if the number of buckets is increased from 1.
919 * However, to maintain old behavior for Asterisk 1.4, these are set to
920 * 1 by default. When using multiple buckets, search order through these
921 * containers is considered random, so you will not be able to depend on
922 * the order the entires are specified in iax.conf for matching order. */
924 #define MAX_PEER_BUCKETS 17
926 #define MAX_PEER_BUCKETS 563
928 static struct ao2_container *peers;
930 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
931 static struct ao2_container *users;
933 /*! Table containing peercnt objects for every ip address consuming a callno */
934 static struct ao2_container *peercnts;
936 /*! Table containing custom callno limit rules for a range of ip addresses. */
937 static struct ao2_container *callno_limits;
939 /*! Table containing ip addresses not requiring calltoken validation */
940 static struct ao2_container *calltoken_ignores;
942 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
944 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
946 static uint16_t global_maxcallno;
948 /*! Total num of call numbers allowed to be allocated without calltoken validation */
949 static uint16_t global_maxcallno_nonval;
951 static uint16_t total_nonval_callno_used = 0;
953 /*! peer connection private, keeps track of all the call numbers
954 * consumed by a single ip address */
956 /*! ip address consuming call numbers */
958 /*! Number of call numbers currently used by this ip address */
960 /*! Max call numbers allowed for this ip address */
962 /*! Specifies whether limit is set by a registration or not, if so normal
963 * limit setting rules do not apply to this address. */
967 /*! used by both callno_limits and calltoken_ignores containers */
969 /*! ip address range for custom callno limit rule */
971 /*! callno limit for this ip address range, only used in callno_limits container */
973 /*! delete me marker for reloads */
978 /*! Extension exists */
979 CACHE_FLAG_EXISTS = (1 << 0),
980 /*! Extension is nonexistent */
981 CACHE_FLAG_NONEXISTENT = (1 << 1),
982 /*! Extension can exist */
983 CACHE_FLAG_CANEXIST = (1 << 2),
984 /*! Waiting to hear back response */
985 CACHE_FLAG_PENDING = (1 << 3),
987 CACHE_FLAG_TIMEOUT = (1 << 4),
988 /*! Request transmitted */
989 CACHE_FLAG_TRANSMITTED = (1 << 5),
991 CACHE_FLAG_UNKNOWN = (1 << 6),
993 CACHE_FLAG_MATCHMORE = (1 << 7),
996 struct iax2_dpcache {
997 char peercontext[AST_MAX_CONTEXT];
998 char exten[AST_MAX_EXTENSION];
1000 struct timeval expiry;
1002 unsigned short callno;
1004 AST_LIST_ENTRY(iax2_dpcache) cache_list;
1005 AST_LIST_ENTRY(iax2_dpcache) peer_list;
1008 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1010 static void reg_source_db(struct iax2_peer *p);
1011 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1012 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
1014 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1015 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1016 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1018 enum iax2_thread_iostate {
1021 IAX_IOSTATE_PROCESSING,
1022 IAX_IOSTATE_SCHEDREADY,
1025 enum iax2_thread_type {
1026 IAX_THREAD_TYPE_POOL,
1027 IAX_THREAD_TYPE_DYNAMIC,
1030 struct iax2_pkt_buf {
1031 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1033 unsigned char buf[1];
1036 struct iax2_thread {
1037 AST_LIST_ENTRY(iax2_thread) list;
1038 enum iax2_thread_type type;
1039 enum iax2_thread_iostate iostate;
1040 #ifdef SCHED_MULTITHREADED
1041 void (*schedfunc)(const void *);
1042 const void *scheddata;
1044 #ifdef DEBUG_SCHED_MULTITHREAD
1050 struct sockaddr_in iosin;
1051 unsigned char readbuf[4096];
1059 ast_mutex_t init_lock;
1060 ast_cond_t init_cond;
1061 /*! if this thread is processing a full frame,
1062 some information about that frame will be stored
1063 here, so we can avoid dispatching any more full
1064 frames for that callno to other threads */
1066 unsigned short callno;
1067 struct sockaddr_in sin;
1071 /*! Queued up full frames for processing. If more full frames arrive for
1072 * a call which this thread is already processing a full frame for, they
1073 * are queued up here. */
1074 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1079 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1080 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1081 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1083 static void *iax2_process_thread(void *data);
1084 static void iax2_destroy(int callno);
1086 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1088 ast_mutex_lock(lock);
1089 ast_cond_signal(cond);
1090 ast_mutex_unlock(lock);
1094 * \brief an array of iax2 pvt structures
1096 * The container for active chan_iax2_pvt structures is implemented as an
1097 * array for extremely quick direct access to the correct pvt structure
1098 * based on the local call number. The local call number is used as the
1099 * index into the array where the associated pvt structure is stored.
1101 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1103 static struct ast_callid *iax_pvt_callid_get(int callno)
1105 if (iaxs[callno]->callid) {
1106 return ast_callid_ref(iaxs[callno]->callid);
1111 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1113 if (iaxs[callno]->callid) {
1114 ast_callid_unref(iaxs[callno]->callid);
1116 ast_callid_ref(callid);
1117 iaxs[callno]->callid = callid;
1120 static void iax_pvt_callid_new(int callno)
1122 struct 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);
1126 ast_callid_unref(callid);
1130 * \brief Another container of iax2_pvt structures
1132 * Active IAX2 pvt structs are also stored in this container, if they are a part
1133 * of an active call where we know the remote side's call number. The reason
1134 * for this is that incoming media frames do not contain our call number. So,
1135 * instead of having to iterate the entire iaxs array, we use this container to
1136 * look up calls where the remote side is using a given call number.
1138 static struct ao2_container *iax_peercallno_pvts;
1141 * \brief chan_iax2_pvt structure locks
1143 * These locks are used when accessing a pvt structure in the iaxs array.
1144 * The index used here is the same as used in the iaxs array. It is the
1145 * local call number for the associated pvt struct.
1147 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1150 * * \brief Another container of iax2_pvt structures
1152 * Active IAX2 pvt stucts used during transfering a call are stored here.
1154 static struct ao2_container *iax_transfercallno_pvts;
1156 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1157 but keeps the division between trunked and non-trunked better. */
1158 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1160 /* Debug routines... */
1161 static struct sockaddr_in debugaddr;
1163 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1166 (sin && debugaddr.sin_addr.s_addr &&
1167 (!ntohs(debugaddr.sin_port) ||
1168 debugaddr.sin_port == sin->sin_port) &&
1169 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1171 iax_showframe(f, fhi, rx, sin, datalen);
1174 iax_showframe(f, fhi, rx, sin, 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 sockaddr_in *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_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 sockaddr_in *sin, callno_entry entry);
1273 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1274 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, 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]);
1334 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
1336 /* The MWI subscriptions exist just so the core knows we care about those
1337 * mailboxes. However, we just grab the events out of the cache when it
1338 * is time to send MWI, since it is only sent with a REGACK. */
1341 static void network_change_stasis_subscribe(void)
1343 if (!network_change_sub) {
1344 network_change_sub = stasis_subscribe(ast_system_topic(),
1345 network_change_stasis_cb, NULL);
1349 static void network_change_stasis_unsubscribe(void)
1351 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1354 static void acl_change_stasis_subscribe(void)
1356 if (!acl_change_sub) {
1357 acl_change_sub = stasis_subscribe(ast_security_topic(),
1358 acl_change_stasis_cb, NULL);
1362 static void acl_change_stasis_unsubscribe(void)
1364 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1367 static int network_change_sched_cb(const void *data)
1369 struct iax2_registry *reg;
1370 network_change_sched_id = -1;
1371 AST_LIST_LOCK(®istrations);
1372 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1373 iax2_do_register(reg);
1375 AST_LIST_UNLOCK(®istrations);
1380 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1381 struct stasis_topic *topic, struct stasis_message *message)
1383 /* This callback is only concerned with network change messages from the system topic. */
1384 if (stasis_message_type(message) != ast_network_change_type()) {
1388 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1389 if (network_change_sched_id == -1) {
1390 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1394 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1395 struct stasis_topic *topic, struct stasis_message *message)
1397 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1401 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1405 static const struct ast_datastore_info iax2_variable_datastore_info = {
1406 .type = "IAX2_VARIABLE",
1407 .duplicate = iax2_dup_variable_datastore,
1408 .destroy = iax2_free_variable_datastore,
1411 static void *iax2_dup_variable_datastore(void *old)
1413 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1414 struct ast_var_t *oldvar, *newvar;
1416 newlist = ast_calloc(sizeof(*newlist), 1);
1418 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1422 AST_LIST_HEAD_INIT(newlist);
1423 AST_LIST_LOCK(oldlist);
1424 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1425 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1427 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1429 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1431 AST_LIST_UNLOCK(oldlist);
1435 static void iax2_free_variable_datastore(void *old)
1437 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1438 struct ast_var_t *oldvar;
1440 AST_LIST_LOCK(oldlist);
1441 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1444 AST_LIST_UNLOCK(oldlist);
1445 AST_LIST_HEAD_DESTROY(oldlist);
1450 /* WARNING: insert_idle_thread should only ever be called within the
1451 * context of an iax2_process_thread() thread.
1453 static void insert_idle_thread(struct iax2_thread *thread)
1455 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1456 AST_LIST_LOCK(&dynamic_list);
1457 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1458 AST_LIST_UNLOCK(&dynamic_list);
1460 AST_LIST_LOCK(&idle_list);
1461 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1462 AST_LIST_UNLOCK(&idle_list);
1468 static struct iax2_thread *find_idle_thread(void)
1470 struct iax2_thread *thread = NULL;
1472 /* Pop the head of the idle list off */
1473 AST_LIST_LOCK(&idle_list);
1474 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1475 AST_LIST_UNLOCK(&idle_list);
1477 /* If we popped a thread off the idle list, just return it */
1479 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1483 /* Pop the head of the dynamic list off */
1484 AST_LIST_LOCK(&dynamic_list);
1485 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1486 AST_LIST_UNLOCK(&dynamic_list);
1488 /* If we popped a thread off the dynamic list, just return it */
1490 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1494 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1495 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1498 /* Set default values */
1499 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1500 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1501 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1503 /* Initialize lock and condition */
1504 ast_mutex_init(&thread->lock);
1505 ast_cond_init(&thread->cond, NULL);
1506 ast_mutex_init(&thread->init_lock);
1507 ast_cond_init(&thread->init_cond, NULL);
1508 ast_mutex_lock(&thread->init_lock);
1510 /* Create thread and send it on it's way */
1511 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1512 ast_cond_destroy(&thread->cond);
1513 ast_mutex_destroy(&thread->lock);
1514 ast_mutex_unlock(&thread->init_lock);
1515 ast_cond_destroy(&thread->init_cond);
1516 ast_mutex_destroy(&thread->init_lock);
1521 /* this thread is not processing a full frame (since it is idle),
1522 so ensure that the field for the full frame call number is empty */
1523 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1525 /* Wait for the thread to be ready before returning it to the caller */
1526 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1528 /* Done with init_lock */
1529 ast_mutex_unlock(&thread->init_lock);
1534 #ifdef SCHED_MULTITHREADED
1535 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1537 struct iax2_thread *thread;
1538 static time_t lasterror;
1541 thread = find_idle_thread();
1542 if (thread != NULL) {
1543 thread->schedfunc = func;
1544 thread->scheddata = data;
1545 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1546 #ifdef DEBUG_SCHED_MULTITHREAD
1547 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1549 signal_condition(&thread->lock, &thread->cond);
1553 if (t != lasterror) {
1555 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1560 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1563 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1564 ast_sched_cb callback, const void *data)
1566 return ast_sched_replace(id, con, when, callback, data);
1569 static int iax2_sched_add(struct ast_sched_context *con, int when,
1570 ast_sched_cb callback, const void *data)
1572 return ast_sched_add(con, when, callback, data);
1575 static int send_ping(const void *data);
1577 static void __send_ping(const void *data)
1579 int callno = (long) data;
1581 ast_mutex_lock(&iaxsl[callno]);
1584 if (iaxs[callno]->peercallno) {
1585 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1586 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1587 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1591 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1594 ast_mutex_unlock(&iaxsl[callno]);
1597 static int send_ping(const void *data)
1599 int callno = (long) data;
1600 ast_mutex_lock(&iaxsl[callno]);
1601 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1602 iaxs[callno]->pingid = -1;
1604 ast_mutex_unlock(&iaxsl[callno]);
1606 #ifdef SCHED_MULTITHREADED
1607 if (schedule_action(__send_ping, data))
1614 static void encmethods_to_str(int e, struct ast_str **buf)
1616 ast_str_set(buf, 0, "(");
1617 if (e & IAX_ENCRYPT_AES128) {
1618 ast_str_append(buf, 0, "aes128");
1620 if (e & IAX_ENCRYPT_KEYROTATE) {
1621 ast_str_append(buf, 0, ",keyrotate");
1623 if (ast_str_strlen(*buf) > 1) {
1624 ast_str_append(buf, 0, ")");
1626 ast_str_set(buf, 0, "No");
1630 static int get_encrypt_methods(const char *s)
1633 if (!strcasecmp(s, "aes128"))
1634 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1635 else if (ast_true(s))
1636 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1642 static int send_lagrq(const void *data);
1644 static void __send_lagrq(const void *data)
1646 int callno = (long) data;
1648 ast_mutex_lock(&iaxsl[callno]);
1651 if (iaxs[callno]->peercallno) {
1652 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1653 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1654 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1658 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1661 ast_mutex_unlock(&iaxsl[callno]);
1664 static int send_lagrq(const void *data)
1666 int callno = (long) data;
1667 ast_mutex_lock(&iaxsl[callno]);
1668 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1669 iaxs[callno]->lagid = -1;
1671 ast_mutex_unlock(&iaxsl[callno]);
1673 #ifdef SCHED_MULTITHREADED
1674 if (schedule_action(__send_lagrq, data))
1680 static unsigned char compress_subclass(iax2_format subclass)
1684 /* If it's 64 or smaller, just return it */
1685 if (subclass < IAX_FLAG_SC_LOG)
1687 /* Otherwise find its power */
1688 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1689 if (subclass & (1LL << x)) {
1691 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1697 return power | IAX_FLAG_SC_LOG;
1700 static iax2_format uncompress_subclass(unsigned char csub)
1702 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1703 if (csub & IAX_FLAG_SC_LOG) {
1704 /* special case for 'compressed' -1 */
1708 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1714 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1716 struct ast_format_cap *cap;
1717 struct ast_format tmpfmt;
1718 iax2_format format = 0;
1719 if ((cap = ast_format_cap_alloc_nolock())) {
1720 ast_format_clear(&tmpfmt);
1721 ast_format_cap_from_old_bitfield(cap, formats);
1722 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1723 format = ast_format_to_old_bitfield(&tmpfmt);
1724 cap = ast_format_cap_destroy(cap);
1730 static iax2_format iax2_best_codec(iax2_format formats)
1732 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1733 struct ast_format tmpfmt;
1738 ast_format_clear(&tmpfmt);
1739 ast_format_cap_from_old_bitfield(cap, formats);
1740 ast_best_codec(cap, &tmpfmt);
1741 cap = ast_format_cap_destroy(cap);
1742 return ast_format_to_old_bitfield(&tmpfmt);
1745 const char *iax2_getformatname(iax2_format format)
1747 struct ast_format tmpfmt;
1748 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1752 return ast_getformatname(&tmpfmt);
1755 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1757 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1762 ast_format_cap_from_old_bitfield(cap, format);
1763 ast_getformatname_multiple(codec_buf, len, cap);
1764 cap = ast_format_cap_destroy(cap);
1769 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1772 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1777 ast_format_cap_from_old_bitfield(cap, *formats);
1778 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1779 *formats = ast_format_cap_to_old_bitfield(cap);
1780 cap = ast_format_cap_destroy(cap);
1785 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1788 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1792 ast_format_cap_from_old_bitfield(cap, formats);
1793 res = ast_data_add_codecs(root, node_name, cap);
1794 cap = ast_format_cap_destroy(cap);
1799 * \note The only member of the peer passed here guaranteed to be set is the name field
1801 static int peer_hash_cb(const void *obj, const int flags)
1803 const struct iax2_peer *peer = obj;
1804 const char *name = obj;
1806 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1810 * \note The only member of the peer passed here guaranteed to be set is the name field
1812 static int peer_cmp_cb(void *obj, void *arg, int flags)
1814 struct iax2_peer *peer = obj, *peer2 = arg;
1815 const char *name = arg;
1817 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1818 CMP_MATCH | CMP_STOP : 0;
1822 * \note The only member of the user passed here guaranteed to be set is the name field
1824 static int user_hash_cb(const void *obj, const int flags)
1826 const struct iax2_user *user = obj;
1827 const char *name = obj;
1829 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1833 * \note The only member of the user passed here guaranteed to be set is the name field
1835 static int user_cmp_cb(void *obj, void *arg, int flags)
1837 struct iax2_user *user = obj, *user2 = arg;
1838 const char *name = arg;
1840 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1841 CMP_MATCH | CMP_STOP : 0;
1845 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1846 * so do not call it with a pvt lock held.
1848 static struct iax2_peer *find_peer(const char *name, int realtime)
1850 struct iax2_peer *peer = NULL;
1852 peer = ao2_find(peers, name, OBJ_KEY);
1854 /* Now go for realtime if applicable */
1855 if(!peer && realtime)
1856 peer = realtime_peer(name, NULL);
1861 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1867 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1873 static struct iax2_user *find_user(const char *name)
1875 return ao2_find(users, name, OBJ_KEY);
1877 static inline struct iax2_user *user_ref(struct iax2_user *user)
1883 static inline struct iax2_user *user_unref(struct iax2_user *user)
1889 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1891 struct iax2_peer *peer = NULL;
1893 struct ao2_iterator i;
1895 i = ao2_iterator_init(peers, 0);
1896 while ((peer = ao2_iterator_next(&i))) {
1897 struct sockaddr_in peer_addr;
1899 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1901 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1902 (peer_addr.sin_port == sin.sin_port)) {
1903 ast_copy_string(host, peer->name, len);
1910 ao2_iterator_destroy(&i);
1913 peer = realtime_peer(NULL, &sin);
1915 ast_copy_string(host, peer->name, len);
1924 /*!\note Assumes the lock on the pvt is already held, when
1925 * iax2_destroy_helper() is called. */
1926 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1928 /* Decrement AUTHREQ count if needed */
1929 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1930 struct iax2_user *user;
1932 user = ao2_find(users, pvt->username, OBJ_KEY);
1934 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1938 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1940 /* No more pings or lagrq's */
1941 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1942 pvt->pingid = DONT_RESCHEDULE;
1943 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1944 pvt->lagid = DONT_RESCHEDULE;
1945 AST_SCHED_DEL(sched, pvt->autoid);
1946 AST_SCHED_DEL(sched, pvt->authid);
1947 AST_SCHED_DEL(sched, pvt->initid);
1948 AST_SCHED_DEL(sched, pvt->jbid);
1949 AST_SCHED_DEL(sched, pvt->keyrotateid);
1952 static void iax2_frame_free(struct iax_frame *fr)
1954 AST_SCHED_DEL(sched, fr->retrans);
1958 static int scheduled_destroy(const void *vid)
1960 unsigned short callno = PTR_TO_CALLNO(vid);
1961 ast_mutex_lock(&iaxsl[callno]);
1963 ast_debug(1, "Really destroying %d now...\n", callno);
1964 iax2_destroy(callno);
1966 ast_mutex_unlock(&iaxsl[callno]);
1970 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1973 ast_free(s->f.data.ptr);
1978 /*! \brief This function must be called once we are sure the other side has
1979 * given us a call number. All signaling is held here until that point. */
1980 static void send_signaling(struct chan_iax2_pvt *pvt)
1982 struct signaling_queue_entry *s = NULL;
1984 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1985 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1986 free_signaling_queue_entry(s);
1988 pvt->hold_signaling = 0;
1991 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1992 * we have received a destination call number. */
1993 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1995 struct signaling_queue_entry *qe;
1997 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1998 return 1; /* do not queue this frame */
1999 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2000 return -1; /* out of memory */
2003 /* copy ast_frame into our queue entry */
2005 if (qe->f.datalen) {
2006 /* if there is data in this frame copy it over as well */
2007 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2008 free_signaling_queue_entry(qe);
2011 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2013 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2018 static void pvt_destructor(void *obj)
2020 struct chan_iax2_pvt *pvt = obj;
2021 struct iax_frame *cur = NULL;
2022 struct signaling_queue_entry *s = NULL;
2024 ast_mutex_lock(&iaxsl[pvt->callno]);
2026 iax2_destroy_helper(pvt);
2028 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2029 pvt->callno_entry = 0;
2032 ast_set_flag64(pvt, IAX_ALREADYGONE);
2034 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2035 /* Cancel any pending transmissions */
2039 ast_mutex_unlock(&iaxsl[pvt->callno]);
2041 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2042 free_signaling_queue_entry(s);
2046 pvt->reg->callno = 0;
2052 ast_variables_destroy(pvt->vars);
2056 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2057 iax2_frame_free(frame.data);
2060 jb_destroy(pvt->jb);
2061 ast_string_field_free_memory(pvt);
2065 ast_callid_unref(pvt->callid);
2070 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2072 struct chan_iax2_pvt *tmp;
2075 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2079 if (ast_string_field_init(tmp, 32)) {
2091 tmp->keyrotateid = -1;
2093 ast_string_field_set(tmp,exten, "s");
2094 ast_string_field_set(tmp,host, host);
2098 jbconf.max_jitterbuf = maxjitterbuffer;
2099 jbconf.resync_threshold = resyncthreshold;
2100 jbconf.max_contig_interp = maxjitterinterps;
2101 jbconf.target_extra = jittertargetextra;
2102 jb_setconf(tmp->jb,&jbconf);
2104 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2106 tmp->hold_signaling = 1;
2107 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2112 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2114 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2116 size_t afdatalen = new->afdatalen;
2117 memcpy(new, fr, sizeof(*new));
2118 iax_frame_wrap(new, &fr->af);
2119 new->afdatalen = afdatalen;
2122 new->direction = DIRECTION_INGRESS;
2127 /* keep these defined in this order. They are used in find_callno to
2128 * determine whether or not a new call number should be allowed. */
2130 /* do not allow a new call number, only search ones in use for match */
2132 /* search for match first, then allow a new one to be allocated */
2134 /* do not search for match, force a new call number */
2136 /* do not search for match, force a new call number. Signifies call number
2137 * has been calltoken validated */
2138 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2141 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2143 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2144 (cur->addr.sin_port == sin->sin_port)) {
2145 /* This is the main host */
2146 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2147 (check_dcallno ? dcallno == cur->callno : 1) ) {
2148 /* That's us. Be sure we keep track of the peer call number */
2152 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2153 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2154 /* We're transferring */
2155 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2161 static int make_trunk(unsigned short callno, int locked)
2166 if (iaxs[callno]->oseqno) {
2167 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2170 if (callno >= TRUNK_CALL_START) {
2171 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2175 if (get_unused_callno(
2177 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2179 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2183 x = CALLNO_ENTRY_GET_CALLNO(entry);
2184 ast_mutex_lock(&iaxsl[x]);
2187 * \note We delete these before switching the slot, because if
2188 * they fire in the meantime, they will generate a warning.
2190 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2191 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2192 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2193 iaxs[x] = iaxs[callno];
2194 iaxs[x]->callno = x;
2196 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2197 * before assigning the new one */
2198 if (iaxs[x]->callno_entry) {
2201 MIN_REUSE_TIME * 1000,
2203 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2206 iaxs[x]->callno_entry = entry;
2208 iaxs[callno] = NULL;
2209 /* Update the two timers that should have been started */
2210 iaxs[x]->pingid = iax2_sched_add(sched,
2211 ping_time * 1000, send_ping, (void *)(long)x);
2212 iaxs[x]->lagid = iax2_sched_add(sched,
2213 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2216 ast_mutex_unlock(&iaxsl[callno]);
2219 ast_mutex_unlock(&iaxsl[x]);
2221 /* We moved this call from a non-trunked to a trunked call */
2222 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2227 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2229 if (!pvt->transfercallno) {
2230 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2234 ao2_link(iax_transfercallno_pvts, pvt);
2237 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2239 if (!pvt->transfercallno) {
2240 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2244 ao2_unlink(iax_transfercallno_pvts, pvt);
2246 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2248 if (!pvt->peercallno) {
2249 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2253 ao2_link(iax_peercallno_pvts, pvt);
2256 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2258 if (!pvt->peercallno) {
2259 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2263 ao2_unlink(iax_peercallno_pvts, pvt);
2266 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2268 struct addr_range *lim = obj;
2273 static int addr_range_hash_cb(const void *obj, const int flags)
2275 const struct addr_range *lim = obj;
2276 struct sockaddr_in sin;
2277 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2278 return abs((int) sin.sin_addr.s_addr);
2281 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2283 struct addr_range *lim1 = obj, *lim2 = arg;
2284 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2285 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2286 CMP_MATCH | CMP_STOP : 0;
2289 static int peercnt_hash_cb(const void *obj, const int flags)
2291 const struct peercnt *peercnt = obj;
2292 return abs((int) peercnt->addr);
2295 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2297 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2298 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2301 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2303 struct addr_range *addr_range = obj;
2304 struct sockaddr_in *sin = arg;
2305 struct sockaddr_in ha_netmask_sin;
2306 struct sockaddr_in ha_addr_sin;
2308 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2309 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2311 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2312 return CMP_MATCH | CMP_STOP;
2320 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2322 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2324 struct addr_range *addr_range;
2325 struct iax2_peer *peer = NULL;
2326 struct iax2_user *user = NULL;
2327 /* if no username is given, check for guest accounts */
2328 const char *find = S_OR(name, "guest");
2329 int res = 1; /* required by default */
2331 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2332 /* There are only two cases in which calltoken validation is not required.
2333 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2334 * the peer definition has not set the requirecalltoken option.
2335 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2338 /* ----- Case 1 ----- */
2339 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2340 ao2_ref(addr_range, -1);
2344 /* ----- Case 2 ----- */
2345 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2346 calltoken_required = user->calltoken_required;
2347 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2348 calltoken_required = user->calltoken_required;
2349 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2350 calltoken_required = peer->calltoken_required;
2351 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2352 calltoken_required = peer->calltoken_required;
2362 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2363 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2364 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2374 * \brief set peercnt callno limit.
2377 * First looks in custom definitions. If not found, global limit
2378 * is used. Entries marked as reg already have
2379 * a custom limit set by a registration and are not modified.
2381 static void set_peercnt_limit(struct peercnt *peercnt)
2383 uint16_t limit = global_maxcallno;
2384 struct addr_range *addr_range;
2385 struct sockaddr_in sin = {
2386 .sin_addr.s_addr = peercnt->addr,
2390 if (peercnt->reg && peercnt->limit) {
2391 return; /* this peercnt has a custom limit set by a registration */
2394 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2395 limit = addr_range->limit;
2396 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2397 ao2_ref(addr_range, -1);
2400 peercnt->limit = limit;
2405 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2407 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2409 struct peercnt *peercnt = obj;
2411 set_peercnt_limit(peercnt);
2412 ast_debug(1, "Reset limits for peercnts table\n");
2419 * \brief returns match if delme is set.
2421 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2423 struct addr_range *addr_range = obj;
2425 return addr_range->delme ? CMP_MATCH : 0;
2430 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2432 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2434 /* this function turns off and on custom callno limits set by peer registration */
2435 struct peercnt *peercnt;
2436 struct peercnt tmp = {
2439 struct sockaddr_in sin;
2441 ast_sockaddr_to_sin(sockaddr, &sin);
2443 tmp.addr = sin.sin_addr.s_addr;
2445 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2448 peercnt->limit = limit;
2450 set_peercnt_limit(peercnt);
2452 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2453 ao2_ref(peercnt, -1); /* decrement ref from find */
2459 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2461 * \details First searches for the address in the peercnts table. If found
2462 * the current count is incremented. If not found a new peercnt is allocated
2463 * and linked into the peercnts table with a call number count of 1.
2465 static int peercnt_add(struct sockaddr_in *sin)
2467 struct peercnt *peercnt;
2468 unsigned long addr = sin->sin_addr.s_addr;
2470 struct peercnt tmp = {
2474 /* Reasoning for peercnts container lock: Two identical ip addresses
2475 * could be added by different threads at the "same time". Without the container
2476 * lock, both threads could alloc space for the same object and attempt
2477 * to link to table. With the lock, one would create the object and link
2478 * to table while the other would find the already created peercnt object
2479 * rather than creating a new one. */
2481 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2483 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2485 /* create and set defaults */
2486 peercnt->addr = addr;
2487 set_peercnt_limit(peercnt);
2488 /* guarantees it does not go away after unlocking table
2489 * ao2_find automatically adds this */
2490 ao2_link(peercnts, peercnt);
2492 ao2_unlock(peercnts);
2496 /* check to see if the address has hit its callno limit. If not increment cur. */
2497 if (peercnt->limit > peercnt->cur) {
2499 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2500 } else { /* max num call numbers for this peer has been reached! */
2501 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2505 /* clean up locks and ref count */
2506 ao2_unlock(peercnt);
2507 ao2_unlock(peercnts);
2508 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2515 * \brief decrements a peercnts table entry
2517 static void peercnt_remove(struct peercnt *peercnt)
2519 struct sockaddr_in sin = {
2520 .sin_addr.s_addr = peercnt->addr,
2524 * Container locked here since peercnt may be unlinked from
2525 * list. If left unlocked, peercnt_add could try and grab this
2526 * entry from the table and modify it at the "same time" this
2527 * thread attemps to unlink it.
2531 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2532 /* if this was the last connection from the peer remove it from table */
2533 if (peercnt->cur == 0) {
2534 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2536 ao2_unlock(peercnts);
2541 * \brief called by scheduler to decrement object
2543 static int peercnt_remove_cb(const void *obj)
2545 struct peercnt *peercnt = (struct peercnt *) obj;
2547 peercnt_remove(peercnt);
2548 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2555 * \brief decrements peercnts connection count, finds by addr
2557 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2559 struct peercnt *peercnt;
2560 struct peercnt tmp = {
2561 .addr = sin->sin_addr.s_addr,
2564 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2565 peercnt_remove(peercnt);
2566 ao2_ref(peercnt, -1); /* decrement ref from find */
2573 * \brief Create callno_limit entry based on configuration
2575 static void build_callno_limits(struct ast_variable *v)
2577 struct addr_range *addr_range = NULL;
2578 struct addr_range tmp;
2584 for (; v; v = v->next) {
2588 ha = ast_append_ha("permit", v->name, NULL, &error);
2590 /* check for valid config information */
2592 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2594 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2595 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2600 ast_copy_ha(ha, &tmp.ha);
2601 /* find or create the addr_range */
2602 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2603 ao2_lock(addr_range);
2605 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2607 return; /* out of memory */
2610 /* copy over config data into addr_range object */
2611 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2612 ast_free_ha(ha); /* cleanup the tmp ha */
2613 addr_range->limit = limit;
2614 addr_range->delme = 0;
2618 ao2_unlock(addr_range);
2620 ao2_link(callno_limits, addr_range);
2622 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2628 * \brief Create calltoken_ignores entry based on configuration
2630 static int add_calltoken_ignore(const char *addr)
2632 struct addr_range tmp;
2633 struct addr_range *addr_range = NULL;
2634 struct ast_ha *ha = NULL;
2637 if (ast_strlen_zero(addr)) {
2638 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2642 ha = ast_append_ha("permit", addr, NULL, &error);
2644 /* check for valid config information */
2646 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2650 ast_copy_ha(ha, &tmp.ha);
2651 /* find or create the addr_range */
2652 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2653 ao2_lock(addr_range);
2654 addr_range->delme = 0;
2655 ao2_unlock(addr_range);
2656 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2657 /* copy over config data into addr_range object */
2658 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2659 ao2_link(calltoken_ignores, addr_range);
2666 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2671 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2673 struct ao2_iterator i;
2674 struct peercnt *peercnt;
2675 struct sockaddr_in sin;
2680 e->command = "iax2 show callnumber usage";
2682 "Usage: iax2 show callnumber usage [IP address]\n"
2683 " Shows current IP addresses which are consuming iax2 call numbers\n";
2688 if (a->argc < 4 || a->argc > 5)
2689 return CLI_SHOWUSAGE;
2692 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2695 i = ao2_iterator_init(peercnts, 0);
2696 while ((peercnt = ao2_iterator_next(&i))) {
2697 sin.sin_addr.s_addr = peercnt->addr;
2699 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2700 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2701 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2702 ao2_ref(peercnt, -1);
2707 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2709 ao2_ref(peercnt, -1);
2711 ao2_iterator_destroy(&i);
2714 size_t pool_avail = callno_pool.available;
2715 size_t trunk_pool_avail = callno_pool_trunk.available;
2717 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2718 "Non-CallToken Validated Callno Used: %d\n",
2719 global_maxcallno_nonval,
2720 total_nonval_callno_used);
2722 ast_cli(a->fd, "Total Available Callno: %zu\n"
2723 "Regular Callno Available: %zu\n"
2724 "Trunk Callno Available: %zu\n",
2725 pool_avail + trunk_pool_avail,
2728 } else if (a->argc == 5 && !found) {
2729 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2739 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2741 struct call_number_pool *pool = NULL;
2746 case CALLNO_TYPE_NORMAL:
2747 pool = &callno_pool;
2749 case CALLNO_TYPE_TRUNK:
2750 pool = &callno_pool_trunk;
2757 /* If we fail, make sure this has a defined value */
2760 /* We lock here primarily to ensure thread safety of the
2761 * total_nonval_callno_used check and increment */
2762 ast_mutex_lock(&callno_pool_lock);
2764 /* Bail out if we don't have any available call numbers */
2765 if (!pool->available) {
2766 ast_log(LOG_WARNING, "Out of call numbers\n");
2767 ast_mutex_unlock(&callno_pool_lock);
2771 /* Only a certain number of non-validated call numbers should be allocated.
2772 * If there ever is an attack, this separates the calltoken validating users
2773 * from the non-calltoken validating users. */
2774 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2775 ast_log(LOG_WARNING,
2776 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2777 total_nonval_callno_used,
2778 global_maxcallno_nonval);
2779 ast_mutex_unlock(&callno_pool_lock);
2783 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2784 * available call numbers. The array of call numbers begins as an ordered
2785 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2786 * - let's call that x. When a call number is needed we pick a random index
2787 * into the array between 0 and x and use that as our call number. In a
2788 * typical FYD shuffle, we would swap the value that we are extracting with
2789 * the number at x, but in our case we swap and don't touch the value at x
2790 * because it is effectively invisible. We rely on the rest of the IAX2 core
2791 * to return the number to us at some point. Finally, we decrement x by 1
2792 * which establishes our new unused range.
2794 * When numbers are returned to the pool, we put them just past x and bump x
2795 * by 1 so that this number is now available for re-use. */
2797 choice = ast_random() % pool->available;
2799 *entry = pool->numbers[choice];
2800 swap = pool->numbers[pool->available - 1];
2802 pool->numbers[choice] = swap;
2806 CALLNO_ENTRY_SET_VALIDATED(*entry);
2808 total_nonval_callno_used++;
2811 ast_mutex_unlock(&callno_pool_lock);
2816 static int replace_callno(const void *obj)
2818 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2819 struct call_number_pool *pool;
2821 /* We lock here primarily to ensure thread safety of the
2822 * total_nonval_callno_used check and decrement */
2823 ast_mutex_lock(&callno_pool_lock);
2825 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2826 if (total_nonval_callno_used) {
2827 total_nonval_callno_used--;
2830 "Attempted to decrement total non calltoken validated "
2831 "callnumbers below zero. Callno is: %d\n",
2832 CALLNO_ENTRY_GET_CALLNO(entry));
2836 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2837 pool = &callno_pool;
2839 pool = &callno_pool_trunk;
2842 ast_assert(pool->capacity > pool->available);
2844 /* This clears the validated flag */
2845 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2847 pool->numbers[pool->available] = entry;
2850 ast_mutex_unlock(&callno_pool_lock);
2855 static int create_callno_pools(void)
2859 callno_pool.available = callno_pool_trunk.available = 0;
2861 /* We start at 2. 0 and 1 are reserved. */
2862 for (i = 2; i < TRUNK_CALL_START; i++) {
2863 callno_pool.numbers[callno_pool.available] = i;
2864 callno_pool.available++;
2867 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2868 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2869 callno_pool_trunk.available++;
2872 callno_pool.capacity = callno_pool.available;
2873 callno_pool_trunk.capacity = callno_pool_trunk.available;
2875 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2882 * \brief Schedules delayed removal of iax2_pvt call number data
2884 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2885 * avaliable again, and the address from the previous connection must be decremented
2886 * from the peercnts table. This function schedules these operations to take place.
2888 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry)
2891 struct peercnt *peercnt;
2892 struct peercnt tmp = {
2893 .addr = sin->sin_addr.s_addr,
2896 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2897 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2898 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2899 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2901 ao2_ref(peercnt, -1);
2907 MIN_REUSE_TIME * 1000,
2909 CALLNO_ENTRY_TO_PTR(entry));
2914 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2916 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2919 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2921 if (frametype != AST_FRAME_IAX) {
2925 case IAX_COMMAND_NEW:
2926 case IAX_COMMAND_REGREQ:
2927 case IAX_COMMAND_FWDOWNL:
2928 case IAX_COMMAND_REGREL:
2930 case IAX_COMMAND_POKE:
2940 * \note Calling this function while holding another pvt lock can cause a deadlock.
2942 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2946 /* this call is calltoken validated as long as it is either NEW_FORCE
2947 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2948 int validated = (new > NEW_ALLOW) ? 1 : 0;
2951 if (new <= NEW_ALLOW) {
2953 struct chan_iax2_pvt *pvt;
2954 struct chan_iax2_pvt tmp_pvt = {
2956 .peercallno = callno,
2957 .transfercallno = callno,
2959 .frames_received = check_dcallno,
2962 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2963 /* this works for finding normal call numbers not involving transfering */
2964 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2965 if (return_locked) {
2966 ast_mutex_lock(&iaxsl[pvt->callno]);
2973 /* this searches for transfer call numbers that might not get caught otherwise */
2974 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2975 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2976 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2977 if (return_locked) {
2978 ast_mutex_lock(&iaxsl[pvt->callno]);
2986 /* This will occur on the first response to a message that we initiated,
2987 * such as a PING. */
2989 ast_mutex_lock(&iaxsl[dcallno]);
2991 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2992 iaxs[dcallno]->peercallno = callno;
2994 store_by_peercallno(iaxs[dcallno]);
2995 if (!res || !return_locked) {
2996 ast_mutex_unlock(&iaxsl[dcallno]);
3001 ast_mutex_unlock(&iaxsl[dcallno]);
3004 if (!res && (new >= NEW_ALLOW)) {
3006 /* It may seem odd that we look through the peer list for a name for
3007 * this *incoming* call. Well, it is weird. However, users don't
3008 * have an IP address/port number that we can match against. So,
3009 * this is just checking for a peer that has that IP/port and
3010 * assuming that we have a user of the same name. This isn't always
3011 * correct, but it will be changed if needed after authentication. */
3012 if (!iax2_getpeername(*sin, host, sizeof(host)))
3013 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
3015 if (peercnt_add(sin)) {
3016 /* This address has hit its callnumber limit. When the limit
3017 * is reached, the connection is not added to the peercnts table.*/
3021 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3022 /* since we ran out of space, remove the peercnt
3023 * entry we added earlier */
3024 peercnt_remove_by_addr(sin);
3025 ast_log(LOG_WARNING, "No more space\n");
3028 x = CALLNO_ENTRY_GET_CALLNO(entry);
3029 ast_mutex_lock(&iaxsl[x]);
3031 iaxs[x] = new_iax(sin, host);
3034 ast_debug(1, "Creating new call structure %d\n", x);
3035 iaxs[x]->callno_entry = entry;
3036 iaxs[x]->sockfd = sockfd;
3037 iaxs[x]->addr.sin_port = sin->sin_port;
3038 iaxs[x]->addr.sin_family = sin->sin_family;
3039 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
3040 iaxs[x]->peercallno = callno;
3041 iaxs[x]->callno = x;
3042 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3043 iaxs[x]->expiry = min_reg_expire;
3044 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3045 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3046 iaxs[x]->amaflags = amaflags;
3047 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3048 ast_string_field_set(iaxs[x], accountcode, accountcode);
3049 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3050 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3051 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3053 if (iaxs[x]->peercallno) {
3054 store_by_peercallno(iaxs[x]);
3057 ast_log(LOG_WARNING, "Out of resources\n");
3058 ast_mutex_unlock(&iaxsl[x]);
3059 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3063 ast_mutex_unlock(&iaxsl[x]);
3069 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3070 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3073 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3075 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3079 * \brief Queue a frame to a call's owning asterisk channel
3081 * \pre This function assumes that iaxsl[callno] is locked when called.
3083 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3084 * was valid before calling it, it may no longer be valid after calling it.
3085 * This function may unlock and lock the mutex associated with this callno,
3086 * meaning that another thread may grab it and destroy the call.
3088 static int iax2_queue_frame(int callno, struct ast_frame *f)
3090 iax2_lock_owner(callno);
3091 if (iaxs[callno] && iaxs[callno]->owner) {
3092 ast_queue_frame(iaxs[callno]->owner, f);
3093 ast_channel_unlock(iaxs[callno]->owner);
3099 * \brief Queue a hold frame on the ast_channel owner
3101 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3102 * is active for the given call number.
3104 * \pre Assumes lock for callno is already held.
3106 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3107 * was valid before calling it, it may no longer be valid after calling it.
3108 * This function may unlock and lock the mutex associated with this callno,
3109 * meaning that another thread may grab it and destroy the call.
3111 static int iax2_queue_hold(int callno, const char *musicclass)
3113 iax2_lock_owner(callno);
3114 if (iaxs[callno] && iaxs[callno]->owner) {
3115 ast_queue_hold(iaxs[callno]->owner, musicclass);
3116 ast_channel_unlock(iaxs[callno]->owner);
3122 * \brief Queue an unhold frame on the ast_channel owner
3124 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3125 * is active for the given call number.
3127 * \pre Assumes lock for callno is already held.
3129 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3130 * was valid before calling it, it may no longer be valid after calling it.
3131 * This function may unlock and lock the mutex associated with this callno,
3132 * meaning that another thread may grab it and destroy the call.
3134 static int iax2_queue_unhold(int callno)
3136 iax2_lock_owner(callno);
3137 if (iaxs[callno] && iaxs[callno]->owner) {
3138 ast_queue_unhold(iaxs[callno]->owner);
3139 ast_channel_unlock(iaxs[callno]->owner);
3145 * \brief Queue a hangup frame on the ast_channel owner
3147 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3148 * is active for the given call number.
3150 * \pre Assumes lock for callno is already held.
3152 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3153 * was valid before calling it, it may no longer be valid after calling it.
3154 * This function may unlock and lock the mutex associated with this callno,
3155 * meaning that another thread may grab it and destroy the call.
3157 static int iax2_queue_hangup(int callno)
3159 iax2_lock_owner(callno);
3160 if (iaxs[callno] && iaxs[callno]->owner) {
3161 ast_queue_hangup(iaxs[callno]->owner);
3162 ast_channel_unlock(iaxs[callno]->owner);
3168 * \note This function assumes that iaxsl[callno] is locked when called.
3170 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3171 * was valid before calling it, it may no longer be valid after calling it.
3172 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3173 * associated with this callno, meaning that another thread may grab it and destroy the call.
3175 static int __do_deliver(void *data)
3177 /* Just deliver the packet by using queueing. This is called by
3178 the IAX thread with the iaxsl lock held. */
3179 struct iax_frame *fr = data;
3181 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3182 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3183 iax2_queue_frame(fr->callno, &fr->af);
3184 /* Free our iax frame */
3185 iax2_frame_free(fr);
3186 /* And don't run again */
3190 static int handle_error(void)
3192 /* XXX Ideally we should figure out why an error occurred and then abort those
3193 rather than continuing to try. Unfortunately, the published interface does
3194 not seem to work XXX */
3196 struct sockaddr_in *sin;
3199 struct sock_extended_err e;
3204 m.msg_controllen = sizeof(e);
3206 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3208 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3210 if (m.msg_controllen) {
3211 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3213 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3215 ast_log(LOG_WARNING, "No address detected??\n");
3217 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3224 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3227 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3230 ast_debug(1, "Received error: %s\n", strerror(errno));
3237 static int send_packet(struct iax_frame *f)
3240 int callno = f->callno;
3242 /* Don't send if there was an error, but return error instead */
3243 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3246 /* Called with iaxsl held */
3248 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3251 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3252 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3254 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3255 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3259 ast_debug(1, "Received error: %s\n", strerror(errno));
3268 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3269 * for the given call number may disappear during its execution.
3271 static int iax2_predestroy(int callno)
3273 struct ast_channel *c = NULL;
3274 struct chan_iax2_pvt *pvt = iaxs[callno];
3279 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3280 iax2_destroy_helper(pvt);
3281 ast_set_flag64(pvt, IAX_ALREADYGONE);
3284 if ((c = pvt->owner)) {
3285 ast_channel_tech_pvt_set(c, NULL);
3286 iax2_queue_hangup(callno);
3288 ast_module_unref(ast_module_info->self);