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
35 <use type="external">crypto</use>
36 <support_level>core</support_level>
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
51 #include <sys/signal.h>
59 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
61 #include "asterisk/lock.h"
62 #include "asterisk/frame.h"
63 #include "asterisk/channel.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/config.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/translate.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/crypto.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/app.h"
78 #include "asterisk/astdb.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/features.h"
81 #include "asterisk/utils.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/localtime.h"
84 #include "asterisk/dnsmgr.h"
85 #include "asterisk/devicestate.h"
86 #include "asterisk/netsock.h"
87 #include "asterisk/stringfields.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/event.h"
90 #include "asterisk/astobj2.h"
91 #include "asterisk/timing.h"
92 #include "asterisk/taskprocessor.h"
93 #include "asterisk/test.h"
94 #include "asterisk/data.h"
95 #include "asterisk/netsock2.h"
98 #include "iax2-parser.h"
99 #include "iax2-provision.h"
100 #include "jitterbuf.h"
103 <application name="IAX2Provision" language="en_US">
105 Provision a calling IAXy with a given template.
108 <parameter name="template">
109 <para>If not specified, defaults to <literal>default</literal>.</para>
113 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
114 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
115 or <literal>0</literal> on success.</para>
118 <function name="IAXPEER" language="en_US">
120 Gets IAX peer information.
123 <parameter name="peername" required="true">
125 <enum name="CURRENTCHANNEL">
126 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
127 endpoint of the current channel</para>
131 <parameter name="item">
132 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
135 <para>(default) The IP address.</para>
138 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
140 <enum name="mailbox">
141 <para>The configured mailbox.</para>
143 <enum name="context">
144 <para>The configured context.</para>
147 <para>The epoch time of the next expire.</para>
149 <enum name="dynamic">
150 <para>Is it dynamic? (yes/no).</para>
152 <enum name="callerid_name">
153 <para>The configured Caller ID name.</para>
155 <enum name="callerid_num">
156 <para>The configured Caller ID number.</para>
159 <para>The configured codecs.</para>
161 <enum name="codec[x]">
162 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
163 with <literal>0</literal>)</para>
168 <description></description>
170 <ref type="function">SIPPEER</ref>
173 <function name="IAXVAR" language="en_US">
175 Sets or retrieves a remote variable.
178 <parameter name="varname" required="true" />
180 <description></description>
182 <manager name="IAXpeers" language="en_US">
187 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
192 <manager name="IAXpeerlist" language="en_US">
197 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
200 <para>List all the IAX peers.</para>
203 <manager name="IAXnetstats" language="en_US">
209 <para>Show IAX channels network statistics.</para>
212 <manager name="IAXregistry" language="en_US">
214 Show IAX registrations.
217 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
220 <para>Show IAX registrations.</para>
225 /* Define SCHED_MULTITHREADED to run the scheduler in a special
226 multithreaded mode. */
227 #define SCHED_MULTITHREADED
229 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
230 thread is actually doing. */
231 #define DEBUG_SCHED_MULTITHREAD
235 static int nochecksums = 0;
238 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
239 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
241 #define DEFAULT_THREAD_COUNT 10
242 #define DEFAULT_MAX_THREAD_COUNT 100
243 #define DEFAULT_RETRY_TIME 1000
244 #define MEMORY_SIZE 100
245 #define DEFAULT_DROP 3
247 #define DEBUG_SUPPORT
249 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
251 /* Sample over last 100 units to determine historic jitter */
254 static struct ast_codec_pref prefs;
256 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
259 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
260 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
261 #define MAX_TRUNK_MTU 1240
263 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
264 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
266 #define DEFAULT_CONTEXT "default"
268 static char default_parkinglot[AST_MAX_CONTEXT];
270 static char language[MAX_LANGUAGE] = "";
271 static char regcontext[AST_MAX_CONTEXT] = "";
273 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
274 static int network_change_event_sched_id = -1;
276 static int maxauthreq = 3;
277 static int max_retries = 4;
278 static int ping_time = 21;
279 static int lagrq_time = 10;
280 static int maxjitterbuffer=1000;
281 static int resyncthreshold=1000;
282 static int maxjitterinterps=10;
283 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
285 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
287 static int trunkfreq = 20;
288 static int trunkmaxsize = MAX_TRUNKDATA;
290 static int authdebug = 0;
291 static int autokill = 0;
292 static int iaxcompat = 0;
293 static int last_authmethod = 0;
295 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
297 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
304 static int min_reg_expire;
305 static int max_reg_expire;
307 static int srvlookup = 0;
309 static struct ast_timer *timer; /* Timer for trunking */
311 static struct ast_netsock_list *netsock;
312 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
313 static int defaultsockfd = -1;
315 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
318 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
320 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
321 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
322 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
323 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
324 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
325 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
326 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
327 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
328 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
330 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
331 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
332 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
333 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
335 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
339 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
340 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
341 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
343 /* if a pvt has encryption setup done and is running on the call */
344 #define IAX_CALLENCRYPTED(pvt) \
345 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
347 #define IAX_DEBUGDIGEST(msg, key) do { \
349 char digest[33] = ""; \
354 for (idx = 0; idx < 16; idx++) \
355 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
357 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
360 static struct io_context *io;
361 static struct ast_sched_context *sched;
363 #define DONT_RESCHEDULE -2
365 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
367 static int iaxdebug = 0;
369 static int iaxtrunkdebug = 0;
371 static int test_losspct = 0;
373 static int test_late = 0;
374 static int test_resync = 0;
375 static int test_jit = 0;
376 static int test_jitpct = 0;
377 #endif /* IAXTESTS */
379 static char accountcode[AST_MAX_ACCOUNT_CODE];
380 static char mohinterpret[MAX_MUSICCLASS];
381 static char mohsuggest[MAX_MUSICCLASS];
382 static int amaflags = 0;
384 static int delayreject = 0;
385 static int iax2_encryption = 0;
387 static struct ast_flags64 globalflags = { 0 };
389 static pthread_t netthreadid = AST_PTHREADT_NULL;
392 IAX_STATE_STARTED = (1 << 0),
393 IAX_STATE_AUTHENTICATED = (1 << 1),
394 IAX_STATE_TBD = (1 << 2),
397 struct iax2_context {
398 char context[AST_MAX_CONTEXT];
399 struct iax2_context *next;
403 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
404 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
405 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
406 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
407 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
408 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
409 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
410 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
411 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
412 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
413 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
414 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
415 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
416 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
417 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
418 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
419 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
420 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
421 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
422 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
423 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
424 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
425 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
426 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
427 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
428 #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 */
429 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
430 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
431 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
432 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
433 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
434 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
435 static int global_rtautoclear = 120;
437 static int reload_config(void);
440 * \brief Call token validation settings.
442 enum calltoken_peer_enum {
443 /*! \brief Default calltoken required unless the ip is in the ignorelist */
444 CALLTOKEN_DEFAULT = 0,
445 /*! \brief Require call token validation. */
447 /*! \brief Require call token validation after a successful registration
448 * using call token validation occurs. */
450 /*! \brief Do not require call token validation. */
455 AST_DECLARE_STRING_FIELDS(
456 AST_STRING_FIELD(name);
457 AST_STRING_FIELD(secret);
458 AST_STRING_FIELD(dbsecret);
459 AST_STRING_FIELD(accountcode);
460 AST_STRING_FIELD(mohinterpret);
461 AST_STRING_FIELD(mohsuggest);
462 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
463 AST_STRING_FIELD(language);
464 AST_STRING_FIELD(cid_num);
465 AST_STRING_FIELD(cid_name);
466 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
474 iax2_format capability;
475 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
476 int curauthreq; /*!< Current number of outstanding AUTHREQs */
477 struct ast_codec_pref prefs;
479 struct iax2_context *contexts;
480 struct ast_variable *vars;
481 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
485 AST_DECLARE_STRING_FIELDS(
486 AST_STRING_FIELD(name);
487 AST_STRING_FIELD(username);
488 AST_STRING_FIELD(description); /*!< Description of the peer */
489 AST_STRING_FIELD(secret);
490 AST_STRING_FIELD(dbsecret);
491 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
493 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
494 AST_STRING_FIELD(context); /*!< For transfers only */
495 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
496 AST_STRING_FIELD(mailbox); /*!< Mailbox */
497 AST_STRING_FIELD(mohinterpret);
498 AST_STRING_FIELD(mohsuggest);
499 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
500 /* Suggested caller id if registering */
501 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
502 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
503 AST_STRING_FIELD(zonetag); /*!< Time Zone */
504 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
506 struct ast_codec_pref prefs;
507 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
508 struct ast_sockaddr addr;
510 int sockfd; /*!< Socket to use for transmission */
515 /* Dynamic Registration fields */
516 struct sockaddr_in defaddr; /*!< Default address if there is one */
517 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
518 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
520 int expire; /*!< Schedule entry for expiry */
521 int expiry; /*!< How soon to expire */
522 iax2_format capability; /*!< Capability */
525 int callno; /*!< Call number of POKE request */
526 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
527 int lastms; /*!< How long last response took (in ms), or -1 for no response */
528 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
530 int pokefreqok; /*!< How often to check if the host is up */
531 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
532 int historicms; /*!< How long recent average responses took */
533 int smoothing; /*!< Sample over how many units to determine historic ms */
534 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
536 struct ast_event_sub *mwi_event_sub;
539 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
542 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
544 struct iax2_trunk_peer {
547 struct sockaddr_in addr;
548 struct timeval txtrunktime; /*!< Transmit trunktime */
549 struct timeval rxtrunktime; /*!< Receive trunktime */
550 struct timeval lasttxtime; /*!< Last transmitted trunktime */
551 struct timeval trunkact; /*!< Last trunk activity */
552 unsigned int lastsent; /*!< Last sent time */
553 /* Trunk data and length */
554 unsigned char *trunkdata;
555 unsigned int trunkdatalen;
556 unsigned int trunkdataalloc;
560 AST_LIST_ENTRY(iax2_trunk_peer) list;
563 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
565 struct iax_firmware {
566 AST_LIST_ENTRY(iax_firmware) list;
570 struct ast_iax2_firmware_header *fwh;
575 REG_STATE_UNREGISTERED = 0,
578 REG_STATE_REGISTERED,
584 enum iax_transfer_state {
589 TRANSFER_PASSTHROUGH,
593 TRANSFER_MPASSTHROUGH,
598 struct iax2_registry {
599 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
601 char secret[80]; /*!< Password or key name in []'s */
602 int expire; /*!< Sched ID of expiration */
603 int refresh; /*!< How often to refresh */
604 enum iax_reg_state regstate;
605 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
606 int callno; /*!< Associated call number if applicable */
607 struct sockaddr_in us; /*!< Who the server thinks we are */
608 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
609 AST_LIST_ENTRY(iax2_registry) entry;
612 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
614 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
615 #define MIN_RETRY_TIME 100
616 #define MAX_RETRY_TIME 10000
618 #define MAX_JITTER_BUFFER 50
619 #define MIN_JITTER_BUFFER 10
621 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
623 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
625 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
626 #define TS_GAP_FOR_JB_RESYNC 5000
628 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
629 #define MARK_IAX_SUBCLASS_TX 0x8000
631 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
632 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
633 static int iaxdynamicthreadcount = 0;
634 static int iaxdynamicthreadnum = 0;
635 static int iaxactivethreadcount = 0;
649 struct chan_iax2_pvt {
650 /*! Socket to send/receive on for this call */
652 /*! Last received voice format */
653 iax2_format voiceformat;
654 /*! Last received video format */
655 iax2_format videoformat;
656 /*! Last sent voice format */
657 iax2_format svoiceformat;
658 /*! Last sent video format */
659 iax2_format svideoformat;
660 /*! What we are capable of sending */
661 iax2_format capability;
662 /*! Last received timestamp */
664 /*! Last sent timestamp - never send the same timestamp twice in a single call */
665 unsigned int lastsent;
666 /*! Timestamp of the last video frame sent */
667 unsigned int lastvsent;
668 /*! Next outgoing timestamp if everything is good */
669 unsigned int nextpred;
670 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
671 int first_iax_message;
672 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
673 int last_iax_message;
674 /*! True if the last voice we transmitted was not silence/CNG */
675 unsigned int notsilenttx:1;
677 unsigned int pingtime;
678 /*! Max time for initial response */
681 struct sockaddr_in addr;
682 /*! Actual used codec preferences */
683 struct ast_codec_pref prefs;
684 /*! Requested codec preferences */
685 struct ast_codec_pref rprefs;
686 /*! Our call number */
687 unsigned short callno;
688 /*! Our callno_entry entry */
689 struct callno_entry *callno_entry;
691 unsigned short peercallno;
692 /*! Negotiated format, this is only used to remember what format was
693 chosen for an unauthenticated call so that the channel can get
694 created later using the right format */
695 iax2_format chosenformat;
696 /*! Peer selected format */
697 iax2_format peerformat;
698 /*! Peer capability */
699 iax2_format peercapability;
700 /*! timeval that we base our transmission on */
701 struct timeval offset;
702 /*! timeval that we base our delivery on */
703 struct timeval rxcore;
704 /*! The jitterbuffer */
706 /*! active jb read scheduler id */
710 /*! Error, as discovered by the manager */
712 /*! Owner if we have one */
713 struct ast_channel *owner;
714 /*! What's our state? */
715 struct ast_flags state;
716 /*! Expiry (optional) */
718 /*! Next outgoing sequence number */
719 unsigned char oseqno;
720 /*! Next sequence number they have not yet acknowledged */
721 unsigned char rseqno;
722 /*! Next incoming sequence number */
723 unsigned char iseqno;
724 /*! Last incoming sequence number we have acknowledged */
725 unsigned char aseqno;
727 AST_DECLARE_STRING_FIELDS(
729 AST_STRING_FIELD(peer);
730 /*! Default Context */
731 AST_STRING_FIELD(context);
732 /*! Caller ID if available */
733 AST_STRING_FIELD(cid_num);
734 AST_STRING_FIELD(cid_name);
735 /*! Hidden Caller ID (i.e. ANI) if appropriate */
736 AST_STRING_FIELD(ani);
738 AST_STRING_FIELD(dnid);
740 AST_STRING_FIELD(rdnis);
741 /*! Requested Extension */
742 AST_STRING_FIELD(exten);
743 /*! Expected Username */
744 AST_STRING_FIELD(username);
745 /*! Expected Secret */
746 AST_STRING_FIELD(secret);
748 AST_STRING_FIELD(challenge);
749 /*! Public keys permitted keys for incoming authentication */
750 AST_STRING_FIELD(inkeys);
751 /*! Private key for outgoing authentication */
752 AST_STRING_FIELD(outkey);
753 /*! Preferred language */
754 AST_STRING_FIELD(language);
755 /*! Hostname/peername for naming purposes */
756 AST_STRING_FIELD(host);
758 AST_STRING_FIELD(dproot);
759 AST_STRING_FIELD(accountcode);
760 AST_STRING_FIELD(mohinterpret);
761 AST_STRING_FIELD(mohsuggest);
762 /*! received OSP token */
763 AST_STRING_FIELD(osptoken);
764 /*! Default parkinglot */
765 AST_STRING_FIELD(parkinglot);
767 /*! AUTHREJ all AUTHREP frames */
769 /*! permitted authentication methods */
771 /*! permitted encryption methods */
773 /*! Encryption AES-128 Key */
774 ast_aes_encrypt_key ecx;
775 /*! Decryption AES-128 Key corresponding to ecx */
776 ast_aes_decrypt_key mydcx;
777 /*! Decryption AES-128 Key used to decrypt peer frames */
778 ast_aes_decrypt_key dcx;
779 /*! scheduler id associated with iax_key_rotate
780 * for encrypted calls*/
782 /*! 32 bytes of semi-random data */
783 unsigned char semirand[32];
784 /*! Associated registry */
785 struct iax2_registry *reg;
786 /*! Associated peer for poking */
787 struct iax2_peer *peerpoke;
792 /*! Transferring status */
793 enum iax_transfer_state transferring;
794 /*! Transfer identifier */
796 /*! Who we are IAX transferring to */
797 struct sockaddr_in transfer;
798 /*! What's the new call number for the transfer */
799 unsigned short transfercallno;
800 /*! Transfer encrypt AES-128 Key */
801 ast_aes_encrypt_key tdcx;
803 /*! Status of knowledge of peer ADSI capability */
806 /*! Who we are bridged to */
807 unsigned short bridgecallno;
809 int pingid; /*!< Transmit PING request */
810 int lagid; /*!< Retransmit lag request */
811 int autoid; /*!< Auto hangup for Dialplan requestor */
812 int authid; /*!< Authentication rejection ID */
813 int authfail; /*!< Reason to report failure */
814 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
819 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
820 /*! variables inherited from the user definition */
821 struct ast_variable *vars;
822 /*! variables transmitted in a NEW packet */
823 struct ast_variable *iaxvars;
824 /*! last received remote rr */
825 struct iax_rr remote_rr;
826 /*! Current base time: (just for stats) */
828 /*! Dropped frame count: (just for stats) */
830 /*! received frame count: (just for stats) */
832 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
833 unsigned char calltoken_ie_len;
834 /*! hold all signaling frames from the pbx thread until we have a destination callno */
836 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
837 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
840 struct signaling_queue_entry {
842 AST_LIST_ENTRY(signaling_queue_entry) next;
845 /*! table of available call numbers */
846 static struct ao2_container *callno_pool;
848 /*! table of available trunk call numbers */
849 static struct ao2_container *callno_pool_trunk;
851 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
854 * \brief a list of frames that may need to be retransmitted
856 * \note The contents of this list do not need to be explicitly destroyed
857 * on module unload. This is because all active calls are destroyed, and
858 * all frames in this queue will get destroyed as a part of that process.
860 * \note Contents protected by the iaxsl[] locks
862 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
864 static struct ast_taskprocessor *transmit_processor;
866 static int randomcalltokendata;
868 static const time_t MAX_CALLTOKEN_DELAY = 10;
871 * This module will get much higher performance when doing a lot of
872 * user and peer lookups if the number of buckets is increased from 1.
873 * However, to maintain old behavior for Asterisk 1.4, these are set to
874 * 1 by default. When using multiple buckets, search order through these
875 * containers is considered random, so you will not be able to depend on
876 * the order the entires are specified in iax.conf for matching order. */
878 #define MAX_PEER_BUCKETS 17
880 #define MAX_PEER_BUCKETS 563
882 static struct ao2_container *peers;
884 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
885 static struct ao2_container *users;
887 /*! Table containing peercnt objects for every ip address consuming a callno */
888 static struct ao2_container *peercnts;
890 /*! Table containing custom callno limit rules for a range of ip addresses. */
891 static struct ao2_container *callno_limits;
893 /*! Table containing ip addresses not requiring calltoken validation */
894 static struct ao2_container *calltoken_ignores;
896 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
898 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
900 static uint16_t global_maxcallno;
902 /*! Total num of call numbers allowed to be allocated without calltoken validation */
903 static uint16_t global_maxcallno_nonval;
905 static uint16_t total_nonval_callno_used = 0;
907 /*! peer connection private, keeps track of all the call numbers
908 * consumed by a single ip address */
910 /*! ip address consuming call numbers */
912 /*! Number of call numbers currently used by this ip address */
914 /*! Max call numbers allowed for this ip address */
916 /*! Specifies whether limit is set by a registration or not, if so normal
917 * limit setting rules do not apply to this address. */
921 /*! used by both callno_limits and calltoken_ignores containers */
923 /*! ip address range for custom callno limit rule */
925 /*! callno limit for this ip address range, only used in callno_limits container */
927 /*! delete me marker for reloads */
931 struct callno_entry {
932 /*! callno used for this entry */
934 /*! was this callno calltoken validated or not */
935 unsigned char validated;
938 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
941 /*! Extension exists */
942 CACHE_FLAG_EXISTS = (1 << 0),
943 /*! Extension is nonexistent */
944 CACHE_FLAG_NONEXISTENT = (1 << 1),
945 /*! Extension can exist */
946 CACHE_FLAG_CANEXIST = (1 << 2),
947 /*! Waiting to hear back response */
948 CACHE_FLAG_PENDING = (1 << 3),
950 CACHE_FLAG_TIMEOUT = (1 << 4),
951 /*! Request transmitted */
952 CACHE_FLAG_TRANSMITTED = (1 << 5),
954 CACHE_FLAG_UNKNOWN = (1 << 6),
956 CACHE_FLAG_MATCHMORE = (1 << 7),
959 struct iax2_dpcache {
960 char peercontext[AST_MAX_CONTEXT];
961 char exten[AST_MAX_EXTENSION];
963 struct timeval expiry;
965 unsigned short callno;
967 AST_LIST_ENTRY(iax2_dpcache) cache_list;
968 AST_LIST_ENTRY(iax2_dpcache) peer_list;
971 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
973 static void reg_source_db(struct iax2_peer *p);
974 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
975 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
977 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
978 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
979 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
981 enum iax2_thread_iostate {
984 IAX_IOSTATE_PROCESSING,
985 IAX_IOSTATE_SCHEDREADY,
988 enum iax2_thread_type {
989 IAX_THREAD_TYPE_POOL,
990 IAX_THREAD_TYPE_DYNAMIC,
993 struct iax2_pkt_buf {
994 AST_LIST_ENTRY(iax2_pkt_buf) entry;
996 unsigned char buf[1];
1000 AST_LIST_ENTRY(iax2_thread) list;
1001 enum iax2_thread_type type;
1002 enum iax2_thread_iostate iostate;
1003 #ifdef SCHED_MULTITHREADED
1004 void (*schedfunc)(const void *);
1005 const void *scheddata;
1007 #ifdef DEBUG_SCHED_MULTITHREAD
1013 struct sockaddr_in iosin;
1014 unsigned char readbuf[4096];
1022 ast_mutex_t init_lock;
1023 ast_cond_t init_cond;
1024 /*! if this thread is processing a full frame,
1025 some information about that frame will be stored
1026 here, so we can avoid dispatching any more full
1027 frames for that callno to other threads */
1029 unsigned short callno;
1030 struct sockaddr_in sin;
1034 /*! Queued up full frames for processing. If more full frames arrive for
1035 * a call which this thread is already processing a full frame for, they
1036 * are queued up here. */
1037 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1042 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1043 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1044 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1046 static void *iax2_process_thread(void *data);
1047 static void iax2_destroy(int callno);
1049 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1051 ast_mutex_lock(lock);
1052 ast_cond_signal(cond);
1053 ast_mutex_unlock(lock);
1057 * \brief an array of iax2 pvt structures
1059 * The container for active chan_iax2_pvt structures is implemented as an
1060 * array for extremely quick direct access to the correct pvt structure
1061 * based on the local call number. The local call number is used as the
1062 * index into the array where the associated pvt structure is stored.
1064 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1067 * \brief Another container of iax2_pvt structures
1069 * Active IAX2 pvt structs are also stored in this container, if they are a part
1070 * of an active call where we know the remote side's call number. The reason
1071 * for this is that incoming media frames do not contain our call number. So,
1072 * instead of having to iterate the entire iaxs array, we use this container to
1073 * look up calls where the remote side is using a given call number.
1075 static struct ao2_container *iax_peercallno_pvts;
1078 * \brief chan_iax2_pvt structure locks
1080 * These locks are used when accessing a pvt structure in the iaxs array.
1081 * The index used here is the same as used in the iaxs array. It is the
1082 * local call number for the associated pvt struct.
1084 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1087 * * \brief Another container of iax2_pvt structures
1089 * Active IAX2 pvt stucts used during transfering a call are stored here.
1091 static struct ao2_container *iax_transfercallno_pvts;
1093 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1094 but keeps the division between trunked and non-trunked better. */
1095 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1097 /* Debug routines... */
1098 static struct sockaddr_in debugaddr;
1100 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1103 (sin && debugaddr.sin_addr.s_addr &&
1104 (!ntohs(debugaddr.sin_port) ||
1105 debugaddr.sin_port == sin->sin_port) &&
1106 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1108 iax_showframe(f, fhi, rx, sin, datalen);
1111 iax_showframe(f, fhi, rx, sin, datalen);
1117 static void iax_debug_output(const char *data)
1120 ast_verbose("%s", data);
1123 static void iax_error_output(const char *data)
1125 ast_log(LOG_WARNING, "%s", data);
1128 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1133 va_start(args, fmt);
1134 vsnprintf(buf, sizeof(buf), fmt, args);
1137 ast_log(LOG_ERROR, "%s", buf);
1140 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1145 va_start(args, fmt);
1146 vsnprintf(buf, sizeof(buf), fmt, args);
1149 ast_log(LOG_WARNING, "%s", buf);
1152 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1157 va_start(args, fmt);
1158 vsnprintf(buf, sizeof(buf), fmt, args);
1161 ast_verbose("%s", buf);
1164 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);
1165 static int expire_registry(const void *data);
1166 static int iax2_answer(struct ast_channel *c);
1167 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1168 static int iax2_devicestate(const char *data);
1169 static int iax2_digit_begin(struct ast_channel *c, char digit);
1170 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1171 static int iax2_do_register(struct iax2_registry *reg);
1172 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1173 static int iax2_hangup(struct ast_channel *c);
1174 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1175 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1176 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1177 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1178 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1179 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1180 static int iax2_sendtext(struct ast_channel *c, const char *text);
1181 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1182 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1183 static int iax2_transfer(struct ast_channel *c, const char *dest);
1184 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1185 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1187 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1188 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1189 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1190 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1191 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1192 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1193 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1194 static struct ast_frame *iax2_read(struct ast_channel *c);
1195 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1196 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1197 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1198 static void *iax2_dup_variable_datastore(void *);
1199 static void prune_peers(void);
1200 static void prune_users(void);
1201 static void iax2_free_variable_datastore(void *);
1203 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1204 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1205 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1206 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1207 static void build_rand_pad(unsigned char *buf, ssize_t len);
1208 static struct callno_entry *get_unused_callno(int trunk, int validated);
1209 static int replace_callno(const void *obj);
1210 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1211 static void network_change_event_cb(const struct ast_event *, void *);
1213 static struct ast_channel_tech iax2_tech = {
1215 .description = tdesc,
1216 .properties = AST_CHAN_TP_WANTSJITTER,
1217 .requester = iax2_request,
1218 .devicestate = iax2_devicestate,
1219 .send_digit_begin = iax2_digit_begin,
1220 .send_digit_end = iax2_digit_end,
1221 .send_text = iax2_sendtext,
1222 .send_image = iax2_sendimage,
1223 .send_html = iax2_sendhtml,
1225 .hangup = iax2_hangup,
1226 .answer = iax2_answer,
1228 .write = iax2_write,
1229 .write_video = iax2_write,
1230 .indicate = iax2_indicate,
1231 .setoption = iax2_setoption,
1232 .queryoption = iax2_queryoption,
1233 .bridge = iax2_bridge,
1234 .transfer = iax2_transfer,
1235 .fixup = iax2_fixup,
1236 .func_channel_read = acf_channel_read,
1241 * \brief Obtain the owner channel lock if the owner exists.
1243 * \param callno IAX2 call id.
1245 * \note Assumes the iaxsl[callno] lock is already obtained.
1248 * IMPORTANT NOTE!!! Any time this function is used, even if
1249 * iaxs[callno] was valid before calling it, it may no longer be
1250 * valid after calling it. This function may unlock and lock
1251 * the mutex associated with this callno, meaning that another
1252 * thread may grab it and destroy the call.
1256 static void iax2_lock_owner(int callno)
1259 if (!iaxs[callno] || !iaxs[callno]->owner) {
1260 /* There is no owner lock to get. */
1263 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1264 /* We got the lock */
1267 /* Avoid deadlock by pausing and trying again */
1268 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1272 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1274 /* The MWI subscriptions exist just so the core knows we care about those
1275 * mailboxes. However, we just grab the events out of the cache when it
1276 * is time to send MWI, since it is only sent with a REGACK. */
1279 static void network_change_event_subscribe(void)
1281 if (!network_change_event_subscription) {
1282 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1283 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1287 static void network_change_event_unsubscribe(void)
1289 if (network_change_event_subscription) {
1290 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1294 static int network_change_event_sched_cb(const void *data)
1296 struct iax2_registry *reg;
1297 network_change_event_sched_id = -1;
1298 AST_LIST_LOCK(®istrations);
1299 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1300 iax2_do_register(reg);
1302 AST_LIST_UNLOCK(®istrations);
1307 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1309 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1310 if (network_change_event_sched_id == -1) {
1311 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1317 /*! \brief Send manager event at call setup to link between Asterisk channel name
1318 and IAX2 call identifiers */
1319 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1321 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1322 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1323 pvt->owner ? ast_channel_name(pvt->owner) : "",
1324 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1327 static struct ast_datastore_info iax2_variable_datastore_info = {
1328 .type = "IAX2_VARIABLE",
1329 .duplicate = iax2_dup_variable_datastore,
1330 .destroy = iax2_free_variable_datastore,
1333 static void *iax2_dup_variable_datastore(void *old)
1335 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1336 struct ast_var_t *oldvar, *newvar;
1338 newlist = ast_calloc(sizeof(*newlist), 1);
1340 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1344 AST_LIST_HEAD_INIT(newlist);
1345 AST_LIST_LOCK(oldlist);
1346 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1347 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1349 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1351 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1353 AST_LIST_UNLOCK(oldlist);
1357 static void iax2_free_variable_datastore(void *old)
1359 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1360 struct ast_var_t *oldvar;
1362 AST_LIST_LOCK(oldlist);
1363 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1366 AST_LIST_UNLOCK(oldlist);
1367 AST_LIST_HEAD_DESTROY(oldlist);
1372 /* WARNING: insert_idle_thread should only ever be called within the
1373 * context of an iax2_process_thread() thread.
1375 static void insert_idle_thread(struct iax2_thread *thread)
1377 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1378 AST_LIST_LOCK(&dynamic_list);
1379 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1380 AST_LIST_UNLOCK(&dynamic_list);
1382 AST_LIST_LOCK(&idle_list);
1383 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1384 AST_LIST_UNLOCK(&idle_list);
1390 static struct iax2_thread *find_idle_thread(void)
1392 struct iax2_thread *thread = NULL;
1394 /* Pop the head of the idle list off */
1395 AST_LIST_LOCK(&idle_list);
1396 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1397 AST_LIST_UNLOCK(&idle_list);
1399 /* If we popped a thread off the idle list, just return it */
1401 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1405 /* Pop the head of the dynamic list off */
1406 AST_LIST_LOCK(&dynamic_list);
1407 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1408 AST_LIST_UNLOCK(&dynamic_list);
1410 /* If we popped a thread off the dynamic list, just return it */
1412 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1416 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1417 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1420 /* Set default values */
1421 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1422 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1423 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1425 /* Initialize lock and condition */
1426 ast_mutex_init(&thread->lock);
1427 ast_cond_init(&thread->cond, NULL);
1428 ast_mutex_init(&thread->init_lock);
1429 ast_cond_init(&thread->init_cond, NULL);
1430 ast_mutex_lock(&thread->init_lock);
1432 /* Create thread and send it on it's way */
1433 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1434 ast_cond_destroy(&thread->cond);
1435 ast_mutex_destroy(&thread->lock);
1436 ast_mutex_unlock(&thread->init_lock);
1437 ast_cond_destroy(&thread->init_cond);
1438 ast_mutex_destroy(&thread->init_lock);
1443 /* this thread is not processing a full frame (since it is idle),
1444 so ensure that the field for the full frame call number is empty */
1445 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1447 /* Wait for the thread to be ready before returning it to the caller */
1448 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1450 /* Done with init_lock */
1451 ast_mutex_unlock(&thread->init_lock);
1456 #ifdef SCHED_MULTITHREADED
1457 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1459 struct iax2_thread *thread = NULL;
1460 static time_t lasterror;
1463 thread = find_idle_thread();
1465 if (thread != NULL) {
1466 thread->schedfunc = func;
1467 thread->scheddata = data;
1468 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1469 #ifdef DEBUG_SCHED_MULTITHREAD
1470 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1472 signal_condition(&thread->lock, &thread->cond);
1477 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1482 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1485 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1486 ast_sched_cb callback, const void *data)
1488 return ast_sched_replace(id, con, when, callback, data);
1491 static int iax2_sched_add(struct ast_sched_context *con, int when,
1492 ast_sched_cb callback, const void *data)
1494 return ast_sched_add(con, when, callback, data);
1497 static int send_ping(const void *data);
1499 static void __send_ping(const void *data)
1501 int callno = (long) data;
1503 ast_mutex_lock(&iaxsl[callno]);
1506 if (iaxs[callno]->peercallno) {
1507 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1508 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1509 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1513 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1516 ast_mutex_unlock(&iaxsl[callno]);
1519 static int send_ping(const void *data)
1521 int callno = (long) data;
1522 ast_mutex_lock(&iaxsl[callno]);
1523 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1524 iaxs[callno]->pingid = -1;
1526 ast_mutex_unlock(&iaxsl[callno]);
1528 #ifdef SCHED_MULTITHREADED
1529 if (schedule_action(__send_ping, data))
1536 static void encmethods_to_str(int e, struct ast_str *buf)
1538 ast_str_set(&buf, 0, "(");
1539 if (e & IAX_ENCRYPT_AES128) {
1540 ast_str_append(&buf, 0, "aes128");
1542 if (e & IAX_ENCRYPT_KEYROTATE) {
1543 ast_str_append(&buf, 0, ",keyrotate");
1545 if (ast_str_strlen(buf) > 1) {
1546 ast_str_append(&buf, 0, ")");
1548 ast_str_set(&buf, 0, "No");
1552 static int get_encrypt_methods(const char *s)
1555 if (!strcasecmp(s, "aes128"))
1556 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1557 else if (ast_true(s))
1558 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1564 static int send_lagrq(const void *data);
1566 static void __send_lagrq(const void *data)
1568 int callno = (long) data;
1570 ast_mutex_lock(&iaxsl[callno]);
1573 if (iaxs[callno]->peercallno) {
1574 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1575 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1576 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1580 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1583 ast_mutex_unlock(&iaxsl[callno]);
1586 static int send_lagrq(const void *data)
1588 int callno = (long) data;
1589 ast_mutex_lock(&iaxsl[callno]);
1590 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1591 iaxs[callno]->lagid = -1;
1593 ast_mutex_unlock(&iaxsl[callno]);
1595 #ifdef SCHED_MULTITHREADED
1596 if (schedule_action(__send_lagrq, data))
1602 static unsigned char compress_subclass(iax2_format subclass)
1606 /* If it's 64 or smaller, just return it */
1607 if (subclass < IAX_FLAG_SC_LOG)
1609 /* Otherwise find its power */
1610 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1611 if (subclass & (1LL << x)) {
1613 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1619 return power | IAX_FLAG_SC_LOG;
1622 static iax2_format uncompress_subclass(unsigned char csub)
1624 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1625 if (csub & IAX_FLAG_SC_LOG) {
1626 /* special case for 'compressed' -1 */
1630 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1636 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1638 struct ast_format_cap *cap;
1639 struct ast_format tmpfmt;
1640 iax2_format format = 0;
1641 if ((cap = ast_format_cap_alloc_nolock())) {
1642 ast_format_clear(&tmpfmt);
1643 ast_format_cap_from_old_bitfield(cap, formats);
1644 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1645 format = ast_format_to_old_bitfield(&tmpfmt);
1646 cap = ast_format_cap_destroy(cap);
1652 static iax2_format iax2_best_codec(iax2_format formats)
1654 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1655 struct ast_format tmpfmt;
1660 ast_format_clear(&tmpfmt);
1661 ast_format_cap_from_old_bitfield(cap, formats);
1662 ast_best_codec(cap, &tmpfmt);
1663 cap = ast_format_cap_destroy(cap);
1664 return ast_format_to_old_bitfield(&tmpfmt);
1667 const char *iax2_getformatname(iax2_format format)
1669 struct ast_format tmpfmt;
1670 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1674 return ast_getformatname(&tmpfmt);
1677 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1679 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1684 ast_format_cap_from_old_bitfield(cap, format);
1685 ast_getformatname_multiple(codec_buf, len, cap);
1686 cap = ast_format_cap_destroy(cap);
1691 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1694 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1699 ast_format_cap_from_old_bitfield(cap, *formats);
1700 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1701 *formats = ast_format_cap_to_old_bitfield(cap);
1702 cap = ast_format_cap_destroy(cap);
1707 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1710 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1714 ast_format_cap_from_old_bitfield(cap, formats);
1715 res = ast_data_add_codecs(root, node_name, cap);
1716 cap = ast_format_cap_destroy(cap);
1721 * \note The only member of the peer passed here guaranteed to be set is the name field
1723 static int peer_hash_cb(const void *obj, const int flags)
1725 const struct iax2_peer *peer = obj;
1726 const char *name = obj;
1728 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1732 * \note The only member of the peer passed here guaranteed to be set is the name field
1734 static int peer_cmp_cb(void *obj, void *arg, int flags)
1736 struct iax2_peer *peer = obj, *peer2 = arg;
1737 const char *name = arg;
1739 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1740 CMP_MATCH | CMP_STOP : 0;
1744 * \note The only member of the user passed here guaranteed to be set is the name field
1746 static int user_hash_cb(const void *obj, const int flags)
1748 const struct iax2_user *user = obj;
1749 const char *name = obj;
1751 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1755 * \note The only member of the user passed here guaranteed to be set is the name field
1757 static int user_cmp_cb(void *obj, void *arg, int flags)
1759 struct iax2_user *user = obj, *user2 = arg;
1760 const char *name = arg;
1762 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1763 CMP_MATCH | CMP_STOP : 0;
1767 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1768 * so do not call it with a pvt lock held.
1770 static struct iax2_peer *find_peer(const char *name, int realtime)
1772 struct iax2_peer *peer = NULL;
1774 peer = ao2_find(peers, name, OBJ_KEY);
1776 /* Now go for realtime if applicable */
1777 if(!peer && realtime)
1778 peer = realtime_peer(name, NULL);
1783 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1789 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1795 static struct iax2_user *find_user(const char *name)
1797 return ao2_find(users, name, OBJ_KEY);
1799 static inline struct iax2_user *user_ref(struct iax2_user *user)
1805 static inline struct iax2_user *user_unref(struct iax2_user *user)
1811 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1813 struct iax2_peer *peer = NULL;
1815 struct ao2_iterator i;
1817 i = ao2_iterator_init(peers, 0);
1818 while ((peer = ao2_iterator_next(&i))) {
1819 struct sockaddr_in peer_addr;
1821 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1823 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1824 (peer_addr.sin_port == sin.sin_port)) {
1825 ast_copy_string(host, peer->name, len);
1832 ao2_iterator_destroy(&i);
1835 peer = realtime_peer(NULL, &sin);
1837 ast_copy_string(host, peer->name, len);
1846 /*!\note Assumes the lock on the pvt is already held, when
1847 * iax2_destroy_helper() is called. */
1848 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1850 /* Decrement AUTHREQ count if needed */
1851 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1852 struct iax2_user *user;
1854 user = ao2_find(users, pvt->username, OBJ_KEY);
1856 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1860 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1862 /* No more pings or lagrq's */
1863 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1864 pvt->pingid = DONT_RESCHEDULE;
1865 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1866 pvt->lagid = DONT_RESCHEDULE;
1867 AST_SCHED_DEL(sched, pvt->autoid);
1868 AST_SCHED_DEL(sched, pvt->authid);
1869 AST_SCHED_DEL(sched, pvt->initid);
1870 AST_SCHED_DEL(sched, pvt->jbid);
1871 AST_SCHED_DEL(sched, pvt->keyrotateid);
1874 static void iax2_frame_free(struct iax_frame *fr)
1876 AST_SCHED_DEL(sched, fr->retrans);
1880 static int scheduled_destroy(const void *vid)
1882 unsigned short callno = PTR_TO_CALLNO(vid);
1883 ast_mutex_lock(&iaxsl[callno]);
1885 ast_debug(1, "Really destroying %d now...\n", callno);
1886 iax2_destroy(callno);
1888 ast_mutex_unlock(&iaxsl[callno]);
1892 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1895 ast_free(s->f.data.ptr);
1900 /*! \brief This function must be called once we are sure the other side has
1901 * given us a call number. All signaling is held here until that point. */
1902 static void send_signaling(struct chan_iax2_pvt *pvt)
1904 struct signaling_queue_entry *s = NULL;
1906 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1907 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1908 free_signaling_queue_entry(s);
1910 pvt->hold_signaling = 0;
1913 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1914 * we have received a destination call number. */
1915 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1917 struct signaling_queue_entry *new;
1919 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1920 return 1; /* do not queue this frame */
1921 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1922 return -1; /* out of memory */
1925 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1927 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1928 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1929 free_signaling_queue_entry(new);
1932 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1934 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1939 static void pvt_destructor(void *obj)
1941 struct chan_iax2_pvt *pvt = obj;
1942 struct iax_frame *cur = NULL;
1943 struct signaling_queue_entry *s = NULL;
1945 ast_mutex_lock(&iaxsl[pvt->callno]);
1947 iax2_destroy_helper(pvt);
1949 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1950 pvt->callno_entry = NULL;
1953 ast_set_flag64(pvt, IAX_ALREADYGONE);
1955 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1956 /* Cancel any pending transmissions */
1960 ast_mutex_unlock(&iaxsl[pvt->callno]);
1962 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1963 free_signaling_queue_entry(s);
1967 pvt->reg->callno = 0;
1973 ast_variables_destroy(pvt->vars);
1977 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1978 iax2_frame_free(frame.data);
1981 jb_destroy(pvt->jb);
1982 ast_string_field_free_memory(pvt);
1986 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1988 struct chan_iax2_pvt *tmp;
1991 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1995 if (ast_string_field_init(tmp, 32)) {
2007 tmp->keyrotateid = -1;
2009 ast_string_field_set(tmp,exten, "s");
2010 ast_string_field_set(tmp,host, host);
2014 jbconf.max_jitterbuf = maxjitterbuffer;
2015 jbconf.resync_threshold = resyncthreshold;
2016 jbconf.max_contig_interp = maxjitterinterps;
2017 jbconf.target_extra = jittertargetextra;
2018 jb_setconf(tmp->jb,&jbconf);
2020 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2022 tmp->hold_signaling = 1;
2023 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2028 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2030 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2032 size_t afdatalen = new->afdatalen;
2033 memcpy(new, fr, sizeof(*new));
2034 iax_frame_wrap(new, &fr->af);
2035 new->afdatalen = afdatalen;
2038 new->direction = DIRECTION_INGRESS;
2043 /* keep these defined in this order. They are used in find_callno to
2044 * determine whether or not a new call number should be allowed. */
2046 /* do not allow a new call number, only search ones in use for match */
2048 /* search for match first, then allow a new one to be allocated */
2050 /* do not search for match, force a new call number */
2052 /* do not search for match, force a new call number. Signifies call number
2053 * has been calltoken validated */
2054 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2057 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2059 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2060 (cur->addr.sin_port == sin->sin_port)) {
2061 /* This is the main host */
2062 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2063 (check_dcallno ? dcallno == cur->callno : 1) ) {
2064 /* That's us. Be sure we keep track of the peer call number */
2068 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2069 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2070 /* We're transferring */
2071 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2077 static int make_trunk(unsigned short callno, int locked)
2081 struct callno_entry *callno_entry;
2082 if (iaxs[callno]->oseqno) {
2083 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2086 if (callno & TRUNK_CALL_START) {
2087 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2091 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2092 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2096 x = callno_entry->callno;
2097 ast_mutex_lock(&iaxsl[x]);
2100 * \note We delete these before switching the slot, because if
2101 * they fire in the meantime, they will generate a warning.
2103 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2104 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2105 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2106 iaxs[x] = iaxs[callno];
2107 iaxs[x]->callno = x;
2109 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2110 * before assigning the new one */
2111 if (iaxs[x]->callno_entry) {
2112 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2114 iaxs[x]->callno_entry = callno_entry;
2116 iaxs[callno] = NULL;
2117 /* Update the two timers that should have been started */
2118 iaxs[x]->pingid = iax2_sched_add(sched,
2119 ping_time * 1000, send_ping, (void *)(long)x);
2120 iaxs[x]->lagid = iax2_sched_add(sched,
2121 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2124 ast_mutex_unlock(&iaxsl[callno]);
2127 ast_mutex_unlock(&iaxsl[x]);
2129 /* We moved this call from a non-trunked to a trunked call */
2130 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2135 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2137 if (!pvt->transfercallno) {
2138 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2142 ao2_link(iax_transfercallno_pvts, pvt);
2145 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2147 if (!pvt->transfercallno) {
2148 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2152 ao2_unlink(iax_transfercallno_pvts, pvt);
2154 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2156 if (!pvt->peercallno) {
2157 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2161 ao2_link(iax_peercallno_pvts, pvt);
2164 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2166 if (!pvt->peercallno) {
2167 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2171 ao2_unlink(iax_peercallno_pvts, pvt);
2174 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2176 struct addr_range *lim = obj;
2181 static int addr_range_hash_cb(const void *obj, const int flags)
2183 const struct addr_range *lim = obj;
2184 struct sockaddr_in sin;
2185 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2186 return abs((int) sin.sin_addr.s_addr);
2189 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2191 struct addr_range *lim1 = obj, *lim2 = arg;
2192 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2193 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2194 CMP_MATCH | CMP_STOP : 0;
2197 static int peercnt_hash_cb(const void *obj, const int flags)
2199 const struct peercnt *peercnt = obj;
2200 return abs((int) peercnt->addr);
2203 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2205 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2206 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2209 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2211 struct addr_range *addr_range = obj;
2212 struct sockaddr_in *sin = arg;
2213 struct sockaddr_in ha_netmask_sin;
2214 struct sockaddr_in ha_addr_sin;
2216 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2217 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2219 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2220 return CMP_MATCH | CMP_STOP;
2228 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2230 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2232 struct addr_range *addr_range;
2233 struct iax2_peer *peer = NULL;
2234 struct iax2_user *user = NULL;
2235 /* if no username is given, check for guest accounts */
2236 const char *find = S_OR(name, "guest");
2237 int res = 1; /* required by default */
2239 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2240 /* There are only two cases in which calltoken validation is not required.
2241 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2242 * the peer definition has not set the requirecalltoken option.
2243 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2246 /* ----- Case 1 ----- */
2247 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2248 ao2_ref(addr_range, -1);
2252 /* ----- Case 2 ----- */
2253 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2254 calltoken_required = user->calltoken_required;
2255 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2256 calltoken_required = user->calltoken_required;
2257 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2258 calltoken_required = peer->calltoken_required;
2259 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2260 calltoken_required = peer->calltoken_required;
2270 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);
2271 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2272 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2282 * \brief set peercnt callno limit.
2285 * First looks in custom definitions. If not found, global limit
2286 * is used. Entries marked as reg already have
2287 * a custom limit set by a registration and are not modified.
2289 static void set_peercnt_limit(struct peercnt *peercnt)
2291 uint16_t limit = global_maxcallno;
2292 struct addr_range *addr_range;
2293 struct sockaddr_in sin = {
2294 .sin_addr.s_addr = peercnt->addr,
2298 if (peercnt->reg && peercnt->limit) {
2299 return; /* this peercnt has a custom limit set by a registration */
2302 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2303 limit = addr_range->limit;
2304 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2305 ao2_ref(addr_range, -1);
2308 peercnt->limit = limit;
2313 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2315 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2317 struct peercnt *peercnt = obj;
2319 set_peercnt_limit(peercnt);
2320 ast_debug(1, "Reset limits for peercnts table\n");
2327 * \brief returns match if delme is set.
2329 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2331 struct addr_range *addr_range = obj;
2333 return addr_range->delme ? CMP_MATCH : 0;
2338 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2340 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2342 /* this function turns off and on custom callno limits set by peer registration */
2343 struct peercnt *peercnt;
2344 struct peercnt tmp = {
2347 struct sockaddr_in sin;
2349 ast_sockaddr_to_sin(sockaddr, &sin);
2351 tmp.addr = sin.sin_addr.s_addr;
2353 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2356 peercnt->limit = limit;
2358 set_peercnt_limit(peercnt);
2360 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2361 ao2_ref(peercnt, -1); /* decrement ref from find */
2367 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2369 * \details First searches for the address in the peercnts table. If found
2370 * the current count is incremented. If not found a new peercnt is allocated
2371 * and linked into the peercnts table with a call number count of 1.
2373 static int peercnt_add(struct sockaddr_in *sin)
2375 struct peercnt *peercnt;
2376 unsigned long addr = sin->sin_addr.s_addr;
2378 struct peercnt tmp = {
2382 /* Reasoning for peercnts container lock: Two identical ip addresses
2383 * could be added by different threads at the "same time". Without the container
2384 * lock, both threads could alloc space for the same object and attempt
2385 * to link to table. With the lock, one would create the object and link
2386 * to table while the other would find the already created peercnt object
2387 * rather than creating a new one. */
2389 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2391 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2393 /* create and set defaults */
2394 peercnt->addr = addr;
2395 set_peercnt_limit(peercnt);
2396 /* guarantees it does not go away after unlocking table
2397 * ao2_find automatically adds this */
2398 ao2_link(peercnts, peercnt);
2400 ao2_unlock(peercnts);
2404 /* check to see if the address has hit its callno limit. If not increment cur. */
2405 if (peercnt->limit > peercnt->cur) {
2407 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2408 } else { /* max num call numbers for this peer has been reached! */
2409 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2413 /* clean up locks and ref count */
2414 ao2_unlock(peercnt);
2415 ao2_unlock(peercnts);
2416 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2423 * \brief decrements a peercnts table entry
2425 static void peercnt_remove(struct peercnt *peercnt)
2427 struct sockaddr_in sin = {
2428 .sin_addr.s_addr = peercnt->addr,
2432 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2433 * peercnt_add could try and grab this entry from the table and modify it at the
2434 * "same time" this thread attemps to unlink it.*/
2437 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2438 /* if this was the last connection from the peer remove it from table */
2439 if (peercnt->cur == 0) {
2440 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2442 ao2_unlock(peercnts);
2448 * \brief called by scheduler to decrement object
2450 static int peercnt_remove_cb(const void *obj)
2452 struct peercnt *peercnt = (struct peercnt *) obj;
2454 peercnt_remove(peercnt);
2455 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2462 * \brief decrements peercnts connection count, finds by addr
2464 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2466 struct peercnt *peercnt;
2467 struct peercnt tmp = {
2468 .addr = sin->sin_addr.s_addr,
2471 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2472 peercnt_remove(peercnt);
2473 ao2_ref(peercnt, -1); /* decrement ref from find */
2480 * \brief Create callno_limit entry based on configuration
2482 static void build_callno_limits(struct ast_variable *v)
2484 struct addr_range *addr_range = NULL;
2485 struct addr_range tmp;
2491 for (; v; v = v->next) {
2495 ha = ast_append_ha("permit", v->name, NULL, &error);
2497 /* check for valid config information */
2499 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2501 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2502 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2507 ast_copy_ha(ha, &tmp.ha);
2508 /* find or create the addr_range */
2509 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2510 ao2_lock(addr_range);
2512 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2514 return; /* out of memory */
2517 /* copy over config data into addr_range object */
2518 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2519 ast_free_ha(ha); /* cleanup the tmp ha */
2520 addr_range->limit = limit;
2521 addr_range->delme = 0;
2525 ao2_unlock(addr_range);
2527 ao2_link(callno_limits, addr_range);
2529 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2535 * \brief Create calltoken_ignores entry based on configuration
2537 static int add_calltoken_ignore(const char *addr)
2539 struct addr_range tmp;
2540 struct addr_range *addr_range = NULL;
2541 struct ast_ha *ha = NULL;
2544 if (ast_strlen_zero(addr)) {
2545 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2549 ha = ast_append_ha("permit", addr, NULL, &error);
2551 /* check for valid config information */
2553 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2557 ast_copy_ha(ha, &tmp.ha);
2558 /* find or create the addr_range */
2559 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2560 ao2_lock(addr_range);
2561 addr_range->delme = 0;
2562 ao2_unlock(addr_range);
2563 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2564 /* copy over config data into addr_range object */
2565 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2566 ao2_link(calltoken_ignores, addr_range);
2573 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2578 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2580 struct ao2_iterator i;
2581 struct peercnt *peercnt;
2582 struct sockaddr_in sin;
2587 e->command = "iax2 show callnumber usage";
2589 "Usage: iax2 show callnumber usage [IP address]\n"
2590 " Shows current IP addresses which are consuming iax2 call numbers\n";
2595 if (a->argc < 4 || a->argc > 5)
2596 return CLI_SHOWUSAGE;
2598 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2599 i = ao2_iterator_init(peercnts, 0);
2600 while ((peercnt = ao2_iterator_next(&i))) {
2601 sin.sin_addr.s_addr = peercnt->addr;
2602 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
2603 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2604 ao2_ref(peercnt, -1);
2608 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2610 ao2_ref(peercnt, -1);
2612 ao2_iterator_destroy(&i);
2615 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2616 "Non-CallToken Validated Callno Used: %d\n",
2617 global_maxcallno_nonval,
2618 total_nonval_callno_used);
2620 ast_cli(a->fd, "Total Available Callno: %d\n"
2621 "Regular Callno Available: %d\n"
2622 "Trunk Callno Available: %d\n",
2623 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2624 ao2_container_count(callno_pool),
2625 ao2_container_count(callno_pool_trunk));
2626 } else if (a->argc == 5 && !found) {
2627 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
2637 static struct callno_entry *get_unused_callno(int trunk, int validated)
2639 struct callno_entry *callno_entry = NULL;
2640 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2641 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2642 /* Minor optimization for the extreme case. */
2646 /* the callno_pool container is locked here primarily to ensure thread
2647 * safety of the total_nonval_callno_used check and increment */
2648 ao2_lock(callno_pool);
2650 /* only a certain number of nonvalidated call numbers should be allocated.
2651 * If there ever is an attack, this separates the calltoken validating
2652 * users from the non calltoken validating users. */
2653 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2654 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2655 ao2_unlock(callno_pool);
2659 /* unlink the object from the container, taking over ownership
2660 * of the reference the container had to the object */
2661 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2664 callno_entry->validated = validated;
2666 total_nonval_callno_used++;
2670 ao2_unlock(callno_pool);
2671 return callno_entry;
2674 static int replace_callno(const void *obj)
2676 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2678 /* the callno_pool container is locked here primarily to ensure thread
2679 * safety of the total_nonval_callno_used check and decrement */
2680 ao2_lock(callno_pool);
2682 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2683 total_nonval_callno_used--;
2684 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2685 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2688 if (callno_entry->callno < TRUNK_CALL_START) {
2689 ao2_link(callno_pool, callno_entry);
2691 ao2_link(callno_pool_trunk, callno_entry);
2693 ao2_ref(callno_entry, -1); /* only container ref remains */
2695 ao2_unlock(callno_pool);
2699 static int callno_hash(const void *obj, const int flags)
2701 return abs(ast_random());
2704 static int create_callno_pools(void)
2708 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2712 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2716 /* start at 2, 0 and 1 are reserved */
2717 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2718 struct callno_entry *callno_entry;
2720 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2724 callno_entry->callno = i;
2726 if (i < TRUNK_CALL_START) {
2727 ao2_link(callno_pool, callno_entry);
2729 ao2_link(callno_pool_trunk, callno_entry);
2732 ao2_ref(callno_entry, -1);
2740 * \brief Schedules delayed removal of iax2_pvt call number data
2742 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2743 * avaliable again, and the address from the previous connection must be decremented
2744 * from the peercnts table. This function schedules these operations to take place.
2746 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2749 struct peercnt *peercnt;
2750 struct peercnt tmp = {
2751 .addr = sin->sin_addr.s_addr,
2754 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2755 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2756 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2757 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2759 ao2_ref(peercnt, -1);
2763 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2768 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2770 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2773 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2775 if (frametype != AST_FRAME_IAX) {
2779 case IAX_COMMAND_NEW:
2780 case IAX_COMMAND_REGREQ:
2781 case IAX_COMMAND_FWDOWNL:
2782 case IAX_COMMAND_REGREL:
2784 case IAX_COMMAND_POKE:
2794 * \note Calling this function while holding another pvt lock can cause a deadlock.
2796 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2800 /* this call is calltoken validated as long as it is either NEW_FORCE
2801 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2802 int validated = (new > NEW_ALLOW) ? 1 : 0;
2805 if (new <= NEW_ALLOW) {
2807 struct chan_iax2_pvt *pvt;
2808 struct chan_iax2_pvt tmp_pvt = {
2810 .peercallno = callno,
2811 .transfercallno = callno,
2813 .frames_received = check_dcallno,
2816 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2817 /* this works for finding normal call numbers not involving transfering */
2818 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2819 if (return_locked) {
2820 ast_mutex_lock(&iaxsl[pvt->callno]);
2827 /* this searches for transfer call numbers that might not get caught otherwise */
2828 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2829 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2830 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2831 if (return_locked) {
2832 ast_mutex_lock(&iaxsl[pvt->callno]);
2840 /* This will occur on the first response to a message that we initiated,
2841 * such as a PING. */
2843 ast_mutex_lock(&iaxsl[dcallno]);
2845 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2846 iaxs[dcallno]->peercallno = callno;
2848 store_by_peercallno(iaxs[dcallno]);
2849 if (!res || !return_locked) {
2850 ast_mutex_unlock(&iaxsl[dcallno]);
2855 ast_mutex_unlock(&iaxsl[dcallno]);
2858 if (!res && (new >= NEW_ALLOW)) {
2859 struct callno_entry *callno_entry;
2860 /* It may seem odd that we look through the peer list for a name for
2861 * this *incoming* call. Well, it is weird. However, users don't
2862 * have an IP address/port number that we can match against. So,
2863 * this is just checking for a peer that has that IP/port and
2864 * assuming that we have a user of the same name. This isn't always
2865 * correct, but it will be changed if needed after authentication. */
2866 if (!iax2_getpeername(*sin, host, sizeof(host)))
2867 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2869 if (peercnt_add(sin)) {
2870 /* This address has hit its callnumber limit. When the limit
2871 * is reached, the connection is not added to the peercnts table.*/
2875 if (!(callno_entry = get_unused_callno(0, validated))) {
2876 /* since we ran out of space, remove the peercnt
2877 * entry we added earlier */
2878 peercnt_remove_by_addr(sin);
2879 ast_log(LOG_WARNING, "No more space\n");
2882 x = callno_entry->callno;
2883 ast_mutex_lock(&iaxsl[x]);
2885 iaxs[x] = new_iax(sin, host);
2888 ast_debug(1, "Creating new call structure %d\n", x);
2889 iaxs[x]->callno_entry = callno_entry;
2890 iaxs[x]->sockfd = sockfd;
2891 iaxs[x]->addr.sin_port = sin->sin_port;
2892 iaxs[x]->addr.sin_family = sin->sin_family;
2893 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2894 iaxs[x]->peercallno = callno;
2895 iaxs[x]->callno = x;
2896 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2897 iaxs[x]->expiry = min_reg_expire;
2898 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2899 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2900 iaxs[x]->amaflags = amaflags;
2901 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2902 ast_string_field_set(iaxs[x], accountcode, accountcode);
2903 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2904 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2905 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2907 if (iaxs[x]->peercallno) {
2908 store_by_peercallno(iaxs[x]);
2911 ast_log(LOG_WARNING, "Out of resources\n");
2912 ast_mutex_unlock(&iaxsl[x]);
2913 replace_callno(callno_entry);
2917 ast_mutex_unlock(&iaxsl[x]);
2923 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2924 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2927 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2929 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2933 * \brief Queue a frame to a call's owning asterisk channel
2935 * \pre This function assumes that iaxsl[callno] is locked when called.
2937 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2938 * was valid before calling it, it may no longer be valid after calling it.
2939 * This function may unlock and lock the mutex associated with this callno,
2940 * meaning that another thread may grab it and destroy the call.
2942 static int iax2_queue_frame(int callno, struct ast_frame *f)
2944 iax2_lock_owner(callno);
2945 if (iaxs[callno] && iaxs[callno]->owner) {
2946 ast_queue_frame(iaxs[callno]->owner, f);
2947 ast_channel_unlock(iaxs[callno]->owner);
2953 * \brief Queue a hangup frame on the ast_channel owner
2955 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2956 * is active for the given call number.
2958 * \pre Assumes lock for callno is already held.
2960 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2961 * was valid before calling it, it may no longer be valid after calling it.
2962 * This function may unlock and lock the mutex associated with this callno,
2963 * meaning that another thread may grab it and destroy the call.
2965 static int iax2_queue_hangup(int callno)
2967 iax2_lock_owner(callno);
2968 if (iaxs[callno] && iaxs[callno]->owner) {
2969 ast_queue_hangup(iaxs[callno]->owner);
2970 ast_channel_unlock(iaxs[callno]->owner);
2976 * \brief Queue a control frame on the ast_channel owner
2978 * This function queues a control frame on the owner of the IAX2 pvt struct that
2979 * is active for the given call number.
2981 * \pre Assumes lock for callno is already held.
2983 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2984 * was valid before calling it, it may no longer be valid after calling it.
2985 * This function may unlock and lock the mutex associated with this callno,
2986 * meaning that another thread may grab it and destroy the call.
2988 static int iax2_queue_control_data(int callno,
2989 enum ast_control_frame_type control, const void *data, size_t datalen)
2991 iax2_lock_owner(callno);
2992 if (iaxs[callno] && iaxs[callno]->owner) {
2993 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2994 ast_channel_unlock(iaxs[callno]->owner);
2998 static void destroy_firmware(struct iax_firmware *cur)
3000 /* Close firmware */
3002 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3008 static int try_firmware(char *s)
3011 struct iax_firmware *cur = NULL;
3012 int ifd, fd, res, len, chunk;
3013 struct ast_iax2_firmware_header *fwh, fwh2;
3014 struct MD5Context md5;
3015 unsigned char sum[16], buf[1024];
3018 if (!(s2 = alloca(strlen(s) + 100))) {
3019 ast_log(LOG_WARNING, "Alloca failed!\n");
3023 last = strrchr(s, '/');
3029 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3031 if (stat(s, &stbuf) < 0) {
3032 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3036 /* Make sure it's not a directory */
3037 if (S_ISDIR(stbuf.st_mode))
3039 ifd = open(s, O_RDONLY);
3041 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3044 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3046 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3050 /* Unlink our newly created file */
3053 /* Now copy the firmware into it */
3054 len = stbuf.st_size;
3057 if (chunk > sizeof(buf))
3058 chunk = sizeof(buf);
3059 res = read(ifd, buf, chunk);
3061 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3066 res = write(fd, buf, chunk);
3068 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3076 /* Return to the beginning */
3077 lseek(fd, 0, SEEK_SET);
3078 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3079 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3083 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3084 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3088 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3089 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3093 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3094 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3098 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3099 if (fwh == MAP_FAILED) {
3100 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3105 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3106 MD5Final(sum, &md5);
3107 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3108 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3109 munmap((void*)fwh, stbuf.st_size);
3114 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3115 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3116 /* Found a candidate */
3117 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3118 /* The version we have on loaded is older, load this one instead */
3120 /* This version is no newer than what we have. Don't worry about it.
3121 We'll consider it a proper load anyhow though */
3122 munmap((void*)fwh, stbuf.st_size);
3128 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3130 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3135 munmap((void*)cur->fwh, cur->mmaplen);
3140 cur->mmaplen = stbuf.st_size;
3147 static int iax_check_version(char *dev)
3150 struct iax_firmware *cur = NULL;
3152 if (ast_strlen_zero(dev))
3155 AST_LIST_LOCK(&firmwares);
3156 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3157 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3158 res = ntohs(cur->fwh->version);
3162 AST_LIST_UNLOCK(&firmwares);
3167 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3170 unsigned int bs = desc & 0xff;
3171 unsigned int start = (desc >> 8) & 0xffffff;
3173 struct iax_firmware *cur;
3175 if (ast_strlen_zero((char *)dev) || !bs)
3180 AST_LIST_LOCK(&firmwares);
3181 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3182 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3184 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3185 if (start < ntohl(cur->fwh->datalen)) {
3186 bytes = ntohl(cur->fwh->datalen) - start;
3189 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3192 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3200 AST_LIST_UNLOCK(&firmwares);
3206 static void reload_firmware(int unload)
3208 struct iax_firmware *cur = NULL;
3211 char dir[256], fn[256];
3213 AST_LIST_LOCK(&firmwares);
3215 /* Mark all as dead */
3216 AST_LIST_TRAVERSE(&firmwares, cur, list)
3219 /* Now that we have marked them dead... load new ones */
3221 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3224 while((de = readdir(fwd))) {
3225 if (de->d_name[0] != '.') {
3226 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3227 if (!try_firmware(fn)) {
3228 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3234 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3237 /* Clean up leftovers */
3238 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3241 AST_LIST_REMOVE_CURRENT(list);
3242 destroy_firmware(cur);
3244 AST_LIST_TRAVERSE_SAFE_END;
3246 AST_LIST_UNLOCK(&firmwares);
3250 * \note This function assumes that iaxsl[callno] is locked when called.
3252 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3253 * was valid before calling it, it may no longer be valid after calling it.
3254 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3255 * associated with this callno, meaning that another thread may grab it and destroy the call.
3257 static int __do_deliver(void *data)
3259 /* Just deliver the packet by using queueing. This is called by
3260 the IAX thread with the iaxsl lock held. */
3261 struct iax_frame *fr = data;
3263 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3264 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3265 iax2_queue_frame(fr->callno, &fr->af);
3266 /* Free our iax frame */
3267 iax2_frame_free(fr);
3268 /* And don't run again */
3272 static int handle_error(void)
3274 /* XXX Ideally we should figure out why an error occurred and then abort those
3275 rather than continuing to try. Unfortunately, the published interface does
3276 not seem to work XXX */
3278 struct sockaddr_in *sin;
3281 struct sock_extended_err e;
3286 m.msg_controllen = sizeof(e);
3288 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3290 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3292 if (m.msg_controllen) {
3293 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3295 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3297 ast_log(LOG_WARNING, "No address detected??\n");
3299 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3306 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3309 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3312 ast_debug(1, "Received error: %s\n", strerror(errno));
3319 static int send_packet(struct iax_frame *f)
3322 int callno = f->callno;
3324 /* Don't send if there was an error, but return error instead */
3325 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3328 /* Called with iaxsl held */
3330 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));
3334 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3335 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3338 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3339 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3343 ast_debug(1, "Received error: %s\n", strerror(errno));
3352 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3353 * for the given call number may disappear during its execution.
3355 static int iax2_predestroy(int callno)
3357 struct ast_channel *c = NULL;
3358 struct chan_iax2_pvt *pvt = iaxs[callno];
3363 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3364 iax2_destroy_helper(pvt);
3365 ast_set_flag64(pvt, IAX_ALREADYGONE);
3368 if ((c = pvt->owner)) {
3370 iax2_queue_hangup(callno);
3372 ast_module_unref(ast_module_info->self);
3378 static void iax2_destroy(int callno)
3380 struct chan_iax2_pvt *pvt = NULL;
3381 struct ast_channel *owner = NULL;
3384 if ((pvt = iaxs[callno])) {
3386 /* iax2_destroy_helper gets called from this function later on. When
3387 * called twice, we get the (previously) familiar FRACK! errors in
3388 * devmode, from the scheduler. An alternative to this approach is to
3389 * reset the scheduler entries to -1 when they're deleted in
3390 * iax2_destroy_helper(). That approach was previously decided to be
3391 * "wrong" because "the memory is going to be deallocated anyway. Why
3392 * should we be resetting those values?" */
3393 iax2_destroy_helper(pvt);
3397 owner = pvt ? pvt->owner : NULL;
3400 if (ast_channel_trylock(owner)) {
3401 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3402 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3408 iaxs[callno] = NULL;
3415 /* If there's an owner, prod it to give up */
3416 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3417 * because we already hold the owner channel lock. */
3418 ast_queue_hangup(owner);
3421 if (pvt->peercallno) {
3422 remove_by_peercallno(pvt);
3425 if (pvt->transfercallno) {
3426 remove_by_transfercallno(pvt);
3436 ast_channel_unlock(owner);
3440 static int update_packet(struct iax_frame *f)
3442 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3443 struct ast_iax2_full_hdr *fh = f->data;
3444 struct ast_frame af;
3446 /* if frame is encrypted. decrypt before updating it. */
3447 if (f->encmethods) {
3448 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3450 /* Mark this as a retransmission */
3451 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3453 f->iseqno = iaxs[f->callno]->iseqno;
3454 fh->iseqno = f->iseqno;
3456 /* Now re-encrypt the frame */
3457 if (f->encmethods) {
3458 /* since this is a retransmit frame, create a new random padding
3459 * before re-encrypting. */
3460 build_rand_pad(f->semirand, sizeof(f->semirand));
3461 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3466 static int attempt_transmit(const void *data);
3467 static void __attempt_transmit(const void *data)
3469 /* Attempt to transmit the frame to the remote peer...
3470 Called without iaxsl held. */
3471 struct iax_frame *f = (struct iax_frame *)data;
3473 int callno = f->callno;
3474 /* Make sure this call is still active */
3476 ast_mutex_lock(&iaxsl[callno]);
3477 if (callno && iaxs[callno]) {
3478 if ((f->retries < 0) /* Already ACK'd */ ||
3479 (f->retries >= max_retries) /* Too many attempts */) {
3480 /* Record an error if we've transmitted too many times */
3481 if (f->retries >= max_retries) {
3483 /* Transfer timeout */
3484 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3485 } else if (f->final) {
3486 iax2_destroy(callno);
3488 if (iaxs[callno]->owner)
3489 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),ast_channel_name(iaxs[f->callno]->owner), f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3490 iaxs[callno]->error = ETIMEDOUT;
3491 if (iaxs[callno]->owner) {
3492 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3494 iax2_queue_frame(callno, &fr); /* XXX */
3495 /* Remember, owner could disappear */
3496 if (iaxs[callno] && iaxs[callno]->owner)
3497 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3499 if (iaxs[callno]->reg) {
3500 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3501 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3502 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3504 iax2_destroy(callno);
3511 /* Update it if it needs it */
3513 /* Attempt transmission */
3516 /* Try again later after 10 times as long */
3518 if (f->retrytime > MAX_RETRY_TIME)
3519 f->retrytime = MAX_RETRY_TIME;
3520 /* Transfer messages max out at one second */
3521 if (f->transfer && (f->retrytime > 1000))
3522 f->retrytime = 1000;
3523 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3526 /* Make sure it gets freed */
3532 /* Don't attempt delivery, just remove it from the queue */
3533 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3534 ast_mutex_unlock(&iaxsl[callno]);
3535 f->retrans = -1; /* this is safe because this is the scheduled function */
3536 /* Free the IAX frame */
3538 } else if (callno) {
3539 ast_mutex_unlock(&iaxsl[callno]);
3543 static int attempt_transmit(const void *data)
3545 #ifdef SCHED_MULTITHREADED
3546 if (schedule_action(__attempt_transmit, data))
3548 __attempt_transmit(data);
3552 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3554 struct iax2_peer *peer = NULL;
3555 struct iax2_user *user = NULL;
3556 static const char * const choices[] = { "all", NULL };
3561 e->command = "iax2 prune realtime";
3563 "Usage: iax2 prune realtime [<peername>|all]\n"
3564 " Prunes object(s) from the cache\n";
3568 cmplt = ast_cli_complete(a->word, choices, a->n);
3570 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3576 return CLI_SHOWUSAGE;
3577 if (!strcmp(a->argv[3], "all")) {
3580 ast_cli(a->fd, "Cache flushed successfully.\n");
3583 peer = find_peer(a->argv[3], 0);
3584 user = find_user(a->argv[3]);
3587 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3588 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3589 expire_registry(peer_ref(peer));
3590 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3592 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3597 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3598 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3599 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3601 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3603 ao2_unlink(users,user);
3607 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3613 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3617 e->command = "iax2 test losspct";
3619 "Usage: iax2 test losspct <percentage>\n"
3620 " For testing, throws away <percentage> percent of incoming packets\n";
3626 return CLI_SHOWUSAGE;
3628 test_losspct = atoi(a->argv[3]);
3634 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3638 e->command = "iax2 test late";
3640 "Usage: iax2 test late <ms>\n"
3641 " For testing, count the next frame as <ms> ms late\n";
3648 return CLI_SHOWUSAGE;
3650 test_late = atoi(a->argv[3]);
3655 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3659 e->command = "iax2 test resync";
3661 "Usage: iax2 test resync <ms>\n"
3662 " For testing, adjust all future frames by <ms> ms\n";
3669 return CLI_SHOWUSAGE;
3671 test_resync = atoi(a->argv[3]);
3676 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3680 e->command = "iax2 test jitter";
3682 "Usage: iax2 test jitter <ms> <pct>\n"
3683 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3684 " percentage of packets. If <pct> is not specified, adds\n"
3685 " jitter to all packets.\n";
3691 if (a->argc < 4 || a->argc > 5)
3692 return CLI_SHOWUSAGE;
3694 test_jit = atoi(a->argv[3]);
3696 test_jitpct = atoi(a->argv[4]);
3700 #endif /* IAXTESTS */
3702 /*! \brief peer_status: Report Peer status in character string */
3703 /* returns 1 if peer is online, -1 if unmonitored */
3704 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3708 if (peer->lastms < 0) {
3709 ast_copy_string(status, "UNREACHABLE", statuslen);
3710 } else if (peer->lastms > peer->maxms) {
3711 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3713 } else if (peer->lastms) {
3714 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3717 ast_copy_string(status, "UNKNOWN", statuslen);
3720 ast_copy_string(status, "Unmonitored", statuslen);
3726 /*! \brief Show one peer in detail */
3727 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3731 struct iax2_peer *peer;
3732 char codec_buf[512];
3733 struct ast_str *encmethods = ast_str_alloca(256);
3734 int x = 0, load_realtime = 0;
3738 e->command = "iax2 show peer";
3740 "Usage: iax2 show peer <name>\n"
3741 " Display details on specific IAX peer\n";
3745 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3750 return CLI_SHOWUSAGE;