2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
35 <use type="external">crypto</use>
36 <support_level>core</support_level>
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
51 #include <sys/signal.h>
59 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
61 #include "asterisk/lock.h"
62 #include "asterisk/frame.h"
63 #include "asterisk/channel.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/config.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/translate.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/crypto.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/app.h"
78 #include "asterisk/astdb.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/features.h"
81 #include "asterisk/utils.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/localtime.h"
84 #include "asterisk/dnsmgr.h"
85 #include "asterisk/devicestate.h"
86 #include "asterisk/netsock.h"
87 #include "asterisk/stringfields.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/event.h"
90 #include "asterisk/astobj2.h"
91 #include "asterisk/timing.h"
92 #include "asterisk/taskprocessor.h"
93 #include "asterisk/test.h"
94 #include "asterisk/data.h"
95 #include "asterisk/netsock2.h"
98 #include "iax2-parser.h"
99 #include "iax2-provision.h"
100 #include "jitterbuf.h"
103 <application name="IAX2Provision" language="en_US">
105 Provision a calling IAXy with a given template.
108 <parameter name="template">
109 <para>If not specified, defaults to <literal>default</literal>.</para>
113 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
114 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
115 or <literal>0</literal> on success.</para>
118 <function name="IAXPEER" language="en_US">
120 Gets IAX peer information.
123 <parameter name="peername" required="true">
125 <enum name="CURRENTCHANNEL">
126 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
127 endpoint of the current channel</para>
131 <parameter name="item">
132 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
135 <para>(default) The IP address.</para>
138 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
140 <enum name="mailbox">
141 <para>The configured mailbox.</para>
143 <enum name="context">
144 <para>The configured context.</para>
147 <para>The epoch time of the next expire.</para>
149 <enum name="dynamic">
150 <para>Is it dynamic? (yes/no).</para>
152 <enum name="callerid_name">
153 <para>The configured Caller ID name.</para>
155 <enum name="callerid_num">
156 <para>The configured Caller ID number.</para>
159 <para>The configured codecs.</para>
161 <enum name="codec[x]">
162 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
163 with <literal>0</literal>)</para>
169 <para>Gets information associated with the specified IAX2 peer.</para>
172 <ref type="function">SIPPEER</ref>
175 <function name="IAXVAR" language="en_US">
177 Sets or retrieves a remote variable.
180 <parameter name="varname" required="true" />
183 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
186 <manager name="IAXpeers" language="en_US">
191 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
196 <manager name="IAXpeerlist" language="en_US">
201 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
204 <para>List all the IAX peers.</para>
207 <manager name="IAXnetstats" language="en_US">
213 <para>Show IAX channels network statistics.</para>
216 <manager name="IAXregistry" language="en_US">
218 Show IAX registrations.
221 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
224 <para>Show IAX registrations.</para>
229 /* Define SCHED_MULTITHREADED to run the scheduler in a special
230 multithreaded mode. */
231 #define SCHED_MULTITHREADED
233 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
234 thread is actually doing. */
235 #define DEBUG_SCHED_MULTITHREAD
239 static int nochecksums = 0;
242 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
243 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
245 #define DEFAULT_THREAD_COUNT 10
246 #define DEFAULT_MAX_THREAD_COUNT 100
247 #define DEFAULT_RETRY_TIME 1000
248 #define MEMORY_SIZE 100
249 #define DEFAULT_DROP 3
251 #define DEBUG_SUPPORT
253 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
255 /* Sample over last 100 units to determine historic jitter */
258 static struct ast_codec_pref prefs;
260 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
263 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
264 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
265 #define MAX_TRUNK_MTU 1240
267 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
268 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
270 #define DEFAULT_CONTEXT "default"
272 static char default_parkinglot[AST_MAX_CONTEXT];
274 static char language[MAX_LANGUAGE] = "";
275 static char regcontext[AST_MAX_CONTEXT] = "";
277 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
278 static int network_change_event_sched_id = -1;
280 static int maxauthreq = 3;
281 static int max_retries = 4;
282 static int ping_time = 21;
283 static int lagrq_time = 10;
284 static int maxjitterbuffer=1000;
285 static int resyncthreshold=1000;
286 static int maxjitterinterps=10;
287 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
289 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
291 static int trunkfreq = 20;
292 static int trunkmaxsize = MAX_TRUNKDATA;
294 static int authdebug = 0;
295 static int autokill = 0;
296 static int iaxcompat = 0;
297 static int last_authmethod = 0;
299 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
301 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
308 static int min_reg_expire;
309 static int max_reg_expire;
311 static int srvlookup = 0;
313 static struct ast_timer *timer; /* Timer for trunking */
315 static struct ast_netsock_list *netsock;
316 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
317 static int defaultsockfd = -1;
319 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
322 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
324 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
325 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
326 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
327 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
328 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
329 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
330 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
331 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
332 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
334 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
335 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
339 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
343 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
344 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
345 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
347 /* if a pvt has encryption setup done and is running on the call */
348 #define IAX_CALLENCRYPTED(pvt) \
349 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
351 #define IAX_DEBUGDIGEST(msg, key) do { \
353 char digest[33] = ""; \
358 for (idx = 0; idx < 16; idx++) \
359 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
361 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
364 static struct io_context *io;
365 static struct ast_sched_context *sched;
367 #define DONT_RESCHEDULE -2
369 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
371 static int iaxdebug = 0;
373 static int iaxtrunkdebug = 0;
375 static int test_losspct = 0;
377 static int test_late = 0;
378 static int test_resync = 0;
379 static int test_jit = 0;
380 static int test_jitpct = 0;
381 #endif /* IAXTESTS */
383 static char accountcode[AST_MAX_ACCOUNT_CODE];
384 static char mohinterpret[MAX_MUSICCLASS];
385 static char mohsuggest[MAX_MUSICCLASS];
386 static int amaflags = 0;
388 static int delayreject = 0;
389 static int iax2_encryption = 0;
391 static struct ast_flags64 globalflags = { 0 };
393 static pthread_t netthreadid = AST_PTHREADT_NULL;
396 IAX_STATE_STARTED = (1 << 0),
397 IAX_STATE_AUTHENTICATED = (1 << 1),
398 IAX_STATE_TBD = (1 << 2),
401 struct iax2_context {
402 char context[AST_MAX_CONTEXT];
403 struct iax2_context *next;
407 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
408 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
409 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
410 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
411 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
412 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
413 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
414 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
415 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
416 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
417 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
418 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
419 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
420 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
421 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
422 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
423 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
424 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
425 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
426 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
427 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
428 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
429 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
430 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
431 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
432 #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 */
433 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
434 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
435 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
436 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
437 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
438 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
439 static int global_rtautoclear = 120;
441 static int reload_config(void);
444 * \brief Call token validation settings.
446 enum calltoken_peer_enum {
447 /*! \brief Default calltoken required unless the ip is in the ignorelist */
448 CALLTOKEN_DEFAULT = 0,
449 /*! \brief Require call token validation. */
451 /*! \brief Require call token validation after a successful registration
452 * using call token validation occurs. */
454 /*! \brief Do not require call token validation. */
459 AST_DECLARE_STRING_FIELDS(
460 AST_STRING_FIELD(name);
461 AST_STRING_FIELD(secret);
462 AST_STRING_FIELD(dbsecret);
463 AST_STRING_FIELD(accountcode);
464 AST_STRING_FIELD(mohinterpret);
465 AST_STRING_FIELD(mohsuggest);
466 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
467 AST_STRING_FIELD(language);
468 AST_STRING_FIELD(cid_num);
469 AST_STRING_FIELD(cid_name);
470 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
478 iax2_format capability;
479 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
480 int curauthreq; /*!< Current number of outstanding AUTHREQs */
481 struct ast_codec_pref prefs;
483 struct iax2_context *contexts;
484 struct ast_variable *vars;
485 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
489 AST_DECLARE_STRING_FIELDS(
490 AST_STRING_FIELD(name);
491 AST_STRING_FIELD(username);
492 AST_STRING_FIELD(description); /*!< Description of the peer */
493 AST_STRING_FIELD(secret);
494 AST_STRING_FIELD(dbsecret);
495 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
497 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
498 AST_STRING_FIELD(context); /*!< For transfers only */
499 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
500 AST_STRING_FIELD(mailbox); /*!< Mailbox */
501 AST_STRING_FIELD(mohinterpret);
502 AST_STRING_FIELD(mohsuggest);
503 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
504 /* Suggested caller id if registering */
505 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
506 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
507 AST_STRING_FIELD(zonetag); /*!< Time Zone */
508 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
510 struct ast_codec_pref prefs;
511 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
512 struct ast_sockaddr addr;
514 int sockfd; /*!< Socket to use for transmission */
519 /* Dynamic Registration fields */
520 struct sockaddr_in defaddr; /*!< Default address if there is one */
521 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
522 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
524 int expire; /*!< Schedule entry for expiry */
525 int expiry; /*!< How soon to expire */
526 iax2_format capability; /*!< Capability */
529 int callno; /*!< Call number of POKE request */
530 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
531 int lastms; /*!< How long last response took (in ms), or -1 for no response */
532 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
534 int pokefreqok; /*!< How often to check if the host is up */
535 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
536 int historicms; /*!< How long recent average responses took */
537 int smoothing; /*!< Sample over how many units to determine historic ms */
538 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
540 struct ast_event_sub *mwi_event_sub;
543 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
546 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
548 struct iax2_trunk_peer {
551 struct sockaddr_in addr;
552 struct timeval txtrunktime; /*!< Transmit trunktime */
553 struct timeval rxtrunktime; /*!< Receive trunktime */
554 struct timeval lasttxtime; /*!< Last transmitted trunktime */
555 struct timeval trunkact; /*!< Last trunk activity */
556 unsigned int lastsent; /*!< Last sent time */
557 /* Trunk data and length */
558 unsigned char *trunkdata;
559 unsigned int trunkdatalen;
560 unsigned int trunkdataalloc;
564 AST_LIST_ENTRY(iax2_trunk_peer) list;
567 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
569 struct iax_firmware {
570 AST_LIST_ENTRY(iax_firmware) list;
574 struct ast_iax2_firmware_header *fwh;
579 REG_STATE_UNREGISTERED = 0,
582 REG_STATE_REGISTERED,
588 enum iax_transfer_state {
593 TRANSFER_PASSTHROUGH,
597 TRANSFER_MPASSTHROUGH,
602 struct iax2_registry {
603 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
605 char secret[80]; /*!< Password or key name in []'s */
606 int expire; /*!< Sched ID of expiration */
607 int refresh; /*!< How often to refresh */
608 enum iax_reg_state regstate;
609 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
610 int callno; /*!< Associated call number if applicable */
611 struct sockaddr_in us; /*!< Who the server thinks we are */
612 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
613 AST_LIST_ENTRY(iax2_registry) entry;
616 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
618 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
619 #define MIN_RETRY_TIME 100
620 #define MAX_RETRY_TIME 10000
622 #define MAX_JITTER_BUFFER 50
623 #define MIN_JITTER_BUFFER 10
625 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
627 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
629 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
630 #define TS_GAP_FOR_JB_RESYNC 5000
632 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
633 #define MARK_IAX_SUBCLASS_TX 0x8000
635 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
636 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
637 static int iaxdynamicthreadcount = 0;
638 static int iaxdynamicthreadnum = 0;
639 static int iaxactivethreadcount = 0;
653 struct chan_iax2_pvt {
654 /*! Socket to send/receive on for this call */
656 /*! Last received voice format */
657 iax2_format voiceformat;
658 /*! Last received video format */
659 iax2_format videoformat;
660 /*! Last sent voice format */
661 iax2_format svoiceformat;
662 /*! Last sent video format */
663 iax2_format svideoformat;
664 /*! What we are capable of sending */
665 iax2_format capability;
666 /*! Last received timestamp */
668 /*! Last sent timestamp - never send the same timestamp twice in a single call */
669 unsigned int lastsent;
670 /*! Timestamp of the last video frame sent */
671 unsigned int lastvsent;
672 /*! Next outgoing timestamp if everything is good */
673 unsigned int nextpred;
674 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
675 int first_iax_message;
676 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
677 int last_iax_message;
678 /*! True if the last voice we transmitted was not silence/CNG */
679 unsigned int notsilenttx:1;
681 unsigned int pingtime;
682 /*! Max time for initial response */
685 struct sockaddr_in addr;
686 /*! Actual used codec preferences */
687 struct ast_codec_pref prefs;
688 /*! Requested codec preferences */
689 struct ast_codec_pref rprefs;
690 /*! Our call number */
691 unsigned short callno;
692 /*! Our callno_entry entry */
693 struct callno_entry *callno_entry;
695 unsigned short peercallno;
696 /*! Negotiated format, this is only used to remember what format was
697 chosen for an unauthenticated call so that the channel can get
698 created later using the right format */
699 iax2_format chosenformat;
700 /*! Peer selected format */
701 iax2_format peerformat;
702 /*! Peer capability */
703 iax2_format peercapability;
704 /*! timeval that we base our transmission on */
705 struct timeval offset;
706 /*! timeval that we base our delivery on */
707 struct timeval rxcore;
708 /*! The jitterbuffer */
710 /*! active jb read scheduler id */
714 /*! Error, as discovered by the manager */
716 /*! Owner if we have one */
717 struct ast_channel *owner;
718 /*! What's our state? */
719 struct ast_flags state;
720 /*! Expiry (optional) */
722 /*! Next outgoing sequence number */
723 unsigned char oseqno;
724 /*! Next sequence number they have not yet acknowledged */
725 unsigned char rseqno;
726 /*! Next incoming sequence number */
727 unsigned char iseqno;
728 /*! Last incoming sequence number we have acknowledged */
729 unsigned char aseqno;
731 AST_DECLARE_STRING_FIELDS(
733 AST_STRING_FIELD(peer);
734 /*! Default Context */
735 AST_STRING_FIELD(context);
736 /*! Caller ID if available */
737 AST_STRING_FIELD(cid_num);
738 AST_STRING_FIELD(cid_name);
739 /*! Hidden Caller ID (i.e. ANI) if appropriate */
740 AST_STRING_FIELD(ani);
742 AST_STRING_FIELD(dnid);
744 AST_STRING_FIELD(rdnis);
745 /*! Requested Extension */
746 AST_STRING_FIELD(exten);
747 /*! Expected Username */
748 AST_STRING_FIELD(username);
749 /*! Expected Secret */
750 AST_STRING_FIELD(secret);
752 AST_STRING_FIELD(challenge);
753 /*! Public keys permitted keys for incoming authentication */
754 AST_STRING_FIELD(inkeys);
755 /*! Private key for outgoing authentication */
756 AST_STRING_FIELD(outkey);
757 /*! Preferred language */
758 AST_STRING_FIELD(language);
759 /*! Hostname/peername for naming purposes */
760 AST_STRING_FIELD(host);
762 AST_STRING_FIELD(dproot);
763 AST_STRING_FIELD(accountcode);
764 AST_STRING_FIELD(mohinterpret);
765 AST_STRING_FIELD(mohsuggest);
766 /*! received OSP token */
767 AST_STRING_FIELD(osptoken);
768 /*! Default parkinglot */
769 AST_STRING_FIELD(parkinglot);
771 /*! AUTHREJ all AUTHREP frames */
773 /*! permitted authentication methods */
775 /*! permitted encryption methods */
777 /*! Encryption AES-128 Key */
778 ast_aes_encrypt_key ecx;
779 /*! Decryption AES-128 Key corresponding to ecx */
780 ast_aes_decrypt_key mydcx;
781 /*! Decryption AES-128 Key used to decrypt peer frames */
782 ast_aes_decrypt_key dcx;
783 /*! scheduler id associated with iax_key_rotate
784 * for encrypted calls*/
786 /*! 32 bytes of semi-random data */
787 unsigned char semirand[32];
788 /*! Associated registry */
789 struct iax2_registry *reg;
790 /*! Associated peer for poking */
791 struct iax2_peer *peerpoke;
796 /*! Transferring status */
797 enum iax_transfer_state transferring;
798 /*! Transfer identifier */
800 /*! Who we are IAX transferring to */
801 struct sockaddr_in transfer;
802 /*! What's the new call number for the transfer */
803 unsigned short transfercallno;
804 /*! Transfer encrypt AES-128 Key */
805 ast_aes_encrypt_key tdcx;
807 /*! Status of knowledge of peer ADSI capability */
810 /*! Who we are bridged to */
811 unsigned short bridgecallno;
813 int pingid; /*!< Transmit PING request */
814 int lagid; /*!< Retransmit lag request */
815 int autoid; /*!< Auto hangup for Dialplan requestor */
816 int authid; /*!< Authentication rejection ID */
817 int authfail; /*!< Reason to report failure */
818 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
823 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
824 /*! variables inherited from the user definition */
825 struct ast_variable *vars;
826 /*! variables transmitted in a NEW packet */
827 struct ast_variable *iaxvars;
828 /*! last received remote rr */
829 struct iax_rr remote_rr;
830 /*! Current base time: (just for stats) */
832 /*! Dropped frame count: (just for stats) */
834 /*! received frame count: (just for stats) */
836 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
837 unsigned char calltoken_ie_len;
838 /*! hold all signaling frames from the pbx thread until we have a destination callno */
840 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
841 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
844 struct signaling_queue_entry {
846 AST_LIST_ENTRY(signaling_queue_entry) next;
849 /*! table of available call numbers */
850 static struct ao2_container *callno_pool;
852 /*! table of available trunk call numbers */
853 static struct ao2_container *callno_pool_trunk;
855 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
858 * \brief a list of frames that may need to be retransmitted
860 * \note The contents of this list do not need to be explicitly destroyed
861 * on module unload. This is because all active calls are destroyed, and
862 * all frames in this queue will get destroyed as a part of that process.
864 * \note Contents protected by the iaxsl[] locks
866 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
868 static struct ast_taskprocessor *transmit_processor;
870 static int randomcalltokendata;
872 static const time_t MAX_CALLTOKEN_DELAY = 10;
875 * This module will get much higher performance when doing a lot of
876 * user and peer lookups if the number of buckets is increased from 1.
877 * However, to maintain old behavior for Asterisk 1.4, these are set to
878 * 1 by default. When using multiple buckets, search order through these
879 * containers is considered random, so you will not be able to depend on
880 * the order the entires are specified in iax.conf for matching order. */
882 #define MAX_PEER_BUCKETS 17
884 #define MAX_PEER_BUCKETS 563
886 static struct ao2_container *peers;
888 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
889 static struct ao2_container *users;
891 /*! Table containing peercnt objects for every ip address consuming a callno */
892 static struct ao2_container *peercnts;
894 /*! Table containing custom callno limit rules for a range of ip addresses. */
895 static struct ao2_container *callno_limits;
897 /*! Table containing ip addresses not requiring calltoken validation */
898 static struct ao2_container *calltoken_ignores;
900 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
902 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
904 static uint16_t global_maxcallno;
906 /*! Total num of call numbers allowed to be allocated without calltoken validation */
907 static uint16_t global_maxcallno_nonval;
909 static uint16_t total_nonval_callno_used = 0;
911 /*! peer connection private, keeps track of all the call numbers
912 * consumed by a single ip address */
914 /*! ip address consuming call numbers */
916 /*! Number of call numbers currently used by this ip address */
918 /*! Max call numbers allowed for this ip address */
920 /*! Specifies whether limit is set by a registration or not, if so normal
921 * limit setting rules do not apply to this address. */
925 /*! used by both callno_limits and calltoken_ignores containers */
927 /*! ip address range for custom callno limit rule */
929 /*! callno limit for this ip address range, only used in callno_limits container */
931 /*! delete me marker for reloads */
935 struct callno_entry {
936 /*! callno used for this entry */
938 /*! was this callno calltoken validated or not */
939 unsigned char validated;
942 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
945 /*! Extension exists */
946 CACHE_FLAG_EXISTS = (1 << 0),
947 /*! Extension is nonexistent */
948 CACHE_FLAG_NONEXISTENT = (1 << 1),
949 /*! Extension can exist */
950 CACHE_FLAG_CANEXIST = (1 << 2),
951 /*! Waiting to hear back response */
952 CACHE_FLAG_PENDING = (1 << 3),
954 CACHE_FLAG_TIMEOUT = (1 << 4),
955 /*! Request transmitted */
956 CACHE_FLAG_TRANSMITTED = (1 << 5),
958 CACHE_FLAG_UNKNOWN = (1 << 6),
960 CACHE_FLAG_MATCHMORE = (1 << 7),
963 struct iax2_dpcache {
964 char peercontext[AST_MAX_CONTEXT];
965 char exten[AST_MAX_EXTENSION];
967 struct timeval expiry;
969 unsigned short callno;
971 AST_LIST_ENTRY(iax2_dpcache) cache_list;
972 AST_LIST_ENTRY(iax2_dpcache) peer_list;
975 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
977 static void reg_source_db(struct iax2_peer *p);
978 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
979 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
981 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
982 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
983 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
985 enum iax2_thread_iostate {
988 IAX_IOSTATE_PROCESSING,
989 IAX_IOSTATE_SCHEDREADY,
992 enum iax2_thread_type {
993 IAX_THREAD_TYPE_POOL,
994 IAX_THREAD_TYPE_DYNAMIC,
997 struct iax2_pkt_buf {
998 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1000 unsigned char buf[1];
1003 struct iax2_thread {
1004 AST_LIST_ENTRY(iax2_thread) list;
1005 enum iax2_thread_type type;
1006 enum iax2_thread_iostate iostate;
1007 #ifdef SCHED_MULTITHREADED
1008 void (*schedfunc)(const void *);
1009 const void *scheddata;
1011 #ifdef DEBUG_SCHED_MULTITHREAD
1017 struct sockaddr_in iosin;
1018 unsigned char readbuf[4096];
1026 ast_mutex_t init_lock;
1027 ast_cond_t init_cond;
1028 /*! if this thread is processing a full frame,
1029 some information about that frame will be stored
1030 here, so we can avoid dispatching any more full
1031 frames for that callno to other threads */
1033 unsigned short callno;
1034 struct sockaddr_in sin;
1038 /*! Queued up full frames for processing. If more full frames arrive for
1039 * a call which this thread is already processing a full frame for, they
1040 * are queued up here. */
1041 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1046 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1047 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1048 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1050 static void *iax2_process_thread(void *data);
1051 static void iax2_destroy(int callno);
1053 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1055 ast_mutex_lock(lock);
1056 ast_cond_signal(cond);
1057 ast_mutex_unlock(lock);
1061 * \brief an array of iax2 pvt structures
1063 * The container for active chan_iax2_pvt structures is implemented as an
1064 * array for extremely quick direct access to the correct pvt structure
1065 * based on the local call number. The local call number is used as the
1066 * index into the array where the associated pvt structure is stored.
1068 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1071 * \brief Another container of iax2_pvt structures
1073 * Active IAX2 pvt structs are also stored in this container, if they are a part
1074 * of an active call where we know the remote side's call number. The reason
1075 * for this is that incoming media frames do not contain our call number. So,
1076 * instead of having to iterate the entire iaxs array, we use this container to
1077 * look up calls where the remote side is using a given call number.
1079 static struct ao2_container *iax_peercallno_pvts;
1082 * \brief chan_iax2_pvt structure locks
1084 * These locks are used when accessing a pvt structure in the iaxs array.
1085 * The index used here is the same as used in the iaxs array. It is the
1086 * local call number for the associated pvt struct.
1088 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1091 * * \brief Another container of iax2_pvt structures
1093 * Active IAX2 pvt stucts used during transfering a call are stored here.
1095 static struct ao2_container *iax_transfercallno_pvts;
1097 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1098 but keeps the division between trunked and non-trunked better. */
1099 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1101 /* Debug routines... */
1102 static struct sockaddr_in debugaddr;
1104 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1107 (sin && debugaddr.sin_addr.s_addr &&
1108 (!ntohs(debugaddr.sin_port) ||
1109 debugaddr.sin_port == sin->sin_port) &&
1110 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1112 iax_showframe(f, fhi, rx, sin, datalen);
1115 iax_showframe(f, fhi, rx, sin, datalen);
1121 static void iax_debug_output(const char *data)
1124 ast_verbose("%s", data);
1127 static void iax_error_output(const char *data)
1129 ast_log(LOG_WARNING, "%s", data);
1132 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1137 va_start(args, fmt);
1138 vsnprintf(buf, sizeof(buf), fmt, args);
1141 ast_log(LOG_ERROR, "%s", buf);
1144 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1149 va_start(args, fmt);
1150 vsnprintf(buf, sizeof(buf), fmt, args);
1153 ast_log(LOG_WARNING, "%s", buf);
1156 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1161 va_start(args, fmt);
1162 vsnprintf(buf, sizeof(buf), fmt, args);
1165 ast_verbose("%s", buf);
1168 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);
1169 static int expire_registry(const void *data);
1170 static int iax2_answer(struct ast_channel *c);
1171 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1172 static int iax2_devicestate(const char *data);
1173 static int iax2_digit_begin(struct ast_channel *c, char digit);
1174 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1175 static int iax2_do_register(struct iax2_registry *reg);
1176 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1177 static int iax2_hangup(struct ast_channel *c);
1178 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1179 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1180 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1181 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1182 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1183 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1184 static int iax2_sendtext(struct ast_channel *c, const char *text);
1185 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1186 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1187 static int iax2_transfer(struct ast_channel *c, const char *dest);
1188 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1189 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1191 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1192 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1193 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1194 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1195 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1196 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1197 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1198 static struct ast_frame *iax2_read(struct ast_channel *c);
1199 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1200 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1201 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1202 static void *iax2_dup_variable_datastore(void *);
1203 static void prune_peers(void);
1204 static void prune_users(void);
1205 static void iax2_free_variable_datastore(void *);
1207 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1208 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1209 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1210 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1211 static void build_rand_pad(unsigned char *buf, ssize_t len);
1212 static struct callno_entry *get_unused_callno(int trunk, int validated);
1213 static int replace_callno(const void *obj);
1214 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1215 static void network_change_event_cb(const struct ast_event *, void *);
1217 static struct ast_channel_tech iax2_tech = {
1219 .description = tdesc,
1220 .properties = AST_CHAN_TP_WANTSJITTER,
1221 .requester = iax2_request,
1222 .devicestate = iax2_devicestate,
1223 .send_digit_begin = iax2_digit_begin,
1224 .send_digit_end = iax2_digit_end,
1225 .send_text = iax2_sendtext,
1226 .send_image = iax2_sendimage,
1227 .send_html = iax2_sendhtml,
1229 .hangup = iax2_hangup,
1230 .answer = iax2_answer,
1232 .write = iax2_write,
1233 .write_video = iax2_write,
1234 .indicate = iax2_indicate,
1235 .setoption = iax2_setoption,
1236 .queryoption = iax2_queryoption,
1237 .bridge = iax2_bridge,
1238 .transfer = iax2_transfer,
1239 .fixup = iax2_fixup,
1240 .func_channel_read = acf_channel_read,
1245 * \brief Obtain the owner channel lock if the owner exists.
1247 * \param callno IAX2 call id.
1249 * \note Assumes the iaxsl[callno] lock is already obtained.
1252 * IMPORTANT NOTE!!! Any time this function is used, even if
1253 * iaxs[callno] was valid before calling it, it may no longer be
1254 * valid after calling it. This function may unlock and lock
1255 * the mutex associated with this callno, meaning that another
1256 * thread may grab it and destroy the call.
1260 static void iax2_lock_owner(int callno)
1263 if (!iaxs[callno] || !iaxs[callno]->owner) {
1264 /* There is no owner lock to get. */
1267 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1268 /* We got the lock */
1271 /* Avoid deadlock by pausing and trying again */
1272 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1276 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1278 /* The MWI subscriptions exist just so the core knows we care about those
1279 * mailboxes. However, we just grab the events out of the cache when it
1280 * is time to send MWI, since it is only sent with a REGACK. */
1283 static void network_change_event_subscribe(void)
1285 if (!network_change_event_subscription) {
1286 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1287 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1291 static void network_change_event_unsubscribe(void)
1293 if (network_change_event_subscription) {
1294 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1298 static int network_change_event_sched_cb(const void *data)
1300 struct iax2_registry *reg;
1301 network_change_event_sched_id = -1;
1302 AST_LIST_LOCK(®istrations);
1303 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1304 iax2_do_register(reg);
1306 AST_LIST_UNLOCK(®istrations);
1311 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1313 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1314 if (network_change_event_sched_id == -1) {
1315 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1321 /*! \brief Send manager event at call setup to link between Asterisk channel name
1322 and IAX2 call identifiers */
1323 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1325 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1326 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1327 pvt->owner ? ast_channel_name(pvt->owner) : "",
1328 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1331 static struct ast_datastore_info iax2_variable_datastore_info = {
1332 .type = "IAX2_VARIABLE",
1333 .duplicate = iax2_dup_variable_datastore,
1334 .destroy = iax2_free_variable_datastore,
1337 static void *iax2_dup_variable_datastore(void *old)
1339 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1340 struct ast_var_t *oldvar, *newvar;
1342 newlist = ast_calloc(sizeof(*newlist), 1);
1344 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1348 AST_LIST_HEAD_INIT(newlist);
1349 AST_LIST_LOCK(oldlist);
1350 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1351 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1353 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1355 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1357 AST_LIST_UNLOCK(oldlist);
1361 static void iax2_free_variable_datastore(void *old)
1363 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1364 struct ast_var_t *oldvar;
1366 AST_LIST_LOCK(oldlist);
1367 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1370 AST_LIST_UNLOCK(oldlist);
1371 AST_LIST_HEAD_DESTROY(oldlist);
1376 /* WARNING: insert_idle_thread should only ever be called within the
1377 * context of an iax2_process_thread() thread.
1379 static void insert_idle_thread(struct iax2_thread *thread)
1381 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1382 AST_LIST_LOCK(&dynamic_list);
1383 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1384 AST_LIST_UNLOCK(&dynamic_list);
1386 AST_LIST_LOCK(&idle_list);
1387 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1388 AST_LIST_UNLOCK(&idle_list);
1394 static struct iax2_thread *find_idle_thread(void)
1396 struct iax2_thread *thread = NULL;
1398 /* Pop the head of the idle list off */
1399 AST_LIST_LOCK(&idle_list);
1400 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1401 AST_LIST_UNLOCK(&idle_list);
1403 /* If we popped a thread off the idle list, just return it */
1405 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1409 /* Pop the head of the dynamic list off */
1410 AST_LIST_LOCK(&dynamic_list);
1411 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1412 AST_LIST_UNLOCK(&dynamic_list);
1414 /* If we popped a thread off the dynamic list, just return it */
1416 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1420 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1421 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1424 /* Set default values */
1425 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1426 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1427 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1429 /* Initialize lock and condition */
1430 ast_mutex_init(&thread->lock);
1431 ast_cond_init(&thread->cond, NULL);
1432 ast_mutex_init(&thread->init_lock);
1433 ast_cond_init(&thread->init_cond, NULL);
1434 ast_mutex_lock(&thread->init_lock);
1436 /* Create thread and send it on it's way */
1437 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1438 ast_cond_destroy(&thread->cond);
1439 ast_mutex_destroy(&thread->lock);
1440 ast_mutex_unlock(&thread->init_lock);
1441 ast_cond_destroy(&thread->init_cond);
1442 ast_mutex_destroy(&thread->init_lock);
1447 /* this thread is not processing a full frame (since it is idle),
1448 so ensure that the field for the full frame call number is empty */
1449 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1451 /* Wait for the thread to be ready before returning it to the caller */
1452 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1454 /* Done with init_lock */
1455 ast_mutex_unlock(&thread->init_lock);
1460 #ifdef SCHED_MULTITHREADED
1461 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1463 struct iax2_thread *thread = NULL;
1464 static time_t lasterror;
1467 thread = find_idle_thread();
1469 if (thread != NULL) {
1470 thread->schedfunc = func;
1471 thread->scheddata = data;
1472 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1473 #ifdef DEBUG_SCHED_MULTITHREAD
1474 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1476 signal_condition(&thread->lock, &thread->cond);
1481 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1486 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1489 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1490 ast_sched_cb callback, const void *data)
1492 return ast_sched_replace(id, con, when, callback, data);
1495 static int iax2_sched_add(struct ast_sched_context *con, int when,
1496 ast_sched_cb callback, const void *data)
1498 return ast_sched_add(con, when, callback, data);
1501 static int send_ping(const void *data);
1503 static void __send_ping(const void *data)
1505 int callno = (long) data;
1507 ast_mutex_lock(&iaxsl[callno]);
1510 if (iaxs[callno]->peercallno) {
1511 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1512 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1513 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1517 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1520 ast_mutex_unlock(&iaxsl[callno]);
1523 static int send_ping(const void *data)
1525 int callno = (long) data;
1526 ast_mutex_lock(&iaxsl[callno]);
1527 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1528 iaxs[callno]->pingid = -1;
1530 ast_mutex_unlock(&iaxsl[callno]);
1532 #ifdef SCHED_MULTITHREADED
1533 if (schedule_action(__send_ping, data))
1540 static void encmethods_to_str(int e, struct ast_str *buf)
1542 ast_str_set(&buf, 0, "(");
1543 if (e & IAX_ENCRYPT_AES128) {
1544 ast_str_append(&buf, 0, "aes128");
1546 if (e & IAX_ENCRYPT_KEYROTATE) {
1547 ast_str_append(&buf, 0, ",keyrotate");
1549 if (ast_str_strlen(buf) > 1) {
1550 ast_str_append(&buf, 0, ")");
1552 ast_str_set(&buf, 0, "No");
1556 static int get_encrypt_methods(const char *s)
1559 if (!strcasecmp(s, "aes128"))
1560 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1561 else if (ast_true(s))
1562 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1568 static int send_lagrq(const void *data);
1570 static void __send_lagrq(const void *data)
1572 int callno = (long) data;
1574 ast_mutex_lock(&iaxsl[callno]);
1577 if (iaxs[callno]->peercallno) {
1578 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1579 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1580 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1584 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1587 ast_mutex_unlock(&iaxsl[callno]);
1590 static int send_lagrq(const void *data)
1592 int callno = (long) data;
1593 ast_mutex_lock(&iaxsl[callno]);
1594 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1595 iaxs[callno]->lagid = -1;
1597 ast_mutex_unlock(&iaxsl[callno]);
1599 #ifdef SCHED_MULTITHREADED
1600 if (schedule_action(__send_lagrq, data))
1606 static unsigned char compress_subclass(iax2_format subclass)
1610 /* If it's 64 or smaller, just return it */
1611 if (subclass < IAX_FLAG_SC_LOG)
1613 /* Otherwise find its power */
1614 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1615 if (subclass & (1LL << x)) {
1617 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1623 return power | IAX_FLAG_SC_LOG;
1626 static iax2_format uncompress_subclass(unsigned char csub)
1628 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1629 if (csub & IAX_FLAG_SC_LOG) {
1630 /* special case for 'compressed' -1 */
1634 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1640 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1642 struct ast_format_cap *cap;
1643 struct ast_format tmpfmt;
1644 iax2_format format = 0;
1645 if ((cap = ast_format_cap_alloc_nolock())) {
1646 ast_format_clear(&tmpfmt);
1647 ast_format_cap_from_old_bitfield(cap, formats);
1648 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1649 format = ast_format_to_old_bitfield(&tmpfmt);
1650 cap = ast_format_cap_destroy(cap);
1656 static iax2_format iax2_best_codec(iax2_format formats)
1658 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1659 struct ast_format tmpfmt;
1664 ast_format_clear(&tmpfmt);
1665 ast_format_cap_from_old_bitfield(cap, formats);
1666 ast_best_codec(cap, &tmpfmt);
1667 cap = ast_format_cap_destroy(cap);
1668 return ast_format_to_old_bitfield(&tmpfmt);
1671 const char *iax2_getformatname(iax2_format format)
1673 struct ast_format tmpfmt;
1674 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1678 return ast_getformatname(&tmpfmt);
1681 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1683 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1688 ast_format_cap_from_old_bitfield(cap, format);
1689 ast_getformatname_multiple(codec_buf, len, cap);
1690 cap = ast_format_cap_destroy(cap);
1695 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1698 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1703 ast_format_cap_from_old_bitfield(cap, *formats);
1704 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1705 *formats = ast_format_cap_to_old_bitfield(cap);
1706 cap = ast_format_cap_destroy(cap);
1711 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1714 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1718 ast_format_cap_from_old_bitfield(cap, formats);
1719 res = ast_data_add_codecs(root, node_name, cap);
1720 cap = ast_format_cap_destroy(cap);
1725 * \note The only member of the peer passed here guaranteed to be set is the name field
1727 static int peer_hash_cb(const void *obj, const int flags)
1729 const struct iax2_peer *peer = obj;
1730 const char *name = obj;
1732 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1736 * \note The only member of the peer passed here guaranteed to be set is the name field
1738 static int peer_cmp_cb(void *obj, void *arg, int flags)
1740 struct iax2_peer *peer = obj, *peer2 = arg;
1741 const char *name = arg;
1743 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1744 CMP_MATCH | CMP_STOP : 0;
1748 * \note The only member of the user passed here guaranteed to be set is the name field
1750 static int user_hash_cb(const void *obj, const int flags)
1752 const struct iax2_user *user = obj;
1753 const char *name = obj;
1755 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1759 * \note The only member of the user passed here guaranteed to be set is the name field
1761 static int user_cmp_cb(void *obj, void *arg, int flags)
1763 struct iax2_user *user = obj, *user2 = arg;
1764 const char *name = arg;
1766 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1767 CMP_MATCH | CMP_STOP : 0;
1771 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1772 * so do not call it with a pvt lock held.
1774 static struct iax2_peer *find_peer(const char *name, int realtime)
1776 struct iax2_peer *peer = NULL;
1778 peer = ao2_find(peers, name, OBJ_KEY);
1780 /* Now go for realtime if applicable */
1781 if(!peer && realtime)
1782 peer = realtime_peer(name, NULL);
1787 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1793 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1799 static struct iax2_user *find_user(const char *name)
1801 return ao2_find(users, name, OBJ_KEY);
1803 static inline struct iax2_user *user_ref(struct iax2_user *user)
1809 static inline struct iax2_user *user_unref(struct iax2_user *user)
1815 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1817 struct iax2_peer *peer = NULL;
1819 struct ao2_iterator i;
1821 i = ao2_iterator_init(peers, 0);
1822 while ((peer = ao2_iterator_next(&i))) {
1823 struct sockaddr_in peer_addr;
1825 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1827 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1828 (peer_addr.sin_port == sin.sin_port)) {
1829 ast_copy_string(host, peer->name, len);
1836 ao2_iterator_destroy(&i);
1839 peer = realtime_peer(NULL, &sin);
1841 ast_copy_string(host, peer->name, len);
1850 /*!\note Assumes the lock on the pvt is already held, when
1851 * iax2_destroy_helper() is called. */
1852 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1854 /* Decrement AUTHREQ count if needed */
1855 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1856 struct iax2_user *user;
1858 user = ao2_find(users, pvt->username, OBJ_KEY);
1860 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1864 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1866 /* No more pings or lagrq's */
1867 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1868 pvt->pingid = DONT_RESCHEDULE;
1869 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1870 pvt->lagid = DONT_RESCHEDULE;
1871 AST_SCHED_DEL(sched, pvt->autoid);
1872 AST_SCHED_DEL(sched, pvt->authid);
1873 AST_SCHED_DEL(sched, pvt->initid);
1874 AST_SCHED_DEL(sched, pvt->jbid);
1875 AST_SCHED_DEL(sched, pvt->keyrotateid);
1878 static void iax2_frame_free(struct iax_frame *fr)
1880 AST_SCHED_DEL(sched, fr->retrans);
1884 static int scheduled_destroy(const void *vid)
1886 unsigned short callno = PTR_TO_CALLNO(vid);
1887 ast_mutex_lock(&iaxsl[callno]);
1889 ast_debug(1, "Really destroying %d now...\n", callno);
1890 iax2_destroy(callno);
1892 ast_mutex_unlock(&iaxsl[callno]);
1896 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1899 ast_free(s->f.data.ptr);
1904 /*! \brief This function must be called once we are sure the other side has
1905 * given us a call number. All signaling is held here until that point. */
1906 static void send_signaling(struct chan_iax2_pvt *pvt)
1908 struct signaling_queue_entry *s = NULL;
1910 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1911 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1912 free_signaling_queue_entry(s);
1914 pvt->hold_signaling = 0;
1917 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1918 * we have received a destination call number. */
1919 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1921 struct signaling_queue_entry *new;
1923 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1924 return 1; /* do not queue this frame */
1925 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1926 return -1; /* out of memory */
1929 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1931 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1932 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1933 free_signaling_queue_entry(new);
1936 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1938 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1943 static void pvt_destructor(void *obj)
1945 struct chan_iax2_pvt *pvt = obj;
1946 struct iax_frame *cur = NULL;
1947 struct signaling_queue_entry *s = NULL;
1949 ast_mutex_lock(&iaxsl[pvt->callno]);
1951 iax2_destroy_helper(pvt);
1953 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1954 pvt->callno_entry = NULL;
1957 ast_set_flag64(pvt, IAX_ALREADYGONE);
1959 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1960 /* Cancel any pending transmissions */
1964 ast_mutex_unlock(&iaxsl[pvt->callno]);
1966 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1967 free_signaling_queue_entry(s);
1971 pvt->reg->callno = 0;
1977 ast_variables_destroy(pvt->vars);
1981 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1982 iax2_frame_free(frame.data);
1985 jb_destroy(pvt->jb);
1986 ast_string_field_free_memory(pvt);
1990 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1992 struct chan_iax2_pvt *tmp;
1995 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1999 if (ast_string_field_init(tmp, 32)) {
2011 tmp->keyrotateid = -1;
2013 ast_string_field_set(tmp,exten, "s");
2014 ast_string_field_set(tmp,host, host);
2018 jbconf.max_jitterbuf = maxjitterbuffer;
2019 jbconf.resync_threshold = resyncthreshold;
2020 jbconf.max_contig_interp = maxjitterinterps;
2021 jbconf.target_extra = jittertargetextra;
2022 jb_setconf(tmp->jb,&jbconf);
2024 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2026 tmp->hold_signaling = 1;
2027 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2032 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2034 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2036 size_t afdatalen = new->afdatalen;
2037 memcpy(new, fr, sizeof(*new));
2038 iax_frame_wrap(new, &fr->af);
2039 new->afdatalen = afdatalen;
2042 new->direction = DIRECTION_INGRESS;
2047 /* keep these defined in this order. They are used in find_callno to
2048 * determine whether or not a new call number should be allowed. */
2050 /* do not allow a new call number, only search ones in use for match */
2052 /* search for match first, then allow a new one to be allocated */
2054 /* do not search for match, force a new call number */
2056 /* do not search for match, force a new call number. Signifies call number
2057 * has been calltoken validated */
2058 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2061 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2063 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2064 (cur->addr.sin_port == sin->sin_port)) {
2065 /* This is the main host */
2066 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2067 (check_dcallno ? dcallno == cur->callno : 1) ) {
2068 /* That's us. Be sure we keep track of the peer call number */
2072 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2073 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2074 /* We're transferring */
2075 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2081 static int make_trunk(unsigned short callno, int locked)
2085 struct callno_entry *callno_entry;
2086 if (iaxs[callno]->oseqno) {
2087 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2090 if (callno & TRUNK_CALL_START) {
2091 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2095 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2096 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2100 x = callno_entry->callno;
2101 ast_mutex_lock(&iaxsl[x]);
2104 * \note We delete these before switching the slot, because if
2105 * they fire in the meantime, they will generate a warning.
2107 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2108 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2109 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2110 iaxs[x] = iaxs[callno];
2111 iaxs[x]->callno = x;
2113 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2114 * before assigning the new one */
2115 if (iaxs[x]->callno_entry) {
2116 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2118 iaxs[x]->callno_entry = callno_entry;
2120 iaxs[callno] = NULL;
2121 /* Update the two timers that should have been started */
2122 iaxs[x]->pingid = iax2_sched_add(sched,
2123 ping_time * 1000, send_ping, (void *)(long)x);
2124 iaxs[x]->lagid = iax2_sched_add(sched,
2125 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2128 ast_mutex_unlock(&iaxsl[callno]);
2131 ast_mutex_unlock(&iaxsl[x]);
2133 /* We moved this call from a non-trunked to a trunked call */
2134 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2139 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2141 if (!pvt->transfercallno) {
2142 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2146 ao2_link(iax_transfercallno_pvts, pvt);
2149 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2151 if (!pvt->transfercallno) {
2152 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2156 ao2_unlink(iax_transfercallno_pvts, pvt);
2158 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2160 if (!pvt->peercallno) {
2161 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2165 ao2_link(iax_peercallno_pvts, pvt);
2168 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2170 if (!pvt->peercallno) {
2171 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2175 ao2_unlink(iax_peercallno_pvts, pvt);
2178 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2180 struct addr_range *lim = obj;
2185 static int addr_range_hash_cb(const void *obj, const int flags)
2187 const struct addr_range *lim = obj;
2188 struct sockaddr_in sin;
2189 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2190 return abs((int) sin.sin_addr.s_addr);
2193 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2195 struct addr_range *lim1 = obj, *lim2 = arg;
2196 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2197 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2198 CMP_MATCH | CMP_STOP : 0;
2201 static int peercnt_hash_cb(const void *obj, const int flags)
2203 const struct peercnt *peercnt = obj;
2204 return abs((int) peercnt->addr);
2207 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2209 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2210 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2213 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2215 struct addr_range *addr_range = obj;
2216 struct sockaddr_in *sin = arg;
2217 struct sockaddr_in ha_netmask_sin;
2218 struct sockaddr_in ha_addr_sin;
2220 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2221 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2223 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2224 return CMP_MATCH | CMP_STOP;
2232 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2234 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2236 struct addr_range *addr_range;
2237 struct iax2_peer *peer = NULL;
2238 struct iax2_user *user = NULL;
2239 /* if no username is given, check for guest accounts */
2240 const char *find = S_OR(name, "guest");
2241 int res = 1; /* required by default */
2243 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2244 /* There are only two cases in which calltoken validation is not required.
2245 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2246 * the peer definition has not set the requirecalltoken option.
2247 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2250 /* ----- Case 1 ----- */
2251 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2252 ao2_ref(addr_range, -1);
2256 /* ----- Case 2 ----- */
2257 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2258 calltoken_required = user->calltoken_required;
2259 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2260 calltoken_required = user->calltoken_required;
2261 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2262 calltoken_required = peer->calltoken_required;
2263 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2264 calltoken_required = peer->calltoken_required;
2274 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);
2275 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2276 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2286 * \brief set peercnt callno limit.
2289 * First looks in custom definitions. If not found, global limit
2290 * is used. Entries marked as reg already have
2291 * a custom limit set by a registration and are not modified.
2293 static void set_peercnt_limit(struct peercnt *peercnt)
2295 uint16_t limit = global_maxcallno;
2296 struct addr_range *addr_range;
2297 struct sockaddr_in sin = {
2298 .sin_addr.s_addr = peercnt->addr,
2302 if (peercnt->reg && peercnt->limit) {
2303 return; /* this peercnt has a custom limit set by a registration */
2306 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2307 limit = addr_range->limit;
2308 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2309 ao2_ref(addr_range, -1);
2312 peercnt->limit = limit;
2317 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2319 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2321 struct peercnt *peercnt = obj;
2323 set_peercnt_limit(peercnt);
2324 ast_debug(1, "Reset limits for peercnts table\n");
2331 * \brief returns match if delme is set.
2333 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2335 struct addr_range *addr_range = obj;
2337 return addr_range->delme ? CMP_MATCH : 0;
2342 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2344 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2346 /* this function turns off and on custom callno limits set by peer registration */
2347 struct peercnt *peercnt;
2348 struct peercnt tmp = {
2351 struct sockaddr_in sin;
2353 ast_sockaddr_to_sin(sockaddr, &sin);
2355 tmp.addr = sin.sin_addr.s_addr;
2357 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2360 peercnt->limit = limit;
2362 set_peercnt_limit(peercnt);
2364 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2365 ao2_ref(peercnt, -1); /* decrement ref from find */
2371 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2373 * \details First searches for the address in the peercnts table. If found
2374 * the current count is incremented. If not found a new peercnt is allocated
2375 * and linked into the peercnts table with a call number count of 1.
2377 static int peercnt_add(struct sockaddr_in *sin)
2379 struct peercnt *peercnt;
2380 unsigned long addr = sin->sin_addr.s_addr;
2382 struct peercnt tmp = {
2386 /* Reasoning for peercnts container lock: Two identical ip addresses
2387 * could be added by different threads at the "same time". Without the container
2388 * lock, both threads could alloc space for the same object and attempt
2389 * to link to table. With the lock, one would create the object and link
2390 * to table while the other would find the already created peercnt object
2391 * rather than creating a new one. */
2393 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2395 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2397 /* create and set defaults */
2398 peercnt->addr = addr;
2399 set_peercnt_limit(peercnt);
2400 /* guarantees it does not go away after unlocking table
2401 * ao2_find automatically adds this */
2402 ao2_link(peercnts, peercnt);
2404 ao2_unlock(peercnts);
2408 /* check to see if the address has hit its callno limit. If not increment cur. */
2409 if (peercnt->limit > peercnt->cur) {
2411 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2412 } else { /* max num call numbers for this peer has been reached! */
2413 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2417 /* clean up locks and ref count */
2418 ao2_unlock(peercnt);
2419 ao2_unlock(peercnts);
2420 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2427 * \brief decrements a peercnts table entry
2429 static void peercnt_remove(struct peercnt *peercnt)
2431 struct sockaddr_in sin = {
2432 .sin_addr.s_addr = peercnt->addr,
2436 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2437 * peercnt_add could try and grab this entry from the table and modify it at the
2438 * "same time" this thread attemps to unlink it.*/
2441 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2442 /* if this was the last connection from the peer remove it from table */
2443 if (peercnt->cur == 0) {
2444 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2446 ao2_unlock(peercnts);
2452 * \brief called by scheduler to decrement object
2454 static int peercnt_remove_cb(const void *obj)
2456 struct peercnt *peercnt = (struct peercnt *) obj;
2458 peercnt_remove(peercnt);
2459 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2466 * \brief decrements peercnts connection count, finds by addr
2468 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2470 struct peercnt *peercnt;
2471 struct peercnt tmp = {
2472 .addr = sin->sin_addr.s_addr,
2475 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2476 peercnt_remove(peercnt);
2477 ao2_ref(peercnt, -1); /* decrement ref from find */
2484 * \brief Create callno_limit entry based on configuration
2486 static void build_callno_limits(struct ast_variable *v)
2488 struct addr_range *addr_range = NULL;
2489 struct addr_range tmp;
2495 for (; v; v = v->next) {
2499 ha = ast_append_ha("permit", v->name, NULL, &error);
2501 /* check for valid config information */
2503 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2505 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2506 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2511 ast_copy_ha(ha, &tmp.ha);
2512 /* find or create the addr_range */
2513 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2514 ao2_lock(addr_range);
2516 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2518 return; /* out of memory */
2521 /* copy over config data into addr_range object */
2522 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2523 ast_free_ha(ha); /* cleanup the tmp ha */
2524 addr_range->limit = limit;
2525 addr_range->delme = 0;
2529 ao2_unlock(addr_range);
2531 ao2_link(callno_limits, addr_range);
2533 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2539 * \brief Create calltoken_ignores entry based on configuration
2541 static int add_calltoken_ignore(const char *addr)
2543 struct addr_range tmp;
2544 struct addr_range *addr_range = NULL;
2545 struct ast_ha *ha = NULL;
2548 if (ast_strlen_zero(addr)) {
2549 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2553 ha = ast_append_ha("permit", addr, NULL, &error);
2555 /* check for valid config information */
2557 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2561 ast_copy_ha(ha, &tmp.ha);
2562 /* find or create the addr_range */
2563 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2564 ao2_lock(addr_range);
2565 addr_range->delme = 0;
2566 ao2_unlock(addr_range);
2567 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2568 /* copy over config data into addr_range object */
2569 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2570 ao2_link(calltoken_ignores, addr_range);
2577 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2582 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2584 struct ao2_iterator i;
2585 struct peercnt *peercnt;
2586 struct sockaddr_in sin;
2591 e->command = "iax2 show callnumber usage";
2593 "Usage: iax2 show callnumber usage [IP address]\n"
2594 " Shows current IP addresses which are consuming iax2 call numbers\n";
2599 if (a->argc < 4 || a->argc > 5)
2600 return CLI_SHOWUSAGE;
2603 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2606 i = ao2_iterator_init(peercnts, 0);
2607 while ((peercnt = ao2_iterator_next(&i))) {
2608 sin.sin_addr.s_addr = peercnt->addr;
2610 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2611 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2612 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2613 ao2_ref(peercnt, -1);
2618 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2620 ao2_ref(peercnt, -1);
2622 ao2_iterator_destroy(&i);
2625 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2626 "Non-CallToken Validated Callno Used: %d\n",
2627 global_maxcallno_nonval,
2628 total_nonval_callno_used);
2630 ast_cli(a->fd, "Total Available Callno: %d\n"
2631 "Regular Callno Available: %d\n"
2632 "Trunk Callno Available: %d\n",
2633 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2634 ao2_container_count(callno_pool),
2635 ao2_container_count(callno_pool_trunk));
2636 } else if (a->argc == 5 && !found) {
2637 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2647 static struct callno_entry *get_unused_callno(int trunk, int validated)
2649 struct callno_entry *callno_entry = NULL;
2650 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2651 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2652 /* Minor optimization for the extreme case. */
2656 /* the callno_pool container is locked here primarily to ensure thread
2657 * safety of the total_nonval_callno_used check and increment */
2658 ao2_lock(callno_pool);
2660 /* only a certain number of nonvalidated call numbers should be allocated.
2661 * If there ever is an attack, this separates the calltoken validating
2662 * users from the non calltoken validating users. */
2663 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2664 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2665 ao2_unlock(callno_pool);
2669 /* unlink the object from the container, taking over ownership
2670 * of the reference the container had to the object */
2671 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2674 callno_entry->validated = validated;
2676 total_nonval_callno_used++;
2680 ao2_unlock(callno_pool);
2681 return callno_entry;
2684 static int replace_callno(const void *obj)
2686 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2688 /* the callno_pool container is locked here primarily to ensure thread
2689 * safety of the total_nonval_callno_used check and decrement */
2690 ao2_lock(callno_pool);
2692 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2693 total_nonval_callno_used--;
2694 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2695 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2698 if (callno_entry->callno < TRUNK_CALL_START) {
2699 ao2_link(callno_pool, callno_entry);
2701 ao2_link(callno_pool_trunk, callno_entry);
2703 ao2_ref(callno_entry, -1); /* only container ref remains */
2705 ao2_unlock(callno_pool);
2709 static int callno_hash(const void *obj, const int flags)
2711 return abs(ast_random());
2714 static int create_callno_pools(void)
2718 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2722 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2726 /* start at 2, 0 and 1 are reserved */
2727 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2728 struct callno_entry *callno_entry;
2730 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2734 callno_entry->callno = i;
2736 if (i < TRUNK_CALL_START) {
2737 ao2_link(callno_pool, callno_entry);
2739 ao2_link(callno_pool_trunk, callno_entry);
2742 ao2_ref(callno_entry, -1);
2750 * \brief Schedules delayed removal of iax2_pvt call number data
2752 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2753 * avaliable again, and the address from the previous connection must be decremented
2754 * from the peercnts table. This function schedules these operations to take place.
2756 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2759 struct peercnt *peercnt;
2760 struct peercnt tmp = {
2761 .addr = sin->sin_addr.s_addr,
2764 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2765 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2766 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2767 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2769 ao2_ref(peercnt, -1);
2773 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2778 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2780 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2783 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2785 if (frametype != AST_FRAME_IAX) {
2789 case IAX_COMMAND_NEW:
2790 case IAX_COMMAND_REGREQ:
2791 case IAX_COMMAND_FWDOWNL:
2792 case IAX_COMMAND_REGREL:
2794 case IAX_COMMAND_POKE:
2804 * \note Calling this function while holding another pvt lock can cause a deadlock.
2806 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2810 /* this call is calltoken validated as long as it is either NEW_FORCE
2811 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2812 int validated = (new > NEW_ALLOW) ? 1 : 0;
2815 if (new <= NEW_ALLOW) {
2817 struct chan_iax2_pvt *pvt;
2818 struct chan_iax2_pvt tmp_pvt = {
2820 .peercallno = callno,
2821 .transfercallno = callno,
2823 .frames_received = check_dcallno,
2826 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2827 /* this works for finding normal call numbers not involving transfering */
2828 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2829 if (return_locked) {
2830 ast_mutex_lock(&iaxsl[pvt->callno]);
2837 /* this searches for transfer call numbers that might not get caught otherwise */
2838 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2839 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2840 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2841 if (return_locked) {
2842 ast_mutex_lock(&iaxsl[pvt->callno]);
2850 /* This will occur on the first response to a message that we initiated,
2851 * such as a PING. */
2853 ast_mutex_lock(&iaxsl[dcallno]);
2855 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2856 iaxs[dcallno]->peercallno = callno;
2858 store_by_peercallno(iaxs[dcallno]);
2859 if (!res || !return_locked) {
2860 ast_mutex_unlock(&iaxsl[dcallno]);
2865 ast_mutex_unlock(&iaxsl[dcallno]);
2868 if (!res && (new >= NEW_ALLOW)) {
2869 struct callno_entry *callno_entry;
2870 /* It may seem odd that we look through the peer list for a name for
2871 * this *incoming* call. Well, it is weird. However, users don't
2872 * have an IP address/port number that we can match against. So,
2873 * this is just checking for a peer that has that IP/port and
2874 * assuming that we have a user of the same name. This isn't always
2875 * correct, but it will be changed if needed after authentication. */
2876 if (!iax2_getpeername(*sin, host, sizeof(host)))
2877 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2879 if (peercnt_add(sin)) {
2880 /* This address has hit its callnumber limit. When the limit
2881 * is reached, the connection is not added to the peercnts table.*/
2885 if (!(callno_entry = get_unused_callno(0, validated))) {
2886 /* since we ran out of space, remove the peercnt
2887 * entry we added earlier */
2888 peercnt_remove_by_addr(sin);
2889 ast_log(LOG_WARNING, "No more space\n");
2892 x = callno_entry->callno;
2893 ast_mutex_lock(&iaxsl[x]);
2895 iaxs[x] = new_iax(sin, host);
2898 ast_debug(1, "Creating new call structure %d\n", x);
2899 iaxs[x]->callno_entry = callno_entry;
2900 iaxs[x]->sockfd = sockfd;
2901 iaxs[x]->addr.sin_port = sin->sin_port;
2902 iaxs[x]->addr.sin_family = sin->sin_family;
2903 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2904 iaxs[x]->peercallno = callno;
2905 iaxs[x]->callno = x;
2906 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2907 iaxs[x]->expiry = min_reg_expire;
2908 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2909 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2910 iaxs[x]->amaflags = amaflags;
2911 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2912 ast_string_field_set(iaxs[x], accountcode, accountcode);
2913 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2914 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2915 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2917 if (iaxs[x]->peercallno) {
2918 store_by_peercallno(iaxs[x]);
2921 ast_log(LOG_WARNING, "Out of resources\n");
2922 ast_mutex_unlock(&iaxsl[x]);
2923 replace_callno(callno_entry);
2927 ast_mutex_unlock(&iaxsl[x]);
2933 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2934 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2937 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2939 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2943 * \brief Queue a frame to a call's owning asterisk channel
2945 * \pre This function assumes that iaxsl[callno] is locked when called.
2947 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2948 * was valid before calling it, it may no longer be valid after calling it.
2949 * This function may unlock and lock the mutex associated with this callno,
2950 * meaning that another thread may grab it and destroy the call.
2952 static int iax2_queue_frame(int callno, struct ast_frame *f)
2954 iax2_lock_owner(callno);
2955 if (iaxs[callno] && iaxs[callno]->owner) {
2956 ast_queue_frame(iaxs[callno]->owner, f);
2957 ast_channel_unlock(iaxs[callno]->owner);
2963 * \brief Queue a hangup frame on the ast_channel owner
2965 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2966 * is active for the given call number.
2968 * \pre Assumes lock for callno is already held.
2970 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2971 * was valid before calling it, it may no longer be valid after calling it.
2972 * This function may unlock and lock the mutex associated with this callno,
2973 * meaning that another thread may grab it and destroy the call.
2975 static int iax2_queue_hangup(int callno)
2977 iax2_lock_owner(callno);
2978 if (iaxs[callno] && iaxs[callno]->owner) {
2979 ast_queue_hangup(iaxs[callno]->owner);
2980 ast_channel_unlock(iaxs[callno]->owner);
2986 * \brief Queue a control frame on the ast_channel owner
2988 * This function queues a control frame on the owner of the IAX2 pvt struct that
2989 * is active for the given call number.
2991 * \pre Assumes lock for callno is already held.
2993 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2994 * was valid before calling it, it may no longer be valid after calling it.
2995 * This function may unlock and lock the mutex associated with this callno,
2996 * meaning that another thread may grab it and destroy the call.
2998 static int iax2_queue_control_data(int callno,
2999 enum ast_control_frame_type control, const void *data, size_t datalen)
3001 iax2_lock_owner(callno);
3002 if (iaxs[callno] && iaxs[callno]->owner) {
3003 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3004 ast_channel_unlock(iaxs[callno]->owner);
3008 static void destroy_firmware(struct iax_firmware *cur)
3010 /* Close firmware */
3012 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3018 static int try_firmware(char *s)
3021 struct iax_firmware *cur = NULL;
3022 int ifd, fd, res, len, chunk;
3023 struct ast_iax2_firmware_header *fwh, fwh2;
3024 struct MD5Context md5;
3025 unsigned char sum[16], buf[1024];
3028 if (!(s2 = alloca(strlen(s) + 100))) {
3029 ast_log(LOG_WARNING, "Alloca failed!\n");
3033 last = strrchr(s, '/');
3039 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3041 if (stat(s, &stbuf) < 0) {
3042 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3046 /* Make sure it's not a directory */
3047 if (S_ISDIR(stbuf.st_mode))
3049 ifd = open(s, O_RDONLY);
3051 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3054 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3056 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3060 /* Unlink our newly created file */
3063 /* Now copy the firmware into it */
3064 len = stbuf.st_size;
3067 if (chunk > sizeof(buf))
3068 chunk = sizeof(buf);
3069 res = read(ifd, buf, chunk);
3071 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3076 res = write(fd, buf, chunk);
3078 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3086 /* Return to the beginning */
3087 lseek(fd, 0, SEEK_SET);
3088 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3089 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3093 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3094 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3098 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3099 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3103 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3104 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3108 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3109 if (fwh == MAP_FAILED) {
3110 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3115 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3116 MD5Final(sum, &md5);
3117 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3118 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3119 munmap((void*)fwh, stbuf.st_size);
3124 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3125 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3126 /* Found a candidate */
3127 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3128 /* The version we have on loaded is older, load this one instead */
3130 /* This version is no newer than what we have. Don't worry about it.
3131 We'll consider it a proper load anyhow though */
3132 munmap((void*)fwh, stbuf.st_size);
3138 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3140 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3145 munmap((void*)cur->fwh, cur->mmaplen);
3150 cur->mmaplen = stbuf.st_size;
3157 static int iax_check_version(char *dev)
3160 struct iax_firmware *cur = NULL;
3162 if (ast_strlen_zero(dev))
3165 AST_LIST_LOCK(&firmwares);
3166 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3167 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3168 res = ntohs(cur->fwh->version);
3172 AST_LIST_UNLOCK(&firmwares);
3177 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3180 unsigned int bs = desc & 0xff;
3181 unsigned int start = (desc >> 8) & 0xffffff;
3183 struct iax_firmware *cur;
3185 if (ast_strlen_zero((char *)dev) || !bs)
3190 AST_LIST_LOCK(&firmwares);
3191 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3192 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3194 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3195 if (start < ntohl(cur->fwh->datalen)) {
3196 bytes = ntohl(cur->fwh->datalen) - start;
3199 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3202 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3210 AST_LIST_UNLOCK(&firmwares);
3216 static void reload_firmware(int unload)
3218 struct iax_firmware *cur = NULL;
3221 char dir[256], fn[256];
3223 AST_LIST_LOCK(&firmwares);
3225 /* Mark all as dead */
3226 AST_LIST_TRAVERSE(&firmwares, cur, list)
3229 /* Now that we have marked them dead... load new ones */
3231 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3234 while((de = readdir(fwd))) {
3235 if (de->d_name[0] != '.') {
3236 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3237 if (!try_firmware(fn)) {
3238 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3244 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3247 /* Clean up leftovers */
3248 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3251 AST_LIST_REMOVE_CURRENT(list);
3252 destroy_firmware(cur);
3254 AST_LIST_TRAVERSE_SAFE_END;
3256 AST_LIST_UNLOCK(&firmwares);
3260 * \note This function assumes that iaxsl[callno] is locked when called.
3262 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3263 * was valid before calling it, it may no longer be valid after calling it.
3264 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3265 * associated with this callno, meaning that another thread may grab it and destroy the call.