2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
24 * \author Mark Spencer <markster@digium.com>
27 * \arg \ref Config_iax
29 * \ingroup channel_drivers
31 * \todo Implement musicclass settings for IAX2 devices
35 * \li The channel chan_iax uses the configuration file \ref iax.conf
36 * \addtogroup configuration_file
39 /*! \page iax.conf iax.conf
40 * \verbinclude iax.conf.sample
44 <use type="external">crypto</use>
45 <support_level>core</support_level>
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
54 #include <sys/socket.h>
55 #include <netinet/in.h>
56 #include <arpa/inet.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/ip.h>
60 #include <sys/signal.h>
68 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
70 #include "asterisk/lock.h"
71 #include "asterisk/frame.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/module.h"
74 #include "asterisk/pbx.h"
75 #include "asterisk/sched.h"
76 #include "asterisk/io.h"
77 #include "asterisk/config.h"
78 #include "asterisk/cli.h"
79 #include "asterisk/translate.h"
80 #include "asterisk/md5.h"
81 #include "asterisk/cdr.h"
82 #include "asterisk/crypto.h"
83 #include "asterisk/acl.h"
84 #include "asterisk/manager.h"
85 #include "asterisk/callerid.h"
86 #include "asterisk/app.h"
87 #include "asterisk/astdb.h"
88 #include "asterisk/musiconhold.h"
89 #include "asterisk/features.h"
90 #include "asterisk/utils.h"
91 #include "asterisk/causes.h"
92 #include "asterisk/localtime.h"
93 #include "asterisk/dnsmgr.h"
94 #include "asterisk/devicestate.h"
95 #include "asterisk/netsock.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/linkedlists.h"
98 #include "asterisk/event.h"
99 #include "asterisk/astobj2.h"
100 #include "asterisk/timing.h"
101 #include "asterisk/taskprocessor.h"
102 #include "asterisk/test.h"
103 #include "asterisk/data.h"
104 #include "asterisk/netsock2.h"
107 #include "iax2-parser.h"
108 #include "iax2-provision.h"
109 #include "jitterbuf.h"
112 <application name="IAX2Provision" language="en_US">
114 Provision a calling IAXy with a given template.
117 <parameter name="template">
118 <para>If not specified, defaults to <literal>default</literal>.</para>
122 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
123 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
124 or <literal>0</literal> on success.</para>
127 <function name="IAXPEER" language="en_US">
129 Gets IAX peer information.
132 <parameter name="peername" required="true">
134 <enum name="CURRENTCHANNEL">
135 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
136 endpoint of the current channel</para>
140 <parameter name="item">
141 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
144 <para>(default) The IP address.</para>
147 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
149 <enum name="mailbox">
150 <para>The configured mailbox.</para>
152 <enum name="context">
153 <para>The configured context.</para>
156 <para>The epoch time of the next expire.</para>
158 <enum name="dynamic">
159 <para>Is it dynamic? (yes/no).</para>
161 <enum name="callerid_name">
162 <para>The configured Caller ID name.</para>
164 <enum name="callerid_num">
165 <para>The configured Caller ID number.</para>
168 <para>The configured codecs.</para>
170 <enum name="codec[x]">
171 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
172 with <literal>0</literal>)</para>
178 <para>Gets information associated with the specified IAX2 peer.</para>
181 <ref type="function">SIPPEER</ref>
184 <function name="IAXVAR" language="en_US">
186 Sets or retrieves a remote variable.
189 <parameter name="varname" required="true" />
192 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
195 <manager name="IAXpeers" language="en_US">
200 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
205 <manager name="IAXpeerlist" language="en_US">
210 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
213 <para>List all the IAX peers.</para>
216 <manager name="IAXnetstats" language="en_US">
222 <para>Show IAX channels network statistics.</para>
225 <manager name="IAXregistry" language="en_US">
227 Show IAX registrations.
230 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
233 <para>Show IAX registrations.</para>
238 /* Define SCHED_MULTITHREADED to run the scheduler in a special
239 multithreaded mode. */
240 #define SCHED_MULTITHREADED
242 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
243 thread is actually doing. */
244 #define DEBUG_SCHED_MULTITHREAD
248 static int nochecksums = 0;
251 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
252 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
254 #define DEFAULT_THREAD_COUNT 10
255 #define DEFAULT_MAX_THREAD_COUNT 100
256 #define DEFAULT_RETRY_TIME 1000
257 #define MEMORY_SIZE 100
258 #define DEFAULT_DROP 3
260 #define DEBUG_SUPPORT
262 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
264 /* Sample over last 100 units to determine historic jitter */
267 static struct ast_codec_pref prefs;
269 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
272 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
273 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
274 #define MAX_TRUNK_MTU 1240
276 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
277 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
279 #define DEFAULT_CONTEXT "default"
281 static char default_parkinglot[AST_MAX_CONTEXT];
283 static char language[MAX_LANGUAGE] = "";
284 static char regcontext[AST_MAX_CONTEXT] = "";
286 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
287 static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
288 static int network_change_event_sched_id = -1;
290 static int maxauthreq = 3;
291 static int max_retries = 4;
292 static int ping_time = 21;
293 static int lagrq_time = 10;
294 static int maxjitterbuffer=1000;
295 static int resyncthreshold=1000;
296 static int maxjitterinterps=10;
297 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
299 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
301 static int trunkfreq = 20;
302 static int trunkmaxsize = MAX_TRUNKDATA;
304 static int authdebug = 0;
305 static int autokill = 0;
306 static int iaxcompat = 0;
307 static int last_authmethod = 0;
309 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
311 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
318 static int min_reg_expire;
319 static int max_reg_expire;
321 static int srvlookup = 0;
323 static struct ast_timer *timer; /* Timer for trunking */
325 static struct ast_netsock_list *netsock;
326 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
327 static int defaultsockfd = -1;
329 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
332 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
334 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
335 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) & \
336 ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) & \
337 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) & \
338 ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) & \
339 ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) & \
340 ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) & \
341 ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) & \
342 ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
344 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
345 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) & \
346 ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) & \
347 ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
349 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
350 ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
353 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
354 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
355 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
357 /* if a pvt has encryption setup done and is running on the call */
358 #define IAX_CALLENCRYPTED(pvt) \
359 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
361 #define IAX_DEBUGDIGEST(msg, key) do { \
363 char digest[33] = ""; \
368 for (idx = 0; idx < 16; idx++) \
369 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
371 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
374 static struct io_context *io;
375 static struct ast_sched_context *sched;
377 #define DONT_RESCHEDULE -2
379 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
381 static int iaxdebug = 0;
383 static int iaxtrunkdebug = 0;
385 static int test_losspct = 0;
387 static int test_late = 0;
388 static int test_resync = 0;
389 static int test_jit = 0;
390 static int test_jitpct = 0;
391 #endif /* IAXTESTS */
393 static char accountcode[AST_MAX_ACCOUNT_CODE];
394 static char mohinterpret[MAX_MUSICCLASS];
395 static char mohsuggest[MAX_MUSICCLASS];
396 static int amaflags = 0;
398 static int delayreject = 0;
399 static int iax2_encryption = 0;
401 static struct ast_flags64 globalflags = { 0 };
403 static pthread_t netthreadid = AST_PTHREADT_NULL;
406 IAX_STATE_STARTED = (1 << 0),
407 IAX_STATE_AUTHENTICATED = (1 << 1),
408 IAX_STATE_TBD = (1 << 2),
411 struct iax2_context {
412 char context[AST_MAX_CONTEXT];
413 struct iax2_context *next;
417 #define IAX_HASCALLERID (uint64_t)(1 << 0) /*!< CallerID has been specified */
418 #define IAX_DELME (uint64_t)(1 << 1) /*!< Needs to be deleted */
419 #define IAX_TEMPONLY (uint64_t)(1 << 2) /*!< Temporary (realtime) */
420 #define IAX_TRUNK (uint64_t)(1 << 3) /*!< Treat as a trunk */
421 #define IAX_NOTRANSFER (uint64_t)(1 << 4) /*!< Don't native bridge */
422 #define IAX_USEJITTERBUF (uint64_t)(1 << 5) /*!< Use jitter buffer */
423 #define IAX_DYNAMIC (uint64_t)(1 << 6) /*!< dynamic peer */
424 #define IAX_SENDANI (uint64_t)(1 << 7) /*!< Send ANI along with CallerID */
425 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8) /*!< Save Systname on Realtime Updates */
426 #define IAX_ALREADYGONE (uint64_t)(1 << 9) /*!< Already disconnected */
427 #define IAX_PROVISION (uint64_t)(1 << 10) /*!< This is a provisioning request */
428 #define IAX_QUELCH (uint64_t)(1 << 11) /*!< Whether or not we quelch audio */
429 #define IAX_ENCRYPTED (uint64_t)(1 << 12) /*!< Whether we should assume encrypted tx/rx */
430 #define IAX_KEYPOPULATED (uint64_t)(1 << 13) /*!< Whether we have a key populated */
431 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14) /*!< are we willing to let the other guy choose the codec? */
432 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15) /*!< Force old behaviour by turning off prefs */
433 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16) /*!< only consider requested format and ignore capabilities*/
434 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17) /*!< let realtime stay till your reload */
435 #define IAX_RTUPDATE (uint64_t)(1 << 18) /*!< Send a realtime update */
436 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19) /*!< erase me on expire */
437 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20) /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
438 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21) /*!< When using realtime, ignore registration expiration */
439 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22) /*!< Send trunk timestamps */
440 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23) /*!< When doing IAX2 transfers, transfer media only */
441 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
442 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
443 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26) /*!< Allow the FWDOWNL command? */
444 #define IAX_IMMEDIATE (uint64_t)(1 << 27) /*!< Allow immediate off-hook to extension s */
445 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28) /*!< Allow sending of connected line updates */
446 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29) /*!< Allow receiving of connected line updates */
447 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30) /*!< Forces call encryption, if encryption not possible hangup */
448 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31) /*!< Turn on and off caller id shrinking */
449 static int global_rtautoclear = 120;
451 static int reload_config(int forced_reload);
454 * \brief Call token validation settings.
456 enum calltoken_peer_enum {
457 /*! \brief Default calltoken required unless the ip is in the ignorelist */
458 CALLTOKEN_DEFAULT = 0,
459 /*! \brief Require call token validation. */
461 /*! \brief Require call token validation after a successful registration
462 * using call token validation occurs. */
464 /*! \brief Do not require call token validation. */
469 AST_DECLARE_STRING_FIELDS(
470 AST_STRING_FIELD(name);
471 AST_STRING_FIELD(secret);
472 AST_STRING_FIELD(dbsecret);
473 AST_STRING_FIELD(accountcode);
474 AST_STRING_FIELD(mohinterpret);
475 AST_STRING_FIELD(mohsuggest);
476 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
477 AST_STRING_FIELD(language);
478 AST_STRING_FIELD(cid_num);
479 AST_STRING_FIELD(cid_name);
480 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
488 iax2_format capability;
489 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
490 int curauthreq; /*!< Current number of outstanding AUTHREQs */
491 struct ast_codec_pref prefs;
492 struct ast_acl_list *acl;
493 struct iax2_context *contexts;
494 struct ast_variable *vars;
495 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
499 AST_DECLARE_STRING_FIELDS(
500 AST_STRING_FIELD(name);
501 AST_STRING_FIELD(username);
502 AST_STRING_FIELD(description); /*!< Description of the peer */
503 AST_STRING_FIELD(secret);
504 AST_STRING_FIELD(dbsecret);
505 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
507 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
508 AST_STRING_FIELD(context); /*!< For transfers only */
509 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
510 AST_STRING_FIELD(mailbox); /*!< Mailbox */
511 AST_STRING_FIELD(mohinterpret);
512 AST_STRING_FIELD(mohsuggest);
513 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
514 /* Suggested caller id if registering */
515 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
516 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
517 AST_STRING_FIELD(zonetag); /*!< Time Zone */
518 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
520 struct ast_codec_pref prefs;
521 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
522 struct ast_sockaddr addr;
524 int sockfd; /*!< Socket to use for transmission */
529 /* Dynamic Registration fields */
530 struct sockaddr_in defaddr; /*!< Default address if there is one */
531 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
532 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
534 int expire; /*!< Schedule entry for expiry */
535 int expiry; /*!< How soon to expire */
536 iax2_format capability; /*!< Capability */
539 int callno; /*!< Call number of POKE request */
540 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
541 int lastms; /*!< How long last response took (in ms), or -1 for no response */
542 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
544 int pokefreqok; /*!< How often to check if the host is up */
545 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
546 int historicms; /*!< How long recent average responses took */
547 int smoothing; /*!< Sample over how many units to determine historic ms */
548 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
550 struct ast_event_sub *mwi_event_sub;
552 struct ast_acl_list *acl;
553 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
556 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
558 struct iax2_trunk_peer {
561 struct sockaddr_in addr;
562 struct timeval txtrunktime; /*!< Transmit trunktime */
563 struct timeval rxtrunktime; /*!< Receive trunktime */
564 struct timeval lasttxtime; /*!< Last transmitted trunktime */
565 struct timeval trunkact; /*!< Last trunk activity */
566 unsigned int lastsent; /*!< Last sent time */
567 /* Trunk data and length */
568 unsigned char *trunkdata;
569 unsigned int trunkdatalen;
570 unsigned int trunkdataalloc;
574 AST_LIST_ENTRY(iax2_trunk_peer) list;
577 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
579 struct iax_firmware {
580 AST_LIST_ENTRY(iax_firmware) list;
584 struct ast_iax2_firmware_header *fwh;
589 REG_STATE_UNREGISTERED = 0,
592 REG_STATE_REGISTERED,
598 enum iax_transfer_state {
603 TRANSFER_PASSTHROUGH,
607 TRANSFER_MPASSTHROUGH,
612 struct iax2_registry {
613 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
615 char secret[80]; /*!< Password or key name in []'s */
616 int expire; /*!< Sched ID of expiration */
617 int refresh; /*!< How often to refresh */
618 enum iax_reg_state regstate;
619 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
620 int callno; /*!< Associated call number if applicable */
621 struct sockaddr_in us; /*!< Who the server thinks we are */
622 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
623 AST_LIST_ENTRY(iax2_registry) entry;
626 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
628 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
629 #define MIN_RETRY_TIME 100
630 #define MAX_RETRY_TIME 10000
632 #define MAX_JITTER_BUFFER 50
633 #define MIN_JITTER_BUFFER 10
635 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
637 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
639 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
640 #define TS_GAP_FOR_JB_RESYNC 5000
642 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
643 #define MARK_IAX_SUBCLASS_TX 0x8000
645 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
646 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
647 static int iaxdynamicthreadcount = 0;
648 static int iaxdynamicthreadnum = 0;
649 static int iaxactivethreadcount = 0;
663 struct chan_iax2_pvt {
664 /*! Socket to send/receive on for this call */
666 /*! ast_callid bound to dialog */
667 struct ast_callid *callid;
668 /*! Last received voice format */
669 iax2_format voiceformat;
670 /*! Last received video format */
671 iax2_format videoformat;
672 /*! Last sent voice format */
673 iax2_format svoiceformat;
674 /*! Last sent video format */
675 iax2_format svideoformat;
676 /*! What we are capable of sending */
677 iax2_format capability;
678 /*! Last received timestamp */
680 /*! Last sent timestamp - never send the same timestamp twice in a single call */
681 unsigned int lastsent;
682 /*! Timestamp of the last video frame sent */
683 unsigned int lastvsent;
684 /*! Next outgoing timestamp if everything is good */
685 unsigned int nextpred;
686 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
687 int first_iax_message;
688 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
689 int last_iax_message;
690 /*! True if the last voice we transmitted was not silence/CNG */
691 unsigned int notsilenttx:1;
693 unsigned int pingtime;
694 /*! Max time for initial response */
697 struct sockaddr_in addr;
698 /*! Actual used codec preferences */
699 struct ast_codec_pref prefs;
700 /*! Requested codec preferences */
701 struct ast_codec_pref rprefs;
702 /*! Our call number */
703 unsigned short callno;
704 /*! Our callno_entry entry */
705 struct callno_entry *callno_entry;
707 unsigned short peercallno;
708 /*! Negotiated format, this is only used to remember what format was
709 chosen for an unauthenticated call so that the channel can get
710 created later using the right format */
711 iax2_format chosenformat;
712 /*! Peer selected format */
713 iax2_format peerformat;
714 /*! Peer capability */
715 iax2_format peercapability;
716 /*! timeval that we base our transmission on */
717 struct timeval offset;
718 /*! timeval that we base our delivery on */
719 struct timeval rxcore;
720 /*! The jitterbuffer */
722 /*! active jb read scheduler id */
726 /*! Error, as discovered by the manager */
728 /*! Owner if we have one */
729 struct ast_channel *owner;
730 /*! What's our state? */
731 struct ast_flags state;
732 /*! Expiry (optional) */
734 /*! Next outgoing sequence number */
735 unsigned char oseqno;
736 /*! Next sequence number they have not yet acknowledged */
737 unsigned char rseqno;
738 /*! Next incoming sequence number */
739 unsigned char iseqno;
740 /*! Last incoming sequence number we have acknowledged */
741 unsigned char aseqno;
743 AST_DECLARE_STRING_FIELDS(
745 AST_STRING_FIELD(peer);
746 /*! Default Context */
747 AST_STRING_FIELD(context);
748 /*! Caller ID if available */
749 AST_STRING_FIELD(cid_num);
750 AST_STRING_FIELD(cid_name);
751 /*! Hidden Caller ID (i.e. ANI) if appropriate */
752 AST_STRING_FIELD(ani);
754 AST_STRING_FIELD(dnid);
756 AST_STRING_FIELD(rdnis);
757 /*! Requested Extension */
758 AST_STRING_FIELD(exten);
759 /*! Expected Username */
760 AST_STRING_FIELD(username);
761 /*! Expected Secret */
762 AST_STRING_FIELD(secret);
764 AST_STRING_FIELD(challenge);
765 /*! Public keys permitted keys for incoming authentication */
766 AST_STRING_FIELD(inkeys);
767 /*! Private key for outgoing authentication */
768 AST_STRING_FIELD(outkey);
769 /*! Preferred language */
770 AST_STRING_FIELD(language);
771 /*! Hostname/peername for naming purposes */
772 AST_STRING_FIELD(host);
774 AST_STRING_FIELD(dproot);
775 AST_STRING_FIELD(accountcode);
776 AST_STRING_FIELD(mohinterpret);
777 AST_STRING_FIELD(mohsuggest);
778 /*! received OSP token */
779 AST_STRING_FIELD(osptoken);
780 /*! Default parkinglot */
781 AST_STRING_FIELD(parkinglot);
783 /*! AUTHREJ all AUTHREP frames */
785 /*! permitted authentication methods */
787 /*! permitted encryption methods */
789 /*! Encryption AES-128 Key */
790 ast_aes_encrypt_key ecx;
791 /*! Decryption AES-128 Key corresponding to ecx */
792 ast_aes_decrypt_key mydcx;
793 /*! Decryption AES-128 Key used to decrypt peer frames */
794 ast_aes_decrypt_key dcx;
795 /*! scheduler id associated with iax_key_rotate
796 * for encrypted calls*/
798 /*! 32 bytes of semi-random data */
799 unsigned char semirand[32];
800 /*! Associated registry */
801 struct iax2_registry *reg;
802 /*! Associated peer for poking */
803 struct iax2_peer *peerpoke;
808 /*! Transferring status */
809 enum iax_transfer_state transferring;
810 /*! Transfer identifier */
812 /*! Who we are IAX transferring to */
813 struct sockaddr_in transfer;
814 /*! What's the new call number for the transfer */
815 unsigned short transfercallno;
816 /*! Transfer encrypt AES-128 Key */
817 ast_aes_encrypt_key tdcx;
819 /*! Status of knowledge of peer ADSI capability */
822 /*! Who we are bridged to */
823 unsigned short bridgecallno;
825 int pingid; /*!< Transmit PING request */
826 int lagid; /*!< Retransmit lag request */
827 int autoid; /*!< Auto hangup for Dialplan requestor */
828 int authid; /*!< Authentication rejection ID */
829 int authfail; /*!< Reason to report failure */
830 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
835 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
836 /*! variables inherited from the user definition */
837 struct ast_variable *vars;
838 /*! variables transmitted in a NEW packet */
839 struct ast_variable *iaxvars;
840 /*! last received remote rr */
841 struct iax_rr remote_rr;
842 /*! Current base time: (just for stats) */
844 /*! Dropped frame count: (just for stats) */
846 /*! received frame count: (just for stats) */
848 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
849 unsigned char calltoken_ie_len;
850 /*! hold all signaling frames from the pbx thread until we have a destination callno */
852 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
853 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
856 struct signaling_queue_entry {
858 AST_LIST_ENTRY(signaling_queue_entry) next;
861 /*! table of available call numbers */
862 static struct ao2_container *callno_pool;
864 /*! table of available trunk call numbers */
865 static struct ao2_container *callno_pool_trunk;
867 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
870 * \brief a list of frames that may need to be retransmitted
872 * \note The contents of this list do not need to be explicitly destroyed
873 * on module unload. This is because all active calls are destroyed, and
874 * all frames in this queue will get destroyed as a part of that process.
876 * \note Contents protected by the iaxsl[] locks
878 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
880 static struct ast_taskprocessor *transmit_processor;
882 static int randomcalltokendata;
884 static const time_t MAX_CALLTOKEN_DELAY = 10;
887 * This module will get much higher performance when doing a lot of
888 * user and peer lookups if the number of buckets is increased from 1.
889 * However, to maintain old behavior for Asterisk 1.4, these are set to
890 * 1 by default. When using multiple buckets, search order through these
891 * containers is considered random, so you will not be able to depend on
892 * the order the entires are specified in iax.conf for matching order. */
894 #define MAX_PEER_BUCKETS 17
896 #define MAX_PEER_BUCKETS 563
898 static struct ao2_container *peers;
900 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
901 static struct ao2_container *users;
903 /*! Table containing peercnt objects for every ip address consuming a callno */
904 static struct ao2_container *peercnts;
906 /*! Table containing custom callno limit rules for a range of ip addresses. */
907 static struct ao2_container *callno_limits;
909 /*! Table containing ip addresses not requiring calltoken validation */
910 static struct ao2_container *calltoken_ignores;
912 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
914 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
916 static uint16_t global_maxcallno;
918 /*! Total num of call numbers allowed to be allocated without calltoken validation */
919 static uint16_t global_maxcallno_nonval;
921 static uint16_t total_nonval_callno_used = 0;
923 /*! peer connection private, keeps track of all the call numbers
924 * consumed by a single ip address */
926 /*! ip address consuming call numbers */
928 /*! Number of call numbers currently used by this ip address */
930 /*! Max call numbers allowed for this ip address */
932 /*! Specifies whether limit is set by a registration or not, if so normal
933 * limit setting rules do not apply to this address. */
937 /*! used by both callno_limits and calltoken_ignores containers */
939 /*! ip address range for custom callno limit rule */
941 /*! callno limit for this ip address range, only used in callno_limits container */
943 /*! delete me marker for reloads */
947 struct callno_entry {
948 /*! callno used for this entry */
950 /*! was this callno calltoken validated or not */
951 unsigned char validated;
954 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
957 /*! Extension exists */
958 CACHE_FLAG_EXISTS = (1 << 0),
959 /*! Extension is nonexistent */
960 CACHE_FLAG_NONEXISTENT = (1 << 1),
961 /*! Extension can exist */
962 CACHE_FLAG_CANEXIST = (1 << 2),
963 /*! Waiting to hear back response */
964 CACHE_FLAG_PENDING = (1 << 3),
966 CACHE_FLAG_TIMEOUT = (1 << 4),
967 /*! Request transmitted */
968 CACHE_FLAG_TRANSMITTED = (1 << 5),
970 CACHE_FLAG_UNKNOWN = (1 << 6),
972 CACHE_FLAG_MATCHMORE = (1 << 7),
975 struct iax2_dpcache {
976 char peercontext[AST_MAX_CONTEXT];
977 char exten[AST_MAX_EXTENSION];
979 struct timeval expiry;
981 unsigned short callno;
983 AST_LIST_ENTRY(iax2_dpcache) cache_list;
984 AST_LIST_ENTRY(iax2_dpcache) peer_list;
987 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
989 static void reg_source_db(struct iax2_peer *p);
990 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
991 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
993 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
994 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
995 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
997 enum iax2_thread_iostate {
1000 IAX_IOSTATE_PROCESSING,
1001 IAX_IOSTATE_SCHEDREADY,
1004 enum iax2_thread_type {
1005 IAX_THREAD_TYPE_POOL,
1006 IAX_THREAD_TYPE_DYNAMIC,
1009 struct iax2_pkt_buf {
1010 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1012 unsigned char buf[1];
1015 struct iax2_thread {
1016 AST_LIST_ENTRY(iax2_thread) list;
1017 enum iax2_thread_type type;
1018 enum iax2_thread_iostate iostate;
1019 #ifdef SCHED_MULTITHREADED
1020 void (*schedfunc)(const void *);
1021 const void *scheddata;
1023 #ifdef DEBUG_SCHED_MULTITHREAD
1029 struct sockaddr_in iosin;
1030 unsigned char readbuf[4096];
1038 ast_mutex_t init_lock;
1039 ast_cond_t init_cond;
1040 /*! if this thread is processing a full frame,
1041 some information about that frame will be stored
1042 here, so we can avoid dispatching any more full
1043 frames for that callno to other threads */
1045 unsigned short callno;
1046 struct sockaddr_in sin;
1050 /*! Queued up full frames for processing. If more full frames arrive for
1051 * a call which this thread is already processing a full frame for, they
1052 * are queued up here. */
1053 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1058 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1059 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1060 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1062 static void *iax2_process_thread(void *data);
1063 static void iax2_destroy(int callno);
1065 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1067 ast_mutex_lock(lock);
1068 ast_cond_signal(cond);
1069 ast_mutex_unlock(lock);
1073 * \brief an array of iax2 pvt structures
1075 * The container for active chan_iax2_pvt structures is implemented as an
1076 * array for extremely quick direct access to the correct pvt structure
1077 * based on the local call number. The local call number is used as the
1078 * index into the array where the associated pvt structure is stored.
1080 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
1082 static struct ast_callid *iax_pvt_callid_get(int callno)
1084 if (iaxs[callno]->callid) {
1085 return ast_callid_ref(iaxs[callno]->callid);
1090 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1092 if (iaxs[callno]->callid) {
1093 ast_callid_unref(iaxs[callno]->callid);
1095 ast_callid_ref(callid);
1096 iaxs[callno]->callid = callid;
1099 static void iax_pvt_callid_new(int callno)
1101 struct ast_callid *callid = ast_create_callid();
1102 char buffer[AST_CALLID_BUFFER_LENGTH];
1103 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1104 ast_log(LOG_NOTICE, "iax_pvt_callid_new created and set %s\n", buffer);
1105 iax_pvt_callid_set(callno, callid);
1106 ast_callid_unref(callid);
1110 * \brief Another container of iax2_pvt structures
1112 * Active IAX2 pvt structs are also stored in this container, if they are a part
1113 * of an active call where we know the remote side's call number. The reason
1114 * for this is that incoming media frames do not contain our call number. So,
1115 * instead of having to iterate the entire iaxs array, we use this container to
1116 * look up calls where the remote side is using a given call number.
1118 static struct ao2_container *iax_peercallno_pvts;
1121 * \brief chan_iax2_pvt structure locks
1123 * These locks are used when accessing a pvt structure in the iaxs array.
1124 * The index used here is the same as used in the iaxs array. It is the
1125 * local call number for the associated pvt struct.
1127 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1130 * * \brief Another container of iax2_pvt structures
1132 * Active IAX2 pvt stucts used during transfering a call are stored here.
1134 static struct ao2_container *iax_transfercallno_pvts;
1136 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1137 but keeps the division between trunked and non-trunked better. */
1138 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
1140 /* Debug routines... */
1141 static struct sockaddr_in debugaddr;
1143 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1146 (sin && debugaddr.sin_addr.s_addr &&
1147 (!ntohs(debugaddr.sin_port) ||
1148 debugaddr.sin_port == sin->sin_port) &&
1149 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1151 iax_showframe(f, fhi, rx, sin, datalen);
1154 iax_showframe(f, fhi, rx, sin, datalen);
1160 static void iax_debug_output(const char *data)
1163 ast_verbose("%s", data);
1166 static void iax_error_output(const char *data)
1168 ast_log(LOG_WARNING, "%s", data);
1171 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1176 va_start(args, fmt);
1177 vsnprintf(buf, sizeof(buf), fmt, args);
1180 ast_log(LOG_ERROR, "%s", buf);
1183 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1188 va_start(args, fmt);
1189 vsnprintf(buf, sizeof(buf), fmt, args);
1192 ast_log(LOG_WARNING, "%s", buf);
1195 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1200 va_start(args, fmt);
1201 vsnprintf(buf, sizeof(buf), fmt, args);
1204 ast_verbose("%s", buf);
1207 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);
1208 static int expire_registry(const void *data);
1209 static int iax2_answer(struct ast_channel *c);
1210 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1211 static int iax2_devicestate(const char *data);
1212 static int iax2_digit_begin(struct ast_channel *c, char digit);
1213 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1214 static int iax2_do_register(struct iax2_registry *reg);
1215 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1216 static int iax2_hangup(struct ast_channel *c);
1217 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1218 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1219 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1220 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1221 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1222 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1223 static int iax2_sendtext(struct ast_channel *c, const char *text);
1224 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1225 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1226 static int iax2_transfer(struct ast_channel *c, const char *dest);
1227 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1228 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1230 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1231 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1232 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1233 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1234 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1235 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1236 static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1237 static struct ast_frame *iax2_read(struct ast_channel *c);
1238 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1239 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1240 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1241 static void *iax2_dup_variable_datastore(void *);
1242 static void prune_peers(void);
1243 static void prune_users(void);
1244 static void iax2_free_variable_datastore(void *);
1246 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1247 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1248 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1249 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1250 static void build_rand_pad(unsigned char *buf, ssize_t len);
1251 static struct callno_entry *get_unused_callno(int trunk, int validated);
1252 static int replace_callno(const void *obj);
1253 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1254 static void network_change_event_cb(const struct ast_event *, void *);
1255 static void acl_change_event_cb(const struct ast_event *, void *);
1257 static struct ast_channel_tech iax2_tech = {
1259 .description = tdesc,
1260 .properties = AST_CHAN_TP_WANTSJITTER,
1261 .requester = iax2_request,
1262 .devicestate = iax2_devicestate,
1263 .send_digit_begin = iax2_digit_begin,
1264 .send_digit_end = iax2_digit_end,
1265 .send_text = iax2_sendtext,
1266 .send_image = iax2_sendimage,
1267 .send_html = iax2_sendhtml,
1269 .hangup = iax2_hangup,
1270 .answer = iax2_answer,
1272 .write = iax2_write,
1273 .write_video = iax2_write,
1274 .indicate = iax2_indicate,
1275 .setoption = iax2_setoption,
1276 .queryoption = iax2_queryoption,
1277 .bridge = iax2_bridge,
1278 .transfer = iax2_transfer,
1279 .fixup = iax2_fixup,
1280 .func_channel_read = acf_channel_read,
1285 * \brief Obtain the owner channel lock if the owner exists.
1287 * \param callno IAX2 call id.
1289 * \note Assumes the iaxsl[callno] lock is already obtained.
1292 * IMPORTANT NOTE!!! Any time this function is used, even if
1293 * iaxs[callno] was valid before calling it, it may no longer be
1294 * valid after calling it. This function may unlock and lock
1295 * the mutex associated with this callno, meaning that another
1296 * thread may grab it and destroy the call.
1300 static void iax2_lock_owner(int callno)
1303 if (!iaxs[callno] || !iaxs[callno]->owner) {
1304 /* There is no owner lock to get. */
1307 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1308 /* We got the lock */
1311 /* Avoid deadlock by pausing and trying again */
1312 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1316 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1318 /* The MWI subscriptions exist just so the core knows we care about those
1319 * mailboxes. However, we just grab the events out of the cache when it
1320 * is time to send MWI, since it is only sent with a REGACK. */
1323 static void network_change_event_subscribe(void)
1325 if (!network_change_event_subscription) {
1326 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1327 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1331 static void network_change_event_unsubscribe(void)
1333 if (network_change_event_subscription) {
1334 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1338 static void acl_change_event_subscribe(void)
1340 if (!acl_change_event_subscription) {
1341 acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1342 acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
1346 static void acl_change_event_unsubscribe(void)
1348 if (acl_change_event_subscription) {
1349 acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1353 static int network_change_event_sched_cb(const void *data)
1355 struct iax2_registry *reg;
1356 network_change_event_sched_id = -1;
1357 AST_LIST_LOCK(®istrations);
1358 AST_LIST_TRAVERSE(®istrations, reg, entry) {
1359 iax2_do_register(reg);
1361 AST_LIST_UNLOCK(®istrations);
1366 static void network_change_event_cb(const struct ast_event *event, void *userdata)
1368 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1369 if (network_change_event_sched_id == -1) {
1370 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1375 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
1377 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1382 /*! \brief Send manager event at call setup to link between Asterisk channel name
1383 and IAX2 call identifiers */
1384 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1386 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1387 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1388 pvt->owner ? ast_channel_name(pvt->owner) : "",
1389 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1392 static const struct ast_datastore_info iax2_variable_datastore_info = {
1393 .type = "IAX2_VARIABLE",
1394 .duplicate = iax2_dup_variable_datastore,
1395 .destroy = iax2_free_variable_datastore,
1398 static void *iax2_dup_variable_datastore(void *old)
1400 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1401 struct ast_var_t *oldvar, *newvar;
1403 newlist = ast_calloc(sizeof(*newlist), 1);
1405 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1409 AST_LIST_HEAD_INIT(newlist);
1410 AST_LIST_LOCK(oldlist);
1411 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1412 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1414 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1416 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1418 AST_LIST_UNLOCK(oldlist);
1422 static void iax2_free_variable_datastore(void *old)
1424 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1425 struct ast_var_t *oldvar;
1427 AST_LIST_LOCK(oldlist);
1428 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1431 AST_LIST_UNLOCK(oldlist);
1432 AST_LIST_HEAD_DESTROY(oldlist);
1437 /* WARNING: insert_idle_thread should only ever be called within the
1438 * context of an iax2_process_thread() thread.
1440 static void insert_idle_thread(struct iax2_thread *thread)
1442 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1443 AST_LIST_LOCK(&dynamic_list);
1444 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1445 AST_LIST_UNLOCK(&dynamic_list);
1447 AST_LIST_LOCK(&idle_list);
1448 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1449 AST_LIST_UNLOCK(&idle_list);
1455 static struct iax2_thread *find_idle_thread(void)
1457 struct iax2_thread *thread = NULL;
1459 /* Pop the head of the idle list off */
1460 AST_LIST_LOCK(&idle_list);
1461 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1462 AST_LIST_UNLOCK(&idle_list);
1464 /* If we popped a thread off the idle list, just return it */
1466 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1470 /* Pop the head of the dynamic list off */
1471 AST_LIST_LOCK(&dynamic_list);
1472 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1473 AST_LIST_UNLOCK(&dynamic_list);
1475 /* If we popped a thread off the dynamic list, just return it */
1477 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1481 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1482 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1485 /* Set default values */
1486 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1487 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1488 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1490 /* Initialize lock and condition */
1491 ast_mutex_init(&thread->lock);
1492 ast_cond_init(&thread->cond, NULL);
1493 ast_mutex_init(&thread->init_lock);
1494 ast_cond_init(&thread->init_cond, NULL);
1495 ast_mutex_lock(&thread->init_lock);
1497 /* Create thread and send it on it's way */
1498 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1499 ast_cond_destroy(&thread->cond);
1500 ast_mutex_destroy(&thread->lock);
1501 ast_mutex_unlock(&thread->init_lock);
1502 ast_cond_destroy(&thread->init_cond);
1503 ast_mutex_destroy(&thread->init_lock);
1508 /* this thread is not processing a full frame (since it is idle),
1509 so ensure that the field for the full frame call number is empty */
1510 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1512 /* Wait for the thread to be ready before returning it to the caller */
1513 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1515 /* Done with init_lock */
1516 ast_mutex_unlock(&thread->init_lock);
1521 #ifdef SCHED_MULTITHREADED
1522 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1524 struct iax2_thread *thread = NULL;
1525 static time_t lasterror;
1528 thread = find_idle_thread();
1530 if (thread != NULL) {
1531 thread->schedfunc = func;
1532 thread->scheddata = data;
1533 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1534 #ifdef DEBUG_SCHED_MULTITHREAD
1535 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1537 signal_condition(&thread->lock, &thread->cond);
1542 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1547 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1550 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1551 ast_sched_cb callback, const void *data)
1553 return ast_sched_replace(id, con, when, callback, data);
1556 static int iax2_sched_add(struct ast_sched_context *con, int when,
1557 ast_sched_cb callback, const void *data)
1559 return ast_sched_add(con, when, callback, data);
1562 static int send_ping(const void *data);
1564 static void __send_ping(const void *data)
1566 int callno = (long) data;
1568 ast_mutex_lock(&iaxsl[callno]);
1571 if (iaxs[callno]->peercallno) {
1572 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1573 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1574 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1578 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1581 ast_mutex_unlock(&iaxsl[callno]);
1584 static int send_ping(const void *data)
1586 int callno = (long) data;
1587 ast_mutex_lock(&iaxsl[callno]);
1588 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1589 iaxs[callno]->pingid = -1;
1591 ast_mutex_unlock(&iaxsl[callno]);
1593 #ifdef SCHED_MULTITHREADED
1594 if (schedule_action(__send_ping, data))
1601 static void encmethods_to_str(int e, struct ast_str *buf)
1603 ast_str_set(&buf, 0, "(");
1604 if (e & IAX_ENCRYPT_AES128) {
1605 ast_str_append(&buf, 0, "aes128");
1607 if (e & IAX_ENCRYPT_KEYROTATE) {
1608 ast_str_append(&buf, 0, ",keyrotate");
1610 if (ast_str_strlen(buf) > 1) {
1611 ast_str_append(&buf, 0, ")");
1613 ast_str_set(&buf, 0, "No");
1617 static int get_encrypt_methods(const char *s)
1620 if (!strcasecmp(s, "aes128"))
1621 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1622 else if (ast_true(s))
1623 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1629 static int send_lagrq(const void *data);
1631 static void __send_lagrq(const void *data)
1633 int callno = (long) data;
1635 ast_mutex_lock(&iaxsl[callno]);
1638 if (iaxs[callno]->peercallno) {
1639 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1640 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1641 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1645 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1648 ast_mutex_unlock(&iaxsl[callno]);
1651 static int send_lagrq(const void *data)
1653 int callno = (long) data;
1654 ast_mutex_lock(&iaxsl[callno]);
1655 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1656 iaxs[callno]->lagid = -1;
1658 ast_mutex_unlock(&iaxsl[callno]);
1660 #ifdef SCHED_MULTITHREADED
1661 if (schedule_action(__send_lagrq, data))
1667 static unsigned char compress_subclass(iax2_format subclass)
1671 /* If it's 64 or smaller, just return it */
1672 if (subclass < IAX_FLAG_SC_LOG)
1674 /* Otherwise find its power */
1675 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1676 if (subclass & (1LL << x)) {
1678 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1684 return power | IAX_FLAG_SC_LOG;
1687 static iax2_format uncompress_subclass(unsigned char csub)
1689 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1690 if (csub & IAX_FLAG_SC_LOG) {
1691 /* special case for 'compressed' -1 */
1695 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1701 static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1703 struct ast_format_cap *cap;
1704 struct ast_format tmpfmt;
1705 iax2_format format = 0;
1706 if ((cap = ast_format_cap_alloc_nolock())) {
1707 ast_format_clear(&tmpfmt);
1708 ast_format_cap_from_old_bitfield(cap, formats);
1709 ast_codec_choose(pref, cap, find_best, &tmpfmt);
1710 format = ast_format_to_old_bitfield(&tmpfmt);
1711 cap = ast_format_cap_destroy(cap);
1717 static iax2_format iax2_best_codec(iax2_format formats)
1719 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1720 struct ast_format tmpfmt;
1725 ast_format_clear(&tmpfmt);
1726 ast_format_cap_from_old_bitfield(cap, formats);
1727 ast_best_codec(cap, &tmpfmt);
1728 cap = ast_format_cap_destroy(cap);
1729 return ast_format_to_old_bitfield(&tmpfmt);
1732 const char *iax2_getformatname(iax2_format format)
1734 struct ast_format tmpfmt;
1735 if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1739 return ast_getformatname(&tmpfmt);
1742 static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1744 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1749 ast_format_cap_from_old_bitfield(cap, format);
1750 ast_getformatname_multiple(codec_buf, len, cap);
1751 cap = ast_format_cap_destroy(cap);
1756 static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1759 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1764 ast_format_cap_from_old_bitfield(cap, *formats);
1765 res = ast_parse_allow_disallow(pref, cap, list, allowing);
1766 *formats = ast_format_cap_to_old_bitfield(cap);
1767 cap = ast_format_cap_destroy(cap);
1772 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1775 struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1779 ast_format_cap_from_old_bitfield(cap, formats);
1780 res = ast_data_add_codecs(root, node_name, cap);
1781 cap = ast_format_cap_destroy(cap);
1786 * \note The only member of the peer passed here guaranteed to be set is the name field
1788 static int peer_hash_cb(const void *obj, const int flags)
1790 const struct iax2_peer *peer = obj;
1791 const char *name = obj;
1793 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1797 * \note The only member of the peer passed here guaranteed to be set is the name field
1799 static int peer_cmp_cb(void *obj, void *arg, int flags)
1801 struct iax2_peer *peer = obj, *peer2 = arg;
1802 const char *name = arg;
1804 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1805 CMP_MATCH | CMP_STOP : 0;
1809 * \note The only member of the user passed here guaranteed to be set is the name field
1811 static int user_hash_cb(const void *obj, const int flags)
1813 const struct iax2_user *user = obj;
1814 const char *name = obj;
1816 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1820 * \note The only member of the user passed here guaranteed to be set is the name field
1822 static int user_cmp_cb(void *obj, void *arg, int flags)
1824 struct iax2_user *user = obj, *user2 = arg;
1825 const char *name = arg;
1827 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1828 CMP_MATCH | CMP_STOP : 0;
1832 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1833 * so do not call it with a pvt lock held.
1835 static struct iax2_peer *find_peer(const char *name, int realtime)
1837 struct iax2_peer *peer = NULL;
1839 peer = ao2_find(peers, name, OBJ_KEY);
1841 /* Now go for realtime if applicable */
1842 if(!peer && realtime)
1843 peer = realtime_peer(name, NULL);
1848 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1854 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1860 static struct iax2_user *find_user(const char *name)
1862 return ao2_find(users, name, OBJ_KEY);
1864 static inline struct iax2_user *user_ref(struct iax2_user *user)
1870 static inline struct iax2_user *user_unref(struct iax2_user *user)
1876 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1878 struct iax2_peer *peer = NULL;
1880 struct ao2_iterator i;
1882 i = ao2_iterator_init(peers, 0);
1883 while ((peer = ao2_iterator_next(&i))) {
1884 struct sockaddr_in peer_addr;
1886 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1888 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1889 (peer_addr.sin_port == sin.sin_port)) {
1890 ast_copy_string(host, peer->name, len);
1897 ao2_iterator_destroy(&i);
1900 peer = realtime_peer(NULL, &sin);
1902 ast_copy_string(host, peer->name, len);
1911 /*!\note Assumes the lock on the pvt is already held, when
1912 * iax2_destroy_helper() is called. */
1913 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1915 /* Decrement AUTHREQ count if needed */
1916 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1917 struct iax2_user *user;
1919 user = ao2_find(users, pvt->username, OBJ_KEY);
1921 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1925 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1927 /* No more pings or lagrq's */
1928 AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1929 pvt->pingid = DONT_RESCHEDULE;
1930 AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1931 pvt->lagid = DONT_RESCHEDULE;
1932 AST_SCHED_DEL(sched, pvt->autoid);
1933 AST_SCHED_DEL(sched, pvt->authid);
1934 AST_SCHED_DEL(sched, pvt->initid);
1935 AST_SCHED_DEL(sched, pvt->jbid);
1936 AST_SCHED_DEL(sched, pvt->keyrotateid);
1939 static void iax2_frame_free(struct iax_frame *fr)
1941 AST_SCHED_DEL(sched, fr->retrans);
1945 static int scheduled_destroy(const void *vid)
1947 unsigned short callno = PTR_TO_CALLNO(vid);
1948 ast_mutex_lock(&iaxsl[callno]);
1950 ast_debug(1, "Really destroying %d now...\n", callno);
1951 iax2_destroy(callno);
1953 ast_mutex_unlock(&iaxsl[callno]);
1957 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1960 ast_free(s->f.data.ptr);
1965 /*! \brief This function must be called once we are sure the other side has
1966 * given us a call number. All signaling is held here until that point. */
1967 static void send_signaling(struct chan_iax2_pvt *pvt)
1969 struct signaling_queue_entry *s = NULL;
1971 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1972 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1973 free_signaling_queue_entry(s);
1975 pvt->hold_signaling = 0;
1978 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1979 * we have received a destination call number. */
1980 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1982 struct signaling_queue_entry *qe;
1984 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1985 return 1; /* do not queue this frame */
1986 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1987 return -1; /* out of memory */
1990 /* copy ast_frame into our queue entry */
1992 if (qe->f.datalen) {
1993 /* if there is data in this frame copy it over as well */
1994 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1995 free_signaling_queue_entry(qe);
1998 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2000 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2005 static void pvt_destructor(void *obj)
2007 struct chan_iax2_pvt *pvt = obj;
2008 struct iax_frame *cur = NULL;
2009 struct signaling_queue_entry *s = NULL;
2011 ast_mutex_lock(&iaxsl[pvt->callno]);
2013 iax2_destroy_helper(pvt);
2015 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2016 pvt->callno_entry = NULL;
2019 ast_set_flag64(pvt, IAX_ALREADYGONE);
2021 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2022 /* Cancel any pending transmissions */
2026 ast_mutex_unlock(&iaxsl[pvt->callno]);
2028 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2029 free_signaling_queue_entry(s);
2033 pvt->reg->callno = 0;
2039 ast_variables_destroy(pvt->vars);
2043 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2044 iax2_frame_free(frame.data);
2047 jb_destroy(pvt->jb);
2048 ast_string_field_free_memory(pvt);
2052 ast_callid_unref(pvt->callid);
2057 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2059 struct chan_iax2_pvt *tmp;
2062 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2066 if (ast_string_field_init(tmp, 32)) {
2078 tmp->keyrotateid = -1;
2080 ast_string_field_set(tmp,exten, "s");
2081 ast_string_field_set(tmp,host, host);
2085 jbconf.max_jitterbuf = maxjitterbuffer;
2086 jbconf.resync_threshold = resyncthreshold;
2087 jbconf.max_contig_interp = maxjitterinterps;
2088 jbconf.target_extra = jittertargetextra;
2089 jb_setconf(tmp->jb,&jbconf);
2091 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2093 tmp->hold_signaling = 1;
2094 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2099 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2101 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2103 size_t afdatalen = new->afdatalen;
2104 memcpy(new, fr, sizeof(*new));
2105 iax_frame_wrap(new, &fr->af);
2106 new->afdatalen = afdatalen;
2109 new->direction = DIRECTION_INGRESS;
2114 /* keep these defined in this order. They are used in find_callno to
2115 * determine whether or not a new call number should be allowed. */
2117 /* do not allow a new call number, only search ones in use for match */
2119 /* search for match first, then allow a new one to be allocated */
2121 /* do not search for match, force a new call number */
2123 /* do not search for match, force a new call number. Signifies call number
2124 * has been calltoken validated */
2125 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2128 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2130 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2131 (cur->addr.sin_port == sin->sin_port)) {
2132 /* This is the main host */
2133 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2134 (check_dcallno ? dcallno == cur->callno : 1) ) {
2135 /* That's us. Be sure we keep track of the peer call number */
2139 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2140 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2141 /* We're transferring */
2142 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2148 static int make_trunk(unsigned short callno, int locked)
2152 struct callno_entry *callno_entry;
2153 if (iaxs[callno]->oseqno) {
2154 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2157 if (callno & TRUNK_CALL_START) {
2158 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2162 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2163 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2167 x = callno_entry->callno;
2168 ast_mutex_lock(&iaxsl[x]);
2171 * \note We delete these before switching the slot, because if
2172 * they fire in the meantime, they will generate a warning.
2174 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2175 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2176 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2177 iaxs[x] = iaxs[callno];
2178 iaxs[x]->callno = x;
2180 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2181 * before assigning the new one */
2182 if (iaxs[x]->callno_entry) {
2183 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2185 iaxs[x]->callno_entry = callno_entry;
2187 iaxs[callno] = NULL;
2188 /* Update the two timers that should have been started */
2189 iaxs[x]->pingid = iax2_sched_add(sched,
2190 ping_time * 1000, send_ping, (void *)(long)x);
2191 iaxs[x]->lagid = iax2_sched_add(sched,
2192 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2195 ast_mutex_unlock(&iaxsl[callno]);
2198 ast_mutex_unlock(&iaxsl[x]);
2200 /* We moved this call from a non-trunked to a trunked call */
2201 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2206 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2208 if (!pvt->transfercallno) {
2209 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2213 ao2_link(iax_transfercallno_pvts, pvt);
2216 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2218 if (!pvt->transfercallno) {
2219 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2223 ao2_unlink(iax_transfercallno_pvts, pvt);
2225 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2227 if (!pvt->peercallno) {
2228 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2232 ao2_link(iax_peercallno_pvts, pvt);
2235 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2237 if (!pvt->peercallno) {
2238 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2242 ao2_unlink(iax_peercallno_pvts, pvt);
2245 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2247 struct addr_range *lim = obj;
2252 static int addr_range_hash_cb(const void *obj, const int flags)
2254 const struct addr_range *lim = obj;
2255 struct sockaddr_in sin;
2256 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2257 return abs((int) sin.sin_addr.s_addr);
2260 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2262 struct addr_range *lim1 = obj, *lim2 = arg;
2263 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2264 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2265 CMP_MATCH | CMP_STOP : 0;
2268 static int peercnt_hash_cb(const void *obj, const int flags)
2270 const struct peercnt *peercnt = obj;
2271 return abs((int) peercnt->addr);
2274 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2276 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2277 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2280 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2282 struct addr_range *addr_range = obj;
2283 struct sockaddr_in *sin = arg;
2284 struct sockaddr_in ha_netmask_sin;
2285 struct sockaddr_in ha_addr_sin;
2287 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2288 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2290 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2291 return CMP_MATCH | CMP_STOP;
2299 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2301 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2303 struct addr_range *addr_range;
2304 struct iax2_peer *peer = NULL;
2305 struct iax2_user *user = NULL;
2306 /* if no username is given, check for guest accounts */
2307 const char *find = S_OR(name, "guest");
2308 int res = 1; /* required by default */
2310 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2311 /* There are only two cases in which calltoken validation is not required.
2312 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2313 * the peer definition has not set the requirecalltoken option.
2314 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2317 /* ----- Case 1 ----- */
2318 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2319 ao2_ref(addr_range, -1);
2323 /* ----- Case 2 ----- */
2324 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2325 calltoken_required = user->calltoken_required;
2326 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2327 calltoken_required = user->calltoken_required;
2328 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2329 calltoken_required = peer->calltoken_required;
2330 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2331 calltoken_required = peer->calltoken_required;
2341 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);
2342 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2343 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2353 * \brief set peercnt callno limit.
2356 * First looks in custom definitions. If not found, global limit
2357 * is used. Entries marked as reg already have
2358 * a custom limit set by a registration and are not modified.
2360 static void set_peercnt_limit(struct peercnt *peercnt)
2362 uint16_t limit = global_maxcallno;
2363 struct addr_range *addr_range;
2364 struct sockaddr_in sin = {
2365 .sin_addr.s_addr = peercnt->addr,
2369 if (peercnt->reg && peercnt->limit) {
2370 return; /* this peercnt has a custom limit set by a registration */
2373 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2374 limit = addr_range->limit;
2375 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2376 ao2_ref(addr_range, -1);
2379 peercnt->limit = limit;
2384 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2386 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2388 struct peercnt *peercnt = obj;
2390 set_peercnt_limit(peercnt);
2391 ast_debug(1, "Reset limits for peercnts table\n");
2398 * \brief returns match if delme is set.
2400 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2402 struct addr_range *addr_range = obj;
2404 return addr_range->delme ? CMP_MATCH : 0;
2409 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2411 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2413 /* this function turns off and on custom callno limits set by peer registration */
2414 struct peercnt *peercnt;
2415 struct peercnt tmp = {
2418 struct sockaddr_in sin;
2420 ast_sockaddr_to_sin(sockaddr, &sin);
2422 tmp.addr = sin.sin_addr.s_addr;
2424 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2427 peercnt->limit = limit;
2429 set_peercnt_limit(peercnt);
2431 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2432 ao2_ref(peercnt, -1); /* decrement ref from find */
2438 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2440 * \details First searches for the address in the peercnts table. If found
2441 * the current count is incremented. If not found a new peercnt is allocated
2442 * and linked into the peercnts table with a call number count of 1.
2444 static int peercnt_add(struct sockaddr_in *sin)
2446 struct peercnt *peercnt;
2447 unsigned long addr = sin->sin_addr.s_addr;
2449 struct peercnt tmp = {
2453 /* Reasoning for peercnts container lock: Two identical ip addresses
2454 * could be added by different threads at the "same time". Without the container
2455 * lock, both threads could alloc space for the same object and attempt
2456 * to link to table. With the lock, one would create the object and link
2457 * to table while the other would find the already created peercnt object
2458 * rather than creating a new one. */
2460 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2462 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2464 /* create and set defaults */
2465 peercnt->addr = addr;
2466 set_peercnt_limit(peercnt);
2467 /* guarantees it does not go away after unlocking table
2468 * ao2_find automatically adds this */
2469 ao2_link(peercnts, peercnt);
2471 ao2_unlock(peercnts);
2475 /* check to see if the address has hit its callno limit. If not increment cur. */
2476 if (peercnt->limit > peercnt->cur) {
2478 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2479 } else { /* max num call numbers for this peer has been reached! */
2480 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2484 /* clean up locks and ref count */
2485 ao2_unlock(peercnt);
2486 ao2_unlock(peercnts);
2487 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2494 * \brief decrements a peercnts table entry
2496 static void peercnt_remove(struct peercnt *peercnt)
2498 struct sockaddr_in sin = {
2499 .sin_addr.s_addr = peercnt->addr,
2503 * Container locked here since peercnt may be unlinked from
2504 * list. If left unlocked, peercnt_add could try and grab this
2505 * entry from the table and modify it at the "same time" this
2506 * thread attemps to unlink it.
2510 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2511 /* if this was the last connection from the peer remove it from table */
2512 if (peercnt->cur == 0) {
2513 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2515 ao2_unlock(peercnts);
2520 * \brief called by scheduler to decrement object
2522 static int peercnt_remove_cb(const void *obj)
2524 struct peercnt *peercnt = (struct peercnt *) obj;
2526 peercnt_remove(peercnt);
2527 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2534 * \brief decrements peercnts connection count, finds by addr
2536 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2538 struct peercnt *peercnt;
2539 struct peercnt tmp = {
2540 .addr = sin->sin_addr.s_addr,
2543 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2544 peercnt_remove(peercnt);
2545 ao2_ref(peercnt, -1); /* decrement ref from find */
2552 * \brief Create callno_limit entry based on configuration
2554 static void build_callno_limits(struct ast_variable *v)
2556 struct addr_range *addr_range = NULL;
2557 struct addr_range tmp;
2563 for (; v; v = v->next) {
2567 ha = ast_append_ha("permit", v->name, NULL, &error);
2569 /* check for valid config information */
2571 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2573 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2574 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2579 ast_copy_ha(ha, &tmp.ha);
2580 /* find or create the addr_range */
2581 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2582 ao2_lock(addr_range);
2584 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2586 return; /* out of memory */
2589 /* copy over config data into addr_range object */
2590 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2591 ast_free_ha(ha); /* cleanup the tmp ha */
2592 addr_range->limit = limit;
2593 addr_range->delme = 0;
2597 ao2_unlock(addr_range);
2599 ao2_link(callno_limits, addr_range);
2601 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2607 * \brief Create calltoken_ignores entry based on configuration
2609 static int add_calltoken_ignore(const char *addr)
2611 struct addr_range tmp;
2612 struct addr_range *addr_range = NULL;
2613 struct ast_ha *ha = NULL;
2616 if (ast_strlen_zero(addr)) {
2617 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2621 ha = ast_append_ha("permit", addr, NULL, &error);
2623 /* check for valid config information */
2625 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2629 ast_copy_ha(ha, &tmp.ha);
2630 /* find or create the addr_range */
2631 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2632 ao2_lock(addr_range);
2633 addr_range->delme = 0;
2634 ao2_unlock(addr_range);
2635 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2636 /* copy over config data into addr_range object */
2637 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2638 ao2_link(calltoken_ignores, addr_range);
2645 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2650 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2652 struct ao2_iterator i;
2653 struct peercnt *peercnt;
2654 struct sockaddr_in sin;
2659 e->command = "iax2 show callnumber usage";
2661 "Usage: iax2 show callnumber usage [IP address]\n"
2662 " Shows current IP addresses which are consuming iax2 call numbers\n";
2667 if (a->argc < 4 || a->argc > 5)
2668 return CLI_SHOWUSAGE;
2671 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2674 i = ao2_iterator_init(peercnts, 0);
2675 while ((peercnt = ao2_iterator_next(&i))) {
2676 sin.sin_addr.s_addr = peercnt->addr;
2678 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2679 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2680 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2681 ao2_ref(peercnt, -1);
2686 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2688 ao2_ref(peercnt, -1);
2690 ao2_iterator_destroy(&i);
2693 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2694 "Non-CallToken Validated Callno Used: %d\n",
2695 global_maxcallno_nonval,
2696 total_nonval_callno_used);
2698 ast_cli(a->fd, "Total Available Callno: %d\n"
2699 "Regular Callno Available: %d\n"
2700 "Trunk Callno Available: %d\n",
2701 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2702 ao2_container_count(callno_pool),
2703 ao2_container_count(callno_pool_trunk));
2704 } else if (a->argc == 5 && !found) {
2705 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2715 static struct callno_entry *get_unused_callno(int trunk, int validated)
2717 struct callno_entry *callno_entry = NULL;
2718 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2719 ast_log(LOG_WARNING, "Out of CallNumbers\n");
2720 /* Minor optimization for the extreme case. */
2724 /* the callno_pool container is locked here primarily to ensure thread
2725 * safety of the total_nonval_callno_used check and increment */
2726 ao2_lock(callno_pool);
2728 /* only a certain number of nonvalidated call numbers should be allocated.
2729 * If there ever is an attack, this separates the calltoken validating
2730 * users from the non calltoken validating users. */
2731 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2732 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2733 ao2_unlock(callno_pool);
2737 /* unlink the object from the container, taking over ownership
2738 * of the reference the container had to the object */
2739 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2742 callno_entry->validated = validated;
2744 total_nonval_callno_used++;
2748 ao2_unlock(callno_pool);
2749 return callno_entry;
2752 static int replace_callno(const void *obj)
2754 struct callno_entry *callno_entry = (struct callno_entry *) obj;
2756 /* the callno_pool container is locked here primarily to ensure thread
2757 * safety of the total_nonval_callno_used check and decrement */
2758 ao2_lock(callno_pool);
2760 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2761 total_nonval_callno_used--;
2762 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2763 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2766 if (callno_entry->callno < TRUNK_CALL_START) {
2767 ao2_link(callno_pool, callno_entry);
2769 ao2_link(callno_pool_trunk, callno_entry);
2771 ao2_ref(callno_entry, -1); /* only container ref remains */
2773 ao2_unlock(callno_pool);
2777 static int callno_hash(const void *obj, const int flags)
2779 return abs(ast_random());
2782 static int create_callno_pools(void)
2786 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2790 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2794 /* start at 2, 0 and 1 are reserved */
2795 for (i = 2; i <= IAX_MAX_CALLS; i++) {
2796 struct callno_entry *callno_entry;
2798 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2802 callno_entry->callno = i;
2804 if (i < TRUNK_CALL_START) {
2805 ao2_link(callno_pool, callno_entry);
2807 ao2_link(callno_pool_trunk, callno_entry);
2810 ao2_ref(callno_entry, -1);
2818 * \brief Schedules delayed removal of iax2_pvt call number data
2820 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2821 * avaliable again, and the address from the previous connection must be decremented
2822 * from the peercnts table. This function schedules these operations to take place.
2824 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2827 struct peercnt *peercnt;
2828 struct peercnt tmp = {
2829 .addr = sin->sin_addr.s_addr,
2832 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2833 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
2834 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2835 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2837 ao2_ref(peercnt, -1);
2841 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2846 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
2848 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2851 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2853 if (frametype != AST_FRAME_IAX) {
2857 case IAX_COMMAND_NEW:
2858 case IAX_COMMAND_REGREQ:
2859 case IAX_COMMAND_FWDOWNL:
2860 case IAX_COMMAND_REGREL:
2862 case IAX_COMMAND_POKE:
2872 * \note Calling this function while holding another pvt lock can cause a deadlock.
2874 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2878 /* this call is calltoken validated as long as it is either NEW_FORCE
2879 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2880 int validated = (new > NEW_ALLOW) ? 1 : 0;
2883 if (new <= NEW_ALLOW) {
2885 struct chan_iax2_pvt *pvt;
2886 struct chan_iax2_pvt tmp_pvt = {
2888 .peercallno = callno,
2889 .transfercallno = callno,
2891 .frames_received = check_dcallno,
2894 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2895 /* this works for finding normal call numbers not involving transfering */
2896 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2897 if (return_locked) {
2898 ast_mutex_lock(&iaxsl[pvt->callno]);
2905 /* this searches for transfer call numbers that might not get caught otherwise */
2906 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2907 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2908 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2909 if (return_locked) {
2910 ast_mutex_lock(&iaxsl[pvt->callno]);
2918 /* This will occur on the first response to a message that we initiated,
2919 * such as a PING. */
2921 ast_mutex_lock(&iaxsl[dcallno]);
2923 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2924 iaxs[dcallno]->peercallno = callno;
2926 store_by_peercallno(iaxs[dcallno]);
2927 if (!res || !return_locked) {
2928 ast_mutex_unlock(&iaxsl[dcallno]);
2933 ast_mutex_unlock(&iaxsl[dcallno]);
2936 if (!res && (new >= NEW_ALLOW)) {
2937 struct callno_entry *callno_entry;
2938 /* It may seem odd that we look through the peer list for a name for
2939 * this *incoming* call. Well, it is weird. However, users don't
2940 * have an IP address/port number that we can match against. So,
2941 * this is just checking for a peer that has that IP/port and
2942 * assuming that we have a user of the same name. This isn't always
2943 * correct, but it will be changed if needed after authentication. */
2944 if (!iax2_getpeername(*sin, host, sizeof(host)))
2945 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2947 if (peercnt_add(sin)) {
2948 /* This address has hit its callnumber limit. When the limit
2949 * is reached, the connection is not added to the peercnts table.*/
2953 if (!(callno_entry = get_unused_callno(0, validated))) {
2954 /* since we ran out of space, remove the peercnt
2955 * entry we added earlier */
2956 peercnt_remove_by_addr(sin);
2957 ast_log(LOG_WARNING, "No more space\n");
2960 x = callno_entry->callno;
2961 ast_mutex_lock(&iaxsl[x]);
2963 iaxs[x] = new_iax(sin, host);
2966 ast_debug(1, "Creating new call structure %d\n", x);
2967 iaxs[x]->callno_entry = callno_entry;
2968 iaxs[x]->sockfd = sockfd;
2969 iaxs[x]->addr.sin_port = sin->sin_port;
2970 iaxs[x]->addr.sin_family = sin->sin_family;
2971 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2972 iaxs[x]->peercallno = callno;
2973 iaxs[x]->callno = x;
2974 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2975 iaxs[x]->expiry = min_reg_expire;
2976 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2977 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2978 iaxs[x]->amaflags = amaflags;
2979 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2980 ast_string_field_set(iaxs[x], accountcode, accountcode);
2981 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2982 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2983 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2985 if (iaxs[x]->peercallno) {
2986 store_by_peercallno(iaxs[x]);
2989 ast_log(LOG_WARNING, "Out of resources\n");
2990 ast_mutex_unlock(&iaxsl[x]);
2991 replace_callno(callno_entry);
2995 ast_mutex_unlock(&iaxsl[x]);
3001 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3002 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
3005 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
3007 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
3011 * \brief Queue a frame to a call's owning asterisk channel
3013 * \pre This function assumes that iaxsl[callno] is locked when called.
3015 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3016 * was valid before calling it, it may no longer be valid after calling it.
3017 * This function may unlock and lock the mutex associated with this callno,
3018 * meaning that another thread may grab it and destroy the call.
3020 static int iax2_queue_frame(int callno, struct ast_frame *f)
3022 iax2_lock_owner(callno);
3023 if (iaxs[callno] && iaxs[callno]->owner) {
3024 ast_queue_frame(iaxs[callno]->owner, f);
3025 ast_channel_unlock(iaxs[callno]->owner);
3031 * \brief Queue a hangup frame on the ast_channel owner
3033 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3034 * is active for the given call number.
3036 * \pre Assumes lock for callno is already held.
3038 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3039 * was valid before calling it, it may no longer be valid after calling it.
3040 * This function may unlock and lock the mutex associated with this callno,
3041 * meaning that another thread may grab it and destroy the call.
3043 static int iax2_queue_hangup(int callno)
3045 iax2_lock_owner(callno);
3046 if (iaxs[callno] && iaxs[callno]->owner) {
3047 ast_queue_hangup(iaxs[callno]->owner);
3048 ast_channel_unlock(iaxs[callno]->owner);
3054 * \brief Queue a control frame on the ast_channel owner
3056 * This function queues a control frame on the owner of the IAX2 pvt struct that
3057 * is active for the given call number.
3059 * \pre Assumes lock for callno is already held.
3061 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3062 * was valid before calling it, it may no longer be valid after calling it.
3063 * This function may unlock and lock the mutex associated with this callno,
3064 * meaning that another thread may grab it and destroy the call.
3066 static int iax2_queue_control_data(int callno,
3067 enum ast_control_frame_type control, const void *data, size_t datalen)
3069 iax2_lock_owner(callno);
3070 if (iaxs[callno] && iaxs[callno]->owner) {
3071 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3072 ast_channel_unlock(iaxs[callno]->owner);
3076 static void destroy_firmware(struct iax_firmware *cur)
3078 /* Close firmware */
3080 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3086 static int try_firmware(char *s)
3089 struct iax_firmware *cur = NULL;
3090 int ifd, fd, res, len, chunk;
3091 struct ast_iax2_firmware_header *fwh, fwh2;
3092 struct MD5Context md5;
3093 unsigned char sum[16], buf[1024];
3096 s2 = ast_alloca(strlen(s) + 100);
3098 last = strrchr(s, '/');
3104 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3106 if (stat(s, &stbuf) < 0) {
3107 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3111 /* Make sure it's not a directory */
3112 if (S_ISDIR(stbuf.st_mode))
3114 ifd = open(s, O_RDONLY);
3116 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3119 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3121 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3125 /* Unlink our newly created file */
3128 /* Now copy the firmware into it */
3129 len = stbuf.st_size;
3132 if (chunk > sizeof(buf))
3133 chunk = sizeof(buf);
3134 res = read(ifd, buf, chunk);
3136 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3141 res = write(fd, buf, chunk);
3143 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3151 /* Return to the beginning */
3152 lseek(fd, 0, SEEK_SET);
3153 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3154 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3158 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3159 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3163 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3164 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3168 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3169 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3173 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
3174 if (fwh == MAP_FAILED) {
3175 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3180 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3181 MD5Final(sum, &md5);
3182 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3183 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3184 munmap((void*)fwh, stbuf.st_size);
3189 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3190 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3191 /* Found a candidate */
3192 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3193 /* The version we have on loaded is older, load this one instead */
3195 /* This version is no newer than what we have. Don't worry about it.
3196 We'll consider it a proper load anyhow though */
3197 munmap((void*)fwh, stbuf.st_size);
3203 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3205 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3210 munmap((void*)cur->fwh, cur->mmaplen);
3215 cur->mmaplen = stbuf.st_size;
3222 static int iax_check_version(char *dev)
3225 struct iax_firmware *cur = NULL;
3227 if (ast_strlen_zero(dev))
3230 AST_LIST_LOCK(&firmwares);
3231 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3232 if (!strcmp(dev, (char *)cur->fwh->devname)) {
3233 res = ntohs(cur->fwh->version);
3237 AST_LIST_UNLOCK(&firmwares);
3242 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3245 unsigned int bs = desc & 0xff;
3246 unsigned int start = (desc >> 8) & 0xffffff;
3248 struct iax_firmware *cur;
3250 if (ast_strlen_zero((char *)dev) || !bs)
3255 AST_LIST_LOCK(&firmwares);
3256 AST_LIST_TRAVERSE(&firmwares, cur, list) {
3257 if (strcmp((char *)dev, (char *)cur->fwh->devname))
3259 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3260 if (start < ntohl(cur->fwh->datalen)) {
3261 bytes = ntohl(cur->fwh->datalen) - start;
3264 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3267 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3275 AST_LIST_UNLOCK(&firmwares);
3281 static void reload_firmware(int unload)
3283 struct iax_firmware *cur = NULL;
3286 char dir[256], fn[256];
3288 AST_LIST_LOCK(&firmwares);
3290 /* Mark all as dead */
3291 AST_LIST_TRAVERSE(&firmwares, cur, list)
3294 /* Now that we have marked them dead... load new ones */
3296 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3299 while((de = readdir(fwd))) {
3300 if (de->d_name[0] != '.') {
3301 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3302 if (!try_firmware(fn)) {
3303 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3309 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3312 /* Clean up leftovers */
3313 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3316 AST_LIST_REMOVE_CURRENT(list);
3317 destroy_firmware(cur);
3319 AST_LIST_TRAVERSE_SAFE_END;
3321 AST_LIST_UNLOCK(&firmwares);
3325 * \note This function assumes that iaxsl[callno] is locked when called.
3327 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3328 * was valid before calling it, it may no longer be valid after calling it.
3329 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3330 * associated with this callno, meaning that another thread may grab it and destroy the call.
3332 static int __do_deliver(void *data)
3334 /* Just deliver the packet by using queueing. This is called by
3335 the IAX thread with the iaxsl lock held. */
3336 struct iax_frame *fr = data;
3338 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3339 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3340 iax2_queue_frame(fr->callno, &fr->af);
3341 /* Free our iax frame */
3342 iax2_frame_free(fr);
3343 /* And don't run again */
3347 static int handle_error(void)
3349 /* XXX Ideally we should figure out why an error occurred and then abort those
3350 rather than continuing to try. Unfortunately, the published interface does
3351 not seem to work XXX */
3353 struct sockaddr_in *sin;
3356 struct sock_extended_err e;
3361 m.msg_controllen = sizeof(e);
3363 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3365 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3367 if (m.msg_controllen) {
3368 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3370 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3372 ast_log(LOG_WARNING, "No address detected??\n");
3374 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3381 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3384 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3387 ast_debug(1, "Received error: %s\n", strerror(errno));
3394 static int send_packet(struct iax_frame *f)
3397 int callno = f->callno;
3399 /* Don't send if there was an error, but return error instead */
3400 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3403 /* Called with iaxsl held */
3405 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));
3408 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3409 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3411 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3412 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3416 ast_debug(1, "Received error: %s\n", strerror(errno));
3425 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3426 * for the given call number may disappear during its execution.
3428 static int iax2_predestroy(int callno)
3430 struct ast_channel *c = NULL;
3431 struct chan_iax2_pvt *pvt = iaxs[callno];
3436 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3437 iax2_destroy_helper(pvt);
3438 ast_set_flag64(pvt, IAX_ALREADYGONE);
3441 if ((c = pvt->owner)) {
3442 ast_channel_tech_pvt_set(c, NULL);
3443 iax2_queue_hangup(callno);
3445 ast_module_unref(ast_module_info->self);
3451 static void iax2_destroy(int callno)
3453 struct chan_iax2_pvt *pvt = NULL;
3454 struct ast_channel *owner = NULL;
3457 if ((pvt = iaxs[callno])) {
3459 /* iax2_destroy_helper gets called from this function later on. When
3460 * called twice, we get the (previously) familiar FRACK! errors in
3461 * devmode, from the scheduler. An alternative to this approach is to
3462 * reset the scheduler entries to -1 when they're deleted in
3463 * iax2_destroy_helper(). That approach was previously decided to be
3464 * "wrong" because "the memory is going to be deallocated anyway. Why
3465 * should we be resetting those values?" */
3466 iax2_destroy_helper(pvt);
3470 owner = pvt ? pvt->owner : NULL;
3473 if (ast_channel_trylock(owner)) {
3474 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3475 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3481 iaxs[callno] = NULL;
3488 /* If there's an owner, prod it to give up */
3489 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3490 * because we already hold the owner channel lock. */
3491 ast_queue_hangup(owner);
3494 if (pvt->peercallno) {
3495 remove_by_peercallno(pvt);
3498 if (pvt->transfercallno) {
3499 remove_by_transfercallno(pvt);
3509 ast_channel_unlock(owner);
3513 static int update_packet(struct iax_frame *f)
3515 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3516 struct ast_iax2_full_hdr *fh = f->data;
3517 struct ast_frame af;
3519 /* if frame is encrypted. decrypt before updating it. */
3520 if (f->encmethods) {
3521 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3523 /* Mark this as a retransmission */
3524 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3526 f->iseqno = iaxs[f->callno]->iseqno;
3527 fh->iseqno = f->iseqno;
3529 /* Now re-encrypt the frame */
3530 if (f->encmethods) {
3531 /* since this is a retransmit frame, create a new random padding
3532 * before re-encrypting. */
3533 build_rand_pad(f->semirand, sizeof(f->semirand));
3534 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3539 static int attempt_transmit(const void *data);
3540 static void __attempt_transmit(const void *data)
3542 /* Attempt to transmit the frame to the remote peer...
3543 Called without iaxsl held. */
3544 struct iax_frame *f = (struct iax_frame *)data;
3546 int callno = f->callno;
3547 /* Make sure this call is still active */
3549 ast_mutex_lock(&iaxsl[callno]);
3550 if (callno && iaxs[callno]) {
3551 if ((f->retries < 0) /* Already ACK'd */ ||
3552 (f->retries >= max_retries) /* Too many attempts */) {
3553 /* Record an error if we've transmitted too many times */
3554 if (f->retries >= max_retries) {
3556 /* Transfer timeout */
3557 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3558 } else if (f->final) {
3559 iax2_destroy(callno);
3561 if (iaxs[callno]->owner)
3562 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);
3563 iaxs[callno]->error = ETIMEDOUT;
3564 if (iaxs[callno]->owner) {
3565 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3567 iax2_queue_frame(callno, &fr); /* XXX */
3568 /* Remember, owner could disappear */
3569 if (iaxs[callno] && iaxs[callno]->owner)
3570 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3572 if (iaxs[callno]->reg) {
3573 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3574 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3575 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3577 iax2_destroy(callno);
3584 /* Update it if it needs it */
3586 /* Attempt transmission */
3589 /* Try again later after 10 times as long */
3591 if (f->retrytime > MAX_RETRY_TIME)
3592 f->retrytime = MAX_RETRY_TIME;
3593 /* Transfer messages max out at one second */
3594 if (f->transfer && (f->retrytime > 1000))
3595 f->retrytime = 1000;
3596 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3599 /* Make sure it gets freed */
3605 /* Don't attempt delivery, just remove it from the queue */
3606 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3607 ast_mutex_unlock(&iaxsl[callno]);
3608 f->retrans = -1; /* this is safe because this is the scheduled function */
3609 /* Free the IAX frame */
3611 } else if (callno) {
3612 ast_mutex_unlock(&iaxsl[callno]);
3616 static int attempt_transmit(const void *data)
3618 #ifdef SCHED_MULTITHREADED
3619 if (schedule_action(__attempt_transmit, data))
3621 __attempt_transmit(data);
3625 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3627 struct iax2_peer *peer = NULL;
3628 struct iax2_user *user = NULL;
3629 static const char * const choices[] = { "all", NULL };
3634 e->command = "iax2 prune realtime";
3636 "Usage: iax2 prune realtime [<peername>|all]\n"
3637 " Prunes object(s) from the cache\n";
3641 cmplt = ast_cli_complete(a->word, choices, a->n);
3643 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3649 return CLI_SHOWUSAGE;
3650 if (!strcmp(a->argv[3], "all")) {
3653 ast_cli(a->fd, "Cache flushed successfully.\n");
3656 peer = find_peer(a->argv[3], 0);
3657 user = find_user(a->argv[3]);
3660 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3661 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3662 expire_registry(peer_ref(peer));
3663 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3665 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3670 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3671 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3672 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3674 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3676 ao2_unlink(users,user);
3680 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3686 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3690 e->command = "iax2 test losspct";
3692 "Usage: iax2 test losspct <percentage>\n"
3693 " For testing, throws away <percentage> percent of incoming packets\n";
3699 return CLI_SHOWUSAGE;
3701 test_losspct = atoi(a->argv[3]);
3707 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3711 e->command = "iax2 test late";
3713 "Usage: iax2 test late <ms>\n"
3714 " For testing, count the next frame as <ms> ms late\n";
3721 return CLI_SHOWUSAGE;
3723 test_late = atoi(a->argv[3]);
3728 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3732 e->command = "iax2 test resync";
3734 "Usage: iax2 test resync <ms>\n"
3735 " For testing, adjust all future frames by <ms> ms\n";
3742 return CLI_SHOWUSAGE;
3744 test_resync = atoi(a->argv[3]);
3749 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3753 e->command = "iax2 test jitter";
3755 "Usage: iax2 test jitter <ms> <pct>\n"
3756 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3757 " percentage of packets. If <pct> is not specified, adds\n"
3758 " jitter to all packets.\n";