2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
34 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35 * \addtogroup configuration_file
38 /*! \page iax.conf iax.conf
39 * \verbinclude iax.conf.sample
43 <use type="external">crypto</use>
44 <support_level>core</support_level>
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
59 #include <sys/signal.h>
67 #include "asterisk/paths.h"
69 #include "asterisk/lock.h"
70 #include "asterisk/frame.h"
71 #include "asterisk/channel.h"
72 #include "asterisk/module.h"
73 #include "asterisk/pbx.h"
74 #include "asterisk/sched.h"
75 #include "asterisk/io.h"
76 #include "asterisk/config.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/cdr.h"
81 #include "asterisk/crypto.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/app.h"
86 #include "asterisk/astdb.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/features.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/causes.h"
91 #include "asterisk/localtime.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
97 #include "asterisk/event.h"
98 #include "asterisk/astobj2.h"
99 #include "asterisk/timing.h"
100 #include "asterisk/taskprocessor.h"
101 #include "asterisk/test.h"
102 #include "asterisk/data.h"
103 #include "asterisk/netsock2.h"
105 #include "iax2/include/iax2.h"
106 #include "iax2/include/firmware.h"
107 #include "iax2/include/parser.h"
108 #include "iax2/include/provision.h"
109 #include "jitterbuf.h"
112 <application name="IAX2Provision" language="en_US">
114 Provision a calling IAXy with a given template.
117 <parameter name="template">
118 <para>If not specified, defaults to <literal>default</literal>.</para>
122 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
123 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
124 or <literal>0</literal> on success.</para>
127 <function name="IAXPEER" language="en_US">
129 Gets IAX peer information.
132 <parameter name="peername" required="true">
134 <enum name="CURRENTCHANNEL">
135 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
136 endpoint of the current channel</para>
140 <parameter name="item">
141 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
144 <para>(default) The IP address.</para>
147 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
149 <enum name="mailbox">
150 <para>The configured mailbox.</para>
152 <enum name="context">
153 <para>The configured context.</para>
156 <para>The epoch time of the next expire.</para>
158 <enum name="dynamic">
159 <para>Is it dynamic? (yes/no).</para>
161 <enum name="callerid_name">
162 <para>The configured Caller ID name.</para>
164 <enum name="callerid_num">
165 <para>The configured Caller ID number.</para>
168 <para>The configured codecs.</para>
170 <enum name="codec[x]">
171 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
172 with <literal>0</literal>)</para>
178 <para>Gets information associated with the specified IAX2 peer.</para>
181 <ref type="function">SIPPEER</ref>
184 <function name="IAXVAR" language="en_US">
186 Sets or retrieves a remote variable.
189 <parameter name="varname" required="true" />
192 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
195 <manager name="IAXpeers" language="en_US">
200 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
205 <manager name="IAXpeerlist" language="en_US">
210 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
213 <para>List all the IAX peers.</para>
216 <manager name="IAXnetstats" language="en_US">
222 <para>Show IAX channels network statistics.</para>
225 <manager name="IAXregistry" language="en_US">
227 Show IAX registrations.
230 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
233 <para>Show IAX registrations.</para>
238 /* Define SCHED_MULTITHREADED to run the scheduler in a special
239 multithreaded mode. */
240 #define SCHED_MULTITHREADED
242 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
243 thread is actually doing. */
244 #define DEBUG_SCHED_MULTITHREAD
248 static int nochecksums = 0;
251 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
252 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
254 #define DEFAULT_THREAD_COUNT 10
255 #define DEFAULT_MAX_THREAD_COUNT 100
256 #define DEFAULT_RETRY_TIME 1000
257 #define MEMORY_SIZE 100
258 #define DEFAULT_DROP 3
260 #define DEBUG_SUPPORT
262 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
264 /* Sample over last 100 units to determine historic jitter */
267 static struct ast_codec_pref prefs;
269 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
272 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
273 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
274 #define MAX_TRUNK_MTU 1240
276 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
277 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
279 #define DEFAULT_CONTEXT "default"
281 static char default_parkinglot[AST_MAX_CONTEXT];
283 static char language[MAX_LANGUAGE] = "";
284 static char regcontext[AST_MAX_CONTEXT] = "";
286 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
287 static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
288 static int network_change_event_sched_id = -1;
290 static int maxauthreq = 3;
291 static int max_retries = 4;
292 static int ping_time = 21;
293 static int lagrq_time = 10;
294 static int maxjitterbuffer=1000;
295 static int resyncthreshold=1000;
296 static int maxjitterinterps=10;
297 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
299 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
301 static int trunkfreq = 20;
302 static int trunkmaxsize = MAX_TRUNKDATA;
304 static int authdebug = 0;
305 static int autokill = 0;
306 static int iaxcompat = 0;
307 static int last_authmethod = 0;
309 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
311 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
318 static int min_reg_expire;
319 static int max_reg_expire;
321 static int srvlookup = 0;
323 static struct ast_timer *timer; /* Timer for trunking */
325 static struct ast_netsock_list *netsock;
326 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
327 static int defaultsockfd = -1;
329 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
332 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
334 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
335 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
338 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
339 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
341 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
342 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
344 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
345 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
346 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
347 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
349 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
350 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
353 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
354 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
355 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
357 /* if a pvt has encryption setup done and is running on the call */
358 #define IAX_CALLENCRYPTED(pvt) \
359 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
361 #define IAX_DEBUGDIGEST(msg, key) do { \
363 char digest[33] = ""; \
368 for (idx = 0; idx < 16; idx++) \
369 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
371 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
374 static struct io_context *io;
375 static struct ast_sched_context *sched;
377 #define DONT_RESCHEDULE -2
379 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
381 static int iaxdebug = 0;
383 static int iaxtrunkdebug = 0;
385 static int test_losspct = 0;
387 static int test_late = 0;
388 static int test_resync = 0;
389 static int test_jit = 0;
390 static int test_jitpct = 0;
391 #endif /* IAXTESTS */
393 static char accountcode[AST_MAX_ACCOUNT_CODE];
394 static char mohinterpret[MAX_MUSICCLASS];
395 static char mohsuggest[MAX_MUSICCLASS];
396 static int amaflags = 0;
398 static int delayreject = 0;
399 static int iax2_encryption = 0;
401 static struct ast_flags64 globalflags = { 0 };
403 static pthread_t netthreadid = AST_PTHREADT_NULL;
406 IAX_STATE_STARTED = (1 << 0),
407 IAX_STATE_AUTHENTICATED = (1 << 1),
408 IAX_STATE_TBD = (1 << 2),
411 struct iax2_context {
412 char context[AST_MAX_CONTEXT];
413 struct iax2_context *next;
417 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
418 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
419 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
420 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
421 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
422 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
423 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
424 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
425 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
426 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
427 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
428 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
429 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
430 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
431 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
432 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
433 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
434 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
435 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
436 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
437 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
438 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
439 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
440 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
441 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
442 #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 */
443 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
444 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
445 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
446 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
447 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
448 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
449 static int global_rtautoclear = 120;
451 static int reload_config(int forced_reload);
454 * \brief Call token validation settings.
456 enum calltoken_peer_enum {
457 /*! \brief Default calltoken required unless the ip is in the ignorelist */
458 CALLTOKEN_DEFAULT = 0,
459 /*! \brief Require call token validation. */
461 /*! \brief Require call token validation after a successful registration
462 * using call token validation occurs. */
464 /*! \brief Do not require call token validation. */
469 AST_DECLARE_STRING_FIELDS(
470 AST_STRING_FIELD(name);
471 AST_STRING_FIELD(secret);
472 AST_STRING_FIELD(dbsecret);
473 AST_STRING_FIELD(accountcode);
474 AST_STRING_FIELD(mohinterpret);
475 AST_STRING_FIELD(mohsuggest);
476 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
477 AST_STRING_FIELD(language);
478 AST_STRING_FIELD(cid_num);
479 AST_STRING_FIELD(cid_name);
480 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
488 iax2_format capability;
489 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
490 int curauthreq; /*!< Current number of outstanding AUTHREQs */
491 struct ast_codec_pref prefs;
492 struct ast_acl_list *acl;
493 struct iax2_context *contexts;
494 struct ast_variable *vars;
495 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
499 AST_DECLARE_STRING_FIELDS(
500 AST_STRING_FIELD(name);
501 AST_STRING_FIELD(username);
502 AST_STRING_FIELD(description); /*!< Description of the peer */
503 AST_STRING_FIELD(secret);
504 AST_STRING_FIELD(dbsecret);
505 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
507 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
508 AST_STRING_FIELD(context); /*!< For transfers only */
509 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
510 AST_STRING_FIELD(mailbox); /*!< Mailbox */
511 AST_STRING_FIELD(mohinterpret);
512 AST_STRING_FIELD(mohsuggest);
513 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
514 /* Suggested caller id if registering */
515 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
516 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
517 AST_STRING_FIELD(zonetag); /*!< Time Zone */
518 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
520 struct ast_codec_pref prefs;
521 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
522 struct ast_sockaddr addr;
524 int sockfd; /*!< Socket to use for transmission */
529 /* Dynamic Registration fields */
530 struct sockaddr_in defaddr; /*!< Default address if there is one */
531 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
532 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
534 int expire; /*!< Schedule entry for expiry */
535 int expiry; /*!< How soon to expire */
536 iax2_format capability; /*!< Capability */
539 int callno; /*!< Call number of POKE request */
540 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
541 int lastms; /*!< How long last response took (in ms), or -1 for no response */
542 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
544 int pokefreqok; /*!< How often to check if the host is up */
545 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
546 int historicms; /*!< How long recent average responses took */
547 int smoothing; /*!< Sample over how many units to determine historic ms */
548 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
550 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
552 struct ast_acl_list *acl;
553 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
556 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
558 struct iax2_trunk_peer {
561 struct sockaddr_in addr;
562 struct timeval txtrunktime; /*!< Transmit trunktime */
563 struct timeval rxtrunktime; /*!< Receive trunktime */
564 struct timeval lasttxtime; /*!< Last transmitted trunktime */
565 struct timeval trunkact; /*!< Last trunk activity */
566 unsigned int lastsent; /*!< Last sent time */
567 /* Trunk data and length */
568 unsigned char *trunkdata;
569 unsigned int trunkdatalen;
570 unsigned int trunkdataalloc;
574 AST_LIST_ENTRY(iax2_trunk_peer) list;
577 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
580 REG_STATE_UNREGISTERED = 0,
583 REG_STATE_REGISTERED,
589 enum iax_transfer_state {
594 TRANSFER_PASSTHROUGH,
598 TRANSFER_MPASSTHROUGH,
603 struct iax2_registry {
604 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
606 char secret[80]; /*!< Password or key name in []'s */
607 int expire; /*!< Sched ID of expiration */
608 int refresh; /*!< How often to refresh */
609 enum iax_reg_state regstate;
610 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
611 int callno; /*!< Associated call number if applicable */
612 struct sockaddr_in us; /*!< Who the server thinks we are */
613 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
614 AST_LIST_ENTRY(iax2_registry) entry;
617 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
619 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
620 #define MIN_RETRY_TIME 100
621 #define MAX_RETRY_TIME 10000
623 #define MAX_JITTER_BUFFER 50
624 #define MIN_JITTER_BUFFER 10
626 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
628 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
630 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
631 #define TS_GAP_FOR_JB_RESYNC 5000
633 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
634 #define MARK_IAX_SUBCLASS_TX 0x8000
636 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
637 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
638 static int iaxdynamicthreadcount = 0;
639 static int iaxdynamicthreadnum = 0;
640 static int iaxactivethreadcount = 0;
654 /* We use the high order bit as the validated flag, and the lower 15 as the
655 * actual call number */
656 typedef uint16_t callno_entry;
658 struct chan_iax2_pvt {
659 /*! Socket to send/receive on for this call */
661 /*! ast_callid bound to dialog */
662 struct ast_callid *callid;
663 /*! Last received voice format */
664 iax2_format voiceformat;
665 /*! Last received video format */
666 iax2_format videoformat;
667 /*! Last sent voice format */
668 iax2_format svoiceformat;
669 /*! Last sent video format */
670 iax2_format svideoformat;
671 /*! What we are capable of sending */
672 iax2_format capability;
673 /*! Last received timestamp */
675 /*! Last sent timestamp - never send the same timestamp twice in a single call */
676 unsigned int lastsent;
677 /*! Timestamp of the last video frame sent */
678 unsigned int lastvsent;
679 /*! Next outgoing timestamp if everything is good */
680 unsigned int nextpred;
681 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
682 int first_iax_message;
683 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
684 int last_iax_message;
685 /*! True if the last voice we transmitted was not silence/CNG */
686 unsigned int notsilenttx:1;
688 unsigned int pingtime;
689 /*! Max time for initial response */
692 struct sockaddr_in addr;
693 /*! Actual used codec preferences */
694 struct ast_codec_pref prefs;
695 /*! Requested codec preferences */
696 struct ast_codec_pref rprefs;
697 /*! Our call number */
698 unsigned short callno;
699 /*! Our callno_entry entry */
700 callno_entry callno_entry;
702 unsigned short peercallno;
703 /*! Negotiated format, this is only used to remember what format was
704 chosen for an unauthenticated call so that the channel can get
705 created later using the right format */
706 iax2_format chosenformat;
707 /*! Peer selected format */
708 iax2_format peerformat;
709 /*! Peer capability */
710 iax2_format peercapability;
711 /*! timeval that we base our transmission on */
712 struct timeval offset;
713 /*! timeval that we base our delivery on */
714 struct timeval rxcore;
715 /*! The jitterbuffer */
717 /*! active jb read scheduler id */
721 /*! Error, as discovered by the manager */
723 /*! Owner if we have one */
724 struct ast_channel *owner;
725 /*! What's our state? */
726 struct ast_flags state;
727 /*! Expiry (optional) */
729 /*! Next outgoing sequence number */
730 unsigned char oseqno;
731 /*! Next sequence number they have not yet acknowledged */
732 unsigned char rseqno;
733 /*! Next incoming sequence number */
734 unsigned char iseqno;
735 /*! Last incoming sequence number we have acknowledged */
736 unsigned char aseqno;
738 AST_DECLARE_STRING_FIELDS(
740 AST_STRING_FIELD(peer);
741 /*! Default Context */
742 AST_STRING_FIELD(context);
743 /*! Caller ID if available */
744 AST_STRING_FIELD(cid_num);
745 AST_STRING_FIELD(cid_name);
746 /*! Hidden Caller ID (i.e. ANI) if appropriate */
747 AST_STRING_FIELD(ani);
749 AST_STRING_FIELD(dnid);
751 AST_STRING_FIELD(rdnis);
752 /*! Requested Extension */
753 AST_STRING_FIELD(exten);
754 /*! Expected Username */
755 AST_STRING_FIELD(username);
756 /*! Expected Secret */
757 AST_STRING_FIELD(secret);
759 AST_STRING_FIELD(challenge);
760 /*! Public keys permitted keys for incoming authentication */
761 AST_STRING_FIELD(inkeys);
762 /*! Private key for outgoing authentication */
763 AST_STRING_FIELD(outkey);
764 /*! Preferred language */
765 AST_STRING_FIELD(language);
766 /*! Hostname/peername for naming purposes */
767 AST_STRING_FIELD(host);
769 AST_STRING_FIELD(dproot);
770 AST_STRING_FIELD(accountcode);
771 AST_STRING_FIELD(mohinterpret);
772 AST_STRING_FIELD(mohsuggest);
773 /*! received OSP token */
774 AST_STRING_FIELD(osptoken);
775 /*! Default parkinglot */
776 AST_STRING_FIELD(parkinglot);
778 /*! AUTHREJ all AUTHREP frames */
780 /*! permitted authentication methods */
782 /*! permitted encryption methods */
784 /*! Encryption AES-128 Key */
785 ast_aes_encrypt_key ecx;
786 /*! Decryption AES-128 Key corresponding to ecx */
787 ast_aes_decrypt_key mydcx;
788 /*! Decryption AES-128 Key used to decrypt peer frames */
789 ast_aes_decrypt_key dcx;
790 /*! scheduler id associated with iax_key_rotate
791 * for encrypted calls*/
793 /*! 32 bytes of semi-random data */
794 unsigned char semirand[32];
795 /*! Associated registry */
796 struct iax2_registry *reg;
797 /*! Associated peer for poking */
798 struct iax2_peer *peerpoke;
803 /*! Transferring status */
804 enum iax_transfer_state transferring;
805 /*! Transfer identifier */
807 /*! Who we are IAX transferring to */
808 struct sockaddr_in transfer;
809 /*! What's the new call number for the transfer */
810 unsigned short transfercallno;
811 /*! Transfer encrypt AES-128 Key */
812 ast_aes_encrypt_key tdcx;
814 /*! Status of knowledge of peer ADSI capability */
817 /*! Who we are bridged to */
818 unsigned short bridgecallno;
820 int pingid; /*!< Transmit PING request */
821 int lagid; /*!< Retransmit lag request */
822 int autoid; /*!< Auto hangup for Dialplan requestor */
823 int authid; /*!< Authentication rejection ID */
824 int authfail; /*!< Reason to report failure */
825 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
830 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
831 /*! variables inherited from the user definition */
832 struct ast_variable *vars;
833 /*! variables transmitted in a NEW packet */
834 struct ast_variable *iaxvars;
835 /*! last received remote rr */
836 struct iax_rr remote_rr;
837 /*! Current base time: (just for stats) */
839 /*! Dropped frame count: (just for stats) */
841 /*! received frame count: (just for stats) */
843 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
844 unsigned char calltoken_ie_len;
845 /*! hold all signaling frames from the pbx thread until we have a destination callno */
847 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
848 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
851 struct signaling_queue_entry {
853 AST_LIST_ENTRY(signaling_queue_entry) next;
861 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
862 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
864 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
865 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
866 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
868 struct call_number_pool {
871 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
874 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
876 /*! table of available call numbers */
877 static struct call_number_pool callno_pool;
879 /*! table of available trunk call numbers */
880 static struct call_number_pool callno_pool_trunk;
883 * \brief a list of frames that may need to be retransmitted
885 * \note The contents of this list do not need to be explicitly destroyed
886 * on module unload. This is because all active calls are destroyed, and
887 * all frames in this queue will get destroyed as a part of that process.
889 * \note Contents protected by the iaxsl[] locks
891 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
893 static struct ast_taskprocessor *transmit_processor;
895 static int randomcalltokendata;
897 static const time_t MAX_CALLTOKEN_DELAY = 10;
900 * This module will get much higher performance when doing a lot of
901 * user and peer lookups if the number of buckets is increased from 1.
902 * However, to maintain old behavior for Asterisk 1.4, these are set to
903 * 1 by default. When using multiple buckets, search order through these
904 * containers is considered random, so you will not be able to depend on
905 * the order the entires are specified in iax.conf for matching order. */
907 #define MAX_PEER_BUCKETS 17
909 #define MAX_PEER_BUCKETS 563
911 static struct ao2_container *peers;
913 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
914 static struct ao2_container *users;
916 /*! Table containing peercnt objects for every ip address consuming a callno */
917 static struct ao2_container *peercnts;
919 /*! Table containing custom callno limit rules for a range of ip addresses. */
920 static struct ao2_container *callno_limits;
922 /*! Table containing ip addresses not requiring calltoken validation */
923 static struct ao2_container *calltoken_ignores;
925 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
927 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
929 static uint16_t global_maxcallno;
931 /*! Total num of call numbers allowed to be allocated without calltoken validation */
932 static uint16_t global_maxcallno_nonval;
934 static uint16_t total_nonval_callno_used = 0;
936 /*! peer connection private, keeps track of all the call numbers
937 * consumed by a single ip address */
939 /*! ip address consuming call numbers */
941 /*! Number of call numbers currently used by this ip address */
943 /*! Max call numbers allowed for this ip address */
945 /*! Specifies whether limit is set by a registration or not, if so normal
946 * limit setting rules do not apply to this address. */
950 /*! used by both callno_limits and calltoken_ignores containers */
952 /*! ip address range for custom callno limit rule */
954 /*! callno limit for this ip address range, only used in callno_limits container */
956 /*! delete me marker for reloads */
961 /*! Extension exists */
962 CACHE_FLAG_EXISTS = (1 << 0),
963 /*! Extension is nonexistent */
964 CACHE_FLAG_NONEXISTENT = (1 << 1),
965 /*! Extension can exist */
966 CACHE_FLAG_CANEXIST = (1 << 2),
967 /*! Waiting to hear back response */
968 CACHE_FLAG_PENDING = (1 << 3),
970 CACHE_FLAG_TIMEOUT = (1 << 4),
971 /*! Request transmitted */
972 CACHE_FLAG_TRANSMITTED = (1 << 5),
974 CACHE_FLAG_UNKNOWN = (1 << 6),
976 CACHE_FLAG_MATCHMORE = (1 << 7),
979 struct iax2_dpcache {
980 char peercontext[AST_MAX_CONTEXT];
981 char exten[AST_MAX_EXTENSION];
983 struct timeval expiry;
985 unsigned short callno;
987 AST_LIST_ENTRY(iax2_dpcache) cache_list;
988 AST_LIST_ENTRY(iax2_dpcache) peer_list;
991 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
993 static void reg_source_db(struct iax2_peer *p);
994 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
995 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
997 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
998 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
999 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1001 enum iax2_thread_iostate {
1004 IAX_IOSTATE_PROCESSING,
1005 IAX_IOSTATE_SCHEDREADY,
1008 enum iax2_thread_type {
1009 IAX_THREAD_TYPE_POOL,
1010 IAX_THREAD_TYPE_DYNAMIC,
1013 struct iax2_pkt_buf {
1014 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1016 unsigned char buf[1];
1019 struct iax2_thread {
1020 AST_LIST_ENTRY(iax2_thread) list;
1021 enum iax2_thread_type type;
1022 enum iax2_thread_iostate iostate;
1023 #ifdef SCHED_MULTITHREADED
1024 void (*schedfunc)(const void *);
1025 const void *scheddata;
1027 #ifdef DEBUG_SCHED_MULTITHREAD
1033 struct sockaddr_in iosin;
1034 unsigned char readbuf[4096];
1042 ast_mutex_t init_lock;
1043 ast_cond_t init_cond;
1044 /*! if this thread is processing a full frame,
1045 some information about that frame will be stored
1046 here, so we can avoid dispatching any more full
1047 frames for that callno to other threads */
1049 unsigned short callno;
1050 struct sockaddr_in sin;
1054 /*! Queued up full frames for processing. If more full frames arrive for
1055 * a call which this thread is already processing a full frame for, they
1056 * are queued up here. */
1057 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1062 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1063 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1064 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1066 static void *iax2_process_thread(void *data);
1067 static void iax2_destroy(int callno);
1069 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1071 ast_mutex_lock(lock);
1072 ast_cond_signal(cond);
1073 ast_mutex_unlock(lock);
1077 * \brief an array of iax2 pvt structures
1079 * The container for active chan_iax2_pvt structures is implemented as an
1080 * array for extremely quick direct access to the correct pvt structure
1081 * based on the local call number. The local call number is used as the
1082 * index into the array where the associated pvt structure is stored.
1084 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1086 static struct ast_callid *iax_pvt_callid_get(int callno)
1088 if (iaxs[callno]->callid) {
1089 return ast_callid_ref(iaxs[callno]->callid);
1094 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1096 if (iaxs[callno]->callid) {
1097 ast_callid_unref(iaxs[callno]->callid);
1099 ast_callid_ref(callid);
1100 iaxs[callno]->callid = callid;
1103 static void iax_pvt_callid_new(int callno)
1105 struct ast_callid *callid = ast_create_callid();
1106 char buffer[AST_CALLID_BUFFER_LENGTH];
1107 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1108 iax_pvt_callid_set(callno, callid);
1109 ast_callid_unref(callid);
1113 * \brief Another container of iax2_pvt structures
1115 * Active IAX2 pvt structs are also stored in this container, if they are a part
1116 * of an active call where we know the remote side's call number. The reason
1117 * for this is that incoming media frames do not contain our call number. So,
1118 * instead of having to iterate the entire iaxs array, we use this container to
1119 * look up calls where the remote side is using a given call number.
1121 static struct ao2_container *iax_peercallno_pvts;
1124 * \brief chan_iax2_pvt structure locks
1126 * These locks are used when accessing a pvt structure in the iaxs array.
1127 * The index used here is the same as used in the iaxs array. It is the
1128 * local call number for the associated pvt struct.
1130 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1133 * * \brief Another container of iax2_pvt structures
1135 * Active IAX2 pvt stucts used during transfering a call are stored here.
1137 static struct ao2_container *iax_transfercallno_pvts;
1139 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1140 but keeps the division between trunked and non-trunked better. */
1141 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1143 /* Debug routines... */
1144 static struct sockaddr_in debugaddr;
1146 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1149 (sin && debugaddr.sin_addr.s_addr &&
1150 (!ntohs(debugaddr.sin_port) ||
1151 debugaddr.sin_port == sin->sin_port) &&
1152 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1154 iax_showframe(f, fhi, rx, sin, datalen);
1157 iax_showframe(f, fhi, rx, sin, datalen);
1163 static void iax_debug_output(const char *data)
1166 ast_verbose("%s", data);
1169 static void iax_error_output(const char *data)
1171 ast_log(LOG_WARNING, "%s", data);
1174 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1179 va_start(args, fmt);
1180 vsnprintf(buf, sizeof(buf), fmt, args);
1183 ast_log(LOG_ERROR, "%s", buf);
1186 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1191 va_start(args, fmt);
1192 vsnprintf(buf, sizeof(buf), fmt, args);
1195 ast_log(LOG_WARNING, "%s", buf);
1198 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1203 va_start(args, fmt);
1204 vsnprintf(buf, sizeof(buf), fmt, args);
1207 ast_verbose("%s", buf);
1210 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);
1211 static int expire_registry(const void *data);
1212 static int iax2_answer(struct ast_channel *c);
1213 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1214 static int iax2_devicestate(const char *data);
1215 static int iax2_digit_begin(struct ast_channel *c, char digit);
1216 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1217 static int iax2_do_register(struct iax2_registry *reg);
1218 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1219 static int iax2_hangup(struct ast_channel *c);
1220 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1221 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1222 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1223 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1224 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1225 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1226 static int iax2_sendtext(struct ast_channel *c, const char *text);
1227 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1228 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1229 static int iax2_transfer(struct ast_channel *c, const char *dest);
1230 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1231 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1233 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1234 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1235 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1236 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1237 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1238 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1239 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1240 static struct ast_frame *iax2_read(struct ast_channel *c);
1241 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1242 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1243 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1244 static void *iax2_dup_variable_datastore(void *);
1245 static void prune_peers(void);
1246 static void prune_users(void);
1247 static void iax2_free_variable_datastore(void *);
1249 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1250 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1251 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1252 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1253 static void build_rand_pad(unsigned char *buf, ssize_t len);
1254 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1255 static int replace_callno(const void *obj);
1256 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry);
1257 static void network_change_event_cb(const struct ast_event *, void *);
1258 static void acl_change_event_cb(const struct ast_event *, void *);
1260 static struct ast_channel_tech iax2_tech = {
1262 .description = tdesc,
1263 .properties = AST_CHAN_TP_WANTSJITTER,
1264 .requester = iax2_request,
1265 .devicestate = iax2_devicestate,
1266 .send_digit_begin = iax2_digit_begin,
1267 .send_digit_end = iax2_digit_end,
1268 .send_text = iax2_sendtext,
1269 .send_image = iax2_sendimage,
1270 .send_html = iax2_sendhtml,
1272 .hangup = iax2_hangup,
1273 .answer = iax2_answer,
1275 .write = iax2_write,
1276 .write_video = iax2_write,
1277 .indicate = iax2_indicate,
1278 .setoption = iax2_setoption,
1279 .queryoption = iax2_queryoption,
1280 .bridge = iax2_bridge,
1281 .transfer = iax2_transfer,
1282 .fixup = iax2_fixup,
1283 .func_channel_read = acf_channel_read,
1288 * \brief Obtain the owner channel lock if the owner exists.
1290 * \param callno IAX2 call id.
1292 * \note Assumes the iaxsl[callno] lock is already obtained.
1295 * IMPORTANT NOTE!!! Any time this function is used, even if
1296 * iaxs[callno] was valid before calling it, it may no longer be
1297 * valid after calling it. This function may unlock and lock
1298 * the mutex associated with this callno, meaning that another
1299 * thread may grab it and destroy the call.
1303 static void iax2_lock_owner(int callno)
1306 if (!iaxs[callno] || !iaxs[callno]->owner) {
1307 /* There is no owner lock to get. */
1310 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1311 /* We got the lock */
1314 /* Avoid deadlock by pausing and trying again */
1315 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1319 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
1321 /* The MWI subscriptions exist just so the core knows we care about those
1322 * mailboxes. However, we just grab the events out of the cache when it
1323 * is time to send MWI, since it is only sent with a REGACK. */
1326 static void network_change_event_subscribe(void)
1328 if (!network_change_event_subscription) {
1329 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1330 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1334 static void network_change_event_unsubscribe(void)
1336 if (network_change_event_subscription) {
1337 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1341 static void acl_change_event_subscribe(void)
1343 if (!acl_change_event_subscription) {
1344 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1345 acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
1349 static void acl_change_event_unsubscribe(void)
1351 if (acl_change_event_subscription) {
1352 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1356 static int network_change_event_sched_cb(const void *data)
1358 struct iax2_registry *reg;
1359 network_change_event_sched_id = -1;
1360 AST_LIST_LOCK(®istrations);
1361 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1362 iax2_do_register(reg);
1364 AST_LIST_UNLOCK(®istrations);
1369 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1371 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1372 if (network_change_event_sched_id == -1) {
1373 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1378 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
1380 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1385 /*! \brief Send manager event at call setup to link between Asterisk channel name
1386 and IAX2 call identifiers */
1387 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1389 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1390 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1391 pvt->owner ? ast_channel_name(pvt->owner) : "",
1392 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1395 static const struct ast_datastore_info iax2_variable_datastore_info = {
1396 .type = "IAX2_VARIABLE",
1397 .duplicate = iax2_dup_variable_datastore,
1398 .destroy = iax2_free_variable_datastore,
1401 static void *iax2_dup_variable_datastore(void *old)
1403 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1404 struct ast_var_t *oldvar, *newvar;
1406 newlist = ast_calloc(sizeof(*newlist), 1);
1408 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1412 AST_LIST_HEAD_INIT(newlist);
1413 AST_LIST_LOCK(oldlist);
1414 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1415 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1417 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1419 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1421 AST_LIST_UNLOCK(oldlist);
1425 static void iax2_free_variable_datastore(void *old)
1427 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1428 struct ast_var_t *oldvar;
1430 AST_LIST_LOCK(oldlist);
1431 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1434 AST_LIST_UNLOCK(oldlist);
1435 AST_LIST_HEAD_DESTROY(oldlist);
1440 /* WARNING: insert_idle_thread should only ever be called within the
1441 * context of an iax2_process_thread() thread.
1443 static void insert_idle_thread(struct iax2_thread *thread)
1445 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1446 AST_LIST_LOCK(&dynamic_list);
1447 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1448 AST_LIST_UNLOCK(&dynamic_list);
1450 AST_LIST_LOCK(&idle_list);
1451 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1452 AST_LIST_UNLOCK(&idle_list);
1458 static struct iax2_thread *find_idle_thread(void)
1460 struct iax2_thread *thread = NULL;
1462 /* Pop the head of the idle list off */
1463 AST_LIST_LOCK(&idle_list);
1464 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1465 AST_LIST_UNLOCK(&idle_list);
1467 /* If we popped a thread off the idle list, just return it */
1469 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1473 /* Pop the head of the dynamic list off */
1474 AST_LIST_LOCK(&dynamic_list);
1475 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1476 AST_LIST_UNLOCK(&dynamic_list);
1478 /* If we popped a thread off the dynamic list, just return it */
1480 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1484 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1485 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1488 /* Set default values */
1489 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1490 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1491 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1493 /* Initialize lock and condition */
1494 ast_mutex_init(&thread->lock);
1495 ast_cond_init(&thread->cond, NULL);
1496 ast_mutex_init(&thread->init_lock);
1497 ast_cond_init(&thread->init_cond, NULL);
1498 ast_mutex_lock(&thread->init_lock);
1500 /* Create thread and send it on it's way */
1501 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1502 ast_cond_destroy(&thread->cond);
1503 ast_mutex_destroy(&thread->lock);
1504 ast_mutex_unlock(&thread->init_lock);
1505 ast_cond_destroy(&thread->init_cond);
1506 ast_mutex_destroy(&thread->init_lock);
1511 /* this thread is not processing a full frame (since it is idle),
1512 so ensure that the field for the full frame call number is empty */
1513 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1515 /* Wait for the thread to be ready before returning it to the caller */
1516 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1518 /* Done with init_lock */
1519 ast_mutex_unlock(&thread->init_lock);
1524 #ifdef SCHED_MULTITHREADED
1525 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1527 struct iax2_thread *thread = NULL;
1528 static time_t lasterror;
1531 thread = find_idle_thread();
1533 if (thread != NULL) {
1534 thread->schedfunc = func;
1535 thread->scheddata = data;
1536 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1537 #ifdef DEBUG_SCHED_MULTITHREAD
1538 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1540 signal_condition(&thread->lock, &thread->cond);
1545 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1550 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1553 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1554 ast_sched_cb callback, const void *data)
1556 return ast_sched_replace(id, con, when, callback, data);
1559 static int iax2_sched_add(struct ast_sched_context *con, int when,
1560 ast_sched_cb callback, const void *data)
1562 return ast_sched_add(con, when, callback, data);
1565 static int send_ping(const void *data);
1567 static void __send_ping(const void *data)
1569 int callno = (long) data;
1571 ast_mutex_lock(&iaxsl[callno]);
1574 if (iaxs[callno]->peercallno) {
1575 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1576 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1577 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1581 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1584 ast_mutex_unlock(&iaxsl[callno]);
1587 static int send_ping(const void *data)
1589 int callno = (long) data;
1590 ast_mutex_lock(&iaxsl[callno]);
1591 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1592 iaxs[callno]->pingid = -1;
1594 ast_mutex_unlock(&iaxsl[callno]);
1596 #ifdef SCHED_MULTITHREADED
1597 if (schedule_action(__send_ping, data))
1604 static void encmethods_to_str(int e, struct ast_str **buf)
1606 ast_str_set(buf, 0, "(");
1607 if (e & IAX_ENCRYPT_AES128) {
1608 ast_str_append(buf, 0, "aes128");
1610 if (e & IAX_ENCRYPT_KEYROTATE) {
1611 ast_str_append(buf, 0, ",keyrotate");
1613 if (ast_str_strlen(*buf) > 1) {
1614 ast_str_append(buf, 0, ")");
1616 ast_str_set(buf, 0, "No");
1620 static int get_encrypt_methods(const char *s)
1623 if (!strcasecmp(s, "aes128"))
1624 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1625 else if (ast_true(s))
1626 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1632 static int send_lagrq(const void *data);
1634 static void __send_lagrq(const void *data)
1636 int callno = (long) data;
1638 ast_mutex_lock(&iaxsl[callno]);
1641 if (iaxs[callno]->peercallno) {
1642 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1643 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1644 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1648 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1651 ast_mutex_unlock(&iaxsl[callno]);
1654 static int send_lagrq(const void *data)
1656 int callno = (long) data;
1657 ast_mutex_lock(&iaxsl[callno]);
1658 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1659 iaxs[callno]->lagid = -1;
1661 ast_mutex_unlock(&iaxsl[callno]);
1663 #ifdef SCHED_MULTITHREADED
1664 if (schedule_action(__send_lagrq, data))
1670 static unsigned char compress_subclass(iax2_format subclass)
1674 /* If it's 64 or smaller, just return it */
1675 if (subclass < IAX_FLAG_SC_LOG)
1677 /* Otherwise find its power */
1678 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1679 if (subclass & (1LL << x)) {
1681 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1687 return power | IAX_FLAG_SC_LOG;
1690 static iax2_format uncompress_subclass(unsigned char csub)
1692 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1693 if (csub & IAX_FLAG_SC_LOG) {
1694 /* special case for 'compressed' -1 */
1698 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1704 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1706 struct ast_format_cap *cap;
1707 struct ast_format tmpfmt;
1708 iax2_format format = 0;
1709 if ((cap = ast_format_cap_alloc_nolock())) {
1710 ast_format_clear(&tmpfmt);
1711 ast_format_cap_from_old_bitfield(cap, formats);
1712 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1713 format = ast_format_to_old_bitfield(&tmpfmt);
1714 cap = ast_format_cap_destroy(cap);
1720 static iax2_format iax2_best_codec(iax2_format formats)
1722 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1723 struct ast_format tmpfmt;
1728 ast_format_clear(&tmpfmt);
1729 ast_format_cap_from_old_bitfield(cap, formats);
1730 ast_best_codec(cap, &tmpfmt);
1731 cap = ast_format_cap_destroy(cap);
1732 return ast_format_to_old_bitfield(&tmpfmt);
1735 const char *iax2_getformatname(iax2_format format)
1737 struct ast_format tmpfmt;
1738 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1742 return ast_getformatname(&tmpfmt);
1745 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1747 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1752 ast_format_cap_from_old_bitfield(cap, format);
1753 ast_getformatname_multiple(codec_buf, len, cap);
1754 cap = ast_format_cap_destroy(cap);
1759 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1762 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1767 ast_format_cap_from_old_bitfield(cap, *formats);
1768 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1769 *formats = ast_format_cap_to_old_bitfield(cap);
1770 cap = ast_format_cap_destroy(cap);
1775 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1778 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1782 ast_format_cap_from_old_bitfield(cap, formats);
1783 res = ast_data_add_codecs(root, node_name, cap);
1784 cap = ast_format_cap_destroy(cap);
1789 * \note The only member of the peer passed here guaranteed to be set is the name field
1791 static int peer_hash_cb(const void *obj, const int flags)
1793 const struct iax2_peer *peer = obj;
1794 const char *name = obj;
1796 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1800 * \note The only member of the peer passed here guaranteed to be set is the name field
1802 static int peer_cmp_cb(void *obj, void *arg, int flags)
1804 struct iax2_peer *peer = obj, *peer2 = arg;
1805 const char *name = arg;
1807 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1808 CMP_MATCH | CMP_STOP : 0;
1812 * \note The only member of the user passed here guaranteed to be set is the name field
1814 static int user_hash_cb(const void *obj, const int flags)
1816 const struct iax2_user *user = obj;
1817 const char *name = obj;
1819 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1823 * \note The only member of the user passed here guaranteed to be set is the name field
1825 static int user_cmp_cb(void *obj, void *arg, int flags)
1827 struct iax2_user *user = obj, *user2 = arg;
1828 const char *name = arg;
1830 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1831 CMP_MATCH | CMP_STOP : 0;
1835 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1836 * so do not call it with a pvt lock held.
1838 static struct iax2_peer *find_peer(const char *name, int realtime)
1840 struct iax2_peer *peer = NULL;
1842 peer = ao2_find(peers, name, OBJ_KEY);
1844 /* Now go for realtime if applicable */
1845 if(!peer && realtime)
1846 peer = realtime_peer(name, NULL);
1851 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1857 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1863 static struct iax2_user *find_user(const char *name)
1865 return ao2_find(users, name, OBJ_KEY);
1867 static inline struct iax2_user *user_ref(struct iax2_user *user)
1873 static inline struct iax2_user *user_unref(struct iax2_user *user)
1879 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1881 struct iax2_peer *peer = NULL;
1883 struct ao2_iterator i;
1885 i = ao2_iterator_init(peers, 0);
1886 while ((peer = ao2_iterator_next(&i))) {
1887 struct sockaddr_in peer_addr;
1889 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1891 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1892 (peer_addr.sin_port == sin.sin_port)) {
1893 ast_copy_string(host, peer->name, len);
1900 ao2_iterator_destroy(&i);
1903 peer = realtime_peer(NULL, &sin);
1905 ast_copy_string(host, peer->name, len);
1914 /*!\note Assumes the lock on the pvt is already held, when
1915 * iax2_destroy_helper() is called. */
1916 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1918 /* Decrement AUTHREQ count if needed */
1919 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1920 struct iax2_user *user;
1922 user = ao2_find(users, pvt->username, OBJ_KEY);
1924 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1928 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1930 /* No more pings or lagrq's */
1931 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1932 pvt->pingid = DONT_RESCHEDULE;
1933 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1934 pvt->lagid = DONT_RESCHEDULE;
1935 AST_SCHED_DEL(sched, pvt->autoid);
1936 AST_SCHED_DEL(sched, pvt->authid);
1937 AST_SCHED_DEL(sched, pvt->initid);
1938 AST_SCHED_DEL(sched, pvt->jbid);
1939 AST_SCHED_DEL(sched, pvt->keyrotateid);
1942 static void iax2_frame_free(struct iax_frame *fr)
1944 AST_SCHED_DEL(sched, fr->retrans);
1948 static int scheduled_destroy(const void *vid)
1950 unsigned short callno = PTR_TO_CALLNO(vid);
1951 ast_mutex_lock(&iaxsl[callno]);
1953 ast_debug(1, "Really destroying %d now...\n", callno);
1954 iax2_destroy(callno);
1956 ast_mutex_unlock(&iaxsl[callno]);
1960 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1963 ast_free(s->f.data.ptr);
1968 /*! \brief This function must be called once we are sure the other side has
1969 * given us a call number. All signaling is held here until that point. */
1970 static void send_signaling(struct chan_iax2_pvt *pvt)
1972 struct signaling_queue_entry *s = NULL;
1974 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1975 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1976 free_signaling_queue_entry(s);
1978 pvt->hold_signaling = 0;
1981 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1982 * we have received a destination call number. */
1983 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1985 struct signaling_queue_entry *qe;
1987 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1988 return 1; /* do not queue this frame */
1989 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1990 return -1; /* out of memory */
1993 /* copy ast_frame into our queue entry */
1995 if (qe->f.datalen) {
1996 /* if there is data in this frame copy it over as well */
1997 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1998 free_signaling_queue_entry(qe);
2001 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2003 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2008 static void pvt_destructor(void *obj)
2010 struct chan_iax2_pvt *pvt = obj;
2011 struct iax_frame *cur = NULL;
2012 struct signaling_queue_entry *s = NULL;
2014 ast_mutex_lock(&iaxsl[pvt->callno]);
2016 iax2_destroy_helper(pvt);
2018 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2019 pvt->callno_entry = 0;
2022 ast_set_flag64(pvt, IAX_ALREADYGONE);
2024 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2025 /* Cancel any pending transmissions */
2029 ast_mutex_unlock(&iaxsl[pvt->callno]);
2031 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2032 free_signaling_queue_entry(s);
2036 pvt->reg->callno = 0;
2042 ast_variables_destroy(pvt->vars);
2046 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2047 iax2_frame_free(frame.data);
2050 jb_destroy(pvt->jb);
2051 ast_string_field_free_memory(pvt);
2055 ast_callid_unref(pvt->callid);
2060 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2062 struct chan_iax2_pvt *tmp;
2065 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2069 if (ast_string_field_init(tmp, 32)) {
2081 tmp->keyrotateid = -1;
2083 ast_string_field_set(tmp,exten, "s");
2084 ast_string_field_set(tmp,host, host);
2088 jbconf.max_jitterbuf = maxjitterbuffer;
2089 jbconf.resync_threshold = resyncthreshold;
2090 jbconf.max_contig_interp = maxjitterinterps;
2091 jbconf.target_extra = jittertargetextra;
2092 jb_setconf(tmp->jb,&jbconf);
2094 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2096 tmp->hold_signaling = 1;
2097 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2102 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2104 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2106 size_t afdatalen = new->afdatalen;
2107 memcpy(new, fr, sizeof(*new));
2108 iax_frame_wrap(new, &fr->af);
2109 new->afdatalen = afdatalen;
2112 new->direction = DIRECTION_INGRESS;
2117 /* keep these defined in this order. They are used in find_callno to
2118 * determine whether or not a new call number should be allowed. */
2120 /* do not allow a new call number, only search ones in use for match */
2122 /* search for match first, then allow a new one to be allocated */
2124 /* do not search for match, force a new call number */
2126 /* do not search for match, force a new call number. Signifies call number
2127 * has been calltoken validated */
2128 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2131 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2133 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2134 (cur->addr.sin_port == sin->sin_port)) {
2135 /* This is the main host */
2136 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2137 (check_dcallno ? dcallno == cur->callno : 1) ) {
2138 /* That's us. Be sure we keep track of the peer call number */
2142 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2143 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2144 /* We're transferring */
2145 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2151 static int make_trunk(unsigned short callno, int locked)
2156 if (iaxs[callno]->oseqno) {
2157 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2160 if (callno >= TRUNK_CALL_START) {
2161 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2165 if (get_unused_callno(
2167 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2169 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2173 x = CALLNO_ENTRY_GET_CALLNO(entry);
2174 ast_mutex_lock(&iaxsl[x]);
2177 * \note We delete these before switching the slot, because if
2178 * they fire in the meantime, they will generate a warning.
2180 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2181 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2182 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2183 iaxs[x] = iaxs[callno];
2184 iaxs[x]->callno = x;
2186 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2187 * before assigning the new one */
2188 if (iaxs[x]->callno_entry) {
2191 MIN_REUSE_TIME * 1000,
2193 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2196 iaxs[x]->callno_entry = entry;
2198 iaxs[callno] = NULL;
2199 /* Update the two timers that should have been started */
2200 iaxs[x]->pingid = iax2_sched_add(sched,
2201 ping_time * 1000, send_ping, (void *)(long)x);
2202 iaxs[x]->lagid = iax2_sched_add(sched,
2203 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2206 ast_mutex_unlock(&iaxsl[callno]);
2209 ast_mutex_unlock(&iaxsl[x]);
2211 /* We moved this call from a non-trunked to a trunked call */
2212 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2217 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2219 if (!pvt->transfercallno) {
2220 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2224 ao2_link(iax_transfercallno_pvts, pvt);
2227 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2229 if (!pvt->transfercallno) {
2230 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2234 ao2_unlink(iax_transfercallno_pvts, pvt);
2236 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2238 if (!pvt->peercallno) {
2239 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2243 ao2_link(iax_peercallno_pvts, pvt);
2246 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2248 if (!pvt->peercallno) {
2249 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2253 ao2_unlink(iax_peercallno_pvts, pvt);
2256 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2258 struct addr_range *lim = obj;
2263 static int addr_range_hash_cb(const void *obj, const int flags)
2265 const struct addr_range *lim = obj;
2266 struct sockaddr_in sin;
2267 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2268 return abs((int) sin.sin_addr.s_addr);
2271 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2273 struct addr_range *lim1 = obj, *lim2 = arg;
2274 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2275 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2276 CMP_MATCH | CMP_STOP : 0;
2279 static int peercnt_hash_cb(const void *obj, const int flags)
2281 const struct peercnt *peercnt = obj;
2282 return abs((int) peercnt->addr);
2285 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2287 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2288 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2291 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2293 struct addr_range *addr_range = obj;
2294 struct sockaddr_in *sin = arg;
2295 struct sockaddr_in ha_netmask_sin;
2296 struct sockaddr_in ha_addr_sin;
2298 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2299 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2301 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2302 return CMP_MATCH | CMP_STOP;
2310 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2312 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2314 struct addr_range *addr_range;
2315 struct iax2_peer *peer = NULL;
2316 struct iax2_user *user = NULL;
2317 /* if no username is given, check for guest accounts */
2318 const char *find = S_OR(name, "guest");
2319 int res = 1; /* required by default */
2321 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2322 /* There are only two cases in which calltoken validation is not required.
2323 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2324 * the peer definition has not set the requirecalltoken option.
2325 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2328 /* ----- Case 1 ----- */
2329 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2330 ao2_ref(addr_range, -1);
2334 /* ----- Case 2 ----- */
2335 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2336 calltoken_required = user->calltoken_required;
2337 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2338 calltoken_required = user->calltoken_required;
2339 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2340 calltoken_required = peer->calltoken_required;
2341 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2342 calltoken_required = peer->calltoken_required;
2352 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);
2353 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2354 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2364 * \brief set peercnt callno limit.
2367 * First looks in custom definitions. If not found, global limit
2368 * is used. Entries marked as reg already have
2369 * a custom limit set by a registration and are not modified.
2371 static void set_peercnt_limit(struct peercnt *peercnt)
2373 uint16_t limit = global_maxcallno;
2374 struct addr_range *addr_range;
2375 struct sockaddr_in sin = {
2376 .sin_addr.s_addr = peercnt->addr,
2380 if (peercnt->reg && peercnt->limit) {
2381 return; /* this peercnt has a custom limit set by a registration */
2384 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2385 limit = addr_range->limit;
2386 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2387 ao2_ref(addr_range, -1);
2390 peercnt->limit = limit;
2395 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2397 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2399 struct peercnt *peercnt = obj;
2401 set_peercnt_limit(peercnt);
2402 ast_debug(1, "Reset limits for peercnts table\n");
2409 * \brief returns match if delme is set.
2411 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2413 struct addr_range *addr_range = obj;
2415 return addr_range->delme ? CMP_MATCH : 0;
2420 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2422 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2424 /* this function turns off and on custom callno limits set by peer registration */
2425 struct peercnt *peercnt;
2426 struct peercnt tmp = {
2429 struct sockaddr_in sin;
2431 ast_sockaddr_to_sin(sockaddr, &sin);
2433 tmp.addr = sin.sin_addr.s_addr;
2435 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2438 peercnt->limit = limit;
2440 set_peercnt_limit(peercnt);
2442 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2443 ao2_ref(peercnt, -1); /* decrement ref from find */
2449 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2451 * \details First searches for the address in the peercnts table. If found
2452 * the current count is incremented. If not found a new peercnt is allocated
2453 * and linked into the peercnts table with a call number count of 1.
2455 static int peercnt_add(struct sockaddr_in *sin)
2457 struct peercnt *peercnt;
2458 unsigned long addr = sin->sin_addr.s_addr;
2460 struct peercnt tmp = {
2464 /* Reasoning for peercnts container lock: Two identical ip addresses
2465 * could be added by different threads at the "same time". Without the container
2466 * lock, both threads could alloc space for the same object and attempt
2467 * to link to table. With the lock, one would create the object and link
2468 * to table while the other would find the already created peercnt object
2469 * rather than creating a new one. */
2471 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2473 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2475 /* create and set defaults */
2476 peercnt->addr = addr;
2477 set_peercnt_limit(peercnt);
2478 /* guarantees it does not go away after unlocking table
2479 * ao2_find automatically adds this */
2480 ao2_link(peercnts, peercnt);
2482 ao2_unlock(peercnts);
2486 /* check to see if the address has hit its callno limit. If not increment cur. */
2487 if (peercnt->limit > peercnt->cur) {
2489 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2490 } else { /* max num call numbers for this peer has been reached! */
2491 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2495 /* clean up locks and ref count */
2496 ao2_unlock(peercnt);
2497 ao2_unlock(peercnts);
2498 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2505 * \brief decrements a peercnts table entry
2507 static void peercnt_remove(struct peercnt *peercnt)
2509 struct sockaddr_in sin = {
2510 .sin_addr.s_addr = peercnt->addr,
2514 * Container locked here since peercnt may be unlinked from
2515 * list. If left unlocked, peercnt_add could try and grab this
2516 * entry from the table and modify it at the "same time" this
2517 * thread attemps to unlink it.
2521 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2522 /* if this was the last connection from the peer remove it from table */
2523 if (peercnt->cur == 0) {
2524 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2526 ao2_unlock(peercnts);
2531 * \brief called by scheduler to decrement object
2533 static int peercnt_remove_cb(const void *obj)
2535 struct peercnt *peercnt = (struct peercnt *) obj;
2537 peercnt_remove(peercnt);
2538 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2545 * \brief decrements peercnts connection count, finds by addr
2547 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2549 struct peercnt *peercnt;
2550 struct peercnt tmp = {
2551 .addr = sin->sin_addr.s_addr,
2554 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2555 peercnt_remove(peercnt);
2556 ao2_ref(peercnt, -1); /* decrement ref from find */
2563 * \brief Create callno_limit entry based on configuration
2565 static void build_callno_limits(struct ast_variable *v)
2567 struct addr_range *addr_range = NULL;
2568 struct addr_range tmp;
2574 for (; v; v = v->next) {
2578 ha = ast_append_ha("permit", v->name, NULL, &error);
2580 /* check for valid config information */
2582 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2584 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2585 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2590 ast_copy_ha(ha, &tmp.ha);
2591 /* find or create the addr_range */
2592 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2593 ao2_lock(addr_range);
2595 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2597 return; /* out of memory */
2600 /* copy over config data into addr_range object */
2601 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2602 ast_free_ha(ha); /* cleanup the tmp ha */
2603 addr_range->limit = limit;
2604 addr_range->delme = 0;
2608 ao2_unlock(addr_range);
2610 ao2_link(callno_limits, addr_range);
2612 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2618 * \brief Create calltoken_ignores entry based on configuration
2620 static int add_calltoken_ignore(const char *addr)
2622 struct addr_range tmp;
2623 struct addr_range *addr_range = NULL;
2624 struct ast_ha *ha = NULL;
2627 if (ast_strlen_zero(addr)) {
2628 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2632 ha = ast_append_ha("permit", addr, NULL, &error);
2634 /* check for valid config information */
2636 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2640 ast_copy_ha(ha, &tmp.ha);
2641 /* find or create the addr_range */
2642 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2643 ao2_lock(addr_range);
2644 addr_range->delme = 0;
2645 ao2_unlock(addr_range);
2646 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2647 /* copy over config data into addr_range object */
2648 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2649 ao2_link(calltoken_ignores, addr_range);
2656 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2661 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2663 struct ao2_iterator i;
2664 struct peercnt *peercnt;
2665 struct sockaddr_in sin;
2670 e->command = "iax2 show callnumber usage";
2672 "Usage: iax2 show callnumber usage [IP address]\n"
2673 " Shows current IP addresses which are consuming iax2 call numbers\n";
2678 if (a->argc < 4 || a->argc > 5)
2679 return CLI_SHOWUSAGE;
2682 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2685 i = ao2_iterator_init(peercnts, 0);
2686 while ((peercnt = ao2_iterator_next(&i))) {
2687 sin.sin_addr.s_addr = peercnt->addr;
2689 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2690 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2691 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2692 ao2_ref(peercnt, -1);
2697 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2699 ao2_ref(peercnt, -1);
2701 ao2_iterator_destroy(&i);
2704 size_t pool_avail = callno_pool.available;
2705 size_t trunk_pool_avail = callno_pool_trunk.available;
2707 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2708 "Non-CallToken Validated Callno Used: %d\n",
2709 global_maxcallno_nonval,
2710 total_nonval_callno_used);
2712 ast_cli(a->fd, "Total Available Callno: %zu\n"
2713 "Regular Callno Available: %zu\n"
2714 "Trunk Callno Available: %zu\n",
2715 pool_avail + trunk_pool_avail,
2718 } else if (a->argc == 5 && !found) {
2719 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2729 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2731 struct call_number_pool *pool = NULL;
2736 case CALLNO_TYPE_NORMAL:
2737 pool = &callno_pool;
2739 case CALLNO_TYPE_TRUNK:
2740 pool = &callno_pool_trunk;
2747 /* If we fail, make sure this has a defined value */
2750 /* We lock here primarily to ensure thread safety of the
2751 * total_nonval_callno_used check and increment */
2752 ast_mutex_lock(&callno_pool_lock);
2754 /* Bail out if we don't have any available call numbers */
2755 if (!pool->available) {
2756 ast_log(LOG_WARNING, "Out of call numbers\n");
2757 ast_mutex_unlock(&callno_pool_lock);
2761 /* Only a certain number of non-validated call numbers should be allocated.
2762 * If there ever is an attack, this separates the calltoken validating users
2763 * from the non-calltoken validating users. */
2764 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2765 ast_log(LOG_WARNING,
2766 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2767 total_nonval_callno_used,
2768 global_maxcallno_nonval);
2769 ast_mutex_unlock(&callno_pool_lock);
2773 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2774 * available call numbers. The array of call numbers begins as an ordered
2775 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2776 * - let's call that x. When a call number is needed we pick a random index
2777 * into the array between 0 and x and use that as our call number. In a
2778 * typical FYD shuffle, we would swap the value that we are extracting with
2779 * the number at x, but in our case we swap and don't touch the value at x
2780 * because it is effectively invisible. We rely on the rest of the IAX2 core
2781 * to return the number to us at some point. Finally, we decrement x by 1
2782 * which establishes our new unused range.
2784 * When numbers are returned to the pool, we put them just past x and bump x
2785 * by 1 so that this number is now available for re-use. */
2787 choice = ast_random() % pool->available;
2789 *entry = pool->numbers[choice];
2790 swap = pool->numbers[pool->available - 1];
2792 pool->numbers[choice] = swap;
2796 CALLNO_ENTRY_SET_VALIDATED(*entry);
2798 total_nonval_callno_used++;
2801 ast_mutex_unlock(&callno_pool_lock);
2806 static int replace_callno(const void *obj)
2808 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2809 struct call_number_pool *pool;
2811 /* We lock here primarily to ensure thread safety of the
2812 * total_nonval_callno_used check and decrement */
2813 ast_mutex_lock(&callno_pool_lock);
2815 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2816 if (total_nonval_callno_used) {
2817 total_nonval_callno_used--;
2820 "Attempted to decrement total non calltoken validated "
2821 "callnumbers below zero. Callno is: %d\n",
2822 CALLNO_ENTRY_GET_CALLNO(entry));
2826 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2827 pool = &callno_pool;
2829 pool = &callno_pool_trunk;
2832 ast_assert(pool->capacity > pool->available);
2834 /* This clears the validated flag */
2835 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2837 pool->numbers[pool->available] = entry;
2840 ast_mutex_unlock(&callno_pool_lock);
2845 static int create_callno_pools(void)
2849 callno_pool.available = callno_pool_trunk.available = 0;
2851 /* We start at 2. 0 and 1 are reserved. */
2852 for (i = 2; i < TRUNK_CALL_START; i++) {
2853 callno_pool.numbers[callno_pool.available] = i;
2854 callno_pool.available++;
2857 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2858 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2859 callno_pool_trunk.available++;
2862 callno_pool.capacity = callno_pool.available;
2863 callno_pool_trunk.capacity = callno_pool_trunk.available;
2865 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2872 * \brief Schedules delayed removal of iax2_pvt call number data
2874 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2875 * avaliable again, and the address from the previous connection must be decremented
2876 * from the peercnts table. This function schedules these operations to take place.
2878 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry)
2881 struct peercnt *peercnt;
2882 struct peercnt tmp = {
2883 .addr = sin->sin_addr.s_addr,
2886 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2887 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2888 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2889 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2891 ao2_ref(peercnt, -1);
2897 MIN_REUSE_TIME * 1000,
2899 CALLNO_ENTRY_TO_PTR(entry));
2904 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2906 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2909 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2911 if (frametype != AST_FRAME_IAX) {
2915 case IAX_COMMAND_NEW:
2916 case IAX_COMMAND_REGREQ:
2917 case IAX_COMMAND_FWDOWNL:
2918 case IAX_COMMAND_REGREL:
2920 case IAX_COMMAND_POKE:
2930 * \note Calling this function while holding another pvt lock can cause a deadlock.
2932 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2936 /* this call is calltoken validated as long as it is either NEW_FORCE
2937 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2938 int validated = (new > NEW_ALLOW) ? 1 : 0;
2941 if (new <= NEW_ALLOW) {
2943 struct chan_iax2_pvt *pvt;
2944 struct chan_iax2_pvt tmp_pvt = {
2946 .peercallno = callno,
2947 .transfercallno = callno,
2949 .frames_received = check_dcallno,
2952 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2953 /* this works for finding normal call numbers not involving transfering */
2954 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2955 if (return_locked) {
2956 ast_mutex_lock(&iaxsl[pvt->callno]);
2963 /* this searches for transfer call numbers that might not get caught otherwise */
2964 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2965 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2966 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2967 if (return_locked) {
2968 ast_mutex_lock(&iaxsl[pvt->callno]);
2976 /* This will occur on the first response to a message that we initiated,
2977 * such as a PING. */
2979 ast_mutex_lock(&iaxsl[dcallno]);
2981 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2982 iaxs[dcallno]->peercallno = callno;
2984 store_by_peercallno(iaxs[dcallno]);
2985 if (!res || !return_locked) {
2986 ast_mutex_unlock(&iaxsl[dcallno]);
2991 ast_mutex_unlock(&iaxsl[dcallno]);
2994 if (!res && (new >= NEW_ALLOW)) {
2996 /* It may seem odd that we look through the peer list for a name for
2997 * this *incoming* call. Well, it is weird. However, users don't
2998 * have an IP address/port number that we can match against. So,
2999 * this is just checking for a peer that has that IP/port and
3000 * assuming that we have a user of the same name. This isn't always
3001 * correct, but it will be changed if needed after authentication. */
3002 if (!iax2_getpeername(*sin, host, sizeof(host)))
3003 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
3005 if (peercnt_add(sin)) {
3006 /* This address has hit its callnumber limit. When the limit
3007 * is reached, the connection is not added to the peercnts table.*/
3011 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3012 /* since we ran out of space, remove the peercnt
3013 * entry we added earlier */
3014 peercnt_remove_by_addr(sin);
3015 ast_log(LOG_WARNING, "No more space\n");
3018 x = CALLNO_ENTRY_GET_CALLNO(entry);
3019 ast_mutex_lock(&iaxsl[x]);
3021 iaxs[x] = new_iax(sin, host);
3024 ast_debug(1, "Creating new call structure %d\n", x);
3025 iaxs[x]->callno_entry = entry;
3026 iaxs[x]->sockfd = sockfd;
3027 iaxs[x]->addr.sin_port = sin->sin_port;
3028 iaxs[x]->addr.sin_family = sin->sin_family;
3029 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
3030 iaxs[x]->peercallno = callno;
3031 iaxs[x]->callno = x;
3032 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3033 iaxs[x]->expiry = min_reg_expire;
3034 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3035 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3036 iaxs[x]->amaflags = amaflags;
3037 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3038 ast_string_field_set(iaxs[x], accountcode, accountcode);
3039 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3040 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3041 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3043 if (iaxs[x]->peercallno) {
3044 store_by_peercallno(iaxs[x]);
3047 ast_log(LOG_WARNING, "Out of resources\n");
3048 ast_mutex_unlock(&iaxsl[x]);
3049 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3053 ast_mutex_unlock(&iaxsl[x]);
3059 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3060 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3063 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3065 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3069 * \brief Queue a frame to a call's owning asterisk channel
3071 * \pre This function assumes that iaxsl[callno] is locked when called.
3073 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3074 * was valid before calling it, it may no longer be valid after calling it.
3075 * This function may unlock and lock the mutex associated with this callno,
3076 * meaning that another thread may grab it and destroy the call.
3078 static int iax2_queue_frame(int callno, struct ast_frame *f)
3080 iax2_lock_owner(callno);
3081 if (iaxs[callno] && iaxs[callno]->owner) {
3082 ast_queue_frame(iaxs[callno]->owner, f);
3083 ast_channel_unlock(iaxs[callno]->owner);
3089 * \brief Queue a hangup frame on the ast_channel owner
3091 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3092 * is active for the given call number.
3094 * \pre Assumes lock for callno is already held.
3096 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3097 * was valid before calling it, it may no longer be valid after calling it.
3098 * This function may unlock and lock the mutex associated with this callno,
3099 * meaning that another thread may grab it and destroy the call.
3101 static int iax2_queue_hangup(int callno)
3103 iax2_lock_owner(callno);
3104 if (iaxs[callno] && iaxs[callno]->owner) {
3105 ast_queue_hangup(iaxs[callno]->owner);
3106 ast_channel_unlock(iaxs[callno]->owner);
3112 * \brief Queue a control frame on the ast_channel owner
3114 * This function queues a control frame on the owner of the IAX2 pvt struct that
3115 * is active for the given call number.
3117 * \pre Assumes lock for callno is already held.
3119 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3120 * was valid before calling it, it may no longer be valid after calling it.
3121 * This function may unlock and lock the mutex associated with this callno,
3122 * meaning that another thread may grab it and destroy the call.
3124 static int iax2_queue_control_data(int callno,
3125 enum ast_control_frame_type control, const void *data, size_t datalen)
3127 iax2_lock_owner(callno);
3128 if (iaxs[callno] && iaxs[callno]->owner) {
3129 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3130 ast_channel_unlock(iaxs[callno]->owner);
3136 * \note This function assumes that iaxsl[callno] is locked when called.
3138 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3139 * was valid before calling it, it may no longer be valid after calling it.
3140 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3141 * associated with this callno, meaning that another thread may grab it and destroy the call.
3143 static int __do_deliver(void *data)
3145 /* Just deliver the packet by using queueing. This is called by
3146 the IAX thread with the iaxsl lock held. */
3147 struct iax_frame *fr = data;
3149 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3150 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3151 iax2_queue_frame(fr->callno, &fr->af);
3152 /* Free our iax frame */
3153 iax2_frame_free(fr);
3154 /* And don't run again */
3158 static int handle_error(void)
3160 /* XXX Ideally we should figure out why an error occurred and then abort those
3161 rather than continuing to try. Unfortunately, the published interface does
3162 not seem to work XXX */
3164 struct sockaddr_in *sin;
3167 struct sock_extended_err e;
3172 m.msg_controllen = sizeof(e);
3174 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3176 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3178 if (m.msg_controllen) {
3179 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3181 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3183 ast_log(LOG_WARNING, "No address detected??\n");
3185 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3192 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3195 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3198 ast_debug(1, "Received error: %s\n", strerror(errno));
3205 static int send_packet(struct iax_frame *f)
3208 int callno = f->callno;
3210 /* Don't send if there was an error, but return error instead */
3211 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3214 /* Called with iaxsl held */
3216 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));
3219 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3220 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3222 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3223 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3227 ast_debug(1, "Received error: %s\n", strerror(errno));
3236 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3237 * for the given call number may disappear during its execution.
3239 static int iax2_predestroy(int callno)
3241 struct ast_channel *c = NULL;
3242 struct chan_iax2_pvt *pvt = iaxs[callno];
3247 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3248 iax2_destroy_helper(pvt);
3249 ast_set_flag64(pvt, IAX_ALREADYGONE);
3252 if ((c = pvt->owner)) {
3253 ast_channel_tech_pvt_set(c, NULL);
3254 iax2_queue_hangup(callno);
3256 ast_module_unref(ast_module_info->self);
3262 static void iax2_destroy(int callno)
3264 struct chan_iax2_pvt *pvt = NULL;
3265 struct ast_channel *owner = NULL;
3268 if ((pvt = iaxs[callno])) {
3270 /* iax2_destroy_helper gets called from this function later on. When
3271 * called twice, we get the (previously) familiar FRACK! errors in
3272 * devmode, from the scheduler. An alternative to this approach is to
3273 * reset the scheduler entries to -1 when they're deleted in
3274 * iax2_destroy_helper(). That approach was previously decided to be
3275 * "wrong" because "the memory is going to be deallocated anyway. Why
3276 * should we be resetting those values?" */
3277 iax2_destroy_helper(pvt);
3281 owner = pvt ? pvt->owner : NULL;
3284 if (ast_channel_trylock(owner)) {
3285 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3286 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3292 iaxs[callno] = NULL;
3299 /* If there's an owner, prod it to give up */
3300 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3301 * because we already hold the owner channel lock. */
3302 ast_queue_hangup(owner);
3305 if (pvt->peercallno) {
3306 remove_by_peercallno(pvt);
3309 if (pvt->transfercallno) {
3310 remove_by_transfercallno(pvt);
3320 ast_channel_unlock(owner);
3324 static int update_packet(struct iax_frame *f)
3326 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3327 struct ast_iax2_full_hdr *fh = f->data;
3328 struct ast_frame af;
3330 /* if frame is encrypted. decrypt before updating it. */
3331 if (f->encmethods) {
3332 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3334 /* Mark this as a retransmission */
3335 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3337 f->iseqno = iaxs[f->callno]->iseqno;
3338 fh->iseqno = f->iseqno;
3340 /* Now re-encrypt the frame */
3341 if (f->encmethods) {
3342 /* since this is a retransmit frame, create a new random padding
3343 * before re-encrypting. */
3344 build_rand_pad(f->semirand, sizeof(f->semirand));
3345 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3350 static int attempt_transmit(const void *data);
3351 static void __attempt_transmit(const void *data)
3353 /* Attempt to transmit the frame to the remote peer...
3354 Called without iaxsl held. */
3355 struct iax_frame *f = (struct iax_frame *)data;
3357 int callno = f->callno;
3358 /* Make sure this call is still active */
3360 ast_mutex_lock(&iaxsl[callno]);
3361 if (callno && iaxs[callno]) {
3362 if ((f->retries < 0) /* Already ACK'd */ ||
3363 (f->retries >= max_retries) /* Too many attempts */) {
3364 /* Record an error if we've transmitted too many times */
3365 if (f->retries >= max_retries) {
3367 /* Transfer timeout */
3368 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3369 } else if (f->final) {
3370 iax2_destroy(callno);
3372 if (iaxs[callno]->owner)
3373 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),ast_channel_name(iaxs[f->callno]->owner), f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3374 iaxs[callno]->error = ETIMEDOUT;
3375 if (iaxs[callno]->owner) {
3376 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3378 iax2_queue_frame(callno, &fr); /* XXX */
3379 /* Remember, owner could disappear */
3380 if (iaxs[callno] && iaxs[callno]->owner)
3381 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3383 if (iaxs[callno]->reg) {
3384 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3385 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3386 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3388 iax2_destroy(callno);
3395 /* Update it if it needs it */
3397 /* Attempt transmission */
3400 /* Try again later after 10 times as long */
3402 if (f->retrytime > MAX_RETRY_TIME)
3403 f->retrytime = MAX_RETRY_TIME;
3404 /* Transfer messages max out at one second */
3405 if (f->transfer && (f->retrytime > 1000))
3406 f->retrytime = 1000;
3407 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3410 /* Make sure it gets freed */
3416 /* Don't attempt delivery, just remove it from the queue */
3417 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3418 ast_mutex_unlock(&iaxsl[callno]);
3419 f->retrans = -1; /* this is safe because this is the scheduled function */
3420 /* Free the IAX frame */
3422 } else if (callno) {
3423 ast_mutex_unlock(&iaxsl[callno]);
3427 static int attempt_transmit(const void *data)
3429 #ifdef SCHED_MULTITHREADED
3430 if (schedule_action(__attempt_transmit, data))
3432 __attempt_transmit(data);
3436 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3438 struct iax2_peer *peer = NULL;
3439 struct iax2_user *user = NULL;
3440 static const char * const choices[] = { "all", NULL };
3445 e->command = "iax2 prune realtime";
3447 "Usage: iax2 prune realtime [<peername>|all]\n"
3448 " Prunes object(s) from the cache\n";
3452 cmplt = ast_cli_complete(a->word, choices, a->n);
3454 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3460 return CLI_SHOWUSAGE;
3461 if (!strcmp(a->argv[3], "all")) {
3464 ast_cli(a->fd, "Cache flushed successfully.\n");
3467 peer = find_peer(a->argv[3], 0);
3468 user = find_user(a->argv[3]);
3471 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3472 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3473 expire_registry(peer_ref(peer));
3474 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3476 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3481 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3482 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3483 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3485 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3487 ao2_unlink(users,user);
3491 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3497 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3501 e->command = "iax2 test losspct";
3503 "Usage: iax2 test losspct <percentage>\n"
3504 " For testing, throws away <percentage> percent of incoming packets\n";
3510 return CLI_SHOWUSAGE;
3512 test_losspct = atoi(a->argv[3]);
3518 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3522 e->command = "iax2 test late";
3524 "Usage: iax2 test late <ms>\n"
3525 " For testing, count the next frame as <ms> ms late\n";
3532 return CLI_SHOWUSAGE;
3534 test_late = atoi(a->argv[3]);
3539 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3543 e->command = "iax2 test resync";
3545 "Usage: iax2 test resync <ms>\n"
3546 " For testing, adjust all future frames by <ms> ms\n";
3553 return CLI_SHOWUSAGE;
3555 test_resync = atoi(a->argv[3]);
3560 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3564 e->command = "iax2 test jitter";
3566 "Usage: iax2 test jitter <ms> <pct>\n"
3567 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3568 " percentage of packets. If <pct> is not specified, adds\n"
3569 " jitter to all packets.\n";
3575 if (a->argc < 4 || a->argc > 5)
3576 return CLI_SHOWUSAGE;
3578 test_jit = atoi(a->argv[3]);
3580 test_jitpct = atoi(a->argv[4]);
3584 #endif /* IAXTESTS */
3586 /*! \brief peer_status: Report Peer status in character string */
3587 /* returns 1 if peer is online, -1 if unmonitored */
3588 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3592 if (peer->lastms < 0) {
3593 ast_copy_string(status, "UNREACHABLE", statuslen);
3594 } else if (peer->lastms > peer->maxms) {
3595 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3597 } else if (peer->lastms) {
3598 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3601 ast_copy_string(status, "UNKNOWN", statuslen);
3604 ast_copy_string(status, "Unmonitored", statuslen);
3610 /*! \brief Show one peer in detail */
3611 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3615 struct iax2_peer *peer;
3616 char codec_buf[512];
3617 struct ast_str *encmethods = ast_str_alloca(256);
3618 int x = 0, load_realtime = 0;
3622 e->command = "iax2 show peer";
3624 "Usage: iax2 show peer <name>\n"
3625 " Display details on specific IAX peer\n";
3629 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3634 return CLI_SHOWUSAGE;
3636 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3638 peer = find_peer(a->argv[3], load_realtime);
3640 struct sockaddr_in peer_addr;
3642 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
3644 encmethods_to_str(peer->encmethods, &encmethods);
3645 ast_cli(a->fd, "\n\n");
3646 ast_cli(a->fd, " * Name : %s\n", peer->name);
3647 ast_cli(a->fd, " Description : %s\n", peer->description);
3648 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3649 ast_cli(a->fd, " Context : %s\n", peer->context);
3650 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3651 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3652 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3653 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3654 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3655 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3656 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3657 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3658 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3659 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3660 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
3661 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3662 ast_cli(a->fd, " Username : %s\n", peer->username);
3663 ast_cli(a->fd, " Codecs : ");
3664 iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3665 ast_cli(a->fd, "%s\n", codec_buf);
3667 ast_cli(a->fd, " Codec Order : (");
3668 for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
3669 struct ast_format tmpfmt;
3670 if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
3672 ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
3673 if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
3674 ast_cli(a->fd, "|");
3678 ast_cli(a->fd, "none");
3679 ast_cli(a->fd, ")\n");
3681 ast_cli(a->fd, " Status : ");
3682 peer_status(peer, status, sizeof(status));
3683 ast_cli(a->fd, "%s\n",status);
3684 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3685 ast_cli(a->fd, "\n");
3688 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3689 ast_cli(a->fd, "\n");
3695 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3698 struct iax2_peer *peer;
3700 int wordlen = strlen(word);
3701 struct ao2_iterator i;
3703 i = ao2_iterator_init(peers, 0);
3704 while ((peer = ao2_iterator_next(&i))) {
3705 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3706 && (!flags || ast_test_flag64(peer, flags))) {
3707 res = ast_strdup(peer->name);
3713 ao2_iterator_destroy(&i);
3718 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3720 struct iax_frame *cur;
3721 int cnt = 0, dead = 0, final = 0, i = 0;
3725 e->command = "iax2 show stats";
3727 "Usage: iax2 show stats\n"
3728 " Display statistics on IAX channel driver.\n";
3735 return CLI_SHOWUSAGE;