2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
34 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35 * \addtogroup configuration_file
38 /*! \page iax.conf iax.conf
39 * \verbinclude iax.conf.sample
43 <use type="external">crypto</use>
44 <support_level>core</support_level>
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
59 #include <sys/signal.h>
67 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
69 #include "asterisk/lock.h"
70 #include "asterisk/frame.h"
71 #include "asterisk/channel.h"
72 #include "asterisk/module.h"
73 #include "asterisk/pbx.h"
74 #include "asterisk/sched.h"
75 #include "asterisk/io.h"
76 #include "asterisk/config.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/cdr.h"
81 #include "asterisk/crypto.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/app.h"
86 #include "asterisk/astdb.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/features.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/causes.h"
91 #include "asterisk/localtime.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
97 #include "asterisk/event.h"
98 #include "asterisk/astobj2.h"
99 #include "asterisk/timing.h"
100 #include "asterisk/taskprocessor.h"
101 #include "asterisk/test.h"
102 #include "asterisk/data.h"
103 #include "asterisk/netsock2.h"
106 #include "iax2-parser.h"
107 #include "iax2-provision.h"
108 #include "jitterbuf.h"
111 <application name="IAX2Provision" language="en_US">
113 Provision a calling IAXy with a given template.
116 <parameter name="template">
117 <para>If not specified, defaults to <literal>default</literal>.</para>
121 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
122 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
123 or <literal>0</literal> on success.</para>
126 <function name="IAXPEER" language="en_US">
128 Gets IAX peer information.
131 <parameter name="peername" required="true">
133 <enum name="CURRENTCHANNEL">
134 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
135 endpoint of the current channel</para>
139 <parameter name="item">
140 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
143 <para>(default) The IP address.</para>
146 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
148 <enum name="mailbox">
149 <para>The configured mailbox.</para>
151 <enum name="context">
152 <para>The configured context.</para>
155 <para>The epoch time of the next expire.</para>
157 <enum name="dynamic">
158 <para>Is it dynamic? (yes/no).</para>
160 <enum name="callerid_name">
161 <para>The configured Caller ID name.</para>
163 <enum name="callerid_num">
164 <para>The configured Caller ID number.</para>
167 <para>The configured codecs.</para>
169 <enum name="codec[x]">
170 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
171 with <literal>0</literal>)</para>
177 <para>Gets information associated with the specified IAX2 peer.</para>
180 <ref type="function">SIPPEER</ref>
183 <function name="IAXVAR" language="en_US">
185 Sets or retrieves a remote variable.
188 <parameter name="varname" required="true" />
191 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
194 <manager name="IAXpeers" language="en_US">
199 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
204 <manager name="IAXpeerlist" language="en_US">
209 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
212 <para>List all the IAX peers.</para>
215 <manager name="IAXnetstats" language="en_US">
221 <para>Show IAX channels network statistics.</para>
224 <manager name="IAXregistry" language="en_US">
226 Show IAX registrations.
229 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
232 <para>Show IAX registrations.</para>
237 /* Define SCHED_MULTITHREADED to run the scheduler in a special
238 multithreaded mode. */
239 #define SCHED_MULTITHREADED
241 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
242 thread is actually doing. */
243 #define DEBUG_SCHED_MULTITHREAD
247 static int nochecksums = 0;
250 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
251 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
253 #define DEFAULT_THREAD_COUNT 10
254 #define DEFAULT_MAX_THREAD_COUNT 100
255 #define DEFAULT_RETRY_TIME 1000
256 #define MEMORY_SIZE 100
257 #define DEFAULT_DROP 3
259 #define DEBUG_SUPPORT
261 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
263 /* Sample over last 100 units to determine historic jitter */
266 static struct ast_codec_pref prefs;
268 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
271 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
272 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
273 #define MAX_TRUNK_MTU 1240
275 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
276 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
278 #define DEFAULT_CONTEXT "default"
280 static char default_parkinglot[AST_MAX_CONTEXT];
282 static char language[MAX_LANGUAGE] = "";
283 static char regcontext[AST_MAX_CONTEXT] = "";
285 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
286 static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
287 static int network_change_event_sched_id = -1;
289 static int maxauthreq = 3;
290 static int max_retries = 4;
291 static int ping_time = 21;
292 static int lagrq_time = 10;
293 static int maxjitterbuffer=1000;
294 static int resyncthreshold=1000;
295 static int maxjitterinterps=10;
296 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
298 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
300 static int trunkfreq = 20;
301 static int trunkmaxsize = MAX_TRUNKDATA;
303 static int authdebug = 0;
304 static int autokill = 0;
305 static int iaxcompat = 0;
306 static int last_authmethod = 0;
308 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
310 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
317 static int min_reg_expire;
318 static int max_reg_expire;
320 static int srvlookup = 0;
322 static struct ast_timer *timer; /* Timer for trunking */
324 static struct ast_netsock_list *netsock;
325 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
326 static int defaultsockfd = -1;
328 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
331 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
333 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
334 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
335 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
338 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
339 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
341 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
343 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
344 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
345 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
346 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
348 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
349 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
352 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
353 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
354 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
356 /* if a pvt has encryption setup done and is running on the call */
357 #define IAX_CALLENCRYPTED(pvt) \
358 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
360 #define IAX_DEBUGDIGEST(msg, key) do { \
362 char digest[33] = ""; \
367 for (idx = 0; idx < 16; idx++) \
368 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
370 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
373 static struct io_context *io;
374 static struct ast_sched_context *sched;
376 #define DONT_RESCHEDULE -2
378 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
380 static int iaxdebug = 0;
382 static int iaxtrunkdebug = 0;
384 static int test_losspct = 0;
386 static int test_late = 0;
387 static int test_resync = 0;
388 static int test_jit = 0;
389 static int test_jitpct = 0;
390 #endif /* IAXTESTS */
392 static char accountcode[AST_MAX_ACCOUNT_CODE];
393 static char mohinterpret[MAX_MUSICCLASS];
394 static char mohsuggest[MAX_MUSICCLASS];
395 static int amaflags = 0;
397 static int delayreject = 0;
398 static int iax2_encryption = 0;
400 static struct ast_flags64 globalflags = { 0 };
402 static pthread_t netthreadid = AST_PTHREADT_NULL;
405 IAX_STATE_STARTED = (1 << 0),
406 IAX_STATE_AUTHENTICATED = (1 << 1),
407 IAX_STATE_TBD = (1 << 2),
410 struct iax2_context {
411 char context[AST_MAX_CONTEXT];
412 struct iax2_context *next;
416 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
417 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
418 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
419 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
420 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
421 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
422 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
423 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
424 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
425 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
426 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
427 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
428 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
429 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
430 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
431 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
432 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
433 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
434 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
435 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
436 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
437 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
438 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
439 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
440 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
441 #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 */
442 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
443 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
444 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
445 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
446 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
447 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
448 static int global_rtautoclear = 120;
450 static int reload_config(int forced_reload);
453 * \brief Call token validation settings.
455 enum calltoken_peer_enum {
456 /*! \brief Default calltoken required unless the ip is in the ignorelist */
457 CALLTOKEN_DEFAULT = 0,
458 /*! \brief Require call token validation. */
460 /*! \brief Require call token validation after a successful registration
461 * using call token validation occurs. */
463 /*! \brief Do not require call token validation. */
468 AST_DECLARE_STRING_FIELDS(
469 AST_STRING_FIELD(name);
470 AST_STRING_FIELD(secret);
471 AST_STRING_FIELD(dbsecret);
472 AST_STRING_FIELD(accountcode);
473 AST_STRING_FIELD(mohinterpret);
474 AST_STRING_FIELD(mohsuggest);
475 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
476 AST_STRING_FIELD(language);
477 AST_STRING_FIELD(cid_num);
478 AST_STRING_FIELD(cid_name);
479 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
487 iax2_format capability;
488 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
489 int curauthreq; /*!< Current number of outstanding AUTHREQs */
490 struct ast_codec_pref prefs;
491 struct ast_acl_list *acl;
492 struct iax2_context *contexts;
493 struct ast_variable *vars;
494 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
498 AST_DECLARE_STRING_FIELDS(
499 AST_STRING_FIELD(name);
500 AST_STRING_FIELD(username);
501 AST_STRING_FIELD(description); /*!< Description of the peer */
502 AST_STRING_FIELD(secret);
503 AST_STRING_FIELD(dbsecret);
504 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
506 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
507 AST_STRING_FIELD(context); /*!< For transfers only */
508 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
509 AST_STRING_FIELD(mailbox); /*!< Mailbox */
510 AST_STRING_FIELD(mohinterpret);
511 AST_STRING_FIELD(mohsuggest);
512 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
513 /* Suggested caller id if registering */
514 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
515 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
516 AST_STRING_FIELD(zonetag); /*!< Time Zone */
517 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
519 struct ast_codec_pref prefs;
520 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
521 struct ast_sockaddr addr;
523 int sockfd; /*!< Socket to use for transmission */
528 /* Dynamic Registration fields */
529 struct sockaddr_in defaddr; /*!< Default address if there is one */
530 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
531 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
533 int expire; /*!< Schedule entry for expiry */
534 int expiry; /*!< How soon to expire */
535 iax2_format capability; /*!< Capability */
538 int callno; /*!< Call number of POKE request */
539 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
540 int lastms; /*!< How long last response took (in ms), or -1 for no response */
541 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
543 int pokefreqok; /*!< How often to check if the host is up */
544 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
545 int historicms; /*!< How long recent average responses took */
546 int smoothing; /*!< Sample over how many units to determine historic ms */
547 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
549 struct ast_event_sub *mwi_event_sub;
551 struct ast_acl_list *acl;
552 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
555 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
557 struct iax2_trunk_peer {
560 struct sockaddr_in addr;
561 struct timeval txtrunktime; /*!< Transmit trunktime */
562 struct timeval rxtrunktime; /*!< Receive trunktime */
563 struct timeval lasttxtime; /*!< Last transmitted trunktime */
564 struct timeval trunkact; /*!< Last trunk activity */
565 unsigned int lastsent; /*!< Last sent time */
566 /* Trunk data and length */
567 unsigned char *trunkdata;
568 unsigned int trunkdatalen;
569 unsigned int trunkdataalloc;
573 AST_LIST_ENTRY(iax2_trunk_peer) list;
576 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
578 struct iax_firmware {
579 AST_LIST_ENTRY(iax_firmware) list;
583 struct ast_iax2_firmware_header *fwh;
588 REG_STATE_UNREGISTERED = 0,
591 REG_STATE_REGISTERED,
597 enum iax_transfer_state {
602 TRANSFER_PASSTHROUGH,
606 TRANSFER_MPASSTHROUGH,
611 struct iax2_registry {
612 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
614 char secret[80]; /*!< Password or key name in []'s */
615 int expire; /*!< Sched ID of expiration */
616 int refresh; /*!< How often to refresh */
617 enum iax_reg_state regstate;
618 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
619 int callno; /*!< Associated call number if applicable */
620 struct sockaddr_in us; /*!< Who the server thinks we are */
621 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
622 AST_LIST_ENTRY(iax2_registry) entry;
625 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
627 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
628 #define MIN_RETRY_TIME 100
629 #define MAX_RETRY_TIME 10000
631 #define MAX_JITTER_BUFFER 50
632 #define MIN_JITTER_BUFFER 10
634 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
636 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
638 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
639 #define TS_GAP_FOR_JB_RESYNC 5000
641 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
642 #define MARK_IAX_SUBCLASS_TX 0x8000
644 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
645 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
646 static int iaxdynamicthreadcount = 0;
647 static int iaxdynamicthreadnum = 0;
648 static int iaxactivethreadcount = 0;
662 struct chan_iax2_pvt {
663 /*! Socket to send/receive on for this call */
665 /*! ast_callid bound to dialog */
666 struct ast_callid *callid;
667 /*! Last received voice format */
668 iax2_format voiceformat;
669 /*! Last received video format */
670 iax2_format videoformat;
671 /*! Last sent voice format */
672 iax2_format svoiceformat;
673 /*! Last sent video format */
674 iax2_format svideoformat;
675 /*! What we are capable of sending */
676 iax2_format capability;
677 /*! Last received timestamp */
679 /*! Last sent timestamp - never send the same timestamp twice in a single call */
680 unsigned int lastsent;
681 /*! Timestamp of the last video frame sent */
682 unsigned int lastvsent;
683 /*! Next outgoing timestamp if everything is good */
684 unsigned int nextpred;
685 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
686 int first_iax_message;
687 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
688 int last_iax_message;
689 /*! True if the last voice we transmitted was not silence/CNG */
690 unsigned int notsilenttx:1;
692 unsigned int pingtime;
693 /*! Max time for initial response */
696 struct sockaddr_in addr;
697 /*! Actual used codec preferences */
698 struct ast_codec_pref prefs;
699 /*! Requested codec preferences */
700 struct ast_codec_pref rprefs;
701 /*! Our call number */
702 unsigned short callno;
703 /*! Our callno_entry entry */
704 struct callno_entry *callno_entry;
706 unsigned short peercallno;
707 /*! Negotiated format, this is only used to remember what format was
708 chosen for an unauthenticated call so that the channel can get
709 created later using the right format */
710 iax2_format chosenformat;
711 /*! Peer selected format */
712 iax2_format peerformat;
713 /*! Peer capability */
714 iax2_format peercapability;
715 /*! timeval that we base our transmission on */
716 struct timeval offset;
717 /*! timeval that we base our delivery on */
718 struct timeval rxcore;
719 /*! The jitterbuffer */
721 /*! active jb read scheduler id */
725 /*! Error, as discovered by the manager */
727 /*! Owner if we have one */
728 struct ast_channel *owner;
729 /*! What's our state? */
730 struct ast_flags state;
731 /*! Expiry (optional) */
733 /*! Next outgoing sequence number */
734 unsigned char oseqno;
735 /*! Next sequence number they have not yet acknowledged */
736 unsigned char rseqno;
737 /*! Next incoming sequence number */
738 unsigned char iseqno;
739 /*! Last incoming sequence number we have acknowledged */
740 unsigned char aseqno;
742 AST_DECLARE_STRING_FIELDS(
744 AST_STRING_FIELD(peer);
745 /*! Default Context */
746 AST_STRING_FIELD(context);
747 /*! Caller ID if available */
748 AST_STRING_FIELD(cid_num);
749 AST_STRING_FIELD(cid_name);
750 /*! Hidden Caller ID (i.e. ANI) if appropriate */
751 AST_STRING_FIELD(ani);
753 AST_STRING_FIELD(dnid);
755 AST_STRING_FIELD(rdnis);
756 /*! Requested Extension */
757 AST_STRING_FIELD(exten);
758 /*! Expected Username */
759 AST_STRING_FIELD(username);
760 /*! Expected Secret */
761 AST_STRING_FIELD(secret);
763 AST_STRING_FIELD(challenge);
764 /*! Public keys permitted keys for incoming authentication */
765 AST_STRING_FIELD(inkeys);
766 /*! Private key for outgoing authentication */
767 AST_STRING_FIELD(outkey);
768 /*! Preferred language */
769 AST_STRING_FIELD(language);
770 /*! Hostname/peername for naming purposes */
771 AST_STRING_FIELD(host);
773 AST_STRING_FIELD(dproot);
774 AST_STRING_FIELD(accountcode);
775 AST_STRING_FIELD(mohinterpret);
776 AST_STRING_FIELD(mohsuggest);
777 /*! received OSP token */
778 AST_STRING_FIELD(osptoken);
779 /*! Default parkinglot */
780 AST_STRING_FIELD(parkinglot);
782 /*! AUTHREJ all AUTHREP frames */
784 /*! permitted authentication methods */
786 /*! permitted encryption methods */
788 /*! Encryption AES-128 Key */
789 ast_aes_encrypt_key ecx;
790 /*! Decryption AES-128 Key corresponding to ecx */
791 ast_aes_decrypt_key mydcx;
792 /*! Decryption AES-128 Key used to decrypt peer frames */
793 ast_aes_decrypt_key dcx;
794 /*! scheduler id associated with iax_key_rotate
795 * for encrypted calls*/
797 /*! 32 bytes of semi-random data */
798 unsigned char semirand[32];
799 /*! Associated registry */
800 struct iax2_registry *reg;
801 /*! Associated peer for poking */
802 struct iax2_peer *peerpoke;
807 /*! Transferring status */
808 enum iax_transfer_state transferring;
809 /*! Transfer identifier */
811 /*! Who we are IAX transferring to */
812 struct sockaddr_in transfer;
813 /*! What's the new call number for the transfer */
814 unsigned short transfercallno;
815 /*! Transfer encrypt AES-128 Key */
816 ast_aes_encrypt_key tdcx;
818 /*! Status of knowledge of peer ADSI capability */
821 /*! Who we are bridged to */
822 unsigned short bridgecallno;
824 int pingid; /*!< Transmit PING request */
825 int lagid; /*!< Retransmit lag request */
826 int autoid; /*!< Auto hangup for Dialplan requestor */
827 int authid; /*!< Authentication rejection ID */
828 int authfail; /*!< Reason to report failure */
829 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
834 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
835 /*! variables inherited from the user definition */
836 struct ast_variable *vars;
837 /*! variables transmitted in a NEW packet */
838 struct ast_variable *iaxvars;
839 /*! last received remote rr */
840 struct iax_rr remote_rr;
841 /*! Current base time: (just for stats) */
843 /*! Dropped frame count: (just for stats) */
845 /*! received frame count: (just for stats) */
847 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
848 unsigned char calltoken_ie_len;
849 /*! hold all signaling frames from the pbx thread until we have a destination callno */
851 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
852 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
855 struct signaling_queue_entry {
857 AST_LIST_ENTRY(signaling_queue_entry) next;
860 /*! table of available call numbers */
861 static struct ao2_container *callno_pool;
863 /*! table of available trunk call numbers */
864 static struct ao2_container *callno_pool_trunk;
866 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
869 * \brief a list of frames that may need to be retransmitted
871 * \note The contents of this list do not need to be explicitly destroyed
872 * on module unload. This is because all active calls are destroyed, and
873 * all frames in this queue will get destroyed as a part of that process.
875 * \note Contents protected by the iaxsl[] locks
877 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
879 static struct ast_taskprocessor *transmit_processor;
881 static int randomcalltokendata;
883 static const time_t MAX_CALLTOKEN_DELAY = 10;
886 * This module will get much higher performance when doing a lot of
887 * user and peer lookups if the number of buckets is increased from 1.
888 * However, to maintain old behavior for Asterisk 1.4, these are set to
889 * 1 by default. When using multiple buckets, search order through these
890 * containers is considered random, so you will not be able to depend on
891 * the order the entires are specified in iax.conf for matching order. */
893 #define MAX_PEER_BUCKETS 17
895 #define MAX_PEER_BUCKETS 563
897 static struct ao2_container *peers;
899 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
900 static struct ao2_container *users;
902 /*! Table containing peercnt objects for every ip address consuming a callno */
903 static struct ao2_container *peercnts;
905 /*! Table containing custom callno limit rules for a range of ip addresses. */
906 static struct ao2_container *callno_limits;
908 /*! Table containing ip addresses not requiring calltoken validation */
909 static struct ao2_container *calltoken_ignores;
911 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
913 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
915 static uint16_t global_maxcallno;
917 /*! Total num of call numbers allowed to be allocated without calltoken validation */
918 static uint16_t global_maxcallno_nonval;
920 static uint16_t total_nonval_callno_used = 0;
922 /*! peer connection private, keeps track of all the call numbers
923 * consumed by a single ip address */
925 /*! ip address consuming call numbers */
927 /*! Number of call numbers currently used by this ip address */
929 /*! Max call numbers allowed for this ip address */
931 /*! Specifies whether limit is set by a registration or not, if so normal
932 * limit setting rules do not apply to this address. */
936 /*! used by both callno_limits and calltoken_ignores containers */
938 /*! ip address range for custom callno limit rule */
940 /*! callno limit for this ip address range, only used in callno_limits container */
942 /*! delete me marker for reloads */
946 struct callno_entry {
947 /*! callno used for this entry */
949 /*! was this callno calltoken validated or not */
950 unsigned char validated;
953 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
956 /*! Extension exists */
957 CACHE_FLAG_EXISTS = (1 << 0),
958 /*! Extension is nonexistent */
959 CACHE_FLAG_NONEXISTENT = (1 << 1),
960 /*! Extension can exist */
961 CACHE_FLAG_CANEXIST = (1 << 2),
962 /*! Waiting to hear back response */
963 CACHE_FLAG_PENDING = (1 << 3),
965 CACHE_FLAG_TIMEOUT = (1 << 4),
966 /*! Request transmitted */
967 CACHE_FLAG_TRANSMITTED = (1 << 5),
969 CACHE_FLAG_UNKNOWN = (1 << 6),
971 CACHE_FLAG_MATCHMORE = (1 << 7),
974 struct iax2_dpcache {
975 char peercontext[AST_MAX_CONTEXT];
976 char exten[AST_MAX_EXTENSION];
978 struct timeval expiry;
980 unsigned short callno;
982 AST_LIST_ENTRY(iax2_dpcache) cache_list;
983 AST_LIST_ENTRY(iax2_dpcache) peer_list;
986 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
988 static void reg_source_db(struct iax2_peer *p);
989 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
990 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
992 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
993 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
994 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
996 enum iax2_thread_iostate {
999 IAX_IOSTATE_PROCESSING,
1000 IAX_IOSTATE_SCHEDREADY,
1003 enum iax2_thread_type {
1004 IAX_THREAD_TYPE_POOL,
1005 IAX_THREAD_TYPE_DYNAMIC,
1008 struct iax2_pkt_buf {
1009 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1011 unsigned char buf[1];
1014 struct iax2_thread {
1015 AST_LIST_ENTRY(iax2_thread) list;
1016 enum iax2_thread_type type;
1017 enum iax2_thread_iostate iostate;
1018 #ifdef SCHED_MULTITHREADED
1019 void (*schedfunc)(const void *);
1020 const void *scheddata;
1022 #ifdef DEBUG_SCHED_MULTITHREAD
1028 struct sockaddr_in iosin;
1029 unsigned char readbuf[4096];
1037 ast_mutex_t init_lock;
1038 ast_cond_t init_cond;
1039 /*! if this thread is processing a full frame,
1040 some information about that frame will be stored
1041 here, so we can avoid dispatching any more full
1042 frames for that callno to other threads */
1044 unsigned short callno;
1045 struct sockaddr_in sin;
1049 /*! Queued up full frames for processing. If more full frames arrive for
1050 * a call which this thread is already processing a full frame for, they
1051 * are queued up here. */
1052 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1057 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1058 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1059 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1061 static void *iax2_process_thread(void *data);
1062 static void iax2_destroy(int callno);
1064 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1066 ast_mutex_lock(lock);
1067 ast_cond_signal(cond);
1068 ast_mutex_unlock(lock);
1072 * \brief an array of iax2 pvt structures
1074 * The container for active chan_iax2_pvt structures is implemented as an
1075 * array for extremely quick direct access to the correct pvt structure
1076 * based on the local call number. The local call number is used as the
1077 * index into the array where the associated pvt structure is stored.
1079 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1081 static struct ast_callid *iax_pvt_callid_get(int callno)
1083 if (iaxs[callno]->callid) {
1084 return ast_callid_ref(iaxs[callno]->callid);
1089 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1091 if (iaxs[callno]->callid) {
1092 ast_callid_unref(iaxs[callno]->callid);
1094 ast_callid_ref(callid);
1095 iaxs[callno]->callid = callid;
1098 static void iax_pvt_callid_new(int callno)
1100 struct ast_callid *callid = ast_create_callid();
1101 char buffer[AST_CALLID_BUFFER_LENGTH];
1102 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1103 ast_log(LOG_NOTICE, "iax_pvt_callid_new created and set %s\n", buffer);
1104 iax_pvt_callid_set(callno, callid);
1105 ast_callid_unref(callid);
1109 * \brief Another container of iax2_pvt structures
1111 * Active IAX2 pvt structs are also stored in this container, if they are a part
1112 * of an active call where we know the remote side's call number. The reason
1113 * for this is that incoming media frames do not contain our call number. So,
1114 * instead of having to iterate the entire iaxs array, we use this container to
1115 * look up calls where the remote side is using a given call number.
1117 static struct ao2_container *iax_peercallno_pvts;
1120 * \brief chan_iax2_pvt structure locks
1122 * These locks are used when accessing a pvt structure in the iaxs array.
1123 * The index used here is the same as used in the iaxs array. It is the
1124 * local call number for the associated pvt struct.
1126 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1129 * * \brief Another container of iax2_pvt structures
1131 * Active IAX2 pvt stucts used during transfering a call are stored here.
1133 static struct ao2_container *iax_transfercallno_pvts;
1135 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1136 but keeps the division between trunked and non-trunked better. */
1137 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1139 /* Debug routines... */
1140 static struct sockaddr_in debugaddr;
1142 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1145 (sin && debugaddr.sin_addr.s_addr &&
1146 (!ntohs(debugaddr.sin_port) ||
1147 debugaddr.sin_port == sin->sin_port) &&
1148 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1150 iax_showframe(f, fhi, rx, sin, datalen);
1153 iax_showframe(f, fhi, rx, sin, datalen);
1159 static void iax_debug_output(const char *data)
1162 ast_verbose("%s", data);
1165 static void iax_error_output(const char *data)
1167 ast_log(LOG_WARNING, "%s", data);
1170 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1175 va_start(args, fmt);
1176 vsnprintf(buf, sizeof(buf), fmt, args);
1179 ast_log(LOG_ERROR, "%s", buf);
1182 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1187 va_start(args, fmt);
1188 vsnprintf(buf, sizeof(buf), fmt, args);
1191 ast_log(LOG_WARNING, "%s", buf);
1194 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1199 va_start(args, fmt);
1200 vsnprintf(buf, sizeof(buf), fmt, args);
1203 ast_verbose("%s", buf);
1206 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);
1207 static int expire_registry(const void *data);
1208 static int iax2_answer(struct ast_channel *c);
1209 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1210 static int iax2_devicestate(const char *data);
1211 static int iax2_digit_begin(struct ast_channel *c, char digit);
1212 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1213 static int iax2_do_register(struct iax2_registry *reg);
1214 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1215 static int iax2_hangup(struct ast_channel *c);
1216 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1217 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1218 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1219 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1220 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1221 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1222 static int iax2_sendtext(struct ast_channel *c, const char *text);
1223 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1224 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1225 static int iax2_transfer(struct ast_channel *c, const char *dest);
1226 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1227 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1229 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1230 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1231 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1232 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1233 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1234 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1235 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1236 static struct ast_frame *iax2_read(struct ast_channel *c);
1237 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1238 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1239 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1240 static void *iax2_dup_variable_datastore(void *);
1241 static void prune_peers(void);
1242 static void prune_users(void);
1243 static void iax2_free_variable_datastore(void *);
1245 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1246 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1247 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1248 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1249 static void build_rand_pad(unsigned char *buf, ssize_t len);
1250 static struct callno_entry *get_unused_callno(int trunk, int validated);
1251 static int replace_callno(const void *obj);
1252 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1253 static void network_change_event_cb(const struct ast_event *, void *);
1254 static void acl_change_event_cb(const struct ast_event *, void *);
1256 static struct ast_channel_tech iax2_tech = {
1258 .description = tdesc,
1259 .properties = AST_CHAN_TP_WANTSJITTER,
1260 .requester = iax2_request,
1261 .devicestate = iax2_devicestate,
1262 .send_digit_begin = iax2_digit_begin,
1263 .send_digit_end = iax2_digit_end,
1264 .send_text = iax2_sendtext,
1265 .send_image = iax2_sendimage,
1266 .send_html = iax2_sendhtml,
1268 .hangup = iax2_hangup,
1269 .answer = iax2_answer,
1271 .write = iax2_write,
1272 .write_video = iax2_write,
1273 .indicate = iax2_indicate,
1274 .setoption = iax2_setoption,
1275 .queryoption = iax2_queryoption,
1276 .bridge = iax2_bridge,
1277 .transfer = iax2_transfer,
1278 .fixup = iax2_fixup,
1279 .func_channel_read = acf_channel_read,
1284 * \brief Obtain the owner channel lock if the owner exists.
1286 * \param callno IAX2 call id.
1288 * \note Assumes the iaxsl[callno] lock is already obtained.
1291 * IMPORTANT NOTE!!! Any time this function is used, even if
1292 * iaxs[callno] was valid before calling it, it may no longer be
1293 * valid after calling it. This function may unlock and lock
1294 * the mutex associated with this callno, meaning that another
1295 * thread may grab it and destroy the call.
1299 static void iax2_lock_owner(int callno)
1302 if (!iaxs[callno] || !iaxs[callno]->owner) {
1303 /* There is no owner lock to get. */
1306 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1307 /* We got the lock */
1310 /* Avoid deadlock by pausing and trying again */
1311 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1315 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1317 /* The MWI subscriptions exist just so the core knows we care about those
1318 * mailboxes. However, we just grab the events out of the cache when it
1319 * is time to send MWI, since it is only sent with a REGACK. */
1322 static void network_change_event_subscribe(void)
1324 if (!network_change_event_subscription) {
1325 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1326 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1330 static void network_change_event_unsubscribe(void)
1332 if (network_change_event_subscription) {
1333 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1337 static void acl_change_event_subscribe(void)
1339 if (!acl_change_event_subscription) {
1340 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1341 acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
1345 static void acl_change_event_unsubscribe(void)
1347 if (acl_change_event_subscription) {
1348 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1352 static int network_change_event_sched_cb(const void *data)
1354 struct iax2_registry *reg;
1355 network_change_event_sched_id = -1;
1356 AST_LIST_LOCK(®istrations);
1357 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1358 iax2_do_register(reg);
1360 AST_LIST_UNLOCK(®istrations);
1365 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1367 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1368 if (network_change_event_sched_id == -1) {
1369 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1374 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
1376 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1381 /*! \brief Send manager event at call setup to link between Asterisk channel name
1382 and IAX2 call identifiers */
1383 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1385 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1386 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1387 pvt->owner ? ast_channel_name(pvt->owner) : "",
1388 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1391 static const struct ast_datastore_info iax2_variable_datastore_info = {
1392 .type = "IAX2_VARIABLE",
1393 .duplicate = iax2_dup_variable_datastore,
1394 .destroy = iax2_free_variable_datastore,
1397 static void *iax2_dup_variable_datastore(void *old)
1399 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1400 struct ast_var_t *oldvar, *newvar;
1402 newlist = ast_calloc(sizeof(*newlist), 1);
1404 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1408 AST_LIST_HEAD_INIT(newlist);
1409 AST_LIST_LOCK(oldlist);
1410 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1411 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1413 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1415 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1417 AST_LIST_UNLOCK(oldlist);
1421 static void iax2_free_variable_datastore(void *old)
1423 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1424 struct ast_var_t *oldvar;
1426 AST_LIST_LOCK(oldlist);
1427 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1430 AST_LIST_UNLOCK(oldlist);
1431 AST_LIST_HEAD_DESTROY(oldlist);
1436 /* WARNING: insert_idle_thread should only ever be called within the
1437 * context of an iax2_process_thread() thread.
1439 static void insert_idle_thread(struct iax2_thread *thread)
1441 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1442 AST_LIST_LOCK(&dynamic_list);
1443 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1444 AST_LIST_UNLOCK(&dynamic_list);
1446 AST_LIST_LOCK(&idle_list);
1447 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1448 AST_LIST_UNLOCK(&idle_list);
1454 static struct iax2_thread *find_idle_thread(void)
1456 struct iax2_thread *thread = NULL;
1458 /* Pop the head of the idle list off */
1459 AST_LIST_LOCK(&idle_list);
1460 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1461 AST_LIST_UNLOCK(&idle_list);
1463 /* If we popped a thread off the idle list, just return it */
1465 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1469 /* Pop the head of the dynamic list off */
1470 AST_LIST_LOCK(&dynamic_list);
1471 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1472 AST_LIST_UNLOCK(&dynamic_list);
1474 /* If we popped a thread off the dynamic list, just return it */
1476 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1480 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1481 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1484 /* Set default values */
1485 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1486 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1487 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1489 /* Initialize lock and condition */
1490 ast_mutex_init(&thread->lock);
1491 ast_cond_init(&thread->cond, NULL);
1492 ast_mutex_init(&thread->init_lock);
1493 ast_cond_init(&thread->init_cond, NULL);
1494 ast_mutex_lock(&thread->init_lock);
1496 /* Create thread and send it on it's way */
1497 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1498 ast_cond_destroy(&thread->cond);
1499 ast_mutex_destroy(&thread->lock);
1500 ast_mutex_unlock(&thread->init_lock);
1501 ast_cond_destroy(&thread->init_cond);
1502 ast_mutex_destroy(&thread->init_lock);
1507 /* this thread is not processing a full frame (since it is idle),
1508 so ensure that the field for the full frame call number is empty */
1509 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1511 /* Wait for the thread to be ready before returning it to the caller */
1512 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1514 /* Done with init_lock */
1515 ast_mutex_unlock(&thread->init_lock);
1520 #ifdef SCHED_MULTITHREADED
1521 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1523 struct iax2_thread *thread = NULL;
1524 static time_t lasterror;
1527 thread = find_idle_thread();
1529 if (thread != NULL) {
1530 thread->schedfunc = func;
1531 thread->scheddata = data;
1532 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1533 #ifdef DEBUG_SCHED_MULTITHREAD
1534 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1536 signal_condition(&thread->lock, &thread->cond);
1541 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1546 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1549 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1550 ast_sched_cb callback, const void *data)
1552 return ast_sched_replace(id, con, when, callback, data);
1555 static int iax2_sched_add(struct ast_sched_context *con, int when,
1556 ast_sched_cb callback, const void *data)
1558 return ast_sched_add(con, when, callback, data);
1561 static int send_ping(const void *data);
1563 static void __send_ping(const void *data)
1565 int callno = (long) data;
1567 ast_mutex_lock(&iaxsl[callno]);
1570 if (iaxs[callno]->peercallno) {
1571 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1572 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1573 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1577 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1580 ast_mutex_unlock(&iaxsl[callno]);
1583 static int send_ping(const void *data)
1585 int callno = (long) data;
1586 ast_mutex_lock(&iaxsl[callno]);
1587 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1588 iaxs[callno]->pingid = -1;
1590 ast_mutex_unlock(&iaxsl[callno]);
1592 #ifdef SCHED_MULTITHREADED
1593 if (schedule_action(__send_ping, data))
1600 static void encmethods_to_str(int e, struct ast_str *buf)
1602 ast_str_set(&buf, 0, "(");
1603 if (e & IAX_ENCRYPT_AES128) {
1604 ast_str_append(&buf, 0, "aes128");
1606 if (e & IAX_ENCRYPT_KEYROTATE) {
1607 ast_str_append(&buf, 0, ",keyrotate");
1609 if (ast_str_strlen(buf) > 1) {
1610 ast_str_append(&buf, 0, ")");
1612 ast_str_set(&buf, 0, "No");
1616 static int get_encrypt_methods(const char *s)
1619 if (!strcasecmp(s, "aes128"))
1620 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1621 else if (ast_true(s))
1622 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1628 static int send_lagrq(const void *data);
1630 static void __send_lagrq(const void *data)
1632 int callno = (long) data;
1634 ast_mutex_lock(&iaxsl[callno]);
1637 if (iaxs[callno]->peercallno) {
1638 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1639 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1640 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1644 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1647 ast_mutex_unlock(&iaxsl[callno]);
1650 static int send_lagrq(const void *data)
1652 int callno = (long) data;
1653 ast_mutex_lock(&iaxsl[callno]);
1654 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1655 iaxs[callno]->lagid = -1;
1657 ast_mutex_unlock(&iaxsl[callno]);
1659 #ifdef SCHED_MULTITHREADED
1660 if (schedule_action(__send_lagrq, data))
1666 static unsigned char compress_subclass(iax2_format subclass)
1670 /* If it's 64 or smaller, just return it */
1671 if (subclass < IAX_FLAG_SC_LOG)
1673 /* Otherwise find its power */
1674 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1675 if (subclass & (1LL << x)) {
1677 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1683 return power | IAX_FLAG_SC_LOG;
1686 static iax2_format uncompress_subclass(unsigned char csub)
1688 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1689 if (csub & IAX_FLAG_SC_LOG) {
1690 /* special case for 'compressed' -1 */
1694 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1700 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1702 struct ast_format_cap *cap;
1703 struct ast_format tmpfmt;
1704 iax2_format format = 0;
1705 if ((cap = ast_format_cap_alloc_nolock())) {
1706 ast_format_clear(&tmpfmt);
1707 ast_format_cap_from_old_bitfield(cap, formats);
1708 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1709 format = ast_format_to_old_bitfield(&tmpfmt);
1710 cap = ast_format_cap_destroy(cap);
1716 static iax2_format iax2_best_codec(iax2_format formats)
1718 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1719 struct ast_format tmpfmt;
1724 ast_format_clear(&tmpfmt);
1725 ast_format_cap_from_old_bitfield(cap, formats);
1726 ast_best_codec(cap, &tmpfmt);
1727 cap = ast_format_cap_destroy(cap);
1728 return ast_format_to_old_bitfield(&tmpfmt);
1731 const char *iax2_getformatname(iax2_format format)
1733 struct ast_format tmpfmt;
1734 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1738 return ast_getformatname(&tmpfmt);
1741 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1743 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1748 ast_format_cap_from_old_bitfield(cap, format);
1749 ast_getformatname_multiple(codec_buf, len, cap);
1750 cap = ast_format_cap_destroy(cap);
1755 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1758 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1763 ast_format_cap_from_old_bitfield(cap, *formats);
1764 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1765 *formats = ast_format_cap_to_old_bitfield(cap);
1766 cap = ast_format_cap_destroy(cap);
1771 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1774 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1778 ast_format_cap_from_old_bitfield(cap, formats);
1779 res = ast_data_add_codecs(root, node_name, cap);
1780 cap = ast_format_cap_destroy(cap);
1785 * \note The only member of the peer passed here guaranteed to be set is the name field
1787 static int peer_hash_cb(const void *obj, const int flags)
1789 const struct iax2_peer *peer = obj;
1790 const char *name = obj;
1792 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1796 * \note The only member of the peer passed here guaranteed to be set is the name field
1798 static int peer_cmp_cb(void *obj, void *arg, int flags)
1800 struct iax2_peer *peer = obj, *peer2 = arg;
1801 const char *name = arg;
1803 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1804 CMP_MATCH | CMP_STOP : 0;
1808 * \note The only member of the user passed here guaranteed to be set is the name field
1810 static int user_hash_cb(const void *obj, const int flags)
1812 const struct iax2_user *user = obj;
1813 const char *name = obj;
1815 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1819 * \note The only member of the user passed here guaranteed to be set is the name field
1821 static int user_cmp_cb(void *obj, void *arg, int flags)
1823 struct iax2_user *user = obj, *user2 = arg;
1824 const char *name = arg;
1826 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1827 CMP_MATCH | CMP_STOP : 0;
1831 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1832 * so do not call it with a pvt lock held.
1834 static struct iax2_peer *find_peer(const char *name, int realtime)
1836 struct iax2_peer *peer = NULL;
1838 peer = ao2_find(peers, name, OBJ_KEY);
1840 /* Now go for realtime if applicable */
1841 if(!peer && realtime)
1842 peer = realtime_peer(name, NULL);
1847 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1853 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1859 static struct iax2_user *find_user(const char *name)
1861 return ao2_find(users, name, OBJ_KEY);
1863 static inline struct iax2_user *user_ref(struct iax2_user *user)
1869 static inline struct iax2_user *user_unref(struct iax2_user *user)
1875 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1877 struct iax2_peer *peer = NULL;
1879 struct ao2_iterator i;
1881 i = ao2_iterator_init(peers, 0);
1882 while ((peer = ao2_iterator_next(&i))) {
1883 struct sockaddr_in peer_addr;
1885 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1887 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1888 (peer_addr.sin_port == sin.sin_port)) {
1889 ast_copy_string(host, peer->name, len);
1896 ao2_iterator_destroy(&i);
1899 peer = realtime_peer(NULL, &sin);
1901 ast_copy_string(host, peer->name, len);
1910 /*!\note Assumes the lock on the pvt is already held, when
1911 * iax2_destroy_helper() is called. */
1912 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1914 /* Decrement AUTHREQ count if needed */
1915 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1916 struct iax2_user *user;
1918 user = ao2_find(users, pvt->username, OBJ_KEY);
1920 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1924 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1926 /* No more pings or lagrq's */
1927 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1928 pvt->pingid = DONT_RESCHEDULE;
1929 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1930 pvt->lagid = DONT_RESCHEDULE;
1931 AST_SCHED_DEL(sched, pvt->autoid);
1932 AST_SCHED_DEL(sched, pvt->authid);
1933 AST_SCHED_DEL(sched, pvt->initid);
1934 AST_SCHED_DEL(sched, pvt->jbid);
1935 AST_SCHED_DEL(sched, pvt->keyrotateid);
1938 static void iax2_frame_free(struct iax_frame *fr)
1940 AST_SCHED_DEL(sched, fr->retrans);
1944 static int scheduled_destroy(const void *vid)
1946 unsigned short callno = PTR_TO_CALLNO(vid);
1947 ast_mutex_lock(&iaxsl[callno]);
1949 ast_debug(1, "Really destroying %d now...\n", callno);
1950 iax2_destroy(callno);
1952 ast_mutex_unlock(&iaxsl[callno]);
1956 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1959 ast_free(s->f.data.ptr);
1964 /*! \brief This function must be called once we are sure the other side has
1965 * given us a call number. All signaling is held here until that point. */
1966 static void send_signaling(struct chan_iax2_pvt *pvt)
1968 struct signaling_queue_entry *s = NULL;
1970 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1971 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1972 free_signaling_queue_entry(s);
1974 pvt->hold_signaling = 0;
1977 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1978 * we have received a destination call number. */
1979 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1981 struct signaling_queue_entry *qe;
1983 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1984 return 1; /* do not queue this frame */
1985 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1986 return -1; /* out of memory */
1989 /* copy ast_frame into our queue entry */
1991 if (qe->f.datalen) {
1992 /* if there is data in this frame copy it over as well */
1993 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1994 free_signaling_queue_entry(qe);
1997 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
1999 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2004 static void pvt_destructor(void *obj)
2006 struct chan_iax2_pvt *pvt = obj;
2007 struct iax_frame *cur = NULL;
2008 struct signaling_queue_entry *s = NULL;
2010 ast_mutex_lock(&iaxsl[pvt->callno]);
2012 iax2_destroy_helper(pvt);
2014 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2015 pvt->callno_entry = NULL;
2018 ast_set_flag64(pvt, IAX_ALREADYGONE);
2020 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2021 /* Cancel any pending transmissions */
2025 ast_mutex_unlock(&iaxsl[pvt->callno]);
2027 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2028 free_signaling_queue_entry(s);
2032 pvt->reg->callno = 0;
2038 ast_variables_destroy(pvt->vars);
2042 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2043 iax2_frame_free(frame.data);
2046 jb_destroy(pvt->jb);
2047 ast_string_field_free_memory(pvt);
2051 ast_callid_unref(pvt->callid);
2056 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2058 struct chan_iax2_pvt *tmp;
2061 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2065 if (ast_string_field_init(tmp, 32)) {
2077 tmp->keyrotateid = -1;
2079 ast_string_field_set(tmp,exten, "s");
2080 ast_string_field_set(tmp,host, host);
2084 jbconf.max_jitterbuf = maxjitterbuffer;
2085 jbconf.resync_threshold = resyncthreshold;
2086 jbconf.max_contig_interp = maxjitterinterps;
2087 jbconf.target_extra = jittertargetextra;
2088 jb_setconf(tmp->jb,&jbconf);
2090 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2092 tmp->hold_signaling = 1;
2093 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2098 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2100 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2102 size_t afdatalen = new->afdatalen;
2103 memcpy(new, fr, sizeof(*new));
2104 iax_frame_wrap(new, &fr->af);
2105 new->afdatalen = afdatalen;
2108 new->direction = DIRECTION_INGRESS;
2113 /* keep these defined in this order. They are used in find_callno to
2114 * determine whether or not a new call number should be allowed. */
2116 /* do not allow a new call number, only search ones in use for match */
2118 /* search for match first, then allow a new one to be allocated */
2120 /* do not search for match, force a new call number */
2122 /* do not search for match, force a new call number. Signifies call number
2123 * has been calltoken validated */
2124 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2127 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2129 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2130 (cur->addr.sin_port == sin->sin_port)) {
2131 /* This is the main host */
2132 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2133 (check_dcallno ? dcallno == cur->callno : 1) ) {
2134 /* That's us. Be sure we keep track of the peer call number */
2138 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2139 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2140 /* We're transferring */
2141 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2147 static int make_trunk(unsigned short callno, int locked)
2151 struct callno_entry *callno_entry;
2152 if (iaxs[callno]->oseqno) {
2153 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2156 if (callno & TRUNK_CALL_START) {
2157 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2161 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2162 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2166 x = callno_entry->callno;
2167 ast_mutex_lock(&iaxsl[x]);
2170 * \note We delete these before switching the slot, because if
2171 * they fire in the meantime, they will generate a warning.
2173 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2174 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2175 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2176 iaxs[x] = iaxs[callno];
2177 iaxs[x]->callno = x;
2179 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2180 * before assigning the new one */
2181 if (iaxs[x]->callno_entry) {
2182 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2184 iaxs[x]->callno_entry = callno_entry;
2186 iaxs[callno] = NULL;
2187 /* Update the two timers that should have been started */
2188 iaxs[x]->pingid = iax2_sched_add(sched,
2189 ping_time * 1000, send_ping, (void *)(long)x);
2190 iaxs[x]->lagid = iax2_sched_add(sched,
2191 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2194 ast_mutex_unlock(&iaxsl[callno]);
2197 ast_mutex_unlock(&iaxsl[x]);
2199 /* We moved this call from a non-trunked to a trunked call */
2200 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2205 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2207 if (!pvt->transfercallno) {
2208 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2212 ao2_link(iax_transfercallno_pvts, pvt);
2215 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2217 if (!pvt->transfercallno) {
2218 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2222 ao2_unlink(iax_transfercallno_pvts, pvt);
2224 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2226 if (!pvt->peercallno) {
2227 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2231 ao2_link(iax_peercallno_pvts, pvt);
2234 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2236 if (!pvt->peercallno) {
2237 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2241 ao2_unlink(iax_peercallno_pvts, pvt);
2244 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2246 struct addr_range *lim = obj;
2251 static int addr_range_hash_cb(const void *obj, const int flags)
2253 const struct addr_range *lim = obj;
2254 struct sockaddr_in sin;
2255 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2256 return abs((int) sin.sin_addr.s_addr);
2259 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2261 struct addr_range *lim1 = obj, *lim2 = arg;
2262 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2263 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2264 CMP_MATCH | CMP_STOP : 0;
2267 static int peercnt_hash_cb(const void *obj, const int flags)
2269 const struct peercnt *peercnt = obj;
2270 return abs((int) peercnt->addr);
2273 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2275 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2276 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2279 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2281 struct addr_range *addr_range = obj;
2282 struct sockaddr_in *sin = arg;
2283 struct sockaddr_in ha_netmask_sin;
2284 struct sockaddr_in ha_addr_sin;
2286 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2287 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2289 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2290 return CMP_MATCH | CMP_STOP;
2298 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2300 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2302 struct addr_range *addr_range;
2303 struct iax2_peer *peer = NULL;
2304 struct iax2_user *user = NULL;
2305 /* if no username is given, check for guest accounts */
2306 const char *find = S_OR(name, "guest");
2307 int res = 1; /* required by default */
2309 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2310 /* There are only two cases in which calltoken validation is not required.
2311 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2312 * the peer definition has not set the requirecalltoken option.
2313 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2316 /* ----- Case 1 ----- */
2317 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2318 ao2_ref(addr_range, -1);
2322 /* ----- Case 2 ----- */
2323 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2324 calltoken_required = user->calltoken_required;
2325 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2326 calltoken_required = user->calltoken_required;
2327 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2328 calltoken_required = peer->calltoken_required;
2329 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2330 calltoken_required = peer->calltoken_required;
2340 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);
2341 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2342 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2352 * \brief set peercnt callno limit.
2355 * First looks in custom definitions. If not found, global limit
2356 * is used. Entries marked as reg already have
2357 * a custom limit set by a registration and are not modified.
2359 static void set_peercnt_limit(struct peercnt *peercnt)
2361 uint16_t limit = global_maxcallno;
2362 struct addr_range *addr_range;
2363 struct sockaddr_in sin = {
2364 .sin_addr.s_addr = peercnt->addr,
2368 if (peercnt->reg && peercnt->limit) {
2369 return; /* this peercnt has a custom limit set by a registration */
2372 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2373 limit = addr_range->limit;
2374 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2375 ao2_ref(addr_range, -1);
2378 peercnt->limit = limit;
2383 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2385 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2387 struct peercnt *peercnt = obj;
2389 set_peercnt_limit(peercnt);
2390 ast_debug(1, "Reset limits for peercnts table\n");
2397 * \brief returns match if delme is set.
2399 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2401 struct addr_range *addr_range = obj;
2403 return addr_range->delme ? CMP_MATCH : 0;
2408 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2410 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2412 /* this function turns off and on custom callno limits set by peer registration */
2413 struct peercnt *peercnt;
2414 struct peercnt tmp = {
2417 struct sockaddr_in sin;
2419 ast_sockaddr_to_sin(sockaddr, &sin);
2421 tmp.addr = sin.sin_addr.s_addr;
2423 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2426 peercnt->limit = limit;
2428 set_peercnt_limit(peercnt);
2430 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2431 ao2_ref(peercnt, -1); /* decrement ref from find */
2437 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2439 * \details First searches for the address in the peercnts table. If found
2440 * the current count is incremented. If not found a new peercnt is allocated
2441 * and linked into the peercnts table with a call number count of 1.
2443 static int peercnt_add(struct sockaddr_in *sin)
2445 struct peercnt *peercnt;
2446 unsigned long addr = sin->sin_addr.s_addr;
2448 struct peercnt tmp = {
2452 /* Reasoning for peercnts container lock: Two identical ip addresses
2453 * could be added by different threads at the "same time". Without the container
2454 * lock, both threads could alloc space for the same object and attempt
2455 * to link to table. With the lock, one would create the object and link
2456 * to table while the other would find the already created peercnt object
2457 * rather than creating a new one. */
2459 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2461 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2463 /* create and set defaults */
2464 peercnt->addr = addr;
2465 set_peercnt_limit(peercnt);
2466 /* guarantees it does not go away after unlocking table
2467 * ao2_find automatically adds this */
2468 ao2_link(peercnts, peercnt);
2470 ao2_unlock(peercnts);
2474 /* check to see if the address has hit its callno limit. If not increment cur. */
2475 if (peercnt->limit > peercnt->cur) {
2477 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2478 } else { /* max num call numbers for this peer has been reached! */
2479 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2483 /* clean up locks and ref count */
2484 ao2_unlock(peercnt);
2485 ao2_unlock(peercnts);
2486 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2493 * \brief decrements a peercnts table entry
2495 static void peercnt_remove(struct peercnt *peercnt)
2497 struct sockaddr_in sin = {
2498 .sin_addr.s_addr = peercnt->addr,
2502 * Container locked here since peercnt may be unlinked from
2503 * list. If left unlocked, peercnt_add could try and grab this
2504 * entry from the table and modify it at the "same time" this
2505 * thread attemps to unlink it.
2509 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2510 /* if this was the last connection from the peer remove it from table */
2511 if (peercnt->cur == 0) {
2512 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2514 ao2_unlock(peercnts);
2519 * \brief called by scheduler to decrement object
2521 static int peercnt_remove_cb(const void *obj)
2523 struct peercnt *peercnt = (struct peercnt *) obj;
2525 peercnt_remove(peercnt);
2526 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2533 * \brief decrements peercnts connection count, finds by addr
2535 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2537 struct peercnt *peercnt;
2538 struct peercnt tmp = {
2539 .addr = sin->sin_addr.s_addr,
2542 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2543 peercnt_remove(peercnt);
2544 ao2_ref(peercnt, -1); /* decrement ref from find */
2551 * \brief Create callno_limit entry based on configuration
2553 static void build_callno_limits(struct ast_variable *v)
2555 struct addr_range *addr_range = NULL;
2556 struct addr_range tmp;
2562 for (; v; v = v->next) {
2566 ha = ast_append_ha("permit", v->name, NULL, &error);
2568 /* check for valid config information */
2570 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2572 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2573 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2578 ast_copy_ha(ha, &tmp.ha);
2579 /* find or create the addr_range */
2580 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2581 ao2_lock(addr_range);
2583 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2585 return; /* out of memory */
2588 /* copy over config data into addr_range object */
2589 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2590 ast_free_ha(ha); /* cleanup the tmp ha */
2591 addr_range->limit = limit;
2592 addr_range->delme = 0;
2596 ao2_unlock(addr_range);
2598 ao2_link(callno_limits, addr_range);
2600 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2606 * \brief Create calltoken_ignores entry based on configuration
2608 static int add_calltoken_ignore(const char *addr)
2610 struct addr_range tmp;
2611 struct addr_range *addr_range = NULL;
2612 struct ast_ha *ha = NULL;
2615 if (ast_strlen_zero(addr)) {
2616 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2620 ha = ast_append_ha("permit", addr, NULL, &error);
2622 /* check for valid config information */
2624 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2628 ast_copy_ha(ha, &tmp.ha);
2629 /* find or create the addr_range */
2630 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2631 ao2_lock(addr_range);
2632 addr_range->delme = 0;
2633 ao2_unlock(addr_range);
2634 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2635 /* copy over config data into addr_range object */
2636 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2637 ao2_link(calltoken_ignores, addr_range);
2644 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2649 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2651 struct ao2_iterator i;
2652 struct peercnt *peercnt;
2653 struct sockaddr_in sin;
2658 e->command = "iax2 show callnumber usage";
2660 "Usage: iax2 show callnumber usage [IP address]\n"
2661 " Shows current IP addresses which are consuming iax2 call numbers\n";
2666 if (a->argc < 4 || a->argc > 5)
2667 return CLI_SHOWUSAGE;
2670 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2673 i = ao2_iterator_init(peercnts, 0);
2674 while ((peercnt = ao2_iterator_next(&i))) {
2675 sin.sin_addr.s_addr = peercnt->addr;
2677 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2678 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2679 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2680 ao2_ref(peercnt, -1);
2685 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2687 ao2_ref(peercnt, -1);
2689 ao2_iterator_destroy(&i);
2692 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2693 "Non-CallToken Validated Callno Used: %d\n",
2694 global_maxcallno_nonval,
2695 total_nonval_callno_used);
2697 ast_cli(a->fd, "Total Available Callno: %d\n"
2698 "Regular Callno Available: %d\n"
2699 "Trunk Callno Available: %d\n",
2700 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2701 ao2_container_count(callno_pool),
2702 ao2_container_count(callno_pool_trunk));
2703 } else if (a->argc == 5 && !found) {
2704 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2714 static struct callno_entry *get_unused_callno(int trunk, int validated)
2716 struct callno_entry *callno_entry = NULL;
2717 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2718 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2719 /* Minor optimization for the extreme case. */
2723 /* the callno_pool container is locked here primarily to ensure thread
2724 * safety of the total_nonval_callno_used check and increment */
2725 ao2_lock(callno_pool);
2727 /* only a certain number of nonvalidated call numbers should be allocated.
2728 * If there ever is an attack, this separates the calltoken validating
2729 * users from the non calltoken validating users. */
2730 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2731 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2732 ao2_unlock(callno_pool);
2736 /* unlink the object from the container, taking over ownership
2737 * of the reference the container had to the object */
2738 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2741 callno_entry->validated = validated;
2743 total_nonval_callno_used++;
2747 ao2_unlock(callno_pool);
2748 return callno_entry;
2751 static int replace_callno(const void *obj)
2753 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2755 /* the callno_pool container is locked here primarily to ensure thread
2756 * safety of the total_nonval_callno_used check and decrement */
2757 ao2_lock(callno_pool);
2759 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2760 total_nonval_callno_used--;
2761 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2762 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2765 if (callno_entry->callno < TRUNK_CALL_START) {
2766 ao2_link(callno_pool, callno_entry);
2768 ao2_link(callno_pool_trunk, callno_entry);
2770 ao2_ref(callno_entry, -1); /* only container ref remains */
2772 ao2_unlock(callno_pool);
2776 static int callno_hash(const void *obj, const int flags)
2778 return abs(ast_random());
2781 static int create_callno_pools(void)
2785 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2789 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2793 /* start at 2, 0 and 1 are reserved */
2794 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2795 struct callno_entry *callno_entry;
2797 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2801 callno_entry->callno = i;
2803 if (i < TRUNK_CALL_START) {
2804 ao2_link(callno_pool, callno_entry);
2806 ao2_link(callno_pool_trunk, callno_entry);
2809 ao2_ref(callno_entry, -1);
2817 * \brief Schedules delayed removal of iax2_pvt call number data
2819 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2820 * avaliable again, and the address from the previous connection must be decremented
2821 * from the peercnts table. This function schedules these operations to take place.
2823 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2826 struct peercnt *peercnt;
2827 struct peercnt tmp = {
2828 .addr = sin->sin_addr.s_addr,
2831 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2832 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2833 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2834 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2836 ao2_ref(peercnt, -1);
2840 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2845 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2847 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2850 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2852 if (frametype != AST_FRAME_IAX) {
2856 case IAX_COMMAND_NEW:
2857 case IAX_COMMAND_REGREQ:
2858 case IAX_COMMAND_FWDOWNL:
2859 case IAX_COMMAND_REGREL:
2861 case IAX_COMMAND_POKE:
2871 * \note Calling this function while holding another pvt lock can cause a deadlock.
2873 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2877 /* this call is calltoken validated as long as it is either NEW_FORCE
2878 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2879 int validated = (new > NEW_ALLOW) ? 1 : 0;
2882 if (new <= NEW_ALLOW) {
2884 struct chan_iax2_pvt *pvt;
2885 struct chan_iax2_pvt tmp_pvt = {
2887 .peercallno = callno,
2888 .transfercallno = callno,
2890 .frames_received = check_dcallno,
2893 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2894 /* this works for finding normal call numbers not involving transfering */
2895 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2896 if (return_locked) {
2897 ast_mutex_lock(&iaxsl[pvt->callno]);
2904 /* this searches for transfer call numbers that might not get caught otherwise */
2905 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2906 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2907 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2908 if (return_locked) {
2909 ast_mutex_lock(&iaxsl[pvt->callno]);
2917 /* This will occur on the first response to a message that we initiated,
2918 * such as a PING. */
2920 ast_mutex_lock(&iaxsl[dcallno]);
2922 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2923 iaxs[dcallno]->peercallno = callno;
2925 store_by_peercallno(iaxs[dcallno]);
2926 if (!res || !return_locked) {
2927 ast_mutex_unlock(&iaxsl[dcallno]);
2932 ast_mutex_unlock(&iaxsl[dcallno]);
2935 if (!res && (new >= NEW_ALLOW)) {
2936 struct callno_entry *callno_entry;
2937 /* It may seem odd that we look through the peer list for a name for
2938 * this *incoming* call. Well, it is weird. However, users don't
2939 * have an IP address/port number that we can match against. So,
2940 * this is just checking for a peer that has that IP/port and
2941 * assuming that we have a user of the same name. This isn't always
2942 * correct, but it will be changed if needed after authentication. */
2943 if (!iax2_getpeername(*sin, host, sizeof(host)))
2944 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2946 if (peercnt_add(sin)) {
2947 /* This address has hit its callnumber limit. When the limit
2948 * is reached, the connection is not added to the peercnts table.*/
2952 if (!(callno_entry = get_unused_callno(0, validated))) {
2953 /* since we ran out of space, remove the peercnt
2954 * entry we added earlier */
2955 peercnt_remove_by_addr(sin);
2956 ast_log(LOG_WARNING, "No more space\n");
2959 x = callno_entry->callno;
2960 ast_mutex_lock(&iaxsl[x]);
2962 iaxs[x] = new_iax(sin, host);
2965 ast_debug(1, "Creating new call structure %d\n", x);
2966 iaxs[x]->callno_entry = callno_entry;
2967 iaxs[x]->sockfd = sockfd;
2968 iaxs[x]->addr.sin_port = sin->sin_port;
2969 iaxs[x]->addr.sin_family = sin->sin_family;
2970 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2971 iaxs[x]->peercallno = callno;
2972 iaxs[x]->callno = x;
2973 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2974 iaxs[x]->expiry = min_reg_expire;
2975 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2976 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2977 iaxs[x]->amaflags = amaflags;
2978 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2979 ast_string_field_set(iaxs[x], accountcode, accountcode);
2980 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2981 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2982 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2984 if (iaxs[x]->peercallno) {
2985 store_by_peercallno(iaxs[x]);
2988 ast_log(LOG_WARNING, "Out of resources\n");
2989 ast_mutex_unlock(&iaxsl[x]);
2990 replace_callno(callno_entry);
2994 ast_mutex_unlock(&iaxsl[x]);
3000 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3001 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3004 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3006 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3010 * \brief Queue a frame to a call's owning asterisk channel
3012 * \pre This function assumes that iaxsl[callno] is locked when called.
3014 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3015 * was valid before calling it, it may no longer be valid after calling it.
3016 * This function may unlock and lock the mutex associated with this callno,
3017 * meaning that another thread may grab it and destroy the call.
3019 static int iax2_queue_frame(int callno, struct ast_frame *f)
3021 iax2_lock_owner(callno);
3022 if (iaxs[callno] && iaxs[callno]->owner) {
3023 ast_queue_frame(iaxs[callno]->owner, f);
3024 ast_channel_unlock(iaxs[callno]->owner);
3030 * \brief Queue a hangup frame on the ast_channel owner
3032 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3033 * is active for the given call number.
3035 * \pre Assumes lock for callno is already held.
3037 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3038 * was valid before calling it, it may no longer be valid after calling it.
3039 * This function may unlock and lock the mutex associated with this callno,
3040 * meaning that another thread may grab it and destroy the call.
3042 static int iax2_queue_hangup(int callno)
3044 iax2_lock_owner(callno);
3045 if (iaxs[callno] && iaxs[callno]->owner) {
3046 ast_queue_hangup(iaxs[callno]->owner);
3047 ast_channel_unlock(iaxs[callno]->owner);
3053 * \brief Queue a control frame on the ast_channel owner
3055 * This function queues a control frame on the owner of the IAX2 pvt struct that
3056 * is active for the given call number.
3058 * \pre Assumes lock for callno is already held.
3060 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3061 * was valid before calling it, it may no longer be valid after calling it.
3062 * This function may unlock and lock the mutex associated with this callno,
3063 * meaning that another thread may grab it and destroy the call.
3065 static int iax2_queue_control_data(int callno,
3066 enum ast_control_frame_type control, const void *data, size_t datalen)
3068 iax2_lock_owner(callno);
3069 if (iaxs[callno] && iaxs[callno]->owner) {
3070 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3071 ast_channel_unlock(iaxs[callno]->owner);
3075 static void destroy_firmware(struct iax_firmware *cur)
3077 /* Close firmware */
3079 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3085 static int try_firmware(char *s)
3088 struct iax_firmware *cur = NULL;
3089 int ifd, fd, res, len, chunk;
3090 struct ast_iax2_firmware_header *fwh, fwh2;
3091 struct MD5Context md5;
3092 unsigned char sum[16], buf[1024];
3095 s2 = ast_alloca(strlen(s) + 100);
3097 last = strrchr(s, '/');
3103 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3105 if (stat(s, &stbuf) < 0) {
3106 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3110 /* Make sure it's not a directory */
3111 if (S_ISDIR(stbuf.st_mode))
3113 ifd = open(s, O_RDONLY);
3115 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3118 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3120 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3124 /* Unlink our newly created file */
3127 /* Now copy the firmware into it */
3128 len = stbuf.st_size;
3131 if (chunk > sizeof(buf))
3132 chunk = sizeof(buf);
3133 res = read(ifd, buf, chunk);
3135 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3140 res = write(fd, buf, chunk);
3142 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3150 /* Return to the beginning */
3151 lseek(fd, 0, SEEK_SET);
3152 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3153 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3157 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3158 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3162 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3163 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3167 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3168 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3172 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3173 if (fwh == MAP_FAILED) {
3174 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3179 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3180 MD5Final(sum, &md5);
3181 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3182 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3183 munmap((void*)fwh, stbuf.st_size);
3188 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3189 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3190 /* Found a candidate */
3191 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3192 /* The version we have on loaded is older, load this one instead */
3194 /* This version is no newer than what we have. Don't worry about it.
3195 We'll consider it a proper load anyhow though */
3196 munmap((void*)fwh, stbuf.st_size);
3202 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3204 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3209 munmap((void*)cur->fwh, cur->mmaplen);
3214 cur->mmaplen = stbuf.st_size;
3221 static int iax_check_version(char *dev)
3224 struct iax_firmware *cur = NULL;
3226 if (ast_strlen_zero(dev))
3229 AST_LIST_LOCK(&firmwares);
3230 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3231 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3232 res = ntohs(cur->fwh->version);
3236 AST_LIST_UNLOCK(&firmwares);
3241 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3244 unsigned int bs = desc & 0xff;
3245 unsigned int start = (desc >> 8) & 0xffffff;
3247 struct iax_firmware *cur;
3249 if (ast_strlen_zero((char *)dev) || !bs)
3254 AST_LIST_LOCK(&firmwares);
3255 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3256 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3258 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3259 if (start < ntohl(cur->fwh->datalen)) {
3260 bytes = ntohl(cur->fwh->datalen) - start;
3263 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3266 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3274 AST_LIST_UNLOCK(&firmwares);