2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
34 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35 * \addtogroup configuration_file
38 /*! \page iax.conf iax.conf
39 * \verbinclude iax.conf.sample
43 <use type="external">crypto</use>
44 <support_level>core</support_level>
49 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
59 #include <sys/signal.h>
67 #include "asterisk/paths.h"
69 #include "asterisk/lock.h"
70 #include "asterisk/frame.h"
71 #include "asterisk/channel.h"
72 #include "asterisk/module.h"
73 #include "asterisk/pbx.h"
74 #include "asterisk/sched.h"
75 #include "asterisk/io.h"
76 #include "asterisk/config.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/crypto.h"
81 #include "asterisk/acl.h"
82 #include "asterisk/manager.h"
83 #include "asterisk/callerid.h"
84 #include "asterisk/app.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/musiconhold.h"
87 #include "asterisk/features.h"
88 #include "asterisk/utils.h"
89 #include "asterisk/causes.h"
90 #include "asterisk/localtime.h"
91 #include "asterisk/dnsmgr.h"
92 #include "asterisk/devicestate.h"
93 #include "asterisk/netsock.h"
94 #include "asterisk/stringfields.h"
95 #include "asterisk/linkedlists.h"
96 #include "asterisk/event.h"
97 #include "asterisk/astobj2.h"
98 #include "asterisk/timing.h"
99 #include "asterisk/taskprocessor.h"
100 #include "asterisk/test.h"
101 #include "asterisk/data.h"
102 #include "asterisk/netsock2.h"
103 #include "asterisk/security_events.h"
104 #include "asterisk/bridging.h"
106 #include "iax2/include/iax2.h"
107 #include "iax2/include/firmware.h"
108 #include "iax2/include/parser.h"
109 #include "iax2/include/provision.h"
110 #include "jitterbuf.h"
113 <application name="IAX2Provision" language="en_US">
115 Provision a calling IAXy with a given template.
118 <parameter name="template">
119 <para>If not specified, defaults to <literal>default</literal>.</para>
123 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
124 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
125 or <literal>0</literal> on success.</para>
128 <function name="IAXPEER" language="en_US">
130 Gets IAX peer information.
133 <parameter name="peername" required="true">
135 <enum name="CURRENTCHANNEL">
136 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
137 endpoint of the current channel</para>
141 <parameter name="item">
142 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
145 <para>(default) The IP address.</para>
148 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
150 <enum name="mailbox">
151 <para>The configured mailbox.</para>
153 <enum name="context">
154 <para>The configured context.</para>
157 <para>The epoch time of the next expire.</para>
159 <enum name="dynamic">
160 <para>Is it dynamic? (yes/no).</para>
162 <enum name="callerid_name">
163 <para>The configured Caller ID name.</para>
165 <enum name="callerid_num">
166 <para>The configured Caller ID number.</para>
169 <para>The configured codecs.</para>
171 <enum name="codec[x]">
172 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
173 with <literal>0</literal>)</para>
179 <para>Gets information associated with the specified IAX2 peer.</para>
182 <ref type="function">SIPPEER</ref>
185 <function name="IAXVAR" language="en_US">
187 Sets or retrieves a remote variable.
190 <parameter name="varname" required="true" />
193 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
196 <manager name="IAXpeers" language="en_US">
201 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
206 <manager name="IAXpeerlist" language="en_US">
211 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
214 <para>List all the IAX peers.</para>
217 <manager name="IAXnetstats" language="en_US">
223 <para>Show IAX channels network statistics.</para>
226 <manager name="IAXregistry" language="en_US">
228 Show IAX registrations.
231 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
234 <para>Show IAX registrations.</para>
239 /* Define SCHED_MULTITHREADED to run the scheduler in a special
240 multithreaded mode. */
241 #define SCHED_MULTITHREADED
243 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
244 thread is actually doing. */
245 #define DEBUG_SCHED_MULTITHREAD
249 static int nochecksums = 0;
252 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
253 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
255 #define DEFAULT_THREAD_COUNT 10
256 #define DEFAULT_MAX_THREAD_COUNT 100
257 #define DEFAULT_RETRY_TIME 1000
258 #define MEMORY_SIZE 100
259 #define DEFAULT_DROP 3
261 #define DEBUG_SUPPORT
263 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
265 /* Sample over last 100 units to determine historic jitter */
268 static struct ast_codec_pref prefs;
270 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
273 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
274 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
275 #define MAX_TRUNK_MTU 1240
277 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
278 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
280 #define DEFAULT_CONTEXT "default"
282 static char default_parkinglot[AST_MAX_CONTEXT];
284 static char language[MAX_LANGUAGE] = "";
285 static char regcontext[AST_MAX_CONTEXT] = "";
287 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
288 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
289 static int network_change_sched_id = -1;
291 static int maxauthreq = 3;
292 static int max_retries = 4;
293 static int ping_time = 21;
294 static int lagrq_time = 10;
295 static int maxjitterbuffer=1000;
296 static int resyncthreshold=1000;
297 static int maxjitterinterps=10;
298 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
300 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
302 static int trunkfreq = 20;
303 static int trunkmaxsize = MAX_TRUNKDATA;
305 static int authdebug = 0;
306 static int autokill = 0;
307 static int iaxcompat = 0;
308 static int last_authmethod = 0;
310 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
312 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
319 static int min_reg_expire;
320 static int max_reg_expire;
322 static int srvlookup = 0;
324 static struct ast_timer *timer; /* Timer for trunking */
326 static struct ast_netsock_list *netsock;
327 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
328 static int defaultsockfd = -1;
330 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
333 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
335 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
338 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
339 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
341 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
342 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
343 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
345 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
346 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
347 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
348 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
350 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
351 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
354 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
355 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
356 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
358 /* if a pvt has encryption setup done and is running on the call */
359 #define IAX_CALLENCRYPTED(pvt) \
360 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
362 #define IAX_DEBUGDIGEST(msg, key) do { \
364 char digest[33] = ""; \
369 for (idx = 0; idx < 16; idx++) \
370 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
372 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
375 static struct io_context *io;
376 static struct ast_sched_context *sched;
378 #define DONT_RESCHEDULE -2
380 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
382 static int iaxdebug = 0;
384 static int iaxtrunkdebug = 0;
386 static int test_losspct = 0;
388 static int test_late = 0;
389 static int test_resync = 0;
390 static int test_jit = 0;
391 static int test_jitpct = 0;
392 #endif /* IAXTESTS */
394 static char accountcode[AST_MAX_ACCOUNT_CODE];
395 static char mohinterpret[MAX_MUSICCLASS];
396 static char mohsuggest[MAX_MUSICCLASS];
397 static int amaflags = 0;
399 static int delayreject = 0;
400 static int iax2_encryption = 0;
402 static struct ast_flags64 globalflags = { 0 };
404 static pthread_t netthreadid = AST_PTHREADT_NULL;
407 IAX_STATE_STARTED = (1 << 0),
408 IAX_STATE_AUTHENTICATED = (1 << 1),
409 IAX_STATE_TBD = (1 << 2),
412 struct iax2_context {
413 char context[AST_MAX_CONTEXT];
414 struct iax2_context *next;
418 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
419 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
420 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
421 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
422 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
423 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
424 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
425 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
426 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
427 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
428 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
429 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
430 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
431 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
432 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
433 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
434 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
435 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
436 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
437 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
438 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
439 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
440 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
441 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
442 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
443 #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 */
444 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
445 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
446 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
447 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
448 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
449 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
450 static int global_rtautoclear = 120;
452 static int reload_config(int forced_reload);
455 * \brief Call token validation settings.
457 enum calltoken_peer_enum {
458 /*! \brief Default calltoken required unless the ip is in the ignorelist */
459 CALLTOKEN_DEFAULT = 0,
460 /*! \brief Require call token validation. */
462 /*! \brief Require call token validation after a successful registration
463 * using call token validation occurs. */
465 /*! \brief Do not require call token validation. */
470 AST_DECLARE_STRING_FIELDS(
471 AST_STRING_FIELD(name);
472 AST_STRING_FIELD(secret);
473 AST_STRING_FIELD(dbsecret);
474 AST_STRING_FIELD(accountcode);
475 AST_STRING_FIELD(mohinterpret);
476 AST_STRING_FIELD(mohsuggest);
477 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
478 AST_STRING_FIELD(language);
479 AST_STRING_FIELD(cid_num);
480 AST_STRING_FIELD(cid_name);
481 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
489 iax2_format capability;
490 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
491 int curauthreq; /*!< Current number of outstanding AUTHREQs */
492 struct ast_codec_pref prefs;
493 struct ast_acl_list *acl;
494 struct iax2_context *contexts;
495 struct ast_variable *vars;
496 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
500 AST_DECLARE_STRING_FIELDS(
501 AST_STRING_FIELD(name);
502 AST_STRING_FIELD(username);
503 AST_STRING_FIELD(description); /*!< Description of the peer */
504 AST_STRING_FIELD(secret);
505 AST_STRING_FIELD(dbsecret);
506 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
508 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
509 AST_STRING_FIELD(context); /*!< For transfers only */
510 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
511 AST_STRING_FIELD(mailbox); /*!< Mailbox */
512 AST_STRING_FIELD(mohinterpret);
513 AST_STRING_FIELD(mohsuggest);
514 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
515 /* Suggested caller id if registering */
516 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
517 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
518 AST_STRING_FIELD(zonetag); /*!< Time Zone */
519 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
521 struct ast_codec_pref prefs;
522 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
523 struct ast_sockaddr addr;
525 int sockfd; /*!< Socket to use for transmission */
530 /* Dynamic Registration fields */
531 struct sockaddr_in defaddr; /*!< Default address if there is one */
532 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
533 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
535 int expire; /*!< Schedule entry for expiry */
536 int expiry; /*!< How soon to expire */
537 iax2_format capability; /*!< Capability */
540 int callno; /*!< Call number of POKE request */
541 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
542 int lastms; /*!< How long last response took (in ms), or -1 for no response */
543 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
545 int pokefreqok; /*!< How often to check if the host is up */
546 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
547 int historicms; /*!< How long recent average responses took */
548 int smoothing; /*!< Sample over how many units to determine historic ms */
549 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
551 struct stasis_subscription *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
553 struct ast_acl_list *acl;
554 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
557 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
559 struct iax2_trunk_peer {
562 struct sockaddr_in addr;
563 struct timeval txtrunktime; /*!< Transmit trunktime */
564 struct timeval rxtrunktime; /*!< Receive trunktime */
565 struct timeval lasttxtime; /*!< Last transmitted trunktime */
566 struct timeval trunkact; /*!< Last trunk activity */
567 unsigned int lastsent; /*!< Last sent time */
568 /* Trunk data and length */
569 unsigned char *trunkdata;
570 unsigned int trunkdatalen;
571 unsigned int trunkdataalloc;
575 AST_LIST_ENTRY(iax2_trunk_peer) list;
578 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
581 REG_STATE_UNREGISTERED = 0,
584 REG_STATE_REGISTERED,
590 enum iax_transfer_state {
595 TRANSFER_PASSTHROUGH,
599 TRANSFER_MPASSTHROUGH,
604 struct iax2_registry {
605 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
607 char secret[80]; /*!< Password or key name in []'s */
608 int expire; /*!< Sched ID of expiration */
609 int refresh; /*!< How often to refresh */
610 enum iax_reg_state regstate;
611 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
612 int callno; /*!< Associated call number if applicable */
613 struct sockaddr_in us; /*!< Who the server thinks we are */
614 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
615 AST_LIST_ENTRY(iax2_registry) entry;
618 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
620 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
621 #define MIN_RETRY_TIME 100
622 #define MAX_RETRY_TIME 10000
624 #define MAX_JITTER_BUFFER 50
625 #define MIN_JITTER_BUFFER 10
627 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
629 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
631 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
632 #define TS_GAP_FOR_JB_RESYNC 5000
634 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
635 #define MARK_IAX_SUBCLASS_TX 0x8000
637 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
638 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
639 static int iaxdynamicthreadcount = 0;
640 static int iaxdynamicthreadnum = 0;
641 static int iaxactivethreadcount = 0;
655 /* We use the high order bit as the validated flag, and the lower 15 as the
656 * actual call number */
657 typedef uint16_t callno_entry;
659 struct chan_iax2_pvt {
660 /*! Socket to send/receive on for this call */
662 /*! ast_callid bound to dialog */
663 struct ast_callid *callid;
664 /*! Last received voice format */
665 iax2_format voiceformat;
666 /*! Last received video format */
667 iax2_format videoformat;
668 /*! Last sent voice format */
669 iax2_format svoiceformat;
670 /*! Last sent video format */
671 iax2_format svideoformat;
672 /*! What we are capable of sending */
673 iax2_format capability;
674 /*! Last received timestamp */
676 /*! Last sent timestamp - never send the same timestamp twice in a single call */
677 unsigned int lastsent;
678 /*! Timestamp of the last video frame sent */
679 unsigned int lastvsent;
680 /*! Next outgoing timestamp if everything is good */
681 unsigned int nextpred;
682 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
683 int first_iax_message;
684 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
685 int last_iax_message;
686 /*! True if the last voice we transmitted was not silence/CNG */
687 unsigned int notsilenttx:1;
689 unsigned int pingtime;
690 /*! Max time for initial response */
693 struct sockaddr_in addr;
694 /*! Actual used codec preferences */
695 struct ast_codec_pref prefs;
696 /*! Requested codec preferences */
697 struct ast_codec_pref rprefs;
698 /*! Our call number */
699 unsigned short callno;
700 /*! Our callno_entry entry */
701 callno_entry callno_entry;
703 unsigned short peercallno;
704 /*! Negotiated format, this is only used to remember what format was
705 chosen for an unauthenticated call so that the channel can get
706 created later using the right format */
707 iax2_format chosenformat;
708 /*! Peer selected format */
709 iax2_format peerformat;
710 /*! Peer capability */
711 iax2_format peercapability;
712 /*! timeval that we base our transmission on */
713 struct timeval offset;
714 /*! timeval that we base our delivery on */
715 struct timeval rxcore;
716 /*! The jitterbuffer */
718 /*! active jb read scheduler id */
722 /*! Error, as discovered by the manager */
724 /*! Owner if we have one */
725 struct ast_channel *owner;
726 /*! What's our state? */
727 struct ast_flags state;
728 /*! Expiry (optional) */
730 /*! Next outgoing sequence number */
731 unsigned char oseqno;
732 /*! Next sequence number they have not yet acknowledged */
733 unsigned char rseqno;
734 /*! Next incoming sequence number */
735 unsigned char iseqno;
736 /*! Last incoming sequence number we have acknowledged */
737 unsigned char aseqno;
739 AST_DECLARE_STRING_FIELDS(
741 AST_STRING_FIELD(peer);
742 /*! Default Context */
743 AST_STRING_FIELD(context);
744 /*! Caller ID if available */
745 AST_STRING_FIELD(cid_num);
746 AST_STRING_FIELD(cid_name);
747 /*! Hidden Caller ID (i.e. ANI) if appropriate */
748 AST_STRING_FIELD(ani);
750 AST_STRING_FIELD(dnid);
752 AST_STRING_FIELD(rdnis);
753 /*! Requested Extension */
754 AST_STRING_FIELD(exten);
755 /*! Expected Username */
756 AST_STRING_FIELD(username);
757 /*! Expected Secret */
758 AST_STRING_FIELD(secret);
760 AST_STRING_FIELD(challenge);
761 /*! Public keys permitted keys for incoming authentication */
762 AST_STRING_FIELD(inkeys);
763 /*! Private key for outgoing authentication */
764 AST_STRING_FIELD(outkey);
765 /*! Preferred language */
766 AST_STRING_FIELD(language);
767 /*! Hostname/peername for naming purposes */
768 AST_STRING_FIELD(host);
770 AST_STRING_FIELD(dproot);
771 AST_STRING_FIELD(accountcode);
772 AST_STRING_FIELD(mohinterpret);
773 AST_STRING_FIELD(mohsuggest);
774 /*! received OSP token */
775 AST_STRING_FIELD(osptoken);
776 /*! Default parkinglot */
777 AST_STRING_FIELD(parkinglot);
779 /*! AUTHREJ all AUTHREP frames */
781 /*! permitted authentication methods */
783 /*! permitted encryption methods */
785 /*! Encryption AES-128 Key */
786 ast_aes_encrypt_key ecx;
787 /*! Decryption AES-128 Key corresponding to ecx */
788 ast_aes_decrypt_key mydcx;
789 /*! Decryption AES-128 Key used to decrypt peer frames */
790 ast_aes_decrypt_key dcx;
791 /*! scheduler id associated with iax_key_rotate
792 * for encrypted calls*/
794 /*! 32 bytes of semi-random data */
795 unsigned char semirand[32];
796 /*! Associated registry */
797 struct iax2_registry *reg;
798 /*! Associated peer for poking */
799 struct iax2_peer *peerpoke;
804 /*! Transferring status */
805 enum iax_transfer_state transferring;
806 /*! Transfer identifier */
808 /*! Who we are IAX transferring to */
809 struct sockaddr_in transfer;
810 /*! What's the new call number for the transfer */
811 unsigned short transfercallno;
812 /*! Transfer encrypt AES-128 Key */
813 ast_aes_encrypt_key tdcx;
815 /*! Status of knowledge of peer ADSI capability */
818 /*! Who we are bridged to */
819 unsigned short bridgecallno;
821 int pingid; /*!< Transmit PING request */
822 int lagid; /*!< Retransmit lag request */
823 int autoid; /*!< Auto hangup for Dialplan requestor */
824 int authid; /*!< Authentication rejection ID */
825 int authfail; /*!< Reason to report failure */
826 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
831 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
832 /*! variables inherited from the user definition */
833 struct ast_variable *vars;
834 /*! variables transmitted in a NEW packet */
835 struct ast_variable *iaxvars;
836 /*! last received remote rr */
837 struct iax_rr remote_rr;
838 /*! Current base time: (just for stats) */
840 /*! Dropped frame count: (just for stats) */
842 /*! received frame count: (just for stats) */
844 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
845 unsigned char calltoken_ie_len;
846 /*! hold all signaling frames from the pbx thread until we have a destination callno */
848 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
849 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
852 struct signaling_queue_entry {
854 AST_LIST_ENTRY(signaling_queue_entry) next;
862 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
863 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
865 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
866 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
867 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
869 struct call_number_pool {
872 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
875 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
877 /*! table of available call numbers */
878 static struct call_number_pool callno_pool;
880 /*! table of available trunk call numbers */
881 static struct call_number_pool callno_pool_trunk;
884 * \brief a list of frames that may need to be retransmitted
886 * \note The contents of this list do not need to be explicitly destroyed
887 * on module unload. This is because all active calls are destroyed, and
888 * all frames in this queue will get destroyed as a part of that process.
890 * \note Contents protected by the iaxsl[] locks
892 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
894 static struct ast_taskprocessor *transmit_processor;
896 static int randomcalltokendata;
898 static const time_t MAX_CALLTOKEN_DELAY = 10;
901 * This module will get much higher performance when doing a lot of
902 * user and peer lookups if the number of buckets is increased from 1.
903 * However, to maintain old behavior for Asterisk 1.4, these are set to
904 * 1 by default. When using multiple buckets, search order through these
905 * containers is considered random, so you will not be able to depend on
906 * the order the entires are specified in iax.conf for matching order. */
908 #define MAX_PEER_BUCKETS 17
910 #define MAX_PEER_BUCKETS 563
912 static struct ao2_container *peers;
914 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
915 static struct ao2_container *users;
917 /*! Table containing peercnt objects for every ip address consuming a callno */
918 static struct ao2_container *peercnts;
920 /*! Table containing custom callno limit rules for a range of ip addresses. */
921 static struct ao2_container *callno_limits;
923 /*! Table containing ip addresses not requiring calltoken validation */
924 static struct ao2_container *calltoken_ignores;
926 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
928 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
930 static uint16_t global_maxcallno;
932 /*! Total num of call numbers allowed to be allocated without calltoken validation */
933 static uint16_t global_maxcallno_nonval;
935 static uint16_t total_nonval_callno_used = 0;
937 /*! peer connection private, keeps track of all the call numbers
938 * consumed by a single ip address */
940 /*! ip address consuming call numbers */
942 /*! Number of call numbers currently used by this ip address */
944 /*! Max call numbers allowed for this ip address */
946 /*! Specifies whether limit is set by a registration or not, if so normal
947 * limit setting rules do not apply to this address. */
951 /*! used by both callno_limits and calltoken_ignores containers */
953 /*! ip address range for custom callno limit rule */
955 /*! callno limit for this ip address range, only used in callno_limits container */
957 /*! delete me marker for reloads */
962 /*! Extension exists */
963 CACHE_FLAG_EXISTS = (1 << 0),
964 /*! Extension is nonexistent */
965 CACHE_FLAG_NONEXISTENT = (1 << 1),
966 /*! Extension can exist */
967 CACHE_FLAG_CANEXIST = (1 << 2),
968 /*! Waiting to hear back response */
969 CACHE_FLAG_PENDING = (1 << 3),
971 CACHE_FLAG_TIMEOUT = (1 << 4),
972 /*! Request transmitted */
973 CACHE_FLAG_TRANSMITTED = (1 << 5),
975 CACHE_FLAG_UNKNOWN = (1 << 6),
977 CACHE_FLAG_MATCHMORE = (1 << 7),
980 struct iax2_dpcache {
981 char peercontext[AST_MAX_CONTEXT];
982 char exten[AST_MAX_EXTENSION];
984 struct timeval expiry;
986 unsigned short callno;
988 AST_LIST_ENTRY(iax2_dpcache) cache_list;
989 AST_LIST_ENTRY(iax2_dpcache) peer_list;
992 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
994 static void reg_source_db(struct iax2_peer *p);
995 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
996 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
998 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
999 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1000 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1002 enum iax2_thread_iostate {
1005 IAX_IOSTATE_PROCESSING,
1006 IAX_IOSTATE_SCHEDREADY,
1009 enum iax2_thread_type {
1010 IAX_THREAD_TYPE_POOL,
1011 IAX_THREAD_TYPE_DYNAMIC,
1014 struct iax2_pkt_buf {
1015 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1017 unsigned char buf[1];
1020 struct iax2_thread {
1021 AST_LIST_ENTRY(iax2_thread) list;
1022 enum iax2_thread_type type;
1023 enum iax2_thread_iostate iostate;
1024 #ifdef SCHED_MULTITHREADED
1025 void (*schedfunc)(const void *);
1026 const void *scheddata;
1028 #ifdef DEBUG_SCHED_MULTITHREAD
1034 struct sockaddr_in iosin;
1035 unsigned char readbuf[4096];
1043 ast_mutex_t init_lock;
1044 ast_cond_t init_cond;
1045 /*! if this thread is processing a full frame,
1046 some information about that frame will be stored
1047 here, so we can avoid dispatching any more full
1048 frames for that callno to other threads */
1050 unsigned short callno;
1051 struct sockaddr_in sin;
1055 /*! Queued up full frames for processing. If more full frames arrive for
1056 * a call which this thread is already processing a full frame for, they
1057 * are queued up here. */
1058 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1063 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1064 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1065 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1067 static void *iax2_process_thread(void *data);
1068 static void iax2_destroy(int callno);
1070 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1072 ast_mutex_lock(lock);
1073 ast_cond_signal(cond);
1074 ast_mutex_unlock(lock);
1078 * \brief an array of iax2 pvt structures
1080 * The container for active chan_iax2_pvt structures is implemented as an
1081 * array for extremely quick direct access to the correct pvt structure
1082 * based on the local call number. The local call number is used as the
1083 * index into the array where the associated pvt structure is stored.
1085 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1087 static struct ast_callid *iax_pvt_callid_get(int callno)
1089 if (iaxs[callno]->callid) {
1090 return ast_callid_ref(iaxs[callno]->callid);
1095 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1097 if (iaxs[callno]->callid) {
1098 ast_callid_unref(iaxs[callno]->callid);
1100 ast_callid_ref(callid);
1101 iaxs[callno]->callid = callid;
1104 static void iax_pvt_callid_new(int callno)
1106 struct ast_callid *callid = ast_create_callid();
1107 char buffer[AST_CALLID_BUFFER_LENGTH];
1108 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1109 iax_pvt_callid_set(callno, callid);
1110 ast_callid_unref(callid);
1114 * \brief Another container of iax2_pvt structures
1116 * Active IAX2 pvt structs are also stored in this container, if they are a part
1117 * of an active call where we know the remote side's call number. The reason
1118 * for this is that incoming media frames do not contain our call number. So,
1119 * instead of having to iterate the entire iaxs array, we use this container to
1120 * look up calls where the remote side is using a given call number.
1122 static struct ao2_container *iax_peercallno_pvts;
1125 * \brief chan_iax2_pvt structure locks
1127 * These locks are used when accessing a pvt structure in the iaxs array.
1128 * The index used here is the same as used in the iaxs array. It is the
1129 * local call number for the associated pvt struct.
1131 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1134 * * \brief Another container of iax2_pvt structures
1136 * Active IAX2 pvt stucts used during transfering a call are stored here.
1138 static struct ao2_container *iax_transfercallno_pvts;
1140 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1141 but keeps the division between trunked and non-trunked better. */
1142 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1144 /* Debug routines... */
1145 static struct sockaddr_in debugaddr;
1147 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1150 (sin && debugaddr.sin_addr.s_addr &&
1151 (!ntohs(debugaddr.sin_port) ||
1152 debugaddr.sin_port == sin->sin_port) &&
1153 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1155 iax_showframe(f, fhi, rx, sin, datalen);
1158 iax_showframe(f, fhi, rx, sin, datalen);
1164 static void iax_debug_output(const char *data)
1167 ast_verbose("%s", data);
1170 static void iax_error_output(const char *data)
1172 ast_log(LOG_WARNING, "%s", data);
1175 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1180 va_start(args, fmt);
1181 vsnprintf(buf, sizeof(buf), fmt, args);
1184 ast_log(LOG_ERROR, "%s", buf);
1187 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1192 va_start(args, fmt);
1193 vsnprintf(buf, sizeof(buf), fmt, args);
1196 ast_log(LOG_WARNING, "%s", buf);
1199 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1204 va_start(args, fmt);
1205 vsnprintf(buf, sizeof(buf), fmt, args);
1208 ast_verbose("%s", buf);
1211 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1212 static int expire_registry(const void *data);
1213 static int iax2_answer(struct ast_channel *c);
1214 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1215 static int iax2_devicestate(const char *data);
1216 static int iax2_digit_begin(struct ast_channel *c, char digit);
1217 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1218 static int iax2_do_register(struct iax2_registry *reg);
1219 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1220 static int iax2_hangup(struct ast_channel *c);
1221 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1222 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1223 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1224 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1225 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1226 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1227 static int iax2_sendtext(struct ast_channel *c, const char *text);
1228 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1229 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1230 static int iax2_transfer(struct ast_channel *c, const char *dest);
1231 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1232 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1234 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1235 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1236 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1237 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1238 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1239 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1240 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1241 static struct ast_frame *iax2_read(struct ast_channel *c);
1242 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1243 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1244 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1245 static void *iax2_dup_variable_datastore(void *);
1246 static void prune_peers(void);
1247 static void prune_users(void);
1248 static void iax2_free_variable_datastore(void *);
1250 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1251 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1252 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1253 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1254 static void build_rand_pad(unsigned char *buf, ssize_t len);
1255 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1256 static int replace_callno(const void *obj);
1257 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry);
1258 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1259 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *message);
1261 /* BUGBUG The IAX2 channel driver needs its own native bridge technology. */
1262 static struct ast_channel_tech iax2_tech = {
1264 .description = tdesc,
1265 .properties = AST_CHAN_TP_WANTSJITTER,
1266 .requester = iax2_request,
1267 .devicestate = iax2_devicestate,
1268 .send_digit_begin = iax2_digit_begin,
1269 .send_digit_end = iax2_digit_end,
1270 .send_text = iax2_sendtext,
1271 .send_image = iax2_sendimage,
1272 .send_html = iax2_sendhtml,
1274 .hangup = iax2_hangup,
1275 .answer = iax2_answer,
1277 .write = iax2_write,
1278 .write_video = iax2_write,
1279 .indicate = iax2_indicate,
1280 .setoption = iax2_setoption,
1281 .queryoption = iax2_queryoption,
1282 .bridge = iax2_bridge,
1283 .transfer = iax2_transfer,
1284 .fixup = iax2_fixup,
1285 .func_channel_read = acf_channel_read,
1290 * \brief Obtain the owner channel lock if the owner exists.
1292 * \param callno IAX2 call id.
1294 * \note Assumes the iaxsl[callno] lock is already obtained.
1297 * IMPORTANT NOTE!!! Any time this function is used, even if
1298 * iaxs[callno] was valid before calling it, it may no longer be
1299 * valid after calling it. This function may unlock and lock
1300 * the mutex associated with this callno, meaning that another
1301 * thread may grab it and destroy the call.
1305 static void iax2_lock_owner(int callno)
1308 if (!iaxs[callno] || !iaxs[callno]->owner) {
1309 /* There is no owner lock to get. */
1312 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1313 /* We got the lock */
1316 /* Avoid deadlock by pausing and trying again */
1317 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1321 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_topic *topic, struct stasis_message *msg)
1323 /* The MWI subscriptions exist just so the core knows we care about those
1324 * mailboxes. However, we just grab the events out of the cache when it
1325 * is time to send MWI, since it is only sent with a REGACK. */
1328 static void network_change_stasis_subscribe(void)
1330 if (!network_change_sub) {
1331 network_change_sub = stasis_subscribe(ast_system_topic(),
1332 network_change_stasis_cb, NULL);
1336 static void network_change_stasis_unsubscribe(void)
1338 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1341 static void acl_change_stasis_subscribe(void)
1343 if (!acl_change_sub) {
1344 acl_change_sub = stasis_subscribe(ast_security_topic(),
1345 acl_change_stasis_cb, NULL);
1349 static void acl_change_stasis_unsubscribe(void)
1351 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1354 static int network_change_sched_cb(const void *data)
1356 struct iax2_registry *reg;
1357 network_change_sched_id = -1;
1358 AST_LIST_LOCK(®istrations);
1359 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1360 iax2_do_register(reg);
1362 AST_LIST_UNLOCK(®istrations);
1367 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1368 struct stasis_topic *topic, struct stasis_message *message)
1370 /* This callback is only concerned with network change messages from the system topic. */
1371 if (stasis_message_type(message) != ast_network_change_type()) {
1375 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1376 if (network_change_sched_id == -1) {
1377 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1381 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1382 struct stasis_topic *topic, struct stasis_message *message)
1384 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1388 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1393 /*! \brief Send manager event at call setup to link between Asterisk channel name
1394 and IAX2 call identifiers */
1395 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1397 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1398 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1399 pvt->owner ? ast_channel_name(pvt->owner) : "",
1400 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1403 static const struct ast_datastore_info iax2_variable_datastore_info = {
1404 .type = "IAX2_VARIABLE",
1405 .duplicate = iax2_dup_variable_datastore,
1406 .destroy = iax2_free_variable_datastore,
1409 static void *iax2_dup_variable_datastore(void *old)
1411 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1412 struct ast_var_t *oldvar, *newvar;
1414 newlist = ast_calloc(sizeof(*newlist), 1);
1416 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1420 AST_LIST_HEAD_INIT(newlist);
1421 AST_LIST_LOCK(oldlist);
1422 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1423 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1425 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1427 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1429 AST_LIST_UNLOCK(oldlist);
1433 static void iax2_free_variable_datastore(void *old)
1435 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1436 struct ast_var_t *oldvar;
1438 AST_LIST_LOCK(oldlist);
1439 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1442 AST_LIST_UNLOCK(oldlist);
1443 AST_LIST_HEAD_DESTROY(oldlist);
1448 /* WARNING: insert_idle_thread should only ever be called within the
1449 * context of an iax2_process_thread() thread.
1451 static void insert_idle_thread(struct iax2_thread *thread)
1453 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1454 AST_LIST_LOCK(&dynamic_list);
1455 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1456 AST_LIST_UNLOCK(&dynamic_list);
1458 AST_LIST_LOCK(&idle_list);
1459 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1460 AST_LIST_UNLOCK(&idle_list);
1466 static struct iax2_thread *find_idle_thread(void)
1468 struct iax2_thread *thread = NULL;
1470 /* Pop the head of the idle list off */
1471 AST_LIST_LOCK(&idle_list);
1472 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1473 AST_LIST_UNLOCK(&idle_list);
1475 /* If we popped a thread off the idle list, just return it */
1477 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1481 /* Pop the head of the dynamic list off */
1482 AST_LIST_LOCK(&dynamic_list);
1483 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1484 AST_LIST_UNLOCK(&dynamic_list);
1486 /* If we popped a thread off the dynamic list, just return it */
1488 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1492 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1493 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1496 /* Set default values */
1497 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1498 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1499 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1501 /* Initialize lock and condition */
1502 ast_mutex_init(&thread->lock);
1503 ast_cond_init(&thread->cond, NULL);
1504 ast_mutex_init(&thread->init_lock);
1505 ast_cond_init(&thread->init_cond, NULL);
1506 ast_mutex_lock(&thread->init_lock);
1508 /* Create thread and send it on it's way */
1509 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1510 ast_cond_destroy(&thread->cond);
1511 ast_mutex_destroy(&thread->lock);
1512 ast_mutex_unlock(&thread->init_lock);
1513 ast_cond_destroy(&thread->init_cond);
1514 ast_mutex_destroy(&thread->init_lock);
1519 /* this thread is not processing a full frame (since it is idle),
1520 so ensure that the field for the full frame call number is empty */
1521 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1523 /* Wait for the thread to be ready before returning it to the caller */
1524 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1526 /* Done with init_lock */
1527 ast_mutex_unlock(&thread->init_lock);
1532 #ifdef SCHED_MULTITHREADED
1533 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1535 struct iax2_thread *thread = NULL;
1536 static time_t lasterror;
1539 thread = find_idle_thread();
1541 if (thread != NULL) {
1542 thread->schedfunc = func;
1543 thread->scheddata = data;
1544 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1545 #ifdef DEBUG_SCHED_MULTITHREAD
1546 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1548 signal_condition(&thread->lock, &thread->cond);
1553 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1558 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1561 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1562 ast_sched_cb callback, const void *data)
1564 return ast_sched_replace(id, con, when, callback, data);
1567 static int iax2_sched_add(struct ast_sched_context *con, int when,
1568 ast_sched_cb callback, const void *data)
1570 return ast_sched_add(con, when, callback, data);
1573 static int send_ping(const void *data);
1575 static void __send_ping(const void *data)
1577 int callno = (long) data;
1579 ast_mutex_lock(&iaxsl[callno]);
1582 if (iaxs[callno]->peercallno) {
1583 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1584 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1585 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1589 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1592 ast_mutex_unlock(&iaxsl[callno]);
1595 static int send_ping(const void *data)
1597 int callno = (long) data;
1598 ast_mutex_lock(&iaxsl[callno]);
1599 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1600 iaxs[callno]->pingid = -1;
1602 ast_mutex_unlock(&iaxsl[callno]);
1604 #ifdef SCHED_MULTITHREADED
1605 if (schedule_action(__send_ping, data))
1612 static void encmethods_to_str(int e, struct ast_str **buf)
1614 ast_str_set(buf, 0, "(");
1615 if (e & IAX_ENCRYPT_AES128) {
1616 ast_str_append(buf, 0, "aes128");
1618 if (e & IAX_ENCRYPT_KEYROTATE) {
1619 ast_str_append(buf, 0, ",keyrotate");
1621 if (ast_str_strlen(*buf) > 1) {
1622 ast_str_append(buf, 0, ")");
1624 ast_str_set(buf, 0, "No");
1628 static int get_encrypt_methods(const char *s)
1631 if (!strcasecmp(s, "aes128"))
1632 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1633 else if (ast_true(s))
1634 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1640 static int send_lagrq(const void *data);
1642 static void __send_lagrq(const void *data)
1644 int callno = (long) data;
1646 ast_mutex_lock(&iaxsl[callno]);
1649 if (iaxs[callno]->peercallno) {
1650 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1651 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1652 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1656 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1659 ast_mutex_unlock(&iaxsl[callno]);
1662 static int send_lagrq(const void *data)
1664 int callno = (long) data;
1665 ast_mutex_lock(&iaxsl[callno]);
1666 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1667 iaxs[callno]->lagid = -1;
1669 ast_mutex_unlock(&iaxsl[callno]);
1671 #ifdef SCHED_MULTITHREADED
1672 if (schedule_action(__send_lagrq, data))
1678 static unsigned char compress_subclass(iax2_format subclass)
1682 /* If it's 64 or smaller, just return it */
1683 if (subclass < IAX_FLAG_SC_LOG)
1685 /* Otherwise find its power */
1686 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1687 if (subclass & (1LL << x)) {
1689 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1695 return power | IAX_FLAG_SC_LOG;
1698 static iax2_format uncompress_subclass(unsigned char csub)
1700 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1701 if (csub & IAX_FLAG_SC_LOG) {
1702 /* special case for 'compressed' -1 */
1706 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1712 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1714 struct ast_format_cap *cap;
1715 struct ast_format tmpfmt;
1716 iax2_format format = 0;
1717 if ((cap = ast_format_cap_alloc_nolock())) {
1718 ast_format_clear(&tmpfmt);
1719 ast_format_cap_from_old_bitfield(cap, formats);
1720 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1721 format = ast_format_to_old_bitfield(&tmpfmt);
1722 cap = ast_format_cap_destroy(cap);
1728 static iax2_format iax2_best_codec(iax2_format formats)
1730 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1731 struct ast_format tmpfmt;
1736 ast_format_clear(&tmpfmt);
1737 ast_format_cap_from_old_bitfield(cap, formats);
1738 ast_best_codec(cap, &tmpfmt);
1739 cap = ast_format_cap_destroy(cap);
1740 return ast_format_to_old_bitfield(&tmpfmt);
1743 const char *iax2_getformatname(iax2_format format)
1745 struct ast_format tmpfmt;
1746 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1750 return ast_getformatname(&tmpfmt);
1753 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1755 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1760 ast_format_cap_from_old_bitfield(cap, format);
1761 ast_getformatname_multiple(codec_buf, len, cap);
1762 cap = ast_format_cap_destroy(cap);
1767 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1770 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1775 ast_format_cap_from_old_bitfield(cap, *formats);
1776 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1777 *formats = ast_format_cap_to_old_bitfield(cap);
1778 cap = ast_format_cap_destroy(cap);
1783 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1786 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1790 ast_format_cap_from_old_bitfield(cap, formats);
1791 res = ast_data_add_codecs(root, node_name, cap);
1792 cap = ast_format_cap_destroy(cap);
1797 * \note The only member of the peer passed here guaranteed to be set is the name field
1799 static int peer_hash_cb(const void *obj, const int flags)
1801 const struct iax2_peer *peer = obj;
1802 const char *name = obj;
1804 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1808 * \note The only member of the peer passed here guaranteed to be set is the name field
1810 static int peer_cmp_cb(void *obj, void *arg, int flags)
1812 struct iax2_peer *peer = obj, *peer2 = arg;
1813 const char *name = arg;
1815 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1816 CMP_MATCH | CMP_STOP : 0;
1820 * \note The only member of the user passed here guaranteed to be set is the name field
1822 static int user_hash_cb(const void *obj, const int flags)
1824 const struct iax2_user *user = obj;
1825 const char *name = obj;
1827 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1831 * \note The only member of the user passed here guaranteed to be set is the name field
1833 static int user_cmp_cb(void *obj, void *arg, int flags)
1835 struct iax2_user *user = obj, *user2 = arg;
1836 const char *name = arg;
1838 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1839 CMP_MATCH | CMP_STOP : 0;
1843 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1844 * so do not call it with a pvt lock held.
1846 static struct iax2_peer *find_peer(const char *name, int realtime)
1848 struct iax2_peer *peer = NULL;
1850 peer = ao2_find(peers, name, OBJ_KEY);
1852 /* Now go for realtime if applicable */
1853 if(!peer && realtime)
1854 peer = realtime_peer(name, NULL);
1859 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1865 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1871 static struct iax2_user *find_user(const char *name)
1873 return ao2_find(users, name, OBJ_KEY);
1875 static inline struct iax2_user *user_ref(struct iax2_user *user)
1881 static inline struct iax2_user *user_unref(struct iax2_user *user)
1887 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1889 struct iax2_peer *peer = NULL;
1891 struct ao2_iterator i;
1893 i = ao2_iterator_init(peers, 0);
1894 while ((peer = ao2_iterator_next(&i))) {
1895 struct sockaddr_in peer_addr;
1897 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1899 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1900 (peer_addr.sin_port == sin.sin_port)) {
1901 ast_copy_string(host, peer->name, len);
1908 ao2_iterator_destroy(&i);
1911 peer = realtime_peer(NULL, &sin);
1913 ast_copy_string(host, peer->name, len);
1922 /*!\note Assumes the lock on the pvt is already held, when
1923 * iax2_destroy_helper() is called. */
1924 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1926 /* Decrement AUTHREQ count if needed */
1927 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1928 struct iax2_user *user;
1930 user = ao2_find(users, pvt->username, OBJ_KEY);
1932 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1936 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1938 /* No more pings or lagrq's */
1939 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1940 pvt->pingid = DONT_RESCHEDULE;
1941 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1942 pvt->lagid = DONT_RESCHEDULE;
1943 AST_SCHED_DEL(sched, pvt->autoid);
1944 AST_SCHED_DEL(sched, pvt->authid);
1945 AST_SCHED_DEL(sched, pvt->initid);
1946 AST_SCHED_DEL(sched, pvt->jbid);
1947 AST_SCHED_DEL(sched, pvt->keyrotateid);
1950 static void iax2_frame_free(struct iax_frame *fr)
1952 AST_SCHED_DEL(sched, fr->retrans);
1956 static int scheduled_destroy(const void *vid)
1958 unsigned short callno = PTR_TO_CALLNO(vid);
1959 ast_mutex_lock(&iaxsl[callno]);
1961 ast_debug(1, "Really destroying %d now...\n", callno);
1962 iax2_destroy(callno);
1964 ast_mutex_unlock(&iaxsl[callno]);
1968 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1971 ast_free(s->f.data.ptr);
1976 /*! \brief This function must be called once we are sure the other side has
1977 * given us a call number. All signaling is held here until that point. */
1978 static void send_signaling(struct chan_iax2_pvt *pvt)
1980 struct signaling_queue_entry *s = NULL;
1982 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1983 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1984 free_signaling_queue_entry(s);
1986 pvt->hold_signaling = 0;
1989 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1990 * we have received a destination call number. */
1991 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1993 struct signaling_queue_entry *qe;
1995 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1996 return 1; /* do not queue this frame */
1997 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1998 return -1; /* out of memory */
2001 /* copy ast_frame into our queue entry */
2003 if (qe->f.datalen) {
2004 /* if there is data in this frame copy it over as well */
2005 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2006 free_signaling_queue_entry(qe);
2009 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2011 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2016 static void pvt_destructor(void *obj)
2018 struct chan_iax2_pvt *pvt = obj;
2019 struct iax_frame *cur = NULL;
2020 struct signaling_queue_entry *s = NULL;
2022 ast_mutex_lock(&iaxsl[pvt->callno]);
2024 iax2_destroy_helper(pvt);
2026 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2027 pvt->callno_entry = 0;
2030 ast_set_flag64(pvt, IAX_ALREADYGONE);
2032 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2033 /* Cancel any pending transmissions */
2037 ast_mutex_unlock(&iaxsl[pvt->callno]);
2039 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2040 free_signaling_queue_entry(s);
2044 pvt->reg->callno = 0;
2050 ast_variables_destroy(pvt->vars);
2054 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2055 iax2_frame_free(frame.data);
2058 jb_destroy(pvt->jb);
2059 ast_string_field_free_memory(pvt);
2063 ast_callid_unref(pvt->callid);
2068 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2070 struct chan_iax2_pvt *tmp;
2073 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2077 if (ast_string_field_init(tmp, 32)) {
2089 tmp->keyrotateid = -1;
2091 ast_string_field_set(tmp,exten, "s");
2092 ast_string_field_set(tmp,host, host);
2096 jbconf.max_jitterbuf = maxjitterbuffer;
2097 jbconf.resync_threshold = resyncthreshold;
2098 jbconf.max_contig_interp = maxjitterinterps;
2099 jbconf.target_extra = jittertargetextra;
2100 jb_setconf(tmp->jb,&jbconf);
2102 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2104 tmp->hold_signaling = 1;
2105 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2110 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2112 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2114 size_t afdatalen = new->afdatalen;
2115 memcpy(new, fr, sizeof(*new));
2116 iax_frame_wrap(new, &fr->af);
2117 new->afdatalen = afdatalen;
2120 new->direction = DIRECTION_INGRESS;
2125 /* keep these defined in this order. They are used in find_callno to
2126 * determine whether or not a new call number should be allowed. */
2128 /* do not allow a new call number, only search ones in use for match */
2130 /* search for match first, then allow a new one to be allocated */
2132 /* do not search for match, force a new call number */
2134 /* do not search for match, force a new call number. Signifies call number
2135 * has been calltoken validated */
2136 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2139 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2141 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2142 (cur->addr.sin_port == sin->sin_port)) {
2143 /* This is the main host */
2144 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2145 (check_dcallno ? dcallno == cur->callno : 1) ) {
2146 /* That's us. Be sure we keep track of the peer call number */
2150 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2151 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2152 /* We're transferring */
2153 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2159 static int make_trunk(unsigned short callno, int locked)
2164 if (iaxs[callno]->oseqno) {
2165 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2168 if (callno >= TRUNK_CALL_START) {
2169 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2173 if (get_unused_callno(
2175 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2177 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2181 x = CALLNO_ENTRY_GET_CALLNO(entry);
2182 ast_mutex_lock(&iaxsl[x]);
2185 * \note We delete these before switching the slot, because if
2186 * they fire in the meantime, they will generate a warning.
2188 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2189 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2190 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2191 iaxs[x] = iaxs[callno];
2192 iaxs[x]->callno = x;
2194 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2195 * before assigning the new one */
2196 if (iaxs[x]->callno_entry) {
2199 MIN_REUSE_TIME * 1000,
2201 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2204 iaxs[x]->callno_entry = entry;
2206 iaxs[callno] = NULL;
2207 /* Update the two timers that should have been started */
2208 iaxs[x]->pingid = iax2_sched_add(sched,
2209 ping_time * 1000, send_ping, (void *)(long)x);
2210 iaxs[x]->lagid = iax2_sched_add(sched,
2211 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2214 ast_mutex_unlock(&iaxsl[callno]);
2217 ast_mutex_unlock(&iaxsl[x]);
2219 /* We moved this call from a non-trunked to a trunked call */
2220 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2225 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2227 if (!pvt->transfercallno) {
2228 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2232 ao2_link(iax_transfercallno_pvts, pvt);
2235 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2237 if (!pvt->transfercallno) {
2238 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2242 ao2_unlink(iax_transfercallno_pvts, pvt);
2244 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2246 if (!pvt->peercallno) {
2247 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2251 ao2_link(iax_peercallno_pvts, pvt);
2254 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2256 if (!pvt->peercallno) {
2257 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2261 ao2_unlink(iax_peercallno_pvts, pvt);
2264 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2266 struct addr_range *lim = obj;
2271 static int addr_range_hash_cb(const void *obj, const int flags)
2273 const struct addr_range *lim = obj;
2274 struct sockaddr_in sin;
2275 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2276 return abs((int) sin.sin_addr.s_addr);
2279 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2281 struct addr_range *lim1 = obj, *lim2 = arg;
2282 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2283 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2284 CMP_MATCH | CMP_STOP : 0;
2287 static int peercnt_hash_cb(const void *obj, const int flags)
2289 const struct peercnt *peercnt = obj;
2290 return abs((int) peercnt->addr);
2293 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2295 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2296 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2299 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2301 struct addr_range *addr_range = obj;
2302 struct sockaddr_in *sin = arg;
2303 struct sockaddr_in ha_netmask_sin;
2304 struct sockaddr_in ha_addr_sin;
2306 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2307 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2309 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2310 return CMP_MATCH | CMP_STOP;
2318 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2320 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2322 struct addr_range *addr_range;
2323 struct iax2_peer *peer = NULL;
2324 struct iax2_user *user = NULL;
2325 /* if no username is given, check for guest accounts */
2326 const char *find = S_OR(name, "guest");
2327 int res = 1; /* required by default */
2329 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2330 /* There are only two cases in which calltoken validation is not required.
2331 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2332 * the peer definition has not set the requirecalltoken option.
2333 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2336 /* ----- Case 1 ----- */
2337 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2338 ao2_ref(addr_range, -1);
2342 /* ----- Case 2 ----- */
2343 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2344 calltoken_required = user->calltoken_required;
2345 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2346 calltoken_required = user->calltoken_required;
2347 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2348 calltoken_required = peer->calltoken_required;
2349 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2350 calltoken_required = peer->calltoken_required;
2360 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2361 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2362 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2372 * \brief set peercnt callno limit.
2375 * First looks in custom definitions. If not found, global limit
2376 * is used. Entries marked as reg already have
2377 * a custom limit set by a registration and are not modified.
2379 static void set_peercnt_limit(struct peercnt *peercnt)
2381 uint16_t limit = global_maxcallno;
2382 struct addr_range *addr_range;
2383 struct sockaddr_in sin = {
2384 .sin_addr.s_addr = peercnt->addr,
2388 if (peercnt->reg && peercnt->limit) {
2389 return; /* this peercnt has a custom limit set by a registration */
2392 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2393 limit = addr_range->limit;
2394 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2395 ao2_ref(addr_range, -1);
2398 peercnt->limit = limit;
2403 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2405 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2407 struct peercnt *peercnt = obj;
2409 set_peercnt_limit(peercnt);
2410 ast_debug(1, "Reset limits for peercnts table\n");
2417 * \brief returns match if delme is set.
2419 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2421 struct addr_range *addr_range = obj;
2423 return addr_range->delme ? CMP_MATCH : 0;
2428 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2430 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2432 /* this function turns off and on custom callno limits set by peer registration */
2433 struct peercnt *peercnt;
2434 struct peercnt tmp = {
2437 struct sockaddr_in sin;
2439 ast_sockaddr_to_sin(sockaddr, &sin);
2441 tmp.addr = sin.sin_addr.s_addr;
2443 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2446 peercnt->limit = limit;
2448 set_peercnt_limit(peercnt);
2450 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2451 ao2_ref(peercnt, -1); /* decrement ref from find */
2457 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2459 * \details First searches for the address in the peercnts table. If found
2460 * the current count is incremented. If not found a new peercnt is allocated
2461 * and linked into the peercnts table with a call number count of 1.
2463 static int peercnt_add(struct sockaddr_in *sin)
2465 struct peercnt *peercnt;
2466 unsigned long addr = sin->sin_addr.s_addr;
2468 struct peercnt tmp = {
2472 /* Reasoning for peercnts container lock: Two identical ip addresses
2473 * could be added by different threads at the "same time". Without the container
2474 * lock, both threads could alloc space for the same object and attempt
2475 * to link to table. With the lock, one would create the object and link
2476 * to table while the other would find the already created peercnt object
2477 * rather than creating a new one. */
2479 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2481 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2483 /* create and set defaults */
2484 peercnt->addr = addr;
2485 set_peercnt_limit(peercnt);
2486 /* guarantees it does not go away after unlocking table
2487 * ao2_find automatically adds this */
2488 ao2_link(peercnts, peercnt);
2490 ao2_unlock(peercnts);
2494 /* check to see if the address has hit its callno limit. If not increment cur. */
2495 if (peercnt->limit > peercnt->cur) {
2497 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2498 } else { /* max num call numbers for this peer has been reached! */
2499 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2503 /* clean up locks and ref count */
2504 ao2_unlock(peercnt);
2505 ao2_unlock(peercnts);
2506 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2513 * \brief decrements a peercnts table entry
2515 static void peercnt_remove(struct peercnt *peercnt)
2517 struct sockaddr_in sin = {
2518 .sin_addr.s_addr = peercnt->addr,
2522 * Container locked here since peercnt may be unlinked from
2523 * list. If left unlocked, peercnt_add could try and grab this
2524 * entry from the table and modify it at the "same time" this
2525 * thread attemps to unlink it.
2529 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2530 /* if this was the last connection from the peer remove it from table */
2531 if (peercnt->cur == 0) {
2532 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2534 ao2_unlock(peercnts);
2539 * \brief called by scheduler to decrement object
2541 static int peercnt_remove_cb(const void *obj)
2543 struct peercnt *peercnt = (struct peercnt *) obj;
2545 peercnt_remove(peercnt);
2546 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2553 * \brief decrements peercnts connection count, finds by addr
2555 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2557 struct peercnt *peercnt;
2558 struct peercnt tmp = {
2559 .addr = sin->sin_addr.s_addr,
2562 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2563 peercnt_remove(peercnt);
2564 ao2_ref(peercnt, -1); /* decrement ref from find */
2571 * \brief Create callno_limit entry based on configuration
2573 static void build_callno_limits(struct ast_variable *v)
2575 struct addr_range *addr_range = NULL;
2576 struct addr_range tmp;
2582 for (; v; v = v->next) {
2586 ha = ast_append_ha("permit", v->name, NULL, &error);
2588 /* check for valid config information */
2590 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2592 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2593 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2598 ast_copy_ha(ha, &tmp.ha);
2599 /* find or create the addr_range */
2600 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2601 ao2_lock(addr_range);
2603 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2605 return; /* out of memory */
2608 /* copy over config data into addr_range object */
2609 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2610 ast_free_ha(ha); /* cleanup the tmp ha */
2611 addr_range->limit = limit;
2612 addr_range->delme = 0;
2616 ao2_unlock(addr_range);
2618 ao2_link(callno_limits, addr_range);
2620 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2626 * \brief Create calltoken_ignores entry based on configuration
2628 static int add_calltoken_ignore(const char *addr)
2630 struct addr_range tmp;
2631 struct addr_range *addr_range = NULL;
2632 struct ast_ha *ha = NULL;
2635 if (ast_strlen_zero(addr)) {
2636 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2640 ha = ast_append_ha("permit", addr, NULL, &error);
2642 /* check for valid config information */
2644 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2648 ast_copy_ha(ha, &tmp.ha);
2649 /* find or create the addr_range */
2650 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2651 ao2_lock(addr_range);
2652 addr_range->delme = 0;
2653 ao2_unlock(addr_range);
2654 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2655 /* copy over config data into addr_range object */
2656 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2657 ao2_link(calltoken_ignores, addr_range);
2664 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2669 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2671 struct ao2_iterator i;
2672 struct peercnt *peercnt;
2673 struct sockaddr_in sin;
2678 e->command = "iax2 show callnumber usage";
2680 "Usage: iax2 show callnumber usage [IP address]\n"
2681 " Shows current IP addresses which are consuming iax2 call numbers\n";
2686 if (a->argc < 4 || a->argc > 5)
2687 return CLI_SHOWUSAGE;
2690 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2693 i = ao2_iterator_init(peercnts, 0);
2694 while ((peercnt = ao2_iterator_next(&i))) {
2695 sin.sin_addr.s_addr = peercnt->addr;
2697 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2698 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2699 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2700 ao2_ref(peercnt, -1);
2705 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2707 ao2_ref(peercnt, -1);
2709 ao2_iterator_destroy(&i);
2712 size_t pool_avail = callno_pool.available;
2713 size_t trunk_pool_avail = callno_pool_trunk.available;
2715 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2716 "Non-CallToken Validated Callno Used: %d\n",
2717 global_maxcallno_nonval,
2718 total_nonval_callno_used);
2720 ast_cli(a->fd, "Total Available Callno: %zu\n"
2721 "Regular Callno Available: %zu\n"
2722 "Trunk Callno Available: %zu\n",
2723 pool_avail + trunk_pool_avail,
2726 } else if (a->argc == 5 && !found) {
2727 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2737 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2739 struct call_number_pool *pool = NULL;
2744 case CALLNO_TYPE_NORMAL:
2745 pool = &callno_pool;
2747 case CALLNO_TYPE_TRUNK:
2748 pool = &callno_pool_trunk;
2755 /* If we fail, make sure this has a defined value */
2758 /* We lock here primarily to ensure thread safety of the
2759 * total_nonval_callno_used check and increment */
2760 ast_mutex_lock(&callno_pool_lock);
2762 /* Bail out if we don't have any available call numbers */
2763 if (!pool->available) {
2764 ast_log(LOG_WARNING, "Out of call numbers\n");
2765 ast_mutex_unlock(&callno_pool_lock);
2769 /* Only a certain number of non-validated call numbers should be allocated.
2770 * If there ever is an attack, this separates the calltoken validating users
2771 * from the non-calltoken validating users. */
2772 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2773 ast_log(LOG_WARNING,
2774 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2775 total_nonval_callno_used,
2776 global_maxcallno_nonval);
2777 ast_mutex_unlock(&callno_pool_lock);
2781 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2782 * available call numbers. The array of call numbers begins as an ordered
2783 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2784 * - let's call that x. When a call number is needed we pick a random index
2785 * into the array between 0 and x and use that as our call number. In a
2786 * typical FYD shuffle, we would swap the value that we are extracting with
2787 * the number at x, but in our case we swap and don't touch the value at x
2788 * because it is effectively invisible. We rely on the rest of the IAX2 core
2789 * to return the number to us at some point. Finally, we decrement x by 1
2790 * which establishes our new unused range.
2792 * When numbers are returned to the pool, we put them just past x and bump x
2793 * by 1 so that this number is now available for re-use. */
2795 choice = ast_random() % pool->available;
2797 *entry = pool->numbers[choice];
2798 swap = pool->numbers[pool->available - 1];
2800 pool->numbers[choice] = swap;
2804 CALLNO_ENTRY_SET_VALIDATED(*entry);
2806 total_nonval_callno_used++;
2809 ast_mutex_unlock(&callno_pool_lock);
2814 static int replace_callno(const void *obj)
2816 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2817 struct call_number_pool *pool;
2819 /* We lock here primarily to ensure thread safety of the
2820 * total_nonval_callno_used check and decrement */
2821 ast_mutex_lock(&callno_pool_lock);
2823 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2824 if (total_nonval_callno_used) {
2825 total_nonval_callno_used--;
2828 "Attempted to decrement total non calltoken validated "
2829 "callnumbers below zero. Callno is: %d\n",
2830 CALLNO_ENTRY_GET_CALLNO(entry));
2834 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2835 pool = &callno_pool;
2837 pool = &callno_pool_trunk;
2840 ast_assert(pool->capacity > pool->available);
2842 /* This clears the validated flag */
2843 entry = CALLNO_ENTRY_GET_CALLNO(entry);
2845 pool->numbers[pool->available] = entry;
2848 ast_mutex_unlock(&callno_pool_lock);
2853 static int create_callno_pools(void)
2857 callno_pool.available = callno_pool_trunk.available = 0;
2859 /* We start at 2. 0 and 1 are reserved. */
2860 for (i = 2; i < TRUNK_CALL_START; i++) {
2861 callno_pool.numbers[callno_pool.available] = i;
2862 callno_pool.available++;
2865 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2866 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2867 callno_pool_trunk.available++;
2870 callno_pool.capacity = callno_pool.available;
2871 callno_pool_trunk.capacity = callno_pool_trunk.available;
2873 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2880 * \brief Schedules delayed removal of iax2_pvt call number data
2882 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2883 * avaliable again, and the address from the previous connection must be decremented
2884 * from the peercnts table. This function schedules these operations to take place.
2886 static void sched_delay_remove(struct sockaddr_in *sin, callno_entry entry)
2889 struct peercnt *peercnt;
2890 struct peercnt tmp = {
2891 .addr = sin->sin_addr.s_addr,
2894 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2895 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2896 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2897 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2899 ao2_ref(peercnt, -1);
2905 MIN_REUSE_TIME * 1000,
2907 CALLNO_ENTRY_TO_PTR(entry));
2912 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2914 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2917 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2919 if (frametype != AST_FRAME_IAX) {
2923 case IAX_COMMAND_NEW:
2924 case IAX_COMMAND_REGREQ:
2925 case IAX_COMMAND_FWDOWNL:
2926 case IAX_COMMAND_REGREL:
2928 case IAX_COMMAND_POKE:
2938 * \note Calling this function while holding another pvt lock can cause a deadlock.
2940 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2944 /* this call is calltoken validated as long as it is either NEW_FORCE
2945 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2946 int validated = (new > NEW_ALLOW) ? 1 : 0;
2949 if (new <= NEW_ALLOW) {
2951 struct chan_iax2_pvt *pvt;
2952 struct chan_iax2_pvt tmp_pvt = {
2954 .peercallno = callno,
2955 .transfercallno = callno,
2957 .frames_received = check_dcallno,
2960 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2961 /* this works for finding normal call numbers not involving transfering */
2962 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2963 if (return_locked) {
2964 ast_mutex_lock(&iaxsl[pvt->callno]);
2971 /* this searches for transfer call numbers that might not get caught otherwise */
2972 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2973 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2974 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2975 if (return_locked) {
2976 ast_mutex_lock(&iaxsl[pvt->callno]);
2984 /* This will occur on the first response to a message that we initiated,
2985 * such as a PING. */
2987 ast_mutex_lock(&iaxsl[dcallno]);
2989 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2990 iaxs[dcallno]->peercallno = callno;
2992 store_by_peercallno(iaxs[dcallno]);
2993 if (!res || !return_locked) {
2994 ast_mutex_unlock(&iaxsl[dcallno]);
2999 ast_mutex_unlock(&iaxsl[dcallno]);
3002 if (!res && (new >= NEW_ALLOW)) {
3004 /* It may seem odd that we look through the peer list for a name for
3005 * this *incoming* call. Well, it is weird. However, users don't
3006 * have an IP address/port number that we can match against. So,
3007 * this is just checking for a peer that has that IP/port and
3008 * assuming that we have a user of the same name. This isn't always
3009 * correct, but it will be changed if needed after authentication. */
3010 if (!iax2_getpeername(*sin, host, sizeof(host)))
3011 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
3013 if (peercnt_add(sin)) {
3014 /* This address has hit its callnumber limit. When the limit
3015 * is reached, the connection is not added to the peercnts table.*/
3019 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3020 /* since we ran out of space, remove the peercnt
3021 * entry we added earlier */
3022 peercnt_remove_by_addr(sin);
3023 ast_log(LOG_WARNING, "No more space\n");
3026 x = CALLNO_ENTRY_GET_CALLNO(entry);
3027 ast_mutex_lock(&iaxsl[x]);
3029 iaxs[x] = new_iax(sin, host);
3032 ast_debug(1, "Creating new call structure %d\n", x);
3033 iaxs[x]->callno_entry = entry;
3034 iaxs[x]->sockfd = sockfd;
3035 iaxs[x]->addr.sin_port = sin->sin_port;
3036 iaxs[x]->addr.sin_family = sin->sin_family;
3037 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
3038 iaxs[x]->peercallno = callno;
3039 iaxs[x]->callno = x;
3040 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3041 iaxs[x]->expiry = min_reg_expire;
3042 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3043 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3044 iaxs[x]->amaflags = amaflags;
3045 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3046 ast_string_field_set(iaxs[x], accountcode, accountcode);
3047 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3048 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3049 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3051 if (iaxs[x]->peercallno) {
3052 store_by_peercallno(iaxs[x]);
3055 ast_log(LOG_WARNING, "Out of resources\n");
3056 ast_mutex_unlock(&iaxsl[x]);
3057 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3061 ast_mutex_unlock(&iaxsl[x]);
3067 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3068 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3071 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3073 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3077 * \brief Queue a frame to a call's owning asterisk channel
3079 * \pre This function assumes that iaxsl[callno] is locked when called.
3081 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3082 * was valid before calling it, it may no longer be valid after calling it.
3083 * This function may unlock and lock the mutex associated with this callno,
3084 * meaning that another thread may grab it and destroy the call.
3086 static int iax2_queue_frame(int callno, struct ast_frame *f)
3088 iax2_lock_owner(callno);
3089 if (iaxs[callno] && iaxs[callno]->owner) {
3090 ast_queue_frame(iaxs[callno]->owner, f);
3091 ast_channel_unlock(iaxs[callno]->owner);
3097 * \brief Queue a hold frame on the ast_channel owner
3099 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3100 * is active for the given call number.
3102 * \pre Assumes lock for callno is already held.
3104 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3105 * was valid before calling it, it may no longer be valid after calling it.
3106 * This function may unlock and lock the mutex associated with this callno,
3107 * meaning that another thread may grab it and destroy the call.
3109 static int iax2_queue_hold(int callno, const char *musicclass)
3111 iax2_lock_owner(callno);
3112 if (iaxs[callno] && iaxs[callno]->owner) {
3113 ast_queue_hold(iaxs[callno]->owner, musicclass);
3114 ast_channel_unlock(iaxs[callno]->owner);
3120 * \brief Queue an unhold frame on the ast_channel owner
3122 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3123 * is active for the given call number.
3125 * \pre Assumes lock for callno is already held.
3127 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3128 * was valid before calling it, it may no longer be valid after calling it.
3129 * This function may unlock and lock the mutex associated with this callno,
3130 * meaning that another thread may grab it and destroy the call.
3132 static int iax2_queue_unhold(int callno)
3134 iax2_lock_owner(callno);
3135 if (iaxs[callno] && iaxs[callno]->owner) {
3136 ast_queue_unhold(iaxs[callno]->owner);
3137 ast_channel_unlock(iaxs[callno]->owner);
3143 * \brief Queue a hangup frame on the ast_channel owner
3145 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3146 * is active for the given call number.
3148 * \pre Assumes lock for callno is already held.
3150 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3151 * was valid before calling it, it may no longer be valid after calling it.
3152 * This function may unlock and lock the mutex associated with this callno,
3153 * meaning that another thread may grab it and destroy the call.
3155 static int iax2_queue_hangup(int callno)
3157 iax2_lock_owner(callno);
3158 if (iaxs[callno] && iaxs[callno]->owner) {
3159 ast_queue_hangup(iaxs[callno]->owner);
3160 ast_channel_unlock(iaxs[callno]->owner);
3166 * \note This function assumes that iaxsl[callno] is locked when called.
3168 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3169 * was valid before calling it, it may no longer be valid after calling it.
3170 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3171 * associated with this callno, meaning that another thread may grab it and destroy the call.
3173 static int __do_deliver(void *data)
3175 /* Just deliver the packet by using queueing. This is called by
3176 the IAX thread with the iaxsl lock held. */
3177 struct iax_frame *fr = data;
3179 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3180 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3181 iax2_queue_frame(fr->callno, &fr->af);
3182 /* Free our iax frame */
3183 iax2_frame_free(fr);
3184 /* And don't run again */
3188 static int handle_error(void)
3190 /* XXX Ideally we should figure out why an error occurred and then abort those
3191 rather than continuing to try. Unfortunately, the published interface does
3192 not seem to work XXX */
3194 struct sockaddr_in *sin;
3197 struct sock_extended_err e;
3202 m.msg_controllen = sizeof(e);
3204 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3206 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3208 if (m.msg_controllen) {
3209 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3211 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3213 ast_log(LOG_WARNING, "No address detected??\n");
3215 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3222 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3225 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3228 ast_debug(1, "Received error: %s\n", strerror(errno));
3235 static int send_packet(struct iax_frame *f)
3238 int callno = f->callno;
3240 /* Don't send if there was an error, but return error instead */
3241 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3244 /* Called with iaxsl held */
3246 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3249 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3250 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3252 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3253 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3257 ast_debug(1, "Received error: %s\n", strerror(errno));
3266 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3267 * for the given call number may disappear during its execution.
3269 static int iax2_predestroy(int callno)
3271 struct ast_channel *c = NULL;
3272 struct chan_iax2_pvt *pvt = iaxs[callno];
3277 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3278 iax2_destroy_helper(pvt);
3279 ast_set_flag64(pvt, IAX_ALREADYGONE);
3282 if ((c = pvt->owner)) {
3283 ast_channel_tech_pvt_set(c, NULL);
3284 iax2_queue_hangup(callno);
3286 ast_module_unref(ast_module_info->self);
3292 static void iax2_destroy(int callno)
3294 struct chan_iax2_pvt *pvt = NULL;
3295 struct ast_channel *owner = NULL;
3298 if ((pvt = iaxs[callno])) {
3300 /* iax2_destroy_helper gets called from this function later on. When
3301 * called twice, we get the (previously) familiar FRACK! errors in
3302 * devmode, from the scheduler. An alternative to this approach is to
3303 * reset the scheduler entries to -1 when they're deleted in
3304 * iax2_destroy_helper(). That approach was previously decided to be
3305 * "wrong" because "the memory is going to be deallocated anyway. Why
3306 * should we be resetting those values?" */
3307 iax2_destroy_helper(pvt);
3311 owner = pvt ? pvt->owner : NULL;
3314 if (ast_channel_trylock(owner)) {
3315 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3316 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3322 iaxs[callno] = NULL;
3329 /* If there's an owner, prod it to give up */
3330 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3331 * because we already hold the owner channel lock. */
3332 ast_queue_hangup(owner);
3335 if (pvt->peercallno) {
3336 remove_by_peercallno(pvt);
3339 if (pvt->transfercallno) {
3340 remove_by_transfercallno(pvt);
3350 ast_channel_unlock(owner);
3354 static int update_packet(struct iax_frame *f)
3356 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3357 struct ast_iax2_full_hdr *fh = f->data;
3358 struct ast_frame af;
3360 /* if frame is encrypted. decrypt before updating it. */
3361 if (f->encmethods) {
3362 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3364 /* Mark this as a retransmission */
3365 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3367 f->iseqno = iaxs[f->callno]->iseqno;
3368 fh->iseqno = f->iseqno;
3370 /* Now re-encrypt the frame */
3371 if (f->encmethods) {
3372 /* since this is a retransmit frame, create a new random padding
3373 * before re-encrypting. */
3374 build_rand_pad(f->semirand, sizeof(f->semirand));
3375 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3380 static int attempt_transmit(const void *data);
3381 static void __attempt_transmit(const void *data)
3383 /* Attempt to transmit the frame to the remote peer...
3384 Called without iaxsl held. */
3385 struct iax_frame *f = (struct iax_frame *)data;
3387 int callno = f->callno;
3388 /* Make sure this call is still active */
3390 ast_mutex_lock(&iaxsl[callno]);
3391 if (callno && iaxs[callno]) {
3392 if ((f->retries < 0) /* Already ACK'd */ ||
3393 (f->retries >= max_retries) /* Too many attempts */) {
3394 /* Record an error if we've transmitted too many times */
3395 if (f->retries >= max_retries) {
3397 /* Transfer timeout */
3398 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3399 } else if (f->final) {
3400 iax2_destroy(callno);
3402 if (iaxs[callno]->owner)
3403 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),ast_channel_name(iaxs[f->callno]->owner), f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3404 iaxs[callno]->error = ETIMEDOUT;
3405 if (iaxs[callno]->owner) {
3406 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3408 iax2_queue_frame(callno, &fr); /* XXX */
3409 /* Remember, owner could disappear */
3410 if (iaxs[callno] && iaxs[callno]->owner)
3411 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3413 if (iaxs[callno]->reg) {
3414 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3415 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3416 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3418 iax2_destroy(callno);
3425 /* Update it if it needs it */
3427 /* Attempt transmission */
3430 /* Try again later after 10 times as long */
3432 if (f->retrytime > MAX_RETRY_TIME)
3433 f->retrytime = MAX_RETRY_TIME;
3434 /* Transfer messages max out at one second */
3435 if (f->transfer && (f->retrytime > 1000))
3436 f->retrytime = 1000;
3437 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3440 /* Make sure it gets freed */
3446 /* Don't attempt delivery, just remove it from the queue */
3447 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3448 ast_mutex_unlock(&iaxsl[callno]);
3449 f->retrans = -1; /* this is safe because this is the scheduled function */
3450 /* Free the IAX frame */
3452 } else if (callno) {
3453 ast_mutex_unlock(&iaxsl[callno]);
3457 static int attempt_transmit(const void *data)
3459 #ifdef SCHED_MULTITHREADED
3460 if (schedule_action(__attempt_transmit, data))
3462 __attempt_transmit(data);
3466 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3468 struct iax2_peer *peer = NULL;
3469 struct iax2_user *user = NULL;
3470 static const char * const choices[] = { "all", NULL };
3475 e->command = "iax2 prune realtime";
3477 "Usage: iax2 prune realtime [<peername>|all]\n"
3478 " Prunes object(s) from the cache\n";
3482 cmplt = ast_cli_complete(a->word, choices, a->n);
3484 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3490 return CLI_SHOWUSAGE;
3491 if (!strcmp(a->argv[3], "all")) {
3494 ast_cli(a->fd, "Cache flushed successfully.\n");
3497 peer = find_peer(a->argv[3], 0);
3498 user = find_user(a->argv[3]);
3501 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3502 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3503 expire_registry(peer_ref(peer));
3504 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3506 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3511 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3512 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3513 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3515 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3517 ao2_unlink(users,user);
3521 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3527 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3531 e->command = "iax2 test losspct";
3533 "Usage: iax2 test losspct <percentage>\n"
3534 " For testing, throws away <percentage> percent of incoming packets\n";
3540 return CLI_SHOWUSAGE;
3542 test_losspct = atoi(a->argv[3]);
3548 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3552 e->command = "iax2 test late";
3554 "Usage: iax2 test late <ms>\n"
3555 " For testing, count the next frame as <ms> ms late\n";
3562 return CLI_SHOWUSAGE;
3564 test_late = atoi(a->argv[3]);
3569 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3573 e->command = "iax2 test resync";
3575 "Usage: iax2 test resync <ms>\n"
3576 " For testing, adjust all future frames by <ms> ms\n";
3583 return CLI_SHOWUSAGE;
3585 test_resync = atoi(a->argv[3]);
3590 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3594 e->command = "iax2 test jitter";
3596 "Usage: iax2 test jitter <ms> <pct>\n"
3597 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3598 " percentage of packets. If <pct> is not specified, adds\n"
3599 " jitter to all packets.\n";
3605 if (a->argc < 4 || a->argc > 5)
3606 return CLI_SHOWUSAGE;
3608 test_jit = atoi(a->argv[3]);
3610 test_jitpct = atoi(a->argv[4]);
3614 #endif /* IAXTESTS */
3616 /*! \brief peer_status: Report Peer status in character string */
3617 /* returns 1 if peer is online, -1 if unmonitored */
3618 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3622 if (peer->lastms < 0) {
3623 ast_copy_string(status, "UNREACHABLE", statuslen);
3624 } else if (peer->lastms > peer->maxms) {
3625 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3627 } else if (peer->lastms) {
3628 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3631 ast_copy_string(status, "UNKNOWN", statuslen);
3634 ast_copy_string(status, "Unmonitored", statuslen);
3640 /*! \brief Show one peer in detail */
3641 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3645 struct iax2_peer *peer;
3646 char codec_buf[512];
3647 struct ast_str *encmethods = ast_str_alloca(256);
3648 int x = 0, load_realtime = 0;
3652 e->command = "iax2 show peer";
3654 "Usage: iax2 show peer <name>\n"
3655 " Display details on specific IAX peer\n";
3659 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3664 return CLI_SHOWUSAGE;
3666 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3668 peer = find_peer(a->argv[3], load_realtime);
3670 struct sockaddr_in peer_addr;
3672 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
3674 encmethods_to_str(peer->encmethods, &encmethods);
3675 ast_cli(a->fd, "\n\n");
3676 ast_cli(a->fd, " * Name : %s\n", peer->name);
3677 ast_cli(a->fd, " Description : %s\n", peer->description);
3678 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3679 ast_cli(a->fd, " Context : %s\n", peer->context);
3680 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3681 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3682 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3683 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3684 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3685 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3686 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3687 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3688 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3689 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3690 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
3691 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3692 ast_cli(a->fd, " Username : %s\n", peer->username);
3693 ast_cli(a->fd, " Codecs : ");
3694 iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3695 ast_cli(a->fd, "%s\n", codec_buf);
3697 ast_cli(a->fd, " Codec Order : (");
3698 for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
3699 struct ast_format tmpfmt;
3700 if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
3702 ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
3703 if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
3704 ast_cli(a->fd, "|");
3708 ast_cli(a->fd, "none");
3709 ast_cli(a->fd, ")\n");
3711 ast_cli(a->fd, " Status : ");
3712 peer_status(peer, status, sizeof(status));
3713 ast_cli(a->fd, "%s\n",status);
3714 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");
3715 ast_cli(a->fd, "\n");
3718 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3719 ast_cli(a->fd, "\n");
3725 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3728 struct iax2_peer *peer;
3730 int wordlen = strlen(word);
3731 struct ao2_iterator i;
3733 i = ao2_iterator_init(peers, 0);
3734 while ((peer = ao2_iterator_next(&i))) {
3735 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3736 && (!flags || ast_test_flag64(peer, flags))) {
3737 res = ast_strdup(peer->name);
3743 ao2_iterator_destroy(&i);
3748 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3750 struct iax_frame *cur;
3751 int cnt = 0, dead = 0, final = 0, i = 0;
3755 e->command = "iax2 show stats";