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 * \todo XXX The IAX2 channel driver needs its native bridge
44 * code converted to the new bridge technology scheme.
46 * \note The chan_dahdi native bridge code can be used as an
47 * example. It also appears that chan_iax2 also has a native
48 * transfer check like chan_dahdi to eliminate tromboned calls.
50 * \note The existing native bridge code is marked with the
51 * IAX2_NATIVE_BRIDGING conditional.
55 <use type="external">crypto</use>
56 <support_level>core</support_level>
61 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
71 #include <sys/signal.h>
79 #include "asterisk/paths.h"
81 #include "asterisk/lock.h"
82 #include "asterisk/frame.h"
83 #include "asterisk/channel.h"
84 #include "asterisk/module.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/sched.h"
87 #include "asterisk/io.h"
88 #include "asterisk/config.h"
89 #include "asterisk/cli.h"
90 #include "asterisk/translate.h"
91 #include "asterisk/md5.h"
92 #include "asterisk/crypto.h"
93 #include "asterisk/acl.h"
94 #include "asterisk/manager.h"
95 #include "asterisk/callerid.h"
96 #include "asterisk/app.h"
97 #include "asterisk/astdb.h"
98 #include "asterisk/musiconhold.h"
99 #include "asterisk/features.h"
100 #include "asterisk/utils.h"
101 #include "asterisk/causes.h"
102 #include "asterisk/localtime.h"
103 #include "asterisk/dnsmgr.h"
104 #include "asterisk/devicestate.h"
105 #include "asterisk/netsock.h"
106 #include "asterisk/stringfields.h"
107 #include "asterisk/linkedlists.h"
108 #include "asterisk/astobj2.h"
109 #include "asterisk/timing.h"
110 #include "asterisk/taskprocessor.h"
111 #include "asterisk/test.h"
112 #include "asterisk/data.h"
113 #include "asterisk/security_events.h"
114 #include "asterisk/stasis_endpoints.h"
115 #include "asterisk/bridge.h"
116 #include "asterisk/stasis.h"
117 #include "asterisk/stasis_system.h"
118 #include "asterisk/stasis_channels.h"
120 #include "iax2/include/iax2.h"
121 #include "iax2/include/firmware.h"
122 #include "iax2/include/parser.h"
123 #include "iax2/include/provision.h"
124 #include "jitterbuf.h"
127 <application name="IAX2Provision" language="en_US">
129 Provision a calling IAXy with a given template.
132 <parameter name="template">
133 <para>If not specified, defaults to <literal>default</literal>.</para>
137 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
138 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
139 or <literal>0</literal> on success.</para>
142 <function name="IAXPEER" language="en_US">
144 Gets IAX peer information.
147 <parameter name="peername" required="true">
149 <enum name="CURRENTCHANNEL">
150 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
151 endpoint of the current channel</para>
155 <parameter name="item">
156 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
159 <para>(default) The IP address.</para>
162 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
164 <enum name="mailbox">
165 <para>The configured mailbox.</para>
167 <enum name="context">
168 <para>The configured context.</para>
171 <para>The epoch time of the next expire.</para>
173 <enum name="dynamic">
174 <para>Is it dynamic? (yes/no).</para>
176 <enum name="callerid_name">
177 <para>The configured Caller ID name.</para>
179 <enum name="callerid_num">
180 <para>The configured Caller ID number.</para>
183 <para>The configured codecs.</para>
185 <enum name="codec[x]">
186 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
187 with <literal>0</literal>)</para>
193 <para>Gets information associated with the specified IAX2 peer.</para>
196 <ref type="function">SIPPEER</ref>
199 <function name="IAXVAR" language="en_US">
201 Sets or retrieves a remote variable.
204 <parameter name="varname" required="true" />
207 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
210 <manager name="IAXpeers" language="en_US">
215 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
220 <manager name="IAXpeerlist" language="en_US">
225 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
228 <para>List all the IAX peers.</para>
231 <manager name="IAXnetstats" language="en_US">
237 <para>Show IAX channels network statistics.</para>
240 <manager name="IAXregistry" language="en_US">
242 Show IAX registrations.
245 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
248 <para>Show IAX registrations.</para>
253 /* Define SCHED_MULTITHREADED to run the scheduler in a special
254 multithreaded mode. */
255 #define SCHED_MULTITHREADED
257 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
258 thread is actually doing. */
259 #define DEBUG_SCHED_MULTITHREAD
263 static int nochecksums = 0;
266 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
267 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
269 #define DEFAULT_THREAD_COUNT 10
270 #define DEFAULT_MAX_THREAD_COUNT 100
271 #define DEFAULT_RETRY_TIME 1000
272 #define MEMORY_SIZE 100
273 #define DEFAULT_DROP 3
275 #define DEBUG_SUPPORT
277 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
279 /* Sample over last 100 units to determine historic jitter */
282 static struct ast_codec_pref prefs;
284 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
287 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
288 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
289 #define MAX_TRUNK_MTU 1240
291 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
292 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
294 #define DEFAULT_CONTEXT "default"
296 static char default_parkinglot[AST_MAX_CONTEXT];
298 static char language[MAX_LANGUAGE] = "";
299 static char regcontext[AST_MAX_CONTEXT] = "";
301 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
302 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
303 static int network_change_sched_id = -1;
305 static int maxauthreq = 3;
306 static int max_retries = 4;
307 static int ping_time = 21;
308 static int lagrq_time = 10;
309 static int maxjitterbuffer=1000;
310 static int resyncthreshold=1000;
311 static int maxjitterinterps=10;
312 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
314 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
316 static int trunkfreq = 20;
317 static int trunkmaxsize = MAX_TRUNKDATA;
319 static int authdebug = 0;
320 static int autokill = 0;
321 static int iaxcompat = 0;
322 static int last_authmethod = 0;
324 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
326 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
333 static int min_reg_expire;
334 static int max_reg_expire;
336 static int srvlookup = 0;
338 static struct ast_timer *timer; /* Timer for trunking */
340 static struct ast_netsock_list *netsock;
341 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
342 static int defaultsockfd = -1;
344 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
347 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
349 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
350 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
351 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
352 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
353 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
354 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
355 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
356 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
357 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
359 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
360 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
361 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
362 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
364 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
365 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
368 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
369 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
370 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
372 /* if a pvt has encryption setup done and is running on the call */
373 #define IAX_CALLENCRYPTED(pvt) \
374 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
376 #define IAX_DEBUGDIGEST(msg, key) do { \
378 char digest[33] = ""; \
383 for (idx = 0; idx < 16; idx++) \
384 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
386 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
389 static struct io_context *io;
390 static struct ast_sched_context *sched;
392 #define DONT_RESCHEDULE -2
394 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
396 static int iaxdebug = 0;
398 static int iaxtrunkdebug = 0;
400 static int test_losspct = 0;
402 static int test_late = 0;
403 static int test_resync = 0;
404 static int test_jit = 0;
405 static int test_jitpct = 0;
406 #endif /* IAXTESTS */
408 static char accountcode[AST_MAX_ACCOUNT_CODE];
409 static char mohinterpret[MAX_MUSICCLASS];
410 static char mohsuggest[MAX_MUSICCLASS];
411 static int amaflags = 0;
413 static int delayreject = 0;
414 static int iax2_encryption = 0;
416 static struct ast_flags64 globalflags = { 0 };
418 static pthread_t netthreadid = AST_PTHREADT_NULL;
421 IAX_STATE_STARTED = (1 << 0),
422 IAX_STATE_AUTHENTICATED = (1 << 1),
423 IAX_STATE_TBD = (1 << 2),
426 struct iax2_context {
427 char context[AST_MAX_CONTEXT];
428 struct iax2_context *next;
432 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
433 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
434 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
435 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
436 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
437 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
438 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
439 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
440 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
441 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
442 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
443 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
444 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
445 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
446 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
447 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
448 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
449 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
450 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
451 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
452 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
453 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
454 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
455 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
456 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
457 #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 */
458 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
459 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
460 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
461 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
462 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
463 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
464 static int global_rtautoclear = 120;
466 static int reload_config(int forced_reload);
469 * \brief Call token validation settings.
471 enum calltoken_peer_enum {
472 /*! \brief Default calltoken required unless the ip is in the ignorelist */
473 CALLTOKEN_DEFAULT = 0,
474 /*! \brief Require call token validation. */
476 /*! \brief Require call token validation after a successful registration
477 * using call token validation occurs. */
479 /*! \brief Do not require call token validation. */
484 AST_DECLARE_STRING_FIELDS(
485 AST_STRING_FIELD(name);
486 AST_STRING_FIELD(secret);
487 AST_STRING_FIELD(dbsecret);
488 AST_STRING_FIELD(accountcode);
489 AST_STRING_FIELD(mohinterpret);
490 AST_STRING_FIELD(mohsuggest);
491 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
492 AST_STRING_FIELD(language);
493 AST_STRING_FIELD(cid_num);
494 AST_STRING_FIELD(cid_name);
495 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
503 iax2_format capability;
504 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
505 int curauthreq; /*!< Current number of outstanding AUTHREQs */
506 struct ast_codec_pref prefs;
507 struct ast_acl_list *acl;
508 struct iax2_context *contexts;
509 struct ast_variable *vars;
510 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
514 AST_DECLARE_STRING_FIELDS(
515 AST_STRING_FIELD(name);
516 AST_STRING_FIELD(username);
517 AST_STRING_FIELD(description); /*!< Description of the peer */
518 AST_STRING_FIELD(secret);
519 AST_STRING_FIELD(dbsecret);
520 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
522 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
523 AST_STRING_FIELD(context); /*!< For transfers only */
524 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
525 AST_STRING_FIELD(mailbox); /*!< Mailbox */
526 AST_STRING_FIELD(mohinterpret);
527 AST_STRING_FIELD(mohsuggest);
528 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
529 /* Suggested caller id if registering */
530 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
531 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
532 AST_STRING_FIELD(zonetag); /*!< Time Zone */
533 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
535 struct ast_codec_pref prefs;
536 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
537 struct ast_sockaddr addr;
539 int sockfd; /*!< Socket to use for transmission */
540 struct ast_sockaddr mask;
544 /* Dynamic Registration fields */
545 struct ast_sockaddr defaddr; /*!< Default address if there is one */
546 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
547 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
549 int expire; /*!< Schedule entry for expiry */
550 int expiry; /*!< How soon to expire */
551 iax2_format capability; /*!< Capability */
554 int callno; /*!< Call number of POKE request */
555 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
556 int lastms; /*!< How long last response took (in ms), or -1 for no response */
557 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
559 int pokefreqok; /*!< How often to check if the host is up */
560 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
561 int historicms; /*!< How long recent average responses took */
562 int smoothing; /*!< Sample over how many units to determine historic ms */
563 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
565 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
567 struct ast_acl_list *acl;
568 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
570 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
573 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
575 struct iax2_trunk_peer {
578 struct ast_sockaddr addr;
579 struct timeval txtrunktime; /*!< Transmit trunktime */
580 struct timeval rxtrunktime; /*!< Receive trunktime */
581 struct timeval lasttxtime; /*!< Last transmitted trunktime */
582 struct timeval trunkact; /*!< Last trunk activity */
583 unsigned int lastsent; /*!< Last sent time */
584 /* Trunk data and length */
585 unsigned char *trunkdata;
586 unsigned int trunkdatalen;
587 unsigned int trunkdataalloc;
591 AST_LIST_ENTRY(iax2_trunk_peer) list;
594 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
597 REG_STATE_UNREGISTERED = 0,
600 REG_STATE_REGISTERED,
606 enum iax_transfer_state {
611 TRANSFER_PASSTHROUGH,
615 TRANSFER_MPASSTHROUGH,
620 struct iax2_registry {
621 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
623 char secret[80]; /*!< Password or key name in []'s */
624 int expire; /*!< Sched ID of expiration */
625 int refresh; /*!< How often to refresh */
626 enum iax_reg_state regstate;
627 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
628 int callno; /*!< Associated call number if applicable */
629 struct ast_sockaddr us; /*!< Who the server thinks we are */
630 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
631 AST_LIST_ENTRY(iax2_registry) entry;
634 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
636 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
637 #define MIN_RETRY_TIME 100
638 #define MAX_RETRY_TIME 10000
640 #define MAX_JITTER_BUFFER 50
641 #define MIN_JITTER_BUFFER 10
643 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
645 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
647 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
648 #define TS_GAP_FOR_JB_RESYNC 5000
650 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
651 #define MARK_IAX_SUBCLASS_TX 0x8000
653 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
654 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
655 static int iaxdynamicthreadcount = 0;
656 static int iaxdynamicthreadnum = 0;
657 static int iaxactivethreadcount = 0;
671 /* We use the high order bit as the validated flag, and the lower 15 as the
672 * actual call number */
673 typedef uint16_t callno_entry;
675 struct chan_iax2_pvt {
676 /*! Socket to send/receive on for this call */
678 /*! ast_callid bound to dialog */
679 struct ast_callid *callid;
680 /*! Last received voice format */
681 iax2_format voiceformat;
682 /*! Last received video format */
683 iax2_format videoformat;
684 /*! Last sent voice format */
685 iax2_format svoiceformat;
686 /*! Last sent video format */
687 iax2_format svideoformat;
688 /*! What we are capable of sending */
689 iax2_format capability;
690 /*! Last received timestamp */
692 /*! Last sent timestamp - never send the same timestamp twice in a single call */
693 unsigned int lastsent;
694 /*! Timestamp of the last video frame sent */
695 unsigned int lastvsent;
696 /*! Next outgoing timestamp if everything is good */
697 unsigned int nextpred;
698 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
699 int first_iax_message;
700 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
701 int last_iax_message;
702 /*! True if the last voice we transmitted was not silence/CNG */
703 unsigned int notsilenttx:1;
705 unsigned int pingtime;
706 /*! Max time for initial response */
709 struct ast_sockaddr addr;
710 /*! Actual used codec preferences */
711 struct ast_codec_pref prefs;
712 /*! Requested codec preferences */
713 struct ast_codec_pref rprefs;
714 /*! Our call number */
715 unsigned short callno;
716 /*! Our callno_entry entry */
717 callno_entry callno_entry;
719 unsigned short peercallno;
720 /*! Negotiated format, this is only used to remember what format was
721 chosen for an unauthenticated call so that the channel can get
722 created later using the right format */
723 iax2_format chosenformat;
724 /*! Peer selected format */
725 iax2_format peerformat;
726 /*! Peer capability */
727 iax2_format peercapability;
728 /*! timeval that we base our transmission on */
729 struct timeval offset;
730 /*! timeval that we base our delivery on */
731 struct timeval rxcore;
732 /*! The jitterbuffer */
734 /*! active jb read scheduler id */
738 /*! Error, as discovered by the manager */
740 /*! Owner if we have one */
741 struct ast_channel *owner;
742 /*! What's our state? */
743 struct ast_flags state;
744 /*! Expiry (optional) */
746 /*! Next outgoing sequence number */
747 unsigned char oseqno;
748 /*! Next sequence number they have not yet acknowledged */
749 unsigned char rseqno;
750 /*! Next incoming sequence number */
751 unsigned char iseqno;
752 /*! Last incoming sequence number we have acknowledged */
753 unsigned char aseqno;
755 AST_DECLARE_STRING_FIELDS(
757 AST_STRING_FIELD(peer);
758 /*! Default Context */
759 AST_STRING_FIELD(context);
760 /*! Caller ID if available */
761 AST_STRING_FIELD(cid_num);
762 AST_STRING_FIELD(cid_name);
763 /*! Hidden Caller ID (i.e. ANI) if appropriate */
764 AST_STRING_FIELD(ani);
766 AST_STRING_FIELD(dnid);
768 AST_STRING_FIELD(rdnis);
769 /*! Requested Extension */
770 AST_STRING_FIELD(exten);
771 /*! Expected Username */
772 AST_STRING_FIELD(username);
773 /*! Expected Secret */
774 AST_STRING_FIELD(secret);
776 AST_STRING_FIELD(challenge);
777 /*! Public keys permitted keys for incoming authentication */
778 AST_STRING_FIELD(inkeys);
779 /*! Private key for outgoing authentication */
780 AST_STRING_FIELD(outkey);
781 /*! Preferred language */
782 AST_STRING_FIELD(language);
783 /*! Hostname/peername for naming purposes */
784 AST_STRING_FIELD(host);
786 AST_STRING_FIELD(dproot);
787 AST_STRING_FIELD(accountcode);
788 AST_STRING_FIELD(mohinterpret);
789 AST_STRING_FIELD(mohsuggest);
790 /*! received OSP token */
791 AST_STRING_FIELD(osptoken);
792 /*! Default parkinglot */
793 AST_STRING_FIELD(parkinglot);
795 /*! AUTHREJ all AUTHREP frames */
797 /*! permitted authentication methods */
799 /*! permitted encryption methods */
801 /*! Encryption AES-128 Key */
802 ast_aes_encrypt_key ecx;
803 /*! Decryption AES-128 Key corresponding to ecx */
804 ast_aes_decrypt_key mydcx;
805 /*! Decryption AES-128 Key used to decrypt peer frames */
806 ast_aes_decrypt_key dcx;
807 /*! scheduler id associated with iax_key_rotate
808 * for encrypted calls*/
810 /*! 32 bytes of semi-random data */
811 unsigned char semirand[32];
812 /*! Associated registry */
813 struct iax2_registry *reg;
814 /*! Associated peer for poking */
815 struct iax2_peer *peerpoke;
820 /*! Transferring status */
821 enum iax_transfer_state transferring;
822 /*! Transfer identifier */
824 /*! Who we are IAX transferring to */
825 struct ast_sockaddr transfer;
826 /*! What's the new call number for the transfer */
827 unsigned short transfercallno;
828 /*! Transfer encrypt AES-128 Key */
829 ast_aes_encrypt_key tdcx;
831 /*! Status of knowledge of peer ADSI capability */
834 /*! Callno of native bridge peer. (Valid if nonzero) */
835 unsigned short bridgecallno;
837 int pingid; /*!< Transmit PING request */
838 int lagid; /*!< Retransmit lag request */
839 int autoid; /*!< Auto hangup for Dialplan requestor */
840 int authid; /*!< Authentication rejection ID */
841 int authfail; /*!< Reason to report failure */
842 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
847 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
848 /*! variables inherited from the user definition */
849 struct ast_variable *vars;
850 /*! variables transmitted in a NEW packet */
851 struct ast_variable *iaxvars;
852 /*! last received remote rr */
853 struct iax_rr remote_rr;
854 /*! Current base time: (just for stats) */
856 /*! Dropped frame count: (just for stats) */
858 /*! received frame count: (just for stats) */
860 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
861 unsigned char calltoken_ie_len;
862 /*! hold all signaling frames from the pbx thread until we have a destination callno */
864 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
865 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
868 struct signaling_queue_entry {
870 AST_LIST_ENTRY(signaling_queue_entry) next;
878 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
879 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
881 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
882 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
883 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
885 struct call_number_pool {
888 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
891 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
893 /*! table of available call numbers */
894 static struct call_number_pool callno_pool;
896 /*! table of available trunk call numbers */
897 static struct call_number_pool callno_pool_trunk;
900 * \brief a list of frames that may need to be retransmitted
902 * \note The contents of this list do not need to be explicitly destroyed
903 * on module unload. This is because all active calls are destroyed, and
904 * all frames in this queue will get destroyed as a part of that process.
906 * \note Contents protected by the iaxsl[] locks
908 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
910 static struct ast_taskprocessor *transmit_processor;
912 static int randomcalltokendata;
914 static const time_t MAX_CALLTOKEN_DELAY = 10;
917 * This module will get much higher performance when doing a lot of
918 * user and peer lookups if the number of buckets is increased from 1.
919 * However, to maintain old behavior for Asterisk 1.4, these are set to
920 * 1 by default. When using multiple buckets, search order through these
921 * containers is considered random, so you will not be able to depend on
922 * the order the entires are specified in iax.conf for matching order. */
924 #define MAX_PEER_BUCKETS 17
926 #define MAX_PEER_BUCKETS 563
928 static struct ao2_container *peers;
930 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
931 static struct ao2_container *users;
933 /*! Table containing peercnt objects for every ip address consuming a callno */
934 static struct ao2_container *peercnts;
936 /*! Table containing custom callno limit rules for a range of ip addresses. */
937 static struct ao2_container *callno_limits;
939 /*! Table containing ip addresses not requiring calltoken validation */
940 static struct ao2_container *calltoken_ignores;
942 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
944 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
946 static uint16_t global_maxcallno;
948 /*! Total num of call numbers allowed to be allocated without calltoken validation */
949 static uint16_t global_maxcallno_nonval;
951 static uint16_t total_nonval_callno_used = 0;
953 /*! peer connection private, keeps track of all the call numbers
954 * consumed by a single ip address */
956 /*! ip address consuming call numbers */
957 struct ast_sockaddr addr;
958 /*! Number of call numbers currently used by this ip address */
960 /*! Max call numbers allowed for this ip address */
962 /*! Specifies whether limit is set by a registration or not, if so normal
963 * limit setting rules do not apply to this address. */
967 /*! used by both callno_limits and calltoken_ignores containers */
969 /*! ip address range for custom callno limit rule */
971 /*! callno limit for this ip address range, only used in callno_limits container */
973 /*! delete me marker for reloads */
978 /*! Extension exists */
979 CACHE_FLAG_EXISTS = (1 << 0),
980 /*! Extension is nonexistent */
981 CACHE_FLAG_NONEXISTENT = (1 << 1),
982 /*! Extension can exist */
983 CACHE_FLAG_CANEXIST = (1 << 2),
984 /*! Waiting to hear back response */
985 CACHE_FLAG_PENDING = (1 << 3),
987 CACHE_FLAG_TIMEOUT = (1 << 4),
988 /*! Request transmitted */
989 CACHE_FLAG_TRANSMITTED = (1 << 5),
991 CACHE_FLAG_UNKNOWN = (1 << 6),
993 CACHE_FLAG_MATCHMORE = (1 << 7),
996 struct iax2_dpcache {
997 char peercontext[AST_MAX_CONTEXT];
998 char exten[AST_MAX_EXTENSION];
1000 struct timeval expiry;
1002 unsigned short callno;
1004 AST_LIST_ENTRY(iax2_dpcache) cache_list;
1005 AST_LIST_ENTRY(iax2_dpcache) peer_list;
1008 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1010 static void reg_source_db(struct iax2_peer *p);
1011 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1012 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1014 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1015 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1016 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1018 enum iax2_thread_iostate {
1021 IAX_IOSTATE_PROCESSING,
1022 IAX_IOSTATE_SCHEDREADY,
1025 enum iax2_thread_type {
1026 IAX_THREAD_TYPE_POOL,
1027 IAX_THREAD_TYPE_DYNAMIC,
1030 struct iax2_pkt_buf {
1031 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1033 unsigned char buf[1];
1036 struct iax2_thread {
1037 AST_LIST_ENTRY(iax2_thread) list;
1038 enum iax2_thread_type type;
1039 enum iax2_thread_iostate iostate;
1040 #ifdef SCHED_MULTITHREADED
1041 void (*schedfunc)(const void *);
1042 const void *scheddata;
1044 #ifdef DEBUG_SCHED_MULTITHREAD
1050 struct ast_sockaddr ioaddr;
1051 unsigned char readbuf[4096];
1059 ast_mutex_t init_lock;
1060 ast_cond_t init_cond;
1061 /*! if this thread is processing a full frame,
1062 some information about that frame will be stored
1063 here, so we can avoid dispatching any more full
1064 frames for that callno to other threads */
1066 unsigned short callno;
1067 struct ast_sockaddr addr;
1071 /*! Queued up full frames for processing. If more full frames arrive for
1072 * a call which this thread is already processing a full frame for, they
1073 * are queued up here. */
1074 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1079 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1080 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1081 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1083 static void *iax2_process_thread(void *data);
1084 static void iax2_destroy(int callno);
1086 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1088 ast_mutex_lock(lock);
1089 ast_cond_signal(cond);
1090 ast_mutex_unlock(lock);
1094 * \brief an array of iax2 pvt structures
1096 * The container for active chan_iax2_pvt structures is implemented as an
1097 * array for extremely quick direct access to the correct pvt structure
1098 * based on the local call number. The local call number is used as the
1099 * index into the array where the associated pvt structure is stored.
1101 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1103 static struct ast_callid *iax_pvt_callid_get(int callno)
1105 if (iaxs[callno]->callid) {
1106 return ast_callid_ref(iaxs[callno]->callid);
1111 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1113 if (iaxs[callno]->callid) {
1114 ast_callid_unref(iaxs[callno]->callid);
1116 ast_callid_ref(callid);
1117 iaxs[callno]->callid = callid;
1120 static void iax_pvt_callid_new(int callno)
1122 struct ast_callid *callid = ast_create_callid();
1123 char buffer[AST_CALLID_BUFFER_LENGTH];
1124 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1125 iax_pvt_callid_set(callno, callid);
1126 ast_callid_unref(callid);
1130 * \brief Another container of iax2_pvt structures
1132 * Active IAX2 pvt structs are also stored in this container, if they are a part
1133 * of an active call where we know the remote side's call number. The reason
1134 * for this is that incoming media frames do not contain our call number. So,
1135 * instead of having to iterate the entire iaxs array, we use this container to
1136 * look up calls where the remote side is using a given call number.
1138 static struct ao2_container *iax_peercallno_pvts;
1141 * \brief chan_iax2_pvt structure locks
1143 * These locks are used when accessing a pvt structure in the iaxs array.
1144 * The index used here is the same as used in the iaxs array. It is the
1145 * local call number for the associated pvt struct.
1147 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1150 * * \brief Another container of iax2_pvt structures
1152 * Active IAX2 pvt stucts used during transfering a call are stored here.
1154 static struct ao2_container *iax_transfercallno_pvts;
1156 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1157 but keeps the division between trunked and non-trunked better. */
1158 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1160 /* Debug routines... */
1161 static struct ast_sockaddr debugaddr;
1163 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1166 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1167 (!ast_sockaddr_port(&debugaddr) ||
1168 ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1169 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1172 iax_showframe(f, fhi, rx, addr, datalen);
1175 iax_showframe(f, fhi, rx, addr, datalen);
1181 static void iax_debug_output(const char *data)
1184 ast_verbose("%s", data);
1187 static void iax_error_output(const char *data)
1189 ast_log(LOG_WARNING, "%s", data);
1192 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1197 va_start(args, fmt);
1198 vsnprintf(buf, sizeof(buf), fmt, args);
1201 ast_log(LOG_ERROR, "%s", buf);
1204 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1209 va_start(args, fmt);
1210 vsnprintf(buf, sizeof(buf), fmt, args);
1213 ast_log(LOG_WARNING, "%s", buf);
1216 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1221 va_start(args, fmt);
1222 vsnprintf(buf, sizeof(buf), fmt, args);
1225 ast_verbose("%s", buf);
1228 static int expire_registry(const void *data);
1229 static int iax2_answer(struct ast_channel *c);
1230 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1231 static int iax2_devicestate(const char *data);
1232 static int iax2_digit_begin(struct ast_channel *c, char digit);
1233 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1234 static int iax2_do_register(struct iax2_registry *reg);
1235 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1236 static int iax2_hangup(struct ast_channel *c);
1237 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1238 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1239 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1240 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1241 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1242 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1243 static int iax2_sendtext(struct ast_channel *c, const char *text);
1244 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1245 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1246 static int iax2_transfer(struct ast_channel *c, const char *dest);
1247 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1248 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1250 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1251 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1252 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1253 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1254 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1255 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1256 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1257 static struct ast_frame *iax2_read(struct ast_channel *c);
1258 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1259 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1260 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1261 static void *iax2_dup_variable_datastore(void *);
1262 static void prune_peers(void);
1263 static void prune_users(void);
1264 static void iax2_free_variable_datastore(void *);
1266 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1267 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1268 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1269 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1270 static void build_rand_pad(unsigned char *buf, ssize_t len);
1271 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1272 static int replace_callno(const void *obj);
1273 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1274 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1275 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1277 static struct ast_channel_tech iax2_tech = {
1279 .description = tdesc,
1280 .properties = AST_CHAN_TP_WANTSJITTER,
1281 .requester = iax2_request,
1282 .devicestate = iax2_devicestate,
1283 .send_digit_begin = iax2_digit_begin,
1284 .send_digit_end = iax2_digit_end,
1285 .send_text = iax2_sendtext,
1286 .send_image = iax2_sendimage,
1287 .send_html = iax2_sendhtml,
1289 .hangup = iax2_hangup,
1290 .answer = iax2_answer,
1292 .write = iax2_write,
1293 .write_video = iax2_write,
1294 .indicate = iax2_indicate,
1295 .setoption = iax2_setoption,
1296 .queryoption = iax2_queryoption,
1297 .transfer = iax2_transfer,
1298 .fixup = iax2_fixup,
1299 .func_channel_read = acf_channel_read,
1304 * \brief Obtain the owner channel lock if the owner exists.
1306 * \param callno IAX2 call id.
1308 * \note Assumes the iaxsl[callno] lock is already obtained.
1311 * IMPORTANT NOTE!!! Any time this function is used, even if
1312 * iaxs[callno] was valid before calling it, it may no longer be
1313 * valid after calling it. This function may unlock and lock
1314 * the mutex associated with this callno, meaning that another
1315 * thread may grab it and destroy the call.
1319 static void iax2_lock_owner(int callno)
1322 if (!iaxs[callno] || !iaxs[callno]->owner) {
1323 /* There is no owner lock to get. */
1326 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1327 /* We got the lock */
1330 /* Avoid deadlock by pausing and trying again */
1331 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1335 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
1337 /* The MWI subscriptions exist just so the core knows we care about those
1338 * mailboxes. However, we just grab the events out of the cache when it
1339 * is time to send MWI, since it is only sent with a REGACK. */
1342 static void network_change_stasis_subscribe(void)
1344 if (!network_change_sub) {
1345 network_change_sub = stasis_subscribe(ast_system_topic(),
1346 network_change_stasis_cb, NULL);
1350 static void network_change_stasis_unsubscribe(void)
1352 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1355 static void acl_change_stasis_subscribe(void)
1357 if (!acl_change_sub) {
1358 acl_change_sub = stasis_subscribe(ast_security_topic(),
1359 acl_change_stasis_cb, NULL);
1363 static void acl_change_stasis_unsubscribe(void)
1365 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1368 static int network_change_sched_cb(const void *data)
1370 struct iax2_registry *reg;
1371 network_change_sched_id = -1;
1372 AST_LIST_LOCK(®istrations);
1373 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1374 iax2_do_register(reg);
1376 AST_LIST_UNLOCK(®istrations);
1381 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1382 struct stasis_message *message)
1384 /* This callback is only concerned with network change messages from the system topic. */
1385 if (stasis_message_type(message) != ast_network_change_type()) {
1389 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1390 if (network_change_sched_id == -1) {
1391 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1395 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1396 struct stasis_message *message)
1398 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1402 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1406 static const struct ast_datastore_info iax2_variable_datastore_info = {
1407 .type = "IAX2_VARIABLE",
1408 .duplicate = iax2_dup_variable_datastore,
1409 .destroy = iax2_free_variable_datastore,
1412 static void *iax2_dup_variable_datastore(void *old)
1414 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1415 struct ast_var_t *oldvar, *newvar;
1417 newlist = ast_calloc(sizeof(*newlist), 1);
1419 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1423 AST_LIST_HEAD_INIT(newlist);
1424 AST_LIST_LOCK(oldlist);
1425 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1426 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1428 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1430 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1432 AST_LIST_UNLOCK(oldlist);
1436 static void iax2_free_variable_datastore(void *old)
1438 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1439 struct ast_var_t *oldvar;
1441 AST_LIST_LOCK(oldlist);
1442 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1445 AST_LIST_UNLOCK(oldlist);
1446 AST_LIST_HEAD_DESTROY(oldlist);
1451 /* WARNING: insert_idle_thread should only ever be called within the
1452 * context of an iax2_process_thread() thread.
1454 static void insert_idle_thread(struct iax2_thread *thread)
1456 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1457 AST_LIST_LOCK(&dynamic_list);
1458 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1459 AST_LIST_UNLOCK(&dynamic_list);
1461 AST_LIST_LOCK(&idle_list);
1462 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1463 AST_LIST_UNLOCK(&idle_list);
1469 static struct iax2_thread *find_idle_thread(void)
1471 struct iax2_thread *thread = NULL;
1473 /* Pop the head of the idle list off */
1474 AST_LIST_LOCK(&idle_list);
1475 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1476 AST_LIST_UNLOCK(&idle_list);
1478 /* If we popped a thread off the idle list, just return it */
1480 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1484 /* Pop the head of the dynamic list off */
1485 AST_LIST_LOCK(&dynamic_list);
1486 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1487 AST_LIST_UNLOCK(&dynamic_list);
1489 /* If we popped a thread off the dynamic list, just return it */
1491 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1495 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1496 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1499 /* Set default values */
1500 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1501 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1502 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1504 /* Initialize lock and condition */
1505 ast_mutex_init(&thread->lock);
1506 ast_cond_init(&thread->cond, NULL);
1507 ast_mutex_init(&thread->init_lock);
1508 ast_cond_init(&thread->init_cond, NULL);
1509 ast_mutex_lock(&thread->init_lock);
1511 /* Create thread and send it on it's way */
1512 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1513 ast_cond_destroy(&thread->cond);
1514 ast_mutex_destroy(&thread->lock);
1515 ast_mutex_unlock(&thread->init_lock);
1516 ast_cond_destroy(&thread->init_cond);
1517 ast_mutex_destroy(&thread->init_lock);
1522 /* this thread is not processing a full frame (since it is idle),
1523 so ensure that the field for the full frame call number is empty */
1524 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1526 /* Wait for the thread to be ready before returning it to the caller */
1527 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1529 /* Done with init_lock */
1530 ast_mutex_unlock(&thread->init_lock);
1535 #ifdef SCHED_MULTITHREADED
1536 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1538 struct iax2_thread *thread;
1539 static time_t lasterror;
1542 thread = find_idle_thread();
1543 if (thread != NULL) {
1544 thread->schedfunc = func;
1545 thread->scheddata = data;
1546 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1547 #ifdef DEBUG_SCHED_MULTITHREAD
1548 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1550 signal_condition(&thread->lock, &thread->cond);
1554 if (t != lasterror) {
1556 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1561 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1564 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1565 ast_sched_cb callback, const void *data)
1567 return ast_sched_replace(id, con, when, callback, data);
1570 static int iax2_sched_add(struct ast_sched_context *con, int when,
1571 ast_sched_cb callback, const void *data)
1573 return ast_sched_add(con, when, callback, data);
1576 static int send_ping(const void *data);
1578 static void __send_ping(const void *data)
1580 int callno = (long) data;
1582 ast_mutex_lock(&iaxsl[callno]);
1585 if (iaxs[callno]->peercallno) {
1586 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1587 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1588 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1592 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1595 ast_mutex_unlock(&iaxsl[callno]);
1598 static int send_ping(const void *data)
1600 int callno = (long) data;
1601 ast_mutex_lock(&iaxsl[callno]);
1602 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1603 iaxs[callno]->pingid = -1;
1605 ast_mutex_unlock(&iaxsl[callno]);
1607 #ifdef SCHED_MULTITHREADED
1608 if (schedule_action(__send_ping, data))
1615 static void encmethods_to_str(int e, struct ast_str **buf)
1617 ast_str_set(buf, 0, "(");
1618 if (e & IAX_ENCRYPT_AES128) {
1619 ast_str_append(buf, 0, "aes128");
1621 if (e & IAX_ENCRYPT_KEYROTATE) {
1622 ast_str_append(buf, 0, ",keyrotate");
1624 if (ast_str_strlen(*buf) > 1) {
1625 ast_str_append(buf, 0, ")");
1627 ast_str_set(buf, 0, "No");
1631 static int get_encrypt_methods(const char *s)
1634 if (!strcasecmp(s, "aes128"))
1635 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1636 else if (ast_true(s))
1637 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1643 static int send_lagrq(const void *data);
1645 static void __send_lagrq(const void *data)
1647 int callno = (long) data;
1649 ast_mutex_lock(&iaxsl[callno]);
1652 if (iaxs[callno]->peercallno) {
1653 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1654 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1655 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1659 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1662 ast_mutex_unlock(&iaxsl[callno]);
1665 static int send_lagrq(const void *data)
1667 int callno = (long) data;
1668 ast_mutex_lock(&iaxsl[callno]);
1669 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1670 iaxs[callno]->lagid = -1;
1672 ast_mutex_unlock(&iaxsl[callno]);
1674 #ifdef SCHED_MULTITHREADED
1675 if (schedule_action(__send_lagrq, data))
1681 static unsigned char compress_subclass(iax2_format subclass)
1685 /* If it's 64 or smaller, just return it */
1686 if (subclass < IAX_FLAG_SC_LOG)
1688 /* Otherwise find its power */
1689 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1690 if (subclass & (1LL << x)) {
1692 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1698 return power | IAX_FLAG_SC_LOG;
1701 static iax2_format uncompress_subclass(unsigned char csub)
1703 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1704 if (csub & IAX_FLAG_SC_LOG) {
1705 /* special case for 'compressed' -1 */
1709 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1715 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1717 struct ast_format_cap *cap;
1718 struct ast_format tmpfmt;
1719 iax2_format format = 0;
1720 if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK))) {
1721 ast_format_clear(&tmpfmt);
1722 ast_format_cap_from_old_bitfield(cap, formats);
1723 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1724 format = ast_format_to_old_bitfield(&tmpfmt);
1725 cap = ast_format_cap_destroy(cap);
1731 static iax2_format iax2_best_codec(iax2_format formats)
1733 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1734 struct ast_format tmpfmt;
1739 ast_format_clear(&tmpfmt);
1740 ast_format_cap_from_old_bitfield(cap, formats);
1741 ast_best_codec(cap, &tmpfmt);
1742 cap = ast_format_cap_destroy(cap);
1743 return ast_format_to_old_bitfield(&tmpfmt);
1746 const char *iax2_getformatname(iax2_format format)
1748 struct ast_format tmpfmt;
1749 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1753 return ast_getformatname(&tmpfmt);
1756 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1758 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1763 ast_format_cap_from_old_bitfield(cap, format);
1764 ast_getformatname_multiple(codec_buf, len, cap);
1765 cap = ast_format_cap_destroy(cap);
1770 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1773 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1778 ast_format_cap_from_old_bitfield(cap, *formats);
1779 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1780 *formats = ast_format_cap_to_old_bitfield(cap);
1781 cap = ast_format_cap_destroy(cap);
1786 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1789 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK);
1793 ast_format_cap_from_old_bitfield(cap, formats);
1794 res = ast_data_add_codecs(root, node_name, cap);
1795 cap = ast_format_cap_destroy(cap);
1800 * \note The only member of the peer passed here guaranteed to be set is the name field
1802 static int peer_hash_cb(const void *obj, const int flags)
1804 const struct iax2_peer *peer = obj;
1805 const char *name = obj;
1807 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1811 * \note The only member of the peer passed here guaranteed to be set is the name field
1813 static int peer_cmp_cb(void *obj, void *arg, int flags)
1815 struct iax2_peer *peer = obj, *peer2 = arg;
1816 const char *name = arg;
1818 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1819 CMP_MATCH | CMP_STOP : 0;
1823 * \note The only member of the user passed here guaranteed to be set is the name field
1825 static int user_hash_cb(const void *obj, const int flags)
1827 const struct iax2_user *user = obj;
1828 const char *name = obj;
1830 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1834 * \note The only member of the user passed here guaranteed to be set is the name field
1836 static int user_cmp_cb(void *obj, void *arg, int flags)
1838 struct iax2_user *user = obj, *user2 = arg;
1839 const char *name = arg;
1841 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1842 CMP_MATCH | CMP_STOP : 0;
1846 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1847 * so do not call it with a pvt lock held.
1849 static struct iax2_peer *find_peer(const char *name, int realtime)
1851 struct iax2_peer *peer = NULL;
1853 peer = ao2_find(peers, name, OBJ_KEY);
1855 /* Now go for realtime if applicable */
1856 if (!peer && realtime) {
1857 peer = realtime_peer(name, NULL);
1862 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1868 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1874 static struct iax2_user *find_user(const char *name)
1876 return ao2_find(users, name, OBJ_KEY);
1878 static inline struct iax2_user *user_ref(struct iax2_user *user)
1884 static inline struct iax2_user *user_unref(struct iax2_user *user)
1890 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
1892 struct iax2_peer *peer = NULL;
1894 struct ao2_iterator i;
1896 i = ao2_iterator_init(peers, 0);
1897 while ((peer = ao2_iterator_next(&i))) {
1899 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
1900 ast_copy_string(host, peer->name, len);
1907 ao2_iterator_destroy(&i);
1910 peer = realtime_peer(NULL, &addr);
1912 ast_copy_string(host, peer->name, len);
1921 /*!\note Assumes the lock on the pvt is already held, when
1922 * iax2_destroy_helper() is called. */
1923 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1925 /* Decrement AUTHREQ count if needed */
1926 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1927 struct iax2_user *user;
1929 user = ao2_find(users, pvt->username, OBJ_KEY);
1931 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1935 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1937 /* No more pings or lagrq's */
1938 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1939 pvt->pingid = DONT_RESCHEDULE;
1940 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1941 pvt->lagid = DONT_RESCHEDULE;
1942 AST_SCHED_DEL(sched, pvt->autoid);
1943 AST_SCHED_DEL(sched, pvt->authid);
1944 AST_SCHED_DEL(sched, pvt->initid);
1945 AST_SCHED_DEL(sched, pvt->jbid);
1946 AST_SCHED_DEL(sched, pvt->keyrotateid);
1949 static void iax2_frame_free(struct iax_frame *fr)
1951 AST_SCHED_DEL(sched, fr->retrans);
1955 static int scheduled_destroy(const void *vid)
1957 unsigned short callno = PTR_TO_CALLNO(vid);
1958 ast_mutex_lock(&iaxsl[callno]);
1960 ast_debug(1, "Really destroying %d now...\n", callno);
1961 iax2_destroy(callno);
1963 ast_mutex_unlock(&iaxsl[callno]);
1967 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1970 ast_free(s->f.data.ptr);
1975 /*! \brief This function must be called once we are sure the other side has
1976 * given us a call number. All signaling is held here until that point. */
1977 static void send_signaling(struct chan_iax2_pvt *pvt)
1979 struct signaling_queue_entry *s = NULL;
1981 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1982 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1983 free_signaling_queue_entry(s);
1985 pvt->hold_signaling = 0;
1988 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1989 * we have received a destination call number. */
1990 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1992 struct signaling_queue_entry *qe;
1994 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1995 return 1; /* do not queue this frame */
1996 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1997 return -1; /* out of memory */
2000 /* copy ast_frame into our queue entry */
2002 if (qe->f.datalen) {
2003 /* if there is data in this frame copy it over as well */
2004 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2005 free_signaling_queue_entry(qe);
2008 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2010 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2015 static void pvt_destructor(void *obj)
2017 struct chan_iax2_pvt *pvt = obj;
2018 struct iax_frame *cur = NULL;
2019 struct signaling_queue_entry *s = NULL;
2021 ast_mutex_lock(&iaxsl[pvt->callno]);
2023 iax2_destroy_helper(pvt);
2025 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2026 pvt->callno_entry = 0;
2029 ast_set_flag64(pvt, IAX_ALREADYGONE);
2031 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2032 /* Cancel any pending transmissions */
2036 ast_mutex_unlock(&iaxsl[pvt->callno]);
2038 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2039 free_signaling_queue_entry(s);
2043 pvt->reg->callno = 0;
2049 ast_variables_destroy(pvt->vars);
2053 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2054 iax2_frame_free(frame.data);
2057 jb_destroy(pvt->jb);
2058 ast_string_field_free_memory(pvt);
2062 ast_callid_unref(pvt->callid);
2067 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2069 struct chan_iax2_pvt *tmp;
2072 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2076 if (ast_string_field_init(tmp, 32)) {
2088 tmp->keyrotateid = -1;
2090 ast_string_field_set(tmp,exten, "s");
2091 ast_string_field_set(tmp,host, host);
2095 jbconf.max_jitterbuf = maxjitterbuffer;
2096 jbconf.resync_threshold = resyncthreshold;
2097 jbconf.max_contig_interp = maxjitterinterps;
2098 jbconf.target_extra = jittertargetextra;
2099 jb_setconf(tmp->jb,&jbconf);
2101 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2103 tmp->hold_signaling = 1;
2104 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2109 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2111 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2113 size_t afdatalen = new->afdatalen;
2114 memcpy(new, fr, sizeof(*new));
2115 iax_frame_wrap(new, &fr->af);
2116 new->afdatalen = afdatalen;
2119 new->direction = DIRECTION_INGRESS;
2124 /* keep these defined in this order. They are used in find_callno to
2125 * determine whether or not a new call number should be allowed. */
2127 /* do not allow a new call number, only search ones in use for match */
2129 /* search for match first, then allow a new one to be allocated */
2131 /* do not search for match, force a new call number */
2133 /* do not search for match, force a new call number. Signifies call number
2134 * has been calltoken validated */
2135 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2138 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2140 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2141 /* This is the main host */
2142 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2143 (check_dcallno ? dcallno == cur->callno : 1) ) {
2144 /* That's us. Be sure we keep track of the peer call number */
2148 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2149 /* We're transferring */
2150 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2156 static int make_trunk(unsigned short callno, int locked)
2161 if (iaxs[callno]->oseqno) {
2162 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2165 if (callno >= TRUNK_CALL_START) {
2166 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2170 if (get_unused_callno(
2172 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2174 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2178 x = CALLNO_ENTRY_GET_CALLNO(entry);
2179 ast_mutex_lock(&iaxsl[x]);
2182 * \note We delete these before switching the slot, because if
2183 * they fire in the meantime, they will generate a warning.
2185 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2186 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2187 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2188 iaxs[x] = iaxs[callno];
2189 iaxs[x]->callno = x;
2191 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2192 * before assigning the new one */
2193 if (iaxs[x]->callno_entry) {
2196 MIN_REUSE_TIME * 1000,
2198 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2201 iaxs[x]->callno_entry = entry;
2203 iaxs[callno] = NULL;
2204 /* Update the two timers that should have been started */
2205 iaxs[x]->pingid = iax2_sched_add(sched,
2206 ping_time * 1000, send_ping, (void *)(long)x);
2207 iaxs[x]->lagid = iax2_sched_add(sched,
2208 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2211 ast_mutex_unlock(&iaxsl[callno]);
2214 ast_mutex_unlock(&iaxsl[x]);
2216 /* We moved this call from a non-trunked to a trunked call */
2217 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2222 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2224 if (!pvt->transfercallno) {
2225 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2229 ao2_link(iax_transfercallno_pvts, pvt);
2232 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2234 if (!pvt->transfercallno) {
2235 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2239 ao2_unlink(iax_transfercallno_pvts, pvt);
2241 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2243 if (!pvt->peercallno) {
2244 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2248 ao2_link(iax_peercallno_pvts, pvt);
2251 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2253 if (!pvt->peercallno) {
2254 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2258 ao2_unlink(iax_peercallno_pvts, pvt);
2261 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2263 struct addr_range *lim = obj;
2268 static int addr_range_hash_cb(const void *obj, const int flags)
2270 const struct addr_range *lim = obj;
2271 return abs(ast_sockaddr_hash(&lim->ha.addr));
2274 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2276 struct addr_range *lim1 = obj, *lim2 = arg;
2277 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2278 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2279 CMP_MATCH | CMP_STOP : 0;
2282 static int peercnt_hash_cb(const void *obj, const int flags)
2284 const struct peercnt *peercnt = obj;
2286 if (ast_sockaddr_isnull(&peercnt->addr)) {
2289 return ast_sockaddr_hash(&peercnt->addr);
2292 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2294 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2295 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2298 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2300 struct addr_range *addr_range = obj;
2301 struct ast_sockaddr *addr = arg;
2302 struct ast_sockaddr tmp_addr;
2304 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2306 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2307 return CMP_MATCH | CMP_STOP;
2315 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2317 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2319 struct addr_range *addr_range;
2320 struct iax2_peer *peer = NULL;
2321 struct iax2_user *user = NULL;
2322 /* if no username is given, check for guest accounts */
2323 const char *find = S_OR(name, "guest");
2324 int res = 1; /* required by default */
2326 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2327 /* There are only two cases in which calltoken validation is not required.
2328 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2329 * the peer definition has not set the requirecalltoken option.
2330 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2333 /* ----- Case 1 ----- */
2334 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2335 ao2_ref(addr_range, -1);
2339 /* ----- Case 2 ----- */
2340 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2341 calltoken_required = user->calltoken_required;
2342 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2343 calltoken_required = user->calltoken_required;
2344 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2345 calltoken_required = peer->calltoken_required;
2346 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2347 calltoken_required = peer->calltoken_required;
2357 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2358 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2359 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2369 * \brief set peercnt callno limit.
2372 * First looks in custom definitions. If not found, global limit
2373 * is used. Entries marked as reg already have
2374 * a custom limit set by a registration and are not modified.
2376 static void set_peercnt_limit(struct peercnt *peercnt)
2378 uint16_t limit = global_maxcallno;
2379 struct addr_range *addr_range;
2380 struct ast_sockaddr addr;
2382 ast_sockaddr_copy(&addr, &peercnt->addr);
2384 if (peercnt->reg && peercnt->limit) {
2385 return; /* this peercnt has a custom limit set by a registration */
2388 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2389 limit = addr_range->limit;
2390 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2391 ao2_ref(addr_range, -1);
2394 peercnt->limit = limit;
2399 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2401 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2403 struct peercnt *peercnt = obj;
2405 set_peercnt_limit(peercnt);
2406 ast_debug(1, "Reset limits for peercnts table\n");
2413 * \brief returns match if delme is set.
2415 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2417 struct addr_range *addr_range = obj;
2419 return addr_range->delme ? CMP_MATCH : 0;
2424 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2426 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2428 /* this function turns off and on custom callno limits set by peer registration */
2429 struct peercnt *peercnt;
2432 ast_sockaddr_copy(&tmp.addr, sockaddr);
2434 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2437 peercnt->limit = limit;
2439 set_peercnt_limit(peercnt);
2441 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2442 ao2_ref(peercnt, -1); /* decrement ref from find */
2448 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2450 * \details First searches for the address in the peercnts table. If found
2451 * the current count is incremented. If not found a new peercnt is allocated
2452 * and linked into the peercnts table with a call number count of 1.
2454 static int peercnt_add(struct ast_sockaddr *addr)
2456 struct peercnt *peercnt;
2460 ast_sockaddr_copy(&tmp.addr, addr);
2462 /* Reasoning for peercnts container lock: Two identical ip addresses
2463 * could be added by different threads at the "same time". Without the container
2464 * lock, both threads could alloc space for the same object and attempt
2465 * to link to table. With the lock, one would create the object and link
2466 * to table while the other would find the already created peercnt object
2467 * rather than creating a new one. */
2469 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2471 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2473 /* create and set defaults */
2474 ast_sockaddr_copy(&peercnt->addr, addr);
2475 set_peercnt_limit(peercnt);
2476 /* guarantees it does not go away after unlocking table
2477 * ao2_find automatically adds this */
2478 ao2_link(peercnts, peercnt);
2480 ao2_unlock(peercnts);
2484 /* check to see if the address has hit its callno limit. If not increment cur. */
2485 if (peercnt->limit > peercnt->cur) {
2487 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2488 } else { /* max num call numbers for this peer has been reached! */
2489 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2493 /* clean up locks and ref count */
2494 ao2_unlock(peercnt);
2495 ao2_unlock(peercnts);
2496 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2503 * \brief decrements a peercnts table entry
2505 static void peercnt_remove(struct peercnt *peercnt)
2507 struct ast_sockaddr addr;
2509 ast_sockaddr_copy(&addr, &peercnt->addr);
2512 * Container locked here since peercnt may be unlinked from
2513 * list. If left unlocked, peercnt_add could try and grab this
2514 * entry from the table and modify it at the "same time" this
2515 * thread attemps to unlink it.
2519 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2520 /* if this was the last connection from the peer remove it from table */
2521 if (peercnt->cur == 0) {
2522 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2524 ao2_unlock(peercnts);
2529 * \brief called by scheduler to decrement object
2531 static int peercnt_remove_cb(const void *obj)
2533 struct peercnt *peercnt = (struct peercnt *) obj;
2535 peercnt_remove(peercnt);
2536 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2543 * \brief decrements peercnts connection count, finds by addr
2545 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2547 struct peercnt *peercnt;
2550 ast_sockaddr_copy(&tmp.addr, addr);
2552 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2553 peercnt_remove(peercnt);
2554 ao2_ref(peercnt, -1); /* decrement ref from find */
2561 * \brief Create callno_limit entry based on configuration
2563 static void build_callno_limits(struct ast_variable *v)
2565 struct addr_range *addr_range = NULL;
2566 struct addr_range tmp;
2572 for (; v; v = v->next) {
2576 ha = ast_append_ha("permit", v->name, NULL, &error);
2578 /* check for valid config information */
2580 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2582 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2583 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2588 ast_copy_ha(ha, &tmp.ha);
2589 /* find or create the addr_range */
2590 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2591 ao2_lock(addr_range);
2593 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2595 return; /* out of memory */
2598 /* copy over config data into addr_range object */
2599 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2600 ast_free_ha(ha); /* cleanup the tmp ha */
2601 addr_range->limit = limit;
2602 addr_range->delme = 0;
2606 ao2_unlock(addr_range);
2608 ao2_link(callno_limits, addr_range);
2610 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2616 * \brief Create calltoken_ignores entry based on configuration
2618 static int add_calltoken_ignore(const char *addr)
2620 struct addr_range tmp;
2621 struct addr_range *addr_range = NULL;
2622 struct ast_ha *ha = NULL;
2625 if (ast_strlen_zero(addr)) {
2626 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2630 ha = ast_append_ha("permit", addr, NULL, &error);
2632 /* check for valid config information */
2634 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2638 ast_copy_ha(ha, &tmp.ha);
2639 /* find or create the addr_range */
2640 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2641 ao2_lock(addr_range);
2642 addr_range->delme = 0;
2643 ao2_unlock(addr_range);
2644 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2645 /* copy over config data into addr_range object */
2646 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2647 ao2_link(calltoken_ignores, addr_range);
2654 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2659 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2661 struct ao2_iterator i;
2662 struct peercnt *peercnt;
2663 struct ast_sockaddr addr;
2668 e->command = "iax2 show callnumber usage";
2670 "Usage: iax2 show callnumber usage [IP address]\n"
2671 " Shows current IP addresses which are consuming iax2 call numbers\n";
2676 if (a->argc < 4 || a->argc > 5)
2677 return CLI_SHOWUSAGE;
2680 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2683 i = ao2_iterator_init(peercnts, 0);
2684 while ((peercnt = ao2_iterator_next(&i))) {
2685 ast_sockaddr_copy(&addr, &peercnt->addr);
2688 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2689 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2690 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2691 ao2_ref(peercnt, -1);
2696 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2698 ao2_ref(peercnt, -1);
2700 ao2_iterator_destroy(&i);
2703 size_t pool_avail = callno_pool.available;
2704 size_t trunk_pool_avail = callno_pool_trunk.available;
2706 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2707 "Non-CallToken Validated Callno Used: %d\n",
2708 global_maxcallno_nonval,
2709 total_nonval_callno_used);
2711 ast_cli(a->fd, "Total Available Callno: %zu\n"
2712 "Regular Callno Available: %zu\n"
2713 "Trunk Callno Available: %zu\n",
2714 pool_avail + trunk_pool_avail,
2717 } else if (a->argc == 5 && !found) {
2718 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2728 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2730 struct call_number_pool *pool = NULL;
2735 case CALLNO_TYPE_NORMAL:
2736 pool = &callno_pool;
2738 case CALLNO_TYPE_TRUNK:
2739 pool = &callno_pool_trunk;
2746 /* If we fail, make sure this has a defined value */
2749 /* We lock here primarily to ensure thread safety of the
2750 * total_nonval_callno_used check and increment */
2751 ast_mutex_lock(&callno_pool_lock);
2753 /* Bail out if we don't have any available call numbers */
2754 if (!pool->available) {
2755 ast_log(LOG_WARNING, "Out of call numbers\n");
2756 ast_mutex_unlock(&callno_pool_lock);
2760 /* Only a certain number of non-validated call numbers should be allocated.
2761 * If there ever is an attack, this separates the calltoken validating users
2762 * from the non-calltoken validating users. */
2763 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2764 ast_log(LOG_WARNING,
2765 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2766 total_nonval_callno_used,
2767 global_maxcallno_nonval);
2768 ast_mutex_unlock(&callno_pool_lock);
2772 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2773 * available call numbers. The array of call numbers begins as an ordered
2774 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2775 * - let's call that x. When a call number is needed we pick a random index
2776 * into the array between 0 and x and use that as our call number. In a
2777 * typical FYD shuffle, we would swap the value that we are extracting with
2778 * the number at x, but in our case we swap and don't touch the value at x
2779 * because it is effectively invisible. We rely on the rest of the IAX2 core
2780 * to return the number to us at some point. Finally, we decrement x by 1
2781 * which establishes our new unused range.
2783 * When numbers are returned to the pool, we put them just past x and bump x
2784 * by 1 so that this number is now available for re-use. */
2786 choice = ast_random() % pool->available;
2788 *entry = pool->numbers[choice];
2789 swap = pool->numbers[pool->available - 1];
2791 pool->numbers[choice] = swap;
2795 CALLNO_ENTRY_SET_VALIDATED(*entry);
2797 total_nonval_callno_used++;
2800 ast_mutex_unlock(&callno_pool_lock);
2805 static int replace_callno(const void *obj)
2807 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2808 struct call_number_pool *pool;
2810 /* We lock here primarily to ensure thread safety of the
2811 * total_nonval_callno_used check and decrement */
2812 ast_mutex_lock(&callno_pool_lock);
2814 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2815 if (total_nonval_callno_used) {
2816 total_nonval_callno_used--;
2819 "Attempted to decrement total non calltoken validated "
2820 "callnumbers below zero. Callno is: %d\n",
2821 CALLNO_ENTRY_GET_CALLNO(entry));
2825 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2826 pool = &callno_pool;
2828 pool = &callno_pool_trunk;
2831 ast_assert(pool->capacity > pool->available);
2833 /* This clears the validated flag */
2834 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2836 pool->numbers[pool->available] = entry;
2839 ast_mutex_unlock(&callno_pool_lock);
2844 static int create_callno_pools(void)
2848 callno_pool.available = callno_pool_trunk.available = 0;
2850 /* We start at 2. 0 and 1 are reserved. */
2851 for (i = 2; i < TRUNK_CALL_START; i++) {
2852 callno_pool.numbers[callno_pool.available] = i;
2853 callno_pool.available++;
2856 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2857 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2858 callno_pool_trunk.available++;
2861 callno_pool.capacity = callno_pool.available;
2862 callno_pool_trunk.capacity = callno_pool_trunk.available;
2864 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2871 * \brief Schedules delayed removal of iax2_pvt call number data
2873 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2874 * avaliable again, and the address from the previous connection must be decremented
2875 * from the peercnts table. This function schedules these operations to take place.
2877 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
2880 struct peercnt *peercnt;
2883 ast_sockaddr_copy(&tmp.addr, addr);
2885 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2886 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2887 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
2888 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2890 ao2_ref(peercnt, -1);
2896 MIN_REUSE_TIME * 1000,
2898 CALLNO_ENTRY_TO_PTR(entry));
2903 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2905 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2908 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2910 if (frametype != AST_FRAME_IAX) {
2914 case IAX_COMMAND_NEW:
2915 case IAX_COMMAND_REGREQ:
2916 case IAX_COMMAND_FWDOWNL:
2917 case IAX_COMMAND_REGREL:
2919 case IAX_COMMAND_POKE:
2929 * \note Calling this function while holding another pvt lock can cause a deadlock.
2931 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
2935 /* this call is calltoken validated as long as it is either NEW_FORCE
2936 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2937 int validated = (new > NEW_ALLOW) ? 1 : 0;
2940 if (new <= NEW_ALLOW) {
2942 struct chan_iax2_pvt *pvt;
2943 struct chan_iax2_pvt tmp_pvt = {
2945 .peercallno = callno,
2946 .transfercallno = callno,
2948 .frames_received = check_dcallno,
2951 ast_sockaddr_copy(&tmp_pvt.addr, addr);
2952 /* this works for finding normal call numbers not involving transfering */
2953 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2954 if (return_locked) {
2955 ast_mutex_lock(&iaxsl[pvt->callno]);
2962 /* this searches for transfer call numbers that might not get caught otherwise */
2963 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2964 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
2965 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2966 if (return_locked) {
2967 ast_mutex_lock(&iaxsl[pvt->callno]);
2975 /* This will occur on the first response to a message that we initiated,
2976 * such as a PING. */
2978 ast_mutex_lock(&iaxsl[dcallno]);
2980 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2981 iaxs[dcallno]->peercallno = callno;
2983 store_by_peercallno(iaxs[dcallno]);
2984 if (!res || !return_locked) {
2985 ast_mutex_unlock(&iaxsl[dcallno]);
2990 ast_mutex_unlock(&iaxsl[dcallno]);
2993 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(*addr, host, sizeof(host)))
3003 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3005 if (peercnt_add(addr)) {
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(addr);
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(addr, host);
3024 ast_debug(1, "Creating new call structure %d\n", x);
3025 iaxs[x]->callno_entry = entry;
3026 iaxs[x]->sockfd = sockfd;
3027 ast_sockaddr_copy(&iaxs[x]->addr, addr);
3028 iaxs[x]->peercallno = callno;
3029 iaxs[x]->callno = x;
3030 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3031 iaxs[x]->expiry = min_reg_expire;
3032 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3033 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3034 iaxs[x]->amaflags = amaflags;
3035 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3036 ast_string_field_set(iaxs[x], accountcode, accountcode);
3037 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3038 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3039 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3041 if (iaxs[x]->peercallno) {
3042 store_by_peercallno(iaxs[x]);
3045 ast_log(LOG_WARNING, "Out of resources\n");
3046 ast_mutex_unlock(&iaxsl[x]);
3047 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3051 ast_mutex_unlock(&iaxsl[x]);
3057 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3058 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3061 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3063 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3067 * \brief Queue a frame to a call's owning asterisk channel
3069 * \pre This function assumes that iaxsl[callno] is locked when called.
3071 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3072 * was valid before calling it, it may no longer be valid after calling it.
3073 * This function may unlock and lock the mutex associated with this callno,
3074 * meaning that another thread may grab it and destroy the call.
3076 static int iax2_queue_frame(int callno, struct ast_frame *f)
3078 iax2_lock_owner(callno);
3079 if (iaxs[callno] && iaxs[callno]->owner) {
3080 ast_queue_frame(iaxs[callno]->owner, f);
3081 ast_channel_unlock(iaxs[callno]->owner);
3087 * \brief Queue a hold frame on the ast_channel owner
3089 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3090 * is active for the given call number.
3092 * \pre Assumes lock for callno is already held.
3094 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3095 * was valid before calling it, it may no longer be valid after calling it.
3096 * This function may unlock and lock the mutex associated with this callno,
3097 * meaning that another thread may grab it and destroy the call.
3099 static int iax2_queue_hold(int callno, const char *musicclass)
3101 iax2_lock_owner(callno);
3102 if (iaxs[callno] && iaxs[callno]->owner) {
3103 ast_queue_hold(iaxs[callno]->owner, musicclass);
3104 ast_channel_unlock(iaxs[callno]->owner);
3110 * \brief Queue an unhold frame on the ast_channel owner
3112 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3113 * is active for the given call number.
3115 * \pre Assumes lock for callno is already held.
3117 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3118 * was valid before calling it, it may no longer be valid after calling it.
3119 * This function may unlock and lock the mutex associated with this callno,
3120 * meaning that another thread may grab it and destroy the call.
3122 static int iax2_queue_unhold(int callno)
3124 iax2_lock_owner(callno);
3125 if (iaxs[callno] && iaxs[callno]->owner) {
3126 ast_queue_unhold(iaxs[callno]->owner);
3127 ast_channel_unlock(iaxs[callno]->owner);
3133 * \brief Queue a hangup frame on the ast_channel owner
3135 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3136 * is active for the given call number.
3138 * \pre Assumes lock for callno is already held.
3140 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3141 * was valid before calling it, it may no longer be valid after calling it.
3142 * This function may unlock and lock the mutex associated with this callno,
3143 * meaning that another thread may grab it and destroy the call.
3145 static int iax2_queue_hangup(int callno)
3147 iax2_lock_owner(callno);
3148 if (iaxs[callno] && iaxs[callno]->owner) {
3149 ast_queue_hangup(iaxs[callno]->owner);
3150 ast_channel_unlock(iaxs[callno]->owner);
3156 * \note This function assumes that iaxsl[callno] is locked when called.
3158 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3159 * was valid before calling it, it may no longer be valid after calling it.
3160 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3161 * associated with this callno, meaning that another thread may grab it and destroy the call.
3163 static int __do_deliver(void *data)
3165 /* Just deliver the packet by using queueing. This is called by
3166 the IAX thread with the iaxsl lock held. */
3167 struct iax_frame *fr = data;
3169 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3170 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3171 iax2_queue_frame(fr->callno, &fr->af);
3172 /* Free our iax frame */
3173 iax2_frame_free(fr);
3174 /* And don't run again */
3178 static int handle_error(void)
3180 /* XXX Ideally we should figure out why an error occurred and then abort those
3181 rather than continuing to try. Unfortunately, the published interface does
3182 not seem to work XXX */
3184 struct sockaddr_in *sin;
3187 struct sock_extended_err e;
3192 m.msg_controllen = sizeof(e);
3194 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3196 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3198 if (m.msg_controllen) {
3199 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3201 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3203 ast_log(LOG_WARNING, "No address detected??\n");
3205 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3212 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3215 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3218 ast_debug(1, "Received error: %s\n", strerror(errno));
3225 static int send_packet(struct iax_frame *f)
3228 int callno = f->callno;
3230 /* Don't send if there was an error, but return error instead */
3231 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3234 /* Called with iaxsl held */
3236 ast_debug(3, "Sending %d on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3239 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3240 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3242 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3243 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3247 ast_debug(1, "Received error: %s\n", strerror(errno));
3256 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3257 * for the given call number may disappear during its execution.
3259 static int iax2_predestroy(int callno)
3261 struct ast_channel *c = NULL;
3262 struct chan_iax2_pvt *pvt = iaxs[callno];
3267 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3268 iax2_destroy_helper(pvt);
3269 ast_set_flag64(pvt, IAX_ALREADYGONE);
3272 if ((c = pvt->owner)) {
3273 ast_channel_tech_pvt_set(c, NULL);
3274 iax2_queue_hangup(callno);
3276 ast_module_unref(ast_module_info->self);
3282 static void iax2_destroy(int callno)
3284 struct chan_iax2_pvt *pvt = NULL;
3285 struct ast_channel *owner = NULL;
3288 if ((pvt = iaxs[callno])) {
3290 /* iax2_destroy_helper gets called from this function later on. When
3291 * called twice, we get the (previously) familiar FRACK! errors in
3292 * devmode, from the scheduler. An alternative to this approach is to
3293 * reset the scheduler entries to -1 when they're deleted in
3294 * iax2_destroy_helper(). That approach was previously decided to be
3295 * "wrong" because "the memory is going to be deallocated anyway. Why
3296 * should we be resetting those values?" */
3297 iax2_destroy_helper(pvt);
3301 owner = pvt ? pvt->owner : NULL;
3304 if (ast_channel_trylock(owner)) {
3305 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3306 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3312 iaxs[callno] = NULL;
3319 /* If there's an owner, prod it to give up */
3320 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3321 * because we already hold the owner channel lock. */
3322 ast_queue_hangup(owner);
3325 if (pvt->peercallno) {
3326 remove_by_peercallno(pvt);
3329 if (pvt->transfercallno) {
3330 remove_by_transfercallno(pvt);
3340 ast_channel_unlock(owner);
3344 static int update_packet(struct iax_frame *f)
3346 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3347 struct ast_iax2_full_hdr *fh = f->data;
3348 struct ast_frame af;
3350 /* if frame is encrypted. decrypt before updating it. */
3351 if (f->encmethods) {
3352 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3354 /* Mark this as a retransmission */
3355 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3357 f->iseqno = iaxs[f->callno]->iseqno;
3358 fh->iseqno = f->iseqno;
3360 /* Now re-encrypt the frame */
3361 if (f->encmethods) {
3362 /* since this is a retransmit frame, create a new random padding
3363 * before re-encrypting. */
3364 build_rand_pad(f->semirand, sizeof(f->semirand));
3365 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3370 static int attempt_transmit(const void *data);
3371 static void __attempt_transmit(const void *data)
3373 /* Attempt to transmit the frame to the remote peer...
3374 Called without iaxsl held. */
3375 struct iax_frame *f = (struct iax_frame *)data;
3377 int callno = f->callno;
3379 /* Make sure this call is still active */
3381 ast_mutex_lock(&iaxsl[callno]);
3382 if (callno && iaxs[callno]) {
3383 if (f->retries < 0) {
3386 } else if (f->retries >= max_retries) {
3387 /* Too many attempts. Record an error. */
3389 /* Transfer timeout */
3390 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3391 } else if (f->final) {
3392 iax2_destroy(callno);
3394 if (iaxs[callno]->owner) {
3395 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n",
3396 ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3397 ast_channel_name(iaxs[f->callno]->owner),
3399 f->af.subclass.integer,
3403 iaxs[callno]->error = ETIMEDOUT;
3404 if (iaxs[callno]->owner) {
3405 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3407 iax2_queue_frame(callno, &fr); /* XXX */
3408 /* Remember, owner could disappear */
3409 if (iaxs[callno] && iaxs[callno]->owner)
3410 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3412 if (iaxs[callno]->reg) {
3413 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3414 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3415 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3417 iax2_destroy(callno);
3422 /* Update it if it needs it */
3424 /* Attempt transmission */
3427 /* Try again later after 10 times as long */
3429 if (f->retrytime > MAX_RETRY_TIME)
3430 f->retrytime = MAX_RETRY_TIME;
3431 /* Transfer messages max out at one second */
3432 if (f->transfer && (f->retrytime > 1000))
3433 f->retrytime = 1000;
3434 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3437 /* Make sure it gets freed */
3443 /* Don't attempt delivery, just remove it from the queue */
3444 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3445 ast_mutex_unlock(&iaxsl[callno]);
3446 f->retrans = -1; /* this is safe because this is the scheduled function */
3447 /* Free the IAX frame */
3449 } else if (callno) {
3450 ast_mutex_unlock(&iaxsl[callno]);
3454 static int attempt_transmit(const void *data)
3456 #ifdef SCHED_MULTITHREADED
3457 if (schedule_action(__attempt_transmit, data))
3459 __attempt_transmit(data);
3463 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3465 struct iax2_peer *peer = NULL;
3466 struct iax2_user *user = NULL;
3467 static const char * const choices[] = { "all", NULL };
3472 e->command = "iax2 prune realtime";
3474 "Usage: iax2 prune realtime [<peername>|all]\n"
3475 " Prunes object(s) from the cache\n";
3479 cmplt = ast_cli_complete(a->word, choices, a->n);
3481 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3487 return CLI_SHOWUSAGE;
3488 if (!strcmp(a->argv[3], "all")) {
3491 ast_cli(a->fd, "Cache flushed successfully.\n");
3494 peer = find_peer(a->argv[3], 0);
3495 user = find_user(a->argv[3]);
3498 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3499 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3500 expire_registry(peer_ref(peer));
3501 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3503 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3508 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3509 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3510 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3512 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3514 ao2_unlink(users,user);
3518 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3524 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3528 e->command = "iax2 test losspct";
3530 "Usage: iax2 test losspct <percentage>\n"
3531 " For testing, throws away <percentage> percent of incoming packets\n";
3537 return CLI_SHOWUSAGE;
3539 test_losspct = atoi(a->argv[3]);
3545 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3549 e->command = "iax2 test late";
3551 "Usage: iax2 test late <ms>\n"
3552 " For testing, count the next frame as <ms> ms late\n";
3559 return CLI_SHOWUSAGE;
3561 test_late = atoi(a->argv[3]);
3566 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3570 e->command = "iax2 test resync";
3572 "Usage: iax2 test resync <ms>\n"
3573 " For testing, adjust all future frames by <ms> ms\n";
3580 return CLI_SHOWUSAGE;
3582 test_resync = atoi(a->argv[3]);
3587 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3591 e->command = "iax2 test jitter";
3593 "Usage: iax2 test jitter <ms> <pct>\n"
3594 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3595 " percentage of packets. If <pct> is not specified, adds\n"
3596 " jitter to all packets.\n";
3602 if (a->argc < 4 || a->argc > 5)
3603 return CLI_SHOWUSAGE;
3605 test_jit = atoi(a->argv[3]);
3607 test_jitpct = atoi(a->argv[4]);
3611 #endif /* IAXTESTS */
3613 /*! \brief peer_status: Report Peer status in character string */
3614 /* returns 1 if peer is online, -1 if unmonitored */
3615 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3619 if (peer->lastms < 0) {
3620 ast_copy_string(status, "UNREACHABLE", statuslen);
3621 } else if (peer->lastms > peer->maxms) {
3622 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3624 } else if (peer->lastms) {
3625 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3628 ast_copy_string(status, "UNKNOWN", statuslen);
3631 ast_copy_string(status, "Unmonitored", statuslen);
3637 /*! \brief Show one peer in detail */
3638 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3642 struct iax2_peer *peer;
3643 char codec_buf[512];
3644 struct ast_str *encmethods = ast_str_alloca(256);
3645 int x = 0, load_realtime = 0;
3649 e->command = "iax2 show peer";
3651 "Usage: iax2 show peer <name>\n"
3652 " Display details on specific IAX peer\n";
3656 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3661 return CLI_SHOWUSAGE;
3663 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3665 peer = find_peer(a->argv[3], load_realtime);
3667 char *str_addr, *str_defaddr;
3668 char *str_port, *str_defport;
3670 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3671 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3672 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3673 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3675 encmethods_to_str(peer->encmethods, &encmethods);
3676 ast_cli(a->fd, "\n\n");
3677 ast_cli(a->fd, " * Name : %s\n", peer->name);
3678 ast_cli(a->fd, " Description : %s\n", peer->description);
3679 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3680 ast_cli(a->fd, " Context : %s\n", peer->context);
3681 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3682 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3683 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3684 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3685 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3686 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3687 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3688 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3689 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3690 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3691 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3692 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3693 ast_cli(a->fd, " Username : %s\n", peer->username);
3694 ast_cli(a->fd, " Codecs : ");
3695 iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3696 ast_cli(a->fd, "%s\n", codec_buf);
3698 ast_cli(a->fd, " Codec Order : (");
3699 for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
3700 struct ast_format tmpfmt;
3701 if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
3703 ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
3704 if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
3705 ast_cli(a->fd, "|");
3709 ast_cli(a->fd, "none");
3710 ast_cli(a->fd, ")\n");
3712 ast_cli(a->fd, " Status : ");
3713 peer_status(peer, status, sizeof(status));
3714 ast_cli(a->fd, "%s\n",status);
3715 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");
3716 ast_cli(a->fd, "\n");
3719 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3720 ast_cli(a->fd, "\n");
3726 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3729 struct iax2_peer *peer;
3731 int wordlen = strlen(word);
3732 struct ao2_iterator i;
3734 i = ao2_iterator_init(peers, 0);
3735 while ((peer = ao2_iterator_next(&i))) {
3736 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3737 && (!flags || ast_test_flag64(peer, flags))) {
3738 res = ast_strdup(peer->name);
3744 ao2_iterator_destroy(&i);
3749 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3751 struct iax_frame *cur;