Asterisk - The Open Source Telephony Project GIT-master-7921072
chan_iax2.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <markster@digium.com>
7 *
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.
13 *
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.
17 */
18
19/*! \file
20 *
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
22 * as specified in RFC 5456
23 *
24 * \author Mark Spencer <markster@digium.com>
25 *
26 * \ingroup channel_drivers
27 *
28 * \todo Implement musicclass settings for IAX2 devices
29 */
30
31/*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
32 * \addtogroup configuration_file
33 */
34
35/*! \page iax.conf iax.conf
36 * \verbinclude iax.conf.sample
37 */
38
39/*!
40 * \todo XXX The IAX2 channel driver needs its native bridge
41 * code converted to the new bridge technology scheme.
42 *
43 * \note The chan_dahdi native bridge code can be used as an
44 * example. It also appears that chan_iax2 also has a native
45 * transfer check like chan_dahdi to eliminate tromboned calls.
46 *
47 * \note The existing native bridge code is marked with the
48 * IAX2_NATIVE_BRIDGING conditional.
49 */
50
51/*** MODULEINFO
52 <use type="module">res_crypto</use>
53 <use type="external">crypto</use>
54 <support_level>core</support_level>
55 ***/
56
57#include "asterisk.h"
58
59#include <sys/mman.h>
60#include <dirent.h>
61#include <sys/socket.h>
62#include <netinet/in.h>
63#include <arpa/inet.h>
64#include <netinet/in_systm.h>
65#include <netinet/ip.h>
66#include <sys/time.h>
67#include <signal.h>
68#include <netdb.h>
69#include <fcntl.h>
70#include <sys/stat.h>
71#include <regex.h>
72
73#include "asterisk/paths.h"
74
75#include "asterisk/lock.h"
76#include "asterisk/frame.h"
77#include "asterisk/channel.h"
78#include "asterisk/module.h"
79#include "asterisk/pbx.h"
80#include "asterisk/sched.h"
81#include "asterisk/io.h"
82#include "asterisk/config.h"
83#include "asterisk/cli.h"
84#include "asterisk/translate.h"
85#include "asterisk/md5.h"
86#include "asterisk/crypto.h"
87#include "asterisk/acl.h"
88#include "asterisk/manager.h"
89#include "asterisk/callerid.h"
90#include "asterisk/app.h"
91#include "asterisk/mwi.h"
92#include "asterisk/astdb.h"
94#include "asterisk/features.h"
95#include "asterisk/utils.h"
96#include "asterisk/causes.h"
97#include "asterisk/localtime.h"
98#include "asterisk/dnsmgr.h"
101#include "asterisk/linkedlists.h"
102#include "asterisk/astobj2.h"
103#include "asterisk/timing.h"
105#include "asterisk/test.h"
108#include "asterisk/bridge.h"
109#include "asterisk/stasis.h"
114#include "asterisk/format_cap.h"
115
116#include "iax2/include/iax2.h"
118#include "iax2/include/parser.h"
122#include "iax2/include/netsock.h"
123
124#include "jitterbuf.h"
125
126/*** DOCUMENTATION
127 <application name="IAX2Provision" language="en_US">
128 <synopsis>
129 Provision a calling IAXy with a given template.
130 </synopsis>
131 <syntax>
132 <parameter name="template">
133 <para>If not specified, defaults to <literal>default</literal>.</para>
134 </parameter>
135 </syntax>
136 <description>
137 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
138 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
139 or <literal>0</literal> on success.</para>
140 </description>
141 </application>
142 <function name="IAXPEER" language="en_US">
143 <synopsis>
144 Gets IAX peer information.
145 </synopsis>
146 <syntax>
147 <parameter name="peername" required="true">
148 <enumlist>
149 <enum name="CURRENTCHANNEL">
150 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
151 endpoint of the current channel</para>
152 </enum>
153 </enumlist>
154 </parameter>
155 <parameter name="item">
156 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
157 <enumlist>
158 <enum name="ip">
159 <para>(default) The IP address.</para>
160 </enum>
161 <enum name="status">
162 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
163 </enum>
164 <enum name="mailbox">
165 <para>The configured mailbox.</para>
166 </enum>
167 <enum name="context">
168 <para>The configured context.</para>
169 </enum>
170 <enum name="expire">
171 <para>The epoch time of the next expire.</para>
172 </enum>
173 <enum name="dynamic">
174 <para>Is it dynamic? (yes/no).</para>
175 </enum>
176 <enum name="callerid_name">
177 <para>The configured Caller ID name.</para>
178 </enum>
179 <enum name="callerid_num">
180 <para>The configured Caller ID number.</para>
181 </enum>
182 <enum name="codecs">
183 <para>The configured codecs.</para>
184 </enum>
185 <enum name="codec[x]">
186 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
187 with <literal>0</literal>)</para>
188 </enum>
189 </enumlist>
190 </parameter>
191 </syntax>
192 <description>
193 <para>Gets information associated with the specified IAX2 peer.</para>
194 </description>
195 </function>
196 <function name="IAXVAR" language="en_US">
197 <synopsis>
198 Sets or retrieves a remote variable.
199 </synopsis>
200 <syntax>
201 <parameter name="varname" required="true" />
202 </syntax>
203 <description>
204 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
205 </description>
206 </function>
207 <info name="CHANNEL" language="en_US" tech="IAX">
208 <enumlist>
209 <enum name="osptoken">
210 <para>R/O Get the peer's osptoken.</para>
211 </enum>
212 <enum name="peerip">
213 <para>R/O Get the peer's ip address.</para>
214 </enum>
215 <enum name="peername">
216 <para>R/O Get the peer's username.</para>
217 </enum>
218 <enum name="secure_signaling">
219 <para>R/O Get the if the IAX channel is secured.</para>
220 </enum>
221 <enum name="secure_media">
222 <para>R/O Get the if the IAX channel is secured.</para>
223 </enum>
224 </enumlist>
225 </info>
226 <info name="Dial_Resource" language="en_US" tech="IAX2">
227 <para>The general syntax is:</para>
228 <para><literal>Dial(IAX2/[username[:password]@]peer[:port][/exten[@context]][/options]</literal></para>
229 <para>IAX2 optionally allows modifiers to be specified after the extension.</para>
230 <enumlist>
231 <enum name="a">
232 <para>Request auto answer (supporting equipment/configuration required)</para>
233 </enum>
234 </enumlist>
235 </info>
236 <manager name="IAXpeers" language="en_US">
237 <synopsis>
238 List IAX peers.
239 </synopsis>
240 <syntax>
241 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
242 </syntax>
243 <description>
244 </description>
245 </manager>
246 <manager name="IAXpeerlist" language="en_US">
247 <synopsis>
248 List IAX Peers.
249 </synopsis>
250 <syntax>
251 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
252 </syntax>
253 <description>
254 <para>List all the IAX peers.</para>
255 </description>
256 </manager>
257 <manager name="IAXnetstats" language="en_US">
258 <synopsis>
259 Show IAX Netstats.
260 </synopsis>
261 <syntax />
262 <description>
263 <para>Show IAX channels network statistics.</para>
264 </description>
265 </manager>
266 <manager name="IAXregistry" language="en_US">
267 <synopsis>
268 Show IAX registrations.
269 </synopsis>
270 <syntax>
271 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
272 </syntax>
273 <description>
274 <para>Show IAX registrations.</para>
275 </description>
276 </manager>
277 ***/
278
279/* Define SCHED_MULTITHREADED to run the scheduler in a special
280 multithreaded mode. */
281#define SCHED_MULTITHREADED
282
283/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
284 thread is actually doing. */
285#define DEBUG_SCHED_MULTITHREAD
286
287
288#ifdef SO_NO_CHECK
289static int nochecksums = 0;
290#endif
291
292#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
293#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
294
295#define DEFAULT_THREAD_COUNT 10
296#define DEFAULT_MAX_THREAD_COUNT 100
297#define DEFAULT_RETRY_TIME 1000
298#define MEMORY_SIZE 100
299#define DEFAULT_DROP 3
300
301#define DEBUG_SUPPORT
302
303#define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
304
305/* Sample over last 100 units to determine historic jitter */
306#define GAMMA (0.01)
307
309
310static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
311
312
313/*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
314 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
315#define MAX_TRUNK_MTU 1240
316
317static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
318static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
319
320#define DEFAULT_CONTEXT "default"
321
323
324static char language[MAX_LANGUAGE] = "";
325static char regcontext[AST_MAX_CONTEXT] = "";
326
327static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
328static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
330
331static int maxauthreq = 3;
332static int max_retries = 4;
333static int ping_time = 21;
334static int lagrq_time = 10;
335static int maxjitterbuffer=1000;
336static int resyncthreshold=1000;
337static int maxjitterinterps=10;
338static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
339
340#define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
341
342static int trunkfreq = 20;
344
345static int authdebug = 0;
346static int autokill = 0;
347static int iaxcompat = 0;
348static int last_authmethod = 0;
349
350static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
351
352static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
353
354static struct {
355 unsigned int tos;
356 unsigned int cos;
357} qos = { 0, 0 };
358
359static int min_reg_expire;
360static int max_reg_expire;
361
362static int srvlookup = 0;
363
364static struct ast_timer *timer; /* Timer for trunking */
365
367static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
368static int defaultsockfd = -1;
369
370static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
371
372/* Ethernet, etc */
373#define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
374/* T1, maybe ISDN */
375#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
376 ~AST_FORMAT_SLIN & \
377 ~AST_FORMAT_SLIN16 & \
378 ~AST_FORMAT_SIREN7 & \
379 ~AST_FORMAT_SIREN14 & \
380 ~AST_FORMAT_G719 & \
381 ~AST_FORMAT_ULAW & \
382 ~AST_FORMAT_ALAW & \
383 ~AST_FORMAT_G722)
384/* A modem */
385#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
386 ~AST_FORMAT_G726 & \
387 ~AST_FORMAT_G726_AAL2 & \
388 ~AST_FORMAT_ADPCM)
389
390#define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
391 ~AST_FORMAT_G723)
392
393
394#define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
395#define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
396#define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
397
398/*! \brief Name of effective auth method */
399static const char *auth_method_labels[] = {
400 [0] = "none",
401 [IAX_AUTH_PLAINTEXT] = "plaintext",
402 [IAX_AUTH_MD5] = "MD5",
403 [IAX_AUTH_RSA] = "RSA",
404};
405
406/* Max length is length of |RSA|MD5|plaintext (18 + 1 for NUL = 19) */
407#define AUTH_METHOD_NAMES_BUFSIZE 19
408
409/*!
410 * \brief Get names of all auth methods
411 * \param Bit field of auth methods
412 * \param[out] buf Buffer into which to write the names. Must be of size AUTH_METHOD_NAMES_BUFSIZE.
413 * \return Auth methods name
414 */
415static char *auth_method_names(int authmethods, char *restrict buf)
416{
417 char *pos = buf;
418
419 *pos = '\0';
420
421 if (authmethods & IAX_AUTH_RSA) {
422 pos += sprintf(pos, "|RSA");
423 }
424 if (authmethods & IAX_AUTH_MD5) {
425 pos += sprintf(pos, "|MD5");
426 }
427 if (authmethods & IAX_AUTH_PLAINTEXT) {
428 pos += sprintf(pos, "|plaintext");
429 }
430
431 if (pos == buf) { /* No auth methods */
432 strcpy(buf, "none");
433 return buf;
434 }
435
436 return buf + 1; /* Skip leading | */
437}
438
439/* if a pvt has encryption setup done and is running on the call */
440#define IAX_CALLENCRYPTED(pvt) \
441 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
442
443#define IAX_DEBUGDIGEST(msg, key) do { \
444 int idx; \
445 char digest[33] = ""; \
446 \
447 if (!iaxdebug) \
448 break; \
449 \
450 for (idx = 0; idx < 16; idx++) \
451 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
452 \
453 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
454 } while(0)
455
456static struct io_context *io;
458
460
461static int iaxdebug = 0;
462
463static int iaxtrunkdebug = 0;
464
465static int test_losspct = 0;
466#ifdef IAXTESTS
467static int test_late = 0;
468static int test_resync = 0;
469static int test_jit = 0;
470static int test_jitpct = 0;
471#endif /* IAXTESTS */
472
476static int amaflags = 0;
477static int adsi = 0;
478static int delayreject = 0;
479static int iax2_encryption = 0;
480static int iax2_authmethods = 0;
481
482static struct ast_flags64 globalflags = { 0 };
483
485
489 IAX_STATE_TBD = (1 << 2),
490};
491
495};
496
497
498#define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
499#define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
500#define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
501#define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
502#define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
503#define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
504#define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
505#define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
506#define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
507#define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
508#define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
509#define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
510#define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
511#define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
512#define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
513#define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
514#define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
515#define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
516#define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
517#define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
518#define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
519#define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
520#define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
521#define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
522#define IAX_DELAYPBXSTART (uint64_t)(1LLU << 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 */
523#define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
524#define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
525#define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
526#define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
527#define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
528#define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
529static int global_rtautoclear = 120;
530
531static int reload_config(int forced_reload);
532
533/*!
534 * \brief Call token validation settings.
535 */
537 /*! \brief Default calltoken required unless the ip is in the ignorelist */
539 /*! \brief Require call token validation. */
541 /*! \brief Require call token validation after a successful registration
542 * using call token validation occurs. */
544 /*! \brief Do not require call token validation. */
546};
547
548struct iax2_user {
556 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
560 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
561 );
562
566 int adsi;
567 uint64_t flags;
569 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
570 int curauthreq; /*!< Current number of outstanding AUTHREQs */
575 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
576};
577
578struct iax2_peer {
582 AST_STRING_FIELD(description); /*!< Description of the peer */
585 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
586
587 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
588 AST_STRING_FIELD(context); /*!< For transfers only */
589 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
590 AST_STRING_FIELD(mailbox); /*!< Mailbox */
593 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
594 /* Suggested caller id if registering */
595 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
596 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
597 AST_STRING_FIELD(zonetag); /*!< Time Zone */
598 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
599 );
601 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
604 int sockfd; /*!< Socket to use for transmission */
606 int adsi;
607 uint64_t flags;
608
609 /* Dynamic Registration fields */
610 struct ast_sockaddr defaddr; /*!< Default address if there is one */
611 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
612 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
613
614 int expire; /*!< Schedule entry for expiry */
615 int expiry; /*!< How soon to expire */
616 iax2_format capability; /*!< Capability */
617
618 /* Qualification */
619 int callno; /*!< Call number of POKE request */
620 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
621 int lastms; /*!< How long last response took (in ms), or -1 for no response */
622 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
623
624 int pokefreqok; /*!< How often to check if the host is up */
625 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
626 int historicms; /*!< How long recent average responses took */
627 int smoothing; /*!< Sample over how many units to determine historic ms */
628 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
629
630 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
631
633 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
634
635 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
636};
637
638#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
639
644 struct timeval txtrunktime; /*!< Transmit trunktime */
645 struct timeval rxtrunktime; /*!< Receive trunktime */
646 struct timeval lasttxtime; /*!< Last transmitted trunktime */
647 struct timeval trunkact; /*!< Last trunk activity */
648 unsigned int lastsent; /*!< Last sent time */
649 /* Trunk data and length */
650 unsigned char *trunkdata;
651 unsigned int trunkdatalen;
652 unsigned int trunkdataalloc;
655 int calls;
657};
658
660
670
684
686 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
687 char username[80];
688 char secret[80]; /*!< Password or key name in []'s */
689 int expire; /*!< Sched ID of expiration */
690 int refresh; /*!< How often to refresh */
692 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
693 int callno; /*!< Associated call number if applicable */
694 struct ast_sockaddr us; /*!< Who the server thinks we are */
695 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
697 int port;
698 char hostname[];
699};
700
702
703/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
704#define MIN_RETRY_TIME 100
705#define MAX_RETRY_TIME 10000
706
707#define MAX_JITTER_BUFFER 50
708#define MIN_JITTER_BUFFER 10
709
710#define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
711
712#define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
713
714/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
715#define TS_GAP_FOR_JB_RESYNC 5000
716
717/* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
718#define MARK_IAX_SUBCLASS_TX 0x8000
719
723static int iaxdynamicthreadnum = 0;
724static int iaxactivethreadcount = 0;
725
726struct iax_rr {
731 int delay;
733 int ooo;
734};
735
736struct iax2_pvt_ref;
737
738/* We use the high order bit as the validated flag, and the lower 15 as the
739 * actual call number */
740typedef uint16_t callno_entry;
741
743 /*! Socket to send/receive on for this call */
745 /*! ast_callid bound to dialog */
747 /*! Last received voice format */
749 /*! Last received video format */
751 /*! Last sent voice format */
753 /*! Last sent video format */
755 /*! What we are capable of sending */
757 /*! Last received timestamp */
758 unsigned int last;
759 /*! Last sent timestamp - never send the same timestamp twice in a single call */
760 unsigned int lastsent;
761 /*! Timestamp of the last video frame sent */
762 unsigned int lastvsent;
763 /*! Next outgoing timestamp if everything is good */
764 unsigned int nextpred;
765 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
767 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
769 /*! True if the last voice we transmitted was not silence/CNG */
770 unsigned int notsilenttx:1;
771 /*! Ping time */
772 unsigned int pingtime;
773 /*! Max time for initial response */
775 /*! Peer Address */
777 /*! Actual used codec preferences */
779 /*! Requested codec preferences */
781 /*! Our call number */
782 unsigned short callno;
783 /*! Our callno_entry entry */
785 /*! Peer callno */
786 unsigned short peercallno;
787 /*! Negotiated format, this is only used to remember what format was
788 chosen for an unauthenticated call so that the channel can get
789 created later using the right format */
791 /*! Peer selected format */
793 /*! Peer capability */
795 /*! timeval that we base our transmission on */
796 struct timeval offset;
797 /*! timeval that we base our delivery on */
798 struct timeval rxcore;
799 /*! The jitterbuffer */
801 /*! active jb read scheduler id */
802 int jbid;
803 /*! LAG */
804 int lag;
805 /*! Error, as discovered by the manager */
806 int error;
807 /*! Owner if we have one */
809 /*! What's our state? */
811 /*! Expiry (optional) */
813 /*! Next outgoing sequence number */
814 unsigned char oseqno;
815 /*! Next sequence number they have not yet acknowledged */
816 unsigned char rseqno;
817 /*! Next incoming sequence number */
818 unsigned char iseqno;
819 /*! Last incoming sequence number we have acknowledged */
820 unsigned char aseqno;
821
823 /*! Peer name */
825 /*! Default Context */
827 /*! Caller ID if available */
830 /*! Hidden Caller ID (i.e. ANI) if appropriate */
832 /*! DNID */
834 /*! RDNIS */
836 /*! Requested Extension */
838 /*! Expected Username */
840 /*! Expected Secret */
842 /*! MD5 challenge */
844 /*! Public keys permitted keys for incoming authentication */
846 /*! Private key for outgoing authentication */
848 /*! Preferred language */
850 /*! Hostname/peername for naming purposes */
852
857 /*! received OSP token */
859 /*! Default parkinglot */
861 );
862 /*! AUTHREJ all AUTHREP frames */
864 /*! permitted authentication methods */
866 /*! effective authentication method */
868 /*! permitted encryption methods */
870 /*! Encryption AES-128 Key */
872 /*! Decryption AES-128 Key corresponding to ecx */
874 /*! Decryption AES-128 Key used to decrypt peer frames */
876 /*! scheduler id associated with iax_key_rotate
877 * for encrypted calls*/
879 /*! 32 bytes of semi-random data */
880 unsigned char semirand[32];
881 /*! Associated registry */
883 /*! Associated peer for poking */
885 /*! IAX_ flags */
886 uint64_t flags;
887 int adsi;
888
889 /*! Transferring status */
891 /*! Transfer identifier */
893 /*! Who we are IAX transferring to */
895 /*! What's the new call number for the transfer */
896 unsigned short transfercallno;
897 /*! Transfer encrypt AES-128 Key */
899
900 /*! Status of knowledge of peer ADSI capability */
902
903 /*! Callno of native bridge peer. (Valid if nonzero) */
904 unsigned short bridgecallno;
905
906 int pingid; /*!< Transmit PING request */
907 int lagid; /*!< Retransmit lag request */
908 int autoid; /*!< Auto hangup for Dialplan requestor */
909 int authid; /*!< Authentication rejection ID */
910 int authfail; /*!< Reason to report failure */
911 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
918 /*! variables inherited from the user definition */
920 /*! variables transmitted in a NEW packet */
922 /*! last received remote rr */
924 /*! Current base time: (just for stats) */
925 int min;
926 /*! Dropped frame count: (just for stats) */
928 /*! received frame count: (just for stats) */
930 /*! Destroying this call initiated. */
932 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
933 unsigned char calltoken_ie_len;
934 /*! hold all signaling frames from the pbx thread until we have a destination callno */
936 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
938};
939
941 struct ast_frame f;
943};
944
948};
949
950#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
951#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
952
953#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
954#define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
955#define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
956
958 size_t capacity;
959 size_t available;
961};
962
964
965/*! table of available call numbers */
967
968/*! table of available trunk call numbers */
970
971/*!
972 * \brief a list of frames that may need to be retransmitted
973 *
974 * \note The contents of this list do not need to be explicitly destroyed
975 * on module unload. This is because all active calls are destroyed, and
976 * all frames in this queue will get destroyed as a part of that process.
977 *
978 * \note Contents protected by the iaxsl[] locks
979 */
981
983
985
986static time_t max_calltoken_delay = 10;
987
988/*!
989 * This module will get much higher performance when doing a lot of
990 * user and peer lookups if the number of buckets is increased from 1.
991 * However, to maintain old behavior for Asterisk 1.4, these are set to
992 * 1 by default. When using multiple buckets, search order through these
993 * containers is considered random, so you will not be able to depend on
994 * the order the entires are specified in iax.conf for matching order. */
995#ifdef LOW_MEMORY
996#define MAX_PEER_BUCKETS 17
997#else
998#define MAX_PEER_BUCKETS 563
999#endif
1000static struct ao2_container *peers;
1001
1002#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
1003static struct ao2_container *users;
1004
1005/*! Table containing peercnt objects for every ip address consuming a callno */
1007
1008/*! Table containing custom callno limit rules for a range of ip addresses. */
1010
1011/*! Table containing ip addresses not requiring calltoken validation */
1013
1014static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
1015
1016static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
1017
1018static uint16_t global_maxcallno;
1019
1020/*! Total num of call numbers allowed to be allocated without calltoken validation */
1022
1023static uint16_t total_nonval_callno_used = 0;
1024
1025/*! peer connection private, keeps track of all the call numbers
1026 * consumed by a single ip address */
1027struct peercnt {
1028 /*! ip address consuming call numbers */
1030 /*! Number of call numbers currently used by this ip address */
1031 uint16_t cur;
1032 /*! Max call numbers allowed for this ip address */
1033 uint16_t limit;
1034 /*! Specifies whether limit is set by a registration or not, if so normal
1035 * limit setting rules do not apply to this address. */
1036 unsigned char reg;
1037};
1038
1039/*! used by both callno_limits and calltoken_ignores containers */
1041 /*! ip address range for custom callno limit rule */
1042 struct ast_ha ha;
1043 /*! callno limit for this ip address range, only used in callno_limits container */
1044 uint16_t limit;
1045 /*! delete me marker for reloads */
1046 unsigned char delme;
1047};
1048
1049enum {
1050 /*! Extension exists */
1052 /*! Extension is nonexistent */
1054 /*! Extension can exist */
1056 /*! Waiting to hear back response */
1058 /*! Timed out */
1060 /*! Request transmitted */
1062 /*! Timeout */
1064 /*! Matchmore */
1066};
1067
1071 struct timeval orig;
1072 struct timeval expiry;
1074 unsigned short callno;
1075 int waiters[256];
1078};
1079
1081
1082static void reg_source_db(struct iax2_peer *p);
1083static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1084static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1085
1086static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1087static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1088static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1089
1095};
1096
1100};
1101
1104 size_t len;
1105 unsigned char buf[1];
1106};
1107
1112#ifdef SCHED_MULTITHREADED
1113 void (*schedfunc)(const void *);
1114 const void *scheddata;
1115#endif
1116#ifdef DEBUG_SCHED_MULTITHREAD
1117 char curfunc[80];
1118#endif
1120 pthread_t threadid;
1123 unsigned char readbuf[4096];
1124 unsigned char *buf;
1125 ssize_t buf_len;
1126 size_t buf_size;
1127 int iofd;
1133 /*! if this thread is processing a full frame,
1134 some information about that frame will be stored
1135 here, so we can avoid dispatching any more full
1136 frames for that callno to other threads */
1137 struct {
1138 unsigned short callno;
1140 unsigned char type;
1141 unsigned char csub;
1143 /*! Queued up full frames for processing. If more full frames arrive for
1144 * a call which this thread is already processing a full frame for, they
1145 * are queued up here. */
1147 unsigned char stop;
1148};
1149
1150/* Thread lists */
1154
1155static void *iax2_process_thread(void *data);
1156static void iax2_destroy(int callno);
1157
1159{
1163}
1164
1165/*!
1166 * \brief an array of iax2 pvt structures
1167 *
1168 * The container for active chan_iax2_pvt structures is implemented as an
1169 * array for extremely quick direct access to the correct pvt structure
1170 * based on the local call number. The local call number is used as the
1171 * index into the array where the associated pvt structure is stored.
1172 */
1174
1176{
1177 return iaxs[callno]->callid;
1178}
1179
1181{
1183}
1184
1186{
1188 char buffer[AST_CALLID_BUFFER_LENGTH];
1189 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1191}
1192
1193/*!
1194 * \brief Another container of iax2_pvt structures
1195 *
1196 * Active IAX2 pvt structs are also stored in this container, if they are a part
1197 * of an active call where we know the remote side's call number. The reason
1198 * for this is that incoming media frames do not contain our call number. So,
1199 * instead of having to iterate the entire iaxs array, we use this container to
1200 * look up calls where the remote side is using a given call number.
1201 */
1203
1204/*!
1205 * \brief chan_iax2_pvt structure locks
1206 *
1207 * These locks are used when accessing a pvt structure in the iaxs array.
1208 * The index used here is the same as used in the iaxs array. It is the
1209 * local call number for the associated pvt struct.
1210 */
1212
1213/*!
1214 * \brief Another container of iax2_pvt structures
1215 *
1216 * Active IAX2 pvt structs used during transfering a call are stored here.
1217 */
1219
1220/* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1221 but keeps the division between trunked and non-trunked better. */
1222#define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1223
1224/* Debug routines... */
1226
1227static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1228{
1229 if (iaxdebug ||
1230 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1233 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1234
1235 if (iaxdebug) {
1236 iax_showframe(f, fhi, rx, addr, datalen);
1237 } else {
1238 iaxdebug = 1;
1239 iax_showframe(f, fhi, rx, addr, datalen);
1240 iaxdebug = 0;
1241 }
1242 }
1243}
1244
1245static void iax_debug_output(const char *data)
1246{
1247 if (iaxdebug)
1248 ast_verbose("%s", data);
1249}
1250
1251static void iax_error_output(const char *data)
1252{
1253 ast_log(LOG_WARNING, "%s", data);
1254}
1255
1256static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1257{
1258 va_list args;
1259 char buf[1024];
1260
1261 va_start(args, fmt);
1262 vsnprintf(buf, sizeof(buf), fmt, args);
1263 va_end(args);
1264
1265 ast_log(LOG_ERROR, "%s", buf);
1266}
1267
1268static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1269{
1270 va_list args;
1271 char buf[1024];
1272
1273 va_start(args, fmt);
1274 vsnprintf(buf, sizeof(buf), fmt, args);
1275 va_end(args);
1276
1277 ast_log(LOG_WARNING, "%s", buf);
1278}
1279
1280static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1281{
1282 va_list args;
1283 char buf[1024];
1284
1285 va_start(args, fmt);
1286 vsnprintf(buf, sizeof(buf), fmt, args);
1287 va_end(args);
1288
1289 ast_verbose("%s", buf);
1290}
1291
1292static int expire_registry(const void *data);
1293static int iax2_answer(struct ast_channel *c);
1294static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1295static int iax2_devicestate(const char *data);
1296static int iax2_digit_begin(struct ast_channel *c, char digit);
1297static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1298static int iax2_do_register(struct iax2_registry *reg);
1299static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1300static int iax2_hangup(struct ast_channel *c);
1301static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1302static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1303static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1304static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1305static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1306static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1307static int iax2_sendtext(struct ast_channel *c, const char *text);
1308static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1309static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1310static int iax2_transfer(struct ast_channel *c, const char *dest);
1311static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1312static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1313
1314static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1315static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1316static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1317static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1318static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1319static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1320static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
1321static struct ast_frame *iax2_read(struct ast_channel *c);
1322static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1323static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1324static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1325static void *iax2_dup_variable_datastore(void *);
1326static void prune_peers(void);
1327static void prune_users(void);
1328static void iax2_free_variable_datastore(void *);
1329
1330static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1331static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1332static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1333static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1334static void build_rand_pad(unsigned char *buf, ssize_t len);
1335static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1336static int replace_callno(const void *obj);
1337static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1338static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1339static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1340
1342 .type = "IAX2",
1343 .description = tdesc,
1344 .properties = AST_CHAN_TP_WANTSJITTER,
1345 .requester = iax2_request,
1346 .devicestate = iax2_devicestate,
1347 .send_digit_begin = iax2_digit_begin,
1348 .send_digit_end = iax2_digit_end,
1349 .send_text = iax2_sendtext,
1350 .send_image = iax2_sendimage,
1351 .send_html = iax2_sendhtml,
1352 .call = iax2_call,
1353 .hangup = iax2_hangup,
1354 .answer = iax2_answer,
1355 .read = iax2_read,
1356 .write = iax2_write,
1357 .write_video = iax2_write,
1358 .indicate = iax2_indicate,
1359 .setoption = iax2_setoption,
1360 .queryoption = iax2_queryoption,
1361 .transfer = iax2_transfer,
1362 .fixup = iax2_fixup,
1363 .func_channel_read = acf_channel_read,
1364};
1365
1366/*!
1367 * \internal
1368 * \brief Obtain the owner channel lock if the owner exists.
1369 *
1370 * \param callno IAX2 call id.
1371 *
1372 * \note Assumes the iaxsl[callno] lock is already obtained.
1373 *
1374 * \note
1375 * IMPORTANT NOTE!!! Any time this function is used, even if
1376 * iaxs[callno] was valid before calling it, it may no longer be
1377 * valid after calling it. This function may unlock and lock
1378 * the mutex associated with this callno, meaning that another
1379 * thread may grab it and destroy the call.
1380 */
1381static void iax2_lock_owner(int callno)
1382{
1383 for (;;) {
1384 if (!iaxs[callno] || !iaxs[callno]->owner) {
1385 /* There is no owner lock to get. */
1386 break;
1387 }
1388 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1389 /* We got the lock */
1390 break;
1391 }
1392 /* Avoid deadlock by pausing and trying again */
1393 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1394 }
1395}
1396
1397/*!
1398 * \internal
1399 * \brief Check if a control subtype is allowed on the wire.
1400 *
1401 * \param subtype Control frame subtype to check if allowed to/from the wire.
1402 *
1403 * \retval non-zero if allowed.
1404 */
1405static int iax2_is_control_frame_allowed(int subtype)
1406{
1407 enum ast_control_frame_type control = subtype;
1408 int is_allowed;
1409
1410 /*
1411 * Note: If we compare the enumeration type, which does not have any
1412 * negative constants, the compiler may optimize this code away.
1413 * Therefore, we must perform an integer comparison here.
1414 */
1415 if (subtype == -1) {
1416 return -1;
1417 }
1418
1419 /* Default to not allowing control frames to pass. */
1420 is_allowed = 0;
1421
1422 /*
1423 * The switch default is not present in order to take advantage
1424 * of the compiler complaining of a missing enum case.
1425 */
1426 switch (control) {
1427 /*
1428 * These control frames make sense to send/receive across the link.
1429 */
1430 case AST_CONTROL_HANGUP:
1431 case AST_CONTROL_RING:
1433 case AST_CONTROL_ANSWER:
1434 case AST_CONTROL_BUSY:
1438 case AST_CONTROL_FLASH:
1439 case AST_CONTROL_WINK:
1440 case AST_CONTROL_OPTION:
1445 case AST_CONTROL_HOLD:
1446 case AST_CONTROL_UNHOLD:
1451 case AST_CONTROL_AOC:
1453 case AST_CONTROL_MCID:
1454 is_allowed = -1;
1455 break;
1456
1457 /*
1458 * These control frames do not make sense to send/receive across the link.
1459 */
1461 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1463 /* Across an IAX link the source is still the same. */
1465 /* A success/fail status report from calling ast_transfer() on this machine. */
1466 case AST_CONTROL_CC:
1467 /* The payload contains pointers that are valid for the sending machine only. */
1469 /* Across an IAX link the source is still the same. */
1471 /* The action can only be done by the sending machine. */
1473 /* This frame would cause the call to unexpectedly hangup. */
1475 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1477 /* Intended only for the sending machine's local channel structure. */
1479 /* Intended only for masquerades when calling ast_indicate_data(). */
1481 /* Intended only for internal stream topology manipulation. */
1483 /* Intended only for internal stream topology change notification. */
1490 /* None of these playback stream control frames should go across the link. */
1495 /* None of these media recording control frames should go across the link. */
1496 break;
1497 }
1498 return is_allowed;
1499}
1500
1502{
1503 if (!network_change_sub) {
1508 }
1509}
1510
1512{
1514}
1515
1517{
1518 if (!acl_change_sub) {
1523 }
1524}
1525
1527{
1529}
1530
1531static int network_change_sched_cb(const void *data)
1532{
1533 struct iax2_registry *reg;
1537 iax2_do_register(reg);
1538 }
1540
1541 return 0;
1542}
1543
1544static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1545 struct stasis_message *message)
1546{
1547 /* This callback is only concerned with network change messages from the system topic. */
1549 return;
1550 }
1551
1552 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1553 if (network_change_sched_id == -1) {
1555 }
1556}
1557
1558static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1559 struct stasis_message *message)
1560{
1562 return;
1563 }
1564
1565 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1566 reload_config(1);
1567}
1568
1570 .type = "IAX2_VARIABLE",
1571 .duplicate = iax2_dup_variable_datastore,
1573};
1574
1575static void *iax2_dup_variable_datastore(void *old)
1576{
1577 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1578 struct ast_var_t *oldvar, *newvar;
1579
1580 newlist = ast_calloc(sizeof(*newlist), 1);
1581 if (!newlist) {
1582 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1583 return NULL;
1584 }
1585
1586 AST_LIST_HEAD_INIT(newlist);
1587 AST_LIST_LOCK(oldlist);
1588 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1589 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1590 if (newvar)
1591 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1592 else
1593 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1594 }
1595 AST_LIST_UNLOCK(oldlist);
1596 return newlist;
1597}
1598
1599static void iax2_free_variable_datastore(void *old)
1600{
1601 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1602 struct ast_var_t *oldvar;
1603
1604 AST_LIST_LOCK(oldlist);
1605 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1606 ast_free(oldvar);
1607 }
1608 AST_LIST_UNLOCK(oldlist);
1609 AST_LIST_HEAD_DESTROY(oldlist);
1610 ast_free(oldlist);
1611}
1612
1613
1614/* WARNING: insert_idle_thread should only ever be called within the
1615 * context of an iax2_process_thread() thread.
1616 */
1618{
1619 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1623 } else {
1627 }
1628
1629 return;
1630}
1631
1632static struct iax2_thread *find_idle_thread(void)
1633{
1634 struct iax2_thread *thread = NULL;
1635
1636 /* Pop the head of the idle list off */
1640
1641 /* If we popped a thread off the idle list, just return it */
1642 if (thread) {
1643 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1644 return thread;
1645 }
1646
1647 /* Pop the head of the dynamic list off */
1651
1652 /* If we popped a thread off the dynamic list, just return it */
1653 if (thread) {
1654 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1655 return thread;
1656 }
1657
1658 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1660 return NULL;
1661
1662 /* Set default values */
1666
1667 /* Initialize lock and condition */
1668 ast_mutex_init(&thread->lock);
1669 ast_cond_init(&thread->cond, NULL);
1670 ast_mutex_init(&thread->init_lock);
1671 ast_cond_init(&thread->init_cond, NULL);
1672 ast_mutex_lock(&thread->init_lock);
1673
1674 /* Create thread and send it on it's way */
1676 ast_cond_destroy(&thread->cond);
1677 ast_mutex_destroy(&thread->lock);
1678 ast_mutex_unlock(&thread->init_lock);
1679 ast_cond_destroy(&thread->init_cond);
1680 ast_mutex_destroy(&thread->init_lock);
1682 return NULL;
1683 }
1684
1685 /* this thread is not processing a full frame (since it is idle),
1686 so ensure that the field for the full frame call number is empty */
1687 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1688
1689 /* Wait for the thread to be ready before returning it to the caller */
1690 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1691
1692 /* Done with init_lock */
1693 ast_mutex_unlock(&thread->init_lock);
1694
1695 return thread;
1696}
1697
1698#ifdef SCHED_MULTITHREADED
1699static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1700{
1701 struct iax2_thread *thread;
1702 static time_t lasterror;
1703 time_t t;
1704
1706 if (thread != NULL) {
1707 thread->schedfunc = func;
1708 thread->scheddata = data;
1709 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1710#ifdef DEBUG_SCHED_MULTITHREAD
1711 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1712#endif
1713 signal_condition(&thread->lock, &thread->cond);
1714 return 0;
1715 }
1716 time(&t);
1717 if (t != lasterror) {
1718 lasterror = t;
1719 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1720 }
1721
1722 return -1;
1723}
1724#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1725#endif
1726
1727static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1728 ast_sched_cb callback, const void *data)
1729{
1730 return ast_sched_replace(id, con, when, callback, data);
1731}
1732
1733static int iax2_sched_add(struct ast_sched_context *con, int when,
1734 ast_sched_cb callback, const void *data)
1735{
1736 return ast_sched_add(con, when, callback, data);
1737}
1738
1739/*!
1740 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1741 * \param callno Call number to lock.
1742 * \retval 0 If call disappeared or has ongoing hangup procedure.
1743 * \retval 1 If call found and mutex is locked.
1744 */
1746{
1748
1749 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1750 * or destroy initiated (in middle of hang up procedure. */
1751 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1752 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1754 return 0;
1755 }
1756
1757 /* Lock acquired, and callno is alive and kicking. */
1758 return 1;
1759}
1760
1761static int send_ping(const void *data);
1762
1763static void __send_ping(const void *data)
1764{
1765 int callno = PTR_TO_CALLNO(data);
1766
1768 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1769 return;
1770 }
1771
1772 /* Mark pingid as invalid scheduler id. */
1773 iaxs[callno]->pingid = -1;
1774
1775 /* callno is now locked. */
1776 if (iaxs[callno]->peercallno) {
1777 /* Send PING packet. */
1779
1780 /* Schedule sending next ping. */
1782 }
1783
1785}
1786
1787static int send_ping(const void *data)
1788{
1789#ifdef SCHED_MULTITHREADED
1790 if (schedule_action(__send_ping, data))
1791#endif
1792 __send_ping(data);
1793
1794 return 0;
1795}
1796
1797static void encmethods_to_str(int e, struct ast_str **buf)
1798{
1799 ast_str_set(buf, 0, "(");
1800 if (e & IAX_ENCRYPT_AES128) {
1801 ast_str_append(buf, 0, "aes128");
1802 }
1803 if (e & IAX_ENCRYPT_KEYROTATE) {
1804 ast_str_append(buf, 0, ",keyrotate");
1805 }
1806 if (ast_str_strlen(*buf) > 1) {
1807 ast_str_append(buf, 0, ")");
1808 } else {
1809 ast_str_set(buf, 0, "No");
1810 }
1811}
1812
1813static int get_encrypt_methods(const char *s)
1814{
1815 int e;
1816 if (!strcasecmp(s, "aes128"))
1818 else if (ast_true(s))
1820 else
1821 e = 0;
1822 return e;
1823}
1824
1825static int send_lagrq(const void *data);
1826
1827static void __send_lagrq(const void *data)
1828{
1829 int callno = PTR_TO_CALLNO(data);
1830
1832 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1833 return;
1834 }
1835
1836 /* Mark lagid as invalid scheduler id. */
1837 iaxs[callno]->lagid = -1;
1838
1839 /* callno is now locked. */
1840 if (iaxs[callno]->peercallno) {
1841 /* Send LAGRQ packet. */
1843
1844 /* Schedule sending next lagrq. */
1846 }
1847
1849}
1850
1851static int send_lagrq(const void *data)
1852{
1853#ifdef SCHED_MULTITHREADED
1854 if (schedule_action(__send_lagrq, data))
1855#endif
1856 __send_lagrq(data);
1857 return 0;
1858}
1859
1860static unsigned char compress_subclass(iax2_format subclass)
1861{
1862 int x;
1863 int power=-1;
1864 /* If it's 64 or smaller, just return it */
1865 if (subclass < IAX_FLAG_SC_LOG)
1866 return subclass;
1867 /* Otherwise find its power */
1868 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1869 if (subclass & (1LL << x)) {
1870 if (power > -1) {
1871 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1872 return 0;
1873 } else
1874 power = x;
1875 }
1876 }
1877 return power | IAX_FLAG_SC_LOG;
1878}
1879
1881{
1882 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1883 if (csub & IAX_FLAG_SC_LOG) {
1884 /* special case for 'compressed' -1 */
1885 if (csub == 0xff)
1886 return -1;
1887 else
1888 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1889 }
1890 else
1891 return csub;
1892}
1893
1894static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1895{
1896 int x;
1897 struct ast_format *found_format = NULL;
1898
1899 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1900 struct ast_format *pref_format;
1901 uint64_t pref_bitfield;
1902
1903 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1904 if (!pref_bitfield) {
1905 break;
1906 }
1907
1908 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1909 if (!pref_format) {
1910 /* The bitfield is not associated with any format. */
1911 continue;
1912 }
1913 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1914 if (found_format) {
1915 break;
1916 }
1917 }
1918
1919 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1920 return found_format;
1921 }
1922
1923 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1924 ao2_cleanup(found_format);
1925 return NULL;
1926}
1927
1929{
1930 struct ast_format_cap *cap;
1931 struct ast_format *tmpfmt;
1932 iax2_format format = 0;
1933
1936 tmpfmt = codec_choose_from_prefs(pref, cap);
1937 if (!tmpfmt) {
1938 ao2_ref(cap, -1);
1939 return 0;
1940 }
1941
1943 ao2_ref(tmpfmt, -1);
1944 ao2_ref(cap, -1);
1945 }
1946
1947 return format;
1948}
1949
1951{
1952 struct ast_format *tmpfmt;
1953
1955 if (!tmpfmt) {
1956 return "Unknown";
1957 }
1958
1959 return ast_format_get_name(tmpfmt);
1960}
1961
1962static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1963{
1965
1966 if (!cap) {
1967 return "(Nothing)";
1968 }
1970 ast_format_cap_get_names(cap, codec_buf);
1971 ao2_ref(cap, -1);
1972
1973 return ast_str_buffer(*codec_buf);
1974}
1975
1976static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1977{
1978 int res, i;
1979 struct ast_format_cap *cap;
1980
1981 /* We want to add the formats to the cap in the preferred order */
1983 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1984 ao2_cleanup(cap);
1985 return 1;
1986 }
1987
1988 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1989
1990 /* Adjust formats bitfield and pref list to match. */
1993
1994 for (i = 0; i < ast_format_cap_count(cap); i++) {
1995 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1996
1998 ao2_ref(fmt, -1);
1999 }
2000
2001 ao2_ref(cap, -1);
2002
2003 return res;
2004}
2005
2006/*!
2007 * \note The only member of the peer passed here guaranteed to be set is the name field
2008 */
2009static int peer_hash_cb(const void *obj, const int flags)
2010{
2011 const struct iax2_peer *peer = obj;
2012 const char *name = obj;
2013
2014 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
2015}
2016
2017/*!
2018 * \note The only member of the peer passed here guaranteed to be set is the name field
2019 */
2020static int peer_cmp_cb(void *obj, void *arg, int flags)
2021{
2022 struct iax2_peer *peer = obj, *peer2 = arg;
2023 const char *name = arg;
2024
2025 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
2026 CMP_MATCH | CMP_STOP : 0;
2027}
2028
2029/*!
2030 * \note The only member of the user passed here guaranteed to be set is the name field
2031 */
2032static int user_hash_cb(const void *obj, const int flags)
2033{
2034 const struct iax2_user *user = obj;
2035 const char *name = obj;
2036
2037 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2038}
2039
2040/*!
2041 * \note The only member of the user passed here guaranteed to be set is the name field
2042 */
2043static int user_cmp_cb(void *obj, void *arg, int flags)
2044{
2045 struct iax2_user *user = obj, *user2 = arg;
2046 const char *name = arg;
2047
2048 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2049 CMP_MATCH | CMP_STOP : 0;
2050}
2051
2052/*!
2053 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2054 * so do not call it with a pvt lock held.
2055 */
2056static struct iax2_peer *find_peer(const char *name, int realtime)
2057{
2058 struct iax2_peer *peer = NULL;
2059
2060 peer = ao2_find(peers, name, OBJ_KEY);
2061
2062 /* Now go for realtime if applicable */
2063 if (!peer && realtime) {
2064 peer = realtime_peer(name, NULL);
2065 }
2066 return peer;
2067}
2068
2069static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2070{
2071 ao2_ref(peer, +1);
2072 return peer;
2073}
2074
2075static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2076{
2077 ao2_ref(peer, -1);
2078 return NULL;
2079}
2080
2081static struct iax2_user *find_user(const char *name)
2082{
2083 return ao2_find(users, name, OBJ_KEY);
2084}
2085
2086static inline struct iax2_user *user_unref(struct iax2_user *user)
2087{
2088 ao2_ref(user, -1);
2089 return NULL;
2090}
2091
2092static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2093{
2094 struct iax2_peer *peer = NULL;
2095 int res = 0;
2096 struct ao2_iterator i;
2097
2098 i = ao2_iterator_init(peers, 0);
2099 while ((peer = ao2_iterator_next(&i))) {
2100
2101 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2102 ast_copy_string(host, peer->name, len);
2103 peer_unref(peer);
2104 res = 1;
2105 break;
2106 }
2107 peer_unref(peer);
2108 }
2110
2111 if (!peer) {
2112 peer = realtime_peer(NULL, &addr);
2113 if (peer) {
2114 ast_copy_string(host, peer->name, len);
2115 peer_unref(peer);
2116 res = 1;
2117 }
2118 }
2119
2120 return res;
2121}
2122
2123/* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2124static int iax2_delete_from_sched(const void* data)
2125{
2126 int sched_id = (int)(long)data;
2127
2129
2130 return 0;
2131}
2132
2133/*!\note Assumes the lock on the pvt is already held, when
2134 * iax2_destroy_helper() is called. */
2135static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2136{
2137 /* Decrement AUTHREQ count if needed */
2138 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2139 struct iax2_user *user;
2140
2142 if (user) {
2143 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2145 }
2146
2148 }
2149
2150
2151 /* Mark call destroy initiated flag. */
2152 pvt->destroy_initiated = 1;
2153
2154 /*
2155 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2156 * Already running tasks will be terminated because of destroy_initiated.
2157 *
2158 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2159 * it leads to a deadlock between the scheduler thread callback locking
2160 * the callno mutex and this thread which holds the callno mutex one or
2161 * more times. It is better to have another thread delete the scheduled
2162 * callbacks which doesn't lock the callno mutex.
2163 */
2164 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2165 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2166
2167 pvt->pingid = -1;
2168 pvt->lagid = -1;
2169
2170 AST_SCHED_DEL(sched, pvt->autoid);
2171 AST_SCHED_DEL(sched, pvt->authid);
2172 AST_SCHED_DEL(sched, pvt->initid);
2173 AST_SCHED_DEL(sched, pvt->jbid);
2175}
2176
2177static void iax2_frame_free(struct iax_frame *fr)
2178{
2180 iax_frame_free(fr);
2181}
2182
2183static int scheduled_destroy(const void *vid)
2184{
2185 unsigned short callno = PTR_TO_CALLNO(vid);
2186 ast_mutex_lock(&iaxsl[callno]);
2187 if (iaxs[callno]) {
2188 ast_debug(1, "Really destroying %d now...\n", callno);
2189 iax2_destroy(callno);
2190 }
2191 ast_mutex_unlock(&iaxsl[callno]);
2192 return 0;
2193}
2194
2196{
2197 if (s->f.datalen) {
2198 ast_free(s->f.data.ptr);
2199 }
2200 ast_free(s);
2201}
2202
2203/*! \brief This function must be called once we are sure the other side has
2204 * given us a call number. All signaling is held here until that point. */
2205static void send_signaling(struct chan_iax2_pvt *pvt)
2206{
2207 struct signaling_queue_entry *s = NULL;
2208
2209 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2210 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2212 }
2213 pvt->hold_signaling = 0;
2214}
2215
2216/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2217 * we have received a destination call number. */
2218static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2219{
2220 struct signaling_queue_entry *qe;
2221
2222 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2223 return 1; /* do not queue this frame */
2224 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2225 return -1; /* out of memory */
2226 }
2227
2228 /* copy ast_frame into our queue entry */
2229 qe->f = *f;
2230 if (qe->f.datalen) {
2231 /* if there is data in this frame copy it over as well */
2232 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2234 return -1;
2235 }
2236 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2237 }
2239
2240 return 0;
2241}
2242
2243static void pvt_destructor(void *obj)
2244{
2245 struct chan_iax2_pvt *pvt = obj;
2246 struct iax_frame *cur = NULL;
2247 struct signaling_queue_entry *s = NULL;
2248
2249 ast_mutex_lock(&iaxsl[pvt->callno]);
2250
2252
2254 pvt->callno_entry = 0;
2255
2256 /* Already gone */
2258
2259 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2260 /* Cancel any pending transmissions */
2261 cur->retries = -1;
2262 }
2263
2265
2266 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2268 }
2269
2270 if (pvt->reg) {
2271 pvt->reg->callno = 0;
2272 }
2273
2274 if (!pvt->owner) {
2275 jb_frame frame;
2276 if (pvt->vars) {
2278 pvt->vars = NULL;
2279 }
2280
2281 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2282 iax2_frame_free(frame.data);
2283 }
2284
2285 jb_destroy(pvt->jb);
2287 }
2288}
2289
2290static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2291{
2292 struct chan_iax2_pvt *tmp;
2293 jb_conf jbconf;
2294
2295 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2296 return NULL;
2297 }
2298
2299 tmp->pingid = -1;
2300 tmp->lagid = -1;
2301 tmp->autoid = -1;
2302 tmp->authid = -1;
2303 tmp->initid = -1;
2304 tmp->keyrotateid = -1;
2305 tmp->jbid = -1;
2306
2307 if (ast_string_field_init(tmp, 32)) {
2308 ao2_ref(tmp, -1);
2309 tmp = NULL;
2310 return NULL;
2311 }
2312
2313 tmp->prefs = prefs_global;
2314
2317
2318 tmp->jb = jb_new();
2323 jb_setconf(tmp->jb,&jbconf);
2324
2325 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2326
2327 tmp->hold_signaling = 1;
2328 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2329
2330 return tmp;
2331}
2332
2333static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2334{
2336 if (new) {
2337 size_t afdatalen = new->afdatalen;
2338 memcpy(new, fr, sizeof(*new));
2339 iax_frame_wrap(new, &fr->af);
2340 new->afdatalen = afdatalen;
2341 new->data = NULL;
2342 new->datalen = 0;
2343 new->direction = DIRECTION_INGRESS;
2344 new->retrans = -1;
2345 }
2346 return new;
2347}
2348/* keep these defined in this order. They are used in find_callno to
2349 * determine whether or not a new call number should be allowed. */
2350enum {
2351 /* do not allow a new call number, only search ones in use for match */
2353 /* search for match first, then allow a new one to be allocated */
2355 /* do not search for match, force a new call number */
2357 /* do not search for match, force a new call number. Signifies call number
2358 * has been calltoken validated */
2360};
2361
2362static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2363{
2364 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2365 /* This is the main host */
2366 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2367 (check_dcallno ? dcallno == cur->callno : 1) ) {
2368 /* That's us. Be sure we keep track of the peer call number */
2369 return 1;
2370 }
2371 }
2372 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2373 /* We're transferring */
2374 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2375 return 1;
2376 }
2377 return 0;
2378}
2379
2380static int make_trunk(unsigned short callno, int locked)
2381{
2382 int x;
2383 int res= 0;
2385 if (iaxs[callno]->oseqno) {
2386 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2387 return -1;
2388 }
2389 if (callno >= TRUNK_CALL_START) {
2390 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2391 return -1;
2392 }
2393
2397 &entry)) {
2398 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2399 return -1;
2400 }
2401
2403 ast_mutex_lock(&iaxsl[x]);
2404
2405 /*!
2406 * \note We delete these before switching the slot, because if
2407 * they fire in the meantime, they will generate a warning.
2408 */
2409 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2410 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2411 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2412 iaxs[x] = iaxs[callno];
2413 iaxs[x]->callno = x;
2414
2415 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2416 * before assigning the new one */
2417 if (iaxs[x]->callno_entry) {
2419 sched,
2420 MIN_REUSE_TIME * 1000,
2423
2424 }
2425 iaxs[x]->callno_entry = entry;
2426
2427 iaxs[callno] = NULL;
2428 /* Update the two timers that should have been started */
2430 ping_time * 1000, send_ping, (void *)(long)x);
2432 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2433
2434 if (locked)
2436 res = x;
2437 if (!locked)
2439
2440 /* We moved this call from a non-trunked to a trunked call */
2441 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2442
2443 return res;
2444}
2445
2447{
2448 if (!pvt->transfercallno) {
2449 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2450 return;
2451 }
2452
2454}
2455
2457{
2458 if (!pvt->transfercallno) {
2459 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2460 return;
2461 }
2462
2464}
2465static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2466{
2467 if (!pvt->peercallno) {
2468 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2469 return;
2470 }
2471
2473}
2474
2475static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2476{
2477 if (!pvt->peercallno) {
2478 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2479 return;
2480 }
2481
2483}
2484
2485static int addr_range_delme_cb(void *obj, void *arg, int flags)
2486{
2487 struct addr_range *lim = obj;
2488 lim->delme = 1;
2489 return 0;
2490}
2491
2492static int addr_range_hash_cb(const void *obj, const int flags)
2493{
2494 const struct addr_range *lim = obj;
2495 return abs(ast_sockaddr_hash(&lim->ha.addr));
2496}
2497
2498static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2499{
2500 struct addr_range *lim1 = obj, *lim2 = arg;
2501 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2502 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2503 CMP_MATCH | CMP_STOP : 0;
2504}
2505
2506static int peercnt_hash_cb(const void *obj, const int flags)
2507{
2508 const struct peercnt *peercnt = obj;
2509
2511 return 0;
2512 }
2513 return ast_sockaddr_hash(&peercnt->addr);
2514}
2515
2516static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2517{
2518 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2519 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2520}
2521
2522static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2523{
2524 struct addr_range *addr_range = obj;
2525 struct ast_sockaddr *addr = arg;
2526 struct ast_sockaddr tmp_addr;
2527
2528 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2529
2530 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2531 return CMP_MATCH | CMP_STOP;
2532 }
2533 return 0;
2534}
2535
2536/*!
2537 * \internal
2538 *
2539 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2540 */
2541static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2542{
2543 struct addr_range *addr_range;
2544 struct iax2_peer *peer = NULL;
2545 struct iax2_user *user = NULL;
2546 /* if no username is given, check for guest accounts */
2547 const char *find = S_OR(name, "guest");
2548 int res = 1; /* required by default */
2549 int optional = 0;
2551 /* There are only two cases in which calltoken validation is not required.
2552 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2553 * the peer definition has not set the requirecalltoken option.
2554 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2555 */
2556
2557 /* ----- Case 1 ----- */
2559 ao2_ref(addr_range, -1);
2560 optional = 1;
2561 }
2562
2563 /* ----- Case 2 ----- */
2564 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2565 calltoken_required = user->calltoken_required;
2566 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2567 calltoken_required = user->calltoken_required;
2568 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2570 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2572 }
2573
2574 if (peer) {
2575 peer_unref(peer);
2576 }
2577 if (user) {
2579 }
2580
2581 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2583 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2584 res = 0;
2585 }
2586
2587 return res;
2588}
2589
2590/*!
2591 * \internal
2592 *
2593 * \brief set peercnt callno limit.
2594 *
2595 * \details
2596 * First looks in custom definitions. If not found, global limit
2597 * is used. Entries marked as reg already have
2598 * a custom limit set by a registration and are not modified.
2599 */
2601{
2602 uint16_t limit = global_maxcallno;
2603 struct addr_range *addr_range;
2604 struct ast_sockaddr addr;
2605
2606 ast_sockaddr_copy(&addr, &peercnt->addr);
2607
2608 if (peercnt->reg && peercnt->limit) {
2609 return; /* this peercnt has a custom limit set by a registration */
2610 }
2611
2613 limit = addr_range->limit;
2614 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2615 ao2_ref(addr_range, -1);
2616 }
2617
2618 peercnt->limit = limit;
2619}
2620
2621/*!
2622 * \internal
2623 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2624 */
2625static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2626{
2627 struct peercnt *peercnt = obj;
2628
2630 ast_debug(1, "Reset limits for peercnts table\n");
2631
2632 return 0;
2633}
2634
2635/*!
2636 * \internal
2637 * \brief returns match if delme is set.
2638 */
2639static int prune_addr_range_cb(void *obj, void *arg, int flags)
2640{
2641 struct addr_range *addr_range = obj;
2642
2643 return addr_range->delme ? CMP_MATCH : 0;
2644}
2645
2646/*!
2647 * \internal
2648 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2649 */
2650static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2651{
2652 /* this function turns off and on custom callno limits set by peer registration */
2653 struct peercnt *peercnt;
2654 struct peercnt tmp;
2655
2656 ast_sockaddr_copy(&tmp.addr, sockaddr);
2657
2658 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2659 peercnt->reg = reg;
2660 if (limit) {
2661 peercnt->limit = limit;
2662 } else {
2664 }
2665 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2666 ao2_ref(peercnt, -1); /* decrement ref from find */
2667 }
2668}
2669
2670/*!
2671 * \internal
2672 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2673 *
2674 * \details First searches for the address in the peercnts table. If found
2675 * the current count is incremented. If not found a new peercnt is allocated
2676 * and linked into the peercnts table with a call number count of 1.
2677 */
2678static int peercnt_add(struct ast_sockaddr *addr)
2679{
2680 struct peercnt *peercnt;
2681 int res = 0;
2682 struct peercnt tmp;
2683
2684 ast_sockaddr_copy(&tmp.addr, addr);
2685
2686 /* Reasoning for peercnts container lock: Two identical ip addresses
2687 * could be added by different threads at the "same time". Without the container
2688 * lock, both threads could alloc space for the same object and attempt
2689 * to link to table. With the lock, one would create the object and link
2690 * to table while the other would find the already created peercnt object
2691 * rather than creating a new one. */
2693 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2695 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2697 /* create and set defaults */
2700 /* guarantees it does not go away after unlocking table
2701 * ao2_find automatically adds this */
2703 } else {
2705 return -1;
2706 }
2707
2708 /* check to see if the address has hit its callno limit. If not increment cur. */
2709 if (peercnt->limit > peercnt->cur) {
2710 peercnt->cur++;
2711 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2712 } else { /* max num call numbers for this peer has been reached! */
2713 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2714 res = -1;
2715 }
2716
2717 /* clean up locks and ref count */
2720 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2721
2722 return res;
2723}
2724
2725/*!
2726 * \internal
2727 * \brief decrements a peercnts table entry
2728 */
2729static void peercnt_remove(struct peercnt *peercnt)
2730{
2731 struct ast_sockaddr addr;
2732
2733 ast_sockaddr_copy(&addr, &peercnt->addr);
2734
2735 /*
2736 * Container locked here since peercnt may be unlinked from
2737 * list. If left unlocked, peercnt_add could try and grab this
2738 * entry from the table and modify it at the "same time" this
2739 * thread attempts to unlink it.
2740 */
2742 peercnt->cur--;
2743 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2744 /* if this was the last connection from the peer remove it from table */
2745 if (peercnt->cur == 0) {
2746 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2747 }
2749}
2750
2751/*!
2752 * \internal
2753 * \brief called by scheduler to decrement object
2754 */
2755static int peercnt_remove_cb(const void *obj)
2756{
2757 struct peercnt *peercnt = (struct peercnt *) obj;
2758
2760 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2761
2762 return 0;
2763}
2764
2765/*!
2766 * \internal
2767 * \brief decrements peercnts connection count, finds by addr
2768 */
2770{
2771 struct peercnt *peercnt;
2772 struct peercnt tmp;
2773
2774 ast_sockaddr_copy(&tmp.addr, addr);
2775
2776 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2778 ao2_ref(peercnt, -1); /* decrement ref from find */
2779 }
2780 return 0;
2781}
2782
2783/*!
2784 * \internal
2785 * \brief Create callno_limit entry based on configuration
2786 */
2787static void build_callno_limits(struct ast_variable *v)
2788{
2789 struct addr_range *addr_range = NULL;
2790 struct addr_range tmp;
2791 struct ast_ha *ha;
2792 int limit;
2793 int error;
2794 int found;
2795
2796 for (; v; v = v->next) {
2797 limit = -1;
2798 error = 0;
2799 found = 0;
2800 ha = ast_append_ha("permit", v->name, NULL, &error);
2801
2802 /* check for valid config information */
2803 if (error) {
2804 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2805 continue;
2806 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2807 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2808 ast_free_ha(ha);
2809 continue;
2810 }
2811
2812 ast_copy_ha(ha, &tmp.ha);
2813 /* find or create the addr_range */
2816 found = 1;
2817 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2818 ast_free_ha(ha);
2819 return; /* out of memory */
2820 }
2821
2822 /* copy over config data into addr_range object */
2823 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2824 ast_free_ha(ha); /* cleanup the tmp ha */
2825 addr_range->limit = limit;
2826 addr_range->delme = 0;
2827
2828 /* cleanup */
2829 if (found) {
2831 } else {
2833 }
2834 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2835 }
2836}
2837
2838/*!
2839 * \internal
2840 * \brief Create calltoken_ignores entry based on configuration
2841 */
2842static int add_calltoken_ignore(const char *addr)
2843{
2844 struct addr_range tmp;
2845 struct addr_range *addr_range = NULL;
2846 struct ast_ha *ha = NULL;
2847 int error = 0;
2848
2849 if (ast_strlen_zero(addr)) {
2850 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2851 return -1;
2852 }
2853
2854 ha = ast_append_ha("permit", addr, NULL, &error);
2855
2856 /* check for valid config information */
2857 if (error) {
2858 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2859 return -1;
2860 }
2861
2862 ast_copy_ha(ha, &tmp.ha);
2863 /* find or create the addr_range */
2866 addr_range->delme = 0;
2868 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2869 /* copy over config data into addr_range object */
2870 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2872 } else {
2873 ast_free_ha(ha);
2874 return -1;
2875 }
2876
2877 ast_free_ha(ha);
2878 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2879
2880 return 0;
2881}
2882
2883static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2884{
2885 struct ao2_iterator i;
2886 struct peercnt *peercnt;
2887 struct ast_sockaddr addr;
2888 int found = 0;
2889
2890 switch (cmd) {
2891 case CLI_INIT:
2892 e->command = "iax2 show callnumber usage";
2893 e->usage =
2894 "Usage: iax2 show callnumber usage [IP address]\n"
2895 " Shows current IP addresses which are consuming iax2 call numbers\n";
2896 return NULL;
2897 case CLI_GENERATE:
2898 return NULL;
2899 case CLI_HANDLER:
2900 if (a->argc < 4 || a->argc > 5)
2901 return CLI_SHOWUSAGE;
2902
2903 if (a->argc == 4) {
2904 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2905 }
2906
2908 while ((peercnt = ao2_iterator_next(&i))) {
2909 ast_sockaddr_copy(&addr, &peercnt->addr);
2910
2911 if (a->argc == 5) {
2912 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2913 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2914 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2915 ao2_ref(peercnt, -1);
2916 found = 1;
2917 break;
2918 }
2919 } else {
2920 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2921 }
2922 ao2_ref(peercnt, -1);
2923 }
2925
2926 if (a->argc == 4) {
2927 size_t pool_avail = callno_pool.available;
2928 size_t trunk_pool_avail = callno_pool_trunk.available;
2929
2930 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2931 "Non-CallToken Validated Callno Used: %d\n",
2934
2935 ast_cli(a->fd, "Total Available Callno: %zu\n"
2936 "Regular Callno Available: %zu\n"
2937 "Trunk Callno Available: %zu\n",
2938 pool_avail + trunk_pool_avail,
2939 pool_avail,
2940 trunk_pool_avail);
2941 } else if (a->argc == 5 && !found) {
2942 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2943 }
2944
2945
2946 return CLI_SUCCESS;
2947 default:
2948 return NULL;
2949 }
2950}
2951
2952static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2953{
2954 struct call_number_pool *pool = NULL;
2955 callno_entry swap;
2956 size_t choice;
2957
2958 switch (type) {
2959 case CALLNO_TYPE_NORMAL:
2960 pool = &callno_pool;
2961 break;
2962 case CALLNO_TYPE_TRUNK:
2963 pool = &callno_pool_trunk;
2964 break;
2965 default:
2966 ast_assert(0);
2967 break;
2968 }
2969
2970 /* If we fail, make sure this has a defined value */
2971 *entry = 0;
2972
2973 /* We lock here primarily to ensure thread safety of the
2974 * total_nonval_callno_used check and increment */
2976
2977 /* Bail out if we don't have any available call numbers */
2978 if (!pool->available) {
2979 ast_log(LOG_WARNING, "Out of call numbers\n");
2981 return 1;
2982 }
2983
2984 /* Only a certain number of non-validated call numbers should be allocated.
2985 * If there ever is an attack, this separates the calltoken validating users
2986 * from the non-calltoken validating users. */
2989 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2993 return 1;
2994 }
2995
2996 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2997 * available call numbers. The array of call numbers begins as an ordered
2998 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2999 * - let's call that x. When a call number is needed we pick a random index
3000 * into the array between 0 and x and use that as our call number. In a
3001 * typical FYD shuffle, we would swap the value that we are extracting with
3002 * the number at x, but in our case we swap and don't touch the value at x
3003 * because it is effectively invisible. We rely on the rest of the IAX2 core
3004 * to return the number to us at some point. Finally, we decrement x by 1
3005 * which establishes our new unused range.
3006 *
3007 * When numbers are returned to the pool, we put them just past x and bump x
3008 * by 1 so that this number is now available for re-use. */
3009
3010 choice = ast_random() % pool->available;
3011
3012 *entry = pool->numbers[choice];
3013 swap = pool->numbers[pool->available - 1];
3014
3015 pool->numbers[choice] = swap;
3016 pool->available--;
3017
3018 if (validated) {
3020 } else {
3022 }
3023
3025
3026 return 0;
3027}
3028
3029static int replace_callno(const void *obj)
3030{
3032 struct call_number_pool *pool;
3033
3034 /* We lock here primarily to ensure thread safety of the
3035 * total_nonval_callno_used check and decrement */
3037
3041 } else {
3043 "Attempted to decrement total non calltoken validated "
3044 "callnumbers below zero. Callno is: %d\n",
3046 }
3047 }
3048
3050 pool = &callno_pool;
3051 } else {
3052 pool = &callno_pool_trunk;
3053 }
3054
3055 ast_assert(pool->capacity > pool->available);
3056
3057 /* This clears the validated flag */
3059
3060 pool->numbers[pool->available] = entry;
3061 pool->available++;
3062
3064
3065 return 0;
3066}
3067
3068static int create_callno_pools(void)
3069{
3070 uint16_t i;
3071
3073
3074 /* We start at 2. 0 and 1 are reserved. */
3075 for (i = 2; i < TRUNK_CALL_START; i++) {
3078 }
3079
3080 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3083 }
3084
3087
3089
3090 return 0;
3091}
3092
3093/*!
3094 * \internal
3095 * \brief Schedules delayed removal of iax2_pvt call number data
3096 *
3097 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3098 * available again, and the address from the previous connection must be decremented
3099 * from the peercnts table. This function schedules these operations to take place.
3100 */
3102{
3103 int i;
3104 struct peercnt *peercnt;
3105 struct peercnt tmp;
3106
3107 ast_sockaddr_copy(&tmp.addr, addr);
3108
3109 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3110 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3111 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3113 if (i == -1) {
3114 ao2_ref(peercnt, -1);
3115 }
3116 }
3117
3119 sched,
3120 MIN_REUSE_TIME * 1000,
3123}
3124
3125/*!
3126 * \internal
3127 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3128 *
3129 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3130 * a new callno.
3131 */
3132static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3133{
3134 if (frametype != AST_FRAME_IAX) {
3135 return 0;
3136 }
3137 switch (subclass) {
3138 case IAX_COMMAND_NEW:
3139 case IAX_COMMAND_REGREQ:
3141 case IAX_COMMAND_REGREL:
3142 return 1;
3143 case IAX_COMMAND_POKE:
3144 if (!inbound) {
3145 return 1;
3146 }
3147 break;
3148 }
3149 return 0;
3150}
3151
3152/*!
3153 * \note Calling this function while holding another pvt lock can cause a deadlock.
3154 */
3155static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3156{
3157 int res = 0;
3158 int x;
3159 /* this call is calltoken validated as long as it is either NEW_FORCE
3160 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3161 int validated = (new > NEW_ALLOW) ? 1 : 0;
3162 char host[80];
3163
3164 if (new <= NEW_ALLOW) {
3165 if (callno) {
3166 struct chan_iax2_pvt *pvt;
3167 struct chan_iax2_pvt tmp_pvt = {
3168 .callno = dcallno,
3169 .peercallno = callno,
3170 .transfercallno = callno,
3171 /* hack!! */
3172 .frames_received = check_dcallno,
3173 };
3174
3175 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3176 /* this works for finding normal call numbers not involving transfering */
3177 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3178 if (return_locked) {
3179 ast_mutex_lock(&iaxsl[pvt->callno]);
3180 }
3181 res = pvt->callno;
3182 ao2_ref(pvt, -1);
3183 pvt = NULL;
3184 return res;
3185 }
3186 /* this searches for transfer call numbers that might not get caught otherwise */
3187 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3188 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3189 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3190 if (return_locked) {
3191 ast_mutex_lock(&iaxsl[pvt->callno]);
3192 }
3193 res = pvt->callno;
3194 ao2_ref(pvt, -1);
3195 pvt = NULL;
3196 return res;
3197 }
3198 }
3199 /* This will occur on the first response to a message that we initiated,
3200 * such as a PING. */
3201 if (dcallno) {
3202 ast_mutex_lock(&iaxsl[dcallno]);
3203 }
3204 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3205 iaxs[dcallno]->peercallno = callno;
3206 res = dcallno;
3207 store_by_peercallno(iaxs[dcallno]);
3208 if (!res || !return_locked) {
3209 ast_mutex_unlock(&iaxsl[dcallno]);
3210 }
3211 return res;
3212 }
3213 if (dcallno) {
3214 ast_mutex_unlock(&iaxsl[dcallno]);
3215 }
3216 }
3217 if (!res && (new >= NEW_ALLOW)) {
3219
3220 /* It may seem odd that we look through the peer list for a name for
3221 * this *incoming* call. Well, it is weird. However, users don't
3222 * have an IP address/port number that we can match against. So,
3223 * this is just checking for a peer that has that IP/port and
3224 * assuming that we have a user of the same name. This isn't always
3225 * correct, but it will be changed if needed after authentication. */
3226 if (!iax2_getpeername(*addr, host, sizeof(host)))
3227 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3228
3229 if (peercnt_add(addr)) {
3230 /* This address has hit its callnumber limit. When the limit
3231 * is reached, the connection is not added to the peercnts table.*/
3232 return 0;
3233 }
3234
3235 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3236 /* since we ran out of space, remove the peercnt
3237 * entry we added earlier */
3239 ast_log(LOG_WARNING, "No more space\n");
3240 return 0;
3241 }
3243 ast_mutex_lock(&iaxsl[x]);
3244
3245 iaxs[x] = new_iax(addr, host);
3246 if (iaxs[x]) {
3247 if (iaxdebug)
3248 ast_debug(1, "Creating new call structure %d\n", x);
3249 iaxs[x]->callno_entry = entry;
3250 iaxs[x]->sockfd = sockfd;
3252 iaxs[x]->peercallno = callno;
3253 iaxs[x]->callno = x;
3256 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3257 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3258 iaxs[x]->amaflags = amaflags;
3264
3265 if (iaxs[x]->peercallno) {
3267 }
3268 } else {
3269 ast_log(LOG_WARNING, "Out of resources\n");
3272 return 0;
3273 }
3274 if (!return_locked)
3276 res = x;
3277 }
3278 return res;
3279}
3280
3281static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3282 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3283}
3284
3285static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3286
3287 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3288}
3289
3290/*!
3291 * \brief Queue a frame to a call's owning asterisk channel
3292 *
3293 * \pre This function assumes that iaxsl[callno] is locked when called.
3294 *
3295 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3296 * was valid before calling it, it may no longer be valid after calling it.
3297 * This function may unlock and lock the mutex associated with this callno,
3298 * meaning that another thread may grab it and destroy the call.
3299 */
3300static int iax2_queue_frame(int callno, struct ast_frame *f)
3301{
3303 if (iaxs[callno] && iaxs[callno]->owner) {
3306 }
3307 return 0;
3308}
3309
3310/*!
3311 * \brief Queue a hold frame on the ast_channel owner
3312 *
3313 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3314 * is active for the given call number.
3315 *
3316 * \pre Assumes lock for callno is already held.
3317 *
3318 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3319 * was valid before calling it, it may no longer be valid after calling it.
3320 * This function may unlock and lock the mutex associated with this callno,
3321 * meaning that another thread may grab it and destroy the call.
3322 */
3323static int iax2_queue_hold(int callno, const char *musicclass)
3324{
3326 if (iaxs[callno] && iaxs[callno]->owner) {
3327 ast_queue_hold(iaxs[callno]->owner, musicclass);
3329 }
3330 return 0;
3331}
3332
3333/*!
3334 * \brief Queue an unhold frame on the ast_channel owner
3335 *
3336 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3337 * is active for the given call number.
3338 *
3339 * \pre Assumes lock for callno is already held.
3340 *
3341 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3342 * was valid before calling it, it may no longer be valid after calling it.
3343 * This function may unlock and lock the mutex associated with this callno,
3344 * meaning that another thread may grab it and destroy the call.
3345 */
3347{
3349 if (iaxs[callno] && iaxs[callno]->owner) {
3352 }
3353 return 0;
3354}
3355
3356/*!
3357 * \brief Queue a hangup frame on the ast_channel owner
3358 *
3359 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3360 * is active for the given call number.
3361 *
3362 * \pre Assumes lock for callno is already held.
3363 *
3364 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3365 * was valid before calling it, it may no longer be valid after calling it.
3366 * This function may unlock and lock the mutex associated with this callno,
3367 * meaning that another thread may grab it and destroy the call.
3368 */
3370{
3372 if (iaxs[callno] && iaxs[callno]->owner) {
3375 }
3376 return 0;
3377}
3378
3379/*!
3380 * \note This function assumes that iaxsl[callno] is locked when called.
3381 *
3382 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3383 * was valid before calling it, it may no longer be valid after calling it.
3384 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3385 * associated with this callno, meaning that another thread may grab it and destroy the call.
3386 */
3387static int __do_deliver(void *data)
3388{
3389 /* Just deliver the packet by using queueing. This is called by
3390 the IAX thread with the iaxsl lock held. */
3391 struct iax_frame *fr = data;
3392 fr->retrans = -1;
3395 iax2_queue_frame(fr->callno, &fr->af);
3396 /* Free our iax frame */
3397 iax2_frame_free(fr);
3398 /* And don't run again */
3399 return 0;
3400}
3401
3402static int handle_error(void)
3403{
3404 /* XXX Ideally we should figure out why an error occurred and then abort those
3405 rather than continuing to try. Unfortunately, the published interface does
3406 not seem to work XXX */
3407#if 0
3408 struct sockaddr_in *sin;
3409 int res;
3410 struct msghdr m;
3411 struct sock_extended_err e;
3412 m.msg_name = NULL;
3413 m.msg_namelen = 0;
3414 m.msg_iov = NULL;
3415 m.msg_control = &e;
3416 m.msg_controllen = sizeof(e);
3417 m.msg_flags = 0;
3418 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3419 if (res < 0)
3420 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3421 else {
3422 if (m.msg_controllen) {
3423 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3424 if (sin)
3425 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3426 else
3427 ast_log(LOG_WARNING, "No address detected??\n");
3428 } else {
3429 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3430 }
3431 }
3432#endif
3433 return 0;
3434}
3435
3436static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3437{
3438 int res;
3439 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3440
3441 if (res < 0) {
3442 ast_debug(1, "Received error: %s\n", strerror(errno));
3443 handle_error();
3444 } else
3445 res = 0;
3446 return res;
3447}
3448
3449static int send_packet(struct iax_frame *f)
3450{
3451 int res;
3452 int callno = f->callno;
3453
3454 /* Don't send if there was an error, but return error instead */
3455 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3456 return -1;
3457
3458 /* Called with iaxsl held */
3459 if (iaxdebug) {
3460 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3461 }
3462 if (f->transfer) {
3463 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3464 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3465 } else {
3466 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3467 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3468 }
3469 if (res < 0) {
3470 if (iaxdebug)
3471 ast_debug(1, "Received error: %s\n", strerror(errno));
3472 handle_error();
3473 } else
3474 res = 0;
3475
3476 return res;
3477}
3478
3479/*!
3480 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3481 * for the given call number may disappear during its execution.
3482 */
3483static int iax2_predestroy(int callno)
3484{
3485 struct ast_channel *c = NULL;
3486 struct chan_iax2_pvt *pvt = iaxs[callno];
3487
3488 if (!pvt)
3489 return -1;
3490
3491 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3494 }
3495
3496 if ((c = pvt->owner)) {
3499 pvt->owner = NULL;
3501 }
3502
3503 return 0;
3504}
3505
3506static void iax2_destroy(int callno)
3507{
3508 struct chan_iax2_pvt *pvt = NULL;
3509 struct ast_channel *owner = NULL;
3510
3511retry:
3512 if ((pvt = iaxs[callno])) {
3513#if 0
3514 /* iax2_destroy_helper gets called from this function later on. When
3515 * called twice, we get the (previously) familiar FRACK! errors in
3516 * devmode, from the scheduler. An alternative to this approach is to
3517 * reset the scheduler entries to -1 when they're deleted in
3518 * iax2_destroy_helper(). That approach was previously decided to be
3519 * "wrong" because "the memory is going to be deallocated anyway. Why
3520 * should we be resetting those values?" */
3522#endif
3523 }
3524
3525 owner = pvt ? pvt->owner : NULL;
3526
3527 if (owner) {
3528 if (ast_channel_trylock(owner)) {
3529 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3530 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3531 goto retry;
3532 }
3533 }
3534
3535 if (!owner) {
3536 iaxs[callno] = NULL;
3537 }
3538
3539 if (pvt) {
3540 if (!owner) {
3541 pvt->owner = NULL;
3542 } else {
3543 /* If there's an owner, prod it to give up */
3544 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3545 * because we already hold the owner channel lock. */
3546 ast_queue_hangup(owner);
3547 }
3548
3549 if (pvt->peercallno) {
3551 }
3552
3553 if (pvt->transfercallno) {
3555 }
3556
3557 if (!owner) {
3558 ao2_ref(pvt, -1);
3559 pvt = NULL;
3560 }
3561 }
3562
3563 if (owner) {
3564 ast_channel_unlock(owner);
3565 }
3566}
3567
3568static int update_packet(struct iax_frame *f)
3569{
3570 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3571 struct ast_iax2_full_hdr *fh = f->data;
3572 struct ast_frame af;
3573
3574 /* if frame is encrypted. decrypt before updating it. */
3575 if (f->encmethods) {
3576 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3577 }
3578 /* Mark this as a retransmission */
3579 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3580 /* Update iseqno */
3581 f->iseqno = iaxs[f->callno]->iseqno;
3582 fh->iseqno = f->iseqno;
3583
3584 /* Now re-encrypt the frame */
3585 if (f->encmethods) {
3586 /* since this is a retransmit frame, create a new random padding
3587 * before re-encrypting. */
3588 build_rand_pad(f->semirand, sizeof(f->semirand));
3589 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3590 }
3591 return 0;
3592}
3593
3594static int attempt_transmit(const void *data);
3595static void __attempt_transmit(const void *data)
3596{
3597 /* Attempt to transmit the frame to the remote peer...
3598 Called without iaxsl held. */
3599 struct iax_frame *f = (struct iax_frame *)data;
3600 int freeme = 0;
3601 int callno = f->callno;
3602
3603 /* Make sure this call is still active */
3604 if (callno)
3606 if (callno && iaxs[callno]) {
3607 if (f->retries < 0) {
3608 /* Already ACK'd */
3609 freeme = 1;
3610 } else if (f->retries >= max_retries) {
3611 /* Too many attempts. Record an error. */
3612 if (f->transfer) {
3613 /* Transfer timeout */
3615 } else if (f->final) {
3617 } else {
3618 if (iaxs[callno]->owner) {
3619 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3622 f->af.frametype,
3623 f->af.subclass.integer,
3624 f->ts,
3625 f->oseqno);
3626 }
3627 iaxs[callno]->error = ETIMEDOUT;
3628 if (iaxs[callno]->owner) {
3630 /* Hangup the fd */
3631 iax2_queue_frame(callno, &fr); /* XXX */
3632 /* Remember, owner could disappear */
3633 if (iaxs[callno] && iaxs[callno]->owner)
3635 } else {
3636 if (iaxs[callno]->reg) {
3637 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3638 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3640 }
3641 iax2_destroy(callno);
3642 }
3643 }
3644 freeme = 1;
3645 } else {
3646 /* Update it if it needs it */
3647 update_packet(f);
3648 /* Attempt transmission */
3649 send_packet(f);
3650 f->retries++;
3651 /* Try again later after 10 times as long */
3652 f->retrytime *= 10;
3653 if (f->retrytime > MAX_RETRY_TIME)
3655 /* Transfer messages max out at one second */
3656 if (f->transfer && (f->retrytime > 1000))
3657 f->retrytime = 1000;
3659 }
3660 } else {
3661 /* Make sure it gets freed */
3662 f->retries = -1;
3663 freeme = 1;
3664 }
3665
3666 if (freeme) {
3667 /* Don't attempt delivery, just remove it from the queue */
3668 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3669 ast_mutex_unlock(&iaxsl[callno]);
3670 f->retrans = -1; /* this is safe because this is the scheduled function */
3671 /* Free the IAX frame */
3672 iax2_frame_free(f);
3673 } else if (callno) {
3674 ast_mutex_unlock(&iaxsl[callno]);
3675 }
3676}
3677
3678static int attempt_transmit(const void *data)
3679{
3680#ifdef SCHED_MULTITHREADED
3682#endif
3684 return 0;
3685}
3686
3687static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3688{
3689 struct iax2_peer *peer = NULL;
3690 struct iax2_user *user = NULL;
3691 static const char * const choices[] = { "all", NULL };
3692 char *cmplt;
3693
3694 switch (cmd) {
3695 case CLI_INIT:
3696 e->command = "iax2 prune realtime";
3697 e->usage =
3698 "Usage: iax2 prune realtime [<peername>|all]\n"
3699 " Prunes object(s) from the cache\n";
3700 return NULL;
3701 case CLI_GENERATE:
3702 if (a->pos == 3) {
3703 cmplt = ast_cli_complete(a->word, choices, a->n);
3704 if (!cmplt)
3705 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3706 return cmplt;
3707 }
3708 return NULL;
3709 }
3710 if (a->argc != 4)
3711 return CLI_SHOWUSAGE;
3712 if (!strcmp(a->argv[3], "all")) {
3713 prune_users();
3714 prune_peers();
3715 ast_cli(a->fd, "Cache flushed successfully.\n");
3716 return CLI_SUCCESS;
3717 }
3718 peer = find_peer(a->argv[3], 0);
3719 user = find_user(a->argv[3]);
3720 if (peer || user) {
3721 if (peer) {
3725 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3726 } else {
3727 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3728 }
3729 peer_unref(peer);
3730 }
3731 if (user) {
3734 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3735 } else {
3736 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3737 }
3740 }
3741 } else {
3742 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3743 }
3744
3745 return CLI_SUCCESS;
3746}
3747
3748static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3749{
3750 switch (cmd) {
3751 case CLI_INIT:
3752 e->command = "iax2 test losspct";
3753 e->usage =
3754 "Usage: iax2 test losspct <percentage>\n"
3755 " For testing, throws away <percentage> percent of incoming packets\n";
3756 return NULL;
3757 case CLI_GENERATE:
3758 return NULL;
3759 }
3760 if (a->argc != 4)
3761 return CLI_SHOWUSAGE;
3762
3763 test_losspct = atoi(a->argv[3]);
3764
3765 return CLI_SUCCESS;
3766}
3767
3768#ifdef IAXTESTS
3769static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3770{
3771 switch (cmd) {
3772 case CLI_INIT:
3773 e->command = "iax2 test late";
3774 e->usage =
3775 "Usage: iax2 test late <ms>\n"
3776 " For testing, count the next frame as <ms> ms late\n";
3777 return NULL;
3778 case CLI_GENERATE:
3779 return NULL;
3780 }
3781
3782 if (a->argc != 4)
3783 return CLI_SHOWUSAGE;
3784
3785 test_late = atoi(a->argv[3]);
3786
3787 return CLI_SUCCESS;
3788}
3789
3790static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3791{
3792 switch (cmd) {
3793 case CLI_INIT:
3794 e->command = "iax2 test resync";
3795 e->usage =
3796 "Usage: iax2 test resync <ms>\n"
3797 " For testing, adjust all future frames by <ms> ms\n";
3798 return NULL;
3799 case CLI_GENERATE:
3800 return NULL;
3801 }
3802
3803 if (a->argc != 4)
3804 return CLI_SHOWUSAGE;
3805
3806 test_resync = atoi(a->argv[3]);
3807
3808 return CLI_SUCCESS;
3809}
3810
3811static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3812{
3813 switch (cmd) {
3814 case CLI_INIT:
3815 e->command = "iax2 test jitter";
3816 e->usage =
3817 "Usage: iax2 test jitter <ms> <pct>\n"
3818 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3819 " percentage of packets. If <pct> is not specified, adds\n"
3820 " jitter to all packets.\n";
3821 return NULL;
3822 case CLI_GENERATE:
3823 return NULL;
3824 }
3825
3826 if (a->argc < 4 || a->argc > 5)
3827 return CLI_SHOWUSAGE;
3828
3829 test_jit = atoi(a->argv[3]);
3830 if (a->argc == 5)
3831 test_jitpct = atoi(a->argv[4]);
3832
3833 return CLI_SUCCESS;
3834}
3835#endif /* IAXTESTS */
3836
3837/*! \brief peer_status: Report Peer status in character string */
3838/* returns 1 if peer is online, -1 if unmonitored */
3839static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3840{
3841 int res = 0;
3842 if (peer->maxms) {
3843 if (peer->lastms < 0) {
3844 ast_copy_string(status, "UNREACHABLE", statuslen);
3845 } else if (peer->lastms > peer->maxms) {
3846 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3847 res = 1;
3848 } else if (peer->lastms) {
3849 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3850 res = 1;
3851 } else {
3852 ast_copy_string(status, "UNKNOWN", statuslen);
3853 }
3854 } else {
3855 ast_copy_string(status, "Unmonitored", statuslen);
3856 res = -1;
3857 }
3858 return res;
3859}
3860
3861/*! \brief Show one peer in detail */
3862static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3863{
3864 char status[64];
3865 char cbuf[256];
3866 struct iax2_peer *peer;
3867 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3868 struct ast_str *encmethods = ast_str_alloca(256);
3869 int load_realtime = 0;
3870
3871 switch (cmd) {
3872 case CLI_INIT:
3873 e->command = "iax2 show peer";
3874 e->usage =
3875 "Usage: iax2 show peer <name>\n"
3876 " Display details on specific IAX peer\n";
3877 return NULL;
3878 case CLI_GENERATE:
3879 if (a->pos == 3)
3880 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3881 return NULL;
3882 }
3883
3884 if (a->argc < 4)
3885 return CLI_SHOWUSAGE;
3886
3887 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3888
3889 peer = find_peer(a->argv[3], load_realtime);
3890 if (peer) {
3891 char *str_addr, *str_defaddr;
3892 char *str_port, *str_defport;
3893
3894 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3895 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3896 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3897 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3898
3899 encmethods_to_str(peer->encmethods, &encmethods);
3900 ast_cli(a->fd, "\n\n");
3901 ast_cli(a->fd, " * Name : %s\n", peer->name);
3902 ast_cli(a->fd, " Description : %s\n", peer->description);
3903 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3904 ast_cli(a->fd, " Context : %s\n", peer->context);
3905 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3906 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3907 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3908 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3909 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3910 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3911 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3912 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3913 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3914 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3915 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3916 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3917 ast_cli(a->fd, " Username : %s\n", peer->username);
3918 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3919
3920 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3921 strcpy(cbuf, "Error"); /* Safe */
3922 }
3923 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3924
3925 peer_status(peer, status, sizeof(status));
3926 ast_cli(a->fd, " Status : %s\n", status);
3927 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3928 ast_cli(a->fd, "\n");
3929 peer_unref(peer);
3930 } else {
3931 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3932 ast_cli(a->fd, "\n");
3933 }
3934
3935 return CLI_SUCCESS;
3936}
3937
3938static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3939{
3940 int which = 0;
3941 struct iax2_peer *peer;
3942 char *res = NULL;
3943 int wordlen = strlen(word);
3944 struct ao2_iterator i;
3945
3946 i = ao2_iterator_init(peers, 0);
3947 while ((peer = ao2_iterator_next(&i))) {
3948 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3949 && (!flags || ast_test_flag64(peer, flags))) {
3950 res = ast_strdup(peer->name);
3951 peer_unref(peer);
3952 break;
3953 }
3954 peer_unref(peer);
3955 }
3957
3958 return res;
3959}
3960
3961static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3962{
3963 struct iax_frame *cur;
3964 int cnt = 0, dead = 0, final = 0, i = 0;
3965
3966 switch (cmd) {
3967 case CLI_INIT:
3968 e->command = "iax2 show stats";
3969 e->usage =
3970 "Usage: iax2 show stats\n"
3971 " Display statistics on IAX channel driver.\n";
3972 return NULL;
3973 case CLI_GENERATE:
3974 return NULL;
3975 }
3976
3977 if (a->argc != 3)
3978 return CLI_SHOWUSAGE;
3979
3980 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3981 ast_mutex_lock(&iaxsl[i]);
3983 if (cur->retries < 0)
3984 dead++;
3985 if (cur->final)
3986 final++;
3987 cnt++;
3988 }
3990 }
3991
3992 ast_cli(a->fd, " IAX Statistics\n");
3993 ast_cli(a->fd, "---------------------\n");
3994 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3995 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3997 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3998
4002
4003 return CLI_SUCCESS;
4004}
4005
4006/*! \brief Set trunk MTU from CLI */
4007static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4008{
4009 int mtuv;
4010
4011 switch (cmd) {
4012 case CLI_INIT:
4013 e->command = "iax2 set mtu";
4014 e->usage =
4015 "Usage: iax2 set mtu <value>\n"
4016 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
4017 " zero to disable. Disabling means that the operating system\n"
4018 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
4019 " packet exceeds the UDP payload size. This is substantially\n"
4020 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4021 " greater for G.711 samples.\n";
4022 return NULL;
4023 case CLI_GENERATE:
4024 return NULL;
4025 }
4026
4027 if (a->argc != 4)
4028 return CLI_SHOWUSAGE;
4029 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4030 mtuv = MAX_TRUNK_MTU;
4031 else
4032 mtuv = atoi(a->argv[3]);
4033
4034 if (mtuv == 0) {
4035 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4037 return CLI_SUCCESS;
4038 }
4039 if (mtuv < 172 || mtuv > 4000) {
4040 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4041 return CLI_SHOWUSAGE;
4042 }
4043 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4044 global_max_trunk_mtu = mtuv;
4045 return CLI_SUCCESS;
4046}
4047
4048static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4049{
4050 struct iax2_dpcache *dp = NULL;
4051 char tmp[1024], *pc = NULL;
4052 int s, x, y;
4053 struct timeval now = ast_tvnow();
4054
4055 switch (cmd) {
4056 case CLI_INIT:
4057 e->command = "iax2 show cache";
4058 e->usage =
4059 "Usage: iax2 show cache\n"
4060 " Display currently cached IAX Dialplan results.\n";
4061 return NULL;
4062 case CLI_GENERATE:
4063 return NULL;
4064 }
4065
4067
4068 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4069
4070 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4071 s = dp->expiry.tv_sec - now.tv_sec;
4072 tmp[0] = '\0';
4073 if (dp->flags & CACHE_FLAG_EXISTS)
4074 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4075 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4076 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4077 if (dp->flags & CACHE_FLAG_CANEXIST)
4078 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4079 if (dp->flags & CACHE_FLAG_PENDING)
4080 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4081 if (dp->flags & CACHE_FLAG_TIMEOUT)
4082 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4083 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4084 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4085 if (dp->flags & CACHE_FLAG_MATCHMORE)
4086 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4087 if (dp->flags & CACHE_FLAG_UNKNOWN)
4088 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4089 /* Trim trailing pipe */
4090 if (!ast_strlen_zero(tmp)) {
4091 tmp[strlen(tmp) - 1] = '\0';
4092 } else {
4093 ast_copy_string(tmp, "(none)", sizeof(tmp));
4094 }
4095 y = 0;
4096 pc = strchr(dp->peercontext, '@');
4097 if (!pc) {
4098 pc = dp->peercontext;
4099 } else {
4100 pc++;
4101 }
4102 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4103 if (dp->waiters[x] > -1)
4104 y++;
4105 }
4106 if (s > 0) {
4107 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4108 } else {
4109 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4110 }
4111 }
4112
4114
4115 return CLI_SUCCESS;
4116}
4117
4118static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4119
4120static void unwrap_timestamp(struct iax_frame *fr)
4121{
4122 /* Video mini frames only encode the lower 15 bits of the session
4123 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4124 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4125 const int lower_mask = (1 << ts_shift) - 1;
4126 const int upper_mask = ~lower_mask;
4127 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4128
4129 if ( (fr->ts & upper_mask) == last_upper ) {
4130 const int x = fr->ts - iaxs[fr->callno]->last;
4131 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4132
4133 if (x < -threshold) {
4134 /* Sudden big jump backwards in timestamp:
4135 What likely happened here is that miniframe timestamp has circled but we haven't
4136 gotten the update from the main packet. We'll just pretend that we did, and
4137 update the timestamp appropriately. */
4138 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4139 if (iaxdebug)
4140 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4141 } else if (x > threshold) {
4142 /* Sudden apparent big jump forwards in timestamp:
4143 What's likely happened is this is an old miniframe belonging to the previous
4144 top 15 or 16-bit timestamp that has turned up out of order.
4145 Adjust the timestamp appropriately. */
4146 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4147 if (iaxdebug)
4148 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4149 }