2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
35 <use type="external">crypto</use>
36 <support_level>core</support_level>
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
51 #include <sys/signal.h>
59 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
61 #include "asterisk/lock.h"
62 #include "asterisk/frame.h"
63 #include "asterisk/channel.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/sched.h"
67 #include "asterisk/io.h"
68 #include "asterisk/config.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/translate.h"
71 #include "asterisk/md5.h"
72 #include "asterisk/cdr.h"
73 #include "asterisk/crypto.h"
74 #include "asterisk/acl.h"
75 #include "asterisk/manager.h"
76 #include "asterisk/callerid.h"
77 #include "asterisk/app.h"
78 #include "asterisk/astdb.h"
79 #include "asterisk/musiconhold.h"
80 #include "asterisk/features.h"
81 #include "asterisk/utils.h"
82 #include "asterisk/causes.h"
83 #include "asterisk/localtime.h"
84 #include "asterisk/dnsmgr.h"
85 #include "asterisk/devicestate.h"
86 #include "asterisk/netsock.h"
87 #include "asterisk/stringfields.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/event.h"
90 #include "asterisk/astobj2.h"
91 #include "asterisk/timing.h"
92 #include "asterisk/taskprocessor.h"
93 #include "asterisk/test.h"
94 #include "asterisk/data.h"
95 #include "asterisk/netsock2.h"
98 #include "iax2-parser.h"
99 #include "iax2-provision.h"
100 #include "jitterbuf.h"
103 <application name="IAX2Provision" language="en_US">
105 Provision a calling IAXy with a given template.
108 <parameter name="template">
109 <para>If not specified, defaults to <literal>default</literal>.</para>
113 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
114 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
115 or <literal>0</literal> on success.</para>
118 <function name="IAXPEER" language="en_US">
120 Gets IAX peer information.
123 <parameter name="peername" required="true">
125 <enum name="CURRENTCHANNEL">
126 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
127 endpoint of the current channel</para>
131 <parameter name="item">
132 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
135 <para>(default) The IP address.</para>
138 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
140 <enum name="mailbox">
141 <para>The configured mailbox.</para>
143 <enum name="context">
144 <para>The configured context.</para>
147 <para>The epoch time of the next expire.</para>
149 <enum name="dynamic">
150 <para>Is it dynamic? (yes/no).</para>
152 <enum name="callerid_name">
153 <para>The configured Caller ID name.</para>
155 <enum name="callerid_num">
156 <para>The configured Caller ID number.</para>
159 <para>The configured codecs.</para>
161 <enum name="codec[x]">
162 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
163 with <literal>0</literal>)</para>
168 <description></description>
170 <ref type="function">SIPPEER</ref>
173 <function name="IAXVAR" language="en_US">
175 Sets or retrieves a remote variable.
178 <parameter name="varname" required="true" />
180 <description></description>
182 <manager name="IAXpeers" language="en_US">
187 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
192 <manager name="IAXpeerlist" language="en_US">
197 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
200 <para>List all the IAX peers.</para>
203 <manager name="IAXnetstats" language="en_US">
209 <para>Show IAX channels network statistics.</para>
212 <manager name="IAXregistry" language="en_US">
214 Show IAX registrations.
217 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
220 <para>Show IAX registrations.</para>
225 /* Define SCHED_MULTITHREADED to run the scheduler in a special
226 multithreaded mode. */
227 #define SCHED_MULTITHREADED
229 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
230 thread is actually doing. */
231 #define DEBUG_SCHED_MULTITHREAD
235 static int nochecksums = 0;
238 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
239 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
241 #define DEFAULT_THREAD_COUNT 10
242 #define DEFAULT_MAX_THREAD_COUNT 100
243 #define DEFAULT_RETRY_TIME 1000
244 #define MEMORY_SIZE 100
245 #define DEFAULT_DROP 3
247 #define DEBUG_SUPPORT
249 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
251 /* Sample over last 100 units to determine historic jitter */
254 static struct ast_codec_pref prefs;
256 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
259 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
260 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
261 #define MAX_TRUNK_MTU 1240
263 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
264 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
266 #define DEFAULT_CONTEXT "default"
268 static char default_parkinglot[AST_MAX_CONTEXT];
270 static char language[MAX_LANGUAGE] = "";
271 static char regcontext[AST_MAX_CONTEXT] = "";
273 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
274 static int network_change_event_sched_id = -1;
276 static int maxauthreq = 3;
277 static int max_retries = 4;
278 static int ping_time = 21;
279 static int lagrq_time = 10;
280 static int maxjitterbuffer=1000;
281 static int resyncthreshold=1000;
282 static int maxjitterinterps=10;
283 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
285 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
287 static int trunkfreq = 20;
288 static int trunkmaxsize = MAX_TRUNKDATA;
290 static int authdebug = 0;
291 static int autokill = 0;
292 static int iaxcompat = 0;
293 static int last_authmethod = 0;
295 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
297 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
304 static int min_reg_expire;
305 static int max_reg_expire;
307 static int srvlookup = 0;
309 static struct ast_timer *timer; /* Timer for trunking */
311 static struct ast_netsock_list *netsock;
312 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
313 static int defaultsockfd = -1;
315 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
318 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
320 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
321 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
322 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
323 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
324 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
325 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
326 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
327 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
328 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
330 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
331 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
332 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
333 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
335 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
339 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
340 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
341 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
343 /* if a pvt has encryption setup done and is running on the call */
344 #define IAX_CALLENCRYPTED(pvt) \
345 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
347 #define IAX_DEBUGDIGEST(msg, key) do { \
349 char digest[33] = ""; \
354 for (idx = 0; idx < 16; idx++) \
355 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
357 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
360 static struct io_context *io;
361 static struct ast_sched_context *sched;
363 #define DONT_RESCHEDULE -2
365 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
367 static int iaxdebug = 0;
369 static int iaxtrunkdebug = 0;
371 static int test_losspct = 0;
373 static int test_late = 0;
374 static int test_resync = 0;
375 static int test_jit = 0;
376 static int test_jitpct = 0;
377 #endif /* IAXTESTS */
379 static char accountcode[AST_MAX_ACCOUNT_CODE];
380 static char mohinterpret[MAX_MUSICCLASS];
381 static char mohsuggest[MAX_MUSICCLASS];
382 static int amaflags = 0;
384 static int delayreject = 0;
385 static int iax2_encryption = 0;
387 static struct ast_flags64 globalflags = { 0 };
389 static pthread_t netthreadid = AST_PTHREADT_NULL;
392 IAX_STATE_STARTED = (1 << 0),
393 IAX_STATE_AUTHENTICATED = (1 << 1),
394 IAX_STATE_TBD = (1 << 2),
397 struct iax2_context {
398 char context[AST_MAX_CONTEXT];
399 struct iax2_context *next;
403 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
404 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
405 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
406 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
407 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
408 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
409 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
410 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
411 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
412 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
413 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
414 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
415 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
416 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
417 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
418 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
419 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
420 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
421 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
422 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
423 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
424 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
425 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
426 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
427 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
428 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
429 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
430 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
431 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
432 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
433 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
434 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
435 static int global_rtautoclear = 120;
437 static int reload_config(void);
440 * \brief Call token validation settings.
442 enum calltoken_peer_enum {
443 /*! \brief Default calltoken required unless the ip is in the ignorelist */
444 CALLTOKEN_DEFAULT = 0,
445 /*! \brief Require call token validation. */
447 /*! \brief Require call token validation after a successful registration
448 * using call token validation occurs. */
450 /*! \brief Do not require call token validation. */
455 AST_DECLARE_STRING_FIELDS(
456 AST_STRING_FIELD(name);
457 AST_STRING_FIELD(secret);
458 AST_STRING_FIELD(dbsecret);
459 AST_STRING_FIELD(accountcode);
460 AST_STRING_FIELD(mohinterpret);
461 AST_STRING_FIELD(mohsuggest);
462 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
463 AST_STRING_FIELD(language);
464 AST_STRING_FIELD(cid_num);
465 AST_STRING_FIELD(cid_name);
466 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
474 iax2_format capability;
475 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
476 int curauthreq; /*!< Current number of outstanding AUTHREQs */
477 struct ast_codec_pref prefs;
479 struct iax2_context *contexts;
480 struct ast_variable *vars;
481 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
485 AST_DECLARE_STRING_FIELDS(
486 AST_STRING_FIELD(name);
487 AST_STRING_FIELD(username);
488 AST_STRING_FIELD(description); /*!< Description of the peer */
489 AST_STRING_FIELD(secret);
490 AST_STRING_FIELD(dbsecret);
491 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
493 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
494 AST_STRING_FIELD(context); /*!< For transfers only */
495 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
496 AST_STRING_FIELD(mailbox); /*!< Mailbox */
497 AST_STRING_FIELD(mohinterpret);
498 AST_STRING_FIELD(mohsuggest);
499 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
500 /* Suggested caller id if registering */
501 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
502 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
503 AST_STRING_FIELD(zonetag); /*!< Time Zone */
504 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
506 struct ast_codec_pref prefs;
507 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
508 struct ast_sockaddr addr;
510 int sockfd; /*!< Socket to use for transmission */
515 /* Dynamic Registration fields */
516 struct sockaddr_in defaddr; /*!< Default address if there is one */
517 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
518 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
520 int expire; /*!< Schedule entry for expiry */
521 int expiry; /*!< How soon to expire */
522 iax2_format capability; /*!< Capability */
525 int callno; /*!< Call number of POKE request */
526 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
527 int lastms; /*!< How long last response took (in ms), or -1 for no response */
528 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
530 int pokefreqok; /*!< How often to check if the host is up */
531 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
532 int historicms; /*!< How long recent average responses took */
533 int smoothing; /*!< Sample over how many units to determine historic ms */
534 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
536 struct ast_event_sub *mwi_event_sub;
539 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
542 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
544 struct iax2_trunk_peer {
547 struct sockaddr_in addr;
548 struct timeval txtrunktime; /*!< Transmit trunktime */
549 struct timeval rxtrunktime; /*!< Receive trunktime */
550 struct timeval lasttxtime; /*!< Last transmitted trunktime */
551 struct timeval trunkact; /*!< Last trunk activity */
552 unsigned int lastsent; /*!< Last sent time */
553 /* Trunk data and length */
554 unsigned char *trunkdata;
555 unsigned int trunkdatalen;
556 unsigned int trunkdataalloc;
560 AST_LIST_ENTRY(iax2_trunk_peer) list;
563 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
565 struct iax_firmware {
566 AST_LIST_ENTRY(iax_firmware) list;
570 struct ast_iax2_firmware_header *fwh;
575 REG_STATE_UNREGISTERED = 0,
578 REG_STATE_REGISTERED,
584 enum iax_transfer_state {
589 TRANSFER_PASSTHROUGH,
593 TRANSFER_MPASSTHROUGH,
598 struct iax2_registry {
599 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
601 char secret[80]; /*!< Password or key name in []'s */
602 int expire; /*!< Sched ID of expiration */
603 int refresh; /*!< How often to refresh */
604 enum iax_reg_state regstate;
605 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
606 int callno; /*!< Associated call number if applicable */
607 struct sockaddr_in us; /*!< Who the server thinks we are */
608 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
609 AST_LIST_ENTRY(iax2_registry) entry;
612 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
614 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
615 #define MIN_RETRY_TIME 100
616 #define MAX_RETRY_TIME 10000
618 #define MAX_JITTER_BUFFER 50
619 #define MIN_JITTER_BUFFER 10
621 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
623 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
625 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
626 #define TS_GAP_FOR_JB_RESYNC 5000
628 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
629 #define MARK_IAX_SUBCLASS_TX 0x8000
631 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
632 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
633 static int iaxdynamicthreadcount = 0;
634 static int iaxdynamicthreadnum = 0;
635 static int iaxactivethreadcount = 0;
649 struct chan_iax2_pvt {
650 /*! Socket to send/receive on for this call */
652 /*! Last received voice format */
653 iax2_format voiceformat;
654 /*! Last received video format */
655 iax2_format videoformat;
656 /*! Last sent voice format */
657 iax2_format svoiceformat;
658 /*! Last sent video format */
659 iax2_format svideoformat;
660 /*! What we are capable of sending */
661 iax2_format capability;
662 /*! Last received timestamp */
664 /*! Last sent timestamp - never send the same timestamp twice in a single call */
665 unsigned int lastsent;
666 /*! Timestamp of the last video frame sent */
667 unsigned int lastvsent;
668 /*! Next outgoing timestamp if everything is good */
669 unsigned int nextpred;
670 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
671 int first_iax_message;
672 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
673 int last_iax_message;
674 /*! True if the last voice we transmitted was not silence/CNG */
675 unsigned int notsilenttx:1;
677 unsigned int pingtime;
678 /*! Max time for initial response */
681 struct sockaddr_in addr;
682 /*! Actual used codec preferences */
683 struct ast_codec_pref prefs;
684 /*! Requested codec preferences */
685 struct ast_codec_pref rprefs;
686 /*! Our call number */
687 unsigned short callno;
688 /*! Our callno_entry entry */
689 struct callno_entry *callno_entry;
691 unsigned short peercallno;
692 /*! Negotiated format, this is only used to remember what format was
693 chosen for an unauthenticated call so that the channel can get
694 created later using the right format */
695 iax2_format chosenformat;
696 /*! Peer selected format */
697 iax2_format peerformat;
698 /*! Peer capability */
699 iax2_format peercapability;
700 /*! timeval that we base our transmission on */
701 struct timeval offset;
702 /*! timeval that we base our delivery on */
703 struct timeval rxcore;
704 /*! The jitterbuffer */
706 /*! active jb read scheduler id */
710 /*! Error, as discovered by the manager */
712 /*! Owner if we have one */
713 struct ast_channel *owner;
714 /*! What's our state? */
715 struct ast_flags state;
716 /*! Expiry (optional) */
718 /*! Next outgoing sequence number */
719 unsigned char oseqno;
720 /*! Next sequence number they have not yet acknowledged */
721 unsigned char rseqno;
722 /*! Next incoming sequence number */
723 unsigned char iseqno;
724 /*! Last incoming sequence number we have acknowledged */
725 unsigned char aseqno;
727 AST_DECLARE_STRING_FIELDS(
729 AST_STRING_FIELD(peer);
730 /*! Default Context */
731 AST_STRING_FIELD(context);
732 /*! Caller ID if available */
733 AST_STRING_FIELD(cid_num);
734 AST_STRING_FIELD(cid_name);
735 /*! Hidden Caller ID (i.e. ANI) if appropriate */
736 AST_STRING_FIELD(ani);
738 AST_STRING_FIELD(dnid);
740 AST_STRING_FIELD(rdnis);
741 /*! Requested Extension */
742 AST_STRING_FIELD(exten);
743 /*! Expected Username */
744 AST_STRING_FIELD(username);
745 /*! Expected Secret */
746 AST_STRING_FIELD(secret);
748 AST_STRING_FIELD(challenge);
749 /*! Public keys permitted keys for incoming authentication */
750 AST_STRING_FIELD(inkeys);
751 /*! Private key for outgoing authentication */
752 AST_STRING_FIELD(outkey);
753 /*! Preferred language */
754 AST_STRING_FIELD(language);
755 /*! Hostname/peername for naming purposes */
756 AST_STRING_FIELD(host);
758 AST_STRING_FIELD(dproot);
759 AST_STRING_FIELD(accountcode);
760 AST_STRING_FIELD(mohinterpret);
761 AST_STRING_FIELD(mohsuggest);
762 /*! received OSP token */
763 AST_STRING_FIELD(osptoken);
764 /*! Default parkinglot */
765 AST_STRING_FIELD(parkinglot);
767 /*! AUTHREJ all AUTHREP frames */
769 /*! permitted authentication methods */
771 /*! permitted encryption methods */
773 /*! Encryption AES-128 Key */
774 ast_aes_encrypt_key ecx;
775 /*! Decryption AES-128 Key corresponding to ecx */
776 ast_aes_decrypt_key mydcx;
777 /*! Decryption AES-128 Key used to decrypt peer frames */
778 ast_aes_decrypt_key dcx;
779 /*! scheduler id associated with iax_key_rotate
780 * for encrypted calls*/
782 /*! 32 bytes of semi-random data */
783 unsigned char semirand[32];
784 /*! Associated registry */
785 struct iax2_registry *reg;
786 /*! Associated peer for poking */
787 struct iax2_peer *peerpoke;
792 /*! Transferring status */
793 enum iax_transfer_state transferring;
794 /*! Transfer identifier */
796 /*! Who we are IAX transferring to */
797 struct sockaddr_in transfer;
798 /*! What's the new call number for the transfer */
799 unsigned short transfercallno;
800 /*! Transfer encrypt AES-128 Key */
801 ast_aes_encrypt_key tdcx;
803 /*! Status of knowledge of peer ADSI capability */
806 /*! Who we are bridged to */
807 unsigned short bridgecallno;
809 int pingid; /*!< Transmit PING request */
810 int lagid; /*!< Retransmit lag request */
811 int autoid; /*!< Auto hangup for Dialplan requestor */
812 int authid; /*!< Authentication rejection ID */
813 int authfail; /*!< Reason to report failure */
814 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
819 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
820 /*! variables inherited from the user definition */
821 struct ast_variable *vars;
822 /*! variables transmitted in a NEW packet */
823 struct ast_variable *iaxvars;
824 /*! last received remote rr */
825 struct iax_rr remote_rr;
826 /*! Current base time: (just for stats) */
828 /*! Dropped frame count: (just for stats) */
830 /*! received frame count: (just for stats) */
832 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
833 unsigned char calltoken_ie_len;
834 /*! hold all signaling frames from the pbx thread until we have a destination callno */
836 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
837 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
840 struct signaling_queue_entry {
842 AST_LIST_ENTRY(signaling_queue_entry) next;
845 /*! table of available call numbers */
846 static struct ao2_container *callno_pool;
848 /*! table of available trunk call numbers */
849 static struct ao2_container *callno_pool_trunk;
851 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
854 * \brief a list of frames that may need to be retransmitted
856 * \note The contents of this list do not need to be explicitly destroyed
857 * on module unload. This is because all active calls are destroyed, and
858 * all frames in this queue will get destroyed as a part of that process.
860 * \note Contents protected by the iaxsl[] locks
862 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
864 static struct ast_taskprocessor *transmit_processor;
866 static int randomcalltokendata;
868 static const time_t MAX_CALLTOKEN_DELAY = 10;
871 * This module will get much higher performance when doing a lot of
872 * user and peer lookups if the number of buckets is increased from 1.
873 * However, to maintain old behavior for Asterisk 1.4, these are set to
874 * 1 by default. When using multiple buckets, search order through these
875 * containers is considered random, so you will not be able to depend on
876 * the order the entires are specified in iax.conf for matching order. */
878 #define MAX_PEER_BUCKETS 17
880 #define MAX_PEER_BUCKETS 563
882 static struct ao2_container *peers;
884 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
885 static struct ao2_container *users;
887 /*! Table containing peercnt objects for every ip address consuming a callno */
888 static struct ao2_container *peercnts;
890 /*! Table containing custom callno limit rules for a range of ip addresses. */
891 static struct ao2_container *callno_limits;
893 /*! Table containing ip addresses not requiring calltoken validation */
894 static struct ao2_container *calltoken_ignores;
896 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
898 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
900 static uint16_t global_maxcallno;
902 /*! Total num of call numbers allowed to be allocated without calltoken validation */
903 static uint16_t global_maxcallno_nonval;
905 static uint16_t total_nonval_callno_used = 0;
907 /*! peer connection private, keeps track of all the call numbers
908 * consumed by a single ip address */
910 /*! ip address consuming call numbers */
912 /*! Number of call numbers currently used by this ip address */
914 /*! Max call numbers allowed for this ip address */
916 /*! Specifies whether limit is set by a registration or not, if so normal
917 * limit setting rules do not apply to this address. */
921 /*! used by both callno_limits and calltoken_ignores containers */
923 /*! ip address range for custom callno limit rule */
925 /*! callno limit for this ip address range, only used in callno_limits container */
927 /*! delete me marker for reloads */
931 struct callno_entry {
932 /*! callno used for this entry */
934 /*! was this callno calltoken validated or not */
935 unsigned char validated;
938 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
941 /*! Extension exists */
942 CACHE_FLAG_EXISTS = (1 << 0),
943 /*! Extension is nonexistent */
944 CACHE_FLAG_NONEXISTENT = (1 << 1),
945 /*! Extension can exist */
946 CACHE_FLAG_CANEXIST = (1 << 2),
947 /*! Waiting to hear back response */
948 CACHE_FLAG_PENDING = (1 << 3),
950 CACHE_FLAG_TIMEOUT = (1 << 4),
951 /*! Request transmitted */
952 CACHE_FLAG_TRANSMITTED = (1 << 5),
954 CACHE_FLAG_UNKNOWN = (1 << 6),
956 CACHE_FLAG_MATCHMORE = (1 << 7),
959 struct iax2_dpcache {
960 char peercontext[AST_MAX_CONTEXT];
961 char exten[AST_MAX_EXTENSION];
963 struct timeval expiry;
965 unsigned short callno;
967 AST_LIST_ENTRY(iax2_dpcache) cache_list;
968 AST_LIST_ENTRY(iax2_dpcache) peer_list;
971 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
973 static void reg_source_db(struct iax2_peer *p);
974 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
975 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
977 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
978 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
979 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
981 enum iax2_thread_iostate {
984 IAX_IOSTATE_PROCESSING,
985 IAX_IOSTATE_SCHEDREADY,
988 enum iax2_thread_type {
989 IAX_THREAD_TYPE_POOL,
990 IAX_THREAD_TYPE_DYNAMIC,
993 struct iax2_pkt_buf {
994 AST_LIST_ENTRY(iax2_pkt_buf) entry;
996 unsigned char buf[1];
1000 AST_LIST_ENTRY(iax2_thread) list;
1001 enum iax2_thread_type type;
1002 enum iax2_thread_iostate iostate;
1003 #ifdef SCHED_MULTITHREADED
1004 void (*schedfunc)(const void *);
1005 const void *scheddata;
1007 #ifdef DEBUG_SCHED_MULTITHREAD
1013 struct sockaddr_in iosin;
1014 unsigned char readbuf[4096];
1022 ast_mutex_t init_lock;
1023 ast_cond_t init_cond;
1024 /*! if this thread is processing a full frame,
1025 some information about that frame will be stored
1026 here, so we can avoid dispatching any more full
1027 frames for that callno to other threads */
1029 unsigned short callno;
1030 struct sockaddr_in sin;
1034 /*! Queued up full frames for processing. If more full frames arrive for
1035 * a call which this thread is already processing a full frame for, they
1036 * are queued up here. */
1037 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1042 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1043 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1044 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1046 static void *iax2_process_thread(void *data);
1047 static void iax2_destroy(int callno);
1049 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1051 ast_mutex_lock(lock);
1052 ast_cond_signal(cond);
1053 ast_mutex_unlock(lock);
1057 * \brief an array of iax2 pvt structures
1059 * The container for active chan_iax2_pvt structures is implemented as an
1060 * array for extremely quick direct access to the correct pvt structure
1061 * based on the local call number. The local call number is used as the
1062 * index into the array where the associated pvt structure is stored.
1064 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1067 * \brief Another container of iax2_pvt structures
1069 * Active IAX2 pvt structs are also stored in this container, if they are a part
1070 * of an active call where we know the remote side's call number. The reason
1071 * for this is that incoming media frames do not contain our call number. So,
1072 * instead of having to iterate the entire iaxs array, we use this container to
1073 * look up calls where the remote side is using a given call number.
1075 static struct ao2_container *iax_peercallno_pvts;
1078 * \brief chan_iax2_pvt structure locks
1080 * These locks are used when accessing a pvt structure in the iaxs array.
1081 * The index used here is the same as used in the iaxs array. It is the
1082 * local call number for the associated pvt struct.
1084 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1087 * * \brief Another container of iax2_pvt structures
1089 * Active IAX2 pvt stucts used during transfering a call are stored here.
1091 static struct ao2_container *iax_transfercallno_pvts;
1093 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1094 but keeps the division between trunked and non-trunked better. */
1095 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1097 /* Debug routines... */
1098 static struct sockaddr_in debugaddr;
1100 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1103 (sin && debugaddr.sin_addr.s_addr &&
1104 (!ntohs(debugaddr.sin_port) ||
1105 debugaddr.sin_port == sin->sin_port) &&
1106 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1108 iax_showframe(f, fhi, rx, sin, datalen);
1111 iax_showframe(f, fhi, rx, sin, datalen);
1117 static void iax_debug_output(const char *data)
1120 ast_verbose("%s", data);
1123 static void iax_error_output(const char *data)
1125 ast_log(LOG_WARNING, "%s", data);
1128 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1133 va_start(args, fmt);
1134 vsnprintf(buf, sizeof(buf), fmt, args);
1137 ast_log(LOG_ERROR, "%s", buf);
1140 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1145 va_start(args, fmt);
1146 vsnprintf(buf, sizeof(buf), fmt, args);
1149 ast_log(LOG_WARNING, "%s", buf);
1152 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1157 va_start(args, fmt);
1158 vsnprintf(buf, sizeof(buf), fmt, args);
1161 ast_verbose("%s", buf);
1164 static int maxtrunkcall = TRUNK_CALL_START;
1165 static int maxnontrunkcall = 1;
1167 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);
1168 static int expire_registry(const void *data);
1169 static int iax2_answer(struct ast_channel *c);
1170 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1171 static int iax2_devicestate(void *data);
1172 static int iax2_digit_begin(struct ast_channel *c, char digit);
1173 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1174 static int iax2_do_register(struct iax2_registry *reg);
1175 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1176 static int iax2_hangup(struct ast_channel *c);
1177 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1178 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1179 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1180 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1181 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1182 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1183 static int iax2_sendtext(struct ast_channel *c, const char *text);
1184 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1185 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1186 static int iax2_transfer(struct ast_channel *c, const char *dest);
1187 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1188 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1190 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1191 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1192 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1193 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1194 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1195 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1196 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause);
1197 static struct ast_frame *iax2_read(struct ast_channel *c);
1198 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1199 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1200 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1201 static void *iax2_dup_variable_datastore(void *);
1202 static void prune_peers(void);
1203 static void prune_users(void);
1204 static void iax2_free_variable_datastore(void *);
1206 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1207 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1208 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1209 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1210 static void build_rand_pad(unsigned char *buf, ssize_t len);
1211 static struct callno_entry *get_unused_callno(int trunk, int validated);
1212 static int replace_callno(const void *obj);
1213 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1214 static void network_change_event_cb(const struct ast_event *, void *);
1216 static struct ast_channel_tech iax2_tech = {
1218 .description = tdesc,
1219 .properties = AST_CHAN_TP_WANTSJITTER,
1220 .requester = iax2_request,
1221 .devicestate = iax2_devicestate,
1222 .send_digit_begin = iax2_digit_begin,
1223 .send_digit_end = iax2_digit_end,
1224 .send_text = iax2_sendtext,
1225 .send_image = iax2_sendimage,
1226 .send_html = iax2_sendhtml,
1228 .hangup = iax2_hangup,
1229 .answer = iax2_answer,
1231 .write = iax2_write,
1232 .write_video = iax2_write,
1233 .indicate = iax2_indicate,
1234 .setoption = iax2_setoption,
1235 .queryoption = iax2_queryoption,
1236 .bridge = iax2_bridge,
1237 .transfer = iax2_transfer,
1238 .fixup = iax2_fixup,
1239 .func_channel_read = acf_channel_read,
1244 * \brief Obtain the owner channel lock if the owner exists.
1246 * \param callno IAX2 call id.
1248 * \note Assumes the iaxsl[callno] lock is already obtained.
1251 * IMPORTANT NOTE!!! Any time this function is used, even if
1252 * iaxs[callno] was valid before calling it, it may no longer be
1253 * valid after calling it. This function may unlock and lock
1254 * the mutex associated with this callno, meaning that another
1255 * thread may grab it and destroy the call.
1259 static void iax2_lock_owner(int callno)
1262 if (!iaxs[callno] || !iaxs[callno]->owner) {
1263 /* There is no owner lock to get. */
1266 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1267 /* We got the lock */
1270 /* Avoid deadlock by pausing and trying again */
1271 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1275 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1277 /* The MWI subscriptions exist just so the core knows we care about those
1278 * mailboxes. However, we just grab the events out of the cache when it
1279 * is time to send MWI, since it is only sent with a REGACK. */
1282 static void network_change_event_subscribe(void)
1284 if (!network_change_event_subscription) {
1285 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1286 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1290 static void network_change_event_unsubscribe(void)
1292 if (network_change_event_subscription) {
1293 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1297 static int network_change_event_sched_cb(const void *data)
1299 struct iax2_registry *reg;
1300 network_change_event_sched_id = -1;
1301 AST_LIST_LOCK(®istrations);
1302 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1303 iax2_do_register(reg);
1305 AST_LIST_UNLOCK(®istrations);
1310 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1312 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1313 if (network_change_event_sched_id == -1) {
1314 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1320 /*! \brief Send manager event at call setup to link between Asterisk channel name
1321 and IAX2 call identifiers */
1322 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1324 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1325 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1326 pvt->owner ? pvt->owner->name : "",
1327 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1330 static struct ast_datastore_info iax2_variable_datastore_info = {
1331 .type = "IAX2_VARIABLE",
1332 .duplicate = iax2_dup_variable_datastore,
1333 .destroy = iax2_free_variable_datastore,
1336 static void *iax2_dup_variable_datastore(void *old)
1338 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1339 struct ast_var_t *oldvar, *newvar;
1341 newlist = ast_calloc(sizeof(*newlist), 1);
1343 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1347 AST_LIST_HEAD_INIT(newlist);
1348 AST_LIST_LOCK(oldlist);
1349 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1350 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1352 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1354 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1356 AST_LIST_UNLOCK(oldlist);
1360 static void iax2_free_variable_datastore(void *old)
1362 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1363 struct ast_var_t *oldvar;
1365 AST_LIST_LOCK(oldlist);
1366 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1369 AST_LIST_UNLOCK(oldlist);
1370 AST_LIST_HEAD_DESTROY(oldlist);
1375 /* WARNING: insert_idle_thread should only ever be called within the
1376 * context of an iax2_process_thread() thread.
1378 static void insert_idle_thread(struct iax2_thread *thread)
1380 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1381 AST_LIST_LOCK(&dynamic_list);
1382 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1383 AST_LIST_UNLOCK(&dynamic_list);
1385 AST_LIST_LOCK(&idle_list);
1386 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1387 AST_LIST_UNLOCK(&idle_list);
1393 static struct iax2_thread *find_idle_thread(void)
1395 struct iax2_thread *thread = NULL;
1397 /* Pop the head of the idle list off */
1398 AST_LIST_LOCK(&idle_list);
1399 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1400 AST_LIST_UNLOCK(&idle_list);
1402 /* If we popped a thread off the idle list, just return it */
1404 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1408 /* Pop the head of the dynamic list off */
1409 AST_LIST_LOCK(&dynamic_list);
1410 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1411 AST_LIST_UNLOCK(&dynamic_list);
1413 /* If we popped a thread off the dynamic list, just return it */
1415 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1419 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1420 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1423 /* Set default values */
1424 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1425 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1426 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1428 /* Initialize lock and condition */
1429 ast_mutex_init(&thread->lock);
1430 ast_cond_init(&thread->cond, NULL);
1431 ast_mutex_init(&thread->init_lock);
1432 ast_cond_init(&thread->init_cond, NULL);
1433 ast_mutex_lock(&thread->init_lock);
1435 /* Create thread and send it on it's way */
1436 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1437 ast_cond_destroy(&thread->cond);
1438 ast_mutex_destroy(&thread->lock);
1439 ast_mutex_unlock(&thread->init_lock);
1440 ast_cond_destroy(&thread->init_cond);
1441 ast_mutex_destroy(&thread->init_lock);
1446 /* this thread is not processing a full frame (since it is idle),
1447 so ensure that the field for the full frame call number is empty */
1448 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1450 /* Wait for the thread to be ready before returning it to the caller */
1451 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1453 /* Done with init_lock */
1454 ast_mutex_unlock(&thread->init_lock);
1459 #ifdef SCHED_MULTITHREADED
1460 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1462 struct iax2_thread *thread = NULL;
1463 static time_t lasterror;
1466 thread = find_idle_thread();
1468 if (thread != NULL) {
1469 thread->schedfunc = func;
1470 thread->scheddata = data;
1471 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1472 #ifdef DEBUG_SCHED_MULTITHREAD
1473 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1475 signal_condition(&thread->lock, &thread->cond);
1480 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1485 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1488 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1489 ast_sched_cb callback, const void *data)
1491 return ast_sched_replace(id, con, when, callback, data);
1494 static int iax2_sched_add(struct ast_sched_context *con, int when,
1495 ast_sched_cb callback, const void *data)
1497 return ast_sched_add(con, when, callback, data);
1500 static int send_ping(const void *data);
1502 static void __send_ping(const void *data)
1504 int callno = (long) data;
1506 ast_mutex_lock(&iaxsl[callno]);
1509 if (iaxs[callno]->peercallno) {
1510 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1511 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1512 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1516 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1519 ast_mutex_unlock(&iaxsl[callno]);
1522 static int send_ping(const void *data)
1524 int callno = (long) data;
1525 ast_mutex_lock(&iaxsl[callno]);
1526 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1527 iaxs[callno]->pingid = -1;
1529 ast_mutex_unlock(&iaxsl[callno]);
1531 #ifdef SCHED_MULTITHREADED
1532 if (schedule_action(__send_ping, data))
1539 static void encmethods_to_str(int e, struct ast_str *buf)
1541 ast_str_set(&buf, 0, "(");
1542 if (e & IAX_ENCRYPT_AES128) {
1543 ast_str_append(&buf, 0, "aes128");
1545 if (e & IAX_ENCRYPT_KEYROTATE) {
1546 ast_str_append(&buf, 0, ",keyrotate");
1548 if (ast_str_strlen(buf) > 1) {
1549 ast_str_append(&buf, 0, ")");
1551 ast_str_set(&buf, 0, "No");
1555 static int get_encrypt_methods(const char *s)
1558 if (!strcasecmp(s, "aes128"))
1559 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1560 else if (ast_true(s))
1561 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1567 static int send_lagrq(const void *data);
1569 static void __send_lagrq(const void *data)
1571 int callno = (long) data;
1573 ast_mutex_lock(&iaxsl[callno]);
1576 if (iaxs[callno]->peercallno) {
1577 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1578 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1579 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1583 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1586 ast_mutex_unlock(&iaxsl[callno]);
1589 static int send_lagrq(const void *data)
1591 int callno = (long) data;
1592 ast_mutex_lock(&iaxsl[callno]);
1593 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1594 iaxs[callno]->lagid = -1;
1596 ast_mutex_unlock(&iaxsl[callno]);
1598 #ifdef SCHED_MULTITHREADED
1599 if (schedule_action(__send_lagrq, data))
1605 static unsigned char compress_subclass(iax2_format subclass)
1609 /* If it's 64 or smaller, just return it */
1610 if (subclass < IAX_FLAG_SC_LOG)
1612 /* Otherwise find its power */
1613 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1614 if (subclass & (1LL << x)) {
1616 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1622 return power | IAX_FLAG_SC_LOG;
1625 static iax2_format uncompress_subclass(unsigned char csub)
1627 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1628 if (csub & IAX_FLAG_SC_LOG) {
1629 /* special case for 'compressed' -1 */
1633 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1639 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1641 struct ast_format_cap *cap;
1642 struct ast_format tmpfmt;
1643 iax2_format format = 0;
1644 if ((cap = ast_format_cap_alloc_nolock())) {
1645 ast_format_clear(&tmpfmt);
1646 ast_format_cap_from_old_bitfield(cap, formats);
1647 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1648 format = ast_format_to_old_bitfield(&tmpfmt);
1649 cap = ast_format_cap_destroy(cap);
1655 static iax2_format iax2_best_codec(iax2_format formats)
1657 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1658 struct ast_format tmpfmt;
1663 ast_format_clear(&tmpfmt);
1664 ast_format_cap_from_old_bitfield(cap, formats);
1665 ast_best_codec(cap, &tmpfmt);
1666 cap = ast_format_cap_destroy(cap);
1667 return ast_format_to_old_bitfield(&tmpfmt);
1670 const char *iax2_getformatname(iax2_format format)
1672 struct ast_format tmpfmt;
1673 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1677 return ast_getformatname(&tmpfmt);
1680 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1682 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1687 ast_format_cap_from_old_bitfield(cap, format);
1688 ast_getformatname_multiple(codec_buf, len, cap);
1689 cap = ast_format_cap_destroy(cap);
1694 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1697 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1702 ast_format_cap_from_old_bitfield(cap, *formats);
1703 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1704 *formats = ast_format_cap_to_old_bitfield(cap);
1705 cap = ast_format_cap_destroy(cap);
1710 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1713 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1717 ast_format_cap_from_old_bitfield(cap, formats);
1718 res = ast_data_add_codecs(root, node_name, cap);
1719 cap = ast_format_cap_destroy(cap);
1724 * \note The only member of the peer passed here guaranteed to be set is the name field
1726 static int peer_hash_cb(const void *obj, const int flags)
1728 const struct iax2_peer *peer = obj;
1729 const char *name = obj;
1731 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1735 * \note The only member of the peer passed here guaranteed to be set is the name field
1737 static int peer_cmp_cb(void *obj, void *arg, int flags)
1739 struct iax2_peer *peer = obj, *peer2 = arg;
1740 const char *name = arg;
1742 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1743 CMP_MATCH | CMP_STOP : 0;
1747 * \note The only member of the user passed here guaranteed to be set is the name field
1749 static int user_hash_cb(const void *obj, const int flags)
1751 const struct iax2_user *user = obj;
1752 const char *name = obj;
1754 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1758 * \note The only member of the user passed here guaranteed to be set is the name field
1760 static int user_cmp_cb(void *obj, void *arg, int flags)
1762 struct iax2_user *user = obj, *user2 = arg;
1763 const char *name = arg;
1765 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1766 CMP_MATCH | CMP_STOP : 0;
1770 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1771 * so do not call it with a pvt lock held.
1773 static struct iax2_peer *find_peer(const char *name, int realtime)
1775 struct iax2_peer *peer = NULL;
1777 peer = ao2_find(peers, name, OBJ_KEY);
1779 /* Now go for realtime if applicable */
1780 if(!peer && realtime)
1781 peer = realtime_peer(name, NULL);
1786 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1792 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1798 static struct iax2_user *find_user(const char *name)
1800 return ao2_find(users, name, OBJ_KEY);
1802 static inline struct iax2_user *user_ref(struct iax2_user *user)
1808 static inline struct iax2_user *user_unref(struct iax2_user *user)
1814 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1816 struct iax2_peer *peer = NULL;
1818 struct ao2_iterator i;
1820 i = ao2_iterator_init(peers, 0);
1821 while ((peer = ao2_iterator_next(&i))) {
1822 struct sockaddr_in peer_addr;
1824 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1826 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1827 (peer_addr.sin_port == sin.sin_port)) {
1828 ast_copy_string(host, peer->name, len);
1835 ao2_iterator_destroy(&i);
1838 peer = realtime_peer(NULL, &sin);
1840 ast_copy_string(host, peer->name, len);
1849 /*!\note Assumes the lock on the pvt is already held, when
1850 * iax2_destroy_helper() is called. */
1851 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1853 /* Decrement AUTHREQ count if needed */
1854 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1855 struct iax2_user *user;
1857 user = ao2_find(users, pvt->username, OBJ_KEY);
1859 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1863 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1865 /* No more pings or lagrq's */
1866 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1867 pvt->pingid = DONT_RESCHEDULE;
1868 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1869 pvt->lagid = DONT_RESCHEDULE;
1870 AST_SCHED_DEL(sched, pvt->autoid);
1871 AST_SCHED_DEL(sched, pvt->authid);
1872 AST_SCHED_DEL(sched, pvt->initid);
1873 AST_SCHED_DEL(sched, pvt->jbid);
1874 AST_SCHED_DEL(sched, pvt->keyrotateid);
1877 static void iax2_frame_free(struct iax_frame *fr)
1879 AST_SCHED_DEL(sched, fr->retrans);
1883 static int scheduled_destroy(const void *vid)
1885 unsigned short callno = PTR_TO_CALLNO(vid);
1886 ast_mutex_lock(&iaxsl[callno]);
1888 ast_debug(1, "Really destroying %d now...\n", callno);
1889 iax2_destroy(callno);
1891 ast_mutex_unlock(&iaxsl[callno]);
1895 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1898 ast_free(s->f.data.ptr);
1903 /*! \brief This function must be called once we are sure the other side has
1904 * given us a call number. All signaling is held here until that point. */
1905 static void send_signaling(struct chan_iax2_pvt *pvt)
1907 struct signaling_queue_entry *s = NULL;
1909 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1910 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1911 free_signaling_queue_entry(s);
1913 pvt->hold_signaling = 0;
1916 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1917 * we have received a destination call number. */
1918 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1920 struct signaling_queue_entry *new;
1922 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1923 return 1; /* do not queue this frame */
1924 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1925 return -1; /* out of memory */
1928 memcpy(&new->f, f, sizeof(new->f)); /* copy ast_frame into our queue entry */
1930 if (new->f.datalen) { /* if there is data in this frame copy it over as well */
1931 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
1932 free_signaling_queue_entry(new);
1935 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
1937 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
1942 static void pvt_destructor(void *obj)
1944 struct chan_iax2_pvt *pvt = obj;
1945 struct iax_frame *cur = NULL;
1946 struct signaling_queue_entry *s = NULL;
1948 ast_mutex_lock(&iaxsl[pvt->callno]);
1950 iax2_destroy_helper(pvt);
1952 sched_delay_remove(&pvt->addr, pvt->callno_entry);
1953 pvt->callno_entry = NULL;
1956 ast_set_flag64(pvt, IAX_ALREADYGONE);
1958 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1959 /* Cancel any pending transmissions */
1963 ast_mutex_unlock(&iaxsl[pvt->callno]);
1965 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1966 free_signaling_queue_entry(s);
1970 pvt->reg->callno = 0;
1976 ast_variables_destroy(pvt->vars);
1980 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1981 iax2_frame_free(frame.data);
1984 jb_destroy(pvt->jb);
1985 ast_string_field_free_memory(pvt);
1989 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1991 struct chan_iax2_pvt *tmp;
1994 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1998 if (ast_string_field_init(tmp, 32)) {
2010 tmp->keyrotateid = -1;
2012 ast_string_field_set(tmp,exten, "s");
2013 ast_string_field_set(tmp,host, host);
2017 jbconf.max_jitterbuf = maxjitterbuffer;
2018 jbconf.resync_threshold = resyncthreshold;
2019 jbconf.max_contig_interp = maxjitterinterps;
2020 jbconf.target_extra = jittertargetextra;
2021 jb_setconf(tmp->jb,&jbconf);
2023 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2025 tmp->hold_signaling = 1;
2026 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2031 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2033 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2035 size_t afdatalen = new->afdatalen;
2036 memcpy(new, fr, sizeof(*new));
2037 iax_frame_wrap(new, &fr->af);
2038 new->afdatalen = afdatalen;
2041 new->direction = DIRECTION_INGRESS;
2046 /* keep these defined in this order. They are used in find_callno to
2047 * determine whether or not a new call number should be allowed. */
2049 /* do not allow a new call number, only search ones in use for match */
2051 /* search for match first, then allow a new one to be allocated */
2053 /* do not search for match, force a new call number */
2055 /* do not search for match, force a new call number. Signifies call number
2056 * has been calltoken validated */
2057 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2060 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2062 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2063 (cur->addr.sin_port == sin->sin_port)) {
2064 /* This is the main host */
2065 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2066 (check_dcallno ? dcallno == cur->callno : 1) ) {
2067 /* That's us. Be sure we keep track of the peer call number */
2071 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2072 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2073 /* We're transferring */
2074 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2080 static void update_max_trunk(void)
2082 int max = TRUNK_CALL_START;
2085 /* XXX Prolly don't need locks here XXX */
2086 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
2094 ast_debug(1, "New max trunk callno is %d\n", max);
2097 static void update_max_nontrunk(void)
2101 /* XXX Prolly don't need locks here XXX */
2102 for (x=1;x<TRUNK_CALL_START - 1; x++) {
2106 maxnontrunkcall = max;
2108 ast_debug(1, "New max nontrunk callno is %d\n", max);
2111 static int make_trunk(unsigned short callno, int locked)
2115 struct callno_entry *callno_entry;
2116 if (iaxs[callno]->oseqno) {
2117 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2120 if (callno & TRUNK_CALL_START) {
2121 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2125 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2126 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2130 x = callno_entry->callno;
2131 ast_mutex_lock(&iaxsl[x]);
2134 * \note We delete these before switching the slot, because if
2135 * they fire in the meantime, they will generate a warning.
2137 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2138 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2139 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2140 iaxs[x] = iaxs[callno];
2141 iaxs[x]->callno = x;
2143 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2144 * before assigning the new one */
2145 if (iaxs[x]->callno_entry) {
2146 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2148 iaxs[x]->callno_entry = callno_entry;
2150 iaxs[callno] = NULL;
2151 /* Update the two timers that should have been started */
2152 iaxs[x]->pingid = iax2_sched_add(sched,
2153 ping_time * 1000, send_ping, (void *)(long)x);
2154 iaxs[x]->lagid = iax2_sched_add(sched,
2155 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2158 ast_mutex_unlock(&iaxsl[callno]);
2161 ast_mutex_unlock(&iaxsl[x]);
2163 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2164 /* We move this call from a non-trunked to a trunked call */
2166 update_max_nontrunk();
2170 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2172 if (!pvt->transfercallno) {
2173 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2177 ao2_link(iax_transfercallno_pvts, pvt);
2180 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2182 if (!pvt->transfercallno) {
2183 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2187 ao2_unlink(iax_transfercallno_pvts, pvt);
2189 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2191 if (!pvt->peercallno) {
2192 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2196 ao2_link(iax_peercallno_pvts, pvt);
2199 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2201 if (!pvt->peercallno) {
2202 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2206 ao2_unlink(iax_peercallno_pvts, pvt);
2209 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2211 struct addr_range *lim = obj;
2216 static int addr_range_hash_cb(const void *obj, const int flags)
2218 const struct addr_range *lim = obj;
2219 struct sockaddr_in sin;
2220 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2221 return abs((int) sin.sin_addr.s_addr);
2224 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2226 struct addr_range *lim1 = obj, *lim2 = arg;
2227 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2228 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2229 CMP_MATCH | CMP_STOP : 0;
2232 static int peercnt_hash_cb(const void *obj, const int flags)
2234 const struct peercnt *peercnt = obj;
2235 return abs((int) peercnt->addr);
2238 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2240 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2241 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2244 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2246 struct addr_range *addr_range = obj;
2247 struct sockaddr_in *sin = arg;
2248 struct sockaddr_in ha_netmask_sin;
2249 struct sockaddr_in ha_addr_sin;
2251 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2252 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2254 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2255 return CMP_MATCH | CMP_STOP;
2263 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2265 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2267 struct addr_range *addr_range;
2268 struct iax2_peer *peer = NULL;
2269 struct iax2_user *user = NULL;
2270 /* if no username is given, check for guest accounts */
2271 const char *find = S_OR(name, "guest");
2272 int res = 1; /* required by default */
2274 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2275 /* There are only two cases in which calltoken validation is not required.
2276 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2277 * the peer definition has not set the requirecalltoken option.
2278 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2281 /* ----- Case 1 ----- */
2282 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2283 ao2_ref(addr_range, -1);
2287 /* ----- Case 2 ----- */
2288 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2289 calltoken_required = user->calltoken_required;
2290 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2291 calltoken_required = user->calltoken_required;
2292 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2293 calltoken_required = peer->calltoken_required;
2294 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2295 calltoken_required = peer->calltoken_required;
2305 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);
2306 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2307 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2317 * \brief set peercnt callno limit.
2320 * First looks in custom definitions. If not found, global limit
2321 * is used. Entries marked as reg already have
2322 * a custom limit set by a registration and are not modified.
2324 static void set_peercnt_limit(struct peercnt *peercnt)
2326 uint16_t limit = global_maxcallno;
2327 struct addr_range *addr_range;
2328 struct sockaddr_in sin = {
2329 .sin_addr.s_addr = peercnt->addr,
2333 if (peercnt->reg && peercnt->limit) {
2334 return; /* this peercnt has a custom limit set by a registration */
2337 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2338 limit = addr_range->limit;
2339 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2340 ao2_ref(addr_range, -1);
2343 peercnt->limit = limit;
2348 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2350 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2352 struct peercnt *peercnt = obj;
2354 set_peercnt_limit(peercnt);
2355 ast_debug(1, "Reset limits for peercnts table\n");
2362 * \brief returns match if delme is set.
2364 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2366 struct addr_range *addr_range = obj;
2368 return addr_range->delme ? CMP_MATCH : 0;
2373 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2375 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2377 /* this function turns off and on custom callno limits set by peer registration */
2378 struct peercnt *peercnt;
2379 struct peercnt tmp = {
2382 struct sockaddr_in sin;
2384 ast_sockaddr_to_sin(sockaddr, &sin);
2386 tmp.addr = sin.sin_addr.s_addr;
2388 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2391 peercnt->limit = limit;
2393 set_peercnt_limit(peercnt);
2395 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2396 ao2_ref(peercnt, -1); /* decrement ref from find */
2402 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2404 * \details First searches for the address in the peercnts table. If found
2405 * the current count is incremented. If not found a new peercnt is allocated
2406 * and linked into the peercnts table with a call number count of 1.
2408 static int peercnt_add(struct sockaddr_in *sin)
2410 struct peercnt *peercnt;
2411 unsigned long addr = sin->sin_addr.s_addr;
2413 struct peercnt tmp = {
2417 /* Reasoning for peercnts container lock: Two identical ip addresses
2418 * could be added by different threads at the "same time". Without the container
2419 * lock, both threads could alloc space for the same object and attempt
2420 * to link to table. With the lock, one would create the object and link
2421 * to table while the other would find the already created peercnt object
2422 * rather than creating a new one. */
2424 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2426 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2428 /* create and set defaults */
2429 peercnt->addr = addr;
2430 set_peercnt_limit(peercnt);
2431 /* guarantees it does not go away after unlocking table
2432 * ao2_find automatically adds this */
2433 ao2_link(peercnts, peercnt);
2435 ao2_unlock(peercnts);
2439 /* check to see if the address has hit its callno limit. If not increment cur. */
2440 if (peercnt->limit > peercnt->cur) {
2442 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2443 } else { /* max num call numbers for this peer has been reached! */
2444 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2448 /* clean up locks and ref count */
2449 ao2_unlock(peercnt);
2450 ao2_unlock(peercnts);
2451 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2458 * \brief decrements a peercnts table entry
2460 static void peercnt_remove(struct peercnt *peercnt)
2462 struct sockaddr_in sin = {
2463 .sin_addr.s_addr = peercnt->addr,
2467 /* Container locked here since peercnt may be unlinked from list. If left unlocked,
2468 * peercnt_add could try and grab this entry from the table and modify it at the
2469 * "same time" this thread attemps to unlink it.*/
2472 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2473 /* if this was the last connection from the peer remove it from table */
2474 if (peercnt->cur == 0) {
2475 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2477 ao2_unlock(peercnts);
2483 * \brief called by scheduler to decrement object
2485 static int peercnt_remove_cb(const void *obj)
2487 struct peercnt *peercnt = (struct peercnt *) obj;
2489 peercnt_remove(peercnt);
2490 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2497 * \brief decrements peercnts connection count, finds by addr
2499 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2501 struct peercnt *peercnt;
2502 struct peercnt tmp = {
2503 .addr = sin->sin_addr.s_addr,
2506 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2507 peercnt_remove(peercnt);
2508 ao2_ref(peercnt, -1); /* decrement ref from find */
2515 * \brief Create callno_limit entry based on configuration
2517 static void build_callno_limits(struct ast_variable *v)
2519 struct addr_range *addr_range = NULL;
2520 struct addr_range tmp;
2526 for (; v; v = v->next) {
2530 ha = ast_append_ha("permit", v->name, NULL, &error);
2532 /* check for valid config information */
2534 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2536 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2537 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2542 ast_copy_ha(ha, &tmp.ha);
2543 /* find or create the addr_range */
2544 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2545 ao2_lock(addr_range);
2547 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2549 return; /* out of memory */
2552 /* copy over config data into addr_range object */
2553 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2554 ast_free_ha(ha); /* cleanup the tmp ha */
2555 addr_range->limit = limit;
2556 addr_range->delme = 0;
2560 ao2_unlock(addr_range);
2562 ao2_link(callno_limits, addr_range);
2564 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2570 * \brief Create calltoken_ignores entry based on configuration
2572 static int add_calltoken_ignore(const char *addr)
2574 struct addr_range tmp;
2575 struct addr_range *addr_range = NULL;
2576 struct ast_ha *ha = NULL;
2579 if (ast_strlen_zero(addr)) {
2580 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2584 ha = ast_append_ha("permit", addr, NULL, &error);
2586 /* check for valid config information */
2588 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2592 ast_copy_ha(ha, &tmp.ha);
2593 /* find or create the addr_range */
2594 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2595 ao2_lock(addr_range);
2596 addr_range->delme = 0;
2597 ao2_unlock(addr_range);
2598 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2599 /* copy over config data into addr_range object */
2600 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2601 ao2_link(calltoken_ignores, addr_range);
2608 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2613 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2615 struct ao2_iterator i;
2616 struct peercnt *peercnt;
2617 struct sockaddr_in sin;
2622 e->command = "iax2 show callnumber usage";
2624 "Usage: iax2 show callnumber usage [IP address]\n"
2625 " Shows current IP addresses which are consuming iax2 call numbers\n";
2630 if (a->argc < 4 || a->argc > 5)
2631 return CLI_SHOWUSAGE;
2633 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2634 i = ao2_iterator_init(peercnts, 0);
2635 while ((peercnt = ao2_iterator_next(&i))) {
2636 sin.sin_addr.s_addr = peercnt->addr;
2637 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
2638 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2642 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2644 ao2_ref(peercnt, -1);
2646 ao2_iterator_destroy(&i);
2649 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2650 "Non-CallToken Validated Callno Used: %d\n",
2651 global_maxcallno_nonval,
2652 total_nonval_callno_used);
2654 ast_cli(a->fd, "Total Available Callno: %d\n"
2655 "Regular Callno Available: %d\n"
2656 "Trunk Callno Available: %d\n",
2657 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2658 ao2_container_count(callno_pool),
2659 ao2_container_count(callno_pool_trunk));
2660 } else if (a->argc == 5 && !found) {
2661 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
2671 static struct callno_entry *get_unused_callno(int trunk, int validated)
2673 struct callno_entry *callno_entry = NULL;
2674 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2675 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2676 /* Minor optimization for the extreme case. */
2680 /* the callno_pool container is locked here primarily to ensure thread
2681 * safety of the total_nonval_callno_used check and increment */
2682 ao2_lock(callno_pool);
2684 /* only a certain number of nonvalidated call numbers should be allocated.
2685 * If there ever is an attack, this separates the calltoken validating
2686 * users from the non calltoken validating users. */
2687 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2688 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2689 ao2_unlock(callno_pool);
2693 /* unlink the object from the container, taking over ownership
2694 * of the reference the container had to the object */
2695 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2698 callno_entry->validated = validated;
2700 total_nonval_callno_used++;
2704 ao2_unlock(callno_pool);
2705 return callno_entry;
2708 static int replace_callno(const void *obj)
2710 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2712 /* the callno_pool container is locked here primarily to ensure thread
2713 * safety of the total_nonval_callno_used check and decrement */
2714 ao2_lock(callno_pool);
2716 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2717 total_nonval_callno_used--;
2718 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2719 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2722 if (callno_entry->callno < TRUNK_CALL_START) {
2723 ao2_link(callno_pool, callno_entry);
2725 ao2_link(callno_pool_trunk, callno_entry);
2727 ao2_ref(callno_entry, -1); /* only container ref remains */
2729 ao2_unlock(callno_pool);
2733 static int callno_hash(const void *obj, const int flags)
2735 return abs(ast_random());
2738 static int create_callno_pools(void)
2742 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2746 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2750 /* start at 2, 0 and 1 are reserved */
2751 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2752 struct callno_entry *callno_entry;
2754 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2758 callno_entry->callno = i;
2760 if (i < TRUNK_CALL_START) {
2761 ao2_link(callno_pool, callno_entry);
2763 ao2_link(callno_pool_trunk, callno_entry);
2766 ao2_ref(callno_entry, -1);
2774 * \brief Schedules delayed removal of iax2_pvt call number data
2776 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2777 * avaliable again, and the address from the previous connection must be decremented
2778 * from the peercnts table. This function schedules these operations to take place.
2780 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2783 struct peercnt *peercnt;
2784 struct peercnt tmp = {
2785 .addr = sin->sin_addr.s_addr,
2788 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2789 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2790 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2791 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2793 ao2_ref(peercnt, -1);
2797 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2802 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2804 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2807 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2809 if (frametype != AST_FRAME_IAX) {
2813 case IAX_COMMAND_NEW:
2814 case IAX_COMMAND_REGREQ:
2815 case IAX_COMMAND_FWDOWNL:
2816 case IAX_COMMAND_REGREL:
2818 case IAX_COMMAND_POKE:
2828 * \note Calling this function while holding another pvt lock can cause a deadlock.
2830 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2834 /* this call is calltoken validated as long as it is either NEW_FORCE
2835 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2836 int validated = (new > NEW_ALLOW) ? 1 : 0;
2839 if (new <= NEW_ALLOW) {
2841 struct chan_iax2_pvt *pvt;
2842 struct chan_iax2_pvt tmp_pvt = {
2844 .peercallno = callno,
2845 .transfercallno = callno,
2847 .frames_received = check_dcallno,
2850 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2851 /* this works for finding normal call numbers not involving transfering */
2852 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2853 if (return_locked) {
2854 ast_mutex_lock(&iaxsl[pvt->callno]);
2861 /* this searches for transfer call numbers that might not get caught otherwise */
2862 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2863 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2864 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2865 if (return_locked) {
2866 ast_mutex_lock(&iaxsl[pvt->callno]);
2874 /* This will occur on the first response to a message that we initiated,
2875 * such as a PING. */
2877 ast_mutex_lock(&iaxsl[dcallno]);
2879 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2880 iaxs[dcallno]->peercallno = callno;
2882 store_by_peercallno(iaxs[dcallno]);
2883 if (!res || !return_locked) {
2884 ast_mutex_unlock(&iaxsl[dcallno]);
2889 ast_mutex_unlock(&iaxsl[dcallno]);
2892 /* If we get here, we SHOULD NOT find a call structure for this
2893 callno; if we do, it means that there is a call structure that
2894 has a peer callno but did NOT get entered into the hash table,
2897 If we find a call structure using this old, slow method, output a log
2898 message so we'll know about it. After a few months of leaving this in
2899 place, if we don't hear about people seeing these messages, we can
2900 remove this code for good.
2903 for (x = 1; !res && x < maxnontrunkcall; x++) {
2904 ast_mutex_lock(&iaxsl[x]);
2906 /* Look for an exact match */
2907 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2911 if (!res || !return_locked)
2912 ast_mutex_unlock(&iaxsl[x]);
2914 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
2915 ast_mutex_lock(&iaxsl[x]);
2917 /* Look for an exact match */
2918 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
2922 if (!res || !return_locked)
2923 ast_mutex_unlock(&iaxsl[x]);
2927 if (!res && (new >= NEW_ALLOW)) {
2928 struct callno_entry *callno_entry;
2929 /* It may seem odd that we look through the peer list for a name for
2930 * this *incoming* call. Well, it is weird. However, users don't
2931 * have an IP address/port number that we can match against. So,
2932 * this is just checking for a peer that has that IP/port and
2933 * assuming that we have a user of the same name. This isn't always
2934 * correct, but it will be changed if needed after authentication. */
2935 if (!iax2_getpeername(*sin, host, sizeof(host)))
2936 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2938 if (peercnt_add(sin)) {
2939 /* This address has hit its callnumber limit. When the limit
2940 * is reached, the connection is not added to the peercnts table.*/
2944 if (!(callno_entry = get_unused_callno(0, validated))) {
2945 /* since we ran out of space, remove the peercnt
2946 * entry we added earlier */
2947 peercnt_remove_by_addr(sin);
2948 ast_log(LOG_WARNING, "No more space\n");
2951 x = callno_entry->callno;
2952 ast_mutex_lock(&iaxsl[x]);
2954 iaxs[x] = new_iax(sin, host);
2955 update_max_nontrunk();
2958 ast_debug(1, "Creating new call structure %d\n", x);
2959 iaxs[x]->callno_entry = callno_entry;
2960 iaxs[x]->sockfd = sockfd;
2961 iaxs[x]->addr.sin_port = sin->sin_port;
2962 iaxs[x]->addr.sin_family = sin->sin_family;
2963 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2964 iaxs[x]->peercallno = callno;
2965 iaxs[x]->callno = x;
2966 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2967 iaxs[x]->expiry = min_reg_expire;
2968 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2969 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2970 iaxs[x]->amaflags = amaflags;
2971 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2972 ast_string_field_set(iaxs[x], accountcode, accountcode);
2973 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2974 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2975 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2977 if (iaxs[x]->peercallno) {
2978 store_by_peercallno(iaxs[x]);
2981 ast_log(LOG_WARNING, "Out of resources\n");
2982 ast_mutex_unlock(&iaxsl[x]);
2983 replace_callno(callno_entry);
2987 ast_mutex_unlock(&iaxsl[x]);
2993 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2994 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2997 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2999 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3003 * \brief Queue a frame to a call's owning asterisk channel
3005 * \pre This function assumes that iaxsl[callno] is locked when called.
3007 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3008 * was valid before calling it, it may no longer be valid after calling it.
3009 * This function may unlock and lock the mutex associated with this callno,
3010 * meaning that another thread may grab it and destroy the call.
3012 static int iax2_queue_frame(int callno, struct ast_frame *f)
3014 iax2_lock_owner(callno);
3015 if (iaxs[callno] && iaxs[callno]->owner) {
3016 ast_queue_frame(iaxs[callno]->owner, f);
3017 ast_channel_unlock(iaxs[callno]->owner);
3023 * \brief Queue a hangup frame on the ast_channel owner
3025 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3026 * is active for the given call number.
3028 * \pre Assumes lock for callno is already held.
3030 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3031 * was valid before calling it, it may no longer be valid after calling it.
3032 * This function may unlock and lock the mutex associated with this callno,
3033 * meaning that another thread may grab it and destroy the call.
3035 static int iax2_queue_hangup(int callno)
3037 iax2_lock_owner(callno);
3038 if (iaxs[callno] && iaxs[callno]->owner) {
3039 ast_queue_hangup(iaxs[callno]->owner);
3040 ast_channel_unlock(iaxs[callno]->owner);
3046 * \brief Queue a control frame on the ast_channel owner
3048 * This function queues a control frame on the owner of the IAX2 pvt struct that
3049 * is active for the given call number.
3051 * \pre Assumes lock for callno is already held.
3053 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3054 * was valid before calling it, it may no longer be valid after calling it.
3055 * This function may unlock and lock the mutex associated with this callno,
3056 * meaning that another thread may grab it and destroy the call.
3058 static int iax2_queue_control_data(int callno,
3059 enum ast_control_frame_type control, const void *data, size_t datalen)
3061 iax2_lock_owner(callno);
3062 if (iaxs[callno] && iaxs[callno]->owner) {
3063 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3064 ast_channel_unlock(iaxs[callno]->owner);
3068 static void destroy_firmware(struct iax_firmware *cur)
3070 /* Close firmware */
3072 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3078 static int try_firmware(char *s)
3081 struct iax_firmware *cur = NULL;
3082 int ifd, fd, res, len, chunk;
3083 struct ast_iax2_firmware_header *fwh, fwh2;
3084 struct MD5Context md5;
3085 unsigned char sum[16], buf[1024];
3088 if (!(s2 = alloca(strlen(s) + 100))) {
3089 ast_log(LOG_WARNING, "Alloca failed!\n");
3093 last = strrchr(s, '/');
3099 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3101 if ((res = stat(s, &stbuf) < 0)) {
3102 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3106 /* Make sure it's not a directory */
3107 if (S_ISDIR(stbuf.st_mode))
3109 ifd = open(s, O_RDONLY);
3111 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3114 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3116 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3120 /* Unlink our newly created file */
3123 /* Now copy the firmware into it */
3124 len = stbuf.st_size;
3127 if (chunk > sizeof(buf))
3128 chunk = sizeof(buf);
3129 res = read(ifd, buf, chunk);
3131 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3136 res = write(fd, buf, chunk);
3138 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3146 /* Return to the beginning */
3147 lseek(fd, 0, SEEK_SET);
3148 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3149 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3153 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3154 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3158 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3159 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3163 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3164 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3168 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3169 if (fwh == MAP_FAILED) {
3170 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3175 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3176 MD5Final(sum, &md5);
3177 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3178 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3179 munmap((void*)fwh, stbuf.st_size);
3184 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3185 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3186 /* Found a candidate */
3187 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3188 /* The version we have on loaded is older, load this one instead */
3190 /* This version is no newer than what we have. Don't worry about it.
3191 We'll consider it a proper load anyhow though */
3192 munmap((void*)fwh, stbuf.st_size);
3198 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3200 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3205 munmap((void*)cur->fwh, cur->mmaplen);
3210 cur->mmaplen = stbuf.st_size;
3217 static int iax_check_version(char *dev)
3220 struct iax_firmware *cur = NULL;
3222 if (ast_strlen_zero(dev))
3225 AST_LIST_LOCK(&firmwares);
3226 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3227 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3228 res = ntohs(cur->fwh->version);
3232 AST_LIST_UNLOCK(&firmwares);
3237 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3240 unsigned int bs = desc & 0xff;
3241 unsigned int start = (desc >> 8) & 0xffffff;
3243 struct iax_firmware *cur;
3245 if (ast_strlen_zero((char *)dev) || !bs)
3250 AST_LIST_LOCK(&firmwares);
3251 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3252 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3254 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3255 if (start < ntohl(cur->fwh->datalen)) {
3256 bytes = ntohl(cur->fwh->datalen) - start;
3259 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3262 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3270 AST_LIST_UNLOCK(&firmwares);
3276 static void reload_firmware(int unload)
3278 struct iax_firmware *cur = NULL;
3281 char dir[256], fn[256];
3283 AST_LIST_LOCK(&firmwares);
3285 /* Mark all as dead */
3286 AST_LIST_TRAVERSE(&firmwares, cur, list)
3289 /* Now that we have marked them dead... load new ones */
3291 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3294 while((de = readdir(fwd))) {
3295 if (de->d_name[0] != '.') {
3296 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3297 if (!try_firmware(fn)) {
3298 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3304 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3307 /* Clean up leftovers */
3308 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3311 AST_LIST_REMOVE_CURRENT(list);
3312 destroy_firmware(cur);
3314 AST_LIST_TRAVERSE_SAFE_END;
3316 AST_LIST_UNLOCK(&firmwares);
3320 * \note This function assumes that iaxsl[callno] is locked when called.
3322 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3323 * was valid before calling it, it may no longer be valid after calling it.
3324 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3325 * associated with this callno, meaning that another thread may grab it and destroy the call.
3327 static int __do_deliver(void *data)
3329 /* Just deliver the packet by using queueing. This is called by
3330 the IAX thread with the iaxsl lock held. */
3331 struct iax_frame *fr = data;
3333 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3334 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3335 iax2_queue_frame(fr->callno, &fr->af);
3336 /* Free our iax frame */
3337 iax2_frame_free(fr);
3338 /* And don't run again */
3342 static int handle_error(void)
3344 /* XXX Ideally we should figure out why an error occurred and then abort those
3345 rather than continuing to try. Unfortunately, the published interface does
3346 not seem to work XXX */
3348 struct sockaddr_in *sin;
3351 struct sock_extended_err e;
3356 m.msg_controllen = sizeof(e);
3358 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3360 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3362 if (m.msg_controllen) {
3363 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3365 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3367 ast_log(LOG_WARNING, "No address detected??\n");
3369 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3376 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3379 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3382 ast_debug(1, "Received error: %s\n", strerror(errno));
3389 static int send_packet(struct iax_frame *f)
3392 int callno = f->callno;
3394 /* Don't send if there was an error, but return error instead */
3395 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3398 /* Called with iaxsl held */
3400 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3404 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3405 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3408 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3409 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3413 ast_debug(1, "Received error: %s\n", strerror(errno));
3422 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3423 * for the given call number may disappear during its execution.
3425 static int iax2_predestroy(int callno)
3427 struct ast_channel *c = NULL;
3428 struct chan_iax2_pvt *pvt = iaxs[callno];
3433 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3434 iax2_destroy_helper(pvt);
3435 ast_set_flag64(pvt, IAX_ALREADYGONE);
3438 if ((c = pvt->owner)) {
3440 iax2_queue_hangup(callno);
3442 ast_module_unref(ast_module_info->self);
3448 static void iax2_destroy(int callno)
3450 struct chan_iax2_pvt *pvt = NULL;
3451 struct ast_channel *owner = NULL;
3454 if ((pvt = iaxs[callno])) {
3456 /* iax2_destroy_helper gets called from this function later on. When
3457 * called twice, we get the (previously) familiar FRACK! errors in
3458 * devmode, from the scheduler. An alternative to this approach is to
3459 * reset the scheduler entries to -1 when they're deleted in
3460 * iax2_destroy_helper(). That approach was previously decided to be
3461 * "wrong" because "the memory is going to be deallocated anyway. Why
3462 * should we be resetting those values?" */
3463 iax2_destroy_helper(pvt);
3467 owner = pvt ? pvt->owner : NULL;
3470 if (ast_channel_trylock(owner)) {
3471 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3472 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3478 iaxs[callno] = NULL;
3485 /* If there's an owner, prod it to give up */
3486 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3487 * because we already hold the owner channel lock. */
3488 ast_queue_hangup(owner);
3491 if (pvt->peercallno) {
3492 remove_by_peercallno(pvt);
3495 if (pvt->transfercallno) {
3496 remove_by_transfercallno(pvt);
3506 ast_channel_unlock(owner);
3509 if (callno & 0x4000) {
3514 static int update_packet(struct iax_frame *f)
3516 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3517 struct ast_iax2_full_hdr *fh = f->data;
3518 struct ast_frame af;
3520 /* if frame is encrypted. decrypt before updating it. */
3521 if (f->encmethods) {
3522 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3524 /* Mark this as a retransmission */
3525 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3527 f->iseqno = iaxs[f->callno]->iseqno;
3528 fh->iseqno = f->iseqno;
3530 /* Now re-encrypt the frame */
3531 if (f->encmethods) {
3532 /* since this is a retransmit frame, create a new random padding
3533 * before re-encrypting. */
3534 build_rand_pad(f->semirand, sizeof(f->semirand));
3535 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3540 static int attempt_transmit(const void *data);
3541 static void __attempt_transmit(const void *data)
3543 /* Attempt to transmit the frame to the remote peer...
3544 Called without iaxsl held. */
3545 struct iax_frame *f = (struct iax_frame *)data;
3547 int callno = f->callno;
3548 /* Make sure this call is still active */
3550 ast_mutex_lock(&iaxsl[callno]);
3551 if (callno && iaxs[callno]) {
3552 if ((f->retries < 0) /* Already ACK'd */ ||
3553 (f->retries >= max_retries) /* Too many attempts */) {
3554 /* Record an error if we've transmitted too many times */
3555 if (f->retries >= max_retries) {
3557 /* Transfer timeout */
3558 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3559 } else if (f->final) {
3560 iax2_destroy(callno);
3562 if (iaxs[callno]->owner)
3563 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3564 iaxs[callno]->error = ETIMEDOUT;
3565 if (iaxs[callno]->owner) {
3566 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3568 iax2_queue_frame(callno, &fr); /* XXX */
3569 /* Remember, owner could disappear */
3570 if (iaxs[callno] && iaxs[callno]->owner)
3571 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3573 if (iaxs[callno]->reg) {
3574 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3575 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3576 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3578 iax2_destroy(callno);
3585 /* Update it if it needs it */
3587 /* Attempt transmission */
3590 /* Try again later after 10 times as long */
3592 if (f->retrytime > MAX_RETRY_TIME)
3593 f->retrytime = MAX_RETRY_TIME;
3594 /* Transfer messages max out at one second */
3595 if (f->transfer && (f->retrytime > 1000))
3596 f->retrytime = 1000;
3597 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3600 /* Make sure it gets freed */
3606 /* Don't attempt delivery, just remove it from the queue */
3607 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3608 ast_mutex_unlock(&iaxsl[callno]);
3609 f->retrans = -1; /* this is safe because this is the scheduled function */
3610 /* Free the IAX frame */
3612 } else if (callno) {
3613 ast_mutex_unlock(&iaxsl[callno]);
3617 static int attempt_transmit(const void *data)
3619 #ifdef SCHED_MULTITHREADED
3620 if (schedule_action(__attempt_transmit, data))
3622 __attempt_transmit(data);
3626 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3628 struct iax2_peer *peer = NULL;
3629 struct iax2_user *user = NULL;
3630 static const char * const choices[] = { "all", NULL };
3635 e->command = "iax2 prune realtime";
3637 "Usage: iax2 prune realtime [<peername>|all]\n"
3638 " Prunes object(s) from the cache\n";
3642 cmplt = ast_cli_complete(a->word, choices, a->n);
3644 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3650 return CLI_SHOWUSAGE;
3651 if (!strcmp(a->argv[3], "all")) {
3654 ast_cli(a->fd, "Cache flushed successfully.\n");
3657 peer = find_peer(a->argv[3], 0);
3658 user = find_user(a->argv[3]);
3661 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3662 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3663 expire_registry(peer_ref(peer));
3664 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3666 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3671 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3672 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3673 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3675 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3677 ao2_unlink(users,user);
3681 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3687 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3691 e->command = "iax2 test losspct";
3693 "Usage: iax2 test losspct <percentage>\n"
3694 " For testing, throws away <percentage> percent of incoming packets\n";
3700 return CLI_SHOWUSAGE;
3702 test_losspct = atoi(a->argv[3]);
3708 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3712 e->command = "iax2 test late";
3714 "Usage: iax2 test late <ms>\n"
3715 " For testing, count the next frame as <ms> ms late\n";
3722 return CLI_SHOWUSAGE;
3724 test_late = atoi(a->argv[3]);
3729 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3733 e->command = "iax2 test resync";
3735 "Usage: iax2 test resync <ms>\n"
3736 " For testing, adjust all future frames by <ms> ms\n";
3743 return CLI_SHOWUSAGE;
3745 test_resync = atoi(a->argv[3]);