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 <use type="external">crypto</use>
44 <support_level>core</support_level>
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
59 #include <sys/signal.h>
67 #include "asterisk/paths.h"
69 #include "asterisk/lock.h"
70 #include "asterisk/frame.h"
71 #include "asterisk/channel.h"
72 #include "asterisk/module.h"
73 #include "asterisk/pbx.h"
74 #include "asterisk/sched.h"
75 #include "asterisk/io.h"
76 #include "asterisk/config.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/cdr.h"
81 #include "asterisk/crypto.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/app.h"
86 #include "asterisk/astdb.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/features.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/causes.h"
91 #include "asterisk/localtime.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
97 #include "asterisk/event.h"
98 #include "asterisk/astobj2.h"
99 #include "asterisk/timing.h"
100 #include "asterisk/taskprocessor.h"
101 #include "asterisk/test.h"
102 #include "asterisk/data.h"
103 #include "asterisk/netsock2.h"
104 #include "asterisk/security_events.h"
105 #include "asterisk/bridging.h"
107 #include "iax2/include/iax2.h"
108 #include "iax2/include/firmware.h"
109 #include "iax2/include/parser.h"
110 #include "iax2/include/provision.h"
111 #include "jitterbuf.h"
114 <application name="IAX2Provision" language="en_US">
116 Provision a calling IAXy with a given template.
119 <parameter name="template">
120 <para>If not specified, defaults to <literal>default</literal>.</para>
124 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
125 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
126 or <literal>0</literal> on success.</para>
129 <function name="IAXPEER" language="en_US">
131 Gets IAX peer information.
134 <parameter name="peername" required="true">
136 <enum name="CURRENTCHANNEL">
137 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
138 endpoint of the current channel</para>
142 <parameter name="item">
143 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
146 <para>(default) The IP address.</para>
149 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
151 <enum name="mailbox">
152 <para>The configured mailbox.</para>
154 <enum name="context">
155 <para>The configured context.</para>
158 <para>The epoch time of the next expire.</para>
160 <enum name="dynamic">
161 <para>Is it dynamic? (yes/no).</para>
163 <enum name="callerid_name">
164 <para>The configured Caller ID name.</para>
166 <enum name="callerid_num">
167 <para>The configured Caller ID number.</para>
170 <para>The configured codecs.</para>
172 <enum name="codec[x]">
173 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
174 with <literal>0</literal>)</para>
180 <para>Gets information associated with the specified IAX2 peer.</para>
183 <ref type="function">SIPPEER</ref>
186 <function name="IAXVAR" language="en_US">
188 Sets or retrieves a remote variable.
191 <parameter name="varname" required="true" />
194 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
197 <manager name="IAXpeers" language="en_US">
202 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
207 <manager name="IAXpeerlist" language="en_US">
212 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
215 <para>List all the IAX peers.</para>
218 <manager name="IAXnetstats" language="en_US">
224 <para>Show IAX channels network statistics.</para>
227 <manager name="IAXregistry" language="en_US">
229 Show IAX registrations.
232 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
235 <para>Show IAX registrations.</para>
240 /* Define SCHED_MULTITHREADED to run the scheduler in a special
241 multithreaded mode. */
242 #define SCHED_MULTITHREADED
244 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
245 thread is actually doing. */
246 #define DEBUG_SCHED_MULTITHREAD
250 static int nochecksums = 0;
253 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
254 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
256 #define DEFAULT_THREAD_COUNT 10
257 #define DEFAULT_MAX_THREAD_COUNT 100
258 #define DEFAULT_RETRY_TIME 1000
259 #define MEMORY_SIZE 100
260 #define DEFAULT_DROP 3
262 #define DEBUG_SUPPORT
264 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
266 /* Sample over last 100 units to determine historic jitter */
269 static struct ast_codec_pref prefs;
271 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
274 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
275 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
276 #define MAX_TRUNK_MTU 1240
278 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
279 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
281 #define DEFAULT_CONTEXT "default"
283 static char default_parkinglot[AST_MAX_CONTEXT];
285 static char language[MAX_LANGUAGE] = "";
286 static char regcontext[AST_MAX_CONTEXT] = "";
288 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
289 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
290 static int network_change_sched_id = -1;
292 static int maxauthreq = 3;
293 static int max_retries = 4;
294 static int ping_time = 21;
295 static int lagrq_time = 10;
296 static int maxjitterbuffer=1000;
297 static int resyncthreshold=1000;
298 static int maxjitterinterps=10;
299 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
301 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
303 static int trunkfreq = 20;
304 static int trunkmaxsize = MAX_TRUNKDATA;
306 static int authdebug = 0;
307 static int autokill = 0;
308 static int iaxcompat = 0;
309 static int last_authmethod = 0;
311 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
313 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
320 static int min_reg_expire;
321 static int max_reg_expire;
323 static int srvlookup = 0;
325 static struct ast_timer *timer; /* Timer for trunking */
327 static struct ast_netsock_list *netsock;
328 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
329 static int defaultsockfd = -1;
331 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
334 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
336 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
338 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
339 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
341 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
342 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
343 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
344 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
346 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
347 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
348 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
349 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
351 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
352 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
355 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
356 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
357 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
359 /* if a pvt has encryption setup done and is running on the call */
360 #define IAX_CALLENCRYPTED(pvt) \
361 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
363 #define IAX_DEBUGDIGEST(msg, key) do { \
365 char digest[33] = ""; \
370 for (idx = 0; idx < 16; idx++) \
371 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
373 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
376 static struct io_context *io;
377 static struct ast_sched_context *sched;
379 #define DONT_RESCHEDULE -2
381 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
383 static int iaxdebug = 0;
385 static int iaxtrunkdebug = 0;
387 static int test_losspct = 0;
389 static int test_late = 0;
390 static int test_resync = 0;
391 static int test_jit = 0;
392 static int test_jitpct = 0;
393 #endif /* IAXTESTS */
395 static char accountcode[AST_MAX_ACCOUNT_CODE];
396 static char mohinterpret[MAX_MUSICCLASS];
397 static char mohsuggest[MAX_MUSICCLASS];
398 static int amaflags = 0;
400 static int delayreject = 0;
401 static int iax2_encryption = 0;
403 static struct ast_flags64 globalflags = { 0 };
405 static pthread_t netthreadid = AST_PTHREADT_NULL;
408 IAX_STATE_STARTED = (1 << 0),
409 IAX_STATE_AUTHENTICATED = (1 << 1),
410 IAX_STATE_TBD = (1 << 2),
413 struct iax2_context {
414 char context[AST_MAX_CONTEXT];
415 struct iax2_context *next;
419 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
420 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
421 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
422 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
423 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
424 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
425 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
426 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
427 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
428 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
429 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
430 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
431 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
432 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
433 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
434 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
435 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
436 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
437 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
438 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
439 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
440 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
441 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
442 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
443 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
444 #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 */
445 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
446 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
447 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
448 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
449 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
450 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
451 static int global_rtautoclear = 120;
453 static int reload_config(int forced_reload);
456 * \brief Call token validation settings.
458 enum calltoken_peer_enum {
459 /*! \brief Default calltoken required unless the ip is in the ignorelist */
460 CALLTOKEN_DEFAULT = 0,
461 /*! \brief Require call token validation. */
463 /*! \brief Require call token validation after a successful registration
464 * using call token validation occurs. */
466 /*! \brief Do not require call token validation. */
471 AST_DECLARE_STRING_FIELDS(
472 AST_STRING_FIELD(name);
473 AST_STRING_FIELD(secret);
474 AST_STRING_FIELD(dbsecret);
475 AST_STRING_FIELD(accountcode);
476 AST_STRING_FIELD(mohinterpret);
477 AST_STRING_FIELD(mohsuggest);
478 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
479 AST_STRING_FIELD(language);
480 AST_STRING_FIELD(cid_num);
481 AST_STRING_FIELD(cid_name);
482 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
490 iax2_format capability;
491 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
492 int curauthreq; /*!< Current number of outstanding AUTHREQs */
493 struct ast_codec_pref prefs;
494 struct ast_acl_list *acl;
495 struct iax2_context *contexts;
496 struct ast_variable *vars;
497 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
501 AST_DECLARE_STRING_FIELDS(
502 AST_STRING_FIELD(name);
503 AST_STRING_FIELD(username);
504 AST_STRING_FIELD(description); /*!< Description of the peer */
505 AST_STRING_FIELD(secret);
506 AST_STRING_FIELD(dbsecret);
507 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
509 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
510 AST_STRING_FIELD(context); /*!< For transfers only */
511 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
512 AST_STRING_FIELD(mailbox); /*!< Mailbox */
513 AST_STRING_FIELD(mohinterpret);
514 AST_STRING_FIELD(mohsuggest);
515 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
516 /* Suggested caller id if registering */
517 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
518 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
519 AST_STRING_FIELD(zonetag); /*!< Time Zone */
520 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
522 struct ast_codec_pref prefs;
523 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
524 struct ast_sockaddr addr;
526 int sockfd; /*!< Socket to use for transmission */
531 /* Dynamic Registration fields */
532 struct sockaddr_in defaddr; /*!< Default address if there is one */
533 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
534 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
536 int expire; /*!< Schedule entry for expiry */
537 int expiry; /*!< How soon to expire */
538 iax2_format capability; /*!< Capability */
541 int callno; /*!< Call number of POKE request */
542 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
543 int lastms; /*!< How long last response took (in ms), or -1 for no response */
544 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
546 int pokefreqok; /*!< How often to check if the host is up */
547 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
548 int historicms; /*!< How long recent average responses took */
549 int smoothing; /*!< Sample over how many units to determine historic ms */
550 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
552 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
554 struct ast_acl_list *acl;
555 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
558 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
560 struct iax2_trunk_peer {
563 struct sockaddr_in addr;
564 struct timeval txtrunktime; /*!< Transmit trunktime */
565 struct timeval rxtrunktime; /*!< Receive trunktime */
566 struct timeval lasttxtime; /*!< Last transmitted trunktime */
567 struct timeval trunkact; /*!< Last trunk activity */
568 unsigned int lastsent; /*!< Last sent time */
569 /* Trunk data and length */
570 unsigned char *trunkdata;
571 unsigned int trunkdatalen;
572 unsigned int trunkdataalloc;
576 AST_LIST_ENTRY(iax2_trunk_peer) list;
579 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
582 REG_STATE_UNREGISTERED = 0,
585 REG_STATE_REGISTERED,
591 enum iax_transfer_state {
596 TRANSFER_PASSTHROUGH,
600 TRANSFER_MPASSTHROUGH,
605 struct iax2_registry {
606 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
608 char secret[80]; /*!< Password or key name in []'s */
609 int expire; /*!< Sched ID of expiration */
610 int refresh; /*!< How often to refresh */
611 enum iax_reg_state regstate;
612 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
613 int callno; /*!< Associated call number if applicable */
614 struct sockaddr_in us; /*!< Who the server thinks we are */
615 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
616 AST_LIST_ENTRY(iax2_registry) entry;
619 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
621 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
622 #define MIN_RETRY_TIME 100
623 #define MAX_RETRY_TIME 10000
625 #define MAX_JITTER_BUFFER 50
626 #define MIN_JITTER_BUFFER 10
628 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
630 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
632 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
633 #define TS_GAP_FOR_JB_RESYNC 5000
635 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
636 #define MARK_IAX_SUBCLASS_TX 0x8000
638 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
639 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
640 static int iaxdynamicthreadcount = 0;
641 static int iaxdynamicthreadnum = 0;
642 static int iaxactivethreadcount = 0;
656 /* We use the high order bit as the validated flag, and the lower 15 as the
657 * actual call number */
658 typedef uint16_t callno_entry;
660 struct chan_iax2_pvt {
661 /*! Socket to send/receive on for this call */
663 /*! ast_callid bound to dialog */
664 struct ast_callid *callid;
665 /*! Last received voice format */
666 iax2_format voiceformat;
667 /*! Last received video format */
668 iax2_format videoformat;
669 /*! Last sent voice format */
670 iax2_format svoiceformat;
671 /*! Last sent video format */
672 iax2_format svideoformat;
673 /*! What we are capable of sending */
674 iax2_format capability;
675 /*! Last received timestamp */
677 /*! Last sent timestamp - never send the same timestamp twice in a single call */
678 unsigned int lastsent;
679 /*! Timestamp of the last video frame sent */
680 unsigned int lastvsent;
681 /*! Next outgoing timestamp if everything is good */
682 unsigned int nextpred;
683 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
684 int first_iax_message;
685 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
686 int last_iax_message;
687 /*! True if the last voice we transmitted was not silence/CNG */
688 unsigned int notsilenttx:1;
690 unsigned int pingtime;
691 /*! Max time for initial response */
694 struct sockaddr_in addr;
695 /*! Actual used codec preferences */
696 struct ast_codec_pref prefs;
697 /*! Requested codec preferences */
698 struct ast_codec_pref rprefs;
699 /*! Our call number */
700 unsigned short callno;
701 /*! Our callno_entry entry */
702 callno_entry callno_entry;
704 unsigned short peercallno;
705 /*! Negotiated format, this is only used to remember what format was
706 chosen for an unauthenticated call so that the channel can get
707 created later using the right format */
708 iax2_format chosenformat;
709 /*! Peer selected format */
710 iax2_format peerformat;
711 /*! Peer capability */
712 iax2_format peercapability;
713 /*! timeval that we base our transmission on */
714 struct timeval offset;
715 /*! timeval that we base our delivery on */
716 struct timeval rxcore;
717 /*! The jitterbuffer */
719 /*! active jb read scheduler id */
723 /*! Error, as discovered by the manager */
725 /*! Owner if we have one */
726 struct ast_channel *owner;
727 /*! What's our state? */
728 struct ast_flags state;
729 /*! Expiry (optional) */
731 /*! Next outgoing sequence number */
732 unsigned char oseqno;
733 /*! Next sequence number they have not yet acknowledged */
734 unsigned char rseqno;
735 /*! Next incoming sequence number */
736 unsigned char iseqno;
737 /*! Last incoming sequence number we have acknowledged */
738 unsigned char aseqno;
740 AST_DECLARE_STRING_FIELDS(
742 AST_STRING_FIELD(peer);
743 /*! Default Context */
744 AST_STRING_FIELD(context);
745 /*! Caller ID if available */
746 AST_STRING_FIELD(cid_num);
747 AST_STRING_FIELD(cid_name);
748 /*! Hidden Caller ID (i.e. ANI) if appropriate */
749 AST_STRING_FIELD(ani);
751 AST_STRING_FIELD(dnid);
753 AST_STRING_FIELD(rdnis);
754 /*! Requested Extension */
755 AST_STRING_FIELD(exten);
756 /*! Expected Username */
757 AST_STRING_FIELD(username);
758 /*! Expected Secret */
759 AST_STRING_FIELD(secret);
761 AST_STRING_FIELD(challenge);
762 /*! Public keys permitted keys for incoming authentication */
763 AST_STRING_FIELD(inkeys);
764 /*! Private key for outgoing authentication */
765 AST_STRING_FIELD(outkey);
766 /*! Preferred language */
767 AST_STRING_FIELD(language);
768 /*! Hostname/peername for naming purposes */
769 AST_STRING_FIELD(host);
771 AST_STRING_FIELD(dproot);
772 AST_STRING_FIELD(accountcode);
773 AST_STRING_FIELD(mohinterpret);
774 AST_STRING_FIELD(mohsuggest);
775 /*! received OSP token */
776 AST_STRING_FIELD(osptoken);
777 /*! Default parkinglot */
778 AST_STRING_FIELD(parkinglot);
780 /*! AUTHREJ all AUTHREP frames */
782 /*! permitted authentication methods */
784 /*! permitted encryption methods */
786 /*! Encryption AES-128 Key */
787 ast_aes_encrypt_key ecx;
788 /*! Decryption AES-128 Key corresponding to ecx */
789 ast_aes_decrypt_key mydcx;
790 /*! Decryption AES-128 Key used to decrypt peer frames */
791 ast_aes_decrypt_key dcx;
792 /*! scheduler id associated with iax_key_rotate
793 * for encrypted calls*/
795 /*! 32 bytes of semi-random data */
796 unsigned char semirand[32];
797 /*! Associated registry */
798 struct iax2_registry *reg;
799 /*! Associated peer for poking */
800 struct iax2_peer *peerpoke;
805 /*! Transferring status */
806 enum iax_transfer_state transferring;
807 /*! Transfer identifier */
809 /*! Who we are IAX transferring to */
810 struct sockaddr_in transfer;
811 /*! What's the new call number for the transfer */
812 unsigned short transfercallno;
813 /*! Transfer encrypt AES-128 Key */
814 ast_aes_encrypt_key tdcx;
816 /*! Status of knowledge of peer ADSI capability */
819 /*! Who we are bridged to */
820 unsigned short bridgecallno;
822 int pingid; /*!< Transmit PING request */
823 int lagid; /*!< Retransmit lag request */
824 int autoid; /*!< Auto hangup for Dialplan requestor */
825 int authid; /*!< Authentication rejection ID */
826 int authfail; /*!< Reason to report failure */
827 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
832 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
833 /*! variables inherited from the user definition */
834 struct ast_variable *vars;
835 /*! variables transmitted in a NEW packet */
836 struct ast_variable *iaxvars;
837 /*! last received remote rr */
838 struct iax_rr remote_rr;
839 /*! Current base time: (just for stats) */
841 /*! Dropped frame count: (just for stats) */
843 /*! received frame count: (just for stats) */
845 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
846 unsigned char calltoken_ie_len;
847 /*! hold all signaling frames from the pbx thread until we have a destination callno */
849 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
850 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
853 struct signaling_queue_entry {
855 AST_LIST_ENTRY(signaling_queue_entry) next;
863 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
864 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
866 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
867 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
868 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
870 struct call_number_pool {
873 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
876 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
878 /*! table of available call numbers */
879 static struct call_number_pool callno_pool;
881 /*! table of available trunk call numbers */
882 static struct call_number_pool callno_pool_trunk;
885 * \brief a list of frames that may need to be retransmitted
887 * \note The contents of this list do not need to be explicitly destroyed
888 * on module unload. This is because all active calls are destroyed, and
889 * all frames in this queue will get destroyed as a part of that process.
891 * \note Contents protected by the iaxsl[] locks
893 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
895 static struct ast_taskprocessor *transmit_processor;
897 static int randomcalltokendata;
899 static const time_t MAX_CALLTOKEN_DELAY = 10;
902 * This module will get much higher performance when doing a lot of
903 * user and peer lookups if the number of buckets is increased from 1.
904 * However, to maintain old behavior for Asterisk 1.4, these are set to
905 * 1 by default. When using multiple buckets, search order through these
906 * containers is considered random, so you will not be able to depend on
907 * the order the entires are specified in iax.conf for matching order. */
909 #define MAX_PEER_BUCKETS 17
911 #define MAX_PEER_BUCKETS 563
913 static struct ao2_container *peers;
915 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
916 static struct ao2_container *users;
918 /*! Table containing peercnt objects for every ip address consuming a callno */
919 static struct ao2_container *peercnts;
921 /*! Table containing custom callno limit rules for a range of ip addresses. */
922 static struct ao2_container *callno_limits;
924 /*! Table containing ip addresses not requiring calltoken validation */
925 static struct ao2_container *calltoken_ignores;
927 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
929 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
931 static uint16_t global_maxcallno;
933 /*! Total num of call numbers allowed to be allocated without calltoken validation */
934 static uint16_t global_maxcallno_nonval;
936 static uint16_t total_nonval_callno_used = 0;
938 /*! peer connection private, keeps track of all the call numbers
939 * consumed by a single ip address */
941 /*! ip address consuming call numbers */
943 /*! Number of call numbers currently used by this ip address */
945 /*! Max call numbers allowed for this ip address */
947 /*! Specifies whether limit is set by a registration or not, if so normal
948 * limit setting rules do not apply to this address. */
952 /*! used by both callno_limits and calltoken_ignores containers */
954 /*! ip address range for custom callno limit rule */
956 /*! callno limit for this ip address range, only used in callno_limits container */
958 /*! delete me marker for reloads */
963 /*! Extension exists */
964 CACHE_FLAG_EXISTS = (1 << 0),
965 /*! Extension is nonexistent */
966 CACHE_FLAG_NONEXISTENT = (1 << 1),
967 /*! Extension can exist */
968 CACHE_FLAG_CANEXIST = (1 << 2),
969 /*! Waiting to hear back response */
970 CACHE_FLAG_PENDING = (1 << 3),
972 CACHE_FLAG_TIMEOUT = (1 << 4),
973 /*! Request transmitted */
974 CACHE_FLAG_TRANSMITTED = (1 << 5),
976 CACHE_FLAG_UNKNOWN = (1 << 6),
978 CACHE_FLAG_MATCHMORE = (1 << 7),
981 struct iax2_dpcache {
982 char peercontext[AST_MAX_CONTEXT];
983 char exten[AST_MAX_EXTENSION];
985 struct timeval expiry;
987 unsigned short callno;
989 AST_LIST_ENTRY(iax2_dpcache) cache_list;
990 AST_LIST_ENTRY(iax2_dpcache) peer_list;
993 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
995 static void reg_source_db(struct iax2_peer *p);
996 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
997 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
999 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1000 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1001 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1003 enum iax2_thread_iostate {
1006 IAX_IOSTATE_PROCESSING,
1007 IAX_IOSTATE_SCHEDREADY,
1010 enum iax2_thread_type {
1011 IAX_THREAD_TYPE_POOL,
1012 IAX_THREAD_TYPE_DYNAMIC,
1015 struct iax2_pkt_buf {
1016 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1018 unsigned char buf[1];
1021 struct iax2_thread {
1022 AST_LIST_ENTRY(iax2_thread) list;
1023 enum iax2_thread_type type;
1024 enum iax2_thread_iostate iostate;
1025 #ifdef SCHED_MULTITHREADED
1026 void (*schedfunc)(const void *);
1027 const void *scheddata;
1029 #ifdef DEBUG_SCHED_MULTITHREAD
1035 struct sockaddr_in iosin;
1036 unsigned char readbuf[4096];
1044 ast_mutex_t init_lock;
1045 ast_cond_t init_cond;
1046 /*! if this thread is processing a full frame,
1047 some information about that frame will be stored
1048 here, so we can avoid dispatching any more full
1049 frames for that callno to other threads */
1051 unsigned short callno;
1052 struct sockaddr_in sin;
1056 /*! Queued up full frames for processing. If more full frames arrive for
1057 * a call which this thread is already processing a full frame for, they
1058 * are queued up here. */
1059 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1064 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1065 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1066 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1068 static void *iax2_process_thread(void *data);
1069 static void iax2_destroy(int callno);
1071 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1073 ast_mutex_lock(lock);
1074 ast_cond_signal(cond);
1075 ast_mutex_unlock(lock);
1079 * \brief an array of iax2 pvt structures
1081 * The container for active chan_iax2_pvt structures is implemented as an
1082 * array for extremely quick direct access to the correct pvt structure
1083 * based on the local call number. The local call number is used as the
1084 * index into the array where the associated pvt structure is stored.
1086 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1088 static struct ast_callid *iax_pvt_callid_get(int callno)
1090 if (iaxs[callno]->callid) {
1091 return ast_callid_ref(iaxs[callno]->callid);
1096 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1098 if (iaxs[callno]->callid) {
1099 ast_callid_unref(iaxs[callno]->callid);
1101 ast_callid_ref(callid);
1102 iaxs[callno]->callid = callid;
1105 static void iax_pvt_callid_new(int callno)
1107 struct ast_callid *callid = ast_create_callid();
1108 char buffer[AST_CALLID_BUFFER_LENGTH];
1109 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1110 iax_pvt_callid_set(callno, callid);
1111 ast_callid_unref(callid);
1115 * \brief Another container of iax2_pvt structures
1117 * Active IAX2 pvt structs are also stored in this container, if they are a part
1118 * of an active call where we know the remote side's call number. The reason
1119 * for this is that incoming media frames do not contain our call number. So,
1120 * instead of having to iterate the entire iaxs array, we use this container to
1121 * look up calls where the remote side is using a given call number.
1123 static struct ao2_container *iax_peercallno_pvts;
1126 * \brief chan_iax2_pvt structure locks
1128 * These locks are used when accessing a pvt structure in the iaxs array.
1129 * The index used here is the same as used in the iaxs array. It is the
1130 * local call number for the associated pvt struct.
1132 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1135 * * \brief Another container of iax2_pvt structures
1137 * Active IAX2 pvt stucts used during transfering a call are stored here.
1139 static struct ao2_container *iax_transfercallno_pvts;
1141 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1142 but keeps the division between trunked and non-trunked better. */
1143 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1145 /* Debug routines... */
1146 static struct sockaddr_in debugaddr;
1148 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1151 (sin && debugaddr.sin_addr.s_addr &&
1152 (!ntohs(debugaddr.sin_port) ||
1153 debugaddr.sin_port == sin->sin_port) &&
1154 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1156 iax_showframe(f, fhi, rx, sin, datalen);
1159 iax_showframe(f, fhi, rx, sin, datalen);
1165 static void iax_debug_output(const char *data)
1168 ast_verbose("%s", data);
1171 static void iax_error_output(const char *data)
1173 ast_log(LOG_WARNING, "%s", data);
1176 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1181 va_start(args, fmt);
1182 vsnprintf(buf, sizeof(buf), fmt, args);
1185 ast_log(LOG_ERROR, "%s", buf);
1188 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1193 va_start(args, fmt);
1194 vsnprintf(buf, sizeof(buf), fmt, args);
1197 ast_log(LOG_WARNING, "%s", buf);
1200 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1205 va_start(args, fmt);
1206 vsnprintf(buf, sizeof(buf), fmt, args);
1209 ast_verbose("%s", buf);
1212 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1213 static int expire_registry(const void *data);
1214 static int iax2_answer(struct ast_channel *c);
1215 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1216 static int iax2_devicestate(const char *data);
1217 static int iax2_digit_begin(struct ast_channel *c, char digit);
1218 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1219 static int iax2_do_register(struct iax2_registry *reg);
1220 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1221 static int iax2_hangup(struct ast_channel *c);
1222 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1223 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1224 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1225 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1226 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1227 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1228 static int iax2_sendtext(struct ast_channel *c, const char *text);
1229 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1230 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1231 static int iax2_transfer(struct ast_channel *c, const char *dest);
1232 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1233 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1235 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1236 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1237 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1238 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1239 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1240 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1241 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1242 static struct ast_frame *iax2_read(struct ast_channel *c);
1243 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1244 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1245 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1246 static void *iax2_dup_variable_datastore(void *);
1247 static void prune_peers(void);
1248 static void prune_users(void);
1249 static void iax2_free_variable_datastore(void *);
1251 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1252 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1253 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1254 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1255 static void build_rand_pad(unsigned char *buf, ssize_t len);
1256 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1257 static int replace_callno(const void *obj);
1258 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry);
1259 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1260 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1262 /* BUGBUG The IAX2 channel driver needs its own native bridge technology. */
1263 static struct ast_channel_tech iax2_tech = {
1265 .description = tdesc,
1266 .properties = AST_CHAN_TP_WANTSJITTER,
1267 .requester = iax2_request,
1268 .devicestate = iax2_devicestate,
1269 .send_digit_begin = iax2_digit_begin,
1270 .send_digit_end = iax2_digit_end,
1271 .send_text = iax2_sendtext,
1272 .send_image = iax2_sendimage,
1273 .send_html = iax2_sendhtml,
1275 .hangup = iax2_hangup,
1276 .answer = iax2_answer,
1278 .write = iax2_write,
1279 .write_video = iax2_write,
1280 .indicate = iax2_indicate,
1281 .setoption = iax2_setoption,
1282 .queryoption = iax2_queryoption,
1283 .bridge = iax2_bridge,
1284 .transfer = iax2_transfer,
1285 .fixup = iax2_fixup,
1286 .func_channel_read = acf_channel_read,
1291 * \brief Obtain the owner channel lock if the owner exists.
1293 * \param callno IAX2 call id.
1295 * \note Assumes the iaxsl[callno] lock is already obtained.
1298 * IMPORTANT NOTE!!! Any time this function is used, even if
1299 * iaxs[callno] was valid before calling it, it may no longer be
1300 * valid after calling it. This function may unlock and lock
1301 * the mutex associated with this callno, meaning that another
1302 * thread may grab it and destroy the call.
1306 static void iax2_lock_owner(int callno)
1309 if (!iaxs[callno] || !iaxs[callno]->owner) {
1310 /* There is no owner lock to get. */
1313 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1314 /* We got the lock */
1317 /* Avoid deadlock by pausing and trying again */
1318 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1322 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
1324 /* The MWI subscriptions exist just so the core knows we care about those
1325 * mailboxes. However, we just grab the events out of the cache when it
1326 * is time to send MWI, since it is only sent with a REGACK. */
1329 static void network_change_stasis_subscribe(void)
1331 if (!network_change_sub) {
1332 network_change_sub = stasis_subscribe(ast_system_topic(),
1333 network_change_stasis_cb, NULL);
1337 static void network_change_stasis_unsubscribe(void)
1339 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1342 static void acl_change_stasis_subscribe(void)
1344 if (!acl_change_sub) {
1345 acl_change_sub = stasis_subscribe(ast_security_topic(),
1346 acl_change_stasis_cb, NULL);
1350 static void acl_change_stasis_unsubscribe(void)
1352 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1355 static int network_change_sched_cb(const void *data)
1357 struct iax2_registry *reg;
1358 network_change_sched_id = -1;
1359 AST_LIST_LOCK(®istrations);
1360 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1361 iax2_do_register(reg);
1363 AST_LIST_UNLOCK(®istrations);
1368 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1369 struct stasis_topic *topic, struct stasis_message *message)
1371 /* This callback is only concerned with network change messages from the system topic. */
1372 if (stasis_message_type(message) != ast_network_change_type()) {
1376 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1377 if (network_change_sched_id == -1) {
1378 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1382 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1383 struct stasis_topic *topic, struct stasis_message *message)
1385 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1389 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1394 /*! \brief Send manager event at call setup to link between Asterisk channel name
1395 and IAX2 call identifiers */
1396 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1398 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1399 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1400 pvt->owner ? ast_channel_name(pvt->owner) : "",
1401 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1404 static const struct ast_datastore_info iax2_variable_datastore_info = {
1405 .type = "IAX2_VARIABLE",
1406 .duplicate = iax2_dup_variable_datastore,
1407 .destroy = iax2_free_variable_datastore,
1410 static void *iax2_dup_variable_datastore(void *old)
1412 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1413 struct ast_var_t *oldvar, *newvar;
1415 newlist = ast_calloc(sizeof(*newlist), 1);
1417 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1421 AST_LIST_HEAD_INIT(newlist);
1422 AST_LIST_LOCK(oldlist);
1423 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1424 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1426 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1428 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1430 AST_LIST_UNLOCK(oldlist);
1434 static void iax2_free_variable_datastore(void *old)
1436 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1437 struct ast_var_t *oldvar;
1439 AST_LIST_LOCK(oldlist);
1440 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1443 AST_LIST_UNLOCK(oldlist);
1444 AST_LIST_HEAD_DESTROY(oldlist);
1449 /* WARNING: insert_idle_thread should only ever be called within the
1450 * context of an iax2_process_thread() thread.
1452 static void insert_idle_thread(struct iax2_thread *thread)
1454 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1455 AST_LIST_LOCK(&dynamic_list);
1456 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1457 AST_LIST_UNLOCK(&dynamic_list);
1459 AST_LIST_LOCK(&idle_list);
1460 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1461 AST_LIST_UNLOCK(&idle_list);
1467 static struct iax2_thread *find_idle_thread(void)
1469 struct iax2_thread *thread = NULL;
1471 /* Pop the head of the idle list off */
1472 AST_LIST_LOCK(&idle_list);
1473 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1474 AST_LIST_UNLOCK(&idle_list);
1476 /* If we popped a thread off the idle list, just return it */
1478 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1482 /* Pop the head of the dynamic list off */
1483 AST_LIST_LOCK(&dynamic_list);
1484 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1485 AST_LIST_UNLOCK(&dynamic_list);
1487 /* If we popped a thread off the dynamic list, just return it */
1489 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1493 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1494 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1497 /* Set default values */
1498 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1499 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1500 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1502 /* Initialize lock and condition */
1503 ast_mutex_init(&thread->lock);
1504 ast_cond_init(&thread->cond, NULL);
1505 ast_mutex_init(&thread->init_lock);
1506 ast_cond_init(&thread->init_cond, NULL);
1507 ast_mutex_lock(&thread->init_lock);
1509 /* Create thread and send it on it's way */
1510 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1511 ast_cond_destroy(&thread->cond);
1512 ast_mutex_destroy(&thread->lock);
1513 ast_mutex_unlock(&thread->init_lock);
1514 ast_cond_destroy(&thread->init_cond);
1515 ast_mutex_destroy(&thread->init_lock);
1520 /* this thread is not processing a full frame (since it is idle),
1521 so ensure that the field for the full frame call number is empty */
1522 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1524 /* Wait for the thread to be ready before returning it to the caller */
1525 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1527 /* Done with init_lock */
1528 ast_mutex_unlock(&thread->init_lock);
1533 #ifdef SCHED_MULTITHREADED
1534 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1536 struct iax2_thread *thread = NULL;
1537 static time_t lasterror;
1540 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);
1554 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1559 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1562 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1563 ast_sched_cb callback, const void *data)
1565 return ast_sched_replace(id, con, when, callback, data);
1568 static int iax2_sched_add(struct ast_sched_context *con, int when,
1569 ast_sched_cb callback, const void *data)
1571 return ast_sched_add(con, when, callback, data);
1574 static int send_ping(const void *data);
1576 static void __send_ping(const void *data)
1578 int callno = (long) data;
1580 ast_mutex_lock(&iaxsl[callno]);
1583 if (iaxs[callno]->peercallno) {
1584 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1585 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1586 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1590 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1593 ast_mutex_unlock(&iaxsl[callno]);
1596 static int send_ping(const void *data)
1598 int callno = (long) data;
1599 ast_mutex_lock(&iaxsl[callno]);
1600 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1601 iaxs[callno]->pingid = -1;
1603 ast_mutex_unlock(&iaxsl[callno]);
1605 #ifdef SCHED_MULTITHREADED
1606 if (schedule_action(__send_ping, data))
1613 static void encmethods_to_str(int e, struct ast_str **buf)
1615 ast_str_set(buf, 0, "(");
1616 if (e & IAX_ENCRYPT_AES128) {
1617 ast_str_append(buf, 0, "aes128");
1619 if (e & IAX_ENCRYPT_KEYROTATE) {
1620 ast_str_append(buf, 0, ",keyrotate");
1622 if (ast_str_strlen(*buf) > 1) {
1623 ast_str_append(buf, 0, ")");
1625 ast_str_set(buf, 0, "No");
1629 static int get_encrypt_methods(const char *s)
1632 if (!strcasecmp(s, "aes128"))
1633 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1634 else if (ast_true(s))
1635 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1641 static int send_lagrq(const void *data);
1643 static void __send_lagrq(const void *data)
1645 int callno = (long) data;
1647 ast_mutex_lock(&iaxsl[callno]);
1650 if (iaxs[callno]->peercallno) {
1651 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1652 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1653 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1657 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1660 ast_mutex_unlock(&iaxsl[callno]);
1663 static int send_lagrq(const void *data)
1665 int callno = (long) data;
1666 ast_mutex_lock(&iaxsl[callno]);
1667 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1668 iaxs[callno]->lagid = -1;
1670 ast_mutex_unlock(&iaxsl[callno]);
1672 #ifdef SCHED_MULTITHREADED
1673 if (schedule_action(__send_lagrq, data))
1679 static unsigned char compress_subclass(iax2_format subclass)
1683 /* If it's 64 or smaller, just return it */
1684 if (subclass < IAX_FLAG_SC_LOG)
1686 /* Otherwise find its power */
1687 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1688 if (subclass & (1LL << x)) {
1690 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1696 return power | IAX_FLAG_SC_LOG;
1699 static iax2_format uncompress_subclass(unsigned char csub)
1701 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1702 if (csub & IAX_FLAG_SC_LOG) {
1703 /* special case for 'compressed' -1 */
1707 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1713 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1715 struct ast_format_cap *cap;
1716 struct ast_format tmpfmt;
1717 iax2_format format = 0;
1718 if ((cap = ast_format_cap_alloc_nolock())) {
1719 ast_format_clear(&tmpfmt);
1720 ast_format_cap_from_old_bitfield(cap, formats);
1721 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1722 format = ast_format_to_old_bitfield(&tmpfmt);
1723 cap = ast_format_cap_destroy(cap);
1729 static iax2_format iax2_best_codec(iax2_format formats)
1731 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1732 struct ast_format tmpfmt;
1737 ast_format_clear(&tmpfmt);
1738 ast_format_cap_from_old_bitfield(cap, formats);
1739 ast_best_codec(cap, &tmpfmt);
1740 cap = ast_format_cap_destroy(cap);
1741 return ast_format_to_old_bitfield(&tmpfmt);
1744 const char *iax2_getformatname(iax2_format format)
1746 struct ast_format tmpfmt;
1747 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1751 return ast_getformatname(&tmpfmt);
1754 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1756 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1761 ast_format_cap_from_old_bitfield(cap, format);
1762 ast_getformatname_multiple(codec_buf, len, cap);
1763 cap = ast_format_cap_destroy(cap);
1768 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1771 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1776 ast_format_cap_from_old_bitfield(cap, *formats);
1777 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1778 *formats = ast_format_cap_to_old_bitfield(cap);
1779 cap = ast_format_cap_destroy(cap);
1784 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1787 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1791 ast_format_cap_from_old_bitfield(cap, formats);
1792 res = ast_data_add_codecs(root, node_name, cap);
1793 cap = ast_format_cap_destroy(cap);
1798 * \note The only member of the peer passed here guaranteed to be set is the name field
1800 static int peer_hash_cb(const void *obj, const int flags)
1802 const struct iax2_peer *peer = obj;
1803 const char *name = obj;
1805 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1809 * \note The only member of the peer passed here guaranteed to be set is the name field
1811 static int peer_cmp_cb(void *obj, void *arg, int flags)
1813 struct iax2_peer *peer = obj, *peer2 = arg;
1814 const char *name = arg;
1816 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1817 CMP_MATCH | CMP_STOP : 0;
1821 * \note The only member of the user passed here guaranteed to be set is the name field
1823 static int user_hash_cb(const void *obj, const int flags)
1825 const struct iax2_user *user = obj;
1826 const char *name = obj;
1828 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1832 * \note The only member of the user passed here guaranteed to be set is the name field
1834 static int user_cmp_cb(void *obj, void *arg, int flags)
1836 struct iax2_user *user = obj, *user2 = arg;
1837 const char *name = arg;
1839 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1840 CMP_MATCH | CMP_STOP : 0;
1844 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1845 * so do not call it with a pvt lock held.
1847 static struct iax2_peer *find_peer(const char *name, int realtime)
1849 struct iax2_peer *peer = NULL;
1851 peer = ao2_find(peers, name, OBJ_KEY);
1853 /* Now go for realtime if applicable */
1854 if(!peer && realtime)
1855 peer = realtime_peer(name, NULL);
1860 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1866 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1872 static struct iax2_user *find_user(const char *name)
1874 return ao2_find(users, name, OBJ_KEY);
1876 static inline struct iax2_user *user_ref(struct iax2_user *user)
1882 static inline struct iax2_user *user_unref(struct iax2_user *user)
1888 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1890 struct iax2_peer *peer = NULL;
1892 struct ao2_iterator i;
1894 i = ao2_iterator_init(peers, 0);
1895 while ((peer = ao2_iterator_next(&i))) {
1896 struct sockaddr_in peer_addr;
1898 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1900 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1901 (peer_addr.sin_port == sin.sin_port)) {
1902 ast_copy_string(host, peer->name, len);
1909 ao2_iterator_destroy(&i);
1912 peer = realtime_peer(NULL, &sin);
1914 ast_copy_string(host, peer->name, len);
1923 /*!\note Assumes the lock on the pvt is already held, when
1924 * iax2_destroy_helper() is called. */
1925 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1927 /* Decrement AUTHREQ count if needed */
1928 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1929 struct iax2_user *user;
1931 user = ao2_find(users, pvt->username, OBJ_KEY);
1933 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1937 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1939 /* No more pings or lagrq's */
1940 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1941 pvt->pingid = DONT_RESCHEDULE;
1942 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1943 pvt->lagid = DONT_RESCHEDULE;
1944 AST_SCHED_DEL(sched, pvt->autoid);
1945 AST_SCHED_DEL(sched, pvt->authid);
1946 AST_SCHED_DEL(sched, pvt->initid);
1947 AST_SCHED_DEL(sched, pvt->jbid);
1948 AST_SCHED_DEL(sched, pvt->keyrotateid);
1951 static void iax2_frame_free(struct iax_frame *fr)
1953 AST_SCHED_DEL(sched, fr->retrans);
1957 static int scheduled_destroy(const void *vid)
1959 unsigned short callno = PTR_TO_CALLNO(vid);
1960 ast_mutex_lock(&iaxsl[callno]);
1962 ast_debug(1, "Really destroying %d now...\n", callno);
1963 iax2_destroy(callno);
1965 ast_mutex_unlock(&iaxsl[callno]);
1969 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1972 ast_free(s->f.data.ptr);
1977 /*! \brief This function must be called once we are sure the other side has
1978 * given us a call number. All signaling is held here until that point. */
1979 static void send_signaling(struct chan_iax2_pvt *pvt)
1981 struct signaling_queue_entry *s = NULL;
1983 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1984 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1985 free_signaling_queue_entry(s);
1987 pvt->hold_signaling = 0;
1990 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1991 * we have received a destination call number. */
1992 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1994 struct signaling_queue_entry *qe;
1996 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1997 return 1; /* do not queue this frame */
1998 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1999 return -1; /* out of memory */
2002 /* copy ast_frame into our queue entry */
2004 if (qe->f.datalen) {
2005 /* if there is data in this frame copy it over as well */
2006 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2007 free_signaling_queue_entry(qe);
2010 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2012 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2017 static void pvt_destructor(void *obj)
2019 struct chan_iax2_pvt *pvt = obj;
2020 struct iax_frame *cur = NULL;
2021 struct signaling_queue_entry *s = NULL;
2023 ast_mutex_lock(&iaxsl[pvt->callno]);
2025 iax2_destroy_helper(pvt);
2027 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2028 pvt->callno_entry = 0;
2031 ast_set_flag64(pvt, IAX_ALREADYGONE);
2033 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2034 /* Cancel any pending transmissions */
2038 ast_mutex_unlock(&iaxsl[pvt->callno]);
2040 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2041 free_signaling_queue_entry(s);
2045 pvt->reg->callno = 0;
2051 ast_variables_destroy(pvt->vars);
2055 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2056 iax2_frame_free(frame.data);
2059 jb_destroy(pvt->jb);
2060 ast_string_field_free_memory(pvt);
2064 ast_callid_unref(pvt->callid);
2069 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2071 struct chan_iax2_pvt *tmp;
2074 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2078 if (ast_string_field_init(tmp, 32)) {
2090 tmp->keyrotateid = -1;
2092 ast_string_field_set(tmp,exten, "s");
2093 ast_string_field_set(tmp,host, host);
2097 jbconf.max_jitterbuf = maxjitterbuffer;
2098 jbconf.resync_threshold = resyncthreshold;
2099 jbconf.max_contig_interp = maxjitterinterps;
2100 jbconf.target_extra = jittertargetextra;
2101 jb_setconf(tmp->jb,&jbconf);
2103 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2105 tmp->hold_signaling = 1;
2106 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2111 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2113 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2115 size_t afdatalen = new->afdatalen;
2116 memcpy(new, fr, sizeof(*new));
2117 iax_frame_wrap(new, &fr->af);
2118 new->afdatalen = afdatalen;
2121 new->direction = DIRECTION_INGRESS;
2126 /* keep these defined in this order. They are used in find_callno to
2127 * determine whether or not a new call number should be allowed. */
2129 /* do not allow a new call number, only search ones in use for match */
2131 /* search for match first, then allow a new one to be allocated */
2133 /* do not search for match, force a new call number */
2135 /* do not search for match, force a new call number. Signifies call number
2136 * has been calltoken validated */
2137 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2140 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2142 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2143 (cur->addr.sin_port == sin->sin_port)) {
2144 /* This is the main host */
2145 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2146 (check_dcallno ? dcallno == cur->callno : 1) ) {
2147 /* That's us. Be sure we keep track of the peer call number */
2151 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2152 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2153 /* We're transferring */
2154 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2160 static int make_trunk(unsigned short callno, int locked)
2165 if (iaxs[callno]->oseqno) {
2166 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2169 if (callno >= TRUNK_CALL_START) {
2170 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2174 if (get_unused_callno(
2176 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2178 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2182 x = CALLNO_ENTRY_GET_CALLNO(entry);
2183 ast_mutex_lock(&iaxsl[x]);
2186 * \note We delete these before switching the slot, because if
2187 * they fire in the meantime, they will generate a warning.
2189 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2190 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2191 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2192 iaxs[x] = iaxs[callno];
2193 iaxs[x]->callno = x;
2195 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2196 * before assigning the new one */
2197 if (iaxs[x]->callno_entry) {
2200 MIN_REUSE_TIME * 1000,
2202 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2205 iaxs[x]->callno_entry = entry;
2207 iaxs[callno] = NULL;
2208 /* Update the two timers that should have been started */
2209 iaxs[x]->pingid = iax2_sched_add(sched,
2210 ping_time * 1000, send_ping, (void *)(long)x);
2211 iaxs[x]->lagid = iax2_sched_add(sched,
2212 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2215 ast_mutex_unlock(&iaxsl[callno]);
2218 ast_mutex_unlock(&iaxsl[x]);
2220 /* We moved this call from a non-trunked to a trunked call */
2221 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2226 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2228 if (!pvt->transfercallno) {
2229 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2233 ao2_link(iax_transfercallno_pvts, pvt);
2236 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2238 if (!pvt->transfercallno) {
2239 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2243 ao2_unlink(iax_transfercallno_pvts, pvt);
2245 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2247 if (!pvt->peercallno) {
2248 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2252 ao2_link(iax_peercallno_pvts, pvt);
2255 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2257 if (!pvt->peercallno) {
2258 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2262 ao2_unlink(iax_peercallno_pvts, pvt);
2265 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2267 struct addr_range *lim = obj;
2272 static int addr_range_hash_cb(const void *obj, const int flags)
2274 const struct addr_range *lim = obj;
2275 struct sockaddr_in sin;
2276 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2277 return abs((int) sin.sin_addr.s_addr);
2280 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2282 struct addr_range *lim1 = obj, *lim2 = arg;
2283 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2284 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2285 CMP_MATCH | CMP_STOP : 0;
2288 static int peercnt_hash_cb(const void *obj, const int flags)
2290 const struct peercnt *peercnt = obj;
2291 return abs((int) peercnt->addr);
2294 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2296 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2297 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2300 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2302 struct addr_range *addr_range = obj;
2303 struct sockaddr_in *sin = arg;
2304 struct sockaddr_in ha_netmask_sin;
2305 struct sockaddr_in ha_addr_sin;
2307 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2308 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2310 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2311 return CMP_MATCH | CMP_STOP;
2319 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2321 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2323 struct addr_range *addr_range;
2324 struct iax2_peer *peer = NULL;
2325 struct iax2_user *user = NULL;
2326 /* if no username is given, check for guest accounts */
2327 const char *find = S_OR(name, "guest");
2328 int res = 1; /* required by default */
2330 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2331 /* There are only two cases in which calltoken validation is not required.
2332 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2333 * the peer definition has not set the requirecalltoken option.
2334 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2337 /* ----- Case 1 ----- */
2338 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2339 ao2_ref(addr_range, -1);
2343 /* ----- Case 2 ----- */
2344 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2345 calltoken_required = user->calltoken_required;
2346 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2347 calltoken_required = user->calltoken_required;
2348 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2349 calltoken_required = peer->calltoken_required;
2350 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2351 calltoken_required = peer->calltoken_required;
2361 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);
2362 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2363 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2373 * \brief set peercnt callno limit.
2376 * First looks in custom definitions. If not found, global limit
2377 * is used. Entries marked as reg already have
2378 * a custom limit set by a registration and are not modified.
2380 static void set_peercnt_limit(struct peercnt *peercnt)
2382 uint16_t limit = global_maxcallno;
2383 struct addr_range *addr_range;
2384 struct sockaddr_in sin = {
2385 .sin_addr.s_addr = peercnt->addr,
2389 if (peercnt->reg && peercnt->limit) {
2390 return; /* this peercnt has a custom limit set by a registration */
2393 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2394 limit = addr_range->limit;
2395 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2396 ao2_ref(addr_range, -1);
2399 peercnt->limit = limit;
2404 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2406 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2408 struct peercnt *peercnt = obj;
2410 set_peercnt_limit(peercnt);
2411 ast_debug(1, "Reset limits for peercnts table\n");
2418 * \brief returns match if delme is set.
2420 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2422 struct addr_range *addr_range = obj;
2424 return addr_range->delme ? CMP_MATCH : 0;
2429 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2431 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2433 /* this function turns off and on custom callno limits set by peer registration */
2434 struct peercnt *peercnt;
2435 struct peercnt tmp = {
2438 struct sockaddr_in sin;
2440 ast_sockaddr_to_sin(sockaddr, &sin);
2442 tmp.addr = sin.sin_addr.s_addr;
2444 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2447 peercnt->limit = limit;
2449 set_peercnt_limit(peercnt);
2451 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2452 ao2_ref(peercnt, -1); /* decrement ref from find */
2458 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2460 * \details First searches for the address in the peercnts table. If found
2461 * the current count is incremented. If not found a new peercnt is allocated
2462 * and linked into the peercnts table with a call number count of 1.
2464 static int peercnt_add(struct sockaddr_in *sin)
2466 struct peercnt *peercnt;
2467 unsigned long addr = sin->sin_addr.s_addr;
2469 struct peercnt tmp = {
2473 /* Reasoning for peercnts container lock: Two identical ip addresses
2474 * could be added by different threads at the "same time". Without the container
2475 * lock, both threads could alloc space for the same object and attempt
2476 * to link to table. With the lock, one would create the object and link
2477 * to table while the other would find the already created peercnt object
2478 * rather than creating a new one. */
2480 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2482 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2484 /* create and set defaults */
2485 peercnt->addr = addr;
2486 set_peercnt_limit(peercnt);
2487 /* guarantees it does not go away after unlocking table
2488 * ao2_find automatically adds this */
2489 ao2_link(peercnts, peercnt);
2491 ao2_unlock(peercnts);
2495 /* check to see if the address has hit its callno limit. If not increment cur. */
2496 if (peercnt->limit > peercnt->cur) {
2498 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2499 } else { /* max num call numbers for this peer has been reached! */
2500 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2504 /* clean up locks and ref count */
2505 ao2_unlock(peercnt);
2506 ao2_unlock(peercnts);
2507 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2514 * \brief decrements a peercnts table entry
2516 static void peercnt_remove(struct peercnt *peercnt)
2518 struct sockaddr_in sin = {
2519 .sin_addr.s_addr = peercnt->addr,
2523 * Container locked here since peercnt may be unlinked from
2524 * list. If left unlocked, peercnt_add could try and grab this
2525 * entry from the table and modify it at the "same time" this
2526 * thread attemps to unlink it.
2530 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2531 /* if this was the last connection from the peer remove it from table */
2532 if (peercnt->cur == 0) {
2533 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2535 ao2_unlock(peercnts);
2540 * \brief called by scheduler to decrement object
2542 static int peercnt_remove_cb(const void *obj)
2544 struct peercnt *peercnt = (struct peercnt *) obj;
2546 peercnt_remove(peercnt);
2547 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2554 * \brief decrements peercnts connection count, finds by addr
2556 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2558 struct peercnt *peercnt;
2559 struct peercnt tmp = {
2560 .addr = sin->sin_addr.s_addr,
2563 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2564 peercnt_remove(peercnt);
2565 ao2_ref(peercnt, -1); /* decrement ref from find */
2572 * \brief Create callno_limit entry based on configuration
2574 static void build_callno_limits(struct ast_variable *v)
2576 struct addr_range *addr_range = NULL;
2577 struct addr_range tmp;
2583 for (; v; v = v->next) {
2587 ha = ast_append_ha("permit", v->name, NULL, &error);
2589 /* check for valid config information */
2591 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2593 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2594 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2599 ast_copy_ha(ha, &tmp.ha);
2600 /* find or create the addr_range */
2601 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2602 ao2_lock(addr_range);
2604 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2606 return; /* out of memory */
2609 /* copy over config data into addr_range object */
2610 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2611 ast_free_ha(ha); /* cleanup the tmp ha */
2612 addr_range->limit = limit;
2613 addr_range->delme = 0;
2617 ao2_unlock(addr_range);
2619 ao2_link(callno_limits, addr_range);
2621 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2627 * \brief Create calltoken_ignores entry based on configuration
2629 static int add_calltoken_ignore(const char *addr)
2631 struct addr_range tmp;
2632 struct addr_range *addr_range = NULL;
2633 struct ast_ha *ha = NULL;
2636 if (ast_strlen_zero(addr)) {
2637 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2641 ha = ast_append_ha("permit", addr, NULL, &error);
2643 /* check for valid config information */
2645 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2649 ast_copy_ha(ha, &tmp.ha);
2650 /* find or create the addr_range */
2651 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2652 ao2_lock(addr_range);
2653 addr_range->delme = 0;
2654 ao2_unlock(addr_range);
2655 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2656 /* copy over config data into addr_range object */
2657 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2658 ao2_link(calltoken_ignores, addr_range);
2665 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2670 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2672 struct ao2_iterator i;
2673 struct peercnt *peercnt;
2674 struct sockaddr_in sin;
2679 e->command = "iax2 show callnumber usage";
2681 "Usage: iax2 show callnumber usage [IP address]\n"
2682 " Shows current IP addresses which are consuming iax2 call numbers\n";
2687 if (a->argc < 4 || a->argc > 5)
2688 return CLI_SHOWUSAGE;
2691 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2694 i = ao2_iterator_init(peercnts, 0);
2695 while ((peercnt = ao2_iterator_next(&i))) {
2696 sin.sin_addr.s_addr = peercnt->addr;
2698 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2699 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2700 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2701 ao2_ref(peercnt, -1);
2706 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2708 ao2_ref(peercnt, -1);
2710 ao2_iterator_destroy(&i);
2713 size_t pool_avail = callno_pool.available;
2714 size_t trunk_pool_avail = callno_pool_trunk.available;
2716 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2717 "Non-CallToken Validated Callno Used: %d\n",
2718 global_maxcallno_nonval,
2719 total_nonval_callno_used);
2721 ast_cli(a->fd, "Total Available Callno: %zu\n"
2722 "Regular Callno Available: %zu\n"
2723 "Trunk Callno Available: %zu\n",
2724 pool_avail + trunk_pool_avail,
2727 } else if (a->argc == 5 && !found) {
2728 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2738 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2740 struct call_number_pool *pool = NULL;
2745 case CALLNO_TYPE_NORMAL:
2746 pool = &callno_pool;
2748 case CALLNO_TYPE_TRUNK:
2749 pool = &callno_pool_trunk;
2756 /* If we fail, make sure this has a defined value */
2759 /* We lock here primarily to ensure thread safety of the
2760 * total_nonval_callno_used check and increment */
2761 ast_mutex_lock(&callno_pool_lock);
2763 /* Bail out if we don't have any available call numbers */
2764 if (!pool->available) {
2765 ast_log(LOG_WARNING, "Out of call numbers\n");
2766 ast_mutex_unlock(&callno_pool_lock);
2770 /* Only a certain number of non-validated call numbers should be allocated.
2771 * If there ever is an attack, this separates the calltoken validating users
2772 * from the non-calltoken validating users. */
2773 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2774 ast_log(LOG_WARNING,
2775 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2776 total_nonval_callno_used,
2777 global_maxcallno_nonval);
2778 ast_mutex_unlock(&callno_pool_lock);
2782 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2783 * available call numbers. The array of call numbers begins as an ordered
2784 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2785 * - let's call that x. When a call number is needed we pick a random index
2786 * into the array between 0 and x and use that as our call number. In a
2787 * typical FYD shuffle, we would swap the value that we are extracting with
2788 * the number at x, but in our case we swap and don't touch the value at x
2789 * because it is effectively invisible. We rely on the rest of the IAX2 core
2790 * to return the number to us at some point. Finally, we decrement x by 1
2791 * which establishes our new unused range.
2793 * When numbers are returned to the pool, we put them just past x and bump x
2794 * by 1 so that this number is now available for re-use. */
2796 choice = ast_random() % pool->available;
2798 *entry = pool->numbers[choice];
2799 swap = pool->numbers[pool->available - 1];
2801 pool->numbers[choice] = swap;
2805 CALLNO_ENTRY_SET_VALIDATED(*entry);
2807 total_nonval_callno_used++;
2810 ast_mutex_unlock(&callno_pool_lock);
2815 static int replace_callno(const void *obj)
2817 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2818 struct call_number_pool *pool;
2820 /* We lock here primarily to ensure thread safety of the
2821 * total_nonval_callno_used check and decrement */
2822 ast_mutex_lock(&callno_pool_lock);
2824 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2825 if (total_nonval_callno_used) {
2826 total_nonval_callno_used--;
2829 "Attempted to decrement total non calltoken validated "
2830 "callnumbers below zero. Callno is: %d\n",
2831 CALLNO_ENTRY_GET_CALLNO(entry));
2835 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2836 pool = &callno_pool;
2838 pool = &callno_pool_trunk;
2841 ast_assert(pool->capacity > pool->available);
2843 /* This clears the validated flag */
2844 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2846 pool->numbers[pool->available] = entry;
2849 ast_mutex_unlock(&callno_pool_lock);
2854 static int create_callno_pools(void)
2858 callno_pool.available = callno_pool_trunk.available = 0;
2860 /* We start at 2. 0 and 1 are reserved. */
2861 for (i = 2; i < TRUNK_CALL_START; i++) {
2862 callno_pool.numbers[callno_pool.available] = i;
2863 callno_pool.available++;
2866 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2867 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2868 callno_pool_trunk.available++;
2871 callno_pool.capacity = callno_pool.available;
2872 callno_pool_trunk.capacity = callno_pool_trunk.available;
2874 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2881 * \brief Schedules delayed removal of iax2_pvt call number data
2883 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2884 * avaliable again, and the address from the previous connection must be decremented
2885 * from the peercnts table. This function schedules these operations to take place.
2887 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry)
2890 struct peercnt *peercnt;
2891 struct peercnt tmp = {
2892 .addr = sin->sin_addr.s_addr,
2895 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2896 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2897 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2898 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2900 ao2_ref(peercnt, -1);
2906 MIN_REUSE_TIME * 1000,
2908 CALLNO_ENTRY_TO_PTR(entry));
2913 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2915 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2918 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2920 if (frametype != AST_FRAME_IAX) {
2924 case IAX_COMMAND_NEW:
2925 case IAX_COMMAND_REGREQ:
2926 case IAX_COMMAND_FWDOWNL:
2927 case IAX_COMMAND_REGREL:
2929 case IAX_COMMAND_POKE:
2939 * \note Calling this function while holding another pvt lock can cause a deadlock.
2941 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2945 /* this call is calltoken validated as long as it is either NEW_FORCE
2946 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2947 int validated = (new > NEW_ALLOW) ? 1 : 0;
2950 if (new <= NEW_ALLOW) {
2952 struct chan_iax2_pvt *pvt;
2953 struct chan_iax2_pvt tmp_pvt = {
2955 .peercallno = callno,
2956 .transfercallno = callno,
2958 .frames_received = check_dcallno,
2961 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2962 /* this works for finding normal call numbers not involving transfering */
2963 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2964 if (return_locked) {
2965 ast_mutex_lock(&iaxsl[pvt->callno]);
2972 /* this searches for transfer call numbers that might not get caught otherwise */
2973 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2974 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2975 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2976 if (return_locked) {
2977 ast_mutex_lock(&iaxsl[pvt->callno]);
2985 /* This will occur on the first response to a message that we initiated,
2986 * such as a PING. */
2988 ast_mutex_lock(&iaxsl[dcallno]);
2990 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2991 iaxs[dcallno]->peercallno = callno;
2993 store_by_peercallno(iaxs[dcallno]);
2994 if (!res || !return_locked) {
2995 ast_mutex_unlock(&iaxsl[dcallno]);
3000 ast_mutex_unlock(&iaxsl[dcallno]);
3003 if (!res && (new >= NEW_ALLOW)) {
3005 /* It may seem odd that we look through the peer list for a name for
3006 * this *incoming* call. Well, it is weird. However, users don't
3007 * have an IP address/port number that we can match against. So,
3008 * this is just checking for a peer that has that IP/port and
3009 * assuming that we have a user of the same name. This isn't always
3010 * correct, but it will be changed if needed after authentication. */
3011 if (!iax2_getpeername(*sin, host, sizeof(host)))
3012 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
3014 if (peercnt_add(sin)) {
3015 /* This address has hit its callnumber limit. When the limit
3016 * is reached, the connection is not added to the peercnts table.*/
3020 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3021 /* since we ran out of space, remove the peercnt
3022 * entry we added earlier */
3023 peercnt_remove_by_addr(sin);
3024 ast_log(LOG_WARNING, "No more space\n");
3027 x = CALLNO_ENTRY_GET_CALLNO(entry);
3028 ast_mutex_lock(&iaxsl[x]);
3030 iaxs[x] = new_iax(sin, host);
3033 ast_debug(1, "Creating new call structure %d\n", x);
3034 iaxs[x]->callno_entry = entry;
3035 iaxs[x]->sockfd = sockfd;
3036 iaxs[x]->addr.sin_port = sin->sin_port;
3037 iaxs[x]->addr.sin_family = sin->sin_family;
3038 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
3039 iaxs[x]->peercallno = callno;
3040 iaxs[x]->callno = x;
3041 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3042 iaxs[x]->expiry = min_reg_expire;
3043 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3044 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3045 iaxs[x]->amaflags = amaflags;
3046 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3047 ast_string_field_set(iaxs[x], accountcode, accountcode);
3048 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3049 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3050 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3052 if (iaxs[x]->peercallno) {
3053 store_by_peercallno(iaxs[x]);
3056 ast_log(LOG_WARNING, "Out of resources\n");
3057 ast_mutex_unlock(&iaxsl[x]);
3058 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3062 ast_mutex_unlock(&iaxsl[x]);
3068 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3069 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3072 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3074 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3078 * \brief Queue a frame to a call's owning asterisk channel
3080 * \pre This function assumes that iaxsl[callno] is locked when called.
3082 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3083 * was valid before calling it, it may no longer be valid after calling it.
3084 * This function may unlock and lock the mutex associated with this callno,
3085 * meaning that another thread may grab it and destroy the call.
3087 static int iax2_queue_frame(int callno, struct ast_frame *f)
3089 iax2_lock_owner(callno);
3090 if (iaxs[callno] && iaxs[callno]->owner) {
3091 ast_queue_frame(iaxs[callno]->owner, f);
3092 ast_channel_unlock(iaxs[callno]->owner);
3098 * \brief Queue a hold frame on the ast_channel owner
3100 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3101 * is active for the given call number.
3103 * \pre Assumes lock for callno is already held.
3105 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3106 * was valid before calling it, it may no longer be valid after calling it.
3107 * This function may unlock and lock the mutex associated with this callno,
3108 * meaning that another thread may grab it and destroy the call.
3110 static int iax2_queue_hold(int callno, const char *musicclass)
3112 iax2_lock_owner(callno);
3113 if (iaxs[callno] && iaxs[callno]->owner) {
3114 ast_queue_hold(iaxs[callno]->owner, musicclass);
3115 ast_channel_unlock(iaxs[callno]->owner);
3121 * \brief Queue an unhold frame on the ast_channel owner
3123 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3124 * is active for the given call number.
3126 * \pre Assumes lock for callno is already held.
3128 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3129 * was valid before calling it, it may no longer be valid after calling it.
3130 * This function may unlock and lock the mutex associated with this callno,
3131 * meaning that another thread may grab it and destroy the call.
3133 static int iax2_queue_unhold(int callno)
3135 iax2_lock_owner(callno);
3136 if (iaxs[callno] && iaxs[callno]->owner) {
3137 ast_queue_unhold(iaxs[callno]->owner);
3138 ast_channel_unlock(iaxs[callno]->owner);
3144 * \brief Queue a hangup frame on the ast_channel owner
3146 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3147 * is active for the given call number.
3149 * \pre Assumes lock for callno is already held.
3151 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3152 * was valid before calling it, it may no longer be valid after calling it.
3153 * This function may unlock and lock the mutex associated with this callno,
3154 * meaning that another thread may grab it and destroy the call.
3156 static int iax2_queue_hangup(int callno)
3158 iax2_lock_owner(callno);
3159 if (iaxs[callno] && iaxs[callno]->owner) {
3160 ast_queue_hangup(iaxs[callno]->owner);
3161 ast_channel_unlock(iaxs[callno]->owner);
3167 * \note This function assumes that iaxsl[callno] is locked when called.
3169 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3170 * was valid before calling it, it may no longer be valid after calling it.
3171 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3172 * associated with this callno, meaning that another thread may grab it and destroy the call.
3174 static int __do_deliver(void *data)
3176 /* Just deliver the packet by using queueing. This is called by
3177 the IAX thread with the iaxsl lock held. */
3178 struct iax_frame *fr = data;
3180 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3181 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3182 iax2_queue_frame(fr->callno, &fr->af);
3183 /* Free our iax frame */
3184 iax2_frame_free(fr);
3185 /* And don't run again */
3189 static int handle_error(void)
3191 /* XXX Ideally we should figure out why an error occurred and then abort those
3192 rather than continuing to try. Unfortunately, the published interface does
3193 not seem to work XXX */
3195 struct sockaddr_in *sin;
3198 struct sock_extended_err e;
3203 m.msg_controllen = sizeof(e);
3205 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3207 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3209 if (m.msg_controllen) {
3210 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3212 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3214 ast_log(LOG_WARNING, "No address detected??\n");
3216 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3223 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3226 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3229 ast_debug(1, "Received error: %s\n", strerror(errno));
3236 static int send_packet(struct iax_frame *f)
3239 int callno = f->callno;
3241 /* Don't send if there was an error, but return error instead */
3242 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3245 /* Called with iaxsl held */
3247 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));
3250 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3251 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3253 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3254 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3258 ast_debug(1, "Received error: %s\n", strerror(errno));
3267 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3268 * for the given call number may disappear during its execution.
3270 static int iax2_predestroy(int callno)
3272 struct ast_channel *c = NULL;
3273 struct chan_iax2_pvt *pvt = iaxs[callno];
3278 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3279 iax2_destroy_helper(pvt);
3280 ast_set_flag64(pvt, IAX_ALREADYGONE);
3283 if ((c = pvt->owner)) {
3284 ast_channel_tech_pvt_set(c, NULL);
3285 iax2_queue_hangup(callno);