Asterisk - The Open Source Telephony Project GIT-master-590b490
Loading...
Searching...
No Matches
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 <since>
129 <version>1.6.1.0</version>
130 </since>
131 <synopsis>
132 Provision a calling IAXy with a given template.
133 </synopsis>
134 <syntax>
135 <parameter name="template">
136 <para>If not specified, defaults to <literal>default</literal>.</para>
137 </parameter>
138 </syntax>
139 <description>
140 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
141 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
142 or <literal>0</literal> on success.</para>
143 </description>
144 </application>
145 <function name="IAXPEER" language="en_US">
146 <since>
147 <version>1.2.0</version>
148 </since>
149 <synopsis>
150 Gets IAX peer information.
151 </synopsis>
152 <syntax>
153 <parameter name="peername" required="true">
154 <enumlist>
155 <enum name="CURRENTCHANNEL">
156 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
157 endpoint of the current channel</para>
158 </enum>
159 </enumlist>
160 </parameter>
161 <parameter name="item">
162 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
163 <enumlist>
164 <enum name="ip">
165 <para>(default) The IP address.</para>
166 </enum>
167 <enum name="status">
168 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
169 </enum>
170 <enum name="mailbox">
171 <para>The configured mailbox.</para>
172 </enum>
173 <enum name="context">
174 <para>The configured context.</para>
175 </enum>
176 <enum name="expire">
177 <para>The epoch time of the next expire.</para>
178 </enum>
179 <enum name="dynamic">
180 <para>Is it dynamic? (yes/no).</para>
181 </enum>
182 <enum name="callerid_name">
183 <para>The configured Caller ID name.</para>
184 </enum>
185 <enum name="callerid_num">
186 <para>The configured Caller ID number.</para>
187 </enum>
188 <enum name="codecs">
189 <para>The configured codecs.</para>
190 </enum>
191 <enum name="codec[x]">
192 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
193 with <literal>0</literal>)</para>
194 </enum>
195 </enumlist>
196 </parameter>
197 </syntax>
198 <description>
199 <para>Gets information associated with the specified IAX2 peer.</para>
200 </description>
201 </function>
202 <function name="IAXVAR" language="en_US">
203 <since>
204 <version>1.6.0</version>
205 </since>
206 <synopsis>
207 Sets or retrieves a remote variable.
208 </synopsis>
209 <syntax>
210 <parameter name="varname" required="true" />
211 </syntax>
212 <description>
213 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
214 </description>
215 </function>
216 <info name="CHANNEL" language="en_US" tech="IAX">
217 <enumlist>
218 <enum name="osptoken">
219 <para>R/O Get the peer's osptoken.</para>
220 </enum>
221 <enum name="peerip">
222 <para>R/O Get the peer's ip address.</para>
223 </enum>
224 <enum name="peername">
225 <para>R/O Get the peer's username.</para>
226 </enum>
227 <enum name="auth_method">
228 <para>R/O Get the authentication method used for the call.</para>
229 <enumlist>
230 <enum name="none"/>
231 <enum name="plaintext"/>
232 <enum name="MD5"/>
233 <enum name="RSA"/>
234 </enumlist>
235 </enum>
236 <enum name="secure_signaling">
237 <para>R/O Get if the IAX channel is secured (encryption used for the call).</para>
238 <para>Because IAX encryption applies to both signaling and media, this setting
239 provides the same value as <literal>secure_media</literal>.</para>
240 </enum>
241 <enum name="secure_media">
242 <para>R/O Get if the IAX channel is secured (encryption used for the call).</para>
243 <para>Because IAX encryption applies to both signaling and media, this setting
244 provides the same value as <literal>secure_signaling</literal>.</para>
245 </enum>
246 </enumlist>
247 </info>
248 <info name="Dial_Resource" language="en_US" tech="IAX2">
249 <para>The general syntax is:</para>
250 <para><literal>Dial(IAX2/[username[:password[:pubkey]]@]peer[:port][/exten[@context]][/options]</literal></para>
251 <para>The IAX username is optionally followed by either the secret or name of the keypair to use for RSA
252 authentication (within square brakcets). If both need to be provided (such as for encrypted calls that
253 are RSA authenticated), both may be specified in either order.</para>
254 <para>IAX2 optionally allows modifiers to be specified after the extension.</para>
255 <enumlist>
256 <enum name="a">
257 <para>Request auto answer (supporting equipment/configuration required)</para>
258 </enum>
259 </enumlist>
260 </info>
261 <manager name="IAXpeers" language="en_US">
262 <since>
263 <version>0.3.0</version>
264 </since>
265 <synopsis>
266 List IAX peers.
267 </synopsis>
268 <syntax>
269 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
270 </syntax>
271 <description>
272 </description>
273 </manager>
274 <manager name="IAXpeerlist" language="en_US">
275 <since>
276 <version>1.6.0</version>
277 </since>
278 <synopsis>
279 List IAX Peers.
280 </synopsis>
281 <syntax>
282 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
283 </syntax>
284 <description>
285 <para>List all the IAX peers.</para>
286 </description>
287 </manager>
288 <manager name="IAXnetstats" language="en_US">
289 <since>
290 <version>1.2.0</version>
291 </since>
292 <synopsis>
293 Show IAX Netstats.
294 </synopsis>
295 <syntax />
296 <description>
297 <para>Show IAX channels network statistics.</para>
298 </description>
299 </manager>
300 <manager name="IAXregistry" language="en_US">
301 <since>
302 <version>1.6.2.0</version>
303 </since>
304 <synopsis>
305 Show IAX registrations.
306 </synopsis>
307 <syntax>
308 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
309 </syntax>
310 <description>
311 <para>Show IAX registrations.</para>
312 </description>
313 </manager>
314 ***/
315
316/* Define SCHED_MULTITHREADED to run the scheduler in a special
317 multithreaded mode. */
318#define SCHED_MULTITHREADED
319
320/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
321 thread is actually doing. */
322#define DEBUG_SCHED_MULTITHREAD
323
324
325#ifdef SO_NO_CHECK
326static int nochecksums = 0;
327#endif
328
329#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
330#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
331
332#define DEFAULT_THREAD_COUNT 10
333#define DEFAULT_MAX_THREAD_COUNT 100
334#define DEFAULT_RETRY_TIME 1000
335#define MEMORY_SIZE 100
336#define DEFAULT_DROP 3
337
338#define DEBUG_SUPPORT
339
340#define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
341
342/* Sample over last 100 units to determine historic jitter */
343#define GAMMA (0.01)
344
346
347static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
348
349
350/*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
351 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
352#define MAX_TRUNK_MTU 1240
353
354static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
355static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
356
357#define DEFAULT_CONTEXT "default"
358
360
361static char language[MAX_LANGUAGE] = "";
362static char regcontext[AST_MAX_CONTEXT] = "";
363
364static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
365static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
367
368static int maxauthreq = 3;
369static int max_retries = 4;
370static int ping_time = 21;
371static int lagrq_time = 10;
372static int maxjitterbuffer=1000;
373static int resyncthreshold=1000;
374static int maxjitterinterps=10;
375static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
376
377#define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
378
379static int trunkfreq = 20;
381
382static int authdebug = 0;
383static int autokill = 0;
384static int iaxcompat = 0;
385static int last_authmethod = 0;
386
387static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
388
389static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
390
391static struct {
392 unsigned int tos;
393 unsigned int cos;
394} qos = { 0, 0 };
395
396static int min_reg_expire;
397static int max_reg_expire;
398
399static int srvlookup = 0;
400
401static struct ast_timer *timer; /* Timer for trunking */
402
404static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
405static int defaultsockfd = -1;
406
407static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
408
409/* Ethernet, etc */
410#define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
411/* T1, maybe ISDN */
412#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
413 ~AST_FORMAT_SLIN & \
414 ~AST_FORMAT_SLIN16 & \
415 ~AST_FORMAT_SIREN7 & \
416 ~AST_FORMAT_SIREN14 & \
417 ~AST_FORMAT_G719 & \
418 ~AST_FORMAT_ULAW & \
419 ~AST_FORMAT_ALAW & \
420 ~AST_FORMAT_G722)
421/* A modem */
422#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
423 ~AST_FORMAT_G726 & \
424 ~AST_FORMAT_G726_AAL2 & \
425 ~AST_FORMAT_ADPCM)
426
427#define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
428 ~AST_FORMAT_G723)
429
430
431#define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
432#define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
433#define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
434
435/*! \brief Name of effective auth method */
436static const char *auth_method_labels[] = {
437 [0] = "none",
438 [IAX_AUTH_PLAINTEXT] = "plaintext",
439 [IAX_AUTH_MD5] = "MD5",
440 [IAX_AUTH_RSA] = "RSA",
441};
442
443/* Max length is length of |RSA|MD5|plaintext (18 + 1 for NUL = 19) */
444#define AUTH_METHOD_NAMES_BUFSIZE 19
445
446/*!
447 * \brief Get names of all auth methods
448 * \param Bit field of auth methods
449 * \param[out] buf Buffer into which to write the names. Must be of size AUTH_METHOD_NAMES_BUFSIZE.
450 * \return Auth methods name
451 */
452static char *auth_method_names(int authmethods, char *restrict buf)
453{
454 char *pos = buf;
455
456 *pos = '\0';
457
458 if (authmethods & IAX_AUTH_RSA) {
459 pos += sprintf(pos, "|RSA");
460 }
461 if (authmethods & IAX_AUTH_MD5) {
462 pos += sprintf(pos, "|MD5");
463 }
464 if (authmethods & IAX_AUTH_PLAINTEXT) {
465 pos += sprintf(pos, "|plaintext");
466 }
467
468 if (pos == buf) { /* No auth methods */
469 strcpy(buf, "none");
470 return buf;
471 }
472
473 return buf + 1; /* Skip leading | */
474}
475
476/* if a pvt has encryption setup done and is running on the call */
477#define IAX_CALLENCRYPTED(pvt) \
478 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
479
480#define IAX_DEBUGDIGEST(msg, key) do { \
481 int idx; \
482 char digest[33] = ""; \
483 \
484 if (!iaxdebug) \
485 break; \
486 \
487 for (idx = 0; idx < 16; idx++) \
488 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
489 \
490 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
491 } while(0)
492
493static struct io_context *io;
495
497
498static int iaxdebug = 0;
499
500static int iaxtrunkdebug = 0;
501
502static int test_losspct = 0;
503#ifdef IAXTESTS
504static int test_late = 0;
505static int test_resync = 0;
506static int test_jit = 0;
507static int test_jitpct = 0;
508#endif /* IAXTESTS */
509
513static int amaflags = 0;
514static int adsi = 0;
515static int delayreject = 0;
516static int iax2_encryption = 0;
517static int iax2_authmethods = 0;
518
519static struct ast_flags64 globalflags = { 0 };
520
522
526 IAX_STATE_TBD = (1 << 2),
527};
528
533
534
535#define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
536#define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
537#define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
538#define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
539#define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
540#define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
541#define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
542#define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
543#define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
544#define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
545#define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
546#define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
547#define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
548#define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
549#define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
550#define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
551#define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
552#define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
553#define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
554#define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
555#define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
556#define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
557#define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
558#define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
559#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 */
560#define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
561#define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
562#define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
563#define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
564#define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
565#define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
566static int global_rtautoclear = 120;
567
568static int reload_config(int forced_reload);
569
570/*!
571 * \brief Call token validation settings.
572 */
574 /*! \brief Default calltoken required unless the ip is in the ignorelist */
576 /*! \brief Require call token validation. */
578 /*! \brief Require call token validation after a successful registration
579 * using call token validation occurs. */
581 /*! \brief Do not require call token validation. */
583};
584
585struct iax2_user {
593 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
597 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
598 );
599
603 int adsi;
604 uint64_t flags;
606 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
607 int curauthreq; /*!< Current number of outstanding AUTHREQs */
612 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
613};
614
615struct iax2_peer {
619 AST_STRING_FIELD(description); /*!< Description of the peer */
622 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
623
624 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
625 AST_STRING_FIELD(context); /*!< For transfers only */
626 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
627 AST_STRING_FIELD(mailbox); /*!< Mailbox */
630 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
631 /* Suggested caller id if registering */
632 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
633 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
634 AST_STRING_FIELD(zonetag); /*!< Time Zone */
635 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
636 );
638 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
641 int sockfd; /*!< Socket to use for transmission */
643 int adsi;
644 uint64_t flags;
645
646 /* Dynamic Registration fields */
647 struct ast_sockaddr defaddr; /*!< Default address if there is one */
648 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
649 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
650
651 int expire; /*!< Schedule entry for expiry */
652 int expiry; /*!< How soon to expire */
653 iax2_format capability; /*!< Capability */
654
655 /* Qualification */
656 int callno; /*!< Call number of POKE request */
657 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
658 int lastms; /*!< How long last response took (in ms), or -1 for no response */
659 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
660
661 int pokefreqok; /*!< How often to check if the host is up */
662 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
663 int historicms; /*!< How long recent average responses took */
664 int smoothing; /*!< Sample over how many units to determine historic ms */
665 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
666
667 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
668
670 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
671
672 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
673};
674
675#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
676
681 struct timeval txtrunktime; /*!< Transmit trunktime */
682 struct timeval rxtrunktime; /*!< Receive trunktime */
683 struct timeval lasttxtime; /*!< Last transmitted trunktime */
684 struct timeval trunkact; /*!< Last trunk activity */
685 unsigned int lastsent; /*!< Last sent time */
686 /* Trunk data and length */
687 unsigned char *trunkdata;
688 unsigned int trunkdatalen;
689 unsigned int trunkdataalloc;
692 int calls;
694};
695
697
707
721
723 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
724 char username[80];
725 char secret[80]; /*!< Password or key name in []'s */
726 int expire; /*!< Sched ID of expiration */
727 int refresh; /*!< How often to refresh */
729 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
730 int callno; /*!< Associated call number if applicable */
731 struct ast_sockaddr us; /*!< Who the server thinks we are */
732 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
734 int port;
735 char hostname[];
736};
737
739
740/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
741#define MIN_RETRY_TIME 100
742#define MAX_RETRY_TIME 10000
743
744#define MAX_JITTER_BUFFER 50
745#define MIN_JITTER_BUFFER 10
746
747#define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
748
749#define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
750
751/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
752#define TS_GAP_FOR_JB_RESYNC 5000
753
754/* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
755#define MARK_IAX_SUBCLASS_TX 0x8000
756
760static int iaxdynamicthreadnum = 0;
761static int iaxactivethreadcount = 0;
762
763struct iax_rr {
768 int delay;
770 int ooo;
771};
772
773struct iax2_pvt_ref;
774
775/* We use the high order bit as the validated flag, and the lower 15 as the
776 * actual call number */
777typedef uint16_t callno_entry;
778
780 /*! Socket to send/receive on for this call */
782 /*! ast_callid bound to dialog */
784 /*! Last received voice format */
786 /*! Last received video format */
788 /*! Last sent voice format */
790 /*! Last sent video format */
792 /*! What we are capable of sending */
794 /*! Last received timestamp */
795 unsigned int last;
796 /*! Last sent timestamp - never send the same timestamp twice in a single call */
797 unsigned int lastsent;
798 /*! Timestamp of the last video frame sent */
799 unsigned int lastvsent;
800 /*! Next outgoing timestamp if everything is good */
801 unsigned int nextpred;
802 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
804 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
806 /*! True if the last voice we transmitted was not silence/CNG */
807 unsigned int notsilenttx:1;
808 /*! Ping time */
809 unsigned int pingtime;
810 /*! Max time for initial response */
812 /*! Peer Address */
814 /*! Actual used codec preferences */
816 /*! Requested codec preferences */
818 /*! Our call number */
819 unsigned short callno;
820 /*! Our callno_entry entry */
822 /*! Peer callno */
823 unsigned short peercallno;
824 /*! Negotiated format, this is only used to remember what format was
825 chosen for an unauthenticated call so that the channel can get
826 created later using the right format. We also use it for
827 authenticated calls to check the format from __get_from_jb. */
829 /*! Peer selected format */
831 /*! Peer capability */
833 /*! timeval that we base our transmission on */
834 struct timeval offset;
835 /*! timeval that we base our delivery on */
836 struct timeval rxcore;
837 /*! The jitterbuffer */
839 /*! active jb read scheduler id */
840 int jbid;
841 /*! LAG */
842 int lag;
843 /*! Error, as discovered by the manager */
844 int error;
845 /*! Owner if we have one */
847 /*! What's our state? */
849 /*! Expiry (optional) */
851 /*! Next outgoing sequence number */
852 unsigned char oseqno;
853 /*! Next sequence number they have not yet acknowledged */
854 unsigned char rseqno;
855 /*! Next incoming sequence number */
856 unsigned char iseqno;
857 /*! Last incoming sequence number we have acknowledged */
858 unsigned char aseqno;
859
861 /*! Peer name */
863 /*! Default Context */
865 /*! Caller ID if available */
868 /*! Hidden Caller ID (i.e. ANI) if appropriate */
870 /*! DNID */
872 /*! RDNIS */
874 /*! Requested Extension */
876 /*! Expected Username */
878 /*! Expected Secret */
880 /*! MD5 challenge */
882 /*! Public keys permitted keys for incoming authentication */
884 /*! Private key for outgoing authentication */
886 /*! Preferred language */
888 /*! Hostname/peername for naming purposes */
890
895 /*! received OSP token */
897 /*! Default parkinglot */
899 );
900 /*! AUTHREJ all AUTHREP frames */
902 /*! permitted authentication methods */
904 /*! effective authentication method */
906 /*! permitted encryption methods */
908 /*! Encryption AES-128 Key */
910 /*! Decryption AES-128 Key corresponding to ecx */
912 /*! Decryption AES-128 Key used to decrypt peer frames */
914 /*! scheduler id associated with iax_key_rotate
915 * for encrypted calls*/
917 /*! 32 bytes of semi-random data */
918 unsigned char semirand[32];
919 /*! Associated registry */
921 /*! Associated peer for poking */
923 /*! IAX_ flags */
924 uint64_t flags;
925 int adsi;
926
927 /*! Transferring status */
929 /*! Transfer identifier */
931 /*! Who we are IAX transferring to */
933 /*! What's the new call number for the transfer */
934 unsigned short transfercallno;
935 /*! Transfer encrypt AES-128 Key */
937
938 /*! Status of knowledge of peer ADSI capability */
940
941 /*! Callno of native bridge peer. (Valid if nonzero) */
942 unsigned short bridgecallno;
943
944 int pingid; /*!< Transmit PING request */
945 int lagid; /*!< Retransmit lag request */
946 int autoid; /*!< Auto hangup for Dialplan requestor */
947 int authid; /*!< Authentication rejection ID */
948 int authfail; /*!< Reason to report failure */
949 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
956 /*! variables inherited from the user definition */
958 /*! variables transmitted in a NEW packet */
960 /*! last received remote rr */
962 /*! Current base time: (just for stats) */
963 int min;
964 /*! Dropped frame count: (just for stats) */
966 /*! received frame count: (just for stats) */
968 /*! Destroying this call initiated. */
970 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
971 unsigned char calltoken_ie_len;
972 /*! hold all signaling frames from the pbx thread until we have a destination callno */
974 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
976};
977
982
987
988#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
989#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
990
991#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
992#define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
993#define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
994
1000
1002
1003/*! table of available call numbers */
1005
1006/*! table of available trunk call numbers */
1008
1009/*!
1010 * \brief a list of frames that may need to be retransmitted
1011 *
1012 * \note The contents of this list do not need to be explicitly destroyed
1013 * on module unload. This is because all active calls are destroyed, and
1014 * all frames in this queue will get destroyed as a part of that process.
1015 *
1016 * \note Contents protected by the iaxsl[] locks
1017 */
1019
1021
1023
1024static time_t max_calltoken_delay = 10;
1025
1026/*!
1027 * This module will get much higher performance when doing a lot of
1028 * user and peer lookups if the number of buckets is increased from 1.
1029 * However, to maintain old behavior for Asterisk 1.4, these are set to
1030 * 1 by default. When using multiple buckets, search order through these
1031 * containers is considered random, so you will not be able to depend on
1032 * the order the entries are specified in iax.conf for matching order. */
1033#ifdef LOW_MEMORY
1034#define MAX_PEER_BUCKETS 17
1035#else
1036#define MAX_PEER_BUCKETS 563
1037#endif
1038static struct ao2_container *peers;
1039
1040#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
1041static struct ao2_container *users;
1042
1043/*! Table containing peercnt objects for every ip address consuming a callno */
1045
1046/*! Table containing custom callno limit rules for a range of ip addresses. */
1048
1049/*! Table containing ip addresses not requiring calltoken validation */
1051
1052static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
1053
1054static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
1055
1056static uint16_t global_maxcallno;
1057
1058/*! Total num of call numbers allowed to be allocated without calltoken validation */
1060
1061static uint16_t total_nonval_callno_used = 0;
1062
1063/*! peer connection private, keeps track of all the call numbers
1064 * consumed by a single ip address */
1065struct peercnt {
1066 /*! ip address consuming call numbers */
1068 /*! Number of call numbers currently used by this ip address */
1069 uint16_t cur;
1070 /*! Max call numbers allowed for this ip address */
1071 uint16_t limit;
1072 /*! Specifies whether limit is set by a registration or not, if so normal
1073 * limit setting rules do not apply to this address. */
1074 unsigned char reg;
1075};
1076
1077/*! used by both callno_limits and calltoken_ignores containers */
1079 /*! ip address range for custom callno limit rule */
1080 struct ast_ha ha;
1081 /*! callno limit for this ip address range, only used in callno_limits container */
1082 uint16_t limit;
1083 /*! delete me marker for reloads */
1084 unsigned char delme;
1085};
1086
1087enum {
1088 /*! Extension exists */
1090 /*! Extension is nonexistent */
1092 /*! Extension can exist */
1094 /*! Waiting to hear back response */
1096 /*! Timed out */
1098 /*! Request transmitted */
1100 /*! Timeout */
1102 /*! Matchmore */
1104};
1105
1117
1119
1120static void reg_source_db(struct iax2_peer *p);
1121static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1122static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1123
1124static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1125static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1126static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1127
1134
1139
1142 size_t len;
1143 unsigned char buf[1];
1144};
1145
1150#ifdef SCHED_MULTITHREADED
1151 void (*schedfunc)(const void *);
1152 const void *scheddata;
1153#endif
1154#ifdef DEBUG_SCHED_MULTITHREAD
1155 char curfunc[80];
1156#endif
1158 pthread_t threadid;
1161 unsigned char readbuf[4096];
1162 unsigned char *buf;
1163 ssize_t buf_len;
1164 size_t buf_size;
1165 int iofd;
1171 /*! if this thread is processing a full frame,
1172 some information about that frame will be stored
1173 here, so we can avoid dispatching any more full
1174 frames for that callno to other threads */
1175 struct {
1176 unsigned short callno;
1177 struct ast_sockaddr addr;
1178 unsigned char type;
1179 unsigned char csub;
1181 /*! Queued up full frames for processing. If more full frames arrive for
1182 * a call which this thread is already processing a full frame for, they
1183 * are queued up here. */
1185 unsigned char stop;
1186};
1187
1188/* Thread lists */
1192
1193static void *iax2_process_thread(void *data);
1194static void iax2_destroy(int callno);
1195
1202
1203/*!
1204 * \brief an array of iax2 pvt structures
1205 *
1206 * The container for active chan_iax2_pvt structures is implemented as an
1207 * array for extremely quick direct access to the correct pvt structure
1208 * based on the local call number. The local call number is used as the
1209 * index into the array where the associated pvt structure is stored.
1210 */
1212
1214{
1215 return iaxs[callno]->callid;
1216}
1217
1219{
1221}
1222
1224{
1226 char buffer[AST_CALLID_BUFFER_LENGTH];
1227 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1229}
1230
1231/*!
1232 * \brief Another container of iax2_pvt structures
1233 *
1234 * Active IAX2 pvt structs are also stored in this container, if they are a part
1235 * of an active call where we know the remote side's call number. The reason
1236 * for this is that incoming media frames do not contain our call number. So,
1237 * instead of having to iterate the entire iaxs array, we use this container to
1238 * look up calls where the remote side is using a given call number.
1239 */
1241
1242/*!
1243 * \brief chan_iax2_pvt structure locks
1244 *
1245 * These locks are used when accessing a pvt structure in the iaxs array.
1246 * The index used here is the same as used in the iaxs array. It is the
1247 * local call number for the associated pvt struct.
1248 */
1250
1251/*!
1252 * \brief Another container of iax2_pvt structures
1253 *
1254 * Active IAX2 pvt structs used during transferring a call are stored here.
1255 */
1257
1258/* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1259 but keeps the division between trunked and non-trunked better. */
1260#define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1261
1262/* Debug routines... */
1264
1265static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1266{
1267 if (iaxdebug ||
1268 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1271 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1272
1273 if (iaxdebug) {
1274 iax_showframe(f, fhi, rx, addr, datalen);
1275 } else {
1276 iaxdebug = 1;
1277 iax_showframe(f, fhi, rx, addr, datalen);
1278 iaxdebug = 0;
1279 }
1280 }
1281}
1282
1283static void iax_debug_output(const char *data)
1284{
1285 if (iaxdebug)
1286 ast_verbose("%s", data);
1287}
1288
1289static void iax_error_output(const char *data)
1290{
1291 ast_log(LOG_WARNING, "%s", data);
1292}
1293
1294static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1295{
1296 va_list args;
1297 char buf[1024];
1298
1299 va_start(args, fmt);
1300 vsnprintf(buf, sizeof(buf), fmt, args);
1301 va_end(args);
1302
1303 ast_log(LOG_ERROR, "%s", buf);
1304}
1305
1306static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1307{
1308 va_list args;
1309 char buf[1024];
1310
1311 va_start(args, fmt);
1312 vsnprintf(buf, sizeof(buf), fmt, args);
1313 va_end(args);
1314
1315 ast_log(LOG_WARNING, "%s", buf);
1316}
1317
1318static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1319{
1320 va_list args;
1321 char buf[1024];
1322
1323 va_start(args, fmt);
1324 vsnprintf(buf, sizeof(buf), fmt, args);
1325 va_end(args);
1326
1327 ast_verbose("%s", buf);
1328}
1329
1330static int expire_registry(const void *data);
1331static int iax2_answer(struct ast_channel *c);
1332static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1333static int iax2_devicestate(const char *data);
1334static int iax2_digit_begin(struct ast_channel *c, char digit);
1335static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1336static int iax2_do_register(struct iax2_registry *reg);
1337static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1338static int iax2_hangup(struct ast_channel *c);
1339static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1340static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1341static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1342static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1343static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1344static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1345static int iax2_sendtext(struct ast_channel *c, const char *text);
1346static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1347static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1348static int iax2_transfer(struct ast_channel *c, const char *dest);
1349static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1350static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1351
1352static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1353static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1354static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1355static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1356static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1357static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1358static 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);
1359static struct ast_frame *iax2_read(struct ast_channel *c);
1360static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1361static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1362static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1363static void *iax2_dup_variable_datastore(void *);
1364static void prune_peers(void);
1365static void prune_users(void);
1366static void iax2_free_variable_datastore(void *);
1367
1368static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1369static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1370static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1371static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1372static void build_rand_pad(unsigned char *buf, ssize_t len);
1373static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1374static int replace_callno(const void *obj);
1375static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1376static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1377static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1378
1380 .type = "IAX2",
1381 .description = tdesc,
1382 .properties = AST_CHAN_TP_WANTSJITTER,
1383 .requester = iax2_request,
1384 .devicestate = iax2_devicestate,
1385 .send_digit_begin = iax2_digit_begin,
1386 .send_digit_end = iax2_digit_end,
1387 .send_text = iax2_sendtext,
1388 .send_image = iax2_sendimage,
1389 .send_html = iax2_sendhtml,
1390 .call = iax2_call,
1391 .hangup = iax2_hangup,
1392 .answer = iax2_answer,
1393 .read = iax2_read,
1394 .write = iax2_write,
1395 .write_video = iax2_write,
1396 .indicate = iax2_indicate,
1397 .setoption = iax2_setoption,
1398 .queryoption = iax2_queryoption,
1399 .transfer = iax2_transfer,
1400 .fixup = iax2_fixup,
1401 .func_channel_read = acf_channel_read,
1402};
1403
1404/*!
1405 * \internal
1406 * \brief Obtain the owner channel lock if the owner exists.
1407 *
1408 * \param callno IAX2 call id.
1409 *
1410 * \note Assumes the iaxsl[callno] lock is already obtained.
1411 *
1412 * \note
1413 * IMPORTANT NOTE!!! Any time this function is used, even if
1414 * iaxs[callno] was valid before calling it, it may no longer be
1415 * valid after calling it. This function may unlock and lock
1416 * the mutex associated with this callno, meaning that another
1417 * thread may grab it and destroy the call.
1418 */
1419static void iax2_lock_owner(int callno)
1420{
1421 for (;;) {
1422 if (!iaxs[callno] || !iaxs[callno]->owner) {
1423 /* There is no owner lock to get. */
1424 break;
1425 }
1426 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1427 /* We got the lock */
1428 break;
1429 }
1430 /* Avoid deadlock by pausing and trying again */
1431 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1432 }
1433}
1434
1435/*!
1436 * \internal
1437 * \brief Check if a control subtype is allowed on the wire.
1438 *
1439 * \param subtype Control frame subtype to check if allowed to/from the wire.
1440 *
1441 * \retval non-zero if allowed.
1442 */
1443static int iax2_is_control_frame_allowed(int subtype)
1444{
1445 enum ast_control_frame_type control = subtype;
1446 int is_allowed;
1447
1448 /*
1449 * Note: If we compare the enumeration type, which does not have any
1450 * negative constants, the compiler may optimize this code away.
1451 * Therefore, we must perform an integer comparison here.
1452 */
1453 if (subtype == -1) {
1454 return -1;
1455 }
1456
1457 /* Default to not allowing control frames to pass. */
1458 is_allowed = 0;
1459
1460 /*
1461 * The switch default is not present in order to take advantage
1462 * of the compiler complaining of a missing enum case.
1463 */
1464 switch (control) {
1465 /*
1466 * These control frames make sense to send/receive across the link.
1467 */
1468 case AST_CONTROL_HANGUP:
1469 case AST_CONTROL_RING:
1471 case AST_CONTROL_ANSWER:
1472 case AST_CONTROL_BUSY:
1476 case AST_CONTROL_FLASH:
1477 case AST_CONTROL_WINK:
1478 case AST_CONTROL_OPTION:
1483 case AST_CONTROL_HOLD:
1484 case AST_CONTROL_UNHOLD:
1489 case AST_CONTROL_AOC:
1491 case AST_CONTROL_MCID:
1492 is_allowed = -1;
1493 break;
1494
1495 /*
1496 * These control frames do not make sense to send/receive across the link.
1497 */
1499 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1501 /* Across an IAX link the source is still the same. */
1503 /* A success/fail status report from calling ast_transfer() on this machine. */
1504 case AST_CONTROL_CC:
1505 /* The payload contains pointers that are valid for the sending machine only. */
1507 /* Across an IAX link the source is still the same. */
1509 /* The action can only be done by the sending machine. */
1511 /* This frame would cause the call to unexpectedly hangup. */
1513 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1515 /* Intended only for the sending machine's local channel structure. */
1517 /* Intended only for masquerades when calling ast_indicate_data(). */
1519 /* Intended only for internal stream topology manipulation. */
1521 /* Intended only for internal stream topology change notification. */
1528 case AST_CONTROL_PLAYBACK_BEGIN: /* Only supported by app_dial currently */
1529 /* None of these playback stream control frames should go across the link. */
1534 /* None of these media recording control frames should go across the link. */
1535 break;
1536 }
1537 return is_allowed;
1538}
1539
1549
1554
1564
1569
1570static int network_change_sched_cb(const void *data)
1571{
1572 struct iax2_registry *reg;
1576 iax2_do_register(reg);
1577 }
1579
1580 return 0;
1581}
1582
1583static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1584 struct stasis_message *message)
1585{
1586 /* This callback is only concerned with network change messages from the system topic. */
1588 return;
1589 }
1590
1591 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1592 if (network_change_sched_id == -1) {
1594 }
1595}
1596
1597static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1598 struct stasis_message *message)
1599{
1601 return;
1602 }
1603
1604 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1605 reload_config(1);
1606}
1607
1609 .type = "IAX2_VARIABLE",
1610 .duplicate = iax2_dup_variable_datastore,
1612};
1613
1614static void *iax2_dup_variable_datastore(void *old)
1615{
1616 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1617 struct ast_var_t *oldvar, *newvar;
1618
1619 newlist = ast_calloc(sizeof(*newlist), 1);
1620 if (!newlist) {
1621 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1622 return NULL;
1623 }
1624
1625 AST_LIST_HEAD_INIT(newlist);
1626 AST_LIST_LOCK(oldlist);
1627 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1628 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1629 if (newvar)
1630 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1631 else
1632 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1633 }
1634 AST_LIST_UNLOCK(oldlist);
1635 return newlist;
1636}
1637
1638static void iax2_free_variable_datastore(void *old)
1639{
1640 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1641 struct ast_var_t *oldvar;
1642
1643 AST_LIST_LOCK(oldlist);
1644 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1645 ast_free(oldvar);
1646 }
1647 AST_LIST_UNLOCK(oldlist);
1648 AST_LIST_HEAD_DESTROY(oldlist);
1649 ast_free(oldlist);
1650}
1651
1652
1653/* WARNING: insert_idle_thread should only ever be called within the
1654 * context of an iax2_process_thread() thread.
1655 */
1657{
1658 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1662 } else {
1666 }
1667
1668 return;
1669}
1670
1671static struct iax2_thread *find_idle_thread(void)
1672{
1673 struct iax2_thread *thread = NULL;
1674
1675 /* Pop the head of the idle list off */
1679
1680 /* If we popped a thread off the idle list, just return it */
1681 if (thread) {
1682 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1683 return thread;
1684 }
1685
1686 /* Pop the head of the dynamic list off */
1690
1691 /* If we popped a thread off the dynamic list, just return it */
1692 if (thread) {
1693 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1694 return thread;
1695 }
1696
1697 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1699 return NULL;
1700
1701 /* Set default values */
1705
1706 /* Initialize lock and condition */
1707 ast_mutex_init(&thread->lock);
1708 ast_cond_init(&thread->cond, NULL);
1709 ast_mutex_init(&thread->init_lock);
1710 ast_cond_init(&thread->init_cond, NULL);
1711 ast_mutex_lock(&thread->init_lock);
1712
1713 /* Create thread and send it on it's way */
1715 ast_cond_destroy(&thread->cond);
1716 ast_mutex_destroy(&thread->lock);
1717 ast_mutex_unlock(&thread->init_lock);
1718 ast_cond_destroy(&thread->init_cond);
1719 ast_mutex_destroy(&thread->init_lock);
1721 return NULL;
1722 }
1723
1724 /* this thread is not processing a full frame (since it is idle),
1725 so ensure that the field for the full frame call number is empty */
1726 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1727
1728 /* Wait for the thread to be ready before returning it to the caller */
1729 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1730
1731 /* Done with init_lock */
1732 ast_mutex_unlock(&thread->init_lock);
1733
1734 return thread;
1735}
1736
1737#ifdef SCHED_MULTITHREADED
1738static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1739{
1740 struct iax2_thread *thread;
1741 static time_t lasterror;
1742 time_t t;
1743
1745 if (thread != NULL) {
1746 thread->schedfunc = func;
1747 thread->scheddata = data;
1748 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1749#ifdef DEBUG_SCHED_MULTITHREAD
1750 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1751#endif
1752 signal_condition(&thread->lock, &thread->cond);
1753 return 0;
1754 }
1755 time(&t);
1756 if (t != lasterror) {
1757 lasterror = t;
1758 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1759 }
1760
1761 return -1;
1762}
1763#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1764#endif
1765
1766static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1767 ast_sched_cb callback, const void *data)
1768{
1769 return ast_sched_replace(id, con, when, callback, data);
1770}
1771
1772static int iax2_sched_add(struct ast_sched_context *con, int when,
1773 ast_sched_cb callback, const void *data)
1774{
1775 return ast_sched_add(con, when, callback, data);
1776}
1777
1778/*!
1779 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1780 * \param callno Call number to lock.
1781 * \retval 0 If call disappeared or has ongoing hangup procedure.
1782 * \retval 1 If call found and mutex is locked.
1783 */
1785{
1787
1788 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1789 * or destroy initiated (in middle of hang up procedure. */
1790 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1791 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1793 return 0;
1794 }
1795
1796 /* Lock acquired, and callno is alive and kicking. */
1797 return 1;
1798}
1799
1800static int send_ping(const void *data);
1801
1802static void __send_ping(const void *data)
1803{
1804 int callno = PTR_TO_CALLNO(data);
1805
1807 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1808 return;
1809 }
1810
1811 /* Mark pingid as invalid scheduler id. */
1812 iaxs[callno]->pingid = -1;
1813
1814 /* callno is now locked. */
1815 if (iaxs[callno]->peercallno) {
1816 /* Send PING packet. */
1818
1819 /* Schedule sending next ping. */
1821 }
1822
1824}
1825
1826static int send_ping(const void *data)
1827{
1828#ifdef SCHED_MULTITHREADED
1829 if (schedule_action(__send_ping, data))
1830#endif
1831 __send_ping(data);
1832
1833 return 0;
1834}
1835
1836static void encmethods_to_str(int e, struct ast_str **buf)
1837{
1838 ast_str_set(buf, 0, "(");
1839 if (e & IAX_ENCRYPT_AES128) {
1840 ast_str_append(buf, 0, "aes128");
1841 }
1842 if (e & IAX_ENCRYPT_KEYROTATE) {
1843 ast_str_append(buf, 0, ",keyrotate");
1844 }
1845 if (ast_str_strlen(*buf) > 1) {
1846 ast_str_append(buf, 0, ")");
1847 } else {
1848 ast_str_set(buf, 0, "No");
1849 }
1850}
1851
1852static int get_encrypt_methods(const char *s)
1853{
1854 int e;
1855 if (!strcasecmp(s, "aes128"))
1857 else if (ast_true(s))
1859 else
1860 e = 0;
1861 return e;
1862}
1863
1864static int send_lagrq(const void *data);
1865
1866static void __send_lagrq(const void *data)
1867{
1868 int callno = PTR_TO_CALLNO(data);
1869
1871 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1872 return;
1873 }
1874
1875 /* Mark lagid as invalid scheduler id. */
1876 iaxs[callno]->lagid = -1;
1877
1878 /* callno is now locked. */
1879 if (iaxs[callno]->peercallno) {
1880 /* Send LAGRQ packet. */
1882
1883 /* Schedule sending next lagrq. */
1885 }
1886
1888}
1889
1890static int send_lagrq(const void *data)
1891{
1892#ifdef SCHED_MULTITHREADED
1893 if (schedule_action(__send_lagrq, data))
1894#endif
1895 __send_lagrq(data);
1896 return 0;
1897}
1898
1899static unsigned char compress_subclass(iax2_format subclass)
1900{
1901 int x;
1902 int power=-1;
1903 /* If it's 64 or smaller, just return it */
1904 if (subclass < IAX_FLAG_SC_LOG)
1905 return subclass;
1906 /* Otherwise find its power */
1907 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1908 if (subclass & (1LL << x)) {
1909 if (power > -1) {
1910 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1911 return 0;
1912 } else
1913 power = x;
1914 }
1915 }
1916 return power | IAX_FLAG_SC_LOG;
1917}
1918
1920{
1921 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1922 if (csub & IAX_FLAG_SC_LOG) {
1923 /* special case for 'compressed' -1 */
1924 if (csub == 0xff)
1925 return -1;
1926 else
1927 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1928 }
1929 else
1930 return csub;
1931}
1932
1933static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1934{
1935 int x;
1936 struct ast_format *found_format = NULL;
1937
1938 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1939 struct ast_format *pref_format;
1940 uint64_t pref_bitfield;
1941
1942 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1943 if (!pref_bitfield) {
1944 break;
1945 }
1946
1947 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1948 if (!pref_format) {
1949 /* The bitfield is not associated with any format. */
1950 continue;
1951 }
1952 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1953 if (found_format) {
1954 break;
1955 }
1956 }
1957
1958 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1959 return found_format;
1960 }
1961
1962 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1963 ao2_cleanup(found_format);
1964 return NULL;
1965}
1966
1968{
1969 struct ast_format_cap *cap;
1970 struct ast_format *tmpfmt;
1971 iax2_format format = 0;
1972
1975 tmpfmt = codec_choose_from_prefs(pref, cap);
1976 if (!tmpfmt) {
1977 ao2_ref(cap, -1);
1978 return 0;
1979 }
1980
1982 ao2_ref(tmpfmt, -1);
1983 ao2_ref(cap, -1);
1984 }
1985
1986 return format;
1987}
1988
1990{
1991 struct ast_format *tmpfmt;
1992
1994 if (!tmpfmt) {
1995 return "Unknown";
1996 }
1997
1998 return ast_format_get_name(tmpfmt);
1999}
2000
2001static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
2002{
2004
2005 if (!cap) {
2006 return "(Nothing)";
2007 }
2009 ast_format_cap_get_names(cap, codec_buf);
2010 ao2_ref(cap, -1);
2011
2012 return ast_str_buffer(*codec_buf);
2013}
2014
2015static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
2016{
2017 int res, i;
2018 struct ast_format_cap *cap;
2019
2020 /* We want to add the formats to the cap in the preferred order */
2022 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
2023 ao2_cleanup(cap);
2024 return 1;
2025 }
2026
2027 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
2028
2029 /* Adjust formats bitfield and pref list to match. */
2032
2033 for (i = 0; i < ast_format_cap_count(cap); i++) {
2034 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
2035
2037 ao2_ref(fmt, -1);
2038 }
2039
2040 ao2_ref(cap, -1);
2041
2042 return res;
2043}
2044
2045/*!
2046 * \note The only member of the peer passed here guaranteed to be set is the name field
2047 */
2048static int peer_hash_cb(const void *obj, const int flags)
2049{
2050 const struct iax2_peer *peer = obj;
2051 const char *name = obj;
2052
2053 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
2054}
2055
2056/*!
2057 * \note The only member of the peer passed here guaranteed to be set is the name field
2058 */
2059static int peer_cmp_cb(void *obj, void *arg, int flags)
2060{
2061 struct iax2_peer *peer = obj, *peer2 = arg;
2062 const char *name = arg;
2063
2064 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
2065 CMP_MATCH | CMP_STOP : 0;
2066}
2067
2068/*!
2069 * \note The only member of the user passed here guaranteed to be set is the name field
2070 */
2071static int user_hash_cb(const void *obj, const int flags)
2072{
2073 const struct iax2_user *user = obj;
2074 const char *name = obj;
2075
2076 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2077}
2078
2079/*!
2080 * \note The only member of the user passed here guaranteed to be set is the name field
2081 */
2082static int user_cmp_cb(void *obj, void *arg, int flags)
2083{
2084 struct iax2_user *user = obj, *user2 = arg;
2085 const char *name = arg;
2086
2087 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2088 CMP_MATCH | CMP_STOP : 0;
2089}
2090
2091/*!
2092 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2093 * so do not call it with a pvt lock held.
2094 */
2095static struct iax2_peer *find_peer(const char *name, int realtime)
2096{
2097 struct iax2_peer *peer = NULL;
2098
2099 peer = ao2_find(peers, name, OBJ_KEY);
2100
2101 /* Now go for realtime if applicable */
2102 if (!peer && realtime) {
2103 peer = realtime_peer(name, NULL);
2104 }
2105 return peer;
2106}
2107
2108static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2109{
2110 ao2_ref(peer, +1);
2111 return peer;
2112}
2113
2114static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2115{
2116 ao2_ref(peer, -1);
2117 return NULL;
2118}
2119
2120static struct iax2_user *find_user(const char *name)
2121{
2122 return ao2_find(users, name, OBJ_KEY);
2123}
2124
2125static inline struct iax2_user *user_unref(struct iax2_user *user)
2126{
2127 ao2_ref(user, -1);
2128 return NULL;
2129}
2130
2131static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2132{
2133 struct iax2_peer *peer = NULL;
2134 int res = 0;
2135 struct ao2_iterator i;
2136
2137 i = ao2_iterator_init(peers, 0);
2138 while ((peer = ao2_iterator_next(&i))) {
2139
2140 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2141 ast_copy_string(host, peer->name, len);
2142 peer_unref(peer);
2143 res = 1;
2144 break;
2145 }
2146 peer_unref(peer);
2147 }
2149
2150 if (!peer) {
2151 peer = realtime_peer(NULL, &addr);
2152 if (peer) {
2153 ast_copy_string(host, peer->name, len);
2154 peer_unref(peer);
2155 res = 1;
2156 }
2157 }
2158
2159 return res;
2160}
2161
2162/* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2163static int iax2_delete_from_sched(const void* data)
2164{
2165 int sched_id = (int)(long)data;
2166
2168
2169 return 0;
2170}
2171
2172/*!\note Assumes the lock on the pvt is already held, when
2173 * iax2_destroy_helper() is called. */
2174static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2175{
2176 /* Decrement AUTHREQ count if needed */
2177 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2178 struct iax2_user *user;
2179
2181 if (user) {
2182 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2184 }
2185
2187 }
2188
2189
2190 /* Mark call destroy initiated flag. */
2191 pvt->destroy_initiated = 1;
2192
2193 /*
2194 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2195 * Already running tasks will be terminated because of destroy_initiated.
2196 *
2197 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2198 * it leads to a deadlock between the scheduler thread callback locking
2199 * the callno mutex and this thread which holds the callno mutex one or
2200 * more times. It is better to have another thread delete the scheduled
2201 * callbacks which doesn't lock the callno mutex.
2202 */
2203 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2204 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2205
2206 pvt->pingid = -1;
2207 pvt->lagid = -1;
2208
2209 AST_SCHED_DEL(sched, pvt->autoid);
2210 AST_SCHED_DEL(sched, pvt->authid);
2211 AST_SCHED_DEL(sched, pvt->initid);
2212 AST_SCHED_DEL(sched, pvt->jbid);
2214}
2215
2216static void iax2_frame_free(struct iax_frame *fr)
2217{
2219 iax_frame_free(fr);
2220}
2221
2222static int scheduled_destroy(const void *vid)
2223{
2224 unsigned short callno = PTR_TO_CALLNO(vid);
2225 ast_mutex_lock(&iaxsl[callno]);
2226 if (iaxs[callno]) {
2227 ast_debug(1, "Really destroying %d now...\n", callno);
2228 iax2_destroy(callno);
2229 }
2230 ast_mutex_unlock(&iaxsl[callno]);
2231 return 0;
2232}
2233
2235{
2236 if (s->f.datalen) {
2237 ast_free(s->f.data.ptr);
2238 }
2239 ast_free(s);
2240}
2241
2242/*! \brief This function must be called once we are sure the other side has
2243 * given us a call number. All signaling is held here until that point. */
2244static void send_signaling(struct chan_iax2_pvt *pvt)
2245{
2246 struct signaling_queue_entry *s = NULL;
2247
2248 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2249 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2251 }
2252 pvt->hold_signaling = 0;
2253}
2254
2255/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2256 * we have received a destination call number. */
2257static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2258{
2259 struct signaling_queue_entry *qe;
2260
2261 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2262 return 1; /* do not queue this frame */
2263 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2264 return -1; /* out of memory */
2265 }
2266
2267 /* copy ast_frame into our queue entry */
2268 qe->f = *f;
2269 if (qe->f.datalen) {
2270 /* if there is data in this frame copy it over as well */
2271 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2273 return -1;
2274 }
2275 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2276 }
2278
2279 return 0;
2280}
2281
2282static void pvt_destructor(void *obj)
2283{
2284 struct chan_iax2_pvt *pvt = obj;
2285 struct iax_frame *cur = NULL;
2286 struct signaling_queue_entry *s = NULL;
2287
2288 ast_mutex_lock(&iaxsl[pvt->callno]);
2289
2291
2293 pvt->callno_entry = 0;
2294
2295 /* Already gone */
2297
2298 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2299 /* Cancel any pending transmissions */
2300 cur->retries = -1;
2301 }
2302
2304
2305 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2307 }
2308
2309 if (pvt->reg) {
2310 pvt->reg->callno = 0;
2311 }
2312
2313 if (!pvt->owner) {
2314 jb_frame frame;
2315 if (pvt->vars) {
2317 pvt->vars = NULL;
2318 }
2319
2320 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2321 iax2_frame_free(frame.data);
2322 }
2323
2324 jb_destroy(pvt->jb);
2326 }
2327}
2328
2329static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2330{
2331 struct chan_iax2_pvt *tmp;
2332 jb_conf jbconf;
2333
2334 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2335 return NULL;
2336 }
2337
2338 tmp->pingid = -1;
2339 tmp->lagid = -1;
2340 tmp->autoid = -1;
2341 tmp->authid = -1;
2342 tmp->initid = -1;
2343 tmp->keyrotateid = -1;
2344 tmp->jbid = -1;
2345
2346 if (ast_string_field_init(tmp, 32)) {
2347 ao2_ref(tmp, -1);
2348 tmp = NULL;
2349 return NULL;
2350 }
2351
2352 tmp->prefs = prefs_global;
2353
2354 ast_string_field_set(tmp,exten, "s");
2356
2357 tmp->jb = jb_new();
2362 jb_setconf(tmp->jb,&jbconf);
2363
2365
2366 tmp->hold_signaling = 1;
2368
2369 return tmp;
2370}
2371
2372static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2373{
2375 if (new) {
2376 size_t afdatalen = new->afdatalen;
2377 memcpy(new, fr, sizeof(*new));
2378 iax_frame_wrap(new, &fr->af);
2379 new->afdatalen = afdatalen;
2380 new->data = NULL;
2381 new->datalen = 0;
2382 new->direction = DIRECTION_INGRESS;
2383 new->retrans = -1;
2384 }
2385 return new;
2386}
2387/* keep these defined in this order. They are used in find_callno to
2388 * determine whether or not a new call number should be allowed. */
2389enum {
2390 /* do not allow a new call number, only search ones in use for match */
2392 /* search for match first, then allow a new one to be allocated */
2394 /* do not search for match, force a new call number */
2396 /* do not search for match, force a new call number. Signifies call number
2397 * has been calltoken validated */
2399};
2400
2401static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2402{
2403 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2404 /* This is the main host */
2405 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2406 (check_dcallno ? dcallno == cur->callno : 1) ) {
2407 /* That's us. Be sure we keep track of the peer call number */
2408 return 1;
2409 }
2410 }
2411 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2412 /* We're transferring */
2413 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2414 return 1;
2415 }
2416 return 0;
2417}
2418
2419static int make_trunk(unsigned short callno, int locked)
2420{
2421 int x;
2422 int res= 0;
2423 callno_entry entry;
2424 if (iaxs[callno]->oseqno) {
2425 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2426 return -1;
2427 }
2428 if (callno >= TRUNK_CALL_START) {
2429 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2430 return -1;
2431 }
2432
2436 &entry)) {
2437 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2438 return -1;
2439 }
2440
2441 x = CALLNO_ENTRY_GET_CALLNO(entry);
2442 ast_mutex_lock(&iaxsl[x]);
2443
2444 /*!
2445 * \note We delete these before switching the slot, because if
2446 * they fire in the meantime, they will generate a warning.
2447 */
2448 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2449 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2450 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2451 iaxs[x] = iaxs[callno];
2452 iaxs[x]->callno = x;
2453
2454 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2455 * before assigning the new one */
2456 if (iaxs[x]->callno_entry) {
2458 sched,
2459 MIN_REUSE_TIME * 1000,
2462
2463 }
2464 iaxs[x]->callno_entry = entry;
2465
2466 iaxs[callno] = NULL;
2467 /* Update the two timers that should have been started */
2469 ping_time * 1000, send_ping, (void *)(long)x);
2471 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2472
2473 if (locked)
2475 res = x;
2476 if (!locked)
2478
2479 /* We moved this call from a non-trunked to a trunked call */
2480 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2481
2482 return res;
2483}
2484
2486{
2487 if (!pvt->transfercallno) {
2488 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2489 return;
2490 }
2491
2493}
2494
2496{
2497 if (!pvt->transfercallno) {
2498 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2499 return;
2500 }
2501
2503}
2504static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2505{
2506 if (!pvt->peercallno) {
2507 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2508 return;
2509 }
2510
2512}
2513
2514static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2515{
2516 if (!pvt->peercallno) {
2517 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2518 return;
2519 }
2520
2522}
2523
2524static int addr_range_delme_cb(void *obj, void *arg, int flags)
2525{
2526 struct addr_range *lim = obj;
2527 lim->delme = 1;
2528 return 0;
2529}
2530
2531static int addr_range_hash_cb(const void *obj, const int flags)
2532{
2533 const struct addr_range *lim = obj;
2534 return abs(ast_sockaddr_hash(&lim->ha.addr));
2535}
2536
2537static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2538{
2539 struct addr_range *lim1 = obj, *lim2 = arg;
2540 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2541 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2542 CMP_MATCH | CMP_STOP : 0;
2543}
2544
2545static int peercnt_hash_cb(const void *obj, const int flags)
2546{
2547 const struct peercnt *peercnt = obj;
2548
2550 return 0;
2551 }
2552 return ast_sockaddr_hash(&peercnt->addr);
2553}
2554
2555static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2556{
2557 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2558 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2559}
2560
2561static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2562{
2563 struct addr_range *addr_range = obj;
2564 struct ast_sockaddr *addr = arg;
2565 struct ast_sockaddr tmp_addr;
2566
2567 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2568
2569 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2570 return CMP_MATCH | CMP_STOP;
2571 }
2572 return 0;
2573}
2574
2575/*!
2576 * \internal
2577 *
2578 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2579 */
2580static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2581{
2582 struct addr_range *addr_range;
2583 struct iax2_peer *peer = NULL;
2584 struct iax2_user *user = NULL;
2585 /* if no username is given, check for guest accounts */
2586 const char *find = S_OR(name, "guest");
2587 int res = 1; /* required by default */
2588 int optional = 0;
2590 /* There are only two cases in which calltoken validation is not required.
2591 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2592 * the peer definition has not set the requirecalltoken option.
2593 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2594 */
2595
2596 /* ----- Case 1 ----- */
2598 ao2_ref(addr_range, -1);
2599 optional = 1;
2600 }
2601
2602 /* ----- Case 2 ----- */
2603 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2604 calltoken_required = user->calltoken_required;
2605 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2606 calltoken_required = user->calltoken_required;
2607 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2609 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2611 }
2612
2613 if (peer) {
2614 peer_unref(peer);
2615 }
2616 if (user) {
2618 }
2619
2620 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);
2622 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2623 res = 0;
2624 }
2625
2626 return res;
2627}
2628
2629/*!
2630 * \internal
2631 *
2632 * \brief set peercnt callno limit.
2633 *
2634 * \details
2635 * First looks in custom definitions. If not found, global limit
2636 * is used. Entries marked as reg already have
2637 * a custom limit set by a registration and are not modified.
2638 */
2640{
2641 uint16_t limit = global_maxcallno;
2642 struct addr_range *addr_range;
2643 struct ast_sockaddr addr;
2644
2645 ast_sockaddr_copy(&addr, &peercnt->addr);
2646
2647 if (peercnt->reg && peercnt->limit) {
2648 return; /* this peercnt has a custom limit set by a registration */
2649 }
2650
2652 limit = addr_range->limit;
2653 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2654 ao2_ref(addr_range, -1);
2655 }
2656
2657 peercnt->limit = limit;
2658}
2659
2660/*!
2661 * \internal
2662 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2663 */
2664static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2665{
2666 struct peercnt *peercnt = obj;
2667
2669 ast_debug(1, "Reset limits for peercnts table\n");
2670
2671 return 0;
2672}
2673
2674/*!
2675 * \internal
2676 * \brief returns match if delme is set.
2677 */
2678static int prune_addr_range_cb(void *obj, void *arg, int flags)
2679{
2680 struct addr_range *addr_range = obj;
2681
2682 return addr_range->delme ? CMP_MATCH : 0;
2683}
2684
2685/*!
2686 * \internal
2687 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2688 */
2689static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2690{
2691 /* this function turns off and on custom callno limits set by peer registration */
2692 struct peercnt *peercnt;
2693 struct peercnt tmp;
2694
2695 ast_sockaddr_copy(&tmp.addr, sockaddr);
2696
2697 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2698 peercnt->reg = reg;
2699 if (limit) {
2700 peercnt->limit = limit;
2701 } else {
2703 }
2704 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2705 ao2_ref(peercnt, -1); /* decrement ref from find */
2706 }
2707}
2708
2709/*!
2710 * \internal
2711 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2712 *
2713 * \details First searches for the address in the peercnts table. If found
2714 * the current count is incremented. If not found a new peercnt is allocated
2715 * and linked into the peercnts table with a call number count of 1.
2716 */
2717static int peercnt_add(struct ast_sockaddr *addr)
2718{
2719 struct peercnt *peercnt;
2720 int res = 0;
2721 struct peercnt tmp;
2722
2724
2725 /* Reasoning for peercnts container lock: Two identical ip addresses
2726 * could be added by different threads at the "same time". Without the container
2727 * lock, both threads could alloc space for the same object and attempt
2728 * to link to table. With the lock, one would create the object and link
2729 * to table while the other would find the already created peercnt object
2730 * rather than creating a new one. */
2732 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2734 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2736 /* create and set defaults */
2739 /* guarantees it does not go away after unlocking table
2740 * ao2_find automatically adds this */
2742 } else {
2744 return -1;
2745 }
2746
2747 /* check to see if the address has hit its callno limit. If not increment cur. */
2748 if (peercnt->limit > peercnt->cur) {
2749 peercnt->cur++;
2750 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2751 } else { /* max num call numbers for this peer has been reached! */
2752 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2753 res = -1;
2754 }
2755
2756 /* clean up locks and ref count */
2759 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2760
2761 return res;
2762}
2763
2764/*!
2765 * \internal
2766 * \brief decrements a peercnts table entry
2767 */
2768static void peercnt_remove(struct peercnt *peercnt)
2769{
2770 struct ast_sockaddr addr;
2771
2772 ast_sockaddr_copy(&addr, &peercnt->addr);
2773
2774 /*
2775 * Container locked here since peercnt may be unlinked from
2776 * list. If left unlocked, peercnt_add could try and grab this
2777 * entry from the table and modify it at the "same time" this
2778 * thread attempts to unlink it.
2779 */
2781 peercnt->cur--;
2782 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2783 /* if this was the last connection from the peer remove it from table */
2784 if (peercnt->cur == 0) {
2785 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2786 }
2788}
2789
2790/*!
2791 * \internal
2792 * \brief called by scheduler to decrement object
2793 */
2794static int peercnt_remove_cb(const void *obj)
2795{
2796 struct peercnt *peercnt = (struct peercnt *) obj;
2797
2799 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2800
2801 return 0;
2802}
2803
2804/*!
2805 * \internal
2806 * \brief decrements peercnts connection count, finds by addr
2807 */
2809{
2810 struct peercnt *peercnt;
2811 struct peercnt tmp;
2812
2814
2815 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2817 ao2_ref(peercnt, -1); /* decrement ref from find */
2818 }
2819 return 0;
2820}
2821
2822/*!
2823 * \internal
2824 * \brief Create callno_limit entry based on configuration
2825 */
2826static void build_callno_limits(struct ast_variable *v)
2827{
2828 struct addr_range *addr_range = NULL;
2829 struct addr_range tmp;
2830 struct ast_ha *ha;
2831 int limit;
2832 int error;
2833 int found;
2834
2835 for (; v; v = v->next) {
2836 limit = -1;
2837 error = 0;
2838 found = 0;
2839 ha = ast_append_ha("permit", v->name, NULL, &error);
2840
2841 /* check for valid config information */
2842 if (error) {
2843 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2844 continue;
2845 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2846 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2847 ast_free_ha(ha);
2848 continue;
2849 }
2850
2851 ast_copy_ha(ha, &tmp.ha);
2852 /* find or create the addr_range */
2853 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2855 found = 1;
2856 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2857 ast_free_ha(ha);
2858 return; /* out of memory */
2859 }
2860
2861 /* copy over config data into addr_range object */
2862 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2863 ast_free_ha(ha); /* cleanup the tmp ha */
2864 addr_range->limit = limit;
2865 addr_range->delme = 0;
2866
2867 /* cleanup */
2868 if (found) {
2870 } else {
2872 }
2873 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2874 }
2875}
2876
2877/*!
2878 * \internal
2879 * \brief Create calltoken_ignores entry based on configuration
2880 */
2881static int add_calltoken_ignore(const char *addr)
2882{
2883 struct addr_range tmp;
2884 struct addr_range *addr_range = NULL;
2885 struct ast_ha *ha = NULL;
2886 int error = 0;
2887
2888 if (ast_strlen_zero(addr)) {
2889 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2890 return -1;
2891 }
2892
2893 ha = ast_append_ha("permit", addr, NULL, &error);
2894
2895 /* check for valid config information */
2896 if (error) {
2897 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2898 return -1;
2899 }
2900
2901 ast_copy_ha(ha, &tmp.ha);
2902 /* find or create the addr_range */
2905 addr_range->delme = 0;
2907 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2908 /* copy over config data into addr_range object */
2909 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2911 } else {
2912 ast_free_ha(ha);
2913 return -1;
2914 }
2915
2916 ast_free_ha(ha);
2917 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2918
2919 return 0;
2920}
2921
2922static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2923{
2924 struct ao2_iterator i;
2925 struct peercnt *peercnt;
2926 struct ast_sockaddr addr;
2927 int found = 0;
2928
2929 switch (cmd) {
2930 case CLI_INIT:
2931 e->command = "iax2 show callnumber usage";
2932 e->usage =
2933 "Usage: iax2 show callnumber usage [IP address]\n"
2934 " Shows current IP addresses which are consuming iax2 call numbers\n";
2935 return NULL;
2936 case CLI_GENERATE:
2937 return NULL;
2938 case CLI_HANDLER:
2939 if (a->argc < 4 || a->argc > 5)
2940 return CLI_SHOWUSAGE;
2941
2942 if (a->argc == 4) {
2943 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2944 }
2945
2947 while ((peercnt = ao2_iterator_next(&i))) {
2948 ast_sockaddr_copy(&addr, &peercnt->addr);
2949
2950 if (a->argc == 5) {
2951 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2952 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2953 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2954 ao2_ref(peercnt, -1);
2955 found = 1;
2956 break;
2957 }
2958 } else {
2959 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2960 }
2961 ao2_ref(peercnt, -1);
2962 }
2964
2965 if (a->argc == 4) {
2966 size_t pool_avail = callno_pool.available;
2967 size_t trunk_pool_avail = callno_pool_trunk.available;
2968
2969 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2970 "Non-CallToken Validated Callno Used: %d\n",
2973
2974 ast_cli(a->fd, "Total Available Callno: %zu\n"
2975 "Regular Callno Available: %zu\n"
2976 "Trunk Callno Available: %zu\n",
2977 pool_avail + trunk_pool_avail,
2978 pool_avail,
2979 trunk_pool_avail);
2980 } else if (a->argc == 5 && !found) {
2981 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2982 }
2983
2984
2985 return CLI_SUCCESS;
2986 default:
2987 return NULL;
2988 }
2989}
2990
2991static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2992{
2993 struct call_number_pool *pool = NULL;
2994 callno_entry swap;
2995 size_t choice;
2996
2997 switch (type) {
2998 case CALLNO_TYPE_NORMAL:
2999 pool = &callno_pool;
3000 break;
3001 case CALLNO_TYPE_TRUNK:
3002 pool = &callno_pool_trunk;
3003 break;
3004 default:
3005 ast_assert(0);
3006 break;
3007 }
3008
3009 /* If we fail, make sure this has a defined value */
3010 *entry = 0;
3011
3012 /* We lock here primarily to ensure thread safety of the
3013 * total_nonval_callno_used check and increment */
3015
3016 /* Bail out if we don't have any available call numbers */
3017 if (!pool->available) {
3018 ast_log(LOG_WARNING, "Out of call numbers\n");
3020 return 1;
3021 }
3022
3023 /* Only a certain number of non-validated call numbers should be allocated.
3024 * If there ever is an attack, this separates the calltoken validating users
3025 * from the non-calltoken validating users. */
3028 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
3032 return 1;
3033 }
3034
3035 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
3036 * available call numbers. The array of call numbers begins as an ordered
3037 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
3038 * - let's call that x. When a call number is needed we pick a random index
3039 * into the array between 0 and x and use that as our call number. In a
3040 * typical FYD shuffle, we would swap the value that we are extracting with
3041 * the number at x, but in our case we swap and don't touch the value at x
3042 * because it is effectively invisible. We rely on the rest of the IAX2 core
3043 * to return the number to us at some point. Finally, we decrement x by 1
3044 * which establishes our new unused range.
3045 *
3046 * When numbers are returned to the pool, we put them just past x and bump x
3047 * by 1 so that this number is now available for re-use. */
3048
3049 choice = ast_random() % pool->available;
3050
3051 *entry = pool->numbers[choice];
3052 swap = pool->numbers[pool->available - 1];
3053
3054 pool->numbers[choice] = swap;
3055 pool->available--;
3056
3057 if (validated) {
3059 } else {
3061 }
3062
3064
3065 return 0;
3066}
3067
3068static int replace_callno(const void *obj)
3069{
3070 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
3071 struct call_number_pool *pool;
3072
3073 /* We lock here primarily to ensure thread safety of the
3074 * total_nonval_callno_used check and decrement */
3076
3077 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
3080 } else {
3082 "Attempted to decrement total non calltoken validated "
3083 "callnumbers below zero. Callno is: %d\n",
3085 }
3086 }
3087
3089 pool = &callno_pool;
3090 } else {
3091 pool = &callno_pool_trunk;
3092 }
3093
3094 ast_assert(pool->capacity > pool->available);
3095
3096 /* This clears the validated flag */
3097 entry = CALLNO_ENTRY_GET_CALLNO(entry);
3098
3099 pool->numbers[pool->available] = entry;
3100 pool->available++;
3101
3103
3104 return 0;
3105}
3106
3107static int create_callno_pools(void)
3108{
3109 uint16_t i;
3110
3112
3113 /* We start at 2. 0 and 1 are reserved. */
3114 for (i = 2; i < TRUNK_CALL_START; i++) {
3117 }
3118
3119 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3122 }
3123
3126
3128
3129 return 0;
3130}
3131
3132/*!
3133 * \internal
3134 * \brief Schedules delayed removal of iax2_pvt call number data
3135 *
3136 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3137 * available again, and the address from the previous connection must be decremented
3138 * from the peercnts table. This function schedules these operations to take place.
3139 */
3140static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3141{
3142 int i;
3143 struct peercnt *peercnt;
3144 struct peercnt tmp;
3145
3147
3148 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3149 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3150 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3152 if (i == -1) {
3153 ao2_ref(peercnt, -1);
3154 }
3155 }
3156
3158 sched,
3159 MIN_REUSE_TIME * 1000,
3161 CALLNO_ENTRY_TO_PTR(entry));
3162}
3163
3164/*!
3165 * \internal
3166 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3167 *
3168 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3169 * a new callno.
3170 */
3171static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3172{
3173 if (frametype != AST_FRAME_IAX) {
3174 return 0;
3175 }
3176 switch (subclass) {
3177 case IAX_COMMAND_NEW:
3178 case IAX_COMMAND_REGREQ:
3180 case IAX_COMMAND_REGREL:
3181 return 1;
3182 case IAX_COMMAND_POKE:
3183 if (!inbound) {
3184 return 1;
3185 }
3186 break;
3187 }
3188 return 0;
3189}
3190
3191/*!
3192 * \note Calling this function while holding another pvt lock can cause a deadlock.
3193 */
3194static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3195{
3196 int res = 0;
3197 int x;
3198 /* this call is calltoken validated as long as it is either NEW_FORCE
3199 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3200 int validated = (new > NEW_ALLOW) ? 1 : 0;
3201 char host[80];
3202
3203 if (new <= NEW_ALLOW) {
3204 if (callno) {
3205 struct chan_iax2_pvt *pvt;
3206 struct chan_iax2_pvt tmp_pvt = {
3207 .callno = dcallno,
3208 .peercallno = callno,
3209 .transfercallno = callno,
3210 /* hack!! */
3211 .frames_received = check_dcallno,
3212 };
3213
3214 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3215 /* this works for finding normal call numbers not involving transferring */
3216 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3217 if (return_locked) {
3218 ast_mutex_lock(&iaxsl[pvt->callno]);
3219 }
3220 res = pvt->callno;
3221 ao2_ref(pvt, -1);
3222 pvt = NULL;
3223 return res;
3224 }
3225 /* this searches for transfer call numbers that might not get caught otherwise */
3226 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3227 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3228 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3229 if (return_locked) {
3230 ast_mutex_lock(&iaxsl[pvt->callno]);
3231 }
3232 res = pvt->callno;
3233 ao2_ref(pvt, -1);
3234 pvt = NULL;
3235 return res;
3236 }
3237 }
3238 /* This will occur on the first response to a message that we initiated,
3239 * such as a PING. */
3240 if (dcallno) {
3241 ast_mutex_lock(&iaxsl[dcallno]);
3242 }
3243 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3244 iaxs[dcallno]->peercallno = callno;
3245 res = dcallno;
3246 store_by_peercallno(iaxs[dcallno]);
3247 if (!res || !return_locked) {
3248 ast_mutex_unlock(&iaxsl[dcallno]);
3249 }
3250 return res;
3251 }
3252 if (dcallno) {
3253 ast_mutex_unlock(&iaxsl[dcallno]);
3254 }
3255 }
3256 if (!res && (new >= NEW_ALLOW)) {
3257 callno_entry entry;
3258
3259 /* It may seem odd that we look through the peer list for a name for
3260 * this *incoming* call. Well, it is weird. However, users don't
3261 * have an IP address/port number that we can match against. So,
3262 * this is just checking for a peer that has that IP/port and
3263 * assuming that we have a user of the same name. This isn't always
3264 * correct, but it will be changed if needed after authentication. */
3265 if (!iax2_getpeername(*addr, host, sizeof(host)))
3266 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3267
3268 if (peercnt_add(addr)) {
3269 /* This address has hit its callnumber limit. When the limit
3270 * is reached, the connection is not added to the peercnts table.*/
3271 return 0;
3272 }
3273
3274 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3275 /* since we ran out of space, remove the peercnt
3276 * entry we added earlier */
3278 ast_log(LOG_WARNING, "No more space\n");
3279 return 0;
3280 }
3281 x = CALLNO_ENTRY_GET_CALLNO(entry);
3282 ast_mutex_lock(&iaxsl[x]);
3283
3284 iaxs[x] = new_iax(addr, host);
3285 if (iaxs[x]) {
3286 if (iaxdebug)
3287 ast_debug(1, "Creating new call structure %d\n", x);
3288 iaxs[x]->callno_entry = entry;
3289 iaxs[x]->sockfd = sockfd;
3291 iaxs[x]->peercallno = callno;
3292 iaxs[x]->callno = x;
3295 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3296 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3297 iaxs[x]->amaflags = amaflags;
3303
3304 if (iaxs[x]->peercallno) {
3306 }
3307 } else {
3308 ast_log(LOG_WARNING, "Out of resources\n");
3311 return 0;
3312 }
3313 if (!return_locked)
3315 res = x;
3316 }
3317 return res;
3318}
3319
3320static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3321 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3322}
3323
3324static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3325
3326 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3327}
3328
3329/*!
3330 * \brief Queue a frame to a call's owning asterisk channel
3331 *
3332 * \pre This function assumes that iaxsl[callno] is locked when called.
3333 *
3334 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3335 * was valid before calling it, it may no longer be valid after calling it.
3336 * This function may unlock and lock the mutex associated with this callno,
3337 * meaning that another thread may grab it and destroy the call.
3338 */
3339static int iax2_queue_frame(int callno, struct ast_frame *f)
3340{
3342 if (iaxs[callno] && iaxs[callno]->owner) {
3345 }
3346 return 0;
3347}
3348
3349/*!
3350 * \brief Queue a hold frame on the ast_channel owner
3351 *
3352 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3353 * is active for the given call number.
3354 *
3355 * \pre Assumes lock for callno is already held.
3356 *
3357 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3358 * was valid before calling it, it may no longer be valid after calling it.
3359 * This function may unlock and lock the mutex associated with this callno,
3360 * meaning that another thread may grab it and destroy the call.
3361 */
3362static int iax2_queue_hold(int callno, const char *musicclass)
3363{
3365 if (iaxs[callno] && iaxs[callno]->owner) {
3366 ast_queue_hold(iaxs[callno]->owner, musicclass);
3368 }
3369 return 0;
3370}
3371
3372/*!
3373 * \brief Queue an unhold frame on the ast_channel owner
3374 *
3375 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3376 * is active for the given call number.
3377 *
3378 * \pre Assumes lock for callno is already held.
3379 *
3380 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3381 * was valid before calling it, it may no longer be valid after calling it.
3382 * This function may unlock and lock the mutex associated with this callno,
3383 * meaning that another thread may grab it and destroy the call.
3384 */
3386{
3388 if (iaxs[callno] && iaxs[callno]->owner) {
3391 }
3392 return 0;
3393}
3394
3395/*!
3396 * \brief Queue a hangup frame on the ast_channel owner
3397 *
3398 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3399 * is active for the given call number.
3400 *
3401 * \pre Assumes lock for callno is already held.
3402 *
3403 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3404 * was valid before calling it, it may no longer be valid after calling it.
3405 * This function may unlock and lock the mutex associated with this callno,
3406 * meaning that another thread may grab it and destroy the call.
3407 */
3409{
3411 if (iaxs[callno] && iaxs[callno]->owner) {
3414 }
3415 return 0;
3416}
3417
3418/*!
3419 * \note This function assumes that iaxsl[callno] is locked when called.
3420 *
3421 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3422 * was valid before calling it, it may no longer be valid after calling it.
3423 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3424 * associated with this callno, meaning that another thread may grab it and destroy the call.
3425 */
3426static int __do_deliver(void *data)
3427{
3428 /* Just deliver the packet by using queueing. This is called by
3429 the IAX thread with the iaxsl lock held. */
3430 struct iax_frame *fr = data;
3431 fr->retrans = -1;
3434 iax2_queue_frame(fr->callno, &fr->af);
3435 /* Free our iax frame */
3436 iax2_frame_free(fr);
3437 /* And don't run again */
3438 return 0;
3439}
3440
3441static int handle_error(void)
3442{
3443 /* XXX Ideally we should figure out why an error occurred and then abort those
3444 rather than continuing to try. Unfortunately, the published interface does
3445 not seem to work XXX */
3446#if 0
3447 struct sockaddr_in *sin;
3448 int res;
3449 struct msghdr m;
3450 struct sock_extended_err e;
3451 m.msg_name = NULL;
3452 m.msg_namelen = 0;
3453 m.msg_iov = NULL;
3454 m.msg_control = &e;
3455 m.msg_controllen = sizeof(e);
3456 m.msg_flags = 0;
3457 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3458 if (res < 0)
3459 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3460 else {
3461 if (m.msg_controllen) {
3462 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3463 if (sin)
3464 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3465 else
3466 ast_log(LOG_WARNING, "No address detected??\n");
3467 } else {
3468 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3469 }
3470 }
3471#endif
3472 return 0;
3473}
3474
3475static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3476{
3477 int res;
3478 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3479
3480 if (res < 0) {
3481 ast_debug(1, "Received error: %s\n", strerror(errno));
3482 handle_error();
3483 } else
3484 res = 0;
3485 return res;
3486}
3487
3488static int send_packet(struct iax_frame *f)
3489{
3490 int res;
3491 int callno = f->callno;
3492
3493 /* Don't send if there was an error, but return error instead */
3494 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3495 return -1;
3496
3497 /* Called with iaxsl held */
3498 if (iaxdebug) {
3499 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3500 }
3501 if (f->transfer) {
3502 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3503 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3504 } else {
3505 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3506 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3507 }
3508 if (res < 0) {
3509 if (iaxdebug)
3510 ast_debug(1, "Received error: %s\n", strerror(errno));
3511 handle_error();
3512 } else
3513 res = 0;
3514
3515 return res;
3516}
3517
3518/*!
3519 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3520 * for the given call number may disappear during its execution.
3521 */
3522static int iax2_predestroy(int callno)
3523{
3524 struct ast_channel *c = NULL;
3525 struct chan_iax2_pvt *pvt = iaxs[callno];
3526
3527 if (!pvt)
3528 return -1;
3529
3530 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3533 }
3534
3535 if ((c = pvt->owner)) {
3538 pvt->owner = NULL;
3540 }
3541
3542 return 0;
3543}
3544
3545static void iax2_destroy(int callno)
3546{
3547 struct chan_iax2_pvt *pvt = NULL;
3548 struct ast_channel *owner = NULL;
3549
3550retry:
3551 if ((pvt = iaxs[callno])) {
3552#if 0
3553 /* iax2_destroy_helper gets called from this function later on. When
3554 * called twice, we get the (previously) familiar FRACK! errors in
3555 * devmode, from the scheduler. An alternative to this approach is to
3556 * reset the scheduler entries to -1 when they're deleted in
3557 * iax2_destroy_helper(). That approach was previously decided to be
3558 * "wrong" because "the memory is going to be deallocated anyway. Why
3559 * should we be resetting those values?" */
3561#endif
3562 }
3563
3564 owner = pvt ? pvt->owner : NULL;
3565
3566 if (owner) {
3567 if (ast_channel_trylock(owner)) {
3568 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3569 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3570 goto retry;
3571 }
3572 }
3573
3574 if (!owner) {
3575 iaxs[callno] = NULL;
3576 }
3577
3578 if (pvt) {
3579 if (!owner) {
3580 pvt->owner = NULL;
3581 } else {
3582 /* If there's an owner, prod it to give up */
3583 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3584 * because we already hold the owner channel lock. */
3585 ast_queue_hangup(owner);
3586 }
3587
3588 if (pvt->peercallno) {
3590 }
3591
3592 if (pvt->transfercallno) {
3594 }
3595
3596 if (!owner) {
3597 ao2_ref(pvt, -1);
3598 pvt = NULL;
3599 }
3600 }
3601
3602 if (owner) {
3603 ast_channel_unlock(owner);
3604 }
3605}
3606
3607static int update_packet(struct iax_frame *f)
3608{
3609 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3610 struct ast_iax2_full_hdr *fh = f->data;
3611 struct ast_frame af;
3612
3613 /* if frame is encrypted. decrypt before updating it. */
3614 if (f->encmethods) {
3615 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3616 }
3617 /* Mark this as a retransmission */
3618 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3619 /* Update iseqno */
3620 f->iseqno = iaxs[f->callno]->iseqno;
3621 fh->iseqno = f->iseqno;
3622
3623 /* Now re-encrypt the frame */
3624 if (f->encmethods) {
3625 /* since this is a retransmit frame, create a new random padding
3626 * before re-encrypting. */
3627 build_rand_pad(f->semirand, sizeof(f->semirand));
3628 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3629 }
3630 return 0;
3631}
3632
3633static int attempt_transmit(const void *data);
3634static void __attempt_transmit(const void *data)
3635{
3636 /* Attempt to transmit the frame to the remote peer...
3637 Called without iaxsl held. */
3638 struct iax_frame *f = (struct iax_frame *)data;
3639 int freeme = 0;
3640 int callno = f->callno;
3641
3642 /* Make sure this call is still active */
3643 if (callno)
3645 if (callno && iaxs[callno]) {
3646 if (f->retries < 0) {
3647 /* Already ACK'd */
3648 freeme = 1;
3649 } else if (f->retries >= max_retries) {
3650 /* Too many attempts. Record an error. */
3651 if (f->transfer) {
3652 /* Transfer timeout */
3654 } else if (f->final) {
3656 } else {
3657 if (iaxs[callno]->owner) {
3658 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3661 f->af.frametype,
3662 f->af.subclass.integer,
3663 f->ts,
3664 f->oseqno);
3665 }
3666 iaxs[callno]->error = ETIMEDOUT;
3667 if (iaxs[callno]->owner) {
3669 /* Hangup the fd */
3670 iax2_queue_frame(callno, &fr); /* XXX */
3671 /* Remember, owner could disappear */
3672 if (iaxs[callno] && iaxs[callno]->owner)
3674 } else {
3675 if (iaxs[callno]->reg) {
3676 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3677 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3679 }
3680 iax2_destroy(callno);
3681 }
3682 }
3683 freeme = 1;
3684 } else {
3685 /* Update it if it needs it */
3686 update_packet(f);
3687 /* Attempt transmission */
3688 send_packet(f);
3689 f->retries++;
3690 /* Try again later after 10 times as long */
3691 f->retrytime *= 10;
3692 if (f->retrytime > MAX_RETRY_TIME)
3694 /* Transfer messages max out at one second */
3695 if (f->transfer && (f->retrytime > 1000))
3696 f->retrytime = 1000;
3698 }
3699 } else {
3700 /* Make sure it gets freed */
3701 f->retries = -1;
3702 freeme = 1;
3703 }
3704
3705 if (freeme) {
3706 /* Don't attempt delivery, just remove it from the queue */
3707 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3708 ast_mutex_unlock(&iaxsl[callno]);
3709 f->retrans = -1; /* this is safe because this is the scheduled function */
3710 /* Free the IAX frame */
3711 iax2_frame_free(f);
3712 } else if (callno) {
3713 ast_mutex_unlock(&iaxsl[callno]);
3714 }
3715}
3716
3717static int attempt_transmit(const void *data)
3718{
3719#ifdef SCHED_MULTITHREADED
3721#endif
3723 return 0;
3724}
3725
3726static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3727{
3728 struct iax2_peer *peer = NULL;
3729 struct iax2_user *user = NULL;
3730 static const char * const choices[] = { "all", NULL };
3731 char *cmplt;
3732
3733 switch (cmd) {
3734 case CLI_INIT:
3735 e->command = "iax2 prune realtime";
3736 e->usage =
3737 "Usage: iax2 prune realtime [<peername>|all]\n"
3738 " Prunes object(s) from the cache\n";
3739 return NULL;
3740 case CLI_GENERATE:
3741 if (a->pos == 3) {
3742 cmplt = ast_cli_complete(a->word, choices, a->n);
3743 if (!cmplt)
3744 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3745 return cmplt;
3746 }
3747 return NULL;
3748 }
3749 if (a->argc != 4)
3750 return CLI_SHOWUSAGE;
3751 if (!strcmp(a->argv[3], "all")) {
3752 prune_users();
3753 prune_peers();
3754 ast_cli(a->fd, "Cache flushed successfully.\n");
3755 return CLI_SUCCESS;
3756 }
3757 peer = find_peer(a->argv[3], 0);
3758 user = find_user(a->argv[3]);
3759 if (peer || user) {
3760 if (peer) {
3764 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3765 } else {
3766 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3767 }
3768 peer_unref(peer);
3769 }
3770 if (user) {
3773 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3774 } else {
3775 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3776 }
3779 }
3780 } else {
3781 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3782 }
3783
3784 return CLI_SUCCESS;
3785}
3786
3787static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3788{
3789 switch (cmd) {
3790 case CLI_INIT:
3791 e->command = "iax2 test losspct";
3792 e->usage =
3793 "Usage: iax2 test losspct <percentage>\n"
3794 " For testing, throws away <percentage> percent of incoming packets\n";
3795 return NULL;
3796 case CLI_GENERATE:
3797 return NULL;
3798 }
3799 if (a->argc != 4)
3800 return CLI_SHOWUSAGE;
3801
3802 test_losspct = atoi(a->argv[3]);
3803
3804 return CLI_SUCCESS;
3805}
3806
3807#ifdef IAXTESTS
3808static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3809{
3810 switch (cmd) {
3811 case CLI_INIT:
3812 e->command = "iax2 test late";
3813 e->usage =
3814 "Usage: iax2 test late <ms>\n"
3815 " For testing, count the next frame as <ms> ms late\n";
3816 return NULL;
3817 case CLI_GENERATE:
3818 return NULL;
3819 }
3820
3821 if (a->argc != 4)
3822 return CLI_SHOWUSAGE;
3823
3824 test_late = atoi(a->argv[3]);
3825
3826 return CLI_SUCCESS;
3827}
3828
3829static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3830{
3831 switch (cmd) {
3832 case CLI_INIT:
3833 e->command = "iax2 test resync";
3834 e->usage =
3835 "Usage: iax2 test resync <ms>\n"
3836 " For testing, adjust all future frames by <ms> ms\n";
3837 return NULL;
3838 case CLI_GENERATE:
3839 return NULL;
3840 }
3841
3842 if (a->argc != 4)
3843 return CLI_SHOWUSAGE;
3844
3845 test_resync = atoi(a->argv[3]);
3846
3847 return CLI_SUCCESS;
3848}
3849
3850static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3851{
3852 switch (cmd) {
3853 case CLI_INIT:
3854 e->command = "iax2 test jitter";
3855 e->usage =
3856 "Usage: iax2 test jitter <ms> <pct>\n"
3857 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3858 " percentage of packets. If <pct> is not specified, adds\n"
3859 " jitter to all packets.\n";
3860 return NULL;
3861 case CLI_GENERATE:
3862 return NULL;
3863 }
3864
3865 if (a->argc < 4 || a->argc > 5)
3866 return CLI_SHOWUSAGE;
3867
3868 test_jit = atoi(a->argv[3]);
3869 if (a->argc == 5)
3870 test_jitpct = atoi(a->argv[4]);
3871
3872 return CLI_SUCCESS;
3873}
3874#endif /* IAXTESTS */
3875
3876/*! \brief peer_status: Report Peer status in character string */
3877/* returns 1 if peer is online, -1 if unmonitored */
3878static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3879{
3880 int res = 0;
3881 if (peer->maxms) {
3882 if (peer->lastms < 0) {
3883 ast_copy_string(status, "UNREACHABLE", statuslen);
3884 } else if (peer->lastms > peer->maxms) {
3885 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3886 res = 1;
3887 } else if (peer->lastms) {
3888 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3889 res = 1;
3890 } else {
3891 ast_copy_string(status, "UNKNOWN", statuslen);
3892 }
3893 } else {
3894 ast_copy_string(status, "Unmonitored", statuslen);
3895 res = -1;
3896 }
3897 return res;
3898}
3899
3900/*! \brief Show one peer in detail */
3901static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3902{
3903 char status[64];
3904 char cbuf[256];
3905 struct iax2_peer *peer;
3906 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3907 struct ast_str *encmethods = ast_str_alloca(256);
3908 int load_realtime = 0;
3909
3910 switch (cmd) {
3911 case CLI_INIT:
3912 e->command = "iax2 show peer";
3913 e->usage =
3914 "Usage: iax2 show peer <name>\n"
3915 " Display details on specific IAX peer\n";
3916 return NULL;
3917 case CLI_GENERATE:
3918 if (a->pos == 3)
3919 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3920 return NULL;
3921 }
3922
3923 if (a->argc < 4)
3924 return CLI_SHOWUSAGE;
3925
3926 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3927
3928 peer = find_peer(a->argv[3], load_realtime);
3929 if (peer) {
3930 char *str_addr, *str_defaddr;
3931 char *str_port, *str_defport;
3932
3933 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3934 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3935 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3936 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3937
3938 encmethods_to_str(peer->encmethods, &encmethods);
3939 ast_cli(a->fd, "\n\n");
3940 ast_cli(a->fd, " * Name : %s\n", peer->name);
3941 ast_cli(a->fd, " Description : %s\n", peer->description);
3942 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3943 ast_cli(a->fd, " Context : %s\n", peer->context);
3944 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3945 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3946 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3947 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3948 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3949 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3950 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3951 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3952 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3953 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3954 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3955 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3956 ast_cli(a->fd, " Username : %s\n", peer->username);
3957 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3958
3959 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3960 strcpy(cbuf, "Error"); /* Safe */
3961 }
3962 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3963
3964 peer_status(peer, status, sizeof(status));
3965 ast_cli(a->fd, " Status : %s\n", status);
3966 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");
3967 ast_cli(a->fd, "\n");
3968 peer_unref(peer);
3969 } else {
3970 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3971 ast_cli(a->fd, "\n");
3972 }
3973
3974 return CLI_SUCCESS;
3975}
3976
3977static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3978{
3979 int which = 0;
3980 struct iax2_peer *peer;
3981 char *res = NULL;
3982 int wordlen = strlen(word);
3983 struct ao2_iterator i;
3984
3985 i = ao2_iterator_init(peers, 0);
3986 while ((peer = ao2_iterator_next(&i))) {
3987 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3988 && (!flags || ast_test_flag64(peer, flags))) {
3989 res = ast_strdup(peer->name);
3990 peer_unref(peer);
3991 break;
3992 }
3993 peer_unref(peer);
3994 }
3996
3997 return res;
3998}
3999
4000static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4001{
4002 struct iax_frame *cur;
4003 int cnt = 0, dead = 0, final = 0, i = 0;
4004
4005 switch (cmd) {
4006 case CLI_INIT:
4007 e->command = "iax2 show stats";
4008 e->usage =
4009 "Usage: iax2 show stats\n"
4010 " Display statistics on IAX channel driver.\n";
4011 return NULL;
4012 case CLI_GENERATE:
4013 return NULL;
4014 }
4015
4016 if (a->argc != 3)
4017 return CLI_SHOWUSAGE;
4018
4019 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
4020 ast_mutex_lock(&iaxsl[i]);
4022 if (cur->retries < 0)
4023 dead++;
4024 if (cur->final)
4025 final++;
4026 cnt++;
4027 }
4029 }
4030
4031 ast_cli(a->fd, " IAX Statistics\n");
4032 ast_cli(a->fd, "---------------------\n");
4033 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
4034 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
4036 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
4037
4041
4042 return CLI_SUCCESS;
4043}
4044
4045/*! \brief Set trunk MTU from CLI */
4046static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4047{
4048 int mtuv;
4049
4050 switch (cmd) {
4051 case CLI_INIT:
4052 e->command = "iax2 set mtu";
4053 e->usage =
4054 "Usage: iax2 set mtu <value>\n"
4055 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
4056 " zero to disable. Disabling means that the operating system\n"
4057 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
4058 " packet exceeds the UDP payload size. This is substantially\n"
4059 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4060 " greater for G.711 samples.\n";
4061 return NULL;
4062 case CLI_GENERATE:
4063 return NULL;
4064 }
4065
4066 if (a->argc != 4)
4067 return CLI_SHOWUSAGE;
4068 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4069 mtuv = MAX_TRUNK_MTU;
4070 else
4071 mtuv = atoi(a->argv[3]);
4072
4073 if (mtuv == 0) {
4074 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4076 return CLI_SUCCESS;
4077 }
4078 if (mtuv < 172 || mtuv > 4000) {
4079 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4080 return CLI_SHOWUSAGE;
4081 }
4082 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4083 global_max_trunk_mtu = mtuv;
4084 return CLI_SUCCESS;
4085}
4086
4087static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4088{
4089 struct iax2_dpcache *dp = NULL;
4090 char tmp[1024], *pc = NULL;
4091 int s, x, y;
4092 struct timeval now = ast_tvnow();
4093
4094 switch (cmd) {
4095 case CLI_INIT:
4096 e->command = "iax2 show cache";
4097 e->usage =
4098 "Usage: iax2 show cache\n"
4099 " Display currently cached IAX Dialplan results.\n";
4100 return NULL;
4101 case CLI_GENERATE:
4102 return NULL;
4103 }
4104
4106
4107 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4108
4109 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4110 s = dp->expiry.tv_sec - now.tv_sec;
4111 tmp[0] = '\0';
4112 if (dp->flags & CACHE_FLAG_EXISTS)
4113 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4114 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4115 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4116 if (dp->flags & CACHE_FLAG_CANEXIST)
4117 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4118 if (dp->flags & CACHE_FLAG_PENDING)
4119 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4120 if (dp->flags & CACHE_FLAG_TIMEOUT)
4121 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4122 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4123 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4124 if (dp->flags & CACHE_FLAG_MATCHMORE)
4125 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4126 if (dp->flags & CACHE_FLAG_UNKNOWN)
4127 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4128 /* Trim trailing pipe */
4129 if (!ast_strlen_zero(tmp)) {
4130 tmp[strlen(tmp) - 1] = '\0';
4131 } else {
4132 ast_copy_string(tmp, "(none)", sizeof(tmp));
4133 }
4134 y = 0;
4135 pc = strchr(dp->peercontext, '@');
4136 if (!pc) {
4137 pc = dp->peercontext;
4138 } else {
4139 pc++;
4140 }
4141 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4142 if (dp->waiters[x] > -1)
4143 y++;
4144 }
4145 if (s > 0) {
4146 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4147 } else {
4148 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4149 }
4150 }
4151
4153
4154 return CLI_SUCCESS;
4155}
4156
4157static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4158
4159static void unwrap_timestamp(struct iax_frame *fr)
4160{
4161 /* Video mini frames only encode the lower 15 bits of the session
4162 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4163 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4164 const int lower_mask = (1 << ts_shift) - 1;
4165 const int upper_mask = ~lower_mask;
4166 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4167
4168 if ( (fr->ts & upper_mask) == last_upper ) {
4169 const int x = fr->ts - iaxs[fr->callno]->last;
4170 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4171
4172 if (x < -threshold) {
4173 /* Sudden big jump backwards in timestamp:
4174 What likely happened here is that miniframe timestamp has circled but we haven't
4175 gotten the update from the main packet. We'll just pretend that we did, and
4176 update the timestamp appropriately. */
4177 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4178 if (iaxdebug)
4179 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4180 } else if (x > threshold) {
4181 /* Sudden apparent big jump forwards in timestamp:
4182 What's likely happened is this is an old miniframe belonging to the previous
4183 top 15 or 16-bit timestamp that has turned up out of order.
4184 Adjust the timestamp appropriately. */
4185 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4186 if (iaxdebug)
4187 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4188 }
4189 }
4190}
4191
4192static int get_from_jb(const void *p);
4193
4194static void update_jbsched(struct chan_iax2_pvt *pvt)
4195{
4196 int when;
4197
4198 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4199
4200 when = jb_next(pvt->jb) - when;
4201
4202 if (when <= 0) {
4203 /* XXX should really just empty until when > 0.. */
4204 when = 1;
4205 }
4206
4207 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4208 CALLNO_TO_PTR(pvt->callno));
4209}
4210
4211static void __get_from_jb(const void *p)
4212{
4213 int callno = PTR_TO_CALLNO(p);
4214 struct chan_iax2_pvt *pvt = NULL;
4215 struct iax_frame *fr;
4216 jb_frame frame;
4217 int ret;
4218 long ms;
4219 long next;
4220 struct timeval now = ast_tvnow();
4221 struct ast_format *voicefmt;
4222
4223 /* Make sure we have a valid private structure before going on */
4224 ast_mutex_lock(&iaxsl[callno]);
4225 pvt = iaxs[callno];
4226 if (!pvt) {
4227 /* No go! */
4228 ast_mutex_unlock(&iaxsl[callno]);
4229 return;
4230 }
4231
4232 pvt->jbid = -1;
4233
4234 /* round up a millisecond since ast_sched_runq does; */
4235 /* prevents us from spinning while waiting for our now */
4236 /* to catch up with runq's now */
4237 now.tv_usec += 1000;
4238
4239 ms = ast_tvdiff_ms(now, pvt->rxcore);
4240 if (ms >= (next = jb_next(pvt->jb))) {
4242 if (!voicefmt) {
4243 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4244 * In this case, fall back to using the format negotiated during call setup,
4245 * so we don't stall the jitterbuffer completely. */
4247 if (!voicefmt) {
4248 /* As a last resort, we can use pvt->chosenformat.
4249 * This is set when we receive a call (either authenticated or unauthenticated),
4250 * so even if we haven't received any voice frames yet, we can still use the
4251 * right format.
4252 *
4253 * If we have to do this, in most cases, we aren't even processing voice frames
4254 * anyways, it's likely a non-voice frame. In that case, the format doesn't
4255 * really matter so much, because we could just pass 20 to jb_get instead
4256 * of calling ast_format_get_default_ms. However, until jb_get returns,
4257 * we don't actually know what kind of frame it is for sure, so use
4258 * the right format just to be safe. */
4260 }
4261 }
4262 if (!voicefmt) {
4263 /* This should never happen, since we should always be able to have an acceptable format to use. */
4264 ast_log(LOG_ERROR, "No voice, peer, or chosen format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4265 goto cleanup; /* Don't crash if there's no voice format */
4266 }
4267 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4268 switch(ret) {
4269 case JB_OK:
4270 fr = frame.data;
4271 __do_deliver(fr);
4272 /* __do_deliver() can cause the call to disappear */
4273 pvt = iaxs[callno];
4274 break;
4275 case JB_INTERP:
4276 {
4277 struct ast_frame af = { 0, };
4278
4279 /* create an interpolation frame */
4281 af.subclass.format = voicefmt;
4282 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4283 af.src = "IAX2 JB interpolation";
4284 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4286
4287 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4288 * which we'd need to malloc, and then it would free it. That seems like a drag */
4289 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4290 iax2_queue_frame(callno, &af);
4291 /* iax2_queue_frame() could cause the call to disappear */
4292 pvt = iaxs[callno];
4293 }
4294 }
4295 break;
4296 case JB_DROP:
4297 iax2_frame_free(frame.data);
4298 break;
4299 case JB_NOFRAME:
4300 case JB_EMPTY:
4301 /* do nothing */
4302 break;
4303 default:
4304 /* shouldn't happen */
4305 break;
4306 }
4307 }
4308cleanup:
4309 if (pvt)
4310 update_jbsched(pvt);
4311 ast_mutex_unlock(&iaxsl[callno]);
4312}
4313
4314static int get_from_jb(const void *data)
4315{
4316#ifdef SCHED_MULTITHREADED
4318#endif
4320 return 0;
4321}
4322
4323/*!
4324 * \note This function assumes fr->callno is locked
4325 *
4326 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4327 * was valid before calling it, it may no longer be valid after calling it.
4328 */
4329static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4330{
4331 int type, len;
4332 int ret;
4333 int needfree = 0;
4334
4335 /*
4336 * Clear fr->af.data if there is no data in the buffer. Things
4337 * like AST_CONTROL_HOLD without a suggested music class must
4338 * have a NULL pointer.
4339 */
4340 if (!fr->af.datalen) {
4341 memset(&fr->af.data, 0, sizeof(fr->af.data));
4342 }
4343
4344 /* Attempt to recover wrapped timestamps */
4345 unwrap_timestamp(fr);
4346
4347 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4348 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4349 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4350 else {
4351#if 0
4352 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4353#endif
4354 fr->af.delivery = ast_tv(0,0);
4355 }
4356
4358 len = 0;
4359
4360 if(fr->af.frametype == AST_FRAME_VOICE) {
4363 } else if(fr->af.frametype == AST_FRAME_CNG) {
4365 }
4366
4367 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4368 if (tsout)
4369 *tsout = fr->ts;
4370 __do_deliver(fr);
4371 return -1;
4372 }
4373
4374 /* insert into jitterbuffer */
4375 /* TODO: Perhaps we could act immediately if it's not droppable and late */
4376 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4377 calc_rxstamp(iaxs[fr->callno],fr->ts));
4378 if (ret == JB_DROP) {
4379 needfree++;
4380 } else if (ret == JB_SCHED) {
4382 }
4383 if (tsout)
4384 *tsout = fr->ts;
4385 if (needfree) {
4386 /* Free our iax frame */
4387 iax2_frame_free(fr);
4388 return -1;
4389 }
4390 return 0;
4391}
4392
4393static int transmit_frame(void *data)
4394{
4395 struct iax_frame *fr = data;
4396
4398
4399 fr->sentyet = 1;
4400
4401 if (iaxs[fr->callno]) {
4402 send_packet(fr);
4403 }
4404
4405 if (fr->retries < 0) {
4407 /* No retransmit requested */
4408 iax_frame_free(fr);
4409 } else {
4410 /* We need reliable delivery. Schedule a retransmission */
4412 fr->retries++;
4415 }
4416
4417 return 0;
4418}
4419
4420static int iax2_transmit(struct iax_frame *fr)
4421{
4422 fr->sentyet = 0;
4423
4425}
4426
4431
4432static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4433{
4435}
4436
4437static int iax2_sendtext(struct ast_channel *c, const char *text)
4438{
4439
4441 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4442}
4443
4444static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4445{
4447}
4448
4449static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4450{
4451 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4452}
4453
4454static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4455{
4456 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4458 if (iaxs[callno])
4459 iaxs[callno]->owner = newchan;
4460 else
4461 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4463 return 0;
4464}
4465
4466/*!
4467 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4468 * so do not call this with a pvt lock held.
4469 */
4470static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4471{
4472 struct ast_variable *var = NULL;
4473 struct ast_variable *tmp;
4474 struct iax2_peer *peer=NULL;
4475 time_t regseconds = 0, nowtime;
4476 int dynamic=0;
4477 char *str_addr, *str_port;
4478
4481
4482 if (peername) {
4483 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4484 if (!var && !ast_sockaddr_isnull(addr)) {
4485 var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4486 }
4487 } else if (!ast_sockaddr_isnull(addr)) {
4488 var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4489 if (var) {
4490 /* We'll need the peer name in order to build the structure! */
4491 for (tmp = var; tmp; tmp = tmp->next) {
4492 if (!strcasecmp(tmp->name, "name"))
4493 peername = tmp->value;
4494 }
4495 }
4496 }
4497 if (!var && peername) { /* Last ditch effort */
4498 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4499 /*!\note
4500 * If this one loaded something, then we need to ensure that the host
4501 * field matched. The only reason why we can't have this as a criteria
4502 * is because we only have the IP address and the host field might be
4503 * set as a name (and the reverse PTR might not match).
4504 */
4505 if (var && !ast_sockaddr_isnull(addr)) {
4506 for (tmp = var; tmp; tmp = tmp->next) {
4507 if (!strcasecmp(tmp->name, "host")) {
4508 struct ast_sockaddr *hostaddr = NULL;
4509
4511 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4512 /* No match */
4514 var = NULL;
4515 }
4516 ast_free(hostaddr);
4517 break;
4518 }
4519 }
4520 }
4521 }
4522 if (!var)
4523 return NULL;
4524
4525 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4526
4527 if (!peer) {
4529 return NULL;
4530 }
4531
4532 for (tmp = var; tmp; tmp = tmp->next) {
4533 /* Make sure it's not a user only... */
4534 if (!strcasecmp(tmp->name, "type")) {
4535 if (strcasecmp(tmp->value, "friend") &&
4536 strcasecmp(tmp->value, "peer")) {
4537 /* Whoops, we weren't supposed to exist! */
4538 peer = peer_unref(peer);
4539 break;
4540 }
4541 } else if (!strcasecmp(tmp->name, "regseconds")) {
4542 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4543 } else if (!strcasecmp(tmp->name, "ipaddr")) {
4544 int setport = ast_sockaddr_port(&peer->addr);
4546 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4547 } else {
4548 ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4549 }
4550 ast_sockaddr_set_port(&peer->addr, setport);
4551 } else if (!strcasecmp(tmp->name, "port")) {
4552 int bindport;
4553 if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4554 bindport = IAX_DEFAULT_PORTNO;
4555 }
4556 ast_sockaddr_set_port(&peer->addr, bindport);
4557 } else if (!strcasecmp(tmp->name, "host")) {
4558 if (!strcasecmp(tmp->value, "dynamic"))
4559 dynamic = 1;
4560 }
4561 }
4562
4564
4567 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4568 if (peer->expire > -1) {
4569 if (!AST_SCHED_DEL(sched, peer->expire)) {
4570 peer->expire = -1;
4571 peer_unref(peer);
4572 }
4573 }
4575 if (peer->expire == -1)
4576 peer_unref(peer);
4577 }
4578 ao2_link(peers, peer);
4579 if (ast_test_flag64(peer, IAX_DYNAMIC))
4580 reg_source_db(peer);
4581 } else {
4583 }
4584
4586 time(&nowtime);
4587 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4588 memset(&peer->addr, 0, sizeof(peer->addr));
4589 realtime_update_peer(peer->name, &peer->addr, 0);
4590 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4591 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4592 }
4593 else {
4594 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4595 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4596 }
4597 }
4598
4599 return peer;
4600}
4601
4602static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4603{
4604 struct ast_variable *var;
4605 struct ast_variable *tmp;
4606 struct iax2_user *user=NULL;
4607 char *str_addr, *str_port;
4608
4609 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4610 str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4611
4612 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4613 if (!var)
4614 var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4615 if (!var && !ast_sockaddr_isnull(addr)) {
4616 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4617 if (!var)
4618 var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4619 }
4620 if (!var) { /* Last ditch effort */
4621 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4622 /*!\note
4623 * If this one loaded something, then we need to ensure that the host
4624 * field matched. The only reason why we can't have this as a criteria
4625 * is because we only have the IP address and the host field might be
4626 * set as a name (and the reverse PTR might not match).
4627 */
4628 if (var) {
4629 for (tmp = var; tmp; tmp = tmp->next) {
4630 if (!strcasecmp(tmp->name, "host")) {
4631 struct ast_sockaddr *hostaddr = NULL;
4632
4634 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4635 /* No match */
4637 var = NULL;
4638 }
4639 ast_free(hostaddr);
4640 break;
4641 }
4642 }
4643 }
4644 }
4645 if (!var)
4646 return NULL;
4647
4648 tmp = var;
4649 while(tmp) {
4650 /* Make sure it's not a peer only... */
4651 if (!strcasecmp(tmp->name, "type")) {
4652 if (strcasecmp(tmp->value, "friend") &&
4653 strcasecmp(tmp->value, "user")) {
4654 return NULL;
4655 }
4656 }
4657 tmp = tmp->next;
4658 }
4659
4661
4663
4664 if (!user)
4665 return NULL;
4666
4670 } else {
4672 }
4673
4674 return user;
4675}
4676
4677static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4678{
4679 char regseconds[20];
4680 const char *sysname = ast_config_AST_SYSTEM_NAME;
4681 char *syslabel = NULL;
4682 char *port;
4683
4684 if (ast_strlen_zero(sysname)) /* No system name, disable this */
4685 sysname = NULL;
4687 syslabel = "regserver";
4688
4689 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4690 port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4691 ast_update_realtime("iaxpeers", "name", peername,
4692 "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4693 "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4694 "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslabel can be NULL */
4695}
4696
4718
4719static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4720{
4721 struct iax2_peer *peer;
4722 int res = -1;
4723
4725 cai->sockfd = defaultsockfd;
4726 cai->maxtime = 0;
4727
4728 if (!(peer = find_peer(peername, 1))) {
4729 struct ast_sockaddr peer_addr;
4730
4731 peer_addr.ss.ss_family = AST_AF_UNSPEC;
4732 cai->found = 0;
4733 if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4734 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4735 return -1;
4736 }
4737
4738 if (!ast_sockaddr_port(&peer_addr)) {
4740 }
4741
4742 ast_sockaddr_copy(addr, &peer_addr);
4743 /*
4744 * Use The global iax prefs for unknown peer/user.
4745 * However, move the calling channel's native codec to
4746 * the top of the preference list.
4747 */
4748 cai->prefs = prefs_global;
4749 if (c) {
4750 int i;
4751
4752 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4753 struct ast_format *format = ast_format_cap_get_format(
4755 iax2_codec_pref_prepend(&cai->prefs, format,
4757 1);
4758 ao2_ref(format, -1);
4759 }
4760 }
4761 return 0;
4762 }
4763
4764 cai->found = 1;
4765
4766 /* if the peer has no address (current or default), return failure */
4767 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4768 goto return_unref;
4769 }
4770
4771 /* if the peer is being monitored and is currently unreachable, return failure */
4772 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4773 goto return_unref;
4774
4776 cai->maxtime = peer->maxms;
4777 cai->capability = peer->capability;
4778 cai->encmethods = peer->encmethods;
4779 cai->authmethods = peer->authmethods;
4780 cai->sockfd = peer->sockfd;
4781 cai->adsi = peer->adsi;
4782 cai->prefs = peer->prefs;
4783 /* Move the calling channel's native codec to the top of the preference list */
4784 if (c) {
4785 int i;
4786
4787 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4788 struct ast_format *tmpfmt = ast_format_cap_get_format(
4790 iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4792 1);
4793 ao2_ref(tmpfmt, -1);
4794 }
4795 }
4796 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4797 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4798 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4799 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4800 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4801 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4802 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4803 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4804 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4805 if (ast_strlen_zero(peer->dbsecret)) {
4806 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4807 } else {
4808 char *family;
4809 char *key = NULL;
4810
4811 family = ast_strdupa(peer->dbsecret);
4812 key = strchr(family, '/');
4813 if (key)
4814 *key++ = '\0';
4815 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4816 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4817 goto return_unref;
4818 }
4819 }
4820
4821 if (!ast_sockaddr_isnull(&peer->addr)) {
4822 ast_sockaddr_copy(addr, &peer->addr);
4823 } else {
4824 ast_sockaddr_copy(addr, &peer->defaddr);
4825 }
4826
4827 res = 0;
4828
4829return_unref:
4830 peer_unref(peer);
4831
4832 return res;
4833}
4834
4835static void __auto_congest(const void *nothing)
4836{
4837 int callno = PTR_TO_CALLNO(nothing);
4839 ast_mutex_lock(&iaxsl[callno]);
4840 if (iaxs[callno]) {
4841 iaxs[callno]->initid = -1;
4842 iax2_queue_frame(callno, &f);
4843 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4844 }
4845 ast_mutex_unlock(&iaxsl[callno]);
4846}
4847
4848static int auto_congest(const void *data)
4849{
4850#ifdef SCHED_MULTITHREADED
4852#endif
4854 return 0;
4855}
4856
4857static unsigned int iax2_datetime(const char *tz)
4858{
4859 struct timeval t = ast_tvnow();
4860 struct ast_tm tm;
4861 unsigned int tmp;
4862 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4863 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4864 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4865 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4866 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4867 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4868 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4869 return tmp;
4870}
4871
4875 char *key;
4876 char *peer;
4877 char *port;
4878 char *exten;
4879 char *context;
4880 char *options;
4881};
4882
4883static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4884 struct ast_sockaddr *addr, int command, int ts, unsigned char seqno,
4885 int sockfd, struct iax_ie_data *ied)
4886{
4887 struct {
4888 struct ast_iax2_full_hdr f;
4889 struct iax_ie_data ied;
4890 } data;
4891 size_t size = sizeof(struct ast_iax2_full_hdr);
4892
4893 if (ied) {
4894 size += ied->pos;
4895 memcpy(&data.ied, ied->buf, ied->pos);
4896 }
4897
4898 data.f.scallno = htons(0x8000 | callno);
4899 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4900 data.f.ts = htonl(ts);
4901 data.f.iseqno = seqno;
4902 data.f.oseqno = 0;
4903 data.f.type = AST_FRAME_IAX;
4904 data.f.csub = compress_subclass(command);
4905
4906 iax_outputframe(NULL, &data.f, 0, addr, size - sizeof(struct ast_iax2_full_hdr));
4907
4908 return ast_sendto(sockfd, &data, size, 0, addr);
4909}
4910
4911static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4912{
4913 /* first make sure their are two empty bytes left in ied->buf */
4914 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4915 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4916 ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4917 pvt->calltoken_ie_len = 2;
4918 }
4919}
4920
4921static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4922{
4923 struct chan_iax2_pvt *pvt = iaxs[callno];
4924 int frametype = f->af.frametype;
4925 int subclass = f->af.subclass.integer;
4926 struct {
4927 struct ast_iax2_full_hdr fh;
4928 struct iax_ie_data ied;
4929 } data = {
4930 .ied.buf = { 0 },
4931 .ied.pos = 0,
4932 };
4933 /* total len - header len gives us the frame's IE len */
4934 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4935
4936 if (!pvt) {
4937 return; /* this should not be possible if called from socket_process() */
4938 }
4939
4940 /*
4941 * Check to make sure last frame sent is valid for call token resend
4942 * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4943 * 2. Frame should _NOT_ already have a destination callno
4944 * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4945 * 4. Pvt must have a calltoken_ie_len which represents the number of
4946 * bytes at the end of the frame used for the previous calltoken ie.
4947 * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4948 * 6. Total length of f->data must be _LESS_ than size of our data struct
4949 * because f->data must be able to fit within data.
4950 */
4951 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4952 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4953 (f->datalen > sizeof(data))) {
4954
4955 return; /* ignore resend, token was not valid for the dialog */
4956 }
4957
4958 /* token is valid
4959 * 1. Copy frame data over
4960 * 2. Redo calltoken IE, it will always be the last ie in the frame.
4961 * NOTE: Having the ie always be last is not protocol specified,
4962 * it is only an implementation choice. Since we only expect the ie to
4963 * be last for frames we have sent, this can no way be affected by
4964 * another end point.
4965 * 3. Remove frame from queue
4966 * 4. Free old frame
4967 * 5. Clear previous seqnos
4968 * 6. Resend with CALLTOKEN ie.
4969 */
4970
4971 /* ---1.--- */
4972 memcpy(&data, f->data, f->datalen);
4973 data.ied.pos = ie_data_pos;
4974
4975 /* ---2.--- */
4976 /* move to the beginning of the calltoken ie so we can write over it */
4977 data.ied.pos -= pvt->calltoken_ie_len;
4978 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4979
4980 /* make sure to update token length incase it ever has to be stripped off again */
4981 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4982
4983 /* ---3.--- */
4984 AST_LIST_REMOVE(&frame_queue[callno], f, list);
4985
4986 /* ---4.--- */
4987 iax2_frame_free(f);
4988
4989 /* ---5.--- */
4990 pvt->oseqno = 0;
4991 pvt->rseqno = 0;
4992 pvt->iseqno = 0;
4993 pvt->aseqno = 0;
4994 if (pvt->peercallno) {
4996 pvt->peercallno = 0;
4997 }
4998
4999 /* ---6.--- */
5000 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
5001}
5002
5003static void requirecalltoken_mark_auto(const char *name, int subclass)
5004{
5005 struct iax2_user *user = NULL;
5006 struct iax2_peer *peer = NULL;
5007
5008 if (ast_strlen_zero(name)) {
5009 return; /* no username given */
5010 }
5011
5012 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
5013 user->calltoken_required = CALLTOKEN_YES;
5014 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
5016 }
5017
5018 if (peer) {
5019 peer_unref(peer);
5020 }
5021 if (user) {
5023 }
5024}
5025
5026/*!
5027 * \internal
5028 *
5029 * \brief handles calltoken logic for a received iax_frame.
5030 *
5031 * \note frametype must be AST_FRAME_IAX.
5032 *
5033 * \note
5034 * Three different cases are possible here.
5035 * Case 1. An empty calltoken is provided. This means the client supports
5036 * calltokens but has not yet received one from us. In this case
5037 * a full calltoken IE is created and sent in a calltoken fullframe.
5038 * Case 2. A full calltoken is received and must be checked for validity.
5039 * Case 3. No calltoken is received indicating that the client does not
5040 * support calltokens. In this case it is up to the configuration
5041 * to decide how this should be handled (reject or permit without calltoken)
5042 */
5043static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
5044 struct ast_sockaddr *addr, int fd)
5045{
5046#define CALLTOKEN_HASH_FORMAT "%s%u%d" /* address + port + ts + randomcalldata */
5047#define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
5048 struct ast_str *buf = ast_str_alloca(256);
5049 time_t t = time(NULL);
5050 char hash[41]; /* 40 char sha1 hash */
5051 int subclass = uncompress_subclass(fh->csub);
5052
5053 /* ----- Case 1 ----- */
5054 if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
5055 struct iax_ie_data ied = {
5056 .buf = { 0 },
5057 .pos = 0,
5058 };
5059
5060 /* create the hash with their address data and our timestamp */
5063
5064 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
5066 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
5067
5068 return 1;
5069
5070 /* ----- Case 2 ----- */
5071 } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
5072 char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
5073 char *rec_ts = NULL; /* received timestamp */
5074 unsigned int rec_time; /* received time_t */
5075
5076 /* split the timestamp from the hash data */
5077 rec_hash = strchr((char *) ies->calltokendata, '?');
5078 if (rec_hash) {
5079 *rec_hash++ = '\0';
5080 rec_ts = (char *) ies->calltokendata;
5081 }
5082
5083 /* check that we have valid data before we do any comparisons */
5084 if (!rec_hash || !rec_ts) {
5085 goto reject;
5086 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
5087 goto reject;
5088 }
5089
5090 /* create a hash with their address and the _TOKEN'S_ timestamp */
5093
5094 /* compare hashes and then check timestamp delay */
5095 if (strcmp(hash, rec_hash)) {
5096 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_sockaddr_stringify(addr));
5097 goto reject; /* received hash does not match ours, reject */
5098 } else if ((t < rec_time) || ((t - rec_time) >= max_calltoken_delay)) {
5099 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_sockaddr_stringify(addr));
5100 goto reject; /* too much delay, reject */
5101 }
5102
5103 /* at this point the call token is valid, returning 0
5104 * will allow socket_process to continue as usual */
5105 requirecalltoken_mark_auto(ies->username, subclass);
5106 return 0;
5107
5108 /* ----- Case 3 ----- */
5109 } else { /* calltokens are not supported for this client, how do we respond? */
5110 if (calltoken_required(addr, ies->username, subclass)) {
5111 ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_sockaddr_stringify(addr), S_OR(ies->username, "guest"));
5112 goto reject;
5113 }
5114 return 0; /* calltoken is not required for this addr, so permit it. */
5115 }
5116
5117reject:
5118 /* received frame has failed calltoken inspection, send apathetic reject messages */
5119 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5120 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5121 } else {
5122 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5123 }
5124
5125 return 1;
5126}
5127
5128/*!
5129 * \brief Parses an IAX dial string into its component parts.
5130 * \param data the string to be parsed
5131 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5132 *
5133 * This function parses the string and fills the structure
5134 * with pointers to its component parts. The input string
5135 * will be modified.
5136 *
5137 * \note This function supports both plaintext passwords and RSA
5138 * key names; if the password string is formatted as '[keyname]',
5139 * then the keyname will be placed into the key field, and the
5140 * password field will be set to NULL.
5141 *
5142 * \note The dial string format is:
5143 * \verbatim [username[:password]@]peer[:port][/exten[@context]][/options] \endverbatim
5144 */
5145static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5146{
5147 char *outkey = NULL;
5148
5149 if (ast_strlen_zero(data))
5150 return;
5151
5152 pds->peer = strsep(&data, "/");
5153 pds->exten = strsep(&data, "/");
5154 pds->options = data;
5155
5156 if (pds->exten) {
5157 data = pds->exten;
5158 pds->exten = strsep(&data, "@");
5159 pds->context = data;
5160 }
5161
5162 if (strchr(pds->peer, '@')) {
5163 data = pds->peer;
5164 pds->username = strsep(&data, "@");
5165 pds->peer = data;
5166 }
5167
5168 if (pds->username) {
5169 data = pds->username;
5170 pds->username = strsep(&data, ":");
5171 pds->password = strsep(&data, ":");
5172 outkey = data;
5173 }
5174
5175 data = pds->peer;
5176 pds->peer = strsep(&data, ":");
5177 pds->port = data;
5178
5179 /*
5180 * Check for a key name wrapped in [] in the password position.
5181 * If found, move it to the key field instead.
5182 * Also allow for both key and secret to be specified, now that
5183 * encryption is possible with RSA authentication.
5184 */
5185
5186 if (pds->password && (pds->password[0] == '[')) { /* key (then maybe secret) */
5187 pds->key = ast_strip_quoted(pds->password, "[", "]");
5188 if (ast_strlen_zero(outkey)) {
5189 pds->password = NULL;
5190 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5191 } else {
5192 pds->password = outkey;
5193 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5194 }
5195 } else if (outkey && (outkey[0] == '[')) { /* secret, then key */
5196 pds->key = ast_strip_quoted(outkey, "[", "]");
5197 if (ast_strlen_zero(pds->password)) {
5198 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5199 } else {
5200 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5201 }
5202 }
5203}
5204
5205static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
5206{
5207 struct ast_sockaddr addr;
5208 char *l=NULL, *n=NULL, *tmpstr;
5209 struct iax_ie_data ied;
5210 char *defaultrdest = "s";
5211 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5212 struct parsed_dial_string pds;
5213 struct create_addr_info cai;
5214 struct ast_var_t *var;
5216 const char* osp_token_ptr;
5217 unsigned int osp_token_length;
5218 unsigned char osp_block_index;
5219 unsigned int osp_block_length;
5220 unsigned char osp_buffer[256];
5221 char encoded_prefs[32];
5222 iax2_format iax2_tmpfmt;
5223
5225 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
5226 return -1;
5227 }
5228
5229 memset(&cai, 0, sizeof(cai));
5232
5233 memset(&pds, 0, sizeof(pds));
5234 tmpstr = ast_strdupa(dest);
5235 parse_dial_string(tmpstr, &pds);
5236
5237 if (ast_strlen_zero(pds.peer)) {
5238 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5239 return -1;
5240 }
5241 if (!pds.exten) {
5242 pds.exten = defaultrdest;
5243 }
5244 if (create_addr(pds.peer, c, &addr, &cai)) {
5245 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5246 return -1;
5247 }
5248
5251 if (!cai.encmethods) {
5252 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5254 return -1;
5255 }
5256 if (((cai.authmethods & IAX_AUTH_RSA) || (cai.authmethods & IAX_AUTH_MD5) || (cai.authmethods & IAX_AUTH_PLAINTEXT)) &&
5258 ast_log(LOG_WARNING, "Call terminated. Encryption forced but no secret provided\n");
5259 return -1;
5260 }
5261 }
5262
5263 if (!pds.username && !ast_strlen_zero(cai.username))
5264 pds.username = cai.username;
5265 if (!pds.password && !ast_strlen_zero(cai.secret))
5266 pds.password = cai.secret;
5267 if (!pds.key && !ast_strlen_zero(cai.outkey))
5268 pds.key = cai.outkey;
5269 if (!pds.context && !ast_strlen_zero(cai.peercontext))
5270 pds.context = cai.peercontext;
5271
5272 /* Keep track of the context for outgoing calls too */
5274
5275 if (pds.port) {
5276 int bindport;
5277 if (ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
5278 ast_sockaddr_set_port(&addr, bindport);
5279 }
5280 }
5281
5284
5285 /* Now build request */
5286 memset(&ied, 0, sizeof(ied));
5287
5288 /* On new call, first IE MUST be IAX version of caller */
5291 if (pds.options && strchr(pds.options, 'a')) {
5292 /* Request auto answer */
5294 }
5295
5296 /* WARNING: this breaks down at 190 bits! */
5297 iax2_codec_pref_convert(&cai.prefs, encoded_prefs, sizeof(encoded_prefs), 1);
5298 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, encoded_prefs);
5299
5300 if (l) {
5304 } else if (n) {
5307 } else {
5309 }
5310
5312 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
5314
5315 if (n)
5317 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5318 && ast_channel_connected(c)->ani.number.valid
5319 && ast_channel_connected(c)->ani.number.str) {
5321 }
5322
5327 }
5328 if (ast_channel_redirecting(c)->from.number.valid
5329 && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
5330 iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
5331 }
5332
5333 if (pds.context)
5335
5336 if (pds.username)
5338
5339 if (cai.encmethods)
5341
5342 ast_mutex_lock(&iaxsl[callno]);
5343
5345 ast_string_field_set(iaxs[callno], context, ast_channel_context(c));
5346
5347 if (pds.username)
5348 ast_string_field_set(iaxs[callno], username, pds.username);
5349
5350 iaxs[callno]->encmethods = cai.encmethods;
5351
5352 iaxs[callno]->adsi = cai.adsi;
5353
5356
5357 if (pds.key)
5358 ast_string_field_set(iaxs[callno], outkey, pds.key);
5359 if (pds.password)
5360 ast_string_field_set(iaxs[callno], secret, pds.password);
5361
5363 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
5364 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
5365
5366 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5367 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
5370
5371 if (iaxs[callno]->maxtime) {
5372 /* Initialize pingtime and auto-congest time */
5373 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5374 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5375 } else if (autokill) {
5376 iaxs[callno]->pingtime = autokill / 2;
5378 }
5379
5380 /* Check if there is an OSP token */
5381 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5382 if (!ast_strlen_zero(osp_token_ptr)) {
5383 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5384 osp_block_index = 0;
5385 while (osp_token_length > 0) {
5386 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5387 osp_buffer[0] = osp_block_index;
5388 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5389 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5390 osp_block_index++;
5391 osp_token_ptr += osp_block_length;
5392 osp_token_length -= osp_block_length;
5393 }
5394 } else
5395 ast_log(LOG_WARNING, "OSP token is too long\n");
5396 } else if (iaxdebug)
5397 ast_debug(1, "OSP token is undefined\n");
5398
5399 /* send the command using the appropriate socket for this peer */
5400 iaxs[callno]->sockfd = cai.sockfd;
5401
5402 /* Add remote vars */
5403 if (variablestore) {
5404 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5405 ast_debug(1, "Found an IAX variable store on this channel\n");
5406 AST_LIST_LOCK(variablelist);
5407 AST_LIST_TRAVERSE(variablelist, var, entries) {
5408 char tmp[256];
5409 int i;
5410 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5411 /* Automatically divide the value up into sized chunks */
5412 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5413 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5415 }
5416 }
5417 AST_LIST_UNLOCK(variablelist);
5418 }
5419
5420 /* Transmit the string in a "NEW" request */
5421 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5422 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5423
5424 ast_mutex_unlock(&iaxsl[callno]);
5426
5427 return 0;
5428}
5429
5430static int iax2_hangup(struct ast_channel *c)
5431{
5432 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5433 struct iax_ie_data ied;
5434 int alreadygone;
5435 memset(&ied, 0, sizeof(ied));
5436 ast_mutex_lock(&iaxsl[callno]);
5437 if (callno && iaxs[callno]) {
5438 ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
5439 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5440 /* Send the hangup unless we have had a transmission error or are already gone */
5442 if (!iaxs[callno]->error && !alreadygone) {
5443 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5444 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5445 }
5446 if (!iaxs[callno]) {
5447 ast_mutex_unlock(&iaxsl[callno]);
5448 return 0;
5449 }
5450 }
5451 /* Explicitly predestroy it */
5452 iax2_predestroy(callno);
5453 /* If we were already gone to begin with, destroy us now */
5454 if (iaxs[callno] && alreadygone) {
5455 ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
5456 iax2_destroy(callno);
5457 } else if (iaxs[callno]) {
5458 if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5459 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5460 iax2_destroy(callno);
5461 }
5462 }
5463 } else if (ast_channel_tech_pvt(c)) {
5464 /* If this call no longer exists, but the channel still
5465 * references it we need to set the channel's tech_pvt to null
5466 * to avoid ast_channel_free() trying to free it.
5467 */
5469 }
5470 ast_mutex_unlock(&iaxsl[callno]);
5471 ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
5472 return 0;
5473}
5474
5475/*!
5476 * \note expects the pvt to be locked
5477 */
5478static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5479{
5480 unsigned short callno = pvt->callno;
5481
5482 if (!pvt->peercallno) {
5483 /* We don't know the remote side's call number, yet. :( */
5484 int count = 10;
5485 while (count-- && pvt && !pvt->peercallno) {
5486 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5487 pvt = iaxs[callno];
5488 }
5489 if (!pvt || !pvt->peercallno) {
5490 return -1;
5491 }
5492 }
5493
5494 return 0;
5495}
5496
5497static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5498{
5499 struct ast_option_header *h;
5500 int res;
5501
5502 switch (option) {
5503 case AST_OPTION_TXGAIN:
5504 case AST_OPTION_RXGAIN:
5505 /* these two cannot be sent, because they require a result */
5506 errno = ENOSYS;
5507 return -1;
5508 case AST_OPTION_OPRMODE:
5509 errno = EINVAL;
5510 return -1;
5513 {
5514 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5515 ast_mutex_lock(&iaxsl[callno]);
5516 if ((*(int *) data)) {
5518 } else {
5520 }
5521 ast_mutex_unlock(&iaxsl[callno]);
5522 return 0;
5523 }
5524 /* These options are sent to the other side across the network where
5525 * they will be passed to whatever channel is bridged there. Don't
5526 * do anything silly like pass an option that transmits pointers to
5527 * memory on this machine to a remote machine to use */
5529 case AST_OPTION_TDD:
5534 {
5535 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5536 struct chan_iax2_pvt *pvt;
5537
5539 pvt = iaxs[callno];
5540
5541 if (wait_for_peercallno(pvt)) {
5543 return -1;
5544 }
5545
5547
5548 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5549 return -1;
5550 }
5551
5553 h->option = htons(option);
5554 memcpy(h->data, data, datalen);
5556 AST_CONTROL_OPTION, 0, (unsigned char *) h,
5557 datalen + sizeof(*h), -1);
5558 ast_free(h);
5559 return res;
5560 }
5561 default:
5562 return -1;
5563 }
5564
5565 /* Just in case someone does a break instead of a return */
5566 return -1;
5567}
5568
5569static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5570{
5571 switch (option) {
5574 {
5575 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5577 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5579 return 0;
5580 }
5581 default:
5582 return -1;
5583 }
5584}
5585
5586static struct ast_frame *iax2_read(struct ast_channel *c)
5587{
5588 ast_debug(1, "I should never be called!\n");
5589 return &ast_null_frame;
5590}
5591
5592static int iax2_key_rotate(const void *vpvt)
5593{
5594 int res = 0;
5595 struct chan_iax2_pvt *pvt = (void *) vpvt;
5596 struct MD5Context md5;
5597 char key[17] = "";
5598 struct iax_ie_data ied = {
5599 .pos = 0,
5600 };
5601
5602 ast_mutex_lock(&iaxsl[pvt->callno]);
5603 pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5604
5605 snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5606
5607 MD5Init(&md5);
5608 MD5Update(&md5, (unsigned char *) key, strlen(key));
5609 MD5Final((unsigned char *) key, &md5);
5610
5611 IAX_DEBUGDIGEST("Sending", key);
5612
5613 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5614
5615 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5616
5617 build_ecx_key((unsigned char *) key, pvt);
5618
5620
5621 return res;
5622}
5623
5624#if defined(IAX2_NATIVE_BRIDGING)
5625static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5626{
5627 int res;
5628 struct iax_ie_data ied0;
5629 struct iax_ie_data ied1;
5630 unsigned int transferid = (unsigned int)ast_random();
5631
5632 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5633 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5636 return 0;
5637 }
5638
5639 memset(&ied0, 0, sizeof(ied0));
5640 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5641 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5642 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5643
5644 memset(&ied1, 0, sizeof(ied1));
5645 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5646 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5647 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5648
5649 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5650 if (res)
5651 return -1;
5652 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5653 if (res)
5654 return -1;
5655 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5656 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5657 return 0;
5658}
5659#endif /* defined(IAX2_NATIVE_BRIDGING) */
5660
5661#if defined(IAX2_NATIVE_BRIDGING)
5662static void lock_both(unsigned short callno0, unsigned short callno1)
5663{
5664 ast_mutex_lock(&iaxsl[callno0]);
5665 while (ast_mutex_trylock(&iaxsl[callno1])) {
5666 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5667 }
5668}
5669#endif /* defined(IAX2_NATIVE_BRIDGING) */
5670
5671#if defined(IAX2_NATIVE_BRIDGING)
5672static void unlock_both(unsigned short callno0, unsigned short callno1)
5673{
5674 ast_mutex_unlock(&iaxsl[callno1]);
5675 ast_mutex_unlock(&iaxsl[callno0]);
5676}
5677#endif /* defined(IAX2_NATIVE_BRIDGING) */
5678
5679#if defined(IAX2_NATIVE_BRIDGING)
5680static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
5681{
5682 struct ast_channel *cs[3];
5683 struct ast_channel *who, *other;
5684 int to = -1;
5685 int res = -1;
5686 int transferstarted=0;
5687 struct ast_frame *f;
5688 unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
5689 unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
5690 struct timeval waittimer = {0, 0};
5691
5692 /* We currently do not support native bridging if a timeoutms value has been provided */
5693 if (timeoutms > 0) {
5694 return AST_BRIDGE_FAILED;
5695 }
5696
5697 timeoutms = -1;
5698
5699 lock_both(callno0, callno1);
5700 if (!iaxs[callno0] || !iaxs[callno1]) {
5701 unlock_both(callno0, callno1);
5702 return AST_BRIDGE_FAILED;
5703 }
5704 /* Put them in native bridge mode */
5706 iaxs[callno0]->bridgecallno = callno1;
5707 iaxs[callno1]->bridgecallno = callno0;
5708 }
5709 unlock_both(callno0, callno1);
5710
5711 /* If not, try to bridge until we can execute a transfer, if we can */
5712 cs[0] = c0;
5713 cs[1] = c1;
5714 for (/* ever */;;) {
5715 /* Check in case we got masqueraded into */
5716 if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
5717 ast_verb(3, "Can't masquerade, we're different...\n");
5718 /* Remove from native mode */
5719 if (ast_channel_tech(c0) == &iax2_tech) {
5720 ast_mutex_lock(&iaxsl[callno0]);
5721 iaxs[callno0]->bridgecallno = 0;
5722 ast_mutex_unlock(&iaxsl[callno0]);
5723 }
5724 if (ast_channel_tech(c1) == &iax2_tech) {
5725 ast_mutex_lock(&iaxsl[callno1]);
5726 iaxs[callno1]->bridgecallno = 0;
5727 ast_mutex_unlock(&iaxsl[callno1]);
5728 }
5730 }
5734
5735 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n",
5738
5739 /* Remove from native mode */
5740 lock_both(callno0, callno1);
5741 if (iaxs[callno0])
5742 iaxs[callno0]->bridgecallno = 0;
5743 if (iaxs[callno1])
5744 iaxs[callno1]->bridgecallno = 0;
5745 unlock_both(callno0, callno1);
5747 }
5748 /* check if transferred and if we really want native bridging */
5749 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5750 /* Try the transfer */
5751 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5753 ast_log(LOG_WARNING, "Unable to start the transfer\n");
5754 transferstarted = 1;
5755 }
5756 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5757 /* Call has been transferred. We're no longer involved */
5758 struct timeval now = ast_tvnow();
5759 if (ast_tvzero(waittimer)) {
5760 waittimer = now;
5761 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5764 *fo = NULL;
5765 *rc = c0;
5766 res = AST_BRIDGE_COMPLETE;
5767 break;
5768 }
5769 }
5770 to = 1000;
5771 who = ast_waitfor_n(cs, 2, &to);
5772 /* XXX This will need to be updated to calculate
5773 * timeout correctly once timeoutms is allowed to be
5774 * > 0. Right now, this can go badly if the waitfor
5775 * times out in less than a millisecond
5776 */
5777 if (timeoutms > -1) {
5778 timeoutms -= (1000 - to);
5779 if (timeoutms < 0)
5780 timeoutms = 0;
5781 }
5782 if (!who) {
5783 if (!timeoutms) {
5784 res = AST_BRIDGE_RETRY;
5785 break;
5786 }
5787 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5788 res = AST_BRIDGE_FAILED;
5789 break;
5790 }
5791 continue;
5792 }
5793 f = ast_read(who);
5794 if (!f) {
5795 *fo = NULL;
5796 *rc = who;
5797 res = AST_BRIDGE_COMPLETE;
5798 break;
5799 }
5800 other = (who == c0) ? c1 : c0; /* the 'other' channel */
5801 if (f->frametype == AST_FRAME_CONTROL) {
5802 switch (f->subclass.integer) {
5807 ast_write(other, f);
5808 break;
5811 break;
5812 default:
5813 *fo = f;
5814 *rc = who;
5815 res = AST_BRIDGE_COMPLETE;
5816 break;
5817 }
5818 if (res == AST_BRIDGE_COMPLETE) {
5819 break;
5820 }
5821 } else if (f->frametype == AST_FRAME_VOICE
5822 || f->frametype == AST_FRAME_TEXT
5823 || f->frametype == AST_FRAME_VIDEO
5824 || f->frametype == AST_FRAME_IMAGE) {
5825 ast_write(other, f);
5826 } else if (f->frametype == AST_FRAME_DTMF) {
5827 /* monitored dtmf take out of the bridge.
5828 * check if we monitor the specific source.
5829 */
5830 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5831
5832 if (flags & monitored_source) {
5833 *rc = who;
5834 *fo = f;
5835 res = AST_BRIDGE_COMPLETE;
5836 /* Remove from native mode */
5837 break;
5838 }
5839 ast_write(other, f);
5840 }
5841 ast_frfree(f);
5842 /* Swap who gets priority */
5843 cs[2] = cs[0];
5844 cs[0] = cs[1];
5845 cs[1] = cs[2];
5846 }
5847 lock_both(callno0, callno1);
5848 if(iaxs[callno0])
5849 iaxs[callno0]->bridgecallno = 0;
5850 if(iaxs[callno1])
5851 iaxs[callno1]->bridgecallno = 0;
5852 unlock_both(callno0, callno1);
5853 return res;
5854}
5855#endif /* defined(IAX2_NATIVE_BRIDGING) */
5856
5857static int iax2_answer(struct ast_channel *c)
5858{
5859 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5860 ast_debug(1, "Answering IAX2 call\n");
5862}
5863
5864static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5865{
5866 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5867 struct chan_iax2_pvt *pvt;
5868 int res = 0;
5869
5870 if (iaxdebug)
5871 ast_debug(1, "Indicating condition %d\n", condition);
5872
5874 pvt = iaxs[callno];
5875
5876 if (wait_for_peercallno(pvt)) {
5877 res = -1;
5878 goto done;
5879 }
5880
5881 switch (condition) {
5882 case AST_CONTROL_HOLD:
5883 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5884 ast_moh_start(c, data, pvt->mohinterpret);
5885 goto done;
5886 }
5887 break;
5888 case AST_CONTROL_UNHOLD:
5889 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5890 ast_moh_stop(c);
5891 goto done;
5892 }
5893 break;
5897 /* We are not configured to allow sending these updates. */
5898 ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5899 callno, condition);
5900 goto done;
5901 }
5902 break;
5905 res = -1;
5906 goto done;
5907 }
5908
5909 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5910
5911done:
5913
5914 return res;
5915}
5916
5917static int iax2_transfer(struct ast_channel *c, const char *dest)
5918{
5919 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5920 struct iax_ie_data ied = { "", };
5921 char tmp[256], *context;
5923 ast_copy_string(tmp, dest, sizeof(tmp));
5924 context = strchr(tmp, '@');
5925 if (context) {
5926 *context = '\0';
5927 context++;
5928 }
5930 if (context)
5932 ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
5934 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5935}
5936
5937static int iax2_getpeertrunk(struct ast_sockaddr addr)
5938{
5939 struct iax2_peer *peer;
5940 int res = 0;
5941 struct ao2_iterator i;
5942
5943 i = ao2_iterator_init(peers, 0);
5944 while ((peer = ao2_iterator_next(&i))) {
5945
5946 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
5947 res = ast_test_flag64(peer, IAX_TRUNK);
5948 peer_unref(peer);
5949 break;
5950 }
5951 peer_unref(peer);
5952 }
5954
5955 return res;
5956}
5957
5958/*! \brief Create new call, interface with the PBX core */
5959static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability,
5960 struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids,
5961 const struct ast_channel *requestor, unsigned int cachable)
5962{
5963 struct ast_channel *tmp = NULL;
5964 struct chan_iax2_pvt *i;
5965 struct iax2_peer *peer;
5966 struct ast_variable *v = NULL;
5967 struct ast_format_cap *native;
5968 struct ast_format *tmpfmt;
5969 ast_callid callid;
5970 char *peer_name = NULL;
5971
5972 if (!(i = iaxs[callno])) {
5973 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5974 return NULL;
5975 }
5976
5977 if (!capability) {
5978 ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5979 i->host, i->callno);
5980 return NULL;
5981 }
5983 if (!native) {
5984 return NULL;
5985 }
5986 if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5987 || !ast_format_cap_count(native)) {
5988 ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5989 i->host, i->callno);
5990 ao2_ref(native, -1);
5991 return NULL;
5992 }
5993
5994 if (!ast_strlen_zero(i->peer)) {
5995 peer_name = ast_strdupa(i->peer);
5996 } else if (!ast_strlen_zero(i->host)) {
5997 peer_name = ast_strdupa(i->host);
5998 }
5999
6000 /* Don't hold call lock while making a channel or looking up a peer */
6001 ast_mutex_unlock(&iaxsl[callno]);
6002
6003 if (!ast_strlen_zero(peer_name)) {
6004 peer = find_peer(peer_name, 1);
6005 if (peer && peer->endpoint) {
6007 i->accountcode, i->exten, i->context, assignedids, requestor,
6008 i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
6009 }
6010 ao2_cleanup(peer);
6011 }
6012
6013 if (!tmp) {
6014 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
6015 i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
6016 i->host, i->callno);
6017 }
6018
6019 ast_mutex_lock(&iaxsl[callno]);
6020 if (i != iaxs[callno]) {
6021 if (tmp) {
6022 /* unlock and relock iaxsl[callno] to preserve locking order */
6023 ast_mutex_unlock(&iaxsl[callno]);
6024 ast_channel_unlock(tmp);
6025 tmp = ast_channel_release(tmp);
6026 ast_mutex_lock(&iaxsl[callno]);
6027 }
6028 ao2_ref(native, -1);
6029 return NULL;
6030 }
6031 if (!tmp) {
6032 ao2_ref(native, -1);
6033 return NULL;
6034 }
6035
6037
6038 if ((callid = iaxs[callno]->callid)) {
6039 ast_channel_callid_set(tmp, callid);
6040 }
6041
6043
6044 /* We can support any format by default, until we get restricted */
6045 ast_channel_nativeformats_set(tmp, native);
6046 tmpfmt = ast_format_cap_get_format(native, 0);
6047
6048 ast_channel_set_readformat(tmp, tmpfmt);
6049 ast_channel_set_rawreadformat(tmp, tmpfmt);
6050 ast_channel_set_writeformat(tmp, tmpfmt);
6051 ast_channel_set_rawwriteformat(tmp, tmpfmt);
6052
6053 ao2_ref(tmpfmt, -1);
6054 ao2_ref(native, -1);
6055
6057
6058 if (!ast_strlen_zero(i->parkinglot))
6059 ast_channel_parkinglot_set(tmp, i->parkinglot);
6060 /* Don't use ast_set_callerid() here because it will
6061 * generate a NewCallerID event before the NewChannel event */
6062 if (!ast_strlen_zero(i->ani)) {
6065 } else if (!ast_strlen_zero(i->cid_num)) {
6068 }
6070 if (!ast_strlen_zero(i->rdnis)) {
6073 }
6079 if (!ast_strlen_zero(i->language))
6080 ast_channel_language_set(tmp, i->language);
6082 ast_channel_accountcode_set(tmp, i->accountcode);
6083 if (i->amaflags)
6087 if (i->adsi)
6089 else
6091 i->owner = tmp;
6092 i->capability = capability;
6093
6094 if (!cachable) {
6096 }
6097
6098 /* Set inherited variables */
6099 if (i->vars) {
6100 for (v = i->vars ; v ; v = v->next)
6102 }
6103 if (i->iaxvars) {
6104 struct ast_datastore *variablestore;
6105 struct ast_variable *var, *prev = NULL;
6106 AST_LIST_HEAD(, ast_var_t) *varlist;
6107 ast_debug(1, "Loading up the channel with IAXVARs\n");
6108 varlist = ast_calloc(1, sizeof(*varlist));
6110 if (variablestore && varlist) {
6111 variablestore->data = varlist;
6112 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6113 AST_LIST_HEAD_INIT(varlist);
6114 for (var = i->iaxvars; var; var = var->next) {
6115 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6116 if (prev)
6117 ast_free(prev);
6118 prev = var;
6119 if (!newvar) {
6120 /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
6121 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6122 } else {
6123 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6124 }
6125 }
6126 if (prev)
6127 ast_free(prev);
6128 i->iaxvars = NULL;
6129 ast_channel_datastore_add(i->owner, variablestore);
6130 } else {
6131 if (variablestore) {
6132 ast_datastore_free(variablestore);
6133 }
6134 if (varlist) {
6135 ast_free(varlist);
6136 }
6137 }
6138 }
6139
6141 ast_channel_unlock(tmp);
6142
6143 if (state != AST_STATE_DOWN) {
6144 if (ast_pbx_start(tmp)) {
6145 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6146 /* unlock and relock iaxsl[callno] to preserve locking order */
6147 ast_mutex_unlock(&iaxsl[callno]);
6148 ast_hangup(tmp);
6149 ast_mutex_lock(&iaxsl[callno]);
6150 return NULL;
6151 }
6152 }
6153
6155 return tmp;
6156}
6157
6158static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
6159{
6160 unsigned long int mssincetx; /* unsigned to handle overflows */
6161 long int ms, pred;
6162
6163 tpeer->trunkact = *now;
6164 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
6165 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
6166 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
6167 tpeer->txtrunktime = *now;
6168 tpeer->lastsent = 999999;
6169 }
6170 /* Update last transmit time now */
6171 tpeer->lasttxtime = *now;
6172
6173 /* Calculate ms offset */
6174 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
6175 /* Predict from last value */
6176 pred = tpeer->lastsent + sampms;
6177 if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
6178 ms = pred;
6179
6180 /* We never send the same timestamp twice, so fudge a little if we must */
6181 if (ms == tpeer->lastsent)
6182 ms = tpeer->lastsent + 1;
6183 tpeer->lastsent = ms;
6184 return ms;
6185}
6186
6187static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
6188{
6189 long ms; /* NOT unsigned */
6190 if (ast_tvzero(iaxs[callno]->rxcore)) {
6191 /* Initialize rxcore time if appropriate */
6192 iaxs[callno]->rxcore = ast_tvnow();
6193 /* Round to nearest 20ms so traces look pretty */
6194 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6195 }
6196 /* Calculate difference between trunk and channel */
6197 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6198 /* Return as the sum of trunk time and the difference between trunk and real time */
6199 return ms + ts;
6200}
6201
6202static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6203{
6204 int ms;
6205 int voice = 0;
6206 int genuine = 0;
6207 int adjust;
6208 int rate = 0;
6209 struct timeval *delivery = NULL;
6210
6211
6212 /* What sort of frame do we have?: voice is self-explanatory
6213 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6214 non-genuine frames are CONTROL frames [ringing etc], DTMF
6215 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6216 the others need a timestamp slaved to the voice frames so that they go in sequence
6217 */
6218 if (f->frametype == AST_FRAME_VOICE) {
6219 voice = 1;
6220 rate = ast_format_get_sample_rate(f->subclass.format) / 1000;
6221 delivery = &f->delivery;
6222 } else if (f->frametype == AST_FRAME_IAX) {
6223 genuine = 1;
6224 } else if (f->frametype == AST_FRAME_CNG) {
6225 p->notsilenttx = 0;
6226 }
6227
6228 if (ast_tvzero(p->offset)) {
6229 p->offset = ast_tvnow();
6230 /* Round to nearest 20ms for nice looking traces */
6231 p->offset.tv_usec -= p->offset.tv_usec % 20000;
6232 }
6233 /* If the timestamp is specified, just send it as is */
6234 if (ts)
6235 return ts;
6236 /* If we have a time that the frame arrived, always use it to make our timestamp */
6237 if (delivery && !ast_tvzero(*delivery)) {
6238 ms = ast_tvdiff_ms(*delivery, p->offset);
6239 if (ms < 0) {
6240 ms = 0;
6241 }
6242 if (iaxdebug)
6243 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6244 } else {
6245 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6246 if (ms < 0)
6247 ms = 0;
6248 if (voice) {
6249 /* On a voice frame, use predicted values if appropriate */
6250 adjust = (ms - p->nextpred);
6251 if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6252 /* Adjust our txcore, keeping voice and non-voice synchronized */
6253 /* AN EXPLANATION:
6254 When we send voice, we usually send "calculated" timestamps worked out
6255 on the basis of the number of samples sent. When we send other frames,
6256 we usually send timestamps worked out from the real clock.
6257 The problem is that they can tend to drift out of step because the
6258 source channel's clock and our clock may not be exactly at the same rate.
6259 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6260 for this call. Moving it adjusts timestamps for non-voice frames.
6261 We make the adjustment in the style of a moving average. Each time we
6262 adjust p->offset by 10% of the difference between our clock-derived
6263 timestamp and the predicted timestamp. That's why you see "10000"
6264 below even though IAX2 timestamps are in milliseconds.
6265 The use of a moving average avoids offset moving too radically.
6266 Generally, "adjust" roams back and forth around 0, with offset hardly
6267 changing at all. But if a consistent different starts to develop it
6268 will be eliminated over the course of 10 frames (200-300msecs)
6269 */
6270 if (adjust < 0)
6271 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6272 else if (adjust > 0)
6273 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6274
6275 if (!p->nextpred) {
6276 p->nextpred = ms; /*f->samples / rate;*/
6277 if (p->nextpred <= p->lastsent)
6278 p->nextpred = p->lastsent + 3;
6279 }
6280 ms = p->nextpred;
6281 } else {
6282 /* in this case, just use the actual
6283 * time, since we're either way off
6284 * (shouldn't happen), or we're ending a
6285 * silent period -- and seed the next
6286 * predicted time. Also, round ms to the
6287 * next multiple of frame size (so our
6288 * silent periods are multiples of
6289 * frame size too) */
6290
6291 if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
6292 ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6293 abs(adjust), MAX_TIMESTAMP_SKEW);
6294
6295 if (f->samples >= rate) /* check to make sure we don't core dump */
6296 {
6297 int diff = ms % (f->samples / rate);
6298 if (diff)
6299 ms += f->samples/rate - diff;
6300 }
6301
6302 p->nextpred = ms;
6303 p->notsilenttx = 1;
6304 }
6305 } else if ( f->frametype == AST_FRAME_VIDEO ) {
6306 /*
6307 * IAX2 draft 03 says that timestamps MUST be in order.
6308 * It does not say anything about several frames having the same timestamp
6309 * When transporting video, we can have a frame that spans multiple iax packets
6310 * (so called slices), so it would make sense to use the same timestamp for all of
6311 * them
6312 * We do want to make sure that frames don't go backwards though
6313 */
6314 if ( (unsigned int)ms < p->lastsent )
6315 ms = p->lastsent;
6316 } else {
6317 /* On a dataframe, use last value + 3 (to accommodate jitter buffer shrinking) if appropriate unless
6318 it's a genuine frame */
6319 adjust = (ms - p->lastsent);
6320 if (genuine) {
6321 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6322 if (ms <= p->lastsent)
6323 ms = p->lastsent + 3;
6324 } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6325 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6326 ms = p->lastsent + 3;
6327 }
6328 }
6329 }
6330 p->lastsent = ms;
6331 if (voice) {
6332 p->nextpred = p->nextpred + f->samples / rate;
6333 }
6334 return ms;
6335}
6336
6337static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6338{
6339 /* Returns where in "receive time" we are. That is, how many ms
6340 since we received (or would have received) the frame with timestamp 0 */
6341 int ms;
6342#ifdef IAXTESTS
6343 int jit;
6344#endif /* IAXTESTS */
6345 /* Setup rxcore if necessary */
6346 if (ast_tvzero(p->rxcore)) {
6347 p->rxcore = ast_tvnow();
6348 if (iaxdebug)
6349 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6350 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6351 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6352#if 1
6353 if (iaxdebug)
6354 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6355 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6356#endif
6357 }
6358
6359 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6360#ifdef IAXTESTS
6361 if (test_jit) {
6362 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6363 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6364 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6365 jit = -jit;
6366 ms += jit;
6367 }
6368 }
6369 if (test_late) {
6370 ms += test_late;
6371 test_late = 0;
6372 }
6373#endif /* IAXTESTS */
6374 return ms;
6375}
6376
6377static struct iax2_trunk_peer *find_tpeer(struct ast_sockaddr *addr, int fd)
6378{
6379 struct iax2_trunk_peer *tpeer = NULL;
6380
6381 /* Finds and locks trunk peer */
6383
6384 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6385 if (!ast_sockaddr_cmp(&tpeer->addr, addr)) {
6386 ast_mutex_lock(&tpeer->lock);
6387 break;
6388 }
6389 }
6390
6391 if (!tpeer) {
6392 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6393 ast_mutex_init(&tpeer->lock);
6394 tpeer->lastsent = 9999;
6395 ast_sockaddr_copy(&tpeer->addr, addr);
6396 tpeer->trunkact = ast_tvnow();
6397 ast_mutex_lock(&tpeer->lock);
6398 tpeer->sockfd = fd;
6399
6400#ifdef SO_NO_CHECK
6401 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6402#endif
6403 ast_debug(1, "Created trunk peer for '%s'\n", ast_sockaddr_stringify(&tpeer->addr));
6405 }
6406 }
6407
6409
6410 return tpeer;
6411}
6412
6413static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6414{
6415 struct ast_frame *f;
6416 struct iax2_trunk_peer *tpeer;
6417 void *tmp, *ptr;
6418 struct timeval now;
6419 struct ast_iax2_meta_trunk_entry *met;
6420 struct ast_iax2_meta_trunk_mini *mtm;
6421
6422 f = &fr->af;
6423 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6424 if (tpeer) {
6425
6426 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6427 /* Need to reallocate space */
6428 if (tpeer->trunkdataalloc < trunkmaxsize) {
6429 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6430 ast_mutex_unlock(&tpeer->lock);
6431 return -1;
6432 }
6433
6435 tpeer->trunkdata = tmp;
6436 ast_debug(1, "Expanded trunk '%s' to %u bytes\n", ast_sockaddr_stringify(&tpeer->addr), tpeer->trunkdataalloc);
6437 } else {
6438 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s\n", ast_sockaddr_stringify(&tpeer->addr));
6439 ast_mutex_unlock(&tpeer->lock);
6440 return -1;
6441 }
6442 }
6443
6444 /* Append to meta frame */
6445 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6447 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6448 mtm->len = htons(f->datalen);
6449 mtm->mini.callno = htons(pvt->callno);
6450 mtm->mini.ts = htons(0xffff & fr->ts);
6451 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6452 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6453 } else {
6454 met = (struct ast_iax2_meta_trunk_entry *)ptr;
6455 /* Store call number and length in meta header */
6456 met->callno = htons(pvt->callno);
6457 met->len = htons(f->datalen);
6458 /* Advance pointers/decrease length past trunk entry header */
6459 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6460 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6461 }
6462 /* Copy actual trunk data */
6463 memcpy(ptr, f->data.ptr, f->datalen);
6464 tpeer->trunkdatalen += f->datalen;
6465
6466 tpeer->calls++;
6467
6468 /* track the largest mtu we actually have sent */
6469 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6470 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6471
6472 /* if we have enough for a full MTU, ship it now without waiting */
6473 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6474 now = ast_tvnow();
6475 send_trunk(tpeer, &now);
6476 trunk_untimed ++;
6477 }
6478
6479 ast_mutex_unlock(&tpeer->lock);
6480 }
6481 return 0;
6482}
6483
6484/* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6485 * before the encryption data. This function randomizes that data. */
6486static void build_rand_pad(unsigned char *buf, ssize_t len)
6487{
6488 long tmp;
6489 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6490 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6491 buf += sizeof(tmp);
6492 len -= sizeof(tmp);
6493 }
6494}
6495
6497{
6498#ifdef HAVE_OPENSSL
6499 int i;
6500 for (i = 0; i < 60; i++) {
6501 if (ecx->raw[i]) {
6502 return 0; /* stop if we encounter anything non-zero */
6503 }
6504 }
6505 /* if ast_aes_encrypt or ast_aes_decrypt is called, then we'll crash when calling AES_encrypt or AES_decrypt */
6506 return -1;
6507#else
6508 return 0; /* Can't verify, but doesn't matter anyways */
6509#endif
6510}
6511
6512static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6513{
6514 build_ecx_key(digest, pvt);
6515 ast_aes_set_decrypt_key(digest, &pvt->dcx);
6516}
6517
6518static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6519{
6520 /* it is required to hold the corresponding decrypt key to our encrypt key
6521 * in the pvt struct because queued frames occasionally need to be decrypted and
6522 * re-encrypted when updated for a retransmission */
6523 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6524 ast_aes_set_encrypt_key(digest, &pvt->ecx);
6525 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6526}
6527
6528static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6529{
6530#if 0
6531 /* Debug with "fake encryption" */
6532 int x;
6533 if (len % 16)
6534 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6535 for (x=0;x<len;x++)
6536 dst[x] = src[x] ^ 0xff;
6537#else
6538 unsigned char lastblock[16] = { 0 };
6539 int x;
6540 while(len > 0) {
6541 ast_aes_decrypt(src, dst, dcx);
6542 for (x=0;x<16;x++)
6543 dst[x] ^= lastblock[x];
6544 memcpy(lastblock, src, sizeof(lastblock));
6545 dst += 16;
6546 src += 16;
6547 len -= 16;
6548 }
6549#endif
6550}
6551
6552static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6553{
6554#if 0
6555 /* Debug with "fake encryption" */
6556 int x;
6557 if (len % 16)
6558 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6559 for (x=0;x<len;x++)
6560 dst[x] = src[x] ^ 0xff;
6561#else
6562 unsigned char curblock[16] = { 0 };
6563 int x;
6564 while(len > 0) {
6565 for (x=0;x<16;x++)
6566 curblock[x] ^= src[x];
6567 ast_aes_encrypt(curblock, dst, ecx);
6568 memcpy(curblock, dst, sizeof(curblock));
6569 dst += 16;
6570 src += 16;
6571 len -= 16;
6572 }
6573#endif
6574}
6575
6576static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6577{
6578 int padding;
6579 unsigned char *workspace;
6580
6581 workspace = ast_alloca(*datalen);
6582 memset(f, 0, sizeof(*f));
6583 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6584 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6585 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6586 return -1;
6587 /* Decrypt */
6588 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6589
6590 padding = 16 + (workspace[15] & 0x0f);
6591 if (iaxdebug)
6592 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
6593 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6594 return -1;
6595
6596 *datalen -= padding;
6597 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6598 f->frametype = fh->type;
6599 if (f->frametype == AST_FRAME_VIDEO) {
6601 if (!f->subclass.format) {
6603 }
6604 } else if (f->frametype == AST_FRAME_VOICE) {
6606 if (!f->subclass.format) {
6608 }
6609 } else {
6611 }
6612 } else {
6613 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6614 if (iaxdebug)
6615 ast_debug(5, "Decoding mini with length %d\n", *datalen);
6616 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6617 return -1;
6618 /* Decrypt */
6619 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6620 padding = 16 + (workspace[15] & 0x0f);
6621 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6622 return -1;
6623 *datalen -= padding;
6624 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6625 }
6626 return 0;
6627}
6628
6629static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6630{
6631 int padding;
6632 unsigned char *workspace;
6633 workspace = ast_alloca(*datalen + 32);
6634 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6635 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6636 if (iaxdebug)
6637 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6638 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6639 padding = 16 + (padding & 0xf);
6640 memcpy(workspace, poo, padding);
6641 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6642 workspace[15] &= 0xf0;
6643 workspace[15] |= (padding & 0xf);
6644 if (iaxdebug)
6645 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
6646 *datalen += padding;
6647 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6648 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6649 memcpy(poo, workspace + *datalen - 32, 32);
6650 } else {
6651 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6652 if (iaxdebug)
6653 ast_debug(5, "Encoding mini frame with length %d\n", *datalen);
6654 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6655 padding = 16 + (padding & 0xf);
6656 memcpy(workspace, poo, padding);
6657 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6658 workspace[15] &= 0xf0;
6659 workspace[15] |= (padding & 0x0f);
6660 *datalen += padding;
6661 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6662 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6663 memcpy(poo, workspace + *datalen - 32, 32);
6664 }
6665 return 0;
6666}
6667
6668static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6669{
6670 int res=-1;
6672 /* Search for possible keys, given secrets */
6673 struct MD5Context md5;
6674 unsigned char digest[16];
6675 char *tmppw, *stringp;
6676
6677 tmppw = ast_strdupa(iaxs[callno]->secret);
6678 stringp = tmppw;
6679 while ((tmppw = strsep(&stringp, ";"))) {
6680 MD5Init(&md5);
6681 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6682 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6683 MD5Final(digest, &md5);
6684 build_encryption_keys(digest, iaxs[callno]);
6685 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6686 if (!res) {
6688 break;
6689 }
6690 }
6691 } else
6692 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6693 return res;
6694}
6695
6696static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6697{
6698 /* Queue a packet for delivery on a given private structure. Use "ts" for
6699 timestamp, or calculate if ts is 0. Send immediately without retransmission
6700 or delayed, with retransmission */
6701 struct ast_iax2_full_hdr *fh;
6702 struct ast_iax2_mini_hdr *mh;
6703 struct ast_iax2_video_hdr *vh;
6704 struct {
6705 struct iax_frame fr2;
6706 unsigned char buffer[4096];
6707 } frb;
6708 struct iax_frame *fr;
6709 int res;
6710 int sendmini=0;
6711 unsigned int lastsent;
6712 unsigned int fts;
6713
6714 frb.fr2.afdatalen = sizeof(frb.buffer);
6715
6716 if (!pvt) {
6717 ast_log(LOG_WARNING, "No private structure for packet?\n");
6718 return -1;
6719 }
6720
6721 lastsent = pvt->lastsent;
6722
6723 /* Calculate actual timestamp */
6724 fts = calc_timestamp(pvt, ts, f);
6725
6726 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6727 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6728 * increment the "predicted timestamps" for voice, if we're predicting */
6729 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6730 return 0;
6731#if 0
6733 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6734 *("=!" + (f->frametype == AST_FRAME_VOICE)),
6735 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6736 pvt->keyrotateid != -1 ? "" : "no "
6737 );
6738#endif
6739 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6740 iax2_key_rotate(pvt);
6741 }
6742
6743 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6744 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6745 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6746 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6748 /* is a voice frame */ &&
6751 /* is the same type */ ) {
6752 /* Force immediate rather than delayed transmission */
6753 now = 1;
6754 /* Mark that mini-style frame is appropriate */
6755 sendmini = 1;
6756 }
6757 if ( f->frametype == AST_FRAME_VIDEO ) {
6758 /*
6759 * If the lower 15 bits of the timestamp roll over, or if
6760 * the video format changed then send a full frame.
6761 * Otherwise send a mini video frame
6762 */
6763 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6766 ) {
6767 now = 1;
6768 sendmini = 1;
6769 } else {
6770 now = 0;
6771 sendmini = 0;
6772 }
6773 pvt->lastvsent = fts;
6774 }
6775 if (f->frametype == AST_FRAME_IAX) {
6776 /* 0x8000 marks this message as TX:, this bit will be stripped later */
6778 if (!pvt->first_iax_message) {
6780 }
6781 }
6782 /* Allocate an iax_frame */
6783 if (now) {
6784 fr = &frb.fr2;
6785 } else
6787 if (!fr) {
6788 ast_log(LOG_WARNING, "Out of memory\n");
6789 return -1;
6790 }
6791 /* Copy our prospective frame into our immediate or retransmitted wrapper */
6792 iax_frame_wrap(fr, f);
6793
6794 fr->ts = fts;
6795 fr->callno = pvt->callno;
6796 fr->transfer = transfer;
6797 fr->final = final;
6798 fr->encmethods = 0;
6799 if (!sendmini) {
6800 /* We need a full frame */
6801 if (seqno > -1)
6802 fr->oseqno = seqno;
6803 else
6804 fr->oseqno = pvt->oseqno++;
6805 fr->iseqno = pvt->iseqno;
6806 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6807 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6808 fh->ts = htonl(fr->ts);
6809 fh->oseqno = fr->oseqno;
6810 if (transfer) {
6811 fh->iseqno = 0;
6812 } else
6813 fh->iseqno = fr->iseqno;
6814 /* Keep track of the last thing we've acknowledged */
6815 if (!transfer)
6816 pvt->aseqno = fr->iseqno;
6817 fh->type = fr->af.frametype & 0xFF;
6818
6819 if (fr->af.frametype == AST_FRAME_VIDEO) {
6821 tmpfmt |= fr->af.subclass.frame_ending ? 0x1LL : 0;
6822 fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
6823 } else if (fr->af.frametype == AST_FRAME_VOICE) {
6825 } else {
6827 }
6828
6829 if (transfer) {
6830 fr->dcallno = pvt->transfercallno;
6831 } else
6832 fr->dcallno = pvt->peercallno;
6833 fh->dcallno = htons(fr->dcallno);
6834 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6835 fr->data = fh;
6836 fr->retries = 0;
6837 /* Retry after 2x the ping time has passed */
6838 fr->retrytime = pvt->pingtime * 2;
6839 if (fr->retrytime < MIN_RETRY_TIME)
6841 if (fr->retrytime > MAX_RETRY_TIME)
6843 /* Acks' don't get retried */
6845 fr->retries = -1;
6846 else if (f->frametype == AST_FRAME_VOICE)
6848 else if (f->frametype == AST_FRAME_VIDEO)
6850 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6852 if (fr->transfer)
6853 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6854 else
6855 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6856 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6857 fr->encmethods = pvt->encmethods;
6858 fr->ecx = pvt->ecx;
6859 fr->mydcx = pvt->mydcx;
6860 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6861 } else
6862 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6863 }
6864
6865 if (now) {
6866 res = send_packet(fr);
6867 } else
6868 res = iax2_transmit(fr);
6869 } else {
6870 if (ast_test_flag64(pvt, IAX_TRUNK)) {
6871 iax2_trunk_queue(pvt, fr);
6872 res = 0;
6873 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6874 /* Video frame have no sequence number */
6875 fr->oseqno = -1;
6876 fr->iseqno = -1;
6877 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6878 vh->zeros = 0;
6879 vh->callno = htons(0x8000 | fr->callno);
6880 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.frame_ending ? 0x8000 : 0));
6881 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6882 fr->data = vh;
6883 fr->retries = -1;
6884 res = send_packet(fr);
6885 } else {
6886 /* Mini-frames have no sequence number */
6887 fr->oseqno = -1;
6888 fr->iseqno = -1;
6889 /* Mini frame will do */
6890 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6891 mh->callno = htons(fr->callno);
6892 mh->ts = htons(fr->ts & 0xFFFF);
6893 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6894 fr->data = mh;
6895 fr->retries = -1;
6896 if (pvt->transferring == TRANSFER_MEDIAPASS)
6897 fr->transfer = 1;
6898 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6900 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6901 } else
6902 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6903 }
6904 res = send_packet(fr);
6905 }
6906 }
6907 return res;
6908}
6909
6910static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6911{
6912 regex_t regexbuf;
6913 int havepattern = 0;
6914
6915#define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6916#define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6917
6918 struct iax2_user *user = NULL;
6919 char auth[90];
6920 char *pstr = "";
6921 struct ao2_iterator i;
6922
6923 switch (cmd) {
6924 case CLI_INIT:
6925 e->command = "iax2 show users [like]";
6926 e->usage =
6927 "Usage: iax2 show users [like <pattern>]\n"
6928 " Lists all known IAX2 users.\n"
6929 " Optional regular expression pattern is used to filter the user list.\n";
6930 return NULL;
6931 case CLI_GENERATE:
6932 return NULL;
6933 }
6934
6935 switch (a->argc) {
6936 case 5:
6937 if (!strcasecmp(a->argv[3], "like")) {
6938 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6939 return CLI_SHOWUSAGE;
6940 havepattern = 1;
6941 } else
6942 return CLI_SHOWUSAGE;
6943 case 3:
6944 break;
6945 default:
6946 return CLI_SHOWUSAGE;
6947 }
6948
6949 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6950 i = ao2_iterator_init(users, 0);
6951 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6952 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6953 continue;
6954
6955 if (!ast_strlen_zero(user->secret)) {
6956 ast_copy_string(auth,user->secret, sizeof(auth));
6957 } else if (!ast_strlen_zero(user->inkeys)) {
6958 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6959 } else
6960 ast_copy_string(auth, "-no secret-", sizeof(auth));
6961
6963 pstr = "REQ Only";
6965 pstr = "Disabled";
6966 else
6967 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6968
6969 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6970 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6971 ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
6972 }
6974
6975 if (havepattern)
6976 regfree(&regexbuf);
6977
6978 return CLI_SUCCESS;
6979#undef FORMAT
6980#undef FORMAT2
6981}
6982
6994
6995#define PEERS_FORMAT2 "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
6996#define PEERS_FORMAT "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
6997
6998static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
6999{
7000 char name[256] = "";
7001 char status[64];
7002 int retstatus;
7003 struct ast_str *encmethods = ast_str_alloca(256);
7004
7005 char *tmp_host, *tmp_mask, *tmp_port;
7006
7007 tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
7008 tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
7009 tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
7010
7011 if (!ast_strlen_zero(peer->username)) {
7012 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
7013 } else {
7014 ast_copy_string(name, peer->name, sizeof(name));
7015 }
7016
7017 encmethods_to_str(peer->encmethods, &encmethods);
7018 retstatus = peer_status(peer, status, sizeof(status));
7019 if (retstatus > 0) {
7020 cont->online_peers++;
7021 } else if (!retstatus) {
7022 cont->offline_peers++;
7023 } else {
7024 cont->unmonitored_peers++;
7025 }
7026
7027 if (s) {
7028 if (cont->peerlist) { /* IAXpeerlist */
7029 astman_append(s,
7030 "Event: PeerEntry\r\n%s"
7031 "Channeltype: IAX\r\n",
7032 cont->idtext);
7033 if (!ast_strlen_zero(peer->username)) {
7034 astman_append(s,
7035 "ObjectName: %s\r\n"
7036 "ObjectUsername: %s\r\n",
7037 peer->name,
7038 peer->username);
7039 } else {
7040 astman_append(s,
7041 "ObjectName: %s\r\n",
7042 name);
7043 }
7044 } else { /* IAXpeers */
7045 astman_append(s,
7046 "Event: PeerEntry\r\n%s"
7047 "Channeltype: IAX2\r\n"
7048 "ObjectName: %s\r\n",
7049 cont->idtext,
7050 name);
7051 }
7052 astman_append(s,
7053 "ChanObjectType: peer\r\n"
7054 "IPaddress: %s\r\n",
7055 tmp_host);
7056 if (cont->peerlist) { /* IAXpeerlist */
7057 astman_append(s,
7058 "Mask: %s\r\n"
7059 "Port: %s\r\n",
7060 tmp_mask,
7061 tmp_port);
7062 } else { /* IAXpeers */
7063 astman_append(s,
7064 "IPport: %s\r\n",
7065 tmp_port);
7066 }
7067 astman_append(s,
7068 "Dynamic: %s\r\n"
7069 "Trunk: %s\r\n"
7070 "Encryption: %s\r\n"
7071 "Status: %s\r\n",
7072 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
7073 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
7074 peer->encmethods ? ast_str_buffer(encmethods) : "no",
7075 status);
7076 if (cont->peerlist) { /* IAXpeerlist */
7077 astman_append(s, "\r\n");
7078 } else { /* IAXpeers */
7079 astman_append(s,
7080 "Description: %s\r\n\r\n",
7081 peer->description);
7082 }
7083 } else {
7085 name,
7086 tmp_host,
7087 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
7088 tmp_mask,
7089 tmp_port,
7090 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
7091 peer->encmethods ? "(E)" : " ",
7092 status,
7093 peer->description);
7094 }
7095
7096 cont->total_peers++;
7097}
7098
7099static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
7100{
7101 struct show_peers_context cont = {
7102 .havepattern = 0,
7103 .idtext = "",
7104 .registeredonly = 0,
7105
7106 .peerlist = 0,
7107
7108 .total_peers = 0,
7109 .online_peers = 0,
7110 .offline_peers = 0,
7111 .unmonitored_peers = 0,
7112 };
7113
7114 struct ao2_iterator i;
7115
7116 struct iax2_peer *peer = NULL;
7117
7118 switch (argc) {
7119 case 6:
7120 if (!strcasecmp(argv[3], "registered"))
7121 cont.registeredonly = 1;
7122 else
7123 return RESULT_SHOWUSAGE;
7124 if (!strcasecmp(argv[4], "like")) {
7125 if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
7126 return RESULT_SHOWUSAGE;
7127 cont.havepattern = 1;
7128 } else
7129 return RESULT_SHOWUSAGE;
7130 break;
7131 case 5:
7132 if (!strcasecmp(argv[3], "like")) {
7133 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
7134 return RESULT_SHOWUSAGE;
7135 cont.havepattern = 1;
7136 } else
7137 return RESULT_SHOWUSAGE;
7138 break;
7139 case 4:
7140 if (!strcasecmp(argv[3], "registered")) {
7141 cont.registeredonly = 1;
7142 } else {
7143 return RESULT_SHOWUSAGE;
7144 }
7145 break;
7146 case 3:
7147 break;
7148 default:
7149 return RESULT_SHOWUSAGE;
7150 }
7151
7152
7153 if (!s) {
7154 ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7155 }
7156
7157 i = ao2_iterator_init(peers, 0);
7158 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7159
7160 if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7161 continue;
7162 }
7163 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7164 continue;
7165 }
7166
7167 _iax2_show_peers_one(fd, s, &cont, peer);
7168
7169 }
7171
7172 if (!s) {
7173 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7175 }
7176
7177 if (cont.havepattern) {
7178 regfree(&cont.regexbuf);
7179 }
7180
7181 if (total) {
7182 *total = cont.total_peers;
7183 }
7184
7185 return RESULT_SUCCESS;
7186
7187}
7188#undef PEERS_FORMAT2
7189#undef PEERS_FORMAT
7190
7191static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7192{
7193 struct iax2_thread *thread = NULL;
7194 time_t t;
7195 int threadcount = 0, dynamiccount = 0;
7196 char type;
7197
7198 switch (cmd) {
7199 case CLI_INIT:
7200 e->command = "iax2 show threads";
7201 e->usage =
7202 "Usage: iax2 show threads\n"
7203 " Lists status of IAX helper threads\n";
7204 return NULL;
7205 case CLI_GENERATE:
7206 return NULL;
7207 }
7208 if (a->argc != 3)
7209 return CLI_SHOWUSAGE;
7210
7211 ast_cli(a->fd, "IAX2 Thread Information\n");
7212 time(&t);
7213 ast_cli(a->fd, "Idle Threads:\n");
7216#ifdef DEBUG_SCHED_MULTITHREAD
7217 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7218 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7219#else
7220 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7221 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7222#endif
7223 threadcount++;
7224 }
7226 ast_cli(a->fd, "Active Threads:\n");
7229 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
7230 type = 'D';
7231 else
7232 type = 'P';
7233#ifdef DEBUG_SCHED_MULTITHREAD
7234 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
7235 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7236#else
7237 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
7238 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7239#endif
7240 threadcount++;
7241 }
7243 ast_cli(a->fd, "Dynamic Threads:\n");
7246#ifdef DEBUG_SCHED_MULTITHREAD
7247 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7248 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7249#else
7250 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7251 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7252#endif
7253 dynamiccount++;
7254 }
7256 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
7257 return CLI_SUCCESS;
7258}
7259
7260static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7261{
7262 struct iax2_peer *p;
7263
7264 switch (cmd) {
7265 case CLI_INIT:
7266 e->command = "iax2 unregister";
7267 e->usage =
7268 "Usage: iax2 unregister <peername>\n"
7269 " Unregister (force expiration) an IAX2 peer from the registry.\n";
7270 return NULL;
7271 case CLI_GENERATE:
7272 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
7273 }
7274
7275 if (a->argc != 3)
7276 return CLI_SHOWUSAGE;
7277
7278 p = find_peer(a->argv[2], 1);
7279 if (p) {
7280 if (p->expire > -1) {
7281 struct iax2_peer *peer;
7282
7283 peer = ao2_find(peers, a->argv[2], OBJ_KEY);
7284 if (peer) {
7285 expire_registry(peer_ref(peer)); /* will release its own reference when done */
7286 peer_unref(peer); /* ref from ao2_find() */
7287 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
7288 } else {
7289 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
7290 }
7291 } else {
7292 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7293 }
7294 peer_unref(p);
7295 } else {
7296 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7297 }
7298 return CLI_SUCCESS;
7299}
7300
7301static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7302{
7303 int which = 0;
7304 struct iax2_peer *p = NULL;
7305 char *res = NULL;
7306 int wordlen = strlen(word);
7307
7308 /* 0 - iax2; 1 - unregister; 2 - <peername> */
7309 if (pos == 2) {
7310 struct ao2_iterator i = ao2_iterator_init(peers, 0);
7311 while ((p = ao2_iterator_next(&i))) {
7312 if (!strncasecmp(p->name, word, wordlen) &&
7313 ++which > state && p->expire > -1) {
7314 res = ast_strdup(p->name);
7315 peer_unref(p);
7316 break;
7317 }
7318 peer_unref(p);
7319 }
7321 }
7322
7323 return res;
7324}
7325
7326static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7327{
7328 switch (cmd) {
7329 case CLI_INIT:
7330 e->command = "iax2 show peers";
7331 e->usage =
7332 "Usage: iax2 show peers [registered] [like <pattern>]\n"
7333 " Lists all known IAX2 peers.\n"
7334 " Optional 'registered' argument lists only peers with known addresses.\n"
7335 " Optional regular expression pattern is used to filter the peer list.\n";
7336 return NULL;
7337 case CLI_GENERATE:
7338 return NULL;
7339 }
7340
7341 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7342 case RESULT_SHOWUSAGE:
7343 return CLI_SHOWUSAGE;
7344 case RESULT_FAILURE:
7345 return CLI_FAILURE;
7346 default:
7347 return CLI_SUCCESS;
7348 }
7349}
7350
7351static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7352{
7353 ast_cli_netstats(s, -1, 0);
7354 astman_append(s, "\r\n");
7355 return RESULT_SUCCESS;
7356}
7357
7359 void *user_data)
7360{
7361 int *fd = user_data;
7362
7363 ast_cli(*fd, "%-15.15s %-15d %-15d\n",
7364 header->devname,
7365 ntohs(header->version),
7366 (int) ntohl(header->datalen));
7367
7368 return 0;
7369}
7370
7371static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7372{
7373 switch (cmd) {
7374 case CLI_INIT:
7375 e->command = "iax2 show firmware";
7376 e->usage =
7377 "Usage: iax2 show firmware\n"
7378 " Lists all known IAX firmware images.\n";
7379 return NULL;
7380 case CLI_GENERATE:
7381 return NULL;
7382 }
7383
7384 if (a->argc != 3 && a->argc != 4)
7385 return CLI_SHOWUSAGE;
7386
7387 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7388
7390 a->argc == 3 ? NULL : a->argv[3],
7392 (void *) &a->fd);
7393
7394 return CLI_SUCCESS;
7395}
7396
7397/*! \brief callback to display iax peers in manager */
7398static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7399{
7400 static const char * const a[] = { "iax2", "show", "peers" };
7401 const char *id = astman_get_header(m,"ActionID");
7402 char idtext[256] = "";
7403 int total = 0;
7404
7405 if (!ast_strlen_zero(id))
7406 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7407
7408 astman_send_listack(s, m, "Peer status list will follow", "start");
7409
7410 /* List the peers in separate manager events */
7411 __iax2_show_peers(-1, &total, s, 3, a);
7412
7413 /* Send final confirmation */
7414 astman_send_list_complete_start(s, m, "PeerlistComplete", total);
7416 return 0;
7417}
7418
7419/*! \brief callback to display iax peers in manager format */
7420static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7421{
7422 struct show_peers_context cont = {
7423 .havepattern = 0,
7424 .idtext = "",
7425 .registeredonly = 0,
7426
7427 .peerlist = 1,
7428
7429 .total_peers = 0,
7430 .online_peers = 0,
7431 .offline_peers = 0,
7432 .unmonitored_peers = 0,
7433 };
7434
7435 struct iax2_peer *peer = NULL;
7436 struct ao2_iterator i;
7437
7438 const char *id = astman_get_header(m,"ActionID");
7439
7440 if (!ast_strlen_zero(id)) {
7441 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
7442 }
7443
7444 astman_send_listack(s, m, "IAX Peer status list will follow", "start");
7445
7446 i = ao2_iterator_init(peers, 0);
7447 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7448 _iax2_show_peers_one(-1, s, &cont, peer);
7449 }
7451
7452 astman_send_list_complete_start(s, m, "PeerlistComplete", cont.total_peers);
7454
7455 return RESULT_SUCCESS;
7456}
7457
7458
7459static char *regstate2str(int regstate)
7460{
7461 switch(regstate) {
7463 return "Unregistered";
7464 case REG_STATE_REGSENT:
7465 return "Request Sent";
7466 case REG_STATE_AUTHSENT:
7467 return "Auth. Sent";
7469 return "Registered";
7470 case REG_STATE_REJECTED:
7471 return "Rejected";
7472 case REG_STATE_TIMEOUT:
7473 return "Timeout";
7474 case REG_STATE_NOAUTH:
7475 return "No Authentication";
7476 default:
7477 return "Unknown";
7478 }
7479}
7480
7481static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7482{
7483#define FORMAT2 "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
7484#define FORMAT "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
7485
7486 struct iax2_registry *reg = NULL;
7487 char host[80];
7488 char perceived[80];
7489 int counter = 0;
7490
7491 switch (cmd) {
7492 case CLI_INIT:
7493 e->command = "iax2 show registry";
7494 e->usage =
7495 "Usage: iax2 show registry\n"
7496 " Lists all registration requests and status.\n";
7497 return NULL;
7498 case CLI_GENERATE:
7499 return NULL;
7500 }
7501 if (a->argc != 3)
7502 return CLI_SHOWUSAGE;
7503 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7506 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7507
7508 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7509
7510 ast_cli(a->fd, FORMAT, host,
7511 (reg->dnsmgr) ? "Y" : "N",
7512 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7513 counter++;
7514 }
7516 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7517 return CLI_SUCCESS;
7518#undef FORMAT
7519#undef FORMAT2
7520}
7521
7522static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7523{
7524 const char *id = astman_get_header(m, "ActionID");
7525 struct iax2_registry *reg = NULL;
7526 char idtext[256] = "";
7527 char host[80] = "";
7528 char perceived[80] = "";
7529 int total = 0;
7530
7531 if (!ast_strlen_zero(id))
7532 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7533
7534 astman_send_listack(s, m, "Registrations will follow", "start");
7535
7538 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7539
7540 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7541
7542 astman_append(s,
7543 "Event: RegistryEntry\r\n"
7544 "%s"
7545 "Host: %s\r\n"
7546 "DNSmanager: %s\r\n"
7547 "Username: %s\r\n"
7548 "Perceived: %s\r\n"
7549 "Refresh: %d\r\n"
7550 "State: %s\r\n"
7551 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7552 reg->refresh, regstate2str(reg->regstate));
7553
7554 total++;
7555 }
7557
7558 astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
7560
7561 return 0;
7562}
7563
7564static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7565{
7566#define FORMAT2 "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7567#define FORMAT "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
7568#define FORMATB "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7569 int x;
7570 int numchans = 0;
7571 char first_message[10] = { 0, };
7572 char last_message[10] = { 0, };
7573
7574 switch (cmd) {
7575 case CLI_INIT:
7576 e->command = "iax2 show channels";
7577 e->usage =
7578 "Usage: iax2 show channels\n"
7579 " Lists all currently active IAX channels.\n";
7580 return NULL;
7581 case CLI_GENERATE:
7582 return NULL;
7583 }
7584
7585 if (a->argc != 3)
7586 return CLI_SHOWUSAGE;
7587 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7588 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7589 ast_mutex_lock(&iaxsl[x]);
7590 if (iaxs[x]) {
7591 int lag, jitter, localdelay;
7592 jb_info jbinfo;
7594 jb_getinfo(iaxs[x]->jb, &jbinfo);
7595 jitter = jbinfo.jitter;
7596 localdelay = jbinfo.current - jbinfo.min;
7597 } else {
7598 jitter = -1;
7599 localdelay = 0;
7600 }
7601
7602 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7603 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7604 lag = iaxs[x]->remote_rr.delay;
7605 ast_cli(a->fd, FORMAT,
7606 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7608 S_OR(iaxs[x]->username, "(None)"),
7609 iaxs[x]->callno, iaxs[x]->peercallno,
7610 iaxs[x]->oseqno, iaxs[x]->iseqno,
7611 lag,
7612 jitter,
7613 localdelay,
7614 iax2_getformatname(iaxs[x]->voiceformat),
7615 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7616 first_message,
7617 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7618 last_message);
7619 numchans++;
7620 }
7622 }
7623 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7624 return CLI_SUCCESS;
7625#undef FORMAT
7626#undef FORMAT2
7627#undef FORMATB
7628}
7629
7630static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7631{
7632 int x;
7633 int numchans = 0;
7634 char first_message[10] = { 0, };
7635 char last_message[10] = { 0, };
7636#define ACN_FORMAT1 "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7637#define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7638 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7639 ast_mutex_lock(&iaxsl[x]);
7640 if (iaxs[x]) {
7641 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7642 jb_info jbinfo;
7643 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7644 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7645
7647 jb_getinfo(iaxs[x]->jb, &jbinfo);
7648 localjitter = jbinfo.jitter;
7649 localdelay = jbinfo.current - jbinfo.min;
7650 locallost = jbinfo.frames_lost;
7651 locallosspct = jbinfo.losspct/1000;
7652 localdropped = jbinfo.frames_dropped;
7653 localooo = jbinfo.frames_ooo;
7654 } else {
7655 localjitter = -1;
7656 localdelay = 0;
7657 locallost = -1;
7658 locallosspct = -1;
7659 localdropped = 0;
7660 localooo = -1;
7661 }
7662 if (s)
7663 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7664 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7665 iaxs[x]->pingtime,
7666 localjitter,
7667 localdelay,
7668 locallost,
7669 locallosspct,
7670 localdropped,
7671 localooo,
7672 iaxs[x]->frames_received/1000,
7673 iaxs[x]->remote_rr.jitter,
7674 iaxs[x]->remote_rr.delay,
7678 iaxs[x]->remote_rr.ooo,
7679 iaxs[x]->remote_rr.packets/1000,
7680 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7681 first_message,
7682 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7683 last_message);
7684 else
7685 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7686 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7687 iaxs[x]->pingtime,
7688 localjitter,
7689 localdelay,
7690 locallost,
7691 locallosspct,
7692 localdropped,
7693 localooo,
7694 iaxs[x]->frames_received/1000,
7695 iaxs[x]->remote_rr.jitter,
7696 iaxs[x]->remote_rr.delay,
7700 iaxs[x]->remote_rr.ooo,
7701 iaxs[x]->remote_rr.packets/1000,
7702 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7703 first_message,
7704 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7705 last_message);
7706 numchans++;
7707 }
7709 }
7710
7711 return numchans;
7712}
7713
7714static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7715{
7716 int numchans = 0;
7717
7718 switch (cmd) {
7719 case CLI_INIT:
7720 e->command = "iax2 show netstats";
7721 e->usage =
7722 "Usage: iax2 show netstats\n"
7723 " Lists network status for all currently active IAX channels.\n";
7724 return NULL;
7725 case CLI_GENERATE:
7726 return NULL;
7727 }
7728 if (a->argc != 3)
7729 return CLI_SHOWUSAGE;
7730 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7731 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7732 numchans = ast_cli_netstats(NULL, a->fd, 1);
7733 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7734 return CLI_SUCCESS;
7735}
7736
7737static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7738{
7739 switch (cmd) {
7740 case CLI_INIT:
7741 e->command = "iax2 set debug {on|off|peer}";
7742 e->usage =
7743 "Usage: iax2 set debug {on|off|peer peername}\n"
7744 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7745 return NULL;
7746 case CLI_GENERATE:
7747 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7748 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7749 return NULL;
7750 }
7751
7752 if (a->argc < e->args || a->argc > e->args + 1)
7753 return CLI_SHOWUSAGE;
7754
7755 if (!strcasecmp(a->argv[3], "peer")) {
7756 struct iax2_peer *peer;
7757
7758 if (a->argc != e->args + 1)
7759 return CLI_SHOWUSAGE;
7760
7761 peer = find_peer(a->argv[4], 1);
7762
7763 if (!peer) {
7764 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7765 return CLI_FAILURE;
7766 }
7767
7769
7770 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_port(&debugaddr));
7771
7772 ao2_ref(peer, -1);
7773 } else if (!strncasecmp(a->argv[3], "on", 2)) {
7774 iaxdebug = 1;
7775 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7776 } else {
7777 iaxdebug = 0;
7778 memset(&debugaddr, 0, sizeof(debugaddr));
7779 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7780 }
7781 return CLI_SUCCESS;
7782}
7783
7784static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7785{
7786 switch (cmd) {
7787 case CLI_INIT:
7788 e->command = "iax2 set debug trunk {on|off}";
7789 e->usage =
7790 "Usage: iax2 set debug trunk {on|off}\n"
7791 " Enables/Disables debugging of IAX trunking\n";
7792 return NULL;
7793 case CLI_GENERATE:
7794 return NULL;
7795 }
7796
7797 if (a->argc != e->args)
7798 return CLI_SHOWUSAGE;
7799
7800 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7801 iaxtrunkdebug = 1;
7802 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7803 } else {
7804 iaxtrunkdebug = 0;
7805 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7806 }
7807 return CLI_SUCCESS;
7808}
7809
7810static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7811{
7812 switch (cmd) {
7813 case CLI_INIT:
7814 e->command = "iax2 set debug jb {on|off}";
7815 e->usage =
7816 "Usage: iax2 set debug jb {on|off}\n"
7817 " Enables/Disables jitterbuffer debugging information\n";
7818 return NULL;
7819 case CLI_GENERATE:
7820 return NULL;
7821 }
7822
7823 if (a->argc != e->args)
7824 return CLI_SHOWUSAGE;
7825
7826 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7828 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7829 } else {
7831 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7832 }
7833 return CLI_SUCCESS;
7834}
7835
7836static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7837{
7838 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
7839 int res = -1;
7841 if (iaxs[callno]) {
7842 /* If there's an outstanding error, return failure now */
7843 if (!iaxs[callno]->error) {
7845 res = 0;
7846 /* Don't waste bandwidth sending null frames */
7847 else if (f->frametype == AST_FRAME_NULL)
7848 res = 0;
7850 res = 0;
7852 res = 0;
7853 else
7854 /* Simple, just queue for transmission */
7855 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7856 } else {
7857 ast_debug(1, "Write error: %s\n", strerror(errno));
7858 }
7859 }
7860 /* If it's already gone, just return */
7862 return res;
7863}
7864
7865static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7866 int now, int transfer, int final)
7867{
7868 struct ast_frame f = { 0, };
7869 int res = 0;
7870
7871 f.frametype = type;
7872 f.subclass.integer = command;
7873 f.datalen = datalen;
7874 f.src = __FUNCTION__;
7875 f.data.ptr = (void *) data;
7876
7877 if ((res = queue_signalling(i, &f)) <= 0) {
7878 return res;
7879 }
7880
7881 return iax2_send(i, &f, ts, seqno, now, transfer, final);
7882}
7883
7884static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7885{
7887 /* Control frame should not go out on the wire. */
7888 ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7889 i->callno, command);
7890 return 0;
7891 }
7892 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7893}
7894
7895static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7896{
7897 int res;
7898 ast_mutex_lock(&iaxsl[callno]);
7899 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7900 ast_mutex_unlock(&iaxsl[callno]);
7901 return res;
7902}
7903
7904/*!
7905 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7906 * the pvt struct for the given call number may disappear during its
7907 * execution.
7908 */
7909static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7910{
7911 int call_num = i->callno;
7912 /* It is assumed that the callno has already been locked */
7914 if (!iaxs[call_num])
7915 return -1;
7916 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7917}
7918
7919static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7920{
7921 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7922}
7923
7924static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7925{
7926 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7927}
7928
7929static int apply_context(struct iax2_context *con, const char *context)
7930{
7931 while(con) {
7932 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7933 return -1;
7934 con = con->next;
7935 }
7936 return 0;
7937}
7938
7939
7940static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
7941{
7942 /* Start pessimistic */
7943 int res = -1;
7944 int version = 2;
7945 struct iax2_user *user = NULL, *best = NULL;
7946 int bestscore = 0;
7947 int gotcapability = 0;
7948 struct ast_variable *v = NULL, *tmpvar = NULL;
7949 struct ao2_iterator i;
7950
7951 if (!iaxs[callno])
7952 return res;
7953 if (ies->called_number)
7954 ast_string_field_set(iaxs[callno], exten, ies->called_number);
7955 if (ies->calling_number) {
7958 }
7959 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7960 }
7961 if (ies->calling_name)
7962 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7963 if (ies->calling_ani)
7964 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7965 if (ies->dnid)
7966 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7967 if (ies->rdnis)
7968 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7969 if (ies->called_context)
7970 ast_string_field_set(iaxs[callno], context, ies->called_context);
7971 if (ies->language)
7973 if (ies->username)
7974 ast_string_field_set(iaxs[callno], username, ies->username);
7975 if (ies->calling_ton > -1)
7976 iaxs[callno]->calling_ton = ies->calling_ton;
7977 if (ies->calling_tns > -1)
7978 iaxs[callno]->calling_tns = ies->calling_tns;
7979 if (ies->calling_pres > -1)
7980 iaxs[callno]->calling_pres = ies->calling_pres;
7981 if (ies->calling_ani2 > -1)
7982 iaxs[callno]->calling_ani2 = ies->calling_ani2;
7983 if (ies->format)
7984 iaxs[callno]->peerformat = ies->format;
7985 if (ies->adsicpe)
7986 iaxs[callno]->peeradsicpe = ies->adsicpe;
7987 if (ies->capability) {
7988 gotcapability = 1;
7989 iaxs[callno]->peercapability = ies->capability;
7990 }
7991 if (ies->version)
7992 version = ies->version;
7993
7994 /* Use provided preferences until told otherwise for actual preferences */
7995 if (ies->codec_prefs) {
7996 iax2_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7997 } else {
7998 memset(&iaxs[callno]->rprefs, 0, sizeof(iaxs[callno]->rprefs));
7999 }
8000 iaxs[callno]->prefs = iaxs[callno]->rprefs;
8001
8002 if (!gotcapability) {
8003 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
8004 }
8005 if (version > IAX_PROTO_VERSION) {
8006 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
8008 return res;
8009 }
8010 /* Search the userlist for a compatible entry, and fill in the rest */
8011 i = ao2_iterator_init(users, 0);
8012 while ((user = ao2_iterator_next(&i))) {
8013 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
8014 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
8015 && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
8016 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
8017 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
8018 if (!ast_strlen_zero(iaxs[callno]->username)) {
8019 /* Exact match, stop right now. */
8020 if (best)
8021 user_unref(best);
8022 best = user;
8023 break;
8024 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
8025 /* No required authentication */
8026 if (user->acl) {
8027 /* There was host authentication and we passed, bonus! */
8028 if (bestscore < 4) {
8029 bestscore = 4;
8030 if (best)
8031 user_unref(best);
8032 best = user;
8033 continue;
8034 }
8035 } else {
8036 /* No host access, but no secret, either, not bad */
8037 if (bestscore < 3) {
8038 bestscore = 3;
8039 if (best)
8040 user_unref(best);
8041 best = user;
8042 continue;
8043 }
8044 }
8045 } else {
8046 if (user->acl) {
8047 /* Authentication, but host access too, eh, it's something.. */
8048 if (bestscore < 2) {
8049 bestscore = 2;
8050 if (best)
8051 user_unref(best);
8052 best = user;
8053 continue;
8054 }
8055 } else {
8056 /* Authentication and no host access... This is our baseline */
8057 if (bestscore < 1) {
8058 bestscore = 1;
8059 if (best)
8060 user_unref(best);
8061 best = user;
8062 continue;
8063 }
8064 }
8065 }
8066 }
8068 }
8070 user = best;
8071 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
8072 user = realtime_user(iaxs[callno]->username, addr);
8073 if (user && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
8074 || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
8075 !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
8076 user = user_unref(user);
8077 }
8078 }
8079 if (user) {
8080 /* We found our match (use the first) */
8081 /* copy vars */
8082 for (v = user->vars ; v ; v = v->next) {
8083 if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
8084 if (ast_variable_list_replace(&iaxs[callno]->vars, tmpvar)) {
8085 tmpvar->next = iaxs[callno]->vars;
8086 iaxs[callno]->vars = tmpvar;
8087 }
8088 }
8089 }
8090 /* If a max AUTHREQ restriction is in place, activate it */
8091 if (user->maxauthreq > 0)
8093 iaxs[callno]->prefs = user->prefs;
8095 iaxs[callno]->encmethods = user->encmethods;
8096 /* Store the requested username if not specified */
8097 if (ast_strlen_zero(iaxs[callno]->username))
8098 ast_string_field_set(iaxs[callno], username, user->name);
8099 /* Store whether this is a trunked call, too, of course, and move if appropriate */
8101 iaxs[callno]->capability = user->capability;
8102 /* And use the default context */
8103 if (ast_strlen_zero(iaxs[callno]->context)) {
8104 if (user->contexts)
8105 ast_string_field_set(iaxs[callno], context, user->contexts->context);
8106 else
8107 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
8108 }
8109 /* And any input keys */
8110 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
8111 /* And the permitted authentication methods */
8112 iaxs[callno]->authmethods = user->authmethods;
8113 iaxs[callno]->adsi = user->adsi;
8114 /* If the user has callerid, override the remote caller id. */
8116 iaxs[callno]->calling_tns = 0;
8117 iaxs[callno]->calling_ton = 0;
8118 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
8119 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
8120 ast_string_field_set(iaxs[callno], ani, user->cid_num);
8122 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
8124 } /* else user is allowed to set their own CID settings */
8125 if (!ast_strlen_zero(user->accountcode))
8126 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
8127 if (!ast_strlen_zero(user->mohinterpret))
8128 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
8129 if (!ast_strlen_zero(user->mohsuggest))
8130 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
8131 if (!ast_strlen_zero(user->parkinglot))
8132 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
8133 if (user->amaflags)
8134 iaxs[callno]->amaflags = user->amaflags;
8135 if (!ast_strlen_zero(user->language))
8136 ast_string_field_set(iaxs[callno], language, user->language);
8138 /* Keep this check last */
8139 if (!ast_strlen_zero(user->dbsecret)) {
8140 char *family, *key=NULL;
8141 char buf[80];
8142 family = ast_strdupa(user->dbsecret);
8143 key = strchr(family, '/');
8144 if (key) {
8145 *key = '\0';
8146 key++;
8147 }
8148 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
8149 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
8150 else
8151 ast_string_field_set(iaxs[callno], secret, buf);
8152 } else
8153 ast_string_field_set(iaxs[callno], secret, user->secret);
8154 res = 0;
8155 user = user_unref(user);
8156 } else {
8157 /* user was not found, but we should still fake an AUTHREQ.
8158 * Set authmethods to the last known authmethod used by the system
8159 * Set a fake secret, it's not looked at, just required to attempt authentication.
8160 * Set authrej so the AUTHREP is rejected without even looking at its contents */
8162 ast_string_field_set(iaxs[callno], secret, "badsecret");
8163 iaxs[callno]->authrej = 1;
8164 if (!ast_strlen_zero(iaxs[callno]->username)) {
8165 /* only send the AUTHREQ if a username was specified. */
8166 res = 0;
8167 }
8168 }
8170 return res;
8171}
8172
8173static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
8174{
8175 struct ast_iax2_full_hdr fh;
8176 fh.scallno = htons(src | IAX_FLAG_FULL);
8177 fh.dcallno = htons(dst);
8178 fh.ts = 0;
8179 fh.oseqno = 0;
8180 fh.iseqno = 0;
8181 fh.type = AST_FRAME_IAX;
8183 iax_outputframe(NULL, &fh, 0, addr, 0);
8184
8185 ast_debug(1, "Raw Hangup %s, src=%d, dst=%d\n", ast_sockaddr_stringify(addr), src, dst);
8186 return ast_sendto(sockfd, &fh, sizeof(fh), 0, addr);
8187}
8188
8189static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
8190{
8191 /* Select exactly one common encryption if there are any */
8192 p->encmethods &= enc;
8193 if (p->encmethods) {
8194 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
8195 p->keyrotateid = -2;
8196 }
8199 else
8200 p->encmethods = 0;
8201 }
8202}
8203
8204/*!
8205 * \pre iaxsl[call_num] is locked
8206 *
8207 * \note Since this function calls send_command_final(), the pvt struct for the given
8208 * call number may disappear while executing this function.
8209 */
8210static int authenticate_request(int call_num)
8211{
8212 struct iax_ie_data ied;
8213 int res = -1, authreq_restrict = 0;
8214 char challenge[10];
8215 struct chan_iax2_pvt *p = iaxs[call_num];
8216
8217 memset(&ied, 0, sizeof(ied));
8218
8219 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8221 struct iax2_user *user;
8222
8224 if (user) {
8225 if (user->curauthreq == user->maxauthreq)
8226 authreq_restrict = 1;
8227 else
8228 user->curauthreq++;
8229 user = user_unref(user);
8230 }
8231 }
8232
8233 /* If the AUTHREQ limit test failed, send back an error */
8234 if (authreq_restrict) {
8235 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8238 return 0;
8239 }
8240
8242 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8243 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8245 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8247 }
8248 if (p->encmethods)
8250
8252
8253 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8254
8255 if (p->encmethods)
8257
8258 return res;
8259}
8260
8261static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
8262{
8263 char requeststr[256];
8264 char md5secret[256] = "";
8265 char secret[256] = "";
8266 char rsasecret[256] = "";
8267 int res = -1;
8268 int x;
8269 struct iax2_user *user;
8270
8271 if (p->authrej) {
8272 return res;
8273 }
8274
8276 if (user) {
8278 ast_atomic_fetchadd_int(&user->curauthreq, -1);
8280 }
8281 ast_string_field_set(p, host, user->name);
8282 user = user_unref(user);
8283 }
8285 ast_log(LOG_WARNING, "Call Terminated, incoming call is unencrypted while force encrypt is enabled.\n");
8286 return res;
8287 }
8289 return res;
8290 if (ies->password)
8291 ast_copy_string(secret, ies->password, sizeof(secret));
8292 if (ies->md5_result)
8293 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8294 if (ies->rsa_result)
8295 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8296 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8297 struct ast_key *key;
8298 char *keyn;
8299 char *tmpkey;
8300 char *stringp=NULL;
8301 if (!(tmpkey = ast_strdup(p->inkeys))) {
8302 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8303 return res;
8304 }
8305 stringp = tmpkey;
8306 keyn = strsep(&stringp, ":");
8307 while(keyn) {
8308 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8309 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8310 res = 0;
8312 break;
8313 } else if (!key) {
8314 ast_log(LOG_WARNING, "Requested inkey '%s' for RSA authentication does not exist\n", keyn);
8315 }
8316 keyn = strsep(&stringp, ":");
8317 }
8318 ast_free(tmpkey);
8319 if (res && authdebug) {
8320 ast_log(LOG_WARNING, "No RSA public keys on file matched incoming call\n");
8321 }
8322 } else if (p->authmethods & IAX_AUTH_MD5) {
8323 struct MD5Context md5;
8324 unsigned char digest[16];
8325 char *tmppw, *stringp;
8326 tmppw = ast_strdupa(p->secret);
8327 stringp = tmppw;
8328 while((tmppw = strsep(&stringp, ";"))) {
8329 MD5Init(&md5);
8330 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8331 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8332 MD5Final(digest, &md5);
8333 /* If they support md5, authenticate with it. */
8334 for (x=0;x<16;x++)
8335 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8336 if (!strcasecmp(requeststr, md5secret)) {
8337 res = 0;
8339 break;
8340 } else if (authdebug) {
8341 ast_log(LOG_WARNING, "MD5 secret mismatch\n");
8342 }
8343 }
8344 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8345 if (!strcmp(secret, p->secret)) {
8346 res = 0;
8348 } else if (authdebug) {
8349 ast_log(LOG_WARNING, "Plaintext secret mismatch\n");
8350 }
8351 }
8352 return res;
8353}
8354
8355/*! \brief Verify inbound registration */
8356static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
8357{
8358 char requeststr[256] = "";
8359 char peer[256] = "";
8360 char md5secret[256] = "";
8361 char rsasecret[256] = "";
8362 char secret[256] = "";
8363 struct iax2_peer *p = NULL;
8364 struct ast_key *key;
8365 char *keyn;
8366 int x;
8367 int expire = 0;
8368 int res = -1;
8369
8371 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8372 if (ies->username)
8373 ast_copy_string(peer, ies->username, sizeof(peer));
8374 if (ies->password)
8375 ast_copy_string(secret, ies->password, sizeof(secret));
8376 if (ies->md5_result)
8377 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8378 if (ies->rsa_result)
8379 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8380 if (ies->refresh)
8381 expire = ies->refresh;
8382
8383 if (ast_strlen_zero(peer)) {
8384 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_sockaddr_stringify_addr(addr));
8385 return -1;
8386 }
8387
8388 /* SLD: first call to lookup peer during registration */
8389 ast_mutex_unlock(&iaxsl[callno]);
8390 p = find_peer(peer, 1);
8391 ast_mutex_lock(&iaxsl[callno]);
8392 if (!p || !iaxs[callno]) {
8393 if (iaxs[callno]) {
8394 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8395 /* Anything, as long as it's non-blank */
8396 ast_string_field_set(iaxs[callno], secret, "badsecret");
8397 /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8398 * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8399 * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8400 * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8401 * to be plaintext, indicating it is an authmethod used by other peers on the system.
8402 *
8403 * If none of these cases exist, res will be returned as 0 without authentication indicating
8404 * an AUTHREQ needs to be sent out. */
8405
8406 if (ast_strlen_zero(iaxs[callno]->challenge) &&
8407 !(!ast_strlen_zero(secret) && plaintext)) {
8408 /* by setting res to 0, an REGAUTH will be sent */
8409 res = 0;
8410 }
8411 }
8412 if (authdebug && !p)
8413 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8414 goto return_unref;
8415 }
8416
8417 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8418 if (authdebug)
8419 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8420 goto return_unref;
8421 }
8422
8423 if (!ast_apply_acl(p->acl, addr, "IAX2 Peer ACL: ")) {
8424 if (authdebug)
8425 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8426 goto return_unref;
8427 }
8428 ast_string_field_set(iaxs[callno], secret, p->secret);
8429 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8430 /* Check secret against what we have on file */
8431 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8432 if (!ast_strlen_zero(p->inkeys)) {
8433 char *tmpkey;
8434 char *stringp=NULL;
8435 if (!(tmpkey = ast_strdup(p->inkeys))) {
8436 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8437 goto return_unref;
8438 }
8439 stringp = tmpkey;
8440 keyn = strsep(&stringp, ":");
8441 while(keyn) {
8442 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8443 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8445 break;
8446 } else if (!key)
8447 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8448 keyn = strsep(&stringp, ":");
8449 }
8450 ast_free(tmpkey);
8451 if (!keyn) {
8452 if (authdebug)
8453 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8454 goto return_unref;
8455 }
8456 } else {
8457 if (authdebug)
8458 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8459 goto return_unref;
8460 }
8461 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8462 struct MD5Context md5;
8463 unsigned char digest[16];
8464 char *tmppw, *stringp;
8465
8466 tmppw = ast_strdupa(p->secret);
8467 stringp = tmppw;
8468 while((tmppw = strsep(&stringp, ";"))) {
8469 MD5Init(&md5);
8470 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8471 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8472 MD5Final(digest, &md5);
8473 for (x=0;x<16;x++)
8474 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8475 if (!strcasecmp(requeststr, md5secret))
8476 break;
8477 }
8478 if (tmppw) {
8480 } else {
8481 if (authdebug)
8482 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_sockaddr_stringify_addr(addr), p->name, requeststr, md5secret);
8483 goto return_unref;
8484 }
8485 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8486 /* They've provided a plain text password and we support that */
8487 if (strcmp(secret, p->secret)) {
8488 if (authdebug)
8489 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8490 goto return_unref;
8491 } else
8493 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8494 /* if challenge has been sent, but no challenge response if given, reject. */
8495 goto return_unref;
8496 }
8497 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8498
8499 /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8500 res = 0;
8501
8502return_unref:
8503 if (iaxs[callno]) {
8504 ast_string_field_set(iaxs[callno], peer, peer);
8505
8506 /* Choose lowest expiry number */
8507 if (expire && (expire < iaxs[callno]->expiry)) {
8508 iaxs[callno]->expiry = expire;
8509 }
8510 }
8511
8512 if (p) {
8513 peer_unref(p);
8514 }
8515 return res;
8516}
8517
8518static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
8519{
8520 int res = -1;
8521 int x;
8522 if (!ast_strlen_zero(keyn)) {
8523 if (!(authmethods & IAX_AUTH_RSA)) {
8524 if (ast_strlen_zero(secret)) {
8525 ast_log(LOG_WARNING, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_sockaddr_stringify_addr(addr));
8526 }
8527 } else if (ast_strlen_zero(challenge)) {
8528 ast_log(LOG_WARNING, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8529 } else {
8530 char sig[256];
8531 struct ast_key *key;
8532 key = ast_key_get(keyn, AST_KEY_PRIVATE);
8533 if (!key) {
8534 ast_log(LOG_WARNING, "Unable to find private key '%s'\n", keyn);
8535 } else {
8536 if (ast_sign(key, (char*)challenge, sig)) {
8537 ast_log(LOG_WARNING, "Unable to sign challenge with key\n");
8538 res = -1;
8539 } else {
8541 if (pvt) {
8543 }
8544 res = 0;
8545 }
8546 }
8547
8548 if (pvt && !ast_strlen_zero(secret)) {
8549 struct MD5Context md5;
8550 unsigned char digest[16];
8551
8552 MD5Init(&md5);
8553 MD5Update(&md5, (unsigned char *) challenge, strlen(challenge));
8554 MD5Update(&md5, (unsigned char *) secret, strlen(secret));
8555 MD5Final(digest, &md5);
8556
8557 build_encryption_keys(digest, pvt);
8558 }
8559 }
8560 }
8561 /* Fall back */
8562 if (res && !ast_strlen_zero(secret)) {
8563 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8564 struct MD5Context md5;
8565 unsigned char digest[16];
8566 char digres[128];
8567 MD5Init(&md5);
8568 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8569 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8570 MD5Final(digest, &md5);
8571 /* If they support md5, authenticate with it. */
8572 for (x=0;x<16;x++)
8573 sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8574 if (pvt) {
8575 build_encryption_keys(digest, pvt);
8577 }
8579 res = 0;
8580 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8581 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8582 if (pvt) {
8584 }
8585 res = 0;
8586 } else
8587 ast_log(LOG_WARNING, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8588 }
8589 return res;
8590}
8591
8592/*!
8593 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8594 * so do not call this function with a pvt lock held.
8595 */
8596static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
8597{
8598 struct iax2_peer *peer = NULL;
8599 /* Start pessimistic */
8600 int res = -1;
8601 int authmethods = 0;
8602 struct iax_ie_data ied;
8603 uint16_t callno = p->callno;
8604
8605 memset(&ied, 0, sizeof(ied));
8606
8607 if (ies->username)
8608 ast_string_field_set(p, username, ies->username);
8609 if (ies->challenge)
8611 if (ies->authmethods)
8612 authmethods = ies->authmethods;
8613 if (authmethods & IAX_AUTH_MD5)
8615 else
8616 p->encmethods = 0;
8617
8618 /* Check for override RSA authentication first */
8619 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8620 /* Normal password authentication */
8621 res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8622 } else {
8623 struct ao2_iterator i = ao2_iterator_init(peers, 0);
8624 while ((peer = ao2_iterator_next(&i))) {
8625 struct ast_sockaddr peer_addr;
8626 struct ast_sockaddr tmp_sockaddr1;
8627 struct ast_sockaddr tmp_sockaddr2;
8628
8629 ast_sockaddr_copy(&peer_addr, &peer->addr);
8630
8631 ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8632 ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8633
8634 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8635 /* No peer specified at our end, or this is the peer */
8636 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8637 /* No username specified in peer rule, or this is the right username */
8638 && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8639 /* No specified host, or this is our host */
8640 ) {
8641 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8642 if (!res) {
8643 peer_unref(peer);
8644 break;
8645 }
8646 }
8647 peer_unref(peer);
8648 }
8650 if (!peer) {
8651 /* We checked our list and didn't find one. It's unlikely, but possible,
8652 that we're trying to authenticate *to* a realtime peer */
8653 const char *peer_name = ast_strdupa(p->peer);
8654 ast_mutex_unlock(&iaxsl[callno]);
8655 if ((peer = realtime_peer(peer_name, NULL))) {
8656 ast_mutex_lock(&iaxsl[callno]);
8657 if (!(p = iaxs[callno])) {
8658 peer_unref(peer);
8659 return -1;
8660 }
8661 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8662 peer_unref(peer);
8663 }
8664 if (!peer) {
8665 ast_mutex_lock(&iaxsl[callno]);
8666 if (!(p = iaxs[callno]))
8667 return -1;
8668 }
8669 }
8670 }
8671
8672 if (!(ies->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT)) && (ies->authmethods & IAX_AUTH_RSA) && ast_strlen_zero(okey)) {
8673 /* If the only thing available is RSA, and we don't have an outkey, we can't do it... */
8674 ast_log(LOG_WARNING, "Call terminated. RSA authentication requires an outkey\n");
8675 return -1;
8676 }
8677
8678 if (ies->encmethods) {
8679 if (ast_strlen_zero(p->secret) &&
8681 ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8682 return -1;
8683 }
8684 /* Don't even THINK about trying to encrypt or decrypt anything if we don't have valid keys, for some reason... */
8685 /* If either of these happens, it's our fault, not the user's. But we should abort rather than crash. */
8689 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8690 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8691 return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8692 }
8693 if (!res) {
8694 struct ast_datastore *variablestore;
8695 struct ast_variable *var, *prev = NULL;
8696 AST_LIST_HEAD(, ast_var_t) *varlist;
8697 varlist = ast_calloc(1, sizeof(*varlist));
8699 if (variablestore && varlist && p->owner) {
8700 variablestore->data = varlist;
8701 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8702 AST_LIST_HEAD_INIT(varlist);
8703 for (var = ies->vars; var; var = var->next) {
8704 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8705 if (prev)
8706 ast_free(prev);
8707 prev = var;
8708 if (!newvar) {
8709 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8710 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8711 } else {
8712 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8713 }
8714 }
8715 if (prev)
8716 ast_free(prev);
8717 ies->vars = NULL;
8718 ast_channel_datastore_add(p->owner, variablestore);
8719 } else {
8720 if (p->owner)
8721 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8722 if (variablestore)
8723 ast_datastore_free(variablestore);
8724 if (varlist)
8725 ast_free(varlist);
8726 }
8727 }
8728
8729 if (!res)
8730 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8731 return res;
8732}
8733
8734static int iax2_do_register(struct iax2_registry *reg);
8735
8736static void __iax2_do_register_s(const void *data)
8737{
8738 struct iax2_registry *reg = (struct iax2_registry *)data;
8739
8740 if (ast_sockaddr_isnull(&reg->addr)) {
8741 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8742 ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8743 if (!ast_sockaddr_port(&reg->addr)) {
8744 ast_sockaddr_set_port(&reg->addr, reg->port);
8745 } else {
8746 reg->port = ast_sockaddr_port(&reg->addr);
8747 }
8748 }
8749
8750 reg->expire = -1;
8751 iax2_do_register(reg);
8752}
8753
8754static int iax2_do_register_s(const void *data)
8755{
8756#ifdef SCHED_MULTITHREADED
8758#endif
8760 return 0;
8761}
8762
8763static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8764{
8765 int newcall = 0;
8766 struct iax_ie_data ied;
8767 struct ast_sockaddr new = { {0,} };
8768
8769 memset(&ied, 0, sizeof(ied));
8770 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8771 ast_sockaddr_copy(&new, &ies->apparent_addr);
8772 }
8773 if (ies->callno) {
8774 newcall = ies->callno;
8775 }
8776 if (!newcall || ast_sockaddr_isnull(&new)) {
8777 ast_log(LOG_WARNING, "Invalid transfer request\n");
8778 return -1;
8779 }
8780 pvt->transfercallno = newcall;
8781 ast_sockaddr_copy(&pvt->transfer, &new);
8782 pvt->transferid = ies->transferid;
8783 /* only store by transfercallno if this is a new transfer,
8784 * just in case we get a duplicate TXREQ */
8785 if (pvt->transferring == TRANSFER_NONE) {
8787 }
8789
8790 if (ies->transferid) {
8792 }
8794 return 0;
8795}
8796
8797static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8798{
8799 char exten[256] = "";
8800 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8801 struct iax2_dpcache *dp = NULL;
8802
8803 if (ies->called_number)
8804 ast_copy_string(exten, ies->called_number, sizeof(exten));
8805
8806 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8808 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8810 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8812
8813 if (ies->refresh)
8814 expiry = ies->refresh;
8817
8820 if (strcmp(dp->exten, exten))
8821 continue;
8823 dp->callno = 0;
8824 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8825 if (dp->flags & CACHE_FLAG_PENDING) {
8826 dp->flags &= ~CACHE_FLAG_PENDING;
8827 dp->flags |= status;
8828 dp->flags |= matchmore;
8829 }
8830 /* Wake up waiters */
8831 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8832 if (dp->waiters[x] > -1) {
8833 if (write(dp->waiters[x], "asdf", 4) < 0) {
8834 }
8835 }
8836 }
8837 }
8840
8841 return 0;
8842}
8843
8844static int complete_transfer(int callno, struct iax_ies *ies)
8845{
8846 int peercallno = 0;
8847 struct chan_iax2_pvt *pvt = iaxs[callno];
8848 struct iax_frame *cur;
8849 jb_frame frame;
8850
8851 if (ies->callno)
8852 peercallno = ies->callno;
8853
8854 if (peercallno < 1) {
8855 ast_log(LOG_WARNING, "Invalid transfer request\n");
8856 return -1;
8857 }
8859 /* since a transfer has taken place, the address will change.
8860 * This must be accounted for in the peercnts table. Remove
8861 * the old address and add the new one */
8863 peercnt_add(&pvt->transfer);
8864 /* now copy over the new address */
8865 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8866 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8867 /* Reset sequence numbers */
8868 pvt->oseqno = 0;
8869 pvt->rseqno = 0;
8870 pvt->iseqno = 0;
8871 pvt->aseqno = 0;
8872
8873 if (pvt->peercallno) {
8875 }
8876 pvt->peercallno = peercallno;
8877 /*this is where the transferring call switches hash tables */
8880 pvt->svoiceformat = -1;
8881 pvt->voiceformat = 0;
8882 pvt->svideoformat = -1;
8883 pvt->videoformat = 0;
8884 pvt->transfercallno = 0;
8885 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8886 memset(&pvt->offset, 0, sizeof(pvt->offset));
8887 /* reset jitterbuffer */
8888 while(jb_getall(pvt->jb,&frame) == JB_OK)
8889 iax2_frame_free(frame.data);
8890 jb_reset(pvt->jb);
8891 pvt->lag = 0;
8892 pvt->last = 0;
8893 pvt->lastsent = 0;
8894 pvt->nextpred = 0;
8897 /* We must cancel any packets that would have been transmitted
8898 because now we're talking to someone new. It's okay, they
8899 were transmitted to someone that didn't care anyway. */
8900 cur->retries = -1;
8901 }
8902 return 0;
8903}
8904
8905static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
8906{
8907 ast_system_publish_registry("IAX2", username, domain, status, cause);
8908}
8909
8910/*! \brief Acknowledgment received for OUR registration */
8911static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
8912{
8913 struct iax2_registry *reg;
8914 /* Start pessimistic */
8915 char peer[256] = "";
8916 char msgstatus[60];
8917 int refresh = 60;
8918 char ourip[256] = "<Unspecified>";
8919 struct ast_sockaddr oldus;
8920 struct ast_sockaddr us;
8921 int oldmsgs;
8922
8923 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8924 ast_sockaddr_copy(&us, &ies->apparent_addr);
8925 }
8926 if (ies->username) {
8927 ast_copy_string(peer, ies->username, sizeof(peer));
8928 }
8929 if (ies->refresh) {
8930 refresh = ies->refresh;
8931 }
8932 if (ies->calling_number) {
8933 /* We don't do anything with it really, but maybe we should */
8934 }
8935 reg = iaxs[callno]->reg;
8936 if (!reg) {
8937 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8938 return -1;
8939 }
8940 ast_sockaddr_copy(&oldus, &reg->us);
8941 oldmsgs = reg->messages;
8942 if (ast_sockaddr_cmp(&reg->addr, addr)) {
8943 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_sockaddr_stringify(addr));
8944 return -1;
8945 }
8946 ast_sockaddr_copy(&reg->us, &us);
8947 if (ies->msgcount >= 0) {
8948 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8949 }
8950 /* always refresh the registration at the interval requested by the server
8951 we are registering to
8952 */
8953 reg->refresh = refresh;
8955 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8956 if (ast_sockaddr_cmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8957
8958 if (reg->messages > 255) {
8959 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8960 } else if (reg->messages > 1) {
8961 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8962 } else if (reg->messages > 0) {
8963 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8964 } else {
8965 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8966 }
8967
8968 snprintf(ourip, sizeof(ourip), "%s", ast_sockaddr_stringify(&reg->us));
8969
8970 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_sockaddr_stringify(addr), ourip, msgstatus);
8971 iax2_publish_registry(reg->username, ast_sockaddr_stringify(addr), "Registered", NULL);
8972 }
8974 return 0;
8975}
8976
8977static int iax2_append_register(const char *hostname, const char *username,
8978 const char *secret, const char *porta)
8979{
8980 struct iax2_registry *reg;
8981
8982 if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
8983 return -1;
8984 }
8985
8986 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8987 if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8988 ast_free(reg);
8989 return -1;
8990 }
8991
8992 ast_copy_string(reg->username, username, sizeof(reg->username));
8993 strcpy(reg->hostname, hostname); /* Note: This is safe */
8994
8995 if (secret) {
8996 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8997 }
8998
8999 reg->expire = -1;
9001
9002 reg->port = ast_sockaddr_port(&reg->addr);
9003
9004 if (!porta && !reg->port) {
9005 reg->port = IAX_DEFAULT_PORTNO;
9006 } else if (porta) {
9007 sscanf(porta, "%5d", &reg->port);
9008 }
9009
9010 ast_sockaddr_set_port(&reg->addr, reg->port);
9011
9015
9016 return 0;
9017}
9018
9019static int iax2_register(const char *value, int lineno)
9020{
9021 char copy[256];
9022 char *username, *hostname, *secret;
9023 char *porta;
9024 char *stringp=NULL;
9025
9026 if (!value)
9027 return -1;
9028
9029 ast_copy_string(copy, value, sizeof(copy));
9030 stringp = copy;
9031 username = strsep(&stringp, "@");
9032 hostname = strsep(&stringp, "@");
9033
9034 if (!hostname) {
9035 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
9036 return -1;
9037 }
9038
9039 stringp = username;
9040 username = strsep(&stringp, ":");
9041 secret = strsep(&stringp, ":");
9042 stringp = hostname;
9043 hostname = strsep(&stringp, ":");
9044 porta = strsep(&stringp, ":");
9045
9046 if (porta && !atoi(porta)) {
9047 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
9048 return -1;
9049 }
9050
9052}
9053
9054
9055static void register_peer_exten(struct iax2_peer *peer, int onoff)
9056{
9057 char multi[256];
9058 char *stringp, *ext;
9060 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
9061 stringp = multi;
9062 while((ext = strsep(&stringp, "&"))) {
9063 if (onoff) {
9066 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
9067 } else
9069 }
9070 }
9071}
9072static void prune_peers(void);
9073
9074static void unlink_peer(struct iax2_peer *peer)
9075{
9076 if (peer->expire > -1) {
9077 if (!AST_SCHED_DEL(sched, peer->expire)) {
9078 peer->expire = -1;
9079 peer_unref(peer);
9080 }
9081 }
9082
9083 if (peer->pokeexpire > -1) {
9084 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
9085 peer->pokeexpire = -1;
9086 peer_unref(peer);
9087 }
9088 }
9089
9090 ao2_unlink(peers, peer);
9091}
9092
9093static void __expire_registry(const void *data)
9094{
9095 struct iax2_peer *peer = (struct iax2_peer *) data;
9096 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9097
9098 if (!peer)
9099 return;
9100 if (peer->expire == -1) {
9101 /* Removed already (possibly through CLI), ignore */
9102 return;
9103 }
9104
9105 peer->expire = -1;
9106
9107 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
9109 realtime_update_peer(peer->name, &peer->addr, 0);
9111 blob = ast_json_pack("{s: s, s: s}",
9112 "peer_status", "Unregistered",
9113 "cause", "Expired");
9115 /* modify entry in peercnts table as _not_ registered */
9116 peercnt_modify((unsigned char) 0, 0, &peer->addr);
9117 /* Reset the address */
9118 ast_sockaddr_setnull(&peer->addr);
9119 /* Reset expiry value */
9120 peer->expiry = min_reg_expire;
9121 if (!ast_test_flag64(peer, IAX_TEMPONLY))
9122 ast_db_del("IAX/Registry", peer->name);
9123 register_peer_exten(peer, 0);
9124 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
9125 if (iax2_regfunk)
9126 iax2_regfunk(peer->name, 0);
9127
9129 unlink_peer(peer);
9130
9131 peer_unref(peer);
9132}
9133
9134static int expire_registry(const void *data)
9135{
9136#ifdef SCHED_MULTITHREADED
9138#endif
9139 __expire_registry(data);
9140 return 0;
9141}
9142
9143static void reg_source_db(struct iax2_peer *p)
9144{
9145 char data[80];
9146 char *expiry;
9147
9148 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
9149 return;
9150 }
9151
9152 expiry = strrchr(data, ':');
9153 if (!expiry) {
9154 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
9155 return;
9156 }
9157 *expiry++ = '\0';
9158
9159 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
9160 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
9161 return;
9162 }
9163
9164 p->expiry = atoi(expiry);
9165
9166 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
9168
9169 iax2_poke_peer(p, 0);
9170 if (p->expire > -1) {
9171 if (!AST_SCHED_DEL(sched, p->expire)) {
9172 p->expire = -1;
9173 peer_unref(p);
9174 }
9175 }
9176
9177 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9178
9179 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9180 if (p->expire == -1) {
9181 peer_unref(p);
9182 }
9183
9184 if (iax2_regfunk) {
9185 iax2_regfunk(p->name, 1);
9186 }
9187
9188 register_peer_exten(p, 1);
9189}
9190
9191/*!
9192 * \pre iaxsl[callno] is locked
9193 *
9194 * \note Since this function calls send_command_final(), the pvt struct for
9195 * the given call number may disappear while executing this function.
9196 */
9197static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
9198{
9199
9200 /* Called from IAX thread only, with proper iaxsl lock */
9201 struct iax_ie_data ied = {
9202 .pos = 0,
9203 };
9204 struct iax2_peer *p;
9205 int msgcount;
9206 char data[80];
9207 uint16_t version;
9208 const char *peer_name;
9209 int res = -1;
9210 char *str_addr;
9211
9212 peer_name = ast_strdupa(iaxs[callno]->peer);
9213
9214 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
9216 if (!(p = find_peer(peer_name, 1))) {
9218 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
9219 return -1;
9220 }
9222 if (!iaxs[callno])
9223 goto return_unref;
9224
9226 if (!ast_sockaddr_isnull(addr)) {
9227 time_t nowtime;
9228 time(&nowtime);
9229 realtime_update_peer(peer_name, addr, nowtime);
9230 } else {
9231 realtime_update_peer(peer_name, addr, 0);
9232 }
9233 }
9234
9235 /* treat an unspecified refresh interval as the minimum */
9236 if (!refresh) {
9238 }
9239 if (refresh > max_reg_expire) {
9240 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9243 } else if (refresh < min_reg_expire) {
9244 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9247 } else {
9248 p->expiry = refresh;
9249 }
9250
9251 if (ast_sockaddr_cmp(&p->addr, addr)) {
9252 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9253
9254 if (iax2_regfunk) {
9255 iax2_regfunk(p->name, 1);
9256 }
9257
9258 /* modify entry in peercnts table as _not_ registered */
9259 peercnt_modify((unsigned char) 0, 0, &p->addr);
9260
9261 /* Stash the IP address from which they registered */
9263
9265
9266 snprintf(data, sizeof(data), "%s:%d", ast_sockaddr_stringify(addr), p->expiry);
9267
9269 ast_db_put("IAX/Registry", p->name, data);
9270 ast_verb(3, "Registered IAX2 '%s' (%s) at %s\n",
9271 p->name,
9272 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED",
9275 blob = ast_json_pack("{s: s, s: s, s: i}",
9276 "peer_status", "Registered",
9277 "address", str_addr,
9278 "port", ast_sockaddr_port(addr));
9279 register_peer_exten(p, 1);
9280 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9281 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
9282 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n",
9283 p->name,
9284 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
9286 blob = ast_json_pack("{s: s}",
9287 "peer_status", "Unregistered");
9288 register_peer_exten(p, 0);
9289 ast_db_del("IAX/Registry", p->name);
9290 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9291 }
9292
9294
9295 /* Update the host */
9296 /* Verify that the host is really there */
9298 }
9299
9300 /* modify entry in peercnts table as registered */
9301 if (p->maxcallno) {
9302 peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
9303 }
9304
9305 /* Make sure our call still exists, an INVAL at the right point may make it go away */
9306 if (!iaxs[callno]) {
9307 res = -1;
9308 goto return_unref;
9309 }
9310
9311 /* Store socket fd */
9312 p->sockfd = fd;
9313 /* Setup the expiry */
9314 if (p->expire > -1) {
9315 if (!AST_SCHED_DEL(sched, p->expire)) {
9316 p->expire = -1;
9317 peer_unref(p);
9318 }
9319 }
9320
9321 if (p->expiry && !ast_sockaddr_isnull(addr)) {
9322 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9323 if (p->expire == -1)
9324 peer_unref(p);
9325 }
9328 if (!ast_sockaddr_isnull(addr)) {
9329 struct ast_sockaddr peer_addr;
9330
9331 ast_sockaddr_copy(&peer_addr, &p->addr);
9332
9334 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
9335 if (!ast_strlen_zero(p->mailbox)) {
9336 int new, old;
9337 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
9338
9340 if (msg) {
9341 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
9342 new = mwi_state->new_msgs;
9343 old = mwi_state->old_msgs;
9344 } else { /* Fall back on checking the mailbox directly */
9345 ast_app_inboxcount(p->mailbox, &new, &old);
9346 }
9347
9348 if (new > 255) {
9349 new = 255;
9350 }
9351 if (old > 255) {
9352 old = 255;
9353 }
9354 msgcount = (old << 8) | new;
9355
9356 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
9357 }
9361 }
9362 }
9363 if (iax_firmware_get_version(devtype, &version)) {
9365 }
9366
9367 res = 0;
9368
9369return_unref:
9370 peer_unref(p);
9371
9372 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9373}
9374
9375static int registry_authrequest(int callno)
9376{
9377 struct iax_ie_data ied;
9378 struct iax2_peer *p;
9379 char challenge[10];
9380 const char *peer_name;
9381 int sentauthmethod;
9382
9383 peer_name = ast_strdupa(iaxs[callno]->peer);
9384
9385 /* SLD: third call to find_peer in registration */
9387 if ((p = find_peer(peer_name, 1))) {
9389 }
9390
9392 if (!iaxs[callno])
9393 goto return_unref;
9394
9395 memset(&ied, 0, sizeof(ied));
9396 /* The selection of which delayed reject is sent may leak information,
9397 * if it sets a static response. For example, if a host is known to only
9398 * use MD5 authentication, then an RSA response would indicate that the
9399 * peer does not exist, and vice-versa.
9400 * Therefore, we use whatever the last peer used (which may vary over the
9401 * course of a server, which should leak minimal information). */
9402 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : IAX_AUTH_MD5;
9403 if (!p) {
9404 iaxs[callno]->authmethods = sentauthmethod;
9405 }
9406 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9407 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9408 /* Build the challenge */
9409 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9412 }
9413 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9414
9415return_unref:
9416 if (p) {
9417 peer_unref(p);
9418 }
9419
9420 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9421}
9422
9423static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
9424{
9425 struct iax2_registry *reg;
9426 /* Start pessimistic */
9427 struct iax_ie_data ied;
9428 char peer[256] = "";
9429 char challenge[256] = "";
9430 int res;
9431 int authmethods = 0;
9432 if (ies->authmethods)
9433 authmethods = ies->authmethods;
9434 if (ies->username)
9435 ast_copy_string(peer, ies->username, sizeof(peer));
9436 if (ies->challenge)
9438 memset(&ied, 0, sizeof(ied));
9439 reg = iaxs[callno]->reg;
9440 if (reg) {
9441
9442 if (ast_sockaddr_cmp(&reg->addr, addr)) {
9443 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_sockaddr_stringify(addr));
9444 return -1;
9445 }
9446 if (ast_strlen_zero(reg->secret)) {
9447 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9449 return -1;
9450 }
9453 if (reg->secret[0] == '[') {
9454 char tmpkey[256];
9455 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9456 tmpkey[strlen(tmpkey) - 1] = '\0';
9457 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, addr, NULL);
9458 } else
9459 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, addr, NULL);
9460 if (!res) {
9462 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9463 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9464 } else
9465 return -1;
9466 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
9467 } else
9468 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9469 return -1;
9470}
9471
9472static void stop_stuff(int callno)
9473{
9474 iax2_destroy_helper(iaxs[callno]);
9475}
9476
9477static void __auth_reject(const void *nothing)
9478{
9479 /* Called from IAX thread only, without iaxs lock */
9480 int callno = (int)(long)(nothing);
9481 struct iax_ie_data ied;
9482 ast_mutex_lock(&iaxsl[callno]);
9483 if (iaxs[callno]) {
9484 memset(&ied, 0, sizeof(ied));
9485 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9486 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9488 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9489 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9491 }
9492 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9493 }
9494 ast_mutex_unlock(&iaxsl[callno]);
9495}
9496
9497static int auth_reject(const void *data)
9498{
9499 int callno = (int)(long)(data);
9500 ast_mutex_lock(&iaxsl[callno]);
9501 if (iaxs[callno])
9502 iaxs[callno]->authid = -1;
9503 ast_mutex_unlock(&iaxsl[callno]);
9504#ifdef SCHED_MULTITHREADED
9505 if (schedule_action(__auth_reject, data))
9506#endif
9507 __auth_reject(data);
9508 return 0;
9509}
9510
9511static int auth_fail(int callno, int failcode)
9512{
9513 /* Schedule sending the authentication failure in one second, to prevent
9514 guessing */
9515 if (iaxs[callno]) {
9516 iaxs[callno]->authfail = failcode;
9517 if (delayreject) {
9518 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9519 sched, 1000, auth_reject, (void *)(long)callno);
9520 } else
9521 auth_reject((void *)(long)callno);
9522 }
9523 return 0;
9524}
9525
9526static void __auto_hangup(const void *nothing)
9527{
9528 /* Called from IAX thread only, without iaxs lock */
9529 int callno = (int)(long)(nothing);
9530 struct iax_ie_data ied;
9531 ast_mutex_lock(&iaxsl[callno]);
9532 if (iaxs[callno]) {
9533 memset(&ied, 0, sizeof(ied));
9534 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9536 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9537 }
9538 ast_mutex_unlock(&iaxsl[callno]);
9539}
9540
9541static int auto_hangup(const void *data)
9542{
9543 int callno = (int)(long)(data);
9544 ast_mutex_lock(&iaxsl[callno]);
9545 if (iaxs[callno]) {
9546 iaxs[callno]->autoid = -1;
9547 }
9548 ast_mutex_unlock(&iaxsl[callno]);
9549#ifdef SCHED_MULTITHREADED
9550 if (schedule_action(__auto_hangup, data))
9551#endif
9552 __auto_hangup(data);
9553 return 0;
9554}
9555
9556static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9557{
9558 struct iax_ie_data ied;
9559 /* Auto-hangup with 30 seconds of inactivity */
9560 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9561 sched, 30000, auto_hangup, (void *)(long)callno);
9562 memset(&ied, 0, sizeof(ied));
9564 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9566}
9567
9568static int iax2_vnak(int callno)
9569{
9570 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9571}
9572
9573static void vnak_retransmit(int callno, int last)
9574{
9575 struct iax_frame *f;
9576
9578 /* Send a copy immediately */
9579 if (((unsigned char) (f->oseqno - last) < 128) &&
9580 (f->retries >= 0)) {
9581 send_packet(f);
9582 }
9583 }
9584}
9585
9586static void __iax2_poke_peer_s(const void *data)
9587{
9588 struct iax2_peer *peer = (struct iax2_peer *)data;
9589 iax2_poke_peer(peer, 0);
9590 peer_unref(peer);
9591}
9592
9593static int iax2_poke_peer_s(const void *data)
9594{
9595 struct iax2_peer *peer = (struct iax2_peer *)data;
9596 peer->pokeexpire = -1;
9597#ifdef SCHED_MULTITHREADED
9599#endif
9600 __iax2_poke_peer_s(data);
9601 return 0;
9602}
9603
9604static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9605{
9606 int res = 0;
9607 struct iax_frame *fr;
9608 struct ast_iax2_meta_hdr *meta;
9609 struct ast_iax2_meta_trunk_hdr *mth;
9610 int calls = 0;
9611
9612 /* Point to frame */
9613 fr = (struct iax_frame *)tpeer->trunkdata;
9614 /* Point to meta data */
9615 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9616 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9617 if (tpeer->trunkdatalen) {
9618 /* We're actually sending a frame, so fill the meta trunk header and meta header */
9619 meta->zeros = 0;
9620 meta->metacmd = IAX_META_TRUNK;
9622 meta->cmddata = IAX_META_TRUNK_MINI;
9623 else
9624 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
9625 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9626 /* And the rest of the ast_iax2 header */
9628 fr->retrans = -1;
9629 fr->transfer = 0;
9630 /* Any appropriate call will do */
9631 fr->data = fr->afdata;
9632 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9633 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9634 calls = tpeer->calls;
9635#if 0
9636 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
9637#endif
9638 /* Reset transmit trunk side data */
9639 tpeer->trunkdatalen = 0;
9640 tpeer->calls = 0;
9641 }
9642 if (res < 0)
9643 return res;
9644 return calls;
9645}
9646
9647static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9648{
9649 /* Drop when trunk is about 5 seconds idle */
9650 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9651 return 1;
9652 return 0;
9653}
9654
9655static int timing_read(int *id, int fd, short events, void *cbdata)
9656{
9657 int res, processed = 0, totalcalls = 0;
9658 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9659 struct timeval now = ast_tvnow();
9660
9661 if (iaxtrunkdebug) {
9662 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9663 }
9664
9665 if (timer) {
9666 if (ast_timer_ack(timer, 1) < 0) {
9667 ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9668 return 0;
9669 }
9670 }
9671
9672 /* For each peer that supports trunking... */
9674 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9675 processed++;
9676 res = 0;
9677 ast_mutex_lock(&tpeer->lock);
9678 /* We can drop a single tpeer per pass. That makes all this logic
9679 substantially easier */
9680 if (!drop && iax2_trunk_expired(tpeer, &now)) {
9681 /* Take it out of the list, but don't free it yet, because it
9682 could be in use */
9684 drop = tpeer;
9685 } else {
9686 res = send_trunk(tpeer, &now);
9687 trunk_timed++;
9688 if (iaxtrunkdebug) {
9689 ast_verbose(" - Trunk peer (%s) has %d call chunk%s in transit, %u bytes backlogged and has hit a high water mark of %u bytes\n",
9691 res,
9692 (res != 1) ? "s" : "",
9693 tpeer->trunkdatalen,
9694 tpeer->trunkdataalloc);
9695 }
9696 }
9697 totalcalls += res;
9698 res = 0;
9699 ast_mutex_unlock(&tpeer->lock);
9700 }
9703
9704 if (drop) {
9705 ast_mutex_lock(&drop->lock);
9706 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9707 because by the time they could get tpeerlock, we've already grabbed it */
9708 ast_debug(1, "Dropping unused iax2 trunk peer '%s'\n", ast_sockaddr_stringify(&drop->addr));
9709 if (drop->trunkdata) {
9710 ast_free(drop->trunkdata);
9711 drop->trunkdata = NULL;
9712 }
9713 ast_mutex_unlock(&drop->lock);
9714 ast_mutex_destroy(&drop->lock);
9715 ast_free(drop);
9716 }
9717
9718 if (iaxtrunkdebug) {
9719 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9720 }
9721 iaxtrunkdebug = 0;
9722
9723 return 1;
9724}
9725
9732
9733static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9734{
9735 unsigned short dpstatus = 0;
9736 struct iax_ie_data ied1;
9737 int mm;
9738
9739 memset(&ied1, 0, sizeof(ied1));
9740 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9741 /* Must be started */
9742 if (ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9743 dpstatus = IAX_DPSTATUS_EXISTS;
9744 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9745 dpstatus = IAX_DPSTATUS_CANEXIST;
9746 } else {
9747 dpstatus = IAX_DPSTATUS_NONEXISTENT;
9748 }
9749 if (ast_ignore_pattern(context, callednum))
9750 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9751 if (mm)
9752 dpstatus |= IAX_DPSTATUS_MATCHMORE;
9753 if (!skiplock)
9754 ast_mutex_lock(&iaxsl[callno]);
9755 if (iaxs[callno]) {
9756 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9757 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9759 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9760 }
9761 if (!skiplock)
9762 ast_mutex_unlock(&iaxsl[callno]);
9763}
9764
9765static void *dp_lookup_thread(void *data)
9766{
9767 /* Look up for dpreq */
9768 struct dpreq_data *dpr = data;
9769 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9770 if (dpr->callerid)
9771 ast_free(dpr->callerid);
9772 ast_free(dpr);
9773 return NULL;
9774}
9775
9776static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9777{
9778 pthread_t newthread;
9779 struct dpreq_data *dpr;
9780
9781 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9782 return;
9783
9784 dpr->callno = callno;
9785 ast_copy_string(dpr->context, context, sizeof(dpr->context));
9786 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9787 if (callerid)
9789 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9790 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9791 }
9792}
9793
9794static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
9795{
9796 unsigned int ourver;
9797 char rsi[80];
9798 snprintf(rsi, sizeof(rsi), "si-%s", si);
9799 if (iax_provision_version(&ourver, rsi, 1))
9800 return 0;
9801 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9802 if (ourver != ver)
9803 iax2_provision(addr, sockfd, NULL, rsi, 1);
9804 return 0;
9805}
9806
9807static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9808{
9809 jb_info stats;
9810 jb_getinfo(pvt->jb, &stats);
9811
9812 memset(iep, 0, sizeof(*iep));
9813
9815 if(stats.frames_in == 0) stats.frames_in = 1;
9816 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9818 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9821}
9822
9823static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9824{
9825 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9826 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9827 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9828 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9829 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9830 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9831 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9832}
9833
9834static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9835{
9836 int i;
9837 unsigned int length, offset = 0;
9838 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9839
9840 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9841 length = ies->ospblocklength[i];
9842 if (length != 0) {
9843 if (length > IAX_MAX_OSPBLOCK_SIZE) {
9844 /* OSP token block length wrong, clear buffer */
9845 offset = 0;
9846 break;
9847 } else {
9848 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9849 offset += length;
9850 }
9851 } else {
9852 break;
9853 }
9854 }
9855 *(full_osptoken + offset) = '\0';
9856 if (strlen(full_osptoken) != offset) {
9857 /* OSP token length wrong, clear buffer */
9858 *full_osptoken = '\0';
9859 }
9860
9861 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9862}
9863
9864static void log_jitterstats(unsigned short callno)
9865{
9866 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9867 jb_info jbinfo;
9868
9870 if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
9872 jb_getinfo(iaxs[callno]->jb, &jbinfo);
9873 localjitter = jbinfo.jitter;
9874 localdelay = jbinfo.current - jbinfo.min;
9875 locallost = jbinfo.frames_lost;
9876 locallosspct = jbinfo.losspct/1000;
9877 localdropped = jbinfo.frames_dropped;
9878 localooo = jbinfo.frames_ooo;
9879 localpackets = jbinfo.frames_in;
9880 }
9881 ast_debug(3, "JB STATS:%s ping=%u ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
9882 ast_channel_name(iaxs[callno]->owner),
9883 iaxs[callno]->pingtime,
9884 localjitter,
9885 localdelay,
9886 locallost,
9887 locallosspct,
9888 localdropped,
9889 localooo,
9890 localpackets,
9891 iaxs[callno]->remote_rr.jitter,
9898 }
9900}
9901
9902static int socket_process(struct iax2_thread *thread);
9903
9904/*!
9905 * \brief Handle any deferred full frames for this thread
9906 */
9908{
9909 struct iax2_pkt_buf *pkt_buf;
9910
9911 ast_mutex_lock(&thread->lock);
9912
9913 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9914 ast_mutex_unlock(&thread->lock);
9915
9916 thread->buf = pkt_buf->buf;
9917 thread->buf_len = pkt_buf->len;
9918 thread->buf_size = pkt_buf->len + 1;
9919
9921
9922 thread->buf = NULL;
9923 ast_free(pkt_buf);
9924
9925 ast_mutex_lock(&thread->lock);
9926 }
9927
9928 ast_mutex_unlock(&thread->lock);
9929}
9930
9931/*!
9932 * \brief Queue the last read full frame for processing by a certain thread
9933 *
9934 * If there are already any full frames queued, they are sorted
9935 * by sequence number.
9936 */
9937static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9938{
9939 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9940 struct ast_iax2_full_hdr *fh, *cur_fh;
9941
9942 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9943 return;
9944
9945 pkt_buf->len = from_here->buf_len;
9946 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9947
9948 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9949 ast_mutex_lock(&to_here->lock);
9950 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9951 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9952 if (fh->oseqno < cur_fh->oseqno) {
9953 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9954 break;
9955 }
9956 }
9958
9959 if (!cur_pkt_buf)
9960 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9961
9962 to_here->iostate = IAX_IOSTATE_READY;
9963 ast_cond_signal(&to_here->cond);
9964
9965 ast_mutex_unlock(&to_here->lock);
9966}
9967
9968static int socket_read(int *id, int fd, short events, void *cbdata)
9969{
9970 struct iax2_thread *thread;
9971 time_t t;
9972 static time_t last_errtime = 0;
9973 struct ast_iax2_full_hdr *fh;
9974
9975 if (!(thread = find_idle_thread())) {
9976 time(&t);
9977 if (t != last_errtime) {
9978 last_errtime = t;
9979 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9980 }
9981 usleep(1);
9982 return 1;
9983 }
9984
9985 thread->iofd = fd;
9986 thread->buf_len = ast_recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, &thread->ioaddr);
9987 thread->buf_size = sizeof(thread->readbuf);
9988 thread->buf = thread->readbuf;
9989 if (thread->buf_len < 0) {
9990 if (errno != ECONNREFUSED && errno != EAGAIN)
9991 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9992 handle_error();
9993 thread->iostate = IAX_IOSTATE_IDLE;
9994 signal_condition(&thread->lock, &thread->cond);
9995 return 1;
9996 }
9997 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9998 thread->iostate = IAX_IOSTATE_IDLE;
9999 signal_condition(&thread->lock, &thread->cond);
10000 return 1;
10001 }
10002
10003 /* Determine if this frame is a full frame; if so, and any thread is currently
10004 processing a full frame for the same callno from this peer, then drop this
10005 frame (and the peer will retransmit it) */
10006 fh = (struct ast_iax2_full_hdr *) thread->buf;
10007 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
10008 struct iax2_thread *cur = NULL;
10009 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
10010
10013 if ((cur->ffinfo.callno == callno) &&
10014 !ast_sockaddr_cmp_addr(&cur->ffinfo.addr, &thread->ioaddr))
10015 break;
10016 }
10017 if (cur) {
10018 /* we found another thread processing a full frame for this call,
10019 so queue it up for processing later. */
10022 thread->iostate = IAX_IOSTATE_IDLE;
10023 signal_condition(&thread->lock, &thread->cond);
10024 return 1;
10025 } else {
10026 /* this thread is going to process this frame, so mark it */
10027 thread->ffinfo.callno = callno;
10028 ast_sockaddr_copy(&thread->ffinfo.addr, &thread->ioaddr);
10029 thread->ffinfo.type = fh->type;
10030 thread->ffinfo.csub = fh->csub;
10032 }
10034 }
10035
10036 /* Mark as ready and send on its way */
10037 thread->iostate = IAX_IOSTATE_READY;
10038#ifdef DEBUG_SCHED_MULTITHREAD
10039 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
10040#endif
10041 signal_condition(&thread->lock, &thread->cond);
10042
10043 return 1;
10044}
10045
10046static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd,
10047 struct iax_frame *fr)
10048{
10049 unsigned char metatype;
10050 struct ast_iax2_meta_trunk_mini *mtm;
10051 struct ast_iax2_meta_trunk_hdr *mth;
10052 struct ast_iax2_meta_trunk_entry *mte;
10053 struct iax2_trunk_peer *tpeer;
10054 unsigned int ts;
10055 void *ptr;
10056 struct timeval rxtrunktime;
10057 struct ast_frame f = { 0, };
10058
10059 if (packet_len < sizeof(*meta)) {
10060 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a meta frame but is too short\n",
10062 return 1;
10063 }
10064
10065 if (meta->metacmd != IAX_META_TRUNK)
10066 return 1;
10067
10068 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
10069 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
10070 (int) (sizeof(*meta) + sizeof(*mth)));
10071 return 1;
10072 }
10073 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
10074 ts = ntohl(mth->ts);
10075 metatype = meta->cmddata;
10076 packet_len -= (sizeof(*meta) + sizeof(*mth));
10077 ptr = mth->data;
10078 tpeer = find_tpeer(addr, sockfd);
10079 if (!tpeer) {
10080 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s': No matching peer\n",
10082 return 1;
10083 }
10084 tpeer->trunkact = ast_tvnow();
10085 if (!ts || ast_tvzero(tpeer->rxtrunktime))
10086 tpeer->rxtrunktime = tpeer->trunkact;
10087 rxtrunktime = tpeer->rxtrunktime;
10088 ast_mutex_unlock(&tpeer->lock);
10089 while (packet_len >= sizeof(*mte)) {
10090 /* Process channels */
10091 unsigned short callno, trunked_ts, len;
10092
10093 if (metatype == IAX_META_TRUNK_MINI) {
10094 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
10095 ptr += sizeof(*mtm);
10096 packet_len -= sizeof(*mtm);
10097 len = ntohs(mtm->len);
10098 callno = ntohs(mtm->mini.callno);
10099 trunked_ts = ntohs(mtm->mini.ts);
10100 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
10101 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
10102 ptr += sizeof(*mte);
10103 packet_len -= sizeof(*mte);
10104 len = ntohs(mte->len);
10105 callno = ntohs(mte->callno);
10106 trunked_ts = 0;
10107 } else {
10108 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s': dropping\n", ast_sockaddr_stringify(addr));
10109 break;
10110 }
10111 /* Stop if we don't have enough data */
10112 if (len > packet_len)
10113 break;
10114 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, addr, NEW_PREVENT, sockfd, 0);
10115 if (!fr->callno)
10116 continue;
10117
10118 /* If it's a valid call, deliver the contents. If not, we
10119 drop it, since we don't have a scallno to use for an INVAL */
10120 /* Process as a mini frame */
10121 memset(&f, 0, sizeof(f));
10123 if (!iaxs[fr->callno]) {
10124 /* drop it */
10125 } else if (iaxs[fr->callno]->voiceformat == 0) {
10126 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
10127 iax2_vnak(fr->callno);
10129 iaxs[fr->callno]->voiceformat))) {
10130 f.datalen = len;
10131 if (f.datalen >= 0) {
10132 if (f.datalen)
10133 f.data.ptr = ptr;
10134 else
10135 f.data.ptr = NULL;
10136 if (trunked_ts)
10137 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
10138 else
10139 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
10140 /* Don't pass any packets until we're started */
10142 struct iax_frame *duped_fr;
10143
10144 /* Common things */
10145 f.src = "IAX2";
10146 f.mallocd = 0;
10147 f.offset = 0;
10148 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
10150 else
10151 f.samples = 0;
10152 fr->outoforder = 0;
10153 iax_frame_wrap(fr, &f);
10154 duped_fr = iaxfrdup2(fr);
10155 if (duped_fr)
10156 schedule_delivery(duped_fr, 1, 1, &fr->ts);
10157 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
10158 iaxs[fr->callno]->last = fr->ts;
10159 }
10160 } else {
10161 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
10162 }
10163 }
10165 ptr += len;
10166 packet_len -= len;
10167 }
10168
10169 return 1;
10170}
10171
10172static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
10173{
10174 struct ast_datastore *variablestore;
10175 AST_LIST_HEAD(, ast_var_t) *varlist;
10176 struct ast_var_t *var;
10177
10178 if (!chan) {
10179 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10180 return -1;
10181 }
10182
10184 if (!variablestore) {
10185 *buf = '\0';
10186 return 0;
10187 }
10188 varlist = variablestore->data;
10189
10190 AST_LIST_LOCK(varlist);
10191 AST_LIST_TRAVERSE(varlist, var, entries) {
10192 if (strcmp(var->name, data) == 0) {
10193 ast_copy_string(buf, var->value, len);
10194 break;
10195 }
10196 }
10197 AST_LIST_UNLOCK(varlist);
10198 return 0;
10199}
10200
10201static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10202{
10203 struct ast_datastore *variablestore;
10204 AST_LIST_HEAD(, ast_var_t) *varlist;
10205 struct ast_var_t *var;
10206
10207 if (!chan) {
10208 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10209 return -1;
10210 }
10211
10213 if (!variablestore) {
10215 if (!variablestore) {
10216 ast_log(LOG_ERROR, "Memory allocation error\n");
10217 return -1;
10218 }
10219 varlist = ast_calloc(1, sizeof(*varlist));
10220 if (!varlist) {
10221 ast_datastore_free(variablestore);
10222 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10223 return -1;
10224 }
10225
10226 AST_LIST_HEAD_INIT(varlist);
10227 variablestore->data = varlist;
10228 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10229 ast_channel_datastore_add(chan, variablestore);
10230 } else
10231 varlist = variablestore->data;
10232
10233 AST_LIST_LOCK(varlist);
10235 if (strcmp(var->name, data) == 0) {
10238 break;
10239 }
10240 }
10242 var = ast_var_assign(data, value);
10243 if (var)
10244 AST_LIST_INSERT_TAIL(varlist, var, entries);
10245 else
10246 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10247 AST_LIST_UNLOCK(varlist);
10248 return 0;
10249}
10250
10252 .name = "IAXVAR",
10253 .read = acf_iaxvar_read,
10254 .write = acf_iaxvar_write,
10255};
10256
10257static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10258{
10259 iax2_lock_owner(callno);
10260 if (iaxs[callno] && iaxs[callno]->owner) {
10261 struct ast_channel *owner;
10262 const char *name;
10263
10264 owner = iaxs[callno]->owner;
10265 if (causecode) {
10266 ast_channel_hangupcause_set(owner, causecode);
10267 }
10269 ast_channel_ref(owner);
10270 ast_channel_unlock(owner);
10271 ast_mutex_unlock(&iaxsl[callno]);
10272 ast_set_hangupsource(owner, name, 0);
10273 ast_channel_unref(owner);
10274 ast_mutex_lock(&iaxsl[callno]);
10275 }
10276}
10277
10279{
10280 struct ast_sockaddr addr;
10281 int res;
10282 int updatehistory=1;
10283 int new = NEW_PREVENT;
10284 int dcallno = 0;
10285 char decrypted = 0;
10286 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10287 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10288 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10289 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10290 struct iax_frame *fr;
10291 struct iax_frame *cur;
10292 struct ast_frame f = { 0, };
10293 struct ast_channel *c = NULL;
10294 struct iax2_dpcache *dp;
10295 struct iax2_peer *peer;
10296 struct iax_ies ies;
10297 struct iax_ie_data ied0, ied1;
10298 iax2_format format;
10299 int fd;
10300 int exists;
10301 int minivid = 0;
10302 char empty[32]=""; /* Safety measure */
10303 struct iax_frame *duped_fr;
10304 char host_pref_buf[128];
10305 char caller_pref_buf[128];
10306 struct iax2_codec_pref pref;
10307 char *using_prefs = "mine";
10308
10309 /* allocate an iax_frame with 4096 bytes of data buffer */
10310 fr = ast_alloca(sizeof(*fr) + 4096);
10311 memset(fr, 0, sizeof(*fr));
10312 fr->afdatalen = 4096; /* From ast_alloca() above */
10313
10314 /* Copy frequently used parameters to the stack */
10315 res = thread->buf_len;
10316 fd = thread->iofd;
10317 ast_sockaddr_copy(&addr, &thread->ioaddr);
10318
10319 if (res < sizeof(*mh)) {
10320 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10321 return 1;
10322 }
10323 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10324 if (res < sizeof(*vh)) {
10325 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a video frame but is too short\n",
10326 ast_sockaddr_stringify(&addr));
10327 return 1;
10328 }
10329
10330 /* This is a video frame, get call number */
10331 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &addr, new, fd, 0);
10332 minivid = 1;
10333 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10334 return socket_process_meta(res, meta, &addr, fd, fr);
10335
10336#ifdef DEBUG_SUPPORT
10337 if (res >= sizeof(*fh))
10338 iax_outputframe(NULL, fh, 1, &addr, res - sizeof(*fh));
10339#endif
10340 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10341 if (res < sizeof(*fh)) {
10342 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a full frame but is too short\n",
10343 ast_sockaddr_stringify(&addr));
10344 return 1;
10345 }
10346
10347 /* Get the destination call number */
10348 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10349
10350
10351 /* check to make sure this full frame isn't encrypted before we attempt
10352 * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10353 * callno is not found here, that just means one hasn't been allocated for
10354 * this connection yet. */
10355 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, NEW_PREVENT, fd, 1))) {
10357 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10358 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10359 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10361 return 1;
10362 }
10363 decrypted = 1;
10364 }
10366 }
10367
10368 /* Retrieve the type and subclass */
10369 f.frametype = fh->type;
10370 if (f.frametype == AST_FRAME_VIDEO) {
10372 if (!f.subclass.format) {
10373 return 1;
10374 }
10375 if ((fh->csub >> 6) & 0x1) {
10376 f.subclass.frame_ending = 1;
10377 }
10378 } else if (f.frametype == AST_FRAME_VOICE) {
10380 if (!f.subclass.format) {
10381 return 1;
10382 }
10383 } else {
10385 }
10386
10387 /* Deal with POKE/PONG without allocating a callno */
10389 /* Reply back with a PONG, but don't care about the result. */
10390 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10391 return 1;
10392 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10393 /* Ignore */
10394 return 1;
10395 }
10396
10397 f.datalen = res - sizeof(*fh);
10398 if (f.datalen) {
10399 if (f.frametype == AST_FRAME_IAX) {
10400 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10401 char subclass[40];
10402 iax_frame_subclass2str(f.subclass.integer, subclass, sizeof(subclass));
10403 ast_log(LOG_WARNING, "Undecodable %s frame received from '%s'\n", subclass, ast_sockaddr_stringify(&addr));
10405 return 1;
10406 }
10407 f.data.ptr = NULL;
10408 f.datalen = 0;
10409 } else {
10410 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10411 memset(&ies, 0, sizeof(ies));
10412 }
10413 } else {
10414 if (f.frametype == AST_FRAME_IAX)
10415 f.data.ptr = NULL;
10416 else
10417 f.data.ptr = empty;
10418 memset(&ies, 0, sizeof(ies));
10419 }
10420
10421 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10422 /* only set NEW_ALLOW if calltoken checks out */
10423 if (handle_call_token(fh, &ies, &addr, fd)) {
10425 return 1;
10426 }
10427
10428 if (ies.calltoken && ies.calltokendata) {
10429 /* if we've gotten this far, and the calltoken ie data exists,
10430 * then calltoken validation _MUST_ have taken place. If calltoken
10431 * data is provided, it is always validated regardless of any
10432 * calltokenoptional or requirecalltoken options */
10434 } else {
10435 new = NEW_ALLOW;
10436 }
10437 }
10438 } else {
10439 /* Don't know anything about it yet */
10441 f.subclass.integer = 0;
10442 memset(&ies, 0, sizeof(ies));
10443 }
10444
10445 if (!fr->callno) {
10446 int check_dcallno = 0;
10447
10448 /*
10449 * We enforce accurate destination call numbers for ACKs. This forces the other
10450 * end to know the destination call number before call setup can complete.
10451 *
10452 * Discussed in the following thread:
10453 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10454 */
10455
10456 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10457 check_dcallno = 1;
10458 }
10459
10460 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, new, fd, check_dcallno))) {
10461 ast_debug(1, "Received frame without existent call number (%d)\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10463 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10465 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10466 } else {
10467 ast_log(LOG_WARNING, "Silently dropping frame without existent call number: %d\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10468 }
10470 return 1;
10471 }
10472 }
10473
10474 if (fr->callno > 0) {
10475 ast_callid mount_callid;
10477 if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10478 /* Bind to thread */
10479 ast_callid_threadassoc_add(mount_callid);
10480 }
10481 }
10482
10483 if (!fr->callno || !iaxs[fr->callno]) {
10484 /* A call arrived for a nonexistent destination. Unless it's an "inval"
10485 frame, reply with an inval */
10486 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10487 /* We can only raw hangup control frames */
10488 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10492 (f.frametype != AST_FRAME_IAX))
10493 raw_hangup(&addr, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10494 fd);
10495 }
10496 if (fr->callno > 0){
10498 }
10500 return 1;
10501 }
10502 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10503 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10504 ast_log(LOG_WARNING, "Packet Decrypt Failed!\n");
10507 return 1;
10508 }
10509 decrypted = 1;
10510 }
10511
10512#ifdef DEBUG_SUPPORT
10513 if (decrypted) {
10514 iax_outputframe(NULL, fh, 3, &addr, res - sizeof(*fh));
10515 }
10516#endif
10517
10518 if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10519 (fh->csub == IAX_COMMAND_HANGUP
10520 || fh->csub == IAX_COMMAND_REJECT
10521 || fh->csub == IAX_COMMAND_REGREJ
10522 || fh->csub == IAX_COMMAND_TXREJ)) {
10523 struct ast_control_pvt_cause_code *cause_code;
10524 int data_size = sizeof(*cause_code);
10525 char subclass[40] = "";
10526
10527 /* get subclass text */
10528 iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10529
10530 /* add length of "IAX2 " */
10531 data_size += 5;
10532 /* for IAX hangup frames, add length of () and number */
10533 data_size += 3;
10534 if (ies.causecode > 9) {
10535 data_size++;
10536 }
10537 if (ies.causecode > 99) {
10538 data_size++;
10539 }
10540 /* add length of subclass */
10541 data_size += strlen(subclass);
10542
10543 cause_code = ast_alloca(data_size);
10544 memset(cause_code, 0, data_size);
10546
10547 cause_code->ast_cause = ies.causecode;
10548 snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10549
10551 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10552 ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10553 ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10555 }
10556 if (!iaxs[fr->callno]) {
10559 return 1;
10560 }
10561 }
10562
10563 /* count this frame */
10564 iaxs[fr->callno]->frames_received++;
10565
10566 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) && !minivid &&
10567 f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10568 f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10569 unsigned short new_peercallno;
10570
10571 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10572 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10573 if (iaxs[fr->callno]->peercallno) {
10575 }
10576 iaxs[fr->callno]->peercallno = new_peercallno;
10578 }
10579 }
10580 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10581 if (iaxdebug)
10582 ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10583 /* Check if it's out of order (and not an ACK or INVAL) */
10584 fr->oseqno = fh->oseqno;
10585 fr->iseqno = fh->iseqno;
10586 fr->ts = ntohl(fh->ts);
10587#ifdef IAXTESTS
10588 if (test_resync) {
10589 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10590 fr->ts += test_resync;
10591 }
10592#endif /* IAXTESTS */
10593#if 0
10594 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10595 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10596 (f.subclass == IAX_COMMAND_NEW ||
10599 f.subclass == IAX_COMMAND_REJECT)) ) )
10600#endif
10601 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10602 updatehistory = 0;
10603 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10604 (iaxs[fr->callno]->iseqno ||
10606 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10607 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10608 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10610 (f.frametype != AST_FRAME_IAX))) {
10611 if (
10615 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10616 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10617 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10620 (f.frametype != AST_FRAME_IAX)) {
10621 /* If it's not an ACK packet, it's out of order. */
10622 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10623 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10624 /* Check to see if we need to request retransmission,
10625 * and take sequence number wraparound into account */
10626 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10627 /* If we've already seen it, ack it XXX There's a border condition here XXX */
10628 if ((f.frametype != AST_FRAME_IAX) ||
10630 ast_debug(1, "Acking anyway\n");
10631 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10632 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10634 }
10635 } else {
10636 /* Send a VNAK requesting retransmission */
10637 iax2_vnak(fr->callno);
10638 }
10641 return 1;
10642 }
10643 } else {
10644 /* Increment unless it's an ACK or VNAK */
10645 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10650 (f.frametype != AST_FRAME_IAX))
10651 iaxs[fr->callno]->iseqno++;
10652 }
10653 /* Ensure text frames are NULL-terminated */
10654 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10655 if (res < thread->buf_size)
10656 thread->buf[res++] = '\0';
10657 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10658 thread->buf[res - 1] = '\0';
10659 }
10660
10661 /* Handle implicit ACKing unless this is an INVAL, and only if this is
10662 from the real peer, not the transfer peer */
10663 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10665 (f.frametype != AST_FRAME_IAX))) {
10666 unsigned char x;
10667 int call_to_destroy;
10668 /* First we have to qualify that the ACKed value is within our window */
10669 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10670 x = fr->iseqno;
10671 else
10672 x = iaxs[fr->callno]->oseqno;
10673 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10674 /* The acknowledgement is within our window. Time to acknowledge everything
10675 that it says to */
10676 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10677 /* Ack the packet with the given timestamp */
10678 if (iaxdebug)
10679 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10680 call_to_destroy = 0;
10681 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10682 /* If it's our call, and our timestamp, mark -1 retries */
10683 if (x == cur->oseqno) {
10684 cur->retries = -1;
10685 /* Destroy call if this is the end */
10686 if (cur->final)
10687 call_to_destroy = fr->callno;
10688 }
10689 }
10690 if (call_to_destroy) {
10691 if (iaxdebug)
10692 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10693 ast_mutex_lock(&iaxsl[call_to_destroy]);
10694 iax2_destroy(call_to_destroy);
10695 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10696 }
10697 }
10698 /* Note how much we've received acknowledgement for */
10699 if (iaxs[fr->callno])
10700 iaxs[fr->callno]->rseqno = fr->iseqno;
10701 else {
10702 /* Stop processing now */
10705 return 1;
10706 }
10707 } else {
10708 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10709 }
10710 }
10711 if (ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10712 ((f.frametype != AST_FRAME_IAX) ||
10715 /* Only messages we accept from a transfer host are TXACC and TXCNT */
10718 return 1;
10719 }
10720
10721 /* when we receive the first full frame for a new incoming channel,
10722 it is safe to start the PBX on the channel because we have now
10723 completed a 3-way handshake with the peer */
10724 if ((f.frametype == AST_FRAME_VOICE) ||
10725 (f.frametype == AST_FRAME_VIDEO) ||
10726 (f.frametype == AST_FRAME_IAX)) {
10734 return 1;
10735 }
10736 }
10737
10738 if (ies.vars) {
10739 struct ast_datastore *variablestore = NULL;
10740 struct ast_variable *var, *prev = NULL;
10741 AST_LIST_HEAD(, ast_var_t) *varlist;
10742
10744 if (!iaxs[fr->callno]) {
10747 return 1;
10748 }
10749 if ((c = iaxs[fr->callno]->owner)) {
10750 varlist = ast_calloc(1, sizeof(*varlist));
10752
10753 if (variablestore && varlist) {
10754 variablestore->data = varlist;
10755 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10756 AST_LIST_HEAD_INIT(varlist);
10757 ast_debug(1, "I can haz IAX vars?\n");
10758 for (var = ies.vars; var; var = var->next) {
10759 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10760 if (prev) {
10761 ast_free(prev);
10762 }
10763 prev = var;
10764 if (!newvar) {
10765 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10766 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10767 } else {
10768 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10769 }
10770 }
10771 if (prev) {
10772 ast_free(prev);
10773 }
10774 ies.vars = NULL;
10775 ast_channel_datastore_add(c, variablestore);
10776 } else {
10777 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10778 if (variablestore) {
10779 ast_datastore_free(variablestore);
10780 }
10781 if (varlist) {
10782 ast_free(varlist);
10783 }
10784 }
10786 } else {
10787 /* No channel yet, so transfer the variables directly over to the pvt,
10788 * for later inheritance. */
10789 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10790 for (var = ies.vars; var && var->next; var = var->next);
10791 if (var) {
10792 var->next = iaxs[fr->callno]->iaxvars;
10793 iaxs[fr->callno]->iaxvars = ies.vars;
10794 ies.vars = NULL;
10795 }
10796 }
10797 }
10798
10799 if (ies.vars) {
10800 ast_debug(1, "I have IAX variables, but they were not processed\n");
10801 }
10802 }
10803
10804 /* once we receive our first IAX Full Frame that is not CallToken related, send all
10805 * queued signaling frames that were being held. */
10808 }
10809
10810 if (f.frametype == AST_FRAME_VOICE) {
10813 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_format_get_name(f.subclass.format));
10814 if (iaxs[fr->callno]->owner) {
10816 if (iaxs[fr->callno]) {
10817 if (iaxs[fr->callno]->owner) {
10819 if (native) {
10824 }
10825 ao2_ref(native, -1);
10826 }
10828 }
10829 } else {
10830 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10831 /* Free remote variables (if any) */
10832 if (ies.vars) {
10834 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10835 ies.vars = NULL;
10836 }
10838 return 1;
10839 }
10840 }
10841 }
10842 }
10843 if (f.frametype == AST_FRAME_VIDEO) {
10845 ast_debug(1, "Ooh, video format changed to %s\n", ast_format_get_name(f.subclass.format));
10847 }
10848 }
10849 if (f.frametype == AST_FRAME_IAX) {
10851 /* Handle the IAX pseudo frame itself */
10852 if (iaxdebug)
10853 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10854
10855 /* Update last ts unless the frame's timestamp originated with us. */
10856 if (iaxs[fr->callno]->last < fr->ts &&
10860 iaxs[fr->callno]->last = fr->ts;
10861 if (iaxdebug)
10862 ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10863 }
10865 if (!iaxs[fr->callno]->first_iax_message) {
10867 }
10868 switch(f.subclass.integer) {
10869 case IAX_COMMAND_ACK:
10870 /* Do nothing */
10871 break;
10872 case IAX_COMMAND_QUELCH:
10875 if (ies.musiconhold) {
10876 const char *moh_suggest;
10877
10879 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10880 break;
10881 }
10882
10883 /*
10884 * We already hold the owner lock so we do not
10885 * need to check iaxs[fr->callno] after it returns.
10886 */
10887 moh_suggest = iaxs[fr->callno]->mohsuggest;
10888 iax2_queue_hold(fr->callno, moh_suggest);
10890 }
10891 }
10892 break;
10896 if (!iaxs[fr->callno]) {
10897 break;
10898 }
10899
10901 if (!iaxs[fr->callno]->owner) {
10902 break;
10903 }
10904
10905 /*
10906 * We already hold the owner lock so we do not
10907 * need to check iaxs[fr->callno] after it returns.
10908 */
10911 }
10912 break;
10913 case IAX_COMMAND_TXACC:
10914 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10915 /* Ack the packet with the given timestamp */
10916 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10917 /* Cancel any outstanding txcnt's */
10918 if (cur->transfer) {
10919 cur->retries = -1;
10920 }
10921 }
10922 memset(&ied1, 0, sizeof(ied1));
10924 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10926 }
10927 break;
10928 case IAX_COMMAND_NEW:
10929 /* Ignore if it's already up */
10931 break;
10932 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
10934 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
10936 if (!iaxs[fr->callno]) {
10937 break;
10938 }
10939 }
10940 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10941 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10942 int new_callno;
10943 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10944 fr->callno = new_callno;
10945 }
10946 /* For security, always ack immediately */
10947 if (delayreject)
10949 if (check_access(fr->callno, &addr, &ies)) {
10950 /* They're not allowed on */
10952 if (authdebug) {
10953 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n",
10955 }
10956 break;
10957 }
10960 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10961 break;
10962 }
10963 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10964 const char *context, *exten, *cid_num;
10965
10966 context = ast_strdupa(iaxs[fr->callno]->context);
10967 exten = ast_strdupa(iaxs[fr->callno]->exten);
10968 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10969
10970 /* This might re-enter the IAX code and need the lock */
10972 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10974
10975 if (!iaxs[fr->callno]) {
10976 break;
10977 }
10978 } else
10979 exists = 0;
10980 /* Get OSP token if it does exist */
10981 save_osptoken(fr, &ies);
10983 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10984 memset(&ied0, 0, sizeof(ied0));
10985 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10988 if (!iaxs[fr->callno]) {
10989 break;
10990 }
10991 if (authdebug) {
10992 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
10994 }
10995 } else {
10996 /* Select an appropriate format */
10997
11000 using_prefs = "reqonly";
11001 } else {
11002 using_prefs = "disabled";
11003 }
11004 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11005 memset(&pref, 0, sizeof(pref));
11006 strcpy(caller_pref_buf, "disabled");
11007 strcpy(host_pref_buf, "disabled");
11008 } else {
11009 struct ast_format *tmpfmt;
11010 using_prefs = "mine";
11011 /* If the information elements are in here... use them */
11012 if (ies.codec_prefs)
11014 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11015 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
11017 pref = iaxs[fr->callno]->rprefs;
11018 using_prefs = "caller";
11019 } else {
11020 pref = iaxs[fr->callno]->prefs;
11021 }
11022 } else
11023 pref = iaxs[fr->callno]->prefs;
11024
11025 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11026 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11027 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11028 }
11029 if (!format) {
11031 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11032 if (!format) {
11033 memset(&ied0, 0, sizeof(ied0));
11034 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11037 if (!iaxs[fr->callno]) {
11038 break;
11039 }
11040 if (authdebug) {
11043 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11044
11046 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11048 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11050 } else {
11051 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11053 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11056 }
11057 }
11058 } else {
11059 /* Pick one... */
11061 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11062 format = 0;
11063 } else {
11065 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11066 memset(&pref, 0, sizeof(pref));
11068 strcpy(caller_pref_buf,"disabled");
11069 strcpy(host_pref_buf,"disabled");
11070 } else {
11071 struct ast_format *tmpfmt;
11072 using_prefs = "mine";
11073 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11074 /* Do the opposite of what we tried above. */
11076 pref = iaxs[fr->callno]->prefs;
11077 } else {
11078 pref = iaxs[fr->callno]->rprefs;
11079 using_prefs = "caller";
11080 }
11081 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11082 } else /* if no codec_prefs IE do it the old way */
11084 }
11085 }
11086
11087 if (!format) {
11090 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11091
11092 memset(&ied0, 0, sizeof(ied0));
11093 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11095 ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11097 if (!iaxs[fr->callno]) {
11098 break;
11099 }
11100 if (authdebug) {
11101 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11103 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11106 }
11108 break;
11109 }
11110 }
11111 }
11112 if (format) {
11113 /* No authentication required, let them in */
11114 memset(&ied1, 0, sizeof(ied1));
11115 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11117 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11118 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11120 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
11121 "%srequested format = %s,\n"
11122 "%srequested prefs = %s,\n"
11123 "%sactual format = %s,\n"
11124 "%shost prefs = %s,\n"
11125 "%spriority = %s\n",
11130 caller_pref_buf,
11132 iax2_getformatname(format),
11134 host_pref_buf,
11136 using_prefs);
11137
11138 iaxs[fr->callno]->chosenformat = format;
11139
11140 /* Since this is a new call, we should go ahead and set the callid for it. */
11143 } else {
11145 /* If this is a TBD call, we're ready but now what... */
11146 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_sockaddr_stringify(&addr));
11147 }
11148 }
11149 }
11150 break;
11151 }
11154 else
11155 iaxs[fr->callno]->encmethods = 0;
11156 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
11158 break;
11159 case IAX_COMMAND_DPREQ:
11160 /* Request status in the dialplan */
11163 if (iaxcompat) {
11164 /* Spawn a thread for the lookup */
11166 } else {
11167 /* Just look it up */
11168 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
11169 }
11170 }
11171 break;
11172 case IAX_COMMAND_HANGUP:
11174 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
11175 /* Set hangup cause according to remote and hangupsource */
11176 if (iaxs[fr->callno]->owner) {
11178 if (!iaxs[fr->callno]) {
11179 break;
11180 }
11181 }
11182
11183 /* Send ack immediately, before we destroy */
11185 iax2_destroy(fr->callno);
11186 break;
11187 case IAX_COMMAND_REJECT:
11188 /* Set hangup cause according to remote and hangup source */
11189 if (iaxs[fr->callno]->owner) {
11191 if (!iaxs[fr->callno]) {
11192 break;
11193 }
11194 }
11195
11197 if (iaxs[fr->callno]->owner && authdebug)
11198 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
11200 ies.cause ? ies.cause : "<Unknown>");
11201 ast_debug(1, "Immediately destroying %d, having received reject\n",
11202 fr->callno);
11203 }
11204 /* Send ack immediately, before we destroy */
11206 fr->ts, NULL, 0, fr->iseqno);
11208 iaxs[fr->callno]->error = EPERM;
11209 iax2_destroy(fr->callno);
11210 break;
11212 {
11214 if (!iaxs[fr->callno]) {
11215 /* Initiating call went away before we could transfer. */
11216 break;
11217 }
11218 if (iaxs[fr->callno]->owner) {
11219 struct ast_channel *owner = iaxs[fr->callno]->owner;
11220 char *context = ast_strdupa(iaxs[fr->callno]->context);
11221
11222 ast_channel_ref(owner);
11223 ast_channel_unlock(owner);
11225
11226 if (ast_bridge_transfer_blind(1, owner, ies.called_number,
11228 ast_log(LOG_WARNING, "Blind transfer of '%s' to '%s@%s' failed\n",
11229 ast_channel_name(owner), ies.called_number,
11230 context);
11231 }
11232
11233 ast_channel_unref(owner);
11235 }
11236
11237 break;
11238 }
11239 case IAX_COMMAND_ACCEPT:
11240 /* Ignore if call is already up or needs authentication or is a TBD */
11242 break;
11244 /* Send ack immediately, before we destroy */
11246 iax2_destroy(fr->callno);
11247 break;
11248 }
11249 if (ies.format) {
11250 iaxs[fr->callno]->peerformat = ies.format;
11251 } else {
11252 if (iaxs[fr->callno]->owner)
11254 else
11256 }
11257 ast_verb(3, "Call accepted by %s (format %s)\n", ast_sockaddr_stringify(&addr),
11259 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11260 memset(&ied0, 0, sizeof(ied0));
11261 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11264 if (!iaxs[fr->callno]) {
11265 break;
11266 }
11267 if (authdebug) {
11270
11271 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11275 }
11276 } else {
11278
11281 if (iaxs[fr->callno] && iaxs[fr->callno]->owner && native) {
11283
11284 /* Switch us to use a compatible format */
11286 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11287 native);
11289 ast_verb(3, "Format for call is %s\n", ast_format_cap_get_names(ast_channel_nativeformats(iaxs[fr->callno]->owner), &cap_buf));
11290
11291 /* Setup read/write formats properly. */
11297 }
11298
11299 ao2_cleanup(native);
11300 }
11301 if (iaxs[fr->callno]) {
11303 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11304 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11305 iax2_dprequest(dp, fr->callno);
11307 }
11308 break;
11309 case IAX_COMMAND_POKE:
11310 /* Send back a pong packet with the original timestamp */
11312 break;
11313 case IAX_COMMAND_PING:
11314 {
11315 struct iax_ie_data pingied;
11316 construct_rr(iaxs[fr->callno], &pingied);
11317 /* Send back a pong packet with the original timestamp */
11318 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11319 }
11320 break;
11321 case IAX_COMMAND_PONG:
11322 /* Calculate ping time */
11323 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11324 /* save RR info */
11325 save_rr(fr, &ies);
11326
11327 /* Good time to write jb stats for this call */
11329
11330 if (iaxs[fr->callno]->peerpoke) {
11331 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
11332 peer = iaxs[fr->callno]->peerpoke;
11333 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11334 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11335 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11337 blob = ast_json_pack("{s: s, s: I}",
11338 "peer_status", "Reachable",
11339 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11340 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11341 }
11342 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11343 if (iaxs[fr->callno]->pingtime > peer->maxms) {
11344 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11346 blob = ast_json_pack("{s: s, s: I}",
11347 "peer_status", "Lagged",
11348 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11349 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11350 }
11351 }
11353 peer->lastms = iaxs[fr->callno]->pingtime;
11354 if (peer->smoothing && (peer->lastms > -1))
11355 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11356 else if (peer->smoothing && peer->lastms < 0)
11357 peer->historicms = (0 + peer->historicms) / 2;
11358 else
11359 peer->historicms = iaxs[fr->callno]->pingtime;
11360
11361 /* Remove scheduled iax2_poke_noanswer */
11362 if (peer->pokeexpire > -1) {
11363 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11364 peer_unref(peer);
11365 peer->pokeexpire = -1;
11366 }
11367 }
11368 /* Schedule the next cycle */
11369 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11371 else
11373 if (peer->pokeexpire == -1)
11374 peer_unref(peer);
11375 /* and finally send the ack */
11377 /* And wrap up the qualify call */
11378 iax2_destroy(fr->callno);
11379 peer->callno = 0;
11380 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11381 }
11382 break;
11383 case IAX_COMMAND_LAGRQ:
11384 case IAX_COMMAND_LAGRP:
11385 f.src = "LAGRQ";
11386 f.mallocd = 0;
11387 f.offset = 0;
11388 f.samples = 0;
11389 iax_frame_wrap(fr, &f);
11391 /* Received a LAGRQ - echo back a LAGRP */
11393 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11394 } else {
11395 /* Received LAGRP in response to our LAGRQ */
11396 unsigned int ts;
11397 /* This is a reply we've been given, actually measure the difference */
11398 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11399 iaxs[fr->callno]->lag = ts - fr->ts;
11400 if (iaxdebug)
11401 ast_debug(1, "Peer %s lag measured as %dms\n",
11402 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->lag);
11403 }
11404 break;
11407 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11408 break;
11409 }
11410 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11411 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11412 .subclass.integer = AST_CONTROL_HANGUP,
11413 };
11415 "I don't know how to authenticate %s to %s\n",
11416 ies.username ? ies.username : "<unknown>", ast_sockaddr_stringify(&addr));
11417 iax2_queue_frame(fr->callno, &hangup_fr);
11418 }
11419 break;
11421 /* For security, always ack immediately */
11422 if (delayreject)
11424 /* Ignore once we've started */
11426 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11427 break;
11428 }
11429 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11430 if (authdebug)
11431 ast_log(LOG_WARNING, "Host %s failed to authenticate as %s\n", ast_sockaddr_stringify(&addr),
11432 iaxs[fr->callno]->username);
11433 memset(&ied0, 0, sizeof(ied0));
11435 break;
11436 }
11437 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11438 /* This might re-enter the IAX code and need the lock */
11440 } else
11441 exists = 0;
11442 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11443 if (authdebug)
11444 ast_log(LOG_WARNING, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
11446 iaxs[fr->callno]->exten,
11447 iaxs[fr->callno]->context);
11448 memset(&ied0, 0, sizeof(ied0));
11449 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11452 if (!iaxs[fr->callno]) {
11453 break;
11454 }
11455 } else {
11456 /* Select an appropriate format */
11459 using_prefs = "reqonly";
11460 } else {
11461 using_prefs = "disabled";
11462 }
11463 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11464 memset(&pref, 0, sizeof(pref));
11465 strcpy(caller_pref_buf, "disabled");
11466 strcpy(host_pref_buf, "disabled");
11467 } else {
11468 struct ast_format *tmpfmt;
11469 using_prefs = "mine";
11470 if (ies.codec_prefs)
11472 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11474 pref = iaxs[fr->callno]->rprefs;
11475 using_prefs = "caller";
11476 } else {
11477 pref = iaxs[fr->callno]->prefs;
11478 }
11479 } else /* if no codec_prefs IE do it the old way */
11480 pref = iaxs[fr->callno]->prefs;
11481 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11482 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11483 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11484 }
11485 if (!format) {
11488 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11489
11491 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11494 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11495 }
11496 if (!format) {
11497 if (authdebug) {
11499 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11501 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11503 } else {
11504 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11506 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11509 }
11510 }
11511 memset(&ied0, 0, sizeof(ied0));
11512 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11515 if (!iaxs[fr->callno]) {
11516 break;
11517 }
11518 } else {
11519 /* Pick one... */
11521 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11522 format = 0;
11523 } else {
11525 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11526 memset(&pref, 0, sizeof(pref));
11528 ? iaxs[fr->callno]->peerformat
11530 strcpy(caller_pref_buf,"disabled");
11531 strcpy(host_pref_buf,"disabled");
11532 } else {
11533 struct ast_format *tmpfmt;
11534 using_prefs = "mine";
11535 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11536 /* Do the opposite of what we tried above. */
11538 pref = iaxs[fr->callno]->prefs;
11539 } else {
11540 pref = iaxs[fr->callno]->rprefs;
11541 using_prefs = "caller";
11542 }
11543 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11544 } else /* if no codec_prefs IE do it the old way */
11546 }
11547 }
11548 if (!format) {
11551 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11552
11553 ast_log(LOG_ERROR, "No best format in %s???\n",
11555 if (authdebug) {
11557 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11559 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11561 } else {
11562 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11564 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11567 }
11568 }
11569 memset(&ied0, 0, sizeof(ied0));
11570 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11573 if (!iaxs[fr->callno]) {
11574 break;
11575 }
11576 }
11577 }
11578 }
11579 if (format) {
11580 /* Authentication received */
11581 memset(&ied1, 0, sizeof(ied1));
11582 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11584 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11585 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11586 char authmethodnames[AUTH_METHOD_NAMES_BUFSIZE];
11588 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11589 "%srequested auth methods = (%s),\n"
11590 "%sactual auth method = %s,\n"
11591 "%sencrypted = %s,\n"
11592 "%srequested format = %s,\n"
11593 "%srequested prefs = %s,\n"
11594 "%sactual format = %s,\n"
11595 "%shost prefs = %s,\n"
11596 "%spriority = %s\n",
11599 auth_method_names(iaxs[fr->callno]->authmethods, authmethodnames),
11603 IAX_CALLENCRYPTED(iaxs[fr->callno]) ? "yes" : "no",
11607 caller_pref_buf,
11609 iax2_getformatname(format),
11611 host_pref_buf,
11613 using_prefs);
11614
11615 /* Unlike unauthenticated calls, we don't need to store
11616 * the chosen format for channel creation.
11617 * However, this is helpful for __get_from_jb. */
11618 iaxs[fr->callno]->chosenformat = format;
11619
11621 c = ast_iax2_new(fr->callno, AST_STATE_RING, format,
11622 &iaxs[fr->callno]->rprefs, NULL, NULL, 1);
11623 if (!c) {
11624 iax2_destroy(fr->callno);
11625 } else if (ies.vars) {
11626 struct ast_datastore *variablestore;
11627 struct ast_variable *var, *prev = NULL;
11628 AST_LIST_HEAD(, ast_var_t) *varlist;
11629 varlist = ast_calloc(1, sizeof(*varlist));
11631 if (variablestore && varlist) {
11632 variablestore->data = varlist;
11633 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11634 AST_LIST_HEAD_INIT(varlist);
11635 ast_debug(1, "I can haz IAX vars? w00t\n");
11636 for (var = ies.vars; var; var = var->next) {
11637 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11638 if (prev)
11639 ast_free(prev);
11640 prev = var;
11641 if (!newvar) {
11642 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11643 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11644 } else {
11645 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11646 }
11647 }
11648 if (prev)
11649 ast_free(prev);
11650 ies.vars = NULL;
11651 ast_channel_datastore_add(c, variablestore);
11652 } else {
11653 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11654 if (variablestore)
11655 ast_datastore_free(variablestore);
11656 if (varlist)
11657 ast_free(varlist);
11658 }
11659 }
11660 } else {
11662 /* If this is a TBD call, we're ready but now what... */
11663 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_sockaddr_stringify(&addr));
11665 goto immediatedial;
11666 }
11667 }
11668 }
11669 }
11670 break;
11671 case IAX_COMMAND_DIAL:
11672immediatedial:
11675 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11676 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11677 if (authdebug)
11678 ast_log(LOG_WARNING, "Rejected dial attempt from %s, request '%s@%s' does not exist\n",
11680 iaxs[fr->callno]->exten,
11681 iaxs[fr->callno]->context);
11682 memset(&ied0, 0, sizeof(ied0));
11683 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11686 if (!iaxs[fr->callno]) {
11687 break;
11688 }
11689 } else {
11692 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11698 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11699 NULL, NULL, 1);
11700 if (!c) {
11701 iax2_destroy(fr->callno);
11702 } else if (ies.vars) {
11703 struct ast_datastore *variablestore;
11704 struct ast_variable *var, *prev = NULL;
11705 AST_LIST_HEAD(, ast_var_t) *varlist;
11706 varlist = ast_calloc(1, sizeof(*varlist));
11708 ast_debug(1, "I can haz IAX vars? w00t\n");
11709 if (variablestore && varlist) {
11710 variablestore->data = varlist;
11711 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11712 AST_LIST_HEAD_INIT(varlist);
11713 for (var = ies.vars; var; var = var->next) {
11714 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11715 if (prev)
11716 ast_free(prev);
11717 prev = var;
11718 if (!newvar) {
11719 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11720 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11721 } else {
11722 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11723 }
11724 }
11725 if (prev)
11726 ast_free(prev);
11727 ies.vars = NULL;
11728 ast_channel_datastore_add(c, variablestore);
11729 } else {
11730 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11731 if (variablestore)
11732 ast_datastore_free(variablestore);
11733 if (varlist)
11734 ast_free(varlist);
11735 }
11736 }
11737 }
11738 }
11739 break;
11740 case IAX_COMMAND_INVAL:
11741 iaxs[fr->callno]->error = ENOTCONN;
11742 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11743 iax2_destroy(fr->callno);
11744 ast_debug(1, "Destroying call %d\n", fr->callno);
11745 break;
11746 case IAX_COMMAND_VNAK:
11747 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11748 /* Force retransmission */
11749 vnak_retransmit(fr->callno, fr->iseqno);
11750 break;
11751 case IAX_COMMAND_REGREQ:
11752 case IAX_COMMAND_REGREL:
11753 /* For security, always ack immediately */
11754 if (delayreject)
11756 if (register_verify(fr->callno, &addr, &ies)) {
11757 if (!iaxs[fr->callno]) {
11758 break;
11759 }
11760 /* Send delayed failure */
11762 break;
11763 }
11764 if (!iaxs[fr->callno]) {
11765 break;
11766 }
11769
11771 ast_sockaddr_setnull(&addr);
11772 }
11773 if (update_registry(&addr, fr->callno, ies.devicetype, fd, ies.refresh)) {
11774 ast_log(LOG_WARNING, "Registry error\n");
11775 }
11776 if (!iaxs[fr->callno]) {
11777 break;
11778 }
11779 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
11781 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
11783 }
11784 break;
11785 }
11787 break;
11788 case IAX_COMMAND_REGACK:
11789 if (iax2_ack_registry(&ies, &addr, fr->callno)) {
11790 ast_log(LOG_WARNING, "Registration failure\n");
11791 }
11792 /* Send ack immediately, before we destroy */
11794 iax2_destroy(fr->callno);
11795 break;
11796 case IAX_COMMAND_REGREJ:
11797 if (iaxs[fr->callno]->reg) {
11798 if (authdebug) {
11799 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n",
11800 iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>",
11801 ast_sockaddr_stringify(&addr));
11802 }
11803 iax2_publish_registry(iaxs[fr->callno]->reg->username, ast_sockaddr_stringify(&addr), "Rejected", S_OR(ies.cause, "<unknown>"));
11805 }
11806 /* Send ack immediately, before we destroy */
11808 iax2_destroy(fr->callno);
11809 break;
11811 /* Authentication request */
11812 if (registry_rerequest(&ies, fr->callno, &addr)) {
11813 memset(&ied0, 0, sizeof(ied0));
11814 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11817 }
11818 break;
11819 case IAX_COMMAND_TXREJ:
11820 while (iaxs[fr->callno]
11821 && iaxs[fr->callno]->bridgecallno
11824 }
11825 if (!iaxs[fr->callno]) {
11826 break;
11827 }
11828
11830 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11831 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11832
11833 if (!iaxs[fr->callno]->bridgecallno) {
11834 break;
11835 }
11836
11837 if (iaxs[iaxs[fr->callno]->bridgecallno]
11841 }
11843 break;
11845 while (iaxs[fr->callno]
11846 && iaxs[fr->callno]->bridgecallno
11849 }
11850 if (!iaxs[fr->callno]) {
11851 break;
11852 }
11853
11854 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11856 } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11858 } else {
11859 if (iaxs[fr->callno]->bridgecallno) {
11861 }
11862 break;
11863 }
11864 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11865
11866 if (!iaxs[fr->callno]->bridgecallno) {
11867 break;
11868 }
11869
11870 if (!iaxs[iaxs[fr->callno]->bridgecallno]
11874 break;
11875 }
11876
11877 /* Both sides are ready */
11878
11879 /* XXX what isn't checked here is that both sides match transfer types. */
11880
11881 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11882 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11884
11887
11888 memset(&ied0, 0, sizeof(ied0));
11889 memset(&ied1, 0, sizeof(ied1));
11892 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11894 } else {
11895 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11897
11902
11903 /* Stop doing lag & ping requests */
11904 stop_stuff(fr->callno);
11906
11907 memset(&ied0, 0, sizeof(ied0));
11908 memset(&ied1, 0, sizeof(ied1));
11911 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11913 }
11915 break;
11916 case IAX_COMMAND_TXREQ:
11917 try_transfer(iaxs[fr->callno], &ies);
11918 break;
11919 case IAX_COMMAND_TXCNT:
11920 if (iaxs[fr->callno]->transferring)
11922 break;
11923 case IAX_COMMAND_TXREL:
11924 /* Send ack immediately, rather than waiting until we've changed addresses */
11926 complete_transfer(fr->callno, &ies);
11927 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11928 break;
11930 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11931 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11932 /* Cancel any outstanding frames and start anew */
11933 if (cur->transfer) {
11934 cur->retries = -1;
11935 }
11936 }
11937 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11939 }
11940 break;
11941 case IAX_COMMAND_RTKEY:
11942 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11944 "we've been told to rotate our encryption key, "
11945 "but this isn't an encrypted call. bad things will happen.\n"
11946 );
11947 break;
11948 }
11949
11950 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11951
11952 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11953 break;
11954 case IAX_COMMAND_DPREP:
11955 complete_dpreply(iaxs[fr->callno], &ies);
11956 break;
11958 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11959 break;
11961 /* Firmware download */
11964 break;
11965 }
11966 memset(&ied0, 0, sizeof(ied0));
11967 res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
11968 if (res < 0)
11970 else if (res > 0)
11972 else
11973 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11974 break;
11976 {
11977 struct iax_frame *cur;
11978 /* find last sent frame */
11979 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11980 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11981 }
11982 break;
11983 }
11984 default:
11985 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11986 memset(&ied0, 0, sizeof(ied0));
11989 }
11990 /* Free remote variables (if any) */
11991 if (ies.vars) {
11993 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11994 ies.vars = NULL;
11995 }
11996
11997 /* Don't actually pass these frames along */
11998 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
12003 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
12005 }
12006 }
12008 return 1;
12009 }
12010 /* Unless this is an ACK or INVAL frame, ack it */
12011 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
12013 } else if (minivid) {
12015 if (iaxs[fr->callno]->videoformat > 0) {
12016 if (ntohs(vh->ts) & 0x8000LL) {
12017 f.subclass.frame_ending = 1;
12018 }
12020 if (!f.subclass.format) {
12023 return 1;
12024 }
12025 } else {
12026 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
12027 iax2_vnak(fr->callno);
12030 return 1;
12031 }
12032 f.datalen = res - sizeof(*vh);
12033 if (f.datalen < 0) {
12034 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12037 return 1;
12038 }
12039 if (f.datalen)
12040 f.data.ptr = thread->buf + sizeof(*vh);
12041 else
12042 f.data.ptr = NULL;
12043#ifdef IAXTESTS
12044 if (test_resync) {
12045 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
12046 } else
12047#endif /* IAXTESTS */
12048 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
12049 } else {
12050 /* A mini frame */
12052 if (iaxs[fr->callno]->voiceformat > 0) {
12054 if (!f.subclass.format) {
12057 return 1;
12058 }
12059 } else {
12060 ast_debug(1, "Received mini frame before first full voice frame\n");
12061 iax2_vnak(fr->callno);
12064 return 1;
12065 }
12066 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
12067 if (f.datalen < 0) {
12068 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12071 return 1;
12072 }
12073 if (f.datalen)
12074 f.data.ptr = thread->buf + sizeof(*mh);
12075 else
12076 f.data.ptr = NULL;
12077#ifdef IAXTESTS
12078 if (test_resync) {
12079 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
12080 } else
12081#endif /* IAXTESTS */
12082 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
12083 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
12084 }
12085
12086 /* Don't pass any packets until we're started */
12087 if (!iaxs[fr->callno]
12091 return 1;
12092 }
12093
12094 if (f.frametype == AST_FRAME_CONTROL) {
12096 /* Control frame not allowed to come from the wire. */
12097 ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
12098 fr->callno, f.subclass.integer);
12101 return 1;
12102 }
12105 if (iaxs[fr->callno]
12107 /* We are not configured to allow receiving these updates. */
12108 ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
12109 fr->callno, f.subclass.integer);
12112 return 1;
12113 }
12114 }
12115
12117 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12120 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
12122 }
12124 }
12125 }
12126
12129 && iaxs[fr->callno]) {
12131
12132 /*
12133 * Process a received connected line update.
12134 *
12135 * Initialize defaults.
12136 */
12138 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
12139 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
12140
12142 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
12143 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
12145
12147 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12149 S_COR(connected.id.number.valid, connected.id.number.str, ""),
12150 S_COR(connected.id.name.valid, connected.id.name.str, ""),
12151 NULL);
12152 ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
12153 ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
12155 }
12156 }
12158 }
12159
12160 /* Common things */
12161 f.src = "IAX2";
12162 f.mallocd = 0;
12163 f.offset = 0;
12164 f.len = 0;
12165 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
12167 /* We need to byteswap incoming slinear samples from network byte order */
12170 } else
12171 f.samples = 0;
12172
12173 if (f.datalen < 0) {
12174 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12177 return 1;
12178 }
12179
12180 iax_frame_wrap(fr, &f);
12181
12182 /* If this is our most recent packet, use it as our basis for timestamping */
12183 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12184 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
12185 fr->outoforder = 0;
12186 } else {
12187 if (iaxdebug && iaxs[fr->callno]) {
12188 ast_debug(1, "Received out of order packet... (type=%u, subclass %d, ts = %u, last = %u)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
12189 }
12190 fr->outoforder = 1;
12191 }
12193 if (iaxs[fr->callno]) {
12194 duped_fr = iaxfrdup2(fr);
12195 if (duped_fr) {
12196 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
12197 }
12198 }
12199 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12200 iaxs[fr->callno]->last = fr->ts;
12201#if 1
12202 if (iaxdebug)
12203 ast_debug(8, "For call=%d, set last=%u\n", fr->callno, fr->ts);
12204#endif
12205 }
12206
12207 /* Always run again */
12210 return 1;
12211}
12212
12214{
12215 int res = socket_process_helper(thread);
12218 }
12219 return res;
12220}
12221
12222/* Function to clean up process thread if it is cancelled */
12223static void iax2_process_thread_cleanup(void *data)
12224{
12225 struct iax2_thread *thread = data;
12226 ast_mutex_destroy(&thread->lock);
12227 ast_cond_destroy(&thread->cond);
12228 ast_mutex_destroy(&thread->init_lock);
12229 ast_cond_destroy(&thread->init_cond);
12231 /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
12233}
12234
12235static void *iax2_process_thread(void *data)
12236{
12237 struct iax2_thread *thread = data;
12238 struct timeval wait;
12239 struct timespec ts;
12240 int put_into_idle = 0;
12241 int first_time = 1;
12242 int old_state;
12243
12245
12246 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12247 pthread_cleanup_push(iax2_process_thread_cleanup, data);
12248
12249 for (;;) {
12250 /* Wait for something to signal us to be awake */
12251 ast_mutex_lock(&thread->lock);
12252
12253 if (thread->stop) {
12254 ast_mutex_unlock(&thread->lock);
12255 break;
12256 }
12257
12258 /* Flag that we're ready to accept signals */
12259 if (first_time) {
12260 signal_condition(&thread->init_lock, &thread->init_cond);
12261 first_time = 0;
12262 }
12263
12264 /* Put into idle list if applicable */
12265 if (put_into_idle) {
12267 }
12268
12269 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12270 struct iax2_thread *t = NULL;
12271 /* Wait to be signalled or time out */
12272 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12273 ts.tv_sec = wait.tv_sec;
12274 ts.tv_nsec = wait.tv_usec * 1000;
12275 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12276 /* This thread was never put back into the available dynamic
12277 * thread list, so just go away. */
12278 if (!put_into_idle || thread->stop) {
12279 ast_mutex_unlock(&thread->lock);
12280 break;
12281 }
12283 /* Account for the case where this thread is acquired *right* after a timeout */
12287 if (t) {
12288 /* This dynamic thread timed out waiting for a task and was
12289 * not acquired immediately after the timeout,
12290 * so it's time to go away. */
12291 ast_mutex_unlock(&thread->lock);
12292 break;
12293 }
12294 /* Someone grabbed our thread *right* after we timed out.
12295 * Wait for them to set us up with something to do and signal
12296 * us to continue. */
12297 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12298 ts.tv_sec = wait.tv_sec;
12299 ts.tv_nsec = wait.tv_usec * 1000;
12300 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12301 ast_mutex_unlock(&thread->lock);
12302 break;
12303 }
12304 }
12305 } else {
12306 ast_cond_wait(&thread->cond, &thread->lock);
12307 }
12308
12309 /* Go back into our respective list */
12310 put_into_idle = 1;
12311
12312 ast_mutex_unlock(&thread->lock);
12313
12314 if (thread->stop) {
12315 break;
12316 }
12317
12318 /* See what we need to do */
12319 switch (thread->iostate) {
12320 case IAX_IOSTATE_IDLE:
12321 continue;
12322 case IAX_IOSTATE_READY:
12323 thread->actions++;
12324 thread->iostate = IAX_IOSTATE_PROCESSING;
12327 break;
12329 thread->actions++;
12330 thread->iostate = IAX_IOSTATE_PROCESSING;
12331#ifdef SCHED_MULTITHREADED
12332 thread->schedfunc(thread->scheddata);
12333#endif
12334 break;
12335 default:
12336 break;
12337 }
12338
12339 /* The network thread added us to the active_thread list when we were given
12340 * frames to process, Now that we are done, we must remove ourselves from
12341 * the active list, and return to the idle list */
12345
12346 /* Make sure another frame didn't sneak in there after we thought we were done. */
12348
12349 time(&thread->checktime);
12350 thread->iostate = IAX_IOSTATE_IDLE;
12351#ifdef DEBUG_SCHED_MULTITHREAD
12352 thread->curfunc[0]='\0';
12353#endif
12354 }
12355
12356 /*!
12357 * \note For some reason, idle threads are exiting without being
12358 * removed from an idle list, which is causing memory
12359 * corruption. Forcibly remove it from the list, if it's there.
12360 */
12364
12368
12369 if (!thread->stop) {
12370 /* Nobody asked me to stop so nobody is waiting to join me. */
12371 pthread_detach(pthread_self());
12372 }
12373
12374 /* I am exiting here on my own volition, I need to clean up my own data structures
12375 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12376 */
12377 pthread_cleanup_pop(1);
12378 return NULL;
12379}
12380
12381static int iax2_do_register(struct iax2_registry *reg)
12382{
12383 struct iax_ie_data ied;
12384 if (iaxdebug)
12385 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12386
12387 if (reg->dnsmgr &&
12388 ((reg->regstate == REG_STATE_TIMEOUT) || ast_sockaddr_isnull(&reg->addr))) {
12389 /* Maybe the IP has changed, force DNS refresh */
12391 }
12392
12393 /*
12394 * if IP has Changed, free allocated call to create a new one with new IP
12395 * call has the pointer to IP and must be updated to the new one
12396 */
12397 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12398 int callno = reg->callno;
12399 ast_mutex_lock(&iaxsl[callno]);
12400 iax2_destroy(callno);
12401 ast_mutex_unlock(&iaxsl[callno]);
12402 reg->callno = 0;
12403 }
12404 if (ast_sockaddr_isnull(&reg->addr)) {
12405 if (iaxdebug)
12406 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12407 /* Setup the next registration attempt */
12409 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12410 return -1;
12411 }
12412 if (!ast_sockaddr_port(&reg->addr) && reg->port) {
12413 ast_sockaddr_set_port(&reg->addr, reg->port);
12414 }
12415
12416 if (!reg->callno) {
12417
12418 ast_debug(3, "Allocate call number\n");
12419
12420 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
12421 if (reg->callno < 1) {
12422 ast_log(LOG_WARNING, "Unable to create call for registration\n");
12423 return -1;
12424 } else
12425 ast_debug(3, "Registration created on call %d\n", reg->callno);
12426 iaxs[reg->callno]->reg = reg;
12428 }
12429 /* Setup the next registration a little early */
12431 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12432 /* Send the request */
12433 memset(&ied, 0, sizeof(ied));
12436 add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12439 return 0;
12440}
12441
12442static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
12443{
12444 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12445 is found for template */
12446 struct iax_ie_data provdata;
12447 struct iax_ie_data ied;
12448 unsigned int sig;
12449 struct ast_sockaddr addr;
12450 int callno;
12451 struct create_addr_info cai;
12452
12453 memset(&cai, 0, sizeof(cai));
12454
12455 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12456
12457 if (iax_provision_build(&provdata, &sig, template, force)) {
12458 ast_debug(1, "No provisioning found for template '%s'\n", template);
12459 return 0;
12460 }
12461
12462 if (end) {
12463 ast_sockaddr_copy(&addr, end);
12464 cai.sockfd = sockfd;
12465 } else if (create_addr(dest, NULL, &addr, &cai))
12466 return -1;
12467
12468 /* Build the rest of the message */
12469 memset(&ied, 0, sizeof(ied));
12470 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12471
12472 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12473 if (!callno)
12474 return -1;
12475
12476 if (iaxs[callno]) {
12477 /* Schedule autodestruct in case they don't ever give us anything back */
12478 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12479 sched, 15000, auto_hangup, (void *)(long)callno);
12481 /* Got a call number now, so go ahead and send the provisioning information */
12482 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12483 }
12484 ast_mutex_unlock(&iaxsl[callno]);
12485
12486 return 1;
12487}
12488
12489static char *papp = "IAX2Provision";
12490
12491/*! iax2provision
12492\ingroup applications
12493*/
12494static int iax2_prov_app(struct ast_channel *chan, const char *data)
12495{
12496 int res;
12497 char *sdata;
12498 char *opts;
12499 int force =0;
12500 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12501 if (ast_strlen_zero(data))
12502 data = "default";
12503 sdata = ast_strdupa(data);
12504 opts = strchr(sdata, '|');
12505 if (opts)
12506 *opts='\0';
12507
12508 if (ast_channel_tech(chan) != &iax2_tech) {
12509 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12510 return -1;
12511 }
12512 if (!callno || !iaxs[callno] || ast_sockaddr_isnull(&iaxs[callno]->addr)) {
12513 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12514 return -1;
12515 }
12516 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12517 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12518 ast_sockaddr_stringify(&iaxs[callno]->addr),
12519 sdata, res);
12520 return res;
12521}
12522
12523static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12524{
12525 int force = 0;
12526 int res;
12527
12528 switch (cmd) {
12529 case CLI_INIT:
12530 e->command = "iax2 provision";
12531 e->usage =
12532 "Usage: iax2 provision <host> <template> [forced]\n"
12533 " Provisions the given peer or IP address using a template\n"
12534 " matching either 'template' or '*' if the template is not\n"
12535 " found. If 'forced' is specified, even empty provisioning\n"
12536 " fields will be provisioned as empty fields.\n";
12537 return NULL;
12538 case CLI_GENERATE:
12539 if (a->pos == 3)
12540 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12541 return NULL;
12542 }
12543
12544 if (a->argc < 4)
12545 return CLI_SHOWUSAGE;
12546 if (a->argc > 4) {
12547 if (!strcasecmp(a->argv[4], "forced"))
12548 force = 1;
12549 else
12550 return CLI_SHOWUSAGE;
12551 }
12552 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12553 if (res < 0)
12554 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12555 else if (res < 1)
12556 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12557 else
12558 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12559 return CLI_SUCCESS;
12560}
12561
12562static void __iax2_poke_noanswer(const void *data)
12563{
12564 struct iax2_peer *peer = (struct iax2_peer *)data;
12565 int callno;
12566
12567 if (peer->lastms > -1) {
12568 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12569
12570 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12572 blob = ast_json_pack("{s: s, s: i}",
12573 "peer_status", "Unreachable",
12574 "time", peer->lastms);
12576 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12577 }
12578 if ((callno = peer->callno) > 0) {
12582 }
12583 peer->callno = 0;
12584 peer->lastms = -1;
12585 /* Try again quickly */
12587 if (peer->pokeexpire == -1)
12588 peer_unref(peer);
12589}
12590
12591static int iax2_poke_noanswer(const void *data)
12592{
12593 struct iax2_peer *peer = (struct iax2_peer *)data;
12594 peer->pokeexpire = -1;
12595#ifdef SCHED_MULTITHREADED
12597#endif
12599 peer_unref(peer);
12600 return 0;
12601}
12602
12603static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12604{
12605 struct iax2_peer *peer = obj;
12606
12607 iax2_poke_peer(peer, 0);
12608
12609 return 0;
12610}
12611
12612static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12613{
12614 int callno;
12615 int poke_timeout;
12616
12617 if (!peer->maxms || (ast_sockaddr_isnull(&peer->addr) && !peer->dnsmgr)) {
12618 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12619 immediately after clearing things out */
12620 peer->lastms = 0;
12621 peer->historicms = 0;
12622 peer->pokeexpire = -1;
12623 peer->callno = 0;
12624 return 0;
12625 }
12626
12627 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12628 if ((callno = peer->callno) > 0) {
12629 ast_log(LOG_NOTICE, "Still have a callno...\n");
12633 }
12634 if (heldcall)
12635 ast_mutex_unlock(&iaxsl[heldcall]);
12636 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
12637 if (heldcall)
12638 ast_mutex_lock(&iaxsl[heldcall]);
12639 if (callno < 1) {
12640 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12641 return -1;
12642 }
12643
12644 if (peer->pokeexpire > -1) {
12645 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12646 peer->pokeexpire = -1;
12647 peer_unref(peer);
12648 }
12649 }
12650
12651 if (peer->lastms < 0){
12652 /* If the host is already unreachable then use time less than the unreachable
12653 * interval. 5/6 is arbitrary multiplier to get value less than
12654 * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
12655 * current POKE before starting new POKE (which is scheduled after
12656 * peer->pokefreqnotok). */
12657 poke_timeout = peer->pokefreqnotok * 5 / 6;
12658 } else {
12659 /* If the host is reachable, use timeout large enough to allow for multiple
12660 * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
12661 * multiplier to get value less than peer->pokefreqok. Value less than
12662 * peer->pokefreqok is used to expire current POKE before starting new POKE
12663 * (which is scheduled after peer->pokefreqok). */
12664 poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
12665 }
12666
12667 /* Queue up a new task to handle no reply */
12668 peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
12669
12670 if (peer->pokeexpire == -1)
12671 peer_unref(peer);
12672
12673 /* And send the poke */
12675 if (iaxs[callno]) {
12676 struct iax_ie_data ied = {
12677 .buf = { 0 },
12678 .pos = 0,
12679 };
12680
12681 /* Speed up retransmission times for this qualify call */
12682 iaxs[callno]->pingtime = peer->maxms / 8;
12683 iaxs[callno]->peerpoke = peer;
12684
12685 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12686 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12687 }
12688 ast_mutex_unlock(&iaxsl[callno]);
12689
12690 return 0;
12691}
12692
12693static void free_context(struct iax2_context *con)
12694{
12695 struct iax2_context *conl;
12696 while(con) {
12697 conl = con;
12698 con = con->next;
12699 ast_free(conl);
12700 }
12701}
12702
12703static 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)
12704{
12705 int callno;
12706 int res;
12707 struct ast_sockaddr addr;
12708 struct ast_channel *c;
12709 struct parsed_dial_string pds;
12710 struct create_addr_info cai;
12711 char *tmpstr;
12712 ast_callid callid;
12713
12714 memset(&pds, 0, sizeof(pds));
12715 tmpstr = ast_strdupa(data);
12716 parse_dial_string(tmpstr, &pds);
12717
12719
12720 if (ast_strlen_zero(pds.peer)) {
12721 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12722 return NULL;
12723 }
12724 memset(&cai, 0, sizeof(cai));
12726
12728
12729 /* Populate our address from the given */
12730 if (create_addr(pds.peer, NULL, &addr, &cai)) {
12731 *cause = AST_CAUSE_UNREGISTERED;
12732 return NULL;
12733 }
12734
12735 if (pds.port) {
12736 int bindport;
12737 ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535);
12738 ast_sockaddr_set_port(&addr, bindport);
12739 }
12740
12741 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12742 if (callno < 1) {
12743 ast_log(LOG_WARNING, "Unable to create call\n");
12744 *cause = AST_CAUSE_CONGESTION;
12745 return NULL;
12746 }
12747
12748 /* If this is a trunk, update it now */
12750 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12751 int new_callno;
12752 if ((new_callno = make_trunk(callno, 1)) != -1)
12753 callno = new_callno;
12754 }
12755 iaxs[callno]->maxtime = cai.maxtime;
12756 if (callid) {
12757 iax_pvt_callid_set(callno, callid);
12758 }
12759
12760 if (cai.found) {
12761 ast_string_field_set(iaxs[callno], host, pds.peer);
12762 }
12763
12764 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, &cai.prefs, assignedids,
12765 requestor, cai.found);
12766
12767 ast_mutex_unlock(&iaxsl[callno]);
12768
12769 if (c) {
12770 struct ast_format_cap *joint;
12771 struct ast_format *format;
12772 if (callid) {
12774 ast_channel_callid_set(c, callid);
12776 }
12777
12779 if (!joint) {
12780 ast_hangup(c);
12781 return NULL;
12782 }
12783
12785
12786 /* If there is no joint format find one through translation */
12787 if (!ast_format_cap_count(joint)) {
12788 struct ast_format *best_fmt_cap = NULL;
12789 struct ast_format *best_fmt_native = NULL;
12790
12791 res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12792 if (res < 0) {
12793 struct ast_str *native_cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12795
12796 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12798 ast_format_cap_get_names(cap, &cap_buf),
12800 ast_hangup(c);
12801 ao2_ref(joint, -1);
12802 return NULL;
12803 }
12804 ast_format_cap_append(joint, best_fmt_native, 0);
12805 ao2_ref(best_fmt_cap, -1);
12806 ao2_ref(best_fmt_native, -1);
12807 }
12812
12813 ao2_ref(joint, -1);
12814 ao2_ref(format, -1);
12815 }
12816
12817 return c;
12818}
12819
12820static void *network_thread(void *ignore)
12821{
12822 int res;
12823
12824 if (timer) {
12826 }
12827
12828 for (;;) {
12829 pthread_testcancel();
12830 /* Wake up once a second just in case SIGURG was sent while
12831 * we weren't in poll(), to make sure we don't hang when trying
12832 * to unload. */
12833 res = ast_io_wait(io, 1000);
12834 /* Timeout(=0), and EINTR is not a thread exit condition. We do
12835 * not want to exit the thread loop on these conditions. */
12836 if (res < 0 && errno != -EINTR) {
12837 ast_log(LOG_ERROR, "IAX2 network thread unexpected exit: %s\n", strerror(errno));
12838 break;
12839 }
12840 }
12841
12842 return NULL;
12843}
12844
12845static int start_network_thread(void)
12846{
12847 struct iax2_thread *thread;
12848 int threadcount = 0;
12849 int x;
12850 for (x = 0; x < iaxthreadcount; x++) {
12851 thread = ast_calloc(1, sizeof(*thread));
12852 if (thread) {
12854 thread->threadnum = ++threadcount;
12855 ast_mutex_init(&thread->lock);
12856 ast_cond_init(&thread->cond, NULL);
12857 ast_mutex_init(&thread->init_lock);
12858 ast_cond_init(&thread->init_cond, NULL);
12859
12860 ast_mutex_lock(&thread->init_lock);
12861
12863 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12864 ast_mutex_destroy(&thread->lock);
12865 ast_cond_destroy(&thread->cond);
12866 ast_mutex_unlock(&thread->init_lock);
12867 ast_mutex_destroy(&thread->init_lock);
12868 ast_cond_destroy(&thread->init_cond);
12870 thread = NULL;
12871 continue;
12872 }
12873 /* Wait for the thread to be ready */
12874 ast_cond_wait(&thread->init_cond, &thread->init_lock);
12875
12876 /* Done with init_lock */
12877 ast_mutex_unlock(&thread->init_lock);
12878
12882 }
12883 }
12885 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12886 return -1;
12887 }
12888 ast_verb(2, "%d helper threads started\n", threadcount);
12889 return 0;
12890}
12891
12892static struct iax2_context *build_context(const char *context)
12893{
12894 struct iax2_context *con;
12895
12896 if ((con = ast_calloc(1, sizeof(*con))))
12897 ast_copy_string(con->context, context, sizeof(con->context));
12898
12899 return con;
12900}
12901
12902static int get_auth_methods(const char *value)
12903{
12904 int methods = 0;
12905 if (strstr(value, "rsa"))
12907 if (strstr(value, "md5"))
12909 if (strstr(value, "plaintext"))
12911 return methods;
12912}
12913
12914
12915/*! \brief Check if address can be used as packet source.
12916 \retval 0 address available
12917 \retval 1 address unavailable
12918 \retval -1 error
12919*/
12920static int check_srcaddr(struct ast_sockaddr *addr)
12921{
12922 int sd;
12923
12924 sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12925 if (sd < 0) {
12926 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12927 return -1;
12928 }
12929
12930 if (ast_bind(sd, addr) < 0) {
12931 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12932 close(sd);
12933 return 1;
12934 }
12935
12936 close(sd);
12937 return 0;
12938}
12939
12940/*! \brief Parse the "sourceaddress" value,
12941 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12942 not found. */
12943static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12944{
12945 struct ast_sockaddr addr;
12946 int nonlocal = 1;
12947 int port = IAX_DEFAULT_PORTNO;
12948 int sockfd = defaultsockfd;
12949 char *tmp;
12950 char *host;
12951 char *portstr;
12952
12953 tmp = ast_strdupa(srcaddr);
12954 ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12955
12956 if (portstr) {
12957 port = atoi(portstr);
12958 if (port < 1)
12959 port = IAX_DEFAULT_PORTNO;
12960 }
12961
12962 addr.ss.ss_family = AST_AF_UNSPEC;
12963 if (!ast_get_ip(&addr, host)) {
12964 struct ast_netsock *sock;
12965
12966 if (check_srcaddr(&addr) == 0) {
12967 /* ip address valid. */
12968 ast_sockaddr_set_port(&addr, port);
12969
12970 if (!(sock = ast_netsock_find(netsock, &addr)))
12971 sock = ast_netsock_find(outsock, &addr);
12972 if (sock) {
12973 sockfd = ast_netsock_sockfd(sock);
12974 nonlocal = 0;
12975 } else {
12976 /* INADDR_ANY matches anyway! */
12977 ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12978 ast_sockaddr_set_port(&addr, port);
12979 if (ast_netsock_find(netsock, &addr)) {
12980 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12981 if (sock) {
12982 sockfd = ast_netsock_sockfd(sock);
12983 ast_netsock_unref(sock);
12984 nonlocal = 0;
12985 } else {
12986 nonlocal = 2;
12987 }
12988 }
12989 }
12990 }
12991 }
12992
12993 peer->sockfd = sockfd;
12994
12995 if (nonlocal == 1) {
12997 "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12998 srcaddr,
12999 peer->name);
13000 return -1;
13001 } else if (nonlocal == 2) {
13003 "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
13004 srcaddr,
13005 peer->name);
13006 return -1;
13007 } else {
13008 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
13009 return 0;
13010 }
13011}
13012
13013static void peer_destructor(void *obj)
13014{
13015 struct iax2_peer *peer = obj;
13016 int callno = peer->callno;
13017
13018 ast_free_acl_list(peer->acl);
13019
13020 if (callno > 0) {
13024 }
13025
13026 register_peer_exten(peer, 0);
13027
13028 if (peer->dnsmgr)
13030
13031 if (peer->mwi_event_sub) {
13033 }
13034
13036
13038}
13039
13040/*! \brief Create peer structure based on configuration */
13041static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13042{
13043 struct iax2_peer *peer = NULL;
13044 struct ast_acl_list *oldacl = NULL;
13045 int maskfound = 0;
13046 int found = 0;
13047 int firstpass = 1;
13048 int subscribe_acl_change = 0;
13049
13050 if (!temponly) {
13051 peer = ao2_find(peers, name, OBJ_KEY);
13052 if (peer && !ast_test_flag64(peer, IAX_DELME))
13053 firstpass = 0;
13054 }
13055
13056 if (peer) {
13057 found++;
13058 if (firstpass) {
13059 oldacl = peer->acl;
13060 peer->acl = NULL;
13061 }
13062 unlink_peer(peer);
13063 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
13064 peer->expire = -1;
13065 peer->pokeexpire = -1;
13066 peer->sockfd = defaultsockfd;
13067 if (ast_string_field_init(peer, 32))
13068 peer = peer_unref(peer);
13069 if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
13070 peer = peer_unref(peer);
13071 }
13072 }
13073
13074 if (peer) {
13075 if (firstpass) {
13079 peer->adsi = adsi;
13080 ast_string_field_set(peer, secret, "");
13081 if (!found) {
13083 ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
13085 peer->expiry = min_reg_expire;
13086 }
13087 peer->prefs = prefs_global;
13089 peer->smoothing = 0;
13092 peer->maxcallno = 0;
13093 peercnt_modify((unsigned char) 0, 0, &peer->addr);
13095 ast_string_field_set(peer,context,"");
13096 ast_string_field_set(peer,peercontext,"");
13098 ast_string_field_set(peer, cid_name, "");
13099 ast_string_field_set(peer, cid_num, "");
13102 }
13103
13104 if (!v) {
13105 v = alt;
13106 alt = NULL;
13107 }
13108 while(v) {
13109 if (!strcasecmp(v->name, "secret")) {
13110 ast_string_field_set(peer, secret, v->value);
13111 } else if (!strcasecmp(v->name, "mailbox")) {
13112 ast_string_field_set(peer, mailbox, v->value);
13113 } else if (!strcasecmp(v->name, "mohinterpret")) {
13115 } else if (!strcasecmp(v->name, "mohsuggest")) {
13117 } else if (!strcasecmp(v->name, "dbsecret")) {
13118 ast_string_field_set(peer, dbsecret, v->value);
13119 } else if (!strcasecmp(v->name, "description")) {
13120 ast_string_field_set(peer, description, v->value);
13121 } else if (!strcasecmp(v->name, "trunk")) {
13123 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
13124 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
13126 }
13127 } else if (!strcasecmp(v->name, "auth")) {
13129 if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
13130 ast_log(LOG_WARNING, "Auth method for peer '%s' is set to deprecated 'plaintext' at line %d of iax.conf\n", peer->name, v->lineno);
13131 }
13132 } else if (!strcasecmp(v->name, "encryption")) {
13134 if (!peer->encmethods) {
13136 }
13137 } else if (!strcasecmp(v->name, "forceencryption")) {
13138 if (ast_false(v->value)) {
13140 } else {
13142 if (peer->encmethods) {
13144 }
13145 }
13146 } else if (!strcasecmp(v->name, "transfer")) {
13147 if (!strcasecmp(v->value, "mediaonly")) {
13149 } else if (ast_true(v->value)) {
13151 } else
13153 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13155 } else if (!strcasecmp(v->name, "host")) {
13156 if (!strcasecmp(v->value, "dynamic")) {
13157 /* They'll register with us */
13159 if (!found) {
13160 int peer_port = ast_sockaddr_port(&peer->addr);
13161 if (peer_port) {
13162 ast_sockaddr_set_port(&peer->defaddr, peer_port);
13163 }
13164 ast_sockaddr_setnull(&peer->addr);
13165 }
13166 } else {
13167 /* Non-dynamic. Make sure we become that way if we're not */
13168 AST_SCHED_DEL(sched, peer->expire);
13170 if (peer->dnsmgr) {
13171 // Make sure we refresh dnsmgr if we're using it
13173 } else {
13174 // Or just invalidate the address
13175 peer->addr.ss.ss_family = AST_AF_UNSPEC;
13176 }
13177 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
13178 return peer_unref(peer);
13179 }
13180 if (!ast_sockaddr_port(&peer->addr)) {
13182 }
13183 }
13184 } else if (!strcasecmp(v->name, "defaultip")) {
13185 struct ast_sockaddr peer_defaddr_tmp;
13186 peer_defaddr_tmp.ss.ss_family = AF_UNSPEC;
13187 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
13188 return peer_unref(peer);
13189 }
13190 ast_sockaddr_set_port(&peer_defaddr_tmp, ast_sockaddr_port(&peer->defaddr));
13191 ast_sockaddr_copy(&peer->defaddr, &peer_defaddr_tmp);
13192 } else if (!strcasecmp(v->name, "sourceaddress")) {
13193 peer_set_srcaddr(peer, v->value);
13194 } else if (!strcasecmp(v->name, "permit") ||
13195 !strcasecmp(v->name, "deny") ||
13196 !strcasecmp(v->name, "acl")) {
13197 ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
13198 } else if (!strcasecmp(v->name, "mask")) {
13199 maskfound++;
13200 ast_sockaddr_parse(&peer->mask, v->value, 0);
13201 } else if (!strcasecmp(v->name, "context")) {
13202 ast_string_field_set(peer, context, v->value);
13203 } else if (!strcasecmp(v->name, "regexten")) {
13204 ast_string_field_set(peer, regexten, v->value);
13205 } else if (!strcasecmp(v->name, "peercontext")) {
13206 ast_string_field_set(peer, peercontext, v->value);
13207 } else if (!strcasecmp(v->name, "port")) {
13208 int bindport;
13209 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
13210 bindport = IAX_DEFAULT_PORTNO;
13211 }
13212 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
13213 ast_sockaddr_set_port(&peer->defaddr, bindport);
13214 } else {
13215 ast_sockaddr_set_port(&peer->addr, bindport);
13216 }
13217 } else if (!strcasecmp(v->name, "username")) {
13218 ast_string_field_set(peer, username, v->value);
13219 } else if (!strcasecmp(v->name, "allow")) {
13220 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
13221 } else if (!strcasecmp(v->name, "disallow")) {
13222 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
13223 } else if (!strcasecmp(v->name, "callerid")) {
13224 if (!ast_strlen_zero(v->value)) {
13225 char name2[80];
13226 char num2[80];
13227 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13228 ast_string_field_set(peer, cid_name, name2);
13229 ast_string_field_set(peer, cid_num, num2);
13230 } else {
13231 ast_string_field_set(peer, cid_name, "");
13232 ast_string_field_set(peer, cid_num, "");
13233 }
13235 } else if (!strcasecmp(v->name, "fullname")) {
13236 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
13238 } else if (!strcasecmp(v->name, "cid_number")) {
13239 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
13241 } else if (!strcasecmp(v->name, "sendani")) {
13243 } else if (!strcasecmp(v->name, "inkeys")) {
13244 ast_string_field_set(peer, inkeys, v->value);
13245 } else if (!strcasecmp(v->name, "outkey")) {
13246 ast_string_field_set(peer, outkey, v->value);
13247 } else if (!strcasecmp(v->name, "qualify")) {
13248 if (!strcasecmp(v->value, "no")) {
13249 peer->maxms = 0;
13250 } else if (!strcasecmp(v->value, "yes")) {
13251 peer->maxms = DEFAULT_MAXMS;
13252 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
13253 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13254 peer->maxms = 0;
13255 }
13256 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
13257 peer->smoothing = ast_true(v->value);
13258 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
13259 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
13260 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13261 }
13262 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
13263 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
13264 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
13265 }
13266 } else if (!strcasecmp(v->name, "timezone")) {
13268 } else if (!strcasecmp(v->name, "adsi")) {
13269 peer->adsi = ast_true(v->value);
13270 } else if (!strcasecmp(v->name, "connectedline")) {
13271 if (ast_true(v->value)) {
13273 } else if (!strcasecmp(v->value, "send")) {
13276 } else if (!strcasecmp(v->value, "receive")) {
13279 } else {
13281 }
13282 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13283 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13284 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13285 } else {
13286 peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13287 }
13288 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13289 /* default is required unless in optional ip list */
13290 if (ast_false(v->value)) {
13292 } else if (!strcasecmp(v->value, "auto")) {
13294 } else if (ast_true(v->value)) {
13296 } else {
13297 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13298 }
13299 } /* else if (strcasecmp(v->name,"type")) */
13300 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13301 v = v->next;
13302 if (!v) {
13303 v = alt;
13304 alt = NULL;
13305 }
13306 }
13307 if (!peer->authmethods)
13308 peer->authmethods = IAX_AUTH_MD5;
13310 }
13311
13312 if (!maskfound && !ast_sockaddr_isnull(&peer->addr)) {
13313 if (ast_sockaddr_is_ipv4_mapped(&peer->addr)) {
13314 ast_sockaddr_parse(&peer->mask, "::ffff:ffff:ffff", 0);
13315 } else if (ast_sockaddr_is_ipv6(&peer->addr)) {
13316 ast_sockaddr_parse(&peer->mask, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0);
13317 } else {
13318 ast_sockaddr_parse(&peer->mask, "255.255.255.255", 0);
13319 }
13320 }
13321
13322 if (oldacl) {
13323 ast_free_acl_list(oldacl);
13324 }
13325
13326 if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
13327 /* The MWI subscriptions exist just so the core knows we care about those
13328 * mailboxes. However, we just grab the events out of the cache when it
13329 * is time to send MWI, since it is only sent with a REGACK. */
13331 }
13332
13333 if (subscribe_acl_change) {
13335 }
13336
13337 return peer;
13338}
13339
13340static void user_destructor(void *obj)
13341{
13342 struct iax2_user *user = obj;
13343
13344 ast_free_acl_list(user->acl);
13345 free_context(user->contexts);
13346 if(user->vars) {
13348 user->vars = NULL;
13349 }
13351}
13352
13353/*! \brief Create in-memory user structure from configuration */
13354static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13355{
13356 struct iax2_user *user = NULL;
13357 struct iax2_context *con, *conl = NULL;
13358 struct ast_acl_list *oldacl = NULL;
13359 struct iax2_context *oldcon = NULL;
13360 int format;
13361 int firstpass=1;
13362 int oldcurauthreq = 0;
13363 int subscribe_acl_change = 0;
13364 char *varname = NULL, *varval = NULL;
13365 struct ast_variable *tmpvar = NULL;
13366
13367 if (!temponly) {
13370 firstpass = 0;
13371 }
13372
13373 if (user) {
13374 if (firstpass) {
13375 oldcurauthreq = user->curauthreq;
13376 oldacl = user->acl;
13377 oldcon = user->contexts;
13378 user->acl = NULL;
13379 user->contexts = NULL;
13380 }
13381 /* Already in the list, remove it and it will be added back (or FREE'd) */
13383 } else {
13384 user = ao2_alloc(sizeof(*user), user_destructor);
13385 }
13386
13387 if (user) {
13388 if (firstpass) {
13390 memset(user, 0, sizeof(struct iax2_user));
13391 if (ast_string_field_init(user, 32)) {
13392 user = user_unref(user);
13393 goto cleanup;
13394 }
13395 user->maxauthreq = maxauthreq;
13396 user->curauthreq = oldcurauthreq;
13397 user->prefs = prefs_global;
13398 user->capability = iax2_capability;
13399 user->encmethods = iax2_encryption;
13400 user->authmethods = iax2_authmethods;
13401 user->adsi = adsi;
13402 user->calltoken_required = CALLTOKEN_DEFAULT;
13407 ast_string_field_set(user, cid_name, "");
13408 ast_string_field_set(user, cid_num, "");
13412 }
13413 if (!v) {
13414 v = alt;
13415 alt = NULL;
13416 }
13417 while(v) {
13418 if (!strcasecmp(v->name, "context")) {
13419 con = build_context(v->value);
13420 if (con) {
13421 if (conl)
13422 conl->next = con;
13423 else
13424 user->contexts = con;
13425 conl = con;
13426 }
13427 } else if (!strcasecmp(v->name, "permit") ||
13428 !strcasecmp(v->name, "deny") ||
13429 !strcasecmp(v->name, "acl")) {
13430 ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13431 } else if (!strcasecmp(v->name, "setvar")) {
13432 varname = ast_strdupa(v->value);
13433 if ((varval = strchr(varname, '='))) {
13434 *varval = '\0';
13435 varval++;
13436 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
13437 if (ast_variable_list_replace(&user->vars, tmpvar)) {
13438 tmpvar->next = user->vars;
13439 user->vars = tmpvar;
13440 }
13441 }
13442 }
13443 } else if (!strcasecmp(v->name, "allow")) {
13444 iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13445 } else if (!strcasecmp(v->name, "disallow")) {
13446 iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13447 } else if (!strcasecmp(v->name, "trunk")) {
13449 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13450 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13452 }
13453 } else if (!strcasecmp(v->name, "auth")) {
13454 user->authmethods = get_auth_methods(v->value);
13455 if (user->authmethods & IAX_AUTH_PLAINTEXT) {
13456 ast_log(LOG_WARNING, "Auth method for user '%s' is set to deprecated 'plaintext' at line %d of iax.conf\n", user->name, v->lineno);
13457 }
13458 } else if (!strcasecmp(v->name, "encryption")) {
13459 user->encmethods |= get_encrypt_methods(v->value);
13460 if (!user->encmethods) {
13462 }
13463 } else if (!strcasecmp(v->name, "forceencryption")) {
13464 if (ast_false(v->value)) {
13466 } else {
13467 user->encmethods |= get_encrypt_methods(v->value);
13468 if (user->encmethods) {
13470 }
13471 }
13472 } else if (!strcasecmp(v->name, "transfer")) {
13473 if (!strcasecmp(v->value, "mediaonly")) {
13475 } else if (ast_true(v->value)) {
13477 } else
13479 } else if (!strcasecmp(v->name, "codecpriority")) {
13480 if(!strcasecmp(v->value, "caller"))
13482 else if(!strcasecmp(v->value, "disabled"))
13484 else if(!strcasecmp(v->value, "reqonly")) {
13487 }
13488 } else if (!strcasecmp(v->name, "immediate")) {
13490 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13492 } else if (!strcasecmp(v->name, "dbsecret")) {
13493 ast_string_field_set(user, dbsecret, v->value);
13494 } else if (!strcasecmp(v->name, "secret")) {
13495 if (!ast_strlen_zero(user->secret)) {
13496 char *old = ast_strdupa(user->secret);
13497
13498 ast_string_field_build(user, secret, "%s;%s", old, v->value);
13499 } else
13500 ast_string_field_set(user, secret, v->value);
13501 } else if (!strcasecmp(v->name, "callerid")) {
13502 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13503 char name2[80];
13504 char num2[80];
13505 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13506 ast_string_field_set(user, cid_name, name2);
13507 ast_string_field_set(user, cid_num, num2);
13509 } else {
13511 ast_string_field_set(user, cid_name, "");
13512 ast_string_field_set(user, cid_num, "");
13513 }
13514 } else if (!strcasecmp(v->name, "fullname")) {
13515 if (!ast_strlen_zero(v->value)) {
13516 ast_string_field_set(user, cid_name, v->value);
13518 } else {
13519 ast_string_field_set(user, cid_name, "");
13520 if (ast_strlen_zero(user->cid_num))
13522 }
13523 } else if (!strcasecmp(v->name, "cid_number")) {
13524 if (!ast_strlen_zero(v->value)) {
13525 ast_string_field_set(user, cid_num, v->value);
13527 } else {
13528 ast_string_field_set(user, cid_num, "");
13529 if (ast_strlen_zero(user->cid_name))
13531 }
13532 } else if (!strcasecmp(v->name, "accountcode")) {
13534 } else if (!strcasecmp(v->name, "mohinterpret")) {
13536 } else if (!strcasecmp(v->name, "mohsuggest")) {
13538 } else if (!strcasecmp(v->name, "parkinglot")) {
13539 ast_string_field_set(user, parkinglot, v->value);
13540 } else if (!strcasecmp(v->name, "language")) {
13542 } else if (!strcasecmp(v->name, "amaflags")) {
13543 format = ast_channel_string2amaflag(v->value);
13544 if (format < 0) {
13545 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13546 } else {
13547 user->amaflags = format;
13548 }
13549 } else if (!strcasecmp(v->name, "inkeys")) {
13550 ast_string_field_set(user, inkeys, v->value);
13551 } else if (!strcasecmp(v->name, "maxauthreq")) {
13552 user->maxauthreq = atoi(v->value);
13553 if (user->maxauthreq < 0)
13554 user->maxauthreq = 0;
13555 } else if (!strcasecmp(v->name, "adsi")) {
13556 user->adsi = ast_true(v->value);
13557 } else if (!strcasecmp(v->name, "connectedline")) {
13558 if (ast_true(v->value)) {
13560 } else if (!strcasecmp(v->value, "send")) {
13563 } else if (!strcasecmp(v->value, "receive")) {
13566 } else {
13568 }
13569 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13570 /* default is required unless in optional ip list */
13571 if (ast_false(v->value)) {
13572 user->calltoken_required = CALLTOKEN_NO;
13573 } else if (!strcasecmp(v->value, "auto")) {
13574 user->calltoken_required = CALLTOKEN_AUTO;
13575 } else if (ast_true(v->value)) {
13576 user->calltoken_required = CALLTOKEN_YES;
13577 } else {
13578 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13579 }
13580 } /* else if (strcasecmp(v->name,"type")) */
13581 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13582 v = v->next;
13583 if (!v) {
13584 v = alt;
13585 alt = NULL;
13586 }
13587 }
13588 if (!user->authmethods) {
13589 if (!ast_strlen_zero(user->secret)) {
13590 user->authmethods = IAX_AUTH_MD5;
13591 if (!ast_strlen_zero(user->inkeys))
13592 user->authmethods |= IAX_AUTH_RSA;
13593 } else if (!ast_strlen_zero(user->inkeys)) {
13594 user->authmethods = IAX_AUTH_RSA;
13595 } else {
13596 user->authmethods = IAX_AUTH_MD5;
13597 }
13598 }
13600 }
13601cleanup:
13602 if (oldacl) {
13603 ast_free_acl_list(oldacl);
13604 }
13605 if (oldcon) {
13606 free_context(oldcon);
13607 }
13608
13609 if (subscribe_acl_change) {
13611 }
13612
13613 return user;
13614}
13615
13616static int peer_delme_cb(void *obj, void *arg, int flags)
13617{
13618 struct iax2_peer *peer = obj;
13619
13621
13622 return 0;
13623}
13624
13625static int user_delme_cb(void *obj, void *arg, int flags)
13626{
13627 struct iax2_user *user = obj;
13628
13630
13631 return 0;
13632}
13633
13634static void delete_users(void)
13635{
13636 struct iax2_registry *reg;
13637
13639
13641 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13642 if (sched) {
13643 AST_SCHED_DEL(sched, reg->expire);
13644 }
13645 if (reg->callno) {
13646 int callno = reg->callno;
13648 if (iaxs[callno]) {
13649 iaxs[callno]->reg = NULL;
13651 }
13653 }
13654 if (reg->dnsmgr)
13656 ast_free(reg);
13657 }
13659
13661}
13662
13663static void prune_users(void)
13664{
13665 struct iax2_user *user;
13666 struct ao2_iterator i;
13667
13668 i = ao2_iterator_init(users, 0);
13669 while ((user = ao2_iterator_next(&i))) {
13672 }
13674 }
13676}
13677
13678/* Prune peers who still are supposed to be deleted */
13679static void prune_peers(void)
13680{
13681 struct iax2_peer *peer;
13682 struct ao2_iterator i;
13683
13684 i = ao2_iterator_init(peers, 0);
13685 while ((peer = ao2_iterator_next(&i))) {
13687 unlink_peer(peer);
13688 }
13689 peer_unref(peer);
13690 }
13692}
13693
13709
13710/*! \brief Load configuration */
13711static int set_config(const char *config_file, int reload, int forced)
13712{
13713 struct ast_config *cfg;
13714 iax2_format capability;
13715 struct ast_variable *v;
13716 char *cat;
13717 const char *utype;
13718 const char *tosval;
13719 int format;
13720 int portno = IAX_DEFAULT_PORTNO;
13721 int x;
13722 int mtuv;
13723 int subscribe_network_change = 1;
13724 struct iax2_user *user;
13725 struct iax2_peer *peer;
13726 struct ast_netsock *ns;
13727 struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13728 struct ast_sockaddr bindaddr;
13729 struct iax2_codec_pref prefs_new;
13730
13731 cfg = ast_config_load(config_file, config_flags);
13732
13733 if (!cfg) {
13734 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13735 return -1;
13736 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13738 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13739 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13740 return 0;
13741 }
13742 if (!cfg) {
13743 /* should have been able to load the config here */
13744 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13745 return -1;
13746 }
13747 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13748 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13749 return 0;
13750 } else { /* iax.conf changed */
13752 }
13753
13754 if (reload) {
13756 }
13757
13758 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
13759
13760 /* Setup new codec prefs */
13762
13763 /* Reset Global Flags */
13764 memset(&globalflags, 0, sizeof(globalflags));
13767
13768#ifdef SO_NO_CHECK
13769 nochecksums = 0;
13770#endif
13771 /* Reset default parking lot */
13772 default_parkinglot[0] = '\0';
13773
13779
13780 maxauthreq = 3;
13781
13782 srvlookup = 0;
13783 iax2_authmethods = 0;
13784
13785 v = ast_variable_browse(cfg, "general");
13786
13787 /* Seed initial tos value */
13788 tosval = ast_variable_retrieve(cfg, "general", "tos");
13789 if (tosval) {
13790 if (ast_str2tos(tosval, &qos.tos))
13791 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13792 }
13793 /* Seed initial cos value */
13794 tosval = ast_variable_retrieve(cfg, "general", "cos");
13795 if (tosval) {
13796 if (ast_str2cos(tosval, &qos.cos))
13797 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13798 }
13799 while(v) {
13800 if (!strcasecmp(v->name, "bindport")) {
13801 if (reload) {
13802 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13803 }
13804 else if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &portno, 1024, 65535)) {
13805 portno = IAX_DEFAULT_PORTNO;
13806 }
13807 } else if (!strcasecmp(v->name, "pingtime")){
13808 ping_time = atoi(v->value);
13809 }
13810 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13811 if (reload) {
13812 if (atoi(v->value) != iaxthreadcount)
13813 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13814 } else {
13815 iaxthreadcount = atoi(v->value);
13816 if (iaxthreadcount < 1) {
13817 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13818 iaxthreadcount = 1;
13819 } else if (iaxthreadcount > 256) {
13820 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13821 iaxthreadcount = 256;
13822 }
13823 }
13824 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13825 if (reload) {
13827 iaxmaxthreadcount = atoi(v->value);
13829 } else {
13830 iaxmaxthreadcount = atoi(v->value);
13831 if (iaxmaxthreadcount < 0) {
13832 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13834 } else if (iaxmaxthreadcount > 256) {
13835 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13836 iaxmaxthreadcount = 256;
13837 }
13838 }
13839 } else if (!strcasecmp(v->name, "nochecksums")) {
13840#ifdef SO_NO_CHECK
13841 if (ast_true(v->value))
13842 nochecksums = 1;
13843 else
13844 nochecksums = 0;
13845#else
13846 if (ast_true(v->value))
13847 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13848#endif
13849 }
13850 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13851 maxjitterbuffer = atoi(v->value);
13852 else if (!strcasecmp(v->name, "resyncthreshold"))
13853 resyncthreshold = atoi(v->value);
13854 else if (!strcasecmp(v->name, "maxjitterinterps"))
13855 maxjitterinterps = atoi(v->value);
13856 else if (!strcasecmp(v->name, "jittertargetextra"))
13857 jittertargetextra = atoi(v->value);
13858 else if (!strcasecmp(v->name, "lagrqtime"))
13859 lagrq_time = atoi(v->value);
13860 else if (!strcasecmp(v->name, "maxregexpire"))
13861 max_reg_expire = atoi(v->value);
13862 else if (!strcasecmp(v->name, "minregexpire"))
13863 min_reg_expire = atoi(v->value);
13864 else if (!strcasecmp(v->name, "bindaddr")) {
13865 if (reload) {
13866 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13867 } else {
13868
13869 if (!ast_parse_arg(v->value, PARSE_ADDR, NULL)) {
13870
13872
13873 if (!ast_sockaddr_port(&bindaddr)) {
13875 }
13876
13877 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13878 ast_log(LOG_WARNING, "Unable to apply binding to '%s' at line %d\n", v->value, v->lineno);
13879 } else {
13880 ast_verb(2, "Binding IAX2 to address %s\n", ast_sockaddr_stringify(&bindaddr));
13881
13882 if (defaultsockfd < 0) {
13884 }
13886 }
13887
13888 } else {
13889 ast_log(LOG_WARNING, "Invalid address '%s' specified, at line %d\n", v->value, v->lineno);
13890 }
13891 }
13892 } else if (!strcasecmp(v->name, "auth")) {
13895 ast_log(LOG_WARNING, "Default auth method is set to deprecated 'plaintext' at line %d of iax.conf\n", v->lineno);
13896 }
13897 } else if (!strcasecmp(v->name, "authdebug")) {
13898 authdebug = ast_true(v->value);
13899 } else if (!strcasecmp(v->name, "encryption")) {
13901 if (!iax2_encryption) {
13903 }
13904 } else if (!strcasecmp(v->name, "forceencryption")) {
13905 if (ast_false(v->value)) {
13907 } else {
13909 if (iax2_encryption) {
13911 }
13912 }
13913 } else if (!strcasecmp(v->name, "transfer")) {
13914 if (!strcasecmp(v->value, "mediaonly")) {
13916 } else if (ast_true(v->value)) {
13918 } else
13920 } else if (!strcasecmp(v->name, "codecpriority")) {
13921 if(!strcasecmp(v->value, "caller"))
13923 else if(!strcasecmp(v->value, "disabled"))
13925 else if(!strcasecmp(v->value, "reqonly")) {
13928 }
13929 } else if (!strcasecmp(v->name, "jitterbuffer"))
13931 else if (!strcasecmp(v->name, "delayreject"))
13933 else if (!strcasecmp(v->name, "allowfwdownload"))
13935 else if (!strcasecmp(v->name, "rtcachefriends"))
13937 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13939 else if (!strcasecmp(v->name, "rtupdate"))
13941 else if (!strcasecmp(v->name, "rtsavesysname"))
13943 else if (!strcasecmp(v->name, "trunktimestamps"))
13945 else if (!strcasecmp(v->name, "rtautoclear")) {
13946 int i = atoi(v->value);
13947 if(i > 0)
13949 else
13950 i = 0;
13952 } else if (!strcasecmp(v->name, "trunkfreq")) {
13953 trunkfreq = atoi(v->value);
13954 if (trunkfreq < 10) {
13955 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13956 trunkfreq = 10;
13957 } else if (trunkfreq > 1000) {
13958 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13959 trunkfreq = 1000;
13960 }
13961 if (timer) {
13963 }
13964 } else if (!strcasecmp(v->name, "trunkmtu")) {
13965 mtuv = atoi(v->value);
13966 if (mtuv == 0 )
13968 else if (mtuv >= 172 && mtuv < 4000)
13969 global_max_trunk_mtu = mtuv;
13970 else
13971 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13972 mtuv, v->lineno);
13973 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13974 trunkmaxsize = atoi(v->value);
13975 if (trunkmaxsize == 0)
13977 } else if (!strcasecmp(v->name, "autokill")) {
13978 if (sscanf(v->value, "%30d", &x) == 1) {
13979 if (x >= 0)
13980 autokill = x;
13981 else
13982 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13983 } else if (ast_true(v->value)) {
13985 } else {
13986 autokill = 0;
13987 }
13988 } else if (!strcasecmp(v->name, "bandwidth")) {
13989 if (!strcasecmp(v->value, "low")) {
13990 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13992 } else if (!strcasecmp(v->value, "medium")) {
13993 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13995 } else if (!strcasecmp(v->value, "high")) {
13996 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13998 } else {
13999 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
14000 }
14001 } else if (!strcasecmp(v->name, "allow")) {
14002 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 1);
14003 } else if (!strcasecmp(v->name, "disallow")) {
14004 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 0);
14005 } else if (!strcasecmp(v->name, "register")) {
14006 iax2_register(v->value, v->lineno);
14007 } else if (!strcasecmp(v->name, "iaxcompat")) {
14008 iaxcompat = ast_true(v->value);
14009 } else if (!strcasecmp(v->name, "regcontext")) {
14011 /* Create context if it doesn't exist already */
14013 } else if (!strcasecmp(v->name, "tos")) {
14014 if (ast_str2tos(v->value, &qos.tos))
14015 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
14016 } else if (!strcasecmp(v->name, "cos")) {
14017 if (ast_str2cos(v->value, &qos.cos))
14018 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
14019 } else if (!strcasecmp(v->name, "parkinglot")) {
14021 } else if (!strcasecmp(v->name, "accountcode")) {
14023 } else if (!strcasecmp(v->name, "mohinterpret")) {
14025 } else if (!strcasecmp(v->name, "mohsuggest")) {
14027 } else if (!strcasecmp(v->name, "amaflags")) {
14028 format = ast_channel_string2amaflag(v->value);
14029 if (format < 0) {
14030 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
14031 } else {
14032 amaflags = format;
14033 }
14034 } else if (!strcasecmp(v->name, "language")) {
14035 ast_copy_string(language, v->value, sizeof(language));
14036 } else if (!strcasecmp(v->name, "maxauthreq")) {
14037 maxauthreq = atoi(v->value);
14038 if (maxauthreq < 0)
14039 maxauthreq = 0;
14040 } else if (!strcasecmp(v->name, "adsi")) {
14041 adsi = ast_true(v->value);
14042 } else if (!strcasecmp(v->name, "srvlookup")) {
14043 srvlookup = ast_true(v->value);
14044 } else if (!strcasecmp(v->name, "connectedline")) {
14045 if (ast_true(v->value)) {
14047 } else if (!strcasecmp(v->value, "send")) {
14050 } else if (!strcasecmp(v->value, "receive")) {
14053 } else {
14055 }
14056 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
14057 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
14058 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
14059 }
14060 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
14061 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
14062 ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
14063 }
14064 } else if (!strcasecmp(v->name, "calltokenoptional")) {
14065 if (add_calltoken_ignore(v->value)) {
14066 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
14067 return -1;
14068 }
14069 } else if (!strcasecmp(v->name, "calltokenexpiration")) {
14070 int temp = -1;
14071 sscanf(v->value, "%u", &temp);
14072 if( temp <= 0 ){
14073 ast_log(LOG_WARNING, "Invalid calltokenexpiration value %s. Should be integer greater than 0.\n", v->value);
14074 } else {
14075 max_calltoken_delay = temp;
14076 }
14077 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
14078 if (ast_true(v->value)) {
14079 subscribe_network_change = 1;
14080 } else if (ast_false(v->value)) {
14081 subscribe_network_change = 0;
14082 } else {
14083 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
14084 }
14085 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
14086 if (ast_true(v->value)) {
14088 } else if (ast_false(v->value)) {
14090 } else {
14091 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
14092 }
14093 }/*else if (strcasecmp(v->name,"type")) */
14094 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
14095 v = v->next;
14096 }
14097
14098 if (subscribe_network_change) {
14100 } else {
14102 }
14103
14104 if (defaultsockfd < 0) {
14105
14107
14108 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
14109 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
14110 } else {
14111 ast_verb(2, "Binding IAX2 to default address %s\n", ast_sockaddr_stringify(&bindaddr));
14114 }
14115 }
14116 if (reload) {
14119 if (!outsock) {
14120 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14121 return -1;
14122 }
14124 }
14125
14127 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
14130 }
14131 prefs_global = prefs_new;
14132 iax2_capability = capability;
14133
14134 cat = ast_category_browse(cfg, NULL);
14135 while(cat) {
14136 if (strcasecmp(cat, "general")) {
14137 utype = ast_variable_retrieve(cfg, cat, "type");
14138 if (!strcasecmp(cat, "callnumberlimits")) {
14140 } else if (utype) {
14141 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
14142 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
14143 if (user) {
14145 user = user_unref(user);
14146 }
14147 }
14148 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
14149 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
14150 if (peer) {
14151 if (ast_test_flag64(peer, IAX_DYNAMIC))
14152 reg_source_db(peer);
14153 ao2_link(peers, peer);
14154 peer = peer_unref(peer);
14155 }
14156 } else if (strcasecmp(utype, "user")) {
14157 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
14158 }
14159 } else
14160 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
14161 }
14162 cat = ast_category_browse(cfg, cat);
14163 }
14164 ast_config_destroy(cfg);
14165 return 1;
14166}
14167
14168static void poke_all_peers(void)
14169{
14170 struct ao2_iterator i;
14171 struct iax2_peer *peer;
14172
14173 i = ao2_iterator_init(peers, 0);
14174 while ((peer = ao2_iterator_next(&i))) {
14175 iax2_poke_peer(peer, 0);
14176 peer_unref(peer);
14177 }
14179}
14180static int reload_config(int forced_reload)
14181{
14182 static const char config[] = "iax.conf";
14183 struct iax2_registry *reg;
14184
14185 if (set_config(config, 1, forced_reload) > 0) {
14186 prune_peers();
14187 prune_users();
14193 memset(&debugaddr, '\0', sizeof(debugaddr));
14194
14197 iax2_do_register(reg);
14199
14200 /* Qualify hosts, too */
14202 }
14203
14206 ast_unload_realtime("iaxpeers");
14207
14208 return 0;
14209}
14210
14211static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14212{
14213 switch (cmd) {
14214 case CLI_INIT:
14215 e->command = "iax2 reload";
14216 e->usage =
14217 "Usage: iax2 reload\n"
14218 " Reloads IAX configuration from iax.conf\n";
14219 return NULL;
14220 case CLI_GENERATE:
14221 return NULL;
14222 }
14223
14224 reload_config(0);
14225
14226 return CLI_SUCCESS;
14227}
14228
14229static int reload(void)
14230{
14231 return reload_config(0);
14232}
14233
14234static int cache_get_callno_locked(const char *data)
14235{
14236 struct ast_sockaddr addr;
14237 int x;
14238 int callno;
14239 struct iax_ie_data ied;
14240 struct create_addr_info cai;
14241 struct parsed_dial_string pds;
14242 char *tmpstr;
14243
14244 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14245 /* Look for an *exact match* call. Once a call is negotiated, it can only
14246 look up entries for a single context */
14247 if (!ast_mutex_trylock(&iaxsl[x])) {
14248 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14249 return x;
14251 }
14252 }
14253
14254 /* No match found, we need to create a new one */
14255
14256 memset(&cai, 0, sizeof(cai));
14257 memset(&ied, 0, sizeof(ied));
14258 memset(&pds, 0, sizeof(pds));
14259
14260 tmpstr = ast_strdupa(data);
14261 parse_dial_string(tmpstr, &pds);
14262
14263 if (ast_strlen_zero(pds.peer)) {
14264 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14265 return -1;
14266 }
14267
14268 /* Populate our address from the given */
14269 if (create_addr(pds.peer, NULL, &addr, &cai))
14270 return -1;
14271
14272 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14273 pds.peer, pds.username, pds.password, pds.context);
14274
14275 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
14276 if (callno < 1) {
14277 ast_log(LOG_WARNING, "Unable to create call\n");
14278 return -1;
14279 }
14280
14281 ast_string_field_set(iaxs[callno], dproot, data);
14283
14286 /* the string format is slightly different from a standard dial string,
14287 because the context appears in the 'exten' position
14288 */
14289 if (pds.exten)
14291 if (pds.username)
14295 /* Keep password handy */
14296 if (pds.password)
14297 ast_string_field_set(iaxs[callno], secret, pds.password);
14298 if (pds.key)
14299 ast_string_field_set(iaxs[callno], outkey, pds.key);
14300 /* Start the call going */
14301 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14302 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14303
14304 return callno;
14305}
14306
14307static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14308{
14309 struct iax2_dpcache *dp = NULL;
14310 struct timeval now = ast_tvnow();
14311 int x, com[2], timeout, doabort, callno;
14312
14313 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14314 if (ast_tvcmp(now, dp->expiry) > 0) {
14315 AST_LIST_REMOVE_CURRENT(cache_list);
14316 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14317 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14318 else
14319 ast_free(dp);
14320 continue;
14321 }
14322 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14323 break;
14324 }
14326
14327 if (!dp) {
14328 /* No matching entry. Create a new one. */
14329 /* First, can we make a callno? */
14330 if ((callno = cache_get_callno_locked(data)) < 0) {
14331 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14332 return NULL;
14333 }
14334 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14335 ast_mutex_unlock(&iaxsl[callno]);
14336 return NULL;
14337 }
14338 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14339 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14340 dp->expiry = ast_tvnow();
14341 dp->orig = dp->expiry;
14342 /* Expires in 30 mins by default */
14343 dp->expiry.tv_sec += iaxdefaultdpcache;
14345 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14346 dp->waiters[x] = -1;
14347 /* Insert into the lists */
14348 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14349 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14350 /* Send the request if we're already up */
14351 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14352 iax2_dprequest(dp, callno);
14353 ast_mutex_unlock(&iaxsl[callno]);
14354 }
14355
14356 /* By here we must have a dp */
14357 if (dp->flags & CACHE_FLAG_PENDING) {
14358 int res;
14359 struct pollfd pfd;
14360 /* Okay, here it starts to get nasty. We need a pipe now to wait
14361 for a reply to come back so long as it's pending */
14362 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14363 /* Find an empty slot */
14364 if (dp->waiters[x] < 0)
14365 break;
14366 }
14367 if (x >= ARRAY_LEN(dp->waiters)) {
14368 ast_log(LOG_WARNING, "No more waiter positions available\n");
14369 return NULL;
14370 }
14371 if (pipe(com)) {
14372 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14373 return NULL;
14374 }
14375 dp->waiters[x] = com[1];
14376 /* Okay, now we wait */
14377 timeout = iaxdefaulttimeout * 1000;
14378 /* Temporarily unlock */
14380 doabort = 0;
14381
14382 /* chan is in autoservice here, so do NOT service it here! */
14383 pfd.fd = com[0];
14384 pfd.events = POLLIN;
14385 pfd.revents = 0;
14386 /* Wait for pipe activity... if the channel hangs up, we'll catch it on the way out. */
14387 res = ast_poll(&pfd, 1, timeout);
14388 if (res < 0) {
14389 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
14390 return NULL;
14391 } else if (!pfd.revents) {
14392 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14393 }
14394
14395 if (chan && ast_check_hangup(chan)) {
14396 doabort = 1;
14397 }
14398
14400 dp->waiters[x] = -1;
14401 close(com[1]);
14402 close(com[0]);
14403 if (doabort) {
14404 /* Don't interpret anything, just abort. */
14405 return NULL;
14406 }
14407 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14408 /* Now to do non-independent analysis the results of our wait */
14409 if (dp->flags & CACHE_FLAG_PENDING) {
14410 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
14411 pending. Don't let it take as long to timeout. */
14412 dp->flags &= ~CACHE_FLAG_PENDING;
14414 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14415 systems without leaving it unavailable once the server comes back online */
14416 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14417 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14418 if (dp->waiters[x] > -1) {
14419 if (write(dp->waiters[x], "asdf", 4) < 0) {
14420 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14421 }
14422 }
14423 }
14424 }
14425 }
14426 /* Our caller will obtain the rest */
14427 }
14428 return dp;
14429}
14430
14431/*! \brief Part of the IAX2 switch interface */
14432static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14433{
14434 int res = 0;
14435 struct iax2_dpcache *dp = NULL;
14436#if 0
14437 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14438#endif
14439 if ((priority != 1) && (priority != 2))
14440 return 0;
14441
14443 if ((dp = find_cache(chan, data, context, exten, priority))) {
14444 if (dp->flags & CACHE_FLAG_EXISTS)
14445 res = 1;
14446 } else {
14447 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14448 }
14450
14451 return res;
14452}
14453
14454/*! \brief part of the IAX2 dial plan switch interface */
14455static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14456{
14457 int res = 0;
14458 struct iax2_dpcache *dp = NULL;
14459#if 0
14460 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14461#endif
14462 if ((priority != 1) && (priority != 2))
14463 return 0;
14464
14466 if ((dp = find_cache(chan, data, context, exten, priority))) {
14467 if (dp->flags & CACHE_FLAG_CANEXIST)
14468 res = 1;
14469 } else {
14470 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14471 }
14473
14474 return res;
14475}
14476
14477/*! \brief Part of the IAX2 Switch interface */
14478static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14479{
14480 int res = 0;
14481 struct iax2_dpcache *dp = NULL;
14482#if 0
14483 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14484#endif
14485 if ((priority != 1) && (priority != 2))
14486 return 0;
14487
14489 if ((dp = find_cache(chan, data, context, exten, priority))) {
14490 if (dp->flags & CACHE_FLAG_MATCHMORE)
14491 res = 1;
14492 } else {
14493 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14494 }
14496
14497 return res;
14498}
14499
14500/*! \brief Execute IAX2 dialplan switch */
14501static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14502{
14503 char odata[256];
14504 char req[sizeof(odata) + AST_MAX_CONTEXT + AST_MAX_EXTENSION + sizeof("IAX2//@")];
14505 char *ncontext;
14506 struct iax2_dpcache *dp = NULL;
14507 struct ast_app *dial = NULL;
14508#if 0
14509 ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
14510#endif
14511 if (priority == 2) {
14512 /* Indicate status, can be overridden in dialplan */
14513 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14514 if (dialstatus) {
14515 dial = pbx_findapp(dialstatus);
14516 if (dial)
14517 pbx_exec(chan, dial, "");
14518 }
14519 return -1;
14520 } else if (priority != 1)
14521 return -1;
14522
14524 if ((dp = find_cache(chan, data, context, exten, priority))) {
14525 if (dp->flags & CACHE_FLAG_EXISTS) {
14526 ast_copy_string(odata, data, sizeof(odata));
14527 ncontext = strchr(odata, '/');
14528 if (ncontext) {
14529 *ncontext = '\0';
14530 ncontext++;
14531 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14532 } else {
14533 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14534 }
14535 ast_verb(3, "Executing Dial('%s')\n", req);
14536 } else {
14538 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14539 return -1;
14540 }
14541 }
14543
14544 if ((dial = pbx_findapp("Dial")))
14545 return pbx_exec(chan, dial, req);
14546 else
14547 ast_log(LOG_WARNING, "No dial application registered\n");
14548
14549 return -1;
14550}
14551
14552static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14553{
14554 struct iax2_peer *peer;
14555 char *peername, *colname;
14556
14557 peername = ast_strdupa(data);
14558
14559 /* if our channel, return the IP address of the endpoint of current channel */
14560 if (!strcmp(peername,"CURRENTCHANNEL")) {
14561 unsigned short callno;
14562 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14563 return -1;
14564 }
14567 return 0;
14568 }
14569
14570 if ((colname = strchr(peername, ',')))
14571 *colname++ = '\0';
14572 else
14573 colname = "ip";
14574
14575 if (!(peer = find_peer(peername, 1)))
14576 return -1;
14577
14578 if (!strcasecmp(colname, "ip")) {
14580 } else if (!strcasecmp(colname, "status")) {
14581 peer_status(peer, buf, len);
14582 } else if (!strcasecmp(colname, "mailbox")) {
14583 ast_copy_string(buf, peer->mailbox, len);
14584 } else if (!strcasecmp(colname, "context")) {
14585 ast_copy_string(buf, peer->context, len);
14586 } else if (!strcasecmp(colname, "expire")) {
14587 snprintf(buf, len, "%d", peer->expire);
14588 } else if (!strcasecmp(colname, "dynamic")) {
14589 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14590 } else if (!strcasecmp(colname, "callerid_name")) {
14592 } else if (!strcasecmp(colname, "callerid_num")) {
14593 ast_copy_string(buf, peer->cid_num, len);
14594 } else if (!strcasecmp(colname, "codecs")) {
14595 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
14596
14597 iax2_getformatname_multiple(peer->capability, &codec_buf);
14598 ast_copy_string(buf, ast_str_buffer(codec_buf), len);
14599 } else if (!strncasecmp(colname, "codec[", 6)) {
14600 char *codecnum, *ptr;
14601 struct ast_format *tmpfmt;
14602
14603 /* skip over "codec" to the '[' */
14604 codecnum = colname + 5;
14605 *codecnum = '\0';
14606 codecnum++;
14607 if ((ptr = strchr(codecnum, ']'))) {
14608 *ptr = '\0';
14609 }
14610 if((iax2_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14612 } else {
14613 buf[0] = '\0';
14614 }
14615 } else {
14616 buf[0] = '\0';
14617 }
14618
14619 peer_unref(peer);
14620
14621 return 0;
14622}
14623
14625 .name = "IAXPEER",
14626 .read = function_iaxpeer,
14627};
14628
14629static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14630{
14631 struct chan_iax2_pvt *pvt;
14632 unsigned int callno;
14633 int res = 0;
14634
14635 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14636 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14637 return -1;
14638 }
14639
14642 if (!(pvt = iaxs[callno])) {
14644 return -1;
14645 }
14646
14647 if (!strcasecmp(args, "osptoken")) {
14648 ast_copy_string(buf, pvt->osptoken, buflen);
14649 } else if (!strcasecmp(args, "peerip")) {
14651 } else if (!strcasecmp(args, "peername")) {
14652 ast_copy_string(buf, pvt->username, buflen);
14653 } else if (!strcasecmp(args, "auth_method")) {
14655 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14656 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14657 } else {
14658 res = -1;
14659 }
14660
14662
14663 return res;
14664}
14665
14666/*! \brief Part of the device state notification system ---*/
14667static int iax2_devicestate(const char *data)
14668{
14669 struct parsed_dial_string pds;
14670 char *tmp = ast_strdupa(data);
14671 struct iax2_peer *p;
14672 int res = AST_DEVICE_INVALID;
14673
14674 memset(&pds, 0, sizeof(pds));
14675 parse_dial_string(tmp, &pds);
14676
14677 if (ast_strlen_zero(pds.peer)) {
14678 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14679 return res;
14680 }
14681
14682 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14683
14684 /* SLD: FIXME: second call to find_peer during registration */
14685 if (!(p = find_peer(pds.peer, 1)))
14686 return res;
14687
14689
14690 ast_debug(3, "Found peer. What's device state of %s? addr=%s, defaddr=%s maxms=%d, lastms=%d\n",
14692
14693 if (((!ast_sockaddr_isnull(&p->addr)) || (!ast_sockaddr_isnull(&p->defaddr))) &&
14694 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14695 /* Peer is registered, or have default IP address
14696 and a valid registration */
14697 if (p->historicms == 0 || p->historicms <= p->maxms)
14698 /* let the core figure out whether it is in use or not */
14699 res = AST_DEVICE_UNKNOWN;
14700 }
14701
14702 peer_unref(p);
14703
14704 return res;
14705}
14706
14708{
14709 .name = "IAX2",
14710 .description = "IAX Remote Dialplan Switch",
14711 .exists = iax2_exists,
14712 .canmatch = iax2_canmatch,
14713 .exec = iax2_exec,
14714 .matchmore = iax2_matchmore,
14715};
14716
14717static struct ast_cli_entry cli_iax2[] = {
14718 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14719 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14720 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14721 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14722 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14723 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14724 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14725 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14726 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14727 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14728 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14729 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14730 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14731 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14732 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14733 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14734 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14735 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14736 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14737 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14738#ifdef IAXTESTS
14739 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14740 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14741 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14742#endif /* IAXTESTS */
14743};
14744
14745static void cleanup_thread_list(void *head)
14746{
14747 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14748 struct iax2_thread_list *list_head = head;
14749 struct iax2_thread *thread;
14750
14751 AST_LIST_LOCK(list_head);
14752 while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14753 pthread_t thread_id = thread->threadid;
14754
14755 thread->stop = 1;
14756 signal_condition(&thread->lock, &thread->cond);
14757
14758 AST_LIST_UNLOCK(list_head);
14759 pthread_join(thread_id, NULL);
14760 AST_LIST_LOCK(list_head);
14761 }
14762 AST_LIST_UNLOCK(list_head);
14763}
14764
14765static int __unload_module(void)
14766{
14767 int x;
14768
14771
14772 ast_manager_unregister("IAXpeers");
14773 ast_manager_unregister("IAXpeerlist");
14774 ast_manager_unregister("IAXnetstats");
14775 ast_manager_unregister("IAXregistry");
14780
14782 pthread_cancel(netthreadid);
14783 pthread_kill(netthreadid, SIGURG);
14784 pthread_join(netthreadid, NULL);
14785 }
14786
14787 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14788 if (iaxs[x]) {
14789 iax2_destroy(x);
14790 }
14791 }
14792
14793 /* Call for all threads to halt */
14797
14800 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14801 if (iaxs[x]) {
14802 iax2_destroy(x);
14803 }
14804 }
14805 ast_manager_unregister( "IAXpeers" );
14806 ast_manager_unregister( "IAXpeerlist" );
14807 ast_manager_unregister( "IAXnetstats" );
14808 ast_manager_unregister( "IAXregistry" );
14813 delete_users();
14816
14817 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14819 }
14820
14821 ao2_ref(peers, -1);
14822 ao2_ref(users, -1);
14827 if (timer) {
14829 timer = NULL;
14830 }
14832
14835 sched = NULL;
14836 ao2_ref(peercnts, -1);
14837
14839 ast_unload_realtime("iaxpeers");
14840
14843 return 0;
14844}
14845
14852
14853static int peer_set_sock_cb(void *obj, void *arg, int flags)
14854{
14855 struct iax2_peer *peer = obj;
14856
14857 if (peer->sockfd < 0)
14858 peer->sockfd = defaultsockfd;
14859
14860 return 0;
14861}
14862
14863static int pvt_hash_cb(const void *obj, const int flags)
14864{
14865 const struct chan_iax2_pvt *pvt = obj;
14866
14867 return pvt->peercallno;
14868}
14869
14870static int pvt_cmp_cb(void *obj, void *arg, int flags)
14871{
14872 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14873
14874 /* The frames_received field is used to hold whether we're matching
14875 * against a full frame or not ... */
14876
14877 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14878 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14879}
14880
14881static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14882{
14883 const struct chan_iax2_pvt *pvt = obj;
14884
14885 return pvt->transfercallno;
14886}
14887
14888static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14889{
14890 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14891
14892 /* The frames_received field is used to hold whether we're matching
14893 * against a full frame or not ... */
14894
14895 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14896 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14897}
14898
14899static int load_objects(void)
14900{
14903
14906 if (!peers) {
14907 goto container_fail;
14908 }
14909
14912 if (!users) {
14913 goto container_fail;
14914 }
14915
14918 if (!iax_peercallno_pvts) {
14919 goto container_fail;
14920 }
14921
14925 goto container_fail;
14926 }
14927
14930 if (!peercnts) {
14931 goto container_fail;
14932 }
14933
14936 if (!callno_limits) {
14937 goto container_fail;
14938 }
14939
14942 if (!calltoken_ignores) {
14943 goto container_fail;
14944 }
14945
14946 if (create_callno_pools()) {
14947 goto container_fail;
14948 }
14949
14951 if (!transmit_processor) {
14952 goto container_fail;
14953 }
14954
14955 return 0;
14956
14957container_fail:
14958 if (peers) {
14959 ao2_ref(peers, -1);
14960 }
14961 if (users) {
14962 ao2_ref(users, -1);
14963 }
14964 if (iax_peercallno_pvts) {
14966 }
14969 }
14970 if (peercnts) {
14971 ao2_ref(peercnts, -1);
14972 }
14973 if (callno_limits) {
14975 }
14976 if (calltoken_ignores) {
14978 }
14979 return -1;
14980}
14981
14982/*!
14983 * \brief Load the module
14984 *
14985 * Module loading including tests for configuration or dependencies.
14986 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
14987 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
14988 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
14989 * configuration file or other non-critical problem return
14990 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
14991 */
14992static int load_module(void)
14993{
14994 static const char config[] = "iax.conf";
14995 int x = 0;
14996 struct iax2_registry *reg = NULL;
14997
15000 }
15002
15003 if (load_objects()) {
15007 }
15008
15009 memset(iaxs, 0, sizeof(iaxs));
15010
15011 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
15012 ast_mutex_init(&iaxsl[x]);
15013 }
15014
15015 if (!(sched = ast_sched_context_create())) {
15016 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
15020 }
15021
15026 sched = NULL;
15028 }
15029
15030 if (!(io = io_context_create())) {
15031 ast_log(LOG_ERROR, "Failed to create I/O context\n");
15035 sched = NULL;
15037 }
15038
15039 if (!(netsock = ast_netsock_list_alloc())) {
15040 ast_log(LOG_ERROR, "Failed to create netsock list\n");
15045 sched = NULL;
15047 }
15049
15051 if (!outsock) {
15052 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
15057 sched = NULL;
15059 }
15061
15063
15067
15068 if ((timer = ast_timer_open())) {
15070 }
15071
15072 if (set_config(config, 0, 0) == -1) {
15073 if (timer) {
15075 timer = NULL;
15076 }
15079 }
15080
15082
15084
15087
15092
15094 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15097 }
15098
15100 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15101 }
15102
15103 if (start_network_thread()) {
15104 ast_log(LOG_ERROR, "Unable to start network thread\n");
15107 } else {
15108 ast_verb(2, "IAX Ready and Listening\n");
15109 }
15110
15113 iax2_do_register(reg);
15115
15118
15119
15122
15123 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15124
15126
15128}
15129
15130AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15131 .support_level = AST_MODULE_SUPPORT_CORE,
15132 .load = load_module,
15133 .unload = unload_module,
15134 .reload = reload,
15135 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15136 .requires = "dnsmgr",
15137 .optional_modules = "res_crypto",
Access Control of various sorts.
enum ast_acl_sense ast_apply_acl(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr, const char *purpose)
Apply a set of rules to a given IP address.
Definition acl.c:799
void ast_free_ha(struct ast_ha *ha)
Free a list of HAs.
Definition acl.c:222
int ast_str2tos(const char *value, unsigned int *tos)
Convert a string to the appropriate TOS value.
Definition acl.c:983
struct stasis_message_type * ast_named_acl_change_type(void)
a stasis_message_type for changes against a named ACL or the set of all named ACLs
void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
Copy the contents of one HA to another.
Definition acl.c:255
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
Add a rule to an ACL struct.
Definition acl.c:429
@ AST_SENSE_ALLOW
Definition acl.h:38
@ AST_SENSE_DENY
Definition acl.h:37
int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
Get the IP address given a hostname.
Definition acl.c:1016
int ast_acl_list_is_empty(struct ast_acl_list *acl_list)
Determines if an ACL is empty or if it contains entries.
Definition acl.c:540
int ast_str2cos(const char *value, unsigned int *cos)
Convert a string to the appropriate COS value.
Definition acl.c:969
struct ast_acl_list * ast_free_acl_list(struct ast_acl_list *acl)
Free a list of ACLs.
Definition acl.c:233
struct ast_ha * ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
Add a new rule to a list of HAs.
Definition acl.c:712
int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
Get the IP address given a hostname and optional service.
Definition acl.c:933
void ast_cli_unregister_multiple(void)
Definition ael_main.c:408
static const struct adsi_event events[]
char digit
jack_status_t status
Definition app_jack.c:149
char * text
Definition app_queue.c:1791
pthread_t thread
Definition app_sla.c:335
ast_cond_t cond
Definition app_sla.c:336
ast_mutex_t lock
Definition app_sla.c:337
static char zonetag[80]
static int copy(char *infile, char *outfile)
Utility function to copy a file.
#define var
Definition ast_expr2f.c:605
Persistent data storage (akin to *doze registry)
int ast_db_put(const char *family, const char *key, const char *value)
Store value addressed by family/key.
Definition db.c:335
int ast_db_get(const char *family, const char *key, char *value, int valuelen)
Get key value specified by family/key.
Definition db.c:421
int ast_db_del(const char *family, const char *key)
Delete entry in astdb.
Definition db.c:472
char * strsep(char **str, const char *delims)
Asterisk main include file. File version handling, generic pbx functions.
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition astmm.h:288
#define ast_free(a)
Definition astmm.h:180
#define ast_realloc(p, len)
A wrapper for realloc()
Definition astmm.h:226
#define ast_strdup(str)
A wrapper for strdup()
Definition astmm.h:241
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition astmm.h:298
void ast_free_ptr(void *ptr)
free() wrapper
Definition astmm.c:1739
#define ast_calloc(num, len)
A wrapper for calloc()
Definition astmm.h:202
#define ast_malloc(len)
A wrapper for malloc()
Definition astmm.h:191
#define ast_log
Definition astobj2.c:42
#define ao2_iterator_next(iter)
Definition astobj2.h:1911
#define ao2_link(container, obj)
Add an object to a container.
Definition astobj2.h:1532
@ CMP_MATCH
Definition astobj2.h:1027
@ CMP_STOP
Definition astobj2.h:1028
#define OBJ_KEY
Definition astobj2.h:1151
#define OBJ_POINTER
Definition astobj2.h:1150
@ AO2_ALLOC_OPT_LOCK_MUTEX
Definition astobj2.h:363
#define ao2_callback(c, flags, cb_fn, arg)
ao2_callback() is a generic function that applies cb_fn() to all objects in a container,...
Definition astobj2.h:1693
#define ao2_cleanup(obj)
Definition astobj2.h:1934
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition astobj2.h:1578
#define ao2_find(container, arg, flags)
Definition astobj2.h:1736
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
#define ao2_unlock(a)
Definition astobj2.h:729
#define ao2_lock(a)
Definition astobj2.h:717
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition astobj2.h:459
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
@ OBJ_NODATA
Definition astobj2.h:1044
@ OBJ_MULTIPLE
Definition astobj2.h:1049
@ OBJ_UNLINK
Definition astobj2.h:1039
#define ao2_alloc(data_size, destructor_fn)
Definition astobj2.h:409
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Allocate and initialize a hash container with the desired number of buckets.
Definition astobj2.h:1303
Bridging API.
enum ast_transfer_result ast_bridge_transfer_blind(int is_external, struct ast_channel *transferer, const char *exten, const char *context, transfer_channel_cb new_channel_cb, void *user_data)
Blind transfer target to the extension and context provided.
Definition bridge.c:4504
@ AST_BRIDGE_TRANSFER_SUCCESS
Definition bridge.h:1104
CallerID (and other GR30) management and generation Includes code and algorithms from the Zapata libr...
#define AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
Definition callerid.h:440
char * ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
Definition callerid.c:1273
#define AST_PRES_NUMBER_NOT_AVAILABLE
Definition callerid.h:461
void ast_shrink_phone_number(char *n)
Shrink a phone number in place to just digits (more accurately it just removes ()'s,...
Definition callerid.c:1101
int ast_callerid_split(const char *src, char *name, int namelen, char *num, int numlen)
Definition callerid.c:1292
Internal Asterisk hangup causes.
#define AST_CAUSE_CONGESTION
Definition causes.h:153
#define AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
Definition causes.h:130
#define AST_CAUSE_DESTINATION_OUT_OF_ORDER
Definition causes.h:115
#define AST_CAUSE_NO_USER_RESPONSE
Definition causes.h:108
#define AST_CAUSE_FACILITY_NOT_SUBSCRIBED
Definition causes.h:126
#define AST_CAUSE_CALL_REJECTED
Definition causes.h:111
#define AST_CAUSE_FACILITY_REJECTED
Definition causes.h:117
#define AST_CAUSE_NO_ROUTE_DESTINATION
Definition causes.h:100
#define AST_CAUSE_UNREGISTERED
Definition causes.h:154
#define AST_CAUSE_BUSY
Definition causes.h:149
static int priority
static const char config_file[]
Definition cdr_odbc.c:54
static int connected
Definition cdr_pgsql.c:73
static char * tz
Definition cdr_pgsql.c:71
#define MAX_USER_BUCKETS
Definition chan_iax2.c:1040
static int timing_read(int *id, int fd, short events, void *cbdata)
Definition chan_iax2.c:9655
#define IAX_TRUNKTIMESTAMPS
Definition chan_iax2.c:556
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
Definition chan_iax2.c:5864
static void set_peercnt_limit(struct peercnt *peercnt)
Definition chan_iax2.c:2639
static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Definition chan_iax2.c:7940
static int iaxthreadcount
Definition chan_iax2.c:757
static int send_ping(const void *data)
Definition chan_iax2.c:1826
static int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition chan_iax2.c:9647
iax2_thread_iostate
Definition chan_iax2.c:1128
@ IAX_IOSTATE_PROCESSING
Definition chan_iax2.c:1131
@ IAX_IOSTATE_SCHEDREADY
Definition chan_iax2.c:1132
@ IAX_IOSTATE_IDLE
Definition chan_iax2.c:1129
@ IAX_IOSTATE_READY
Definition chan_iax2.c:1130
static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
callback to display iax peers in manager
Definition chan_iax2.c:7398
static struct ao2_container * peercnts
Definition chan_iax2.c:1044
static struct iax2_context * build_context(const char *context)
static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
Definition chan_iax2.c:9823
#define IAX_ALREADYGONE
Definition chan_iax2.c:544
#define IAX_PROVISION
Definition chan_iax2.c:545
static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
Definition chan_iax2.c:9197
static int iax2_write(struct ast_channel *c, struct ast_frame *f)
Definition chan_iax2.c:7836
#define AUTH_METHOD_NAMES_BUFSIZE
Definition chan_iax2.c:444
static struct iax2_peer * realtime_peer(const char *peername, struct ast_sockaddr *addr)
Definition chan_iax2.c:4470
static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd, struct iax_frame *fr)
static struct iax2_user * user_unref(struct iax2_user *user)
Definition chan_iax2.c:2125
static int apply_context(struct iax2_context *con, const char *context)
Definition chan_iax2.c:7929
static struct ast_channel_tech iax2_tech
Definition chan_iax2.c:1379
static void __auto_hangup(const void *nothing)
Definition chan_iax2.c:9526
static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2174
static char * complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
Definition chan_iax2.c:3977
static int autokill
Definition chan_iax2.c:383
static int randomcalltokendata
Definition chan_iax2.c:1022
static int iaxdynamicthreadcount
Definition chan_iax2.c:759
static void iax2_lock_owner(int callno)
Definition chan_iax2.c:1419
static int delayreject
Definition chan_iax2.c:515
static int iax2_queue_hold(int callno, const char *musicclass)
Queue a hold frame on the ast_channel owner.
Definition chan_iax2.c:3362
#define MAX_TIMESTAMP_SKEW
Definition chan_iax2.c:749
static void acl_change_stasis_subscribe(void)
Definition chan_iax2.c:1555
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2485
static struct ast_channel * ast_iax2_new(int callno, int state, iax2_format capability, struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, unsigned int cachable)
Create new call, interface with the PBX core.
Definition chan_iax2.c:5959
static void jb_error_output(const char *fmt,...)
Definition chan_iax2.c:1294
static int peer_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2048
static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
Definition chan_iax2.c:8905
static int replace_callno(const void *obj)
Definition chan_iax2.c:3068
#define CALLNO_ENTRY_IS_VALIDATED(a)
Definition chan_iax2.c:992
static int auto_congest(const void *data)
Definition chan_iax2.c:4848
static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
Definition chan_iax2.c:6158
static void __iax2_poke_noanswer(const void *data)
static int iax2_predestroy(int callno)
Definition chan_iax2.c:3522
static int update_packet(struct iax_frame *f)
Definition chan_iax2.c:3607
static int iaxcompat
Definition chan_iax2.c:384
static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
Definition chan_iax2.c:6413
static char * handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:3726
static int peercnt_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2545
static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
Definition chan_iax2.c:9794
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
Definition chan_iax2.c:5497
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
Definition chan_iax2.c:7924
static void unwrap_timestamp(struct iax_frame *fr)
Definition chan_iax2.c:4159
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:5478
static int iax2_hangup(struct ast_channel *c)
Definition chan_iax2.c:5430
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
All frames other than that of type AST_FRAME_IAX must be held until we have received a destination ca...
Definition chan_iax2.c:2257
static int __schedule_action(void(*func)(const void *data), const void *data, const char *funcname)
Definition chan_iax2.c:1738
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2561
static int maxjitterbuffer
Definition chan_iax2.c:372
static int auth_fail(int callno, int failcode)
Definition chan_iax2.c:9511
static char * handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:3787
#define PEERS_FORMAT2
Definition chan_iax2.c:6995
#define PTR_TO_CALLNO(a)
Definition chan_iax2.c:329
unsigned int tos
Definition chan_iax2.c:392
static int iax2_queue_hangup(int callno)
Queue a hangup frame on the ast_channel owner.
Definition chan_iax2.c:3408
static int peercnt_remove_cb(const void *obj)
Definition chan_iax2.c:2794
static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
Definition chan_iax2.c:6187
static unsigned char compress_subclass(iax2_format subclass)
Definition chan_iax2.c:1899
static int handle_error(void)
Definition chan_iax2.c:3441
#define IAX_TRUNK
Definition chan_iax2.c:538
static const char * auth_method_labels[]
Name of effective auth method.
Definition chan_iax2.c:436
static int peer_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2059
static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
Definition chan_iax2.c:4921
static int get_auth_methods(const char *value)
static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies, struct ast_sockaddr *addr, int fd)
Definition chan_iax2.c:5043
static struct chan_iax2_pvt * new_iax(struct ast_sockaddr *addr, const char *host)
Definition chan_iax2.c:2329
static char default_parkinglot[AST_MAX_CONTEXT]
Definition chan_iax2.c:359
static struct iax2_trunk_peer * find_tpeer(struct ast_sockaddr *addr, int fd)
Definition chan_iax2.c:6377
static void iax_error_output(const char *data)
Definition chan_iax2.c:1289
static void vnak_retransmit(int callno, int last)
Definition chan_iax2.c:9573
static int user_delme_cb(void *obj, void *arg, int flags)
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7919
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
static struct ast_custom_function iaxvar_function
#define IAX_SHRINKCALLERID
Definition chan_iax2.c:565
static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
Queue the last read full frame for processing by a certain thread.
Definition chan_iax2.c:9937
static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Execute IAX2 dialplan switch.
static int __unload_module(void)
static char * handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7737
static struct stasis_subscription * acl_change_sub
Definition chan_iax2.c:365
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
static iax2_format iax2_capability
Definition chan_iax2.c:496
#define DEFAULT_MAX_THREAD_COUNT
Definition chan_iax2.c:333
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)]
chan_iax2_pvt structure locks
Definition chan_iax2.c:1249
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
Definition chan_iax2.c:4432
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL
Definition chan_iax2.c:1054
static struct ast_sched_context * sched
Definition chan_iax2.c:494
static void * dp_lookup_thread(void *data)
Definition chan_iax2.c:9765
static uint16_t DEFAULT_MAXCALLNO_LIMIT
Definition chan_iax2.c:1052
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
Definition chan_iax2.c:2689
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
Definition chan_iax2.c:3475
static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
Definition chan_iax2.c:9423
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7884
static void encmethods_to_str(int e, struct ast_str **buf)
Definition chan_iax2.c:1836
static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
Definition chan_iax2.c:9807
static struct ast_custom_function iaxpeer_function
static int load_objects(void)
static int complete_transfer(int callno, struct iax_ies *ies)
Definition chan_iax2.c:8844
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
Definition chan_iax2.c:4454
static struct ast_format * codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Definition chan_iax2.c:1933
static int prune_addr_range_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2678
static void iax_debug_output(const char *data)
Definition chan_iax2.c:1283
#define IAX_CALLENCRYPTED(pvt)
Definition chan_iax2.c:477
static char * handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static uint16_t global_maxcallno_nonval
Definition chan_iax2.c:1059
static int maxjitterinterps
Definition chan_iax2.c:374
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
Definition chan_iax2.c:4329
#define IAX_ENCRYPTED
Definition chan_iax2.c:547
static void jb_debug_output(const char *fmt,...)
Definition chan_iax2.c:1318
#define IAX_CODEC_NOCAP
Definition chan_iax2.c:551
static int ping_time
Definition chan_iax2.c:370
static void iax_pvt_callid_new(int callno)
Definition chan_iax2.c:1223
static char * regstate2str(int regstate)
Definition chan_iax2.c:7459
static int last_authmethod
Definition chan_iax2.c:385
#define IAX_NOTRANSFER
Definition chan_iax2.c:539
static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
Definition chan_iax2.c:7099
#define IAX_IMMEDIATE
Definition chan_iax2.c:561
static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
Definition chan_iax2.c:5205
static char * handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Set trunk MTU from CLI.
Definition chan_iax2.c:4046
static int trunk_untimed
Definition chan_iax2.c:355
static void pvt_destructor(void *obj)
Definition chan_iax2.c:2282
static int addr_range_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2531
static int pvt_hash_cb(const void *obj, const int flags)
static int iax2_queue_unhold(int callno)
Queue an unhold frame on the ast_channel owner.
Definition chan_iax2.c:3385
#define MAX_TRUNK_MTU
Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516...
Definition chan_iax2.c:352
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
Definition chan_iax2.c:2131
static struct iax2_peer * build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create peer structure based on configuration.
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition chan_iax2.c:3324
static void * iax2_process_thread(void *data)
static struct @119 frame_queue[IAX_MAX_CALLS]
a list of frames that may need to be retransmitted
static int iax2_digit_begin(struct ast_channel *c, char digit)
Definition chan_iax2.c:4427
static struct iax2_user * build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create in-memory user structure from configuration.
static char regcontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:362
static int socket_process_helper(struct iax2_thread *thread)
#define IAX_CAPABILITY_FULLBANDWIDTH
Definition chan_iax2.c:410
static struct ao2_container * peers
Definition chan_iax2.c:1038
static int set_config(const char *config_file, int reload, int forced)
Load configuration.
static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition chan_iax2.c:8763
static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
Definition chan_iax2.c:6998
static void __auto_congest(const void *nothing)
Definition chan_iax2.c:4835
#define IAX_HASCALLERID
Definition chan_iax2.c:535
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
Definition chan_iax2.c:2234
static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, int now, int transfer, int final)
Definition chan_iax2.c:7865
#define MARK_IAX_SUBCLASS_TX
Definition chan_iax2.c:755
static int iax2_key_rotate(const void *vpvt)
Definition chan_iax2.c:5592
#define schedule_action(func, data)
Definition chan_iax2.c:1763
static int invalid_key(ast_aes_decrypt_key *ecx)
Definition chan_iax2.c:6496
static int user_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2082
static void __expire_registry(const void *data)
Definition chan_iax2.c:9093
static void reg_source_db(struct iax2_peer *p)
Definition chan_iax2.c:9143
static int scheduled_destroy(const void *vid)
Definition chan_iax2.c:2222
static void prune_peers(void)
static time_t max_calltoken_delay
Definition chan_iax2.c:1024
static struct ao2_container * callno_limits
Definition chan_iax2.c:1047
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
Definition chan_iax2.c:2580
static struct ast_frame * iax2_read(struct ast_channel *c)
Definition chan_iax2.c:5586
static struct ast_netsock_list * netsock
Definition chan_iax2.c:403
static int min_reg_expire
Definition chan_iax2.c:396
static int add_calltoken_ignore(const char *addr)
Definition chan_iax2.c:2881
static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
Definition chan_iax2.c:8596
#define ACN_FORMAT2
static char * handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7371
static int iax2_transfer(struct ast_channel *c, const char *dest)
Definition chan_iax2.c:5917
static int iax2_transmit(struct iax_frame *fr)
Definition chan_iax2.c:4420
#define IAX_SENDANI
Definition chan_iax2.c:542
struct iax_frame * last
Definition chan_iax2.c:1018
static void __auth_reject(const void *nothing)
Definition chan_iax2.c:9477
static int adsi
Definition chan_iax2.c:514
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:6518
iax2_thread_type
Definition chan_iax2.c:1135
@ IAX_THREAD_TYPE_DYNAMIC
Definition chan_iax2.c:1137
@ IAX_THREAD_TYPE_POOL
Definition chan_iax2.c:1136
#define CALLNO_ENTRY_GET_CALLNO(a)
Definition chan_iax2.c:993
static int iax2_getpeertrunk(struct ast_sockaddr addr)
Definition chan_iax2.c:5937
static int attempt_transmit(const void *data)
Definition chan_iax2.c:3717
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
Definition chan_iax2.c:6629
static struct ast_netsock_list * outsock
Definition chan_iax2.c:404
static void prune_users(void)
#define DEFAULT_CONTEXT
Definition chan_iax2.c:357
static void user_destructor(void *obj)
static struct ao2_container * iax_transfercallno_pvts
Another container of iax2_pvt structures.
Definition chan_iax2.c:1256
static struct iax2_user * find_user(const char *name)
Definition chan_iax2.c:2120
static int resyncthreshold
Definition chan_iax2.c:373
#define IAX_RECVCONNECTEDLINE
Definition chan_iax2.c:563
static void register_peer_exten(struct iax2_peer *peer, int onoff)
Definition chan_iax2.c:9055
static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
#define MAX_RETRY_TIME
Definition chan_iax2.c:742
static int iaxdynamicthreadnum
Definition chan_iax2.c:760
static ast_mutex_t callno_pool_lock
Definition chan_iax2.c:1001
#define TRUNK_CALL_START
Definition chan_iax2.c:1260
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7909
#define MAX_TRUNKDATA
Definition chan_iax2.c:377
static int trunk_maxmtu
Definition chan_iax2.c:355
#define DEFAULT_FREQ_OK
Definition chan_iax2.c:432
static void free_context(struct iax2_context *con)
static char * handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7564
#define CALLNO_ENTRY_SET_VALIDATED(a)
Definition chan_iax2.c:991
static uint16_t total_nonval_callno_used
Definition chan_iax2.c:1061
static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition chan_iax2.c:8797
#define IAX_DEBUGDIGEST(msg, key)
Definition chan_iax2.c:480
static const char tdesc[]
Definition chan_iax2.c:347
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
Parses an IAX dial string into its component parts.
Definition chan_iax2.c:5145
static int global_rtautoclear
Definition chan_iax2.c:566
static void iax2_destroy(int callno)
Definition chan_iax2.c:3545
static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
Definition chan_iax2.c:7351
static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
Definition chan_iax2.c:9776
#define CALLNO_TO_PTR(a)
Definition chan_iax2.c:330
static struct iax_frame * iaxfrdup2(struct iax_frame *fr)
Definition chan_iax2.c:2372
static int transmit_frame(void *data)
Definition chan_iax2.c:4393
static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
static int iax2_answer(struct ast_channel *c)
Definition chan_iax2.c:5857
static int iax2_authmethods
Definition chan_iax2.c:517
static const char * iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
Definition chan_iax2.c:2001
static void set_hangup_source_and_cause(int callno, unsigned char causecode)
#define IAX_RTUPDATE
Definition chan_iax2.c:553
#define IAX_QUELCH
Definition chan_iax2.c:546
static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
part of the IAX2 dial plan switch interface
static void __send_ping(const void *data)
Definition chan_iax2.c:1802
static struct iax2_peer * find_peer(const char *name, int realtime)
Definition chan_iax2.c:2095
static char * handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7714
#define MIN_RETRY_TIME
Definition chan_iax2.c:741
static int iaxactivethreadcount
Definition chan_iax2.c:761
static int check_srcaddr(struct ast_sockaddr *addr)
Check if address can be used as packet source.
#define IAX_MAXAUTHREQ
Definition chan_iax2.c:558
static void insert_idle_thread(struct iax2_thread *thread)
Definition chan_iax2.c:1656
static void acl_change_stasis_unsubscribe(void)
Definition chan_iax2.c:1565
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
Definition chan_iax2.c:2401
static int pvt_cmp_cb(void *obj, void *arg, int flags)
static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:8518
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition chan_iax2.c:1583
static int iaxdefaulttimeout
Definition chan_iax2.c:389
static struct ao2_container * users
Definition chan_iax2.c:1041
static int auth_reject(const void *data)
Definition chan_iax2.c:9497
static int create_callno_pools(void)
Definition chan_iax2.c:3107
static void send_signaling(struct chan_iax2_pvt *pvt)
This function must be called once we are sure the other side has given us a call number....
Definition chan_iax2.c:2244
#define CALLTOKEN_IE_FORMAT
static char * handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:4087
#define IAX_FORCE_ENCRYPT
Definition chan_iax2.c:564
static char * handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static void network_change_stasis_subscribe(void)
Definition chan_iax2.c:1540
static struct ast_switch iax2_switch
iax_transfer_state
Definition chan_iax2.c:708
@ TRANSFER_MEDIA
Definition chan_iax2.c:718
@ TRANSFER_NONE
Definition chan_iax2.c:709
@ TRANSFER_MPASSTHROUGH
Definition chan_iax2.c:717
@ TRANSFER_MEDIAPASS
Definition chan_iax2.c:719
@ TRANSFER_PASSTHROUGH
Definition chan_iax2.c:713
@ TRANSFER_MRELEASED
Definition chan_iax2.c:716
@ TRANSFER_BEGIN
Definition chan_iax2.c:710
@ TRANSFER_MREADY
Definition chan_iax2.c:715
@ TRANSFER_READY
Definition chan_iax2.c:711
@ TRANSFER_MBEGIN
Definition chan_iax2.c:714
@ TRANSFER_RELEASED
Definition chan_iax2.c:712
static void poke_all_peers(void)
#define IAX_SENDCONNECTEDLINE
Definition chan_iax2.c:562
static int(* iax2_regfunk)(const char *username, int onoff)
Definition chan_iax2.c:407
static int network_change_sched_cb(const void *data)
Definition chan_iax2.c:1570
static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition chan_iax2.c:3320
static int __do_deliver(void *data)
Definition chan_iax2.c:3426
#define IAX_RTCACHEFRIENDS
Definition chan_iax2.c:552
#define IAX_RTIGNOREREGEXPIRE
Definition chan_iax2.c:555
static char * papp
static int socket_process(struct iax2_thread *thread)
static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
Definition chan_iax2.c:7522
static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
Definition chan_iax2.c:9733
static int iax2_poke_noanswer(const void *data)
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
Definition chan_iax2.c:2991
static char * handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:2922
static char * handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:4000
static int authdebug
Definition chan_iax2.c:382
static struct ast_taskprocessor * transmit_processor
Definition chan_iax2.c:1020
static int iaxdefaultdpcache
Definition chan_iax2.c:387
static int trunk_nmaxmtu
Definition chan_iax2.c:355
static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
#define DEFAULT_MAXMS
Definition chan_iax2.c:431
static int send_lagrq(const void *data)
Definition chan_iax2.c:1890
static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
Parse the "sourceaddress" value, lookup in netsock list and set peer's sockfd. Defaults to defaultsoc...
static int peercnt_add(struct ast_sockaddr *addr)
Definition chan_iax2.c:2717
static int iax2_do_register(struct iax2_registry *reg)
static int iax2_register(const char *value, int lineno)
Definition chan_iax2.c:9019
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
Definition chan_iax2.c:4444
static struct ast_timer * timer
Definition chan_iax2.c:401
static void __send_lagrq(const void *data)
Definition chan_iax2.c:1866
static void unlink_peer(struct iax2_peer *peer)
Definition chan_iax2.c:9074
static int authenticate_request(int call_num)
Definition chan_iax2.c:8210
static struct iax2_peer * peer_unref(struct iax2_peer *peer)
Definition chan_iax2.c:2114
static int iax2_append_register(const char *hostname, const char *username, const char *secret, const char *porta)
Definition chan_iax2.c:8977
static int maxauthreq
Definition chan_iax2.c:368
static int firmware_show_callback(struct ast_iax2_firmware_header *header, void *user_data)
Definition chan_iax2.c:7358
static int get_from_jb(const void *p)
Definition chan_iax2.c:4314
static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
Definition chan_iax2.c:9834
static int max_reg_expire
Definition chan_iax2.c:397
iax_reg_state
Definition chan_iax2.c:698
@ REG_STATE_REGSENT
Definition chan_iax2.c:700
@ REG_STATE_TIMEOUT
Definition chan_iax2.c:704
@ REG_STATE_AUTHSENT
Definition chan_iax2.c:701
@ REG_STATE_NOAUTH
Definition chan_iax2.c:705
@ REG_STATE_REGISTERED
Definition chan_iax2.c:702
@ REG_STATE_REJECTED
Definition chan_iax2.c:703
@ REG_STATE_UNREGISTERED
Definition chan_iax2.c:699
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
Definition chan_iax2.c:5569
static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
Definition chan_iax2.c:6202
#define ACN_FORMAT1
#define DEFAULT_RETRY_TIME
Definition chan_iax2.c:334
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
peer_status: Report Peer status in character string
Definition chan_iax2.c:3878
static void set_config_destroy(void)
static int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
Definition chan_iax2.c:3171
#define IAX_RTSAVE_SYSNAME
Definition chan_iax2.c:543
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
Definition chan_iax2.c:1967
static int iax2_delete_from_sched(const void *data)
Definition chan_iax2.c:2163
static int lagrq_time
Definition chan_iax2.c:371
static char * handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7810
#define DEFAULT_FREQ_NOTOK
Definition chan_iax2.c:433
static void update_jbsched(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:4194
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2504
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2664
static int trunkmaxsize
Definition chan_iax2.c:380
@ NEW_PREVENT
Definition chan_iax2.c:2391
@ NEW_ALLOW
Definition chan_iax2.c:2393
@ NEW_FORCE
Definition chan_iax2.c:2395
@ NEW_ALLOW_CALLTOKEN_VALIDATED
Definition chan_iax2.c:2398
static void handle_deferred_full_frames(struct iax2_thread *thread)
Handle any deferred full frames for this thread.
Definition chan_iax2.c:9907
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
Definition chan_iax2.c:7630
static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
static int test_losspct
Definition chan_iax2.c:502
static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition chan_iax2.c:6668
static int srvlookup
Definition chan_iax2.c:399
static void iax_pvt_callid_set(int callno, ast_callid callid)
Definition chan_iax2.c:1218
static void __get_from_jb(const void *p)
Definition chan_iax2.c:4211
static int iax2_encryption
Definition chan_iax2.c:516
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
Definition chan_iax2.c:2808
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition chan_iax2.c:6576
static struct call_number_pool callno_pool
Definition chan_iax2.c:1004
static pthread_t netthreadid
Definition chan_iax2.c:521
#define CALLNO_ENTRY_TO_PTR(a)
Definition chan_iax2.c:989
static int trunkfreq
Definition chan_iax2.c:379
static void build_rand_pad(unsigned char *buf, ssize_t len)
Definition chan_iax2.c:6486
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
Definition chan_iax2.c:1196
static char * handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7784
static char * handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7481
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data)
Definition chan_iax2.c:1772
static int socket_read(int *id, int fd, short events, void *cbdata)
Definition chan_iax2.c:9968
static int peer_delme_cb(void *obj, void *arg, int flags)
static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
Definition chan_iax2.c:4719
static char * auth_method_names(int authmethods, char *restrict buf)
Get names of all auth methods.
Definition chan_iax2.c:452
static int user_hash_cb(const void *obj, const int flags)
Definition chan_iax2.c:2071
static void peer_destructor(void *obj)
static void __iax2_do_register_s(const void *data)
Definition chan_iax2.c:8736
#define IAX_USEJITTERBUF
Definition chan_iax2.c:540
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int command, int ts, unsigned char seqno, int sockfd, struct iax_ie_data *ied)
Definition chan_iax2.c:4883
static void jb_warning_output(const char *fmt,...)
Definition chan_iax2.c:1306
static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 switch interface.
calltoken_peer_enum
Call token validation settings.
Definition chan_iax2.c:573
@ CALLTOKEN_DEFAULT
Default calltoken required unless the ip is in the ignorelist.
Definition chan_iax2.c:575
@ CALLTOKEN_AUTO
Require call token validation after a successful registration using call token validation occurs.
Definition chan_iax2.c:580
@ CALLTOKEN_NO
Do not require call token validation.
Definition chan_iax2.c:582
@ CALLTOKEN_YES
Require call token validation.
Definition chan_iax2.c:577
static int get_encrypt_methods(const char *s)
Definition chan_iax2.c:1852
static int jittertargetextra
Definition chan_iax2.c:375
static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 Switch interface.
static struct ast_flags64 globalflags
Definition chan_iax2.c:519
static struct iax2_dpcache * find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
static iax2_format uncompress_subclass(unsigned char csub)
Definition chan_iax2.c:1919
static void * network_thread(void *ignore)
static char * handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7326
static int iax2_is_control_frame_allowed(int subtype)
Definition chan_iax2.c:1443
static void network_change_stasis_unsubscribe(void)
Definition chan_iax2.c:1550
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
Definition chan_iax2.c:4677
static struct io_context * io
Definition chan_iax2.c:493
static int trunk_timed
Definition chan_iax2.c:355
static char * complete_iax2_unregister(const char *line, const char *word, int pos, int state)
Definition chan_iax2.c:7301
static struct stasis_subscription * network_change_sub
Definition chan_iax2.c:364
static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
Definition chan_iax2.c:8173
#define PTR_TO_CALLNO_ENTRY(a)
Definition chan_iax2.c:988
static struct ao2_container * calltoken_ignores
Definition chan_iax2.c:1050
static void * iax2_dup_variable_datastore(void *)
Definition chan_iax2.c:1614
static struct iax2_codec_pref prefs_global
Definition chan_iax2.c:345
iax2_state
Definition chan_iax2.c:523
@ IAX_STATE_TBD
Definition chan_iax2.c:526
@ IAX_STATE_AUTHENTICATED
Definition chan_iax2.c:525
@ IAX_STATE_STARTED
Definition chan_iax2.c:524
static struct iax2_user * realtime_user(const char *username, struct ast_sockaddr *addr)
Definition chan_iax2.c:4602
#define IAX2_TRUNK_PREFACE
Definition chan_iax2.c:675
static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
Acknowledgment received for OUR registration.
Definition chan_iax2.c:8911
static void __iax2_poke_peer_s(const void *data)
Definition chan_iax2.c:9586
static int load_module(void)
Load the module.
static int iax2_vnak(int callno)
Definition chan_iax2.c:9568
#define IAX_CAPABILITY_MEDBANDWIDTH
Definition chan_iax2.c:412
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
Definition chan_iax2.c:2015
#define DEFAULT_TRUNKDATA
Definition chan_iax2.c:747
static char * handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Show one peer in detail.
Definition chan_iax2.c:3901
static void iax2_process_thread_cleanup(void *data)
#define IAX_TRANSFERMEDIA
Definition chan_iax2.c:557
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
Definition chan_iax2.c:4449
#define IAX_KEYPOPULATED
Definition chan_iax2.c:548
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2537
#define IAX_RTAUTOCLEAR
Definition chan_iax2.c:554
static int registry_authrequest(int callno)
Definition chan_iax2.c:9375
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
#define FORMAT
const char * iax2_getformatname(iax2_format format)
iax2 wrapper function for ast_getformatname
Definition chan_iax2.c:1989
#define DEFAULT_THREAD_COUNT
Definition chan_iax2.c:332
static int iaxdebug
Definition chan_iax2.c:498
static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
static void iax2_free_variable_datastore(void *)
Definition chan_iax2.c:1638
uint16_t callno_entry
Definition chan_iax2.c:777
static int iax2_poke_peer_s(const void *data)
Definition chan_iax2.c:9593
static int addr_range_delme_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2524
static struct iax2_thread * find_idle_thread(void)
Definition chan_iax2.c:1671
static 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)
#define IAX_DYNAMIC
Definition chan_iax2.c:541
static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
Definition chan_iax2.c:4911
static int max_retries
Definition chan_iax2.c:369
static void delete_users(void)
#define MIN_REUSE_TIME
Definition chan_iax2.c:340
#define FORMAT2
#define IAX_TEMPONLY
Definition chan_iax2.c:537
#define IAX_DELAYPBXSTART
Definition chan_iax2.c:559
static int cache_get_callno_locked(const char *data)
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition chan_iax2.c:1265
static int unload_module(void)
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2495
static struct chan_iax2_pvt * iaxs[IAX_MAX_CALLS]
an array of iax2 pvt structures
Definition chan_iax2.c:1211
static int reload(void)
static int peer_set_sock_cb(void *obj, void *arg, int flags)
static int amaflags
Definition chan_iax2.c:513
static void stop_stuff(int callno)
Definition chan_iax2.c:9472
static char * handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:6910
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition chan_iax2.c:9604
static void log_jitterstats(unsigned short callno)
Definition chan_iax2.c:9864
static struct iax2_peer * peer_ref(struct iax2_peer *peer)
Definition chan_iax2.c:2108
static ast_callid iax_pvt_callid_get(int callno)
Definition chan_iax2.c:1213
#define IAX_CAPABILITY_LOWBANDWIDTH
Definition chan_iax2.c:422
static void cleanup_thread_list(void *head)
static int iaxtrunkdebug
Definition chan_iax2.c:500
static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
callback to display iax peers in manager format
Definition chan_iax2.c:7420
static int iax2_queue_frame(int callno, struct ast_frame *f)
Queue a frame to a call's owning asterisk channel.
Definition chan_iax2.c:3339
static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
Definition chan_iax2.c:8261
static int iax2_sendtext(struct ast_channel *c, const char *text)
Definition chan_iax2.c:4437
static struct ast_sockaddr debugaddr
Definition chan_iax2.c:1263
static int send_packet(struct iax_frame *f)
Definition chan_iax2.c:3488
static char language[MAX_LANGUAGE]
Definition chan_iax2.c:361
static char accountcode[AST_MAX_ACCOUNT_CODE]
Definition chan_iax2.c:510
static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
Definition chan_iax2.c:8189
static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
Definition chan_iax2.c:6528
static char * handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7260
#define IAX_ALLOWFWDOWNLOAD
Definition chan_iax2.c:560
#define IAX_CODEC_USER_FIRST
Definition chan_iax2.c:549
static int iax2_lock_callno_unless_destroyed(int callno)
Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
Definition chan_iax2.c:1784
static struct call_number_pool callno_pool_trunk
Definition chan_iax2.c:1007
static uint16_t global_maxcallno
Definition chan_iax2.c:1056
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:2514
#define CALLTOKEN_HASH_FORMAT
#define IAX_DELME
Definition chan_iax2.c:536
@ CACHE_FLAG_TIMEOUT
Definition chan_iax2.c:1097
@ CACHE_FLAG_EXISTS
Definition chan_iax2.c:1089
@ CACHE_FLAG_UNKNOWN
Definition chan_iax2.c:1101
@ CACHE_FLAG_MATCHMORE
Definition chan_iax2.c:1103
@ CACHE_FLAG_CANEXIST
Definition chan_iax2.c:1093
@ CACHE_FLAG_PENDING
Definition chan_iax2.c:1095
@ CACHE_FLAG_NONEXISTENT
Definition chan_iax2.c:1091
@ CACHE_FLAG_TRANSMITTED
Definition chan_iax2.c:1099
static int start_network_thread(void)
#define PEERS_FORMAT
Definition chan_iax2.c:6996
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
Definition chan_iax2.c:6337
unsigned int cos
Definition chan_iax2.c:393
callno_type
Definition chan_iax2.c:983
@ CALLNO_TYPE_TRUNK
Definition chan_iax2.c:985
@ CALLNO_TYPE_NORMAL
Definition chan_iax2.c:984
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data)
Definition chan_iax2.c:1766
static char mohsuggest[MAX_MUSICCLASS]
Definition chan_iax2.c:512
static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
Definition chan_iax2.c:3194
static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition chan_iax2.c:6512
static struct @118 qos
static void build_callno_limits(struct ast_variable *v)
Definition chan_iax2.c:2826
static void __attempt_transmit(const void *data)
Definition chan_iax2.c:3634
static struct ast_cli_entry cli_iax2[]
static unsigned int iax2_datetime(const char *tz)
Definition chan_iax2.c:4857
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
Definition chan_iax2.c:6696
#define IAX_CODEC_NOPREFS
Definition chan_iax2.c:550
static int auto_hangup(const void *data)
Definition chan_iax2.c:9541
static char * handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition chan_iax2.c:7191
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition chan_iax2.c:1597
static char mohinterpret[MAX_MUSICCLASS]
Definition chan_iax2.c:511
static const struct ast_datastore_info iax2_variable_datastore_info
Definition chan_iax2.c:1608
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
Definition chan_iax2.c:3140
static int iax2_do_register_s(const void *data)
Definition chan_iax2.c:8754
static int iax2_devicestate(const char *data)
Part of the device state notification system —.
static void peercnt_remove(struct peercnt *peercnt)
Definition chan_iax2.c:2768
static int network_change_sched_id
Definition chan_iax2.c:366
static int expire_registry(const void *data)
Definition chan_iax2.c:9134
#define MAX_PEER_BUCKETS
Definition chan_iax2.c:1036
static void iax2_frame_free(struct iax_frame *fr)
Definition chan_iax2.c:2216
static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
Definition chan_iax2.c:6552
static void requirecalltoken_mark_auto(const char *name, int subclass)
Definition chan_iax2.c:5003
static int defaultsockfd
Definition chan_iax2.c:405
static int iaxmaxthreadcount
Definition chan_iax2.c:758
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
Definition chan_iax2.c:2555
static struct ao2_container * iax_peercallno_pvts
Another container of iax2_pvt structures.
Definition chan_iax2.c:1240
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
Definition chan_iax2.c:7895
static int make_trunk(unsigned short callno, int locked)
Definition chan_iax2.c:2419
static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Verify inbound registration.
Definition chan_iax2.c:8356
static int global_max_trunk_mtu
Definition chan_iax2.c:354
static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
Definition chan_iax2.c:9556
static const char type[]
struct ast_sockaddr bindaddr
static char version[AST_MAX_EXTENSION]
static const char config[]
static int transfer(void *data)
static int reload_config(void)
General Asterisk PBX channel definitions.
void ast_channel_exten_set(struct ast_channel *chan, const char *value)
const char * ast_channel_name(const struct ast_channel *chan)
#define ast_channel_alloc_with_endpoint(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag, endpoint,...)
Definition channel.h:1303
void * ast_channel_tech_pvt(const struct ast_channel *chan)
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition channel.c:2376
void ast_hangup(struct ast_channel *chan)
Hang up a channel.
Definition channel.c:2552
#define AST_BRIDGE_DTMF_CHANNEL_0
Report DTMF on channel 0.
Definition channel.h:2420
#define ast_channel_alloc(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag,...)
Create a channel structure.
Definition channel.h:1299
int ast_queue_hangup(struct ast_channel *chan)
Queue a hangup frame.
Definition channel.c:1182
int ast_party_id_presentation(const struct ast_party_id *id)
Determine the overall presentation value for the given party.
Definition channel.c:1808
#define DATASTORE_INHERIT_FOREVER
Definition channel.h:194
void ast_channel_nativeformats_set(struct ast_channel *chan, struct ast_format_cap *value)
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
Destroy the connected line information contents.
Definition channel.c:2059
struct ast_channel * ast_waitfor_n(struct ast_channel **chan, int n, int *ms)
Waits for input on a group of channels Wait for input on an array of channels for a given # of millis...
Definition channel.c:3173
#define ast_channel_lock(chan)
Definition channel.h:2982
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
struct ast_party_redirecting * ast_channel_redirecting(struct ast_channel *chan)
void ast_channel_unregister(const struct ast_channel_tech *tech)
Unregister a channel technology.
Definition channel.c:571
struct ast_flags * ast_channel_flags(struct ast_channel *chan)
#define ast_channel_ref(c)
Increase channel reference count.
Definition channel.h:3007
struct ast_party_connected_line * ast_channel_connected(struct ast_channel *chan)
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f)
Queue one or more frames to a channel's frame queue.
Definition channel.c:1171
const char * ast_channel_context(const struct ast_channel *chan)
int ast_write(struct ast_channel *chan, struct ast_frame *frame)
Write a frame to a channel This function writes the given frame to the indicated channel.
Definition channel.c:5179
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition channel.c:4290
#define AST_BRIDGE_DTMF_CHANNEL_1
Report DTMF on channel 1.
Definition channel.h:2422
#define ast_channel_trylock(chan)
Definition channel.h:2984
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control, const void *data, size_t datalen)
Queue a control frame with payload.
Definition channel.c:1296
ast_channel_adsicpe
Definition channel.h:888
@ AST_ADSI_UNAVAILABLE
Definition channel.h:891
void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
Set caller ID number, name and ANI and generate AMI event.
Definition channel.c:7386
int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
Sets read format on channel chan.
Definition channel.c:5797
@ AST_SOFTHANGUP_DEV
Definition channel.h:1141
void ast_channel_set_rawreadformat(struct ast_channel *chan, struct ast_format *format)
#define MAX_LANGUAGE
Definition channel.h:174
void ast_channel_tech_pvt_set(struct ast_channel *chan, void *value)
int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
Parse connected line indication frame data.
Definition channel.c:8869
int ast_check_hangup(struct ast_channel *chan)
Check to see if a channel is needing hang up.
Definition channel.c:446
int ast_channel_hangupcause(const struct ast_channel *chan)
void ast_channel_set_rawwriteformat(struct ast_channel *chan, struct ast_format *format)
struct ast_party_dialed * ast_channel_dialed(struct ast_channel *chan)
#define AST_MAX_ACCOUNT_CODE
Definition channel.h:172
struct ast_channel * ast_channel_release(struct ast_channel *chan)
Unlink and release reference to a channel.
Definition channel.c:1571
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
Set the source of the hangup in this channel and it's bridge.
Definition channel.c:2510
void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
Sets the HANGUPCAUSE hash and optionally the SIP_CAUSE hash on the given channel.
Definition channel.c:4380
int ast_queue_unhold(struct ast_channel *chan)
Queue an unhold frame.
Definition channel.c:1274
ast_bridge_result
Definition channel.h:208
@ AST_BRIDGE_FAILED_NOWARN
Definition channel.h:211
@ AST_BRIDGE_RETRY
Definition channel.h:212
@ AST_BRIDGE_COMPLETE
Definition channel.h:209
@ AST_BRIDGE_FAILED
Definition channel.h:210
int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
Queue a hold frame.
Definition channel.c:1249
void ast_channel_set_readformat(struct ast_channel *chan, struct ast_format *format)
#define AST_CHANNEL_NAME
Definition channel.h:173
int ast_channel_register(const struct ast_channel_tech *tech)
Register a channel technology (a new channel driver) Called by a channel module to register the kind ...
Definition channel.c:540
void ast_channel_softhangup_internal_flag_add(struct ast_channel *chan, int value)
#define ast_channel_unref(c)
Decrease channel reference count.
Definition channel.h:3018
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition channel.c:5838
#define AST_MAX_CONTEXT
Definition channel.h:135
void ast_party_connected_line_init(struct ast_party_connected_line *init)
Initialize the given connected line structure.
Definition channel.c:2009
void ast_channel_amaflags_set(struct ast_channel *chan, enum ama_flags value)
const char * ast_channel_language(const struct ast_channel *chan)
void ast_channel_context_set(struct ast_channel *chan, const char *value)
enum ama_flags ast_channel_string2amaflag(const char *flag)
Convert a string to a detail record AMA flag.
Definition channel.c:4394
@ AST_FLAG_DISABLE_DEVSTATE_CACHE
Definition channel.h:1049
struct ast_party_caller * ast_channel_caller(struct ast_channel *chan)
void ast_channel_callid_set(struct ast_channel *chan, ast_callid value)
void ast_channel_hangupcause_set(struct ast_channel *chan, int value)
void ast_channel_adsicpe_set(struct ast_channel *chan, enum ast_channel_adsicpe value)
void ast_channel_tech_set(struct ast_channel *chan, const struct ast_channel_tech *value)
#define ast_channel_unlock(chan)
Definition channel.h:2983
#define AST_MAX_EXTENSION
Definition channel.h:134
@ AST_CHAN_TP_WANTSJITTER
Channels have this property if they can accept input with jitter; i.e. most VoIP channels.
Definition channel.h:980
void ast_channel_set_writeformat(struct ast_channel *chan, struct ast_format *format)
#define MAX_MUSICCLASS
Definition channel.h:175
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition channel.c:2390
struct ast_format * ast_channel_readformat(struct ast_channel *chan)
uint64_t iax2_format_compatibility_best(uint64_t formats)
Pick the best format from the given bitfield formats.
uint64_t iax2_format_compatibility_cap2bitfield(const struct ast_format_cap *cap)
Convert a format capabilities structure to a bitfield.
int iax2_format_compatibility_bitfield2cap(uint64_t bitfield, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure.
Media Format Bitfield Compatibility API.
ast_channel_state
ast_channel states
@ AST_STATE_RING
@ AST_STATE_RINGING
@ AST_STATE_DOWN
@ AST_STATE_RESERVED
int ast_setstate(struct ast_channel *chan, enum ast_channel_state)
Change the state of a channel.
Definition channel.c:7438
static struct ast_channel * callback(struct ast_channelstorage_instance *driver, ao2_callback_data_fn *cb_fn, void *arg, void *data, int ao2_flags, int rdlock)
const char * ast_var_name(const struct ast_var_t *var)
Definition chanvars.c:60
#define ast_var_assign(name, value)
Definition chanvars.h:40
const char * ast_var_value(const struct ast_var_t *var)
Definition chanvars.c:80
void ast_var_delete(struct ast_var_t *var)
Definition extconf.c:2469
Standard Command Line Interface.
#define CLI_SHOWUSAGE
Definition cli.h:45
#define CLI_SUCCESS
Definition cli.h:44
#define AST_CLI_DEFINE(fn, txt,...)
Definition cli.h:197
#define RESULT_SHOWUSAGE
Definition cli.h:41
void ast_cli(int fd, const char *fmt,...)
Definition clicompat.c:6
#define RESULT_SUCCESS
Definition cli.h:40
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
Definition main/cli.c:1931
@ CLI_HANDLER
Definition cli.h:154
@ CLI_INIT
Definition cli.h:152
@ CLI_GENERATE
Definition cli.h:153
#define CLI_FAILURE
Definition cli.h:46
#define RESULT_FAILURE
Definition cli.h:42
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition cli.h:265
@ AST_MEDIA_TYPE_AUDIO
Definition codec.h:32
@ AST_MEDIA_TYPE_UNKNOWN
Definition codec.h:31
unsigned int ast_codec_samples_count(struct ast_frame *frame)
Get the number of samples contained within a frame.
Definition codec.c:379
int iax2_codec_pref_string(struct iax2_codec_pref *pref, char *buf, size_t size)
Dump audio codec preference list into a string.
Definition codec_pref.c:178
void iax2_codec_pref_prepend(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing, int only_if_existing)
Prepend an audio codec to a preference list, removing it first if it was already there.
Definition codec_pref.c:432
uint64_t iax2_codec_pref_order_value_to_format_bitfield(int order_value)
Convert an iax2_codec_pref order value into a format bitfield.
Definition codec_pref.c:367
uint64_t iax2_codec_pref_from_bitfield(struct iax2_codec_pref *pref, uint64_t bitfield)
Create codec preference list from the given bitfield formats.
Definition codec_pref.c:481
struct ast_format * iax2_codec_pref_index(struct iax2_codec_pref *pref, int idx, struct ast_format **result)
Codec located at a particular place in the preference index.
Definition codec_pref.c:77
void iax2_codec_pref_convert(struct iax2_codec_pref *pref, char *buf, size_t size, int right)
Shift an audio codec preference list up or down 65 bytes so that it becomes an ASCII string.
Definition codec_pref.c:44
void iax2_codec_pref_remove_missing(struct iax2_codec_pref *pref, uint64_t bitfield)
Removes format from the pref list that aren't in the bitfield.
Definition codec_pref.c:288
void iax2_codec_pref_append(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing)
Append a audio codec to a preference list, removing it first if it was already there.
Definition codec_pref.c:420
int iax2_codec_pref_to_cap(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Convert a preference structure to a capabilities structure.
Definition codec_pref.c:91
int iax2_codec_pref_best_bitfield2cap(uint64_t bitfield, struct iax2_codec_pref *prefs, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure in the "best" order.
Definition codec_pref.c:112
Media Format Bitfield Compatibility API.
short word
#define attribute_pure
Definition compiler.h:35
#define SENTINEL
Definition compiler.h:87
Provide cryptographic signature routines.
int AST_OPTIONAL_API_NAME() ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
Check the authenticity of a message signature using a given public key.
Definition res_crypto.c:673
int AST_OPTIONAL_API_NAME() ast_aes_set_encrypt_key(const unsigned char *key, ast_aes_encrypt_key *ctx)
Set an encryption key.
Definition res_crypto.c:700
int AST_OPTIONAL_API_NAME() ast_sign(struct ast_key *key, char *msg, char *sig)
Sign a message signature using a given private key.
Definition res_crypto.c:584
int AST_OPTIONAL_API_NAME() ast_aes_decrypt(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *key)
AES decrypt data.
Definition res_crypto.c:790
#define AST_KEY_PUBLIC
Definition crypto.h:46
#define AST_KEY_PRIVATE
Definition crypto.h:47
struct ast_key *AST_OPTIONAL_API_NAME() ast_key_get(const char *kname, int ktype)
Retrieve a key.
Definition res_crypto.c:149
int AST_OPTIONAL_API_NAME() ast_aes_set_decrypt_key(const unsigned char *key, ast_aes_decrypt_key *ctx)
Set a decryption key.
Definition res_crypto.c:709
int AST_OPTIONAL_API_NAME() ast_aes_encrypt(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *key)
AES encrypt data.
Definition res_crypto.c:749
#define ast_datastore_alloc(info, uid)
Definition datastore.h:85
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition datastore.c:68
Device state management.
@ AST_DEVSTATE_CACHABLE
Definition devicestate.h:70
int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt,...)
Tells Asterisk the State for Device is changed.
@ AST_DEVICE_UNKNOWN
Definition devicestate.h:53
@ AST_DEVICE_INVALID
Definition devicestate.h:57
@ AST_DEVICE_NOT_INUSE
Definition devicestate.h:54
@ AST_DEVICE_UNAVAILABLE
Definition devicestate.h:58
Background DNS update manager.
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
Free a DNS manager entry.
Definition dnsmgr.c:136
int ast_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service)
Allocate and initialize a DNS manager entry.
Definition dnsmgr.c:191
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
Check is see if a dnsmgr entry has changed.
Definition dnsmgr.c:247
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
Force a refresh of a dnsmgr entry.
Definition dnsmgr.c:239
threshold
Definition dsp.h:73
char * end
Definition eagi_proxy.c:73
char buf[BUFSIZE]
Definition eagi_proxy.c:66
@ AST_ENDPOINT_OFFLINE
Definition endpoints.h:55
@ AST_ENDPOINT_ONLINE
Definition endpoints.h:57
void ast_endpoint_set_state(struct ast_endpoint *endpoint, enum ast_endpoint_state state)
Updates the state of the given endpoint.
void ast_endpoint_shutdown(struct ast_endpoint *endpoint)
Shutsdown an ast_endpoint.
struct ast_endpoint * ast_endpoint_create(const char *tech, const char *resource)
Create an endpoint struct.
#define abs(x)
Definition f2c.h:195
Call Parking and Pickup API Includes code and algorithms from the Zapata library.
int iax_firmware_get_version(const char *dev, uint16_t *version)
Definition firmware.c:263
void iax_firmware_reload(void)
Definition firmware.c:206
void iax_firmware_unload(void)
Definition firmware.c:250
int iax_firmware_append(struct iax_ie_data *ied, const char *dev, unsigned int desc)
Definition firmware.c:283
void iax_firmware_traverse(const char *filter, int(*callback)(struct ast_iax2_firmware_header *header, void *data), void *data)
Definition firmware.c:321
IAX Firmware Support header file.
enum ast_media_type ast_format_get_type(const struct ast_format *format)
Get the media type of a format.
Definition format.c:354
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition format.c:379
enum ast_format_cmp_res ast_format_cmp(const struct ast_format *format1, const struct ast_format *format2)
Compare two formats.
Definition format.c:201
@ AST_FORMAT_CMP_EQUAL
Definition format.h:36
const char * ast_format_get_name(const struct ast_format *format)
Get the name associated with a format.
Definition format.c:334
unsigned int ast_format_get_default_ms(const struct ast_format *format)
Get the default framing size (in milliseconds) for a format.
Definition format.c:359
Media Format Cache API.
struct ast_format * ast_format_slin
Built-in cached signed linear 8kHz format.
struct ast_format * ast_format_none
Built-in "null" format.
Format Capabilities API.
#define AST_FORMAT_CAP_NAMES_LEN
Definition format_cap.h:324
int ast_format_cap_append_by_type(struct ast_format_cap *cap, enum ast_media_type type)
Add all codecs Asterisk knows about for a specific type to the capabilities structure.
Definition format_cap.c:216
struct ast_format * ast_format_cap_get_format(const struct ast_format_cap *cap, int position)
Get the format at a specific index.
Definition format_cap.c:400
unsigned int ast_format_cap_get_format_framing(const struct ast_format_cap *cap, const struct ast_format *format)
Get the framing for a format.
Definition format_cap.c:443
int ast_format_cap_update_by_allow_disallow(struct ast_format_cap *cap, const char *list, int allowing)
Parse an "allow" or "deny" list and modify a format capabilities structure accordingly.
Definition format_cap.c:320
int ast_format_cap_get_compatible(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2, struct ast_format_cap *result)
Find the compatible formats between two capabilities structures.
Definition format_cap.c:628
@ AST_FORMAT_CAP_FLAG_DEFAULT
Definition format_cap.h:38
const char * ast_format_cap_get_names(const struct ast_format_cap *cap, struct ast_str **buf)
Get the names of codecs of a set of formats.
Definition format_cap.c:734
int ast_format_cap_identical(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2)
Determine if two capabilities structures are identical.
Definition format_cap.c:687
#define ast_format_cap_append(cap, format, framing)
Add format capability to capabilities structure.
Definition format_cap.h:99
#define ast_format_cap_alloc(flags)
Allocate a new ast_format_cap structure.
Definition format_cap.h:49
size_t ast_format_cap_count(const struct ast_format_cap *cap)
Get the number of formats present within the capabilities structure.
Definition format_cap.c:395
struct ast_format * ast_format_cap_get_compatible_format(const struct ast_format_cap *cap, const struct ast_format *format)
Find if input ast_format is within the capabilities of the ast_format_cap object then return the comp...
Definition format_cap.c:546
static const char name[]
Definition format_mp3.c:68
static int exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition func_logic.c:185
static int md5(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition func_md5.c:55
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
Send ack in manager transaction to begin a list.
Definition manager.c:2030
void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
Start the list complete event.
Definition manager.c:2066
const char * astman_get_header(const struct message *m, char *var)
Get header from manager transaction.
Definition manager.c:1649
void astman_send_list_complete_end(struct mansession *s)
End the list complete event.
Definition manager.c:2074
void astman_append(struct mansession *s, const char *fmt,...)
Definition manager.c:1909
int ast_manager_unregister(const char *action)
Unregister a registered manager command.
Definition manager.c:7704
void ast_endpoint_blob_publish(struct ast_endpoint *endpoint, struct stasis_message_type *type, struct ast_json *blob)
Creates and publishes a ast_endpoint_blob message.
void ast_channel_stage_snapshot_done(struct ast_channel *chan)
Clear flag to indicate channel snapshot is being staged, and publish snapshot.
struct stasis_message_type * ast_endpoint_state_type(void)
Message type for endpoint state changes.
void ast_channel_stage_snapshot(struct ast_channel *chan)
Set flag to indicate channel snapshot is being staged.
static int iax2_prov_app(struct ast_channel *chan, const char *data)
const char * ext
Definition http.c:151
Implementation of Inter-Asterisk eXchange, version 2 parser.c parser.h chan_iax2.c.
#define IAX_IE_PASSWORD
Definition iax2.h:137
#define IAX_LINGER_TIMEOUT
Definition iax2.h:126
#define IAX_IE_RR_PKTS
Definition iax2.h:179
#define IAX_DPSTATUS_CANEXIST
Definition iax2.h:218
@ IAX_COMMAND_FWDOWNL
Definition iax2.h:111
@ IAX_COMMAND_TXREL
Definition iax2.h:91
@ IAX_COMMAND_TXMEDIA
Definition iax2.h:115
@ IAX_COMMAND_AUTHREP
Definition iax2.h:60
@ IAX_COMMAND_PROVISION
Definition iax2.h:109
@ IAX_COMMAND_DPREP
Definition iax2.h:79
@ IAX_COMMAND_REGAUTH
Definition iax2.h:67
@ IAX_COMMAND_INVAL
Definition iax2.h:61
@ IAX_COMMAND_REJECT
Definition iax2.h:57
@ IAX_COMMAND_FWDATA
Definition iax2.h:113
@ IAX_COMMAND_ACK
Definition iax2.h:55
@ IAX_COMMAND_PONG
Definition iax2.h:54
@ IAX_COMMAND_LAGRQ
Definition iax2.h:62
@ IAX_COMMAND_HANGUP
Definition iax2.h:56
@ IAX_COMMAND_TXREADY
Definition iax2.h:89
@ IAX_COMMAND_TXACC
Definition iax2.h:87
@ IAX_COMMAND_QUELCH
Definition iax2.h:95
@ IAX_COMMAND_PING
Definition iax2.h:53
@ IAX_COMMAND_TRANSFER
Definition iax2.h:107
@ IAX_COMMAND_LAGRP
Definition iax2.h:63
@ IAX_COMMAND_TXCNT
Definition iax2.h:85
@ IAX_COMMAND_REGACK
Definition iax2.h:69
@ IAX_COMMAND_AUTHREQ
Definition iax2.h:59
@ IAX_COMMAND_TXREJ
Definition iax2.h:93
@ IAX_COMMAND_REGREJ
Definition iax2.h:71
@ IAX_COMMAND_REGREL
Definition iax2.h:73
@ IAX_COMMAND_CALLTOKEN
Definition iax2.h:119
@ IAX_COMMAND_DIAL
Definition iax2.h:81
@ IAX_COMMAND_ACCEPT
Definition iax2.h:58
@ IAX_COMMAND_UNSUPPORT
Definition iax2.h:105
@ IAX_COMMAND_NEW
Definition iax2.h:52
@ IAX_COMMAND_POKE
Definition iax2.h:99
@ IAX_COMMAND_REGREQ
Definition iax2.h:65
@ IAX_COMMAND_VNAK
Definition iax2.h:75
@ IAX_COMMAND_UNQUELCH
Definition iax2.h:97
@ IAX_COMMAND_TXREQ
Definition iax2.h:83
@ IAX_COMMAND_RTKEY
Definition iax2.h:117
@ IAX_COMMAND_DPREQ
Definition iax2.h:77
#define IAX_IE_RR_JITTER
Definition iax2.h:177
#define IAX_MAX_OSPBLOCK_SIZE
Definition iax2.h:192
#define IAX_IE_DNID
Definition iax2.h:143
#define IAX_IE_CALLINGANI2
Definition iax2.h:190
#define IAX_FLAG_SC_LOG
Definition iax2.h:44
#define IAX_IE_DATETIME
Definition iax2.h:161
#define IAX_IE_CAUSE
Definition iax2.h:152
#define IAX_IE_DPSTATUS
Definition iax2.h:150
#define IAX_IE_CALLING_NUMBER
Definition iax2.h:132
#define IAX_IE_TRANSFERID
Definition iax2.h:157
#define IAX_IE_CALLTOKEN
Definition iax2.h:185
#define IAX_IE_CALLING_ANI
Definition iax2.h:133
#define IAX_DEFAULT_PORTNO
Definition iax2.h:128
#define IAX_IE_CALLINGTNS
Definition iax2.h:170
#define IAX_IE_RSA_RESULT
Definition iax2.h:147
#define IAX_IE_MSGCOUNT
Definition iax2.h:154
#define IAX_META_TRUNK_SUPERMINI
Definition iax2.h:207
#define IAX_IE_IAX_UNKNOWN
Definition iax2.h:153
int64_t iax2_format
Definition iax2.h:224
#define IAX_DPSTATUS_NONEXISTENT
Definition iax2.h:219
#define IAX_IE_FORMAT2
Definition iax2.h:188
#define IAX_DPSTATUS_IGNOREPAT
Definition iax2.h:220
#define IAX_IE_CAPABILITY2
Definition iax2.h:187
#define IAX_IE_CALLING_NAME
Definition iax2.h:134
#define IAX_DEFAULT_REG_EXPIRE
Definition iax2.h:123
#define IAX_IE_ADSICPE
Definition iax2.h:142
#define IAX_IE_VARIABLE
Definition iax2.h:183
#define IAX_AUTH_RSA
Definition iax2.h:199
#define IAX_IE_OSPTOKEN
Definition iax2.h:184
#define IAX_IE_LANGUAGE
Definition iax2.h:140
#define IAX_MAX_OSPTOKEN_SIZE
Definition iax2.h:194
#define IAX_IE_RDNIS
Definition iax2.h:158
#define IAX_FLAG_FULL
Definition iax2.h:40
#define IAX_IE_RR_DROPPED
Definition iax2.h:181
#define IAX_MAX_SHIFT
Definition iax2.h:46
#define IAX_IE_FORMAT
Definition iax2.h:139
#define IAX_IE_ENCRYPTION
Definition iax2.h:173
#define IAX_ENCRYPT_AES128
Definition iax2.h:201
#define IAX_AUTH_MD5
Definition iax2.h:198
#define IAX_MAX_OSPBUFF_SIZE
Definition iax2.h:195
#define IAX_IE_FIRMWAREVER
Definition iax2.h:164
#define IAX_FLAG_RETRANS
Definition iax2.h:42
#define IAX_IE_CODEC_PREFS
Definition iax2.h:175
#define IAX_IE_CALLED_NUMBER
Definition iax2.h:131
#define IAX_IE_CAPABILITY
Definition iax2.h:138
#define IAX_DPSTATUS_MATCHMORE
Definition iax2.h:221
#define IAX_IE_PROVISIONING
Definition iax2.h:159
#define IAX_IE_MD5_RESULT
Definition iax2.h:146
#define IAX_PROTO_VERSION
Definition iax2.h:27
#define IAX_IE_AUTOANSWER
Definition iax2.h:155
#define IAX_IE_VERSION
Definition iax2.h:141
#define IAX_ENCRYPT_KEYROTATE
Definition iax2.h:202
#define IAX_IE_RR_OOO
Definition iax2.h:182
#define IAX_IE_CALLNO
Definition iax2.h:151
#define IAX_IE_APPARENT_ADDR
Definition iax2.h:148
#define IAX_AUTH_PLAINTEXT
Definition iax2.h:197
#define IAX_IE_REFRESH
Definition iax2.h:149
#define IAX_MAX_OSPBLOCK_NUM
Definition iax2.h:193
#define IAX_META_TRUNK
Definition iax2.h:204
#define IAX_META_TRUNK_MINI
Definition iax2.h:208
#define IAX_IE_CALLINGPRES
Definition iax2.h:168
#define IAX_IE_CAUSECODE
Definition iax2.h:172
#define IAX_IE_AUTHMETHODS
Definition iax2.h:144
#define IAX_IE_RR_LOSS
Definition iax2.h:178
#define IAX_MAX_CALLS
Definition iax2.h:37
#define IAX_IE_CALLED_CONTEXT
Definition iax2.h:135
#define IAX_IE_CALLINGTON
Definition iax2.h:169
#define IAX_DPSTATUS_EXISTS
Definition iax2.h:217
#define IAX_IE_USERNAME
Definition iax2.h:136
#define IAX_IE_CHALLENGE
Definition iax2.h:145
#define IAX_IE_RR_DELAY
Definition iax2.h:180
Application convenience functions, designed to give consistent look and feel to Asterisk apps.
int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
Determine number of new/old messages in a mailbox.
Definition main/app.c:604
Configuration File Parser.
#define ast_config_load(filename, flags)
Load a config file.
char * ast_category_browse(struct ast_config *config, const char *prev_name)
Browse categories.
Definition extconf.c:3324
int ast_realtime_require_field(const char *family,...) attribute_sentinel
Inform realtime what fields that may be stored.
#define ast_variable_new(name, value, filename)
int ast_unload_realtime(const char *family)
Release any resources cached for a realtime family.
#define CONFIG_STATUS_FILEUNCHANGED
@ CONFIG_FLAG_FILEUNCHANGED
#define CONFIG_STATUS_FILEINVALID
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
Definition extconf.c:1287
int ast_variable_list_replace(struct ast_variable **head, struct ast_variable *replacement)
Replace a variable in the given list with a new value.
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
int ast_update_realtime(const char *family, const char *keyfield, const char *lookup,...) attribute_sentinel
Update realtime configuration.
struct ast_variable * ast_load_realtime(const char *family,...) attribute_sentinel
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition extconf.c:1260
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition extconf.c:1213
Media Format Bitfield Compatibility API.
uint64_t ast_format_compatibility_format2bitfield(const struct ast_format *format)
Convert a format structure to its respective bitfield.
struct ast_format * ast_format_compatibility_bitfield2format(uint64_t bitfield)
Convert a bitfield to its respective format structure.
Asterisk internal frame definitions.
#define ast_frame_byteswap_be(fr)
#define AST_FRAME_DTMF
#define AST_OPTION_RELAXDTMF
#define AST_OPTION_TONE_VERIFY
#define AST_OPTION_RXGAIN
#define AST_OPTION_DIGIT_DETECT
@ AST_TRANSFER_SUCCESS
#define AST_OPTION_OPRMODE
#define ast_frfree(fr)
#define AST_OPTION_TDD
#define AST_OPTION_SECURE_MEDIA
#define AST_OPTION_FLAG_REQUEST
@ AST_FRFLAG_HAS_TIMING_INFO
#define AST_OPTION_FAX_DETECT
#define AST_OPTION_TXGAIN
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
#define AST_OPTION_SECURE_SIGNALING
@ AST_FRAME_DTMF_END
@ AST_FRAME_DTMF_BEGIN
@ AST_FRAME_CONTROL
ast_control_frame_type
Internal control frame subtype field values.
@ AST_CONTROL_SRCUPDATE
@ AST_CONTROL_RECORD_CANCEL
@ AST_CONTROL_PROGRESS
@ AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED
@ AST_CONTROL_OFFHOOK
@ AST_CONTROL_STREAM_RESTART
@ AST_CONTROL_STREAM_SUSPEND
@ AST_CONTROL_RADIO_UNKEY
@ AST_CONTROL_UNHOLD
@ AST_CONTROL_VIDUPDATE
@ AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE
@ AST_CONTROL_STREAM_REVERSE
@ AST_CONTROL_PROCEEDING
@ AST_CONTROL_REDIRECTING
@ AST_CONTROL_TAKEOFFHOOK
@ AST_CONTROL_T38_PARAMETERS
@ AST_CONTROL_READ_ACTION
@ AST_CONTROL_RECORD_STOP
@ AST_CONTROL_CONGESTION
@ AST_CONTROL_PLAYBACK_BEGIN
@ AST_CONTROL_ANSWER
@ AST_CONTROL_RECORD_MUTE
@ AST_CONTROL_RINGING
@ AST_CONTROL_HANGUP
@ AST_CONTROL_STREAM_STOP
@ AST_CONTROL_RADIO_KEY
@ AST_CONTROL_OPTION
@ AST_CONTROL_STREAM_TOPOLOGY_CHANGED
@ AST_CONTROL_CONNECTED_LINE
@ AST_CONTROL_END_OF_Q
@ AST_CONTROL_TRANSFER
@ AST_CONTROL_STREAM_FORWARD
@ AST_CONTROL_FLASH
@ AST_CONTROL_RECORD_SUSPEND
@ AST_CONTROL_SRCCHANGE
@ AST_CONTROL_INCOMPLETE
@ _XXX_AST_CONTROL_T38
@ AST_CONTROL_MASQUERADE_NOTIFY
@ AST_CONTROL_PVT_CAUSE_CODE
@ AST_CONTROL_UPDATE_RTP_PEER
#define AST_OPTION_AUDIO_MODE
struct ast_frame ast_null_frame
Definition main/frame.c:79
void ast_callid_strnprint(char *buffer, size_t buffer_size, ast_callid callid)
copy a string representation of the callid into a target string
Definition logger.c:2258
#define ast_debug(level,...)
Log a DEBUG message.
ast_callid ast_read_threadstorage_callid(void)
extracts the callid from the thread
Definition logger.c:2268
int ast_callid_threadassoc_add(ast_callid callid)
Adds a known callid to thread storage of the calling thread.
Definition logger.c:2290
#define AST_CALLID_BUFFER_LENGTH
ast_callid ast_create_callid(void)
factory function to create a new uniquely identifying callid.
Definition logger.c:2263
unsigned int ast_callid
#define VERBOSE_PREFIX_4
int ast_callid_threadassoc_remove(void)
Removes callid from thread storage of the calling thread.
Definition logger.c:2309
#define LOG_ERROR
#define ast_verb(level,...)
#define LOG_NOTICE
#define LOG_WARNING
#define ast_verbose(...)
I/O Management (derived from Cheops-NG)
#define AST_IO_IN
Definition io.h:34
struct io_context * io_context_create(void)
Creates a context Create a context for I/O operations Basically mallocs an IO structure and sets up s...
Definition io.c:81
int * ast_io_add(struct io_context *ioc, int fd, ast_io_cb callback, short events, void *data)
Adds an IO context.
Definition io.c:162
#define AST_IO_PRI
Definition io.h:38
void io_context_destroy(struct io_context *ioc)
Destroys a context.
Definition io.c:107
int ast_io_wait(struct io_context *ioc, int howlong)
Waits for IO.
Definition io.c:278
jitterbuf: an application-independent jitterbuffer jitterbuf.c
void jb_destroy(jitterbuf *jb)
destroy jitterbuf
Definition jitterbuf.c:99
void jb_reset(jitterbuf *jb)
reset jitterbuf
Definition jitterbuf.c:72
enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frame, long now, long interpl)
get a frame for time now (receiver's time) return value is one of JB_OK: You've got frame!...
Definition jitterbuf.c:785
jitterbuf * jb_new(void)
new jitterbuf
Definition jitterbuf.c:86
void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg)
Definition jitterbuf.c:55
enum jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now)
queue a frame
Definition jitterbuf.c:525
long jb_next(jitterbuf *jb)
when is the next frame due out, in receiver's time (0=EMPTY) This value may change as frames are adde...
Definition jitterbuf.c:767
@ JB_TYPE_CONTROL
Definition jitterbuf.h:61
@ JB_TYPE_SILENCE
Definition jitterbuf.h:64
@ JB_TYPE_VOICE
Definition jitterbuf.h:62
enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf)
set jitterbuf conf
Definition jitterbuf.c:825
enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout)
unconditionally get frames from jitterbuf until empty
Definition jitterbuf.c:801
@ JB_EMPTY
Definition jitterbuf.h:52
@ JB_SCHED
Definition jitterbuf.h:56
@ JB_DROP
Definition jitterbuf.h:55
@ JB_NOFRAME
Definition jitterbuf.h:53
@ JB_INTERP
Definition jitterbuf.h:54
@ JB_OK
Definition jitterbuf.h:51
enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats)
get jitterbuf info: only "statistics" may be valid
Definition jitterbuf.c:815
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
Definition json.c:73
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
Definition json.c:612
AST_JSON_INT_T ast_json_int_t
Primarily used to cast when packing to an "I" type.
Definition json.h:87
A set of macros to manage forward-linked lists.
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
#define AST_LIST_INSERT_BEFORE_CURRENT(elm, field)
Inserts a list entry before the current entry during a traversal.
#define AST_LIST_LOCK(head)
Locks a list.
Definition linkedlists.h:40
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
Custom localtime functions for multiple timezones.
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition localtime.c:1739
Asterisk locking-related definitions:
#define ast_cond_destroy(cond)
Definition lock.h:209
#define ast_cond_wait(cond, mutex)
Definition lock.h:212
#define AST_PTHREADT_NULL
Definition lock.h:73
#define ast_cond_init(cond, attr)
Definition lock.h:208
#define ast_cond_timedwait(cond, mutex, time)
Definition lock.h:213
#define ast_mutex_init(pmutex)
Definition lock.h:193
#define DEADLOCK_AVOIDANCE(lock)
Definition lock.h:486
#define ast_mutex_unlock(a)
Definition lock.h:197
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition lock.h:764
#define ast_mutex_trylock(a)
Definition lock.h:198
pthread_cond_t ast_cond_t
Definition lock.h:185
#define ast_mutex_destroy(a)
Definition lock.h:195
#define ast_mutex_lock(a)
Definition lock.h:196
#define AST_MUTEX_DEFINE_STATIC(mutex)
Definition lock.h:527
int ast_atomic_dec_and_test(volatile int *p)
decrement *p by 1 and return true if the variable has reached 0.
Definition lock.h:774
#define ast_cond_signal(cond)
Definition lock.h:210
static char hostname[MAXHOSTNAMELEN]
Definition logger.c:116
int errno
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
#define EVENT_FLAG_REPORTING
Definition manager.h:84
#define EVENT_FLAG_SYSTEM
Definition manager.h:75
#define ast_manager_register_xml(action, authority, func)
Register a manager callback using XML documentation to describe the manager.
Definition manager.h:193
MD5 digest functions.
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition md5.c:72
void MD5Init(struct MD5Context *context)
Definition md5.c:57
void MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], struct MD5Context *context)
Definition md5.c:120
Asterisk module definitions.
@ AST_MODFLAG_LOAD_ORDER
Definition module.h:331
#define ast_module_unref(mod)
Release a reference to the module.
Definition module.h:483
#define ast_module_ref(mod)
Hold a reference to the module.
Definition module.h:457
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition module.h:557
@ AST_MODPRI_CHANNEL_DRIVER
Definition module.h:341
@ AST_MODULE_SUPPORT_CORE
Definition module.h:121
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition module.h:46
int ast_unregister_application(const char *app)
Unregister an application.
Definition pbx_app.c:404
@ AST_MODULE_LOAD_SUCCESS
Definition module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition module.h:78
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition module.h:640
Music on hold handling.
int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
Turn on music on hold on a given channel.
Definition channel.c:7818
void ast_moh_stop(struct ast_channel *chan)
Turn off music on hold on a given channel.
Definition channel.c:7828
Asterisk MWI API.
struct stasis_message_type * ast_mwi_state_type(void)
Get the Stasis Message Bus API message type for MWI messages.
void * ast_mwi_unsubscribe(struct ast_mwi_subscriber *sub)
Unsubscribe from the stasis topic and MWI.
Definition mwi.c:254
struct stasis_cache * ast_mwi_state_cache(void)
Backend cache for ast_mwi_topic_cached().
Definition mwi.c:94
struct ast_mwi_subscriber * ast_mwi_subscribe_pool(const char *mailbox, stasis_subscription_cb callback, void *data)
Add an MWI state subscriber, and stasis subscription to the mailbox.
Definition mwi.c:235
@ AST_AF_UNSPEC
Definition netsock2.h:54
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition netsock2.h:256
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
Definition netsock2.h:517
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
Definition netsock2.h:167
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
Definition netsock2.c:524
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
Definition netsock2.c:590
int ast_sockaddr_apply_netmask(const struct ast_sockaddr *addr, const struct ast_sockaddr *netmask, struct ast_sockaddr *result)
Apply a netmask to an address and store the result in a separate structure.
Definition netsock2.c:357
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
Definition netsock2.c:413
ssize_t ast_sendto(int sockfd, const void *buf, size_t len, int flags, const struct ast_sockaddr *dest_addr)
Wrapper around sendto(2) that uses ast_sockaddr.
Definition netsock2.c:614
int ast_sockaddr_split_hostport(char *str, char **host, char **port, int flags)
Splits a string into its host and port components.
Definition netsock2.c:164
int ast_sockaddr_resolve(struct ast_sockaddr **addrs, const char *str, int flags, int family)
Parses a string with an IPv4 or IPv6 address and place results into an array.
Definition netsock2.c:280
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
Definition netsock2.c:230
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized,...
Definition netsock2.h:127
ssize_t ast_recvfrom(int sockfd, void *buf, size_t len, int flags, struct ast_sockaddr *src_addr)
Wrapper around recvfrom(2) that uses struct ast_sockaddr.
Definition netsock2.c:606
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
Definition netsock2.c:388
static char * ast_sockaddr_stringify_port(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return a port only.
Definition netsock2.h:358
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
Definition netsock2.h:532
static char * ast_sockaddr_stringify_addr(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only.
Definition netsock2.h:286
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Definition netsock2.h:138
int ast_sockaddr_is_ipv4_mapped(const struct ast_sockaddr *addr)
Determine if this is an IPv4-mapped IPv6 address.
Definition netsock2.c:507
int ast_sockaddr_hash(const struct ast_sockaddr *addr)
Computes a hash value from the address. The port is ignored.
Definition netsock2.c:548
Network socket handling.
int ast_netsock_release(struct ast_netsock_list *list)
Definition netsock.c:85
struct ast_netsock_list * ast_netsock_list_alloc(void)
Definition netsock.c:72
struct ast_netsock * ast_netsock_bind(struct ast_netsock_list *list, struct io_context *ioc, const char *bindinfo, int defaultport, int tos, int cos, ast_io_cb callback, void *data)
Definition netsock.c:167
void ast_netsock_unref(struct ast_netsock *ns)
Definition netsock.c:198
int ast_netsock_sockfd(const struct ast_netsock *ns)
Definition netsock.c:183
struct ast_netsock * ast_netsock_find(struct ast_netsock_list *list, struct ast_sockaddr *addr)
Definition netsock.c:94
int ast_netsock_init(struct ast_netsock_list *list)
Definition netsock.c:77
struct ast_netsock * ast_netsock_bindaddr(struct ast_netsock_list *list, struct io_context *ioc, struct ast_sockaddr *bindaddr, int tos, int cos, ast_io_cb callback, void *data)
Definition netsock.c:109
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
Definition utils.c:962
Implementation of the IAX2 protocol.
int iax_parse_ies(struct iax_ies *ies, unsigned char *data, int datalen)
Definition parser.c:795
int iax_get_iframes(void)
Definition parser.c:1354
#define DIRECTION_OUTGRESS
Definition parser.h:89
int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, const struct ast_sockaddr *addr)
Definition parser.c:741
void iax_frame_subclass2str(enum iax_frame_subclass subclass, char *str, size_t len)
Definition parser.c:463
int iax_ie_append_byte(struct iax_ie_data *ied, unsigned char ie, unsigned char dat)
Definition parser.c:775
void iax_frame_free(struct iax_frame *fr)
Definition parser.c:1299
int iax_ie_append(struct iax_ie_data *ied, unsigned char ie)
Definition parser.c:780
int iax_ie_append_versioned_uint64(struct iax_ie_data *ied, unsigned char ie, unsigned char version, uint64_t value)
Definition parser.c:746
struct iax_frame * iax_frame_new(int direction, int datalen, unsigned int cacheable)
Definition parser.c:1230
int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, const void *data, int datalen)
Definition parser.c:726
int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value)
Definition parser.c:756
void iax_set_output(void(*output)(const char *data))
int iax_get_oframes(void)
Definition parser.c:1355
#define DIRECTION_INGRESS
Definition parser.h:88
void iax_frame_wrap(struct iax_frame *fr, struct ast_frame *f)
Definition parser.c:1196
int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value)
Definition parser.c:763
void iax_showframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition parser.c:595
int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, const char *str)
Definition parser.c:770
int iax_get_frames(void)
Definition parser.c:1353
void iax_set_error(void(*output)(const char *data))
Asterisk file paths, configured in asterisk.conf.
const char * ast_config_AST_SYSTEM_NAME
Definition options.c:171
static int totalcalls
Definition pbx.c:794
Core PBX routines and definitions.
int ast_add_extension(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void(*datad)(void *), const char *registrar)
Add and extension to an extension context.
Definition pbx.c:6968
int ast_context_destroy_by_name(const char *context, const char *registrar)
Destroy a context by name.
Definition pbx.c:8249
void ast_unregister_switch(struct ast_switch *sw)
Unregister an alternative switch.
Definition pbx_switch.c:76
int ast_register_switch(struct ast_switch *sw)
Register an alternative dialplan switch.
Definition pbx_switch.c:58
const char * pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
Return a pointer to the value of the corresponding channel variable.
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Determine whether an extension exists.
Definition pbx.c:4211
struct ast_context * ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
Register a new context or find an existing one.
Definition pbx.c:6185
int pbx_exec(struct ast_channel *c, struct ast_app *app, const char *data)
Execute an application.
Definition pbx_app.c:483
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name.
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
Simply remove extension from context.
Definition pbx.c:4984
#define ast_custom_function_register(acf)
Register a custom function.
Definition pbx.h:1563
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks for a valid matching extension.
Definition pbx.c:4226
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
Create a new thread and start the PBX.
Definition pbx.c:4744
int ast_ignore_pattern(const char *context, const char *pattern)
Checks to see if a number should be ignored.
Definition pbx.c:6919
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks to see if adding anything to this extension might match something. (exists ^ canmatch)
Definition pbx.c:4231
struct ast_app * pbx_findapp(const char *app)
Look up an application.
Definition ael_main.c:165
static int netsocket
Definition pbx_dundi.c:195
static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Definition pbx_lua.c:1386
#define ast_poll(a, b, c)
Definition poll-compat.h:88
IAX2 Provisioning protocol.
int iax_provision_reload(int reload)
Definition provision.c:526
int iax_provision_build(struct iax_ie_data *provdata, unsigned int *signature, const char *template, int force)
Definition provision.c:209
int iax_provision_unload(void)
Definition provision.c:517
char * iax_prov_complete_template(const char *line, const char *word, int pos, int state)
Definition provision.c:179
int iax_provision_version(unsigned int *signature, const char *template, int force)
Definition provision.c:258
static int total
Definition res_adsi.c:970
static struct stasis_subscription * sub
Statsd channel stats. Exmaple of how to subscribe to Stasis events.
static struct @486 methods[]
static void challenge(const char *endpoint_id, struct ast_sip_auth *auth, pjsip_tx_data *tdata, const pjsip_rx_data *rdata, int is_stale, const pjsip_auth_algorithm *algorithm)
Send a WWW-Authenticate challenge.
static void cleanup(void)
Clean up any old apps that we don't need any more.
Definition res_stasis.c:327
static struct @522 args
unsigned int refresh
#define NULL
Definition resample.c:96
Scheduler Routines (derived from cheops)
#define AST_SCHED_DEL(sched, id)
Remove a scheduler entry.
Definition sched.h:46
void ast_sched_clean_by_callback(struct ast_sched_context *con, ast_sched_cb match, ast_sched_cb cleanup_cb)
Clean all scheduled events with matching callback.
Definition sched.c:409
int ast_sched_replace(int old_id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
replace a scheduler entry
Definition sched.c:559
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
Definition sched.c:567
void ast_sched_context_destroy(struct ast_sched_context *c)
destroys a schedule context
Definition sched.c:271
int ast_sched_start_thread(struct ast_sched_context *con)
Start a thread for processing scheduler entries.
Definition sched.c:197
int(* ast_sched_cb)(const void *data)
scheduler callback
Definition sched.h:178
struct ast_sched_context * ast_sched_context_create(void)
Create a scheduler context.
Definition sched.c:238
Security Event Reporting API.
struct stasis_topic * ast_security_topic(void)
A stasis_topic which publishes messages for security related issues.
Stasis Message Bus API. See Stasis Message Bus API for detailed documentation.
@ STASIS_SUBSCRIPTION_FILTER_SELECTIVE
Definition stasis.h:297
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
Definition stasis.c:1090
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
Definition stasis.c:1144
void stasis_subscription_cb_noop(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Stasis subscription callback function that does nothing.
Definition stasis.c:876
void * stasis_message_data(const struct stasis_message *msg)
Get the data contained in a message.
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
Definition stasis.c:1201
struct stasis_message * stasis_cache_get(struct stasis_cache *cache, struct stasis_message_type *type, const char *id)
Retrieve an item from the cache for the ast_eid_default entity.
#define stasis_subscribe(topic, callback, data)
Definition stasis.h:649
Endpoint abstractions.
void ast_system_publish_registry(const char *channeltype, const char *username, const char *domain, const char *status, const char *cause)
Publish a channel driver outgoing registration message.
struct stasis_topic * ast_system_topic(void)
A Stasis Message Bus API topic which publishes messages regarding system changes.
struct stasis_message_type * ast_network_change_type(void)
A stasis_message_type for network changes.
#define AST_DECLARE_STRING_FIELDS(field_list)
Declare the fields needed in a structure.
#define AST_STRING_FIELD(name)
Declare a string field.
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
#define ast_string_field_init(x, size)
Initialize a field pool and fields.
#define ast_string_field_build(x, field, fmt, args...)
Set a field to a complex (built) value.
#define ast_string_field_free_memory(x)
free all memory - to be called before destroying the object
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition strings.h:1139
size_t attribute_pure ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition strings.h:730
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
Definition strings.h:80
static force_inline int attribute_pure ast_str_hash(const char *str)
Compute a hash value on a string.
Definition strings.h:1259
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true"....
Definition utils.c:2233
#define S_COR(a, b, c)
returns the equivalent of logic or for strings, with an additional boolean check: second one if not e...
Definition strings.h:87
int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
Parse a time (integer) string.
Definition utils.c:2480
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition strings.h:65
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is "false"....
Definition utils.c:2250
#define ast_str_alloca(init_len)
Definition strings.h:848
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition utils.c:1852
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition strings.h:1113
char *attribute_pure ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition strings.h:761
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition strings.h:425
struct ast_ha ha
Definition chan_iax2.c:1080
unsigned char delme
Definition chan_iax2.c:1084
uint16_t limit
Definition chan_iax2.c:1082
unsigned char raw[AST_CRYPTO_AES_BLOCKSIZE/8]
Definition crypto.h:40
Generic container type.
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition astobj2.h:1821
Wrapper for an ast_acl linked list.
Definition acl.h:76
ast_app: A registered application
Definition pbx_app.c:45
Structure to pass both assignedid values to channel drivers.
Definition channel.h:606
Structure to describe a channel "technology", ie a channel driver See for examples:
Definition channel.h:648
struct ast_format_cap * capabilities
Definition channel.h:652
const char *const type
Definition channel.h:649
Main Channel structure associated with a channel.
const char * data
char context[AST_MAX_CONTEXT]
descriptor for a cli entry.
Definition cli.h:171
int args
This gets set in ast_cli_register()
Definition cli.h:185
char * command
Definition cli.h:186
const char * usage
Definition cli.h:177
Data structure associated with a custom dialplan function.
Definition pbx.h:118
const char * name
Definition pbx.h:119
Structure for a data store type.
Definition datastore.h:31
const char * type
Definition datastore.h:32
Structure for a data store object.
Definition datastore.h:64
void * data
Definition datastore.h:66
unsigned int inheritance
Definition datastore.h:69
Definition dnsmgr.c:66
Structure used to handle a large number of boolean flags == used only in app_dial?
Definition utils.h:225
Structure used to handle boolean flags.
Definition utils.h:220
Format capabilities structure, holds formats + preference order + etc.
Definition format_cap.c:54
Definition of a media format.
Definition format.c:43
struct ast_format * format
Data structure associated with a single frame of data.
struct ast_frame_subclass subclass
struct timeval delivery
enum ast_frame_type frametype
union ast_frame::@235 data
struct ast_frame * next
internal representation of ACL entries In principle user applications would have no need for this,...
Definition acl.h:51
struct ast_sockaddr addr
Definition acl.h:53
struct ast_sockaddr netmask
Definition acl.h:54
unsigned char encdata[0]
Definition iax2.h:245
unsigned short dcallno
Definition iax2.h:232
unsigned short scallno
Definition iax2.h:231
unsigned int ts
Definition iax2.h:233
unsigned char iseqno
Definition iax2.h:235
unsigned char csub
Definition iax2.h:237
unsigned char oseqno
Definition iax2.h:234
unsigned char type
Definition iax2.h:236
Definition iax2.h:282
unsigned short callno
Definition iax2.h:283
unsigned short len
Definition iax2.h:284
unsigned int ts
Definition iax2.h:278
unsigned char data[0]
Definition iax2.h:279
unsigned short len
Definition iax2.h:289
struct ast_iax2_mini_hdr mini
Definition iax2.h:290
unsigned short callno
Definition iax2.h:259
unsigned char encdata[0]
Definition iax2.h:260
unsigned short callno
Definition iax2.h:250
unsigned short ts
Definition iax2.h:251
unsigned short zeros
Definition iax2.h:271
unsigned short callno
Definition iax2.h:272
unsigned short ts
Definition iax2.h:273
Abstract JSON element (object, array, string, int, ...).
struct ast_module * self
Definition module.h:356
Structure for mutex and tracking information.
Definition lock.h:142
The structure that contains MWI state.
Definition mwi.h:455
int old_msgs
Definition mwi.h:460
int new_msgs
Definition mwi.h:459
int sockfd
Definition netsock.c:54
struct ast_party_id id
Caller party ID.
Definition channel.h:422
int ani2
Automatic Number Identification 2 (Info Digits)
Definition channel.h:435
struct ast_party_id ani
Automatic Number Identification (ANI)
Definition channel.h:429
Connected Line/Party information.
Definition channel.h:458
struct ast_party_id id
Connected party ID.
Definition channel.h:460
char * str
Subscriber phone number (Malloced)
Definition channel.h:388
struct ast_party_dialed::@217 number
Dialed/Called number.
int transit_network_select
Transit Network Select.
Definition channel.h:399
struct ast_party_name name
Subscriber name.
Definition channel.h:342
struct ast_party_number number
Subscriber phone number.
Definition channel.h:344
int presentation
Q.931 encoded presentation-indicator encoded field.
Definition channel.h:279
unsigned char valid
TRUE if the name information is valid/present.
Definition channel.h:281
char * str
Subscriber name (Malloced)
Definition channel.h:266
int presentation
Q.931 presentation-indicator and screening-indicator encoded fields.
Definition channel.h:297
unsigned char valid
TRUE if the number information is valid/present.
Definition channel.h:299
char * str
Subscriber phone number (Malloced)
Definition channel.h:293
int plan
Q.931 Type-Of-Number and Numbering-Plan encoded fields.
Definition channel.h:295
struct ast_party_id from
Who is redirecting the call (Sent to the party the call is redirected toward)
Definition channel.h:529
Socket address structure.
Definition netsock2.h:97
struct sockaddr_storage ss
Definition netsock2.h:98
Support for dynamic strings.
Definition strings.h:623
const char * name
Definition pbx.h:164
A ast_taskprocessor structure is a singleton by name.
int tm_mday
Definition localtime.h:39
int tm_sec
Definition localtime.h:36
int tm_hour
Definition localtime.h:38
int tm_min
Definition localtime.h:37
int tm_year
Definition localtime.h:41
int tm_mon
Definition localtime.h:40
struct ast_var_t::@220 entries
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
callno_entry numbers[IAX_MAX_CALLS/2+1]
Definition chan_iax2.c:998
unsigned char semirand[32]
Definition chan_iax2.c:918
const ast_string_field mohinterpret
Definition chan_iax2.c:899
int first_iax_message
Definition chan_iax2.c:803
struct ast_sockaddr addr
Definition chan_iax2.c:813
struct ast_variable * vars
Definition chan_iax2.c:957
const ast_string_field language
Definition chan_iax2.c:899
int frames_received
Definition chan_iax2.c:967
const ast_string_field cid_num
Definition chan_iax2.c:899
struct chan_iax2_pvt::signaling_queue signaling_queue
iax2_format svideoformat
Definition chan_iax2.c:791
unsigned int lastsent
Definition chan_iax2.c:797
const ast_string_field inkeys
Definition chan_iax2.c:899
const ast_string_field outkey
Definition chan_iax2.c:899
unsigned int nextpred
Definition chan_iax2.c:801
iax2_format capability
Definition chan_iax2.c:793
int destroy_initiated
Definition chan_iax2.c:969
unsigned int pingtime
Definition chan_iax2.c:809
const ast_string_field dproot
Definition chan_iax2.c:899
const ast_string_field mohsuggest
Definition chan_iax2.c:899
unsigned short bridgecallno
Definition chan_iax2.c:942
const ast_string_field accountcode
Definition chan_iax2.c:899
const ast_string_field username
Definition chan_iax2.c:899
iax2_format peercapability
Definition chan_iax2.c:832
struct ast_variable * iaxvars
Definition chan_iax2.c:959
struct ast_flags state
Definition chan_iax2.c:848
unsigned int notsilenttx
Definition chan_iax2.c:807
unsigned int lastvsent
Definition chan_iax2.c:799
ast_callid callid
Definition chan_iax2.c:783
unsigned char iseqno
Definition chan_iax2.c:856
char hold_signaling
Definition chan_iax2.c:973
struct timeval rxcore
Definition chan_iax2.c:836
struct ast_sockaddr transfer
Definition chan_iax2.c:932
iax2_format voiceformat
Definition chan_iax2.c:785
const ast_string_field context
Definition chan_iax2.c:899
unsigned short peercallno
Definition chan_iax2.c:823
struct iax2_codec_pref prefs
Definition chan_iax2.c:815
unsigned short callno
Definition chan_iax2.c:819
unsigned char calltoken_ie_len
Definition chan_iax2.c:971
const ast_string_field parkinglot
Definition chan_iax2.c:899
iax2_format videoformat
Definition chan_iax2.c:787
unsigned char rseqno
Definition chan_iax2.c:854
const ast_string_field host
Definition chan_iax2.c:899
callno_entry callno_entry
Definition chan_iax2.c:821
uint64_t flags
Definition chan_iax2.c:924
unsigned short transfercallno
Definition chan_iax2.c:934
struct ast_channel * owner
Definition chan_iax2.c:846
const ast_string_field rdnis
Definition chan_iax2.c:899
unsigned char oseqno
Definition chan_iax2.c:852
struct timeval offset
Definition chan_iax2.c:834
unsigned char aseqno
Definition chan_iax2.c:858
iax2_format svoiceformat
Definition chan_iax2.c:789
const ast_string_field challenge
Definition chan_iax2.c:899
const ast_string_field exten
Definition chan_iax2.c:899
ast_aes_decrypt_key dcx
Definition chan_iax2.c:913
struct iax_rr remote_rr
Definition chan_iax2.c:961
unsigned int last
Definition chan_iax2.c:795
ast_aes_encrypt_key tdcx
Definition chan_iax2.c:936
const ast_string_field ani
Definition chan_iax2.c:899
iax2_format peerformat
Definition chan_iax2.c:830
struct iax2_codec_pref rprefs
Definition chan_iax2.c:817
jitterbuf * jb
Definition chan_iax2.c:838
struct iax2_registry * reg
Definition chan_iax2.c:920
ast_aes_decrypt_key mydcx
Definition chan_iax2.c:911
const ast_string_field cid_name
Definition chan_iax2.c:899
enum iax_transfer_state transferring
Definition chan_iax2.c:928
int last_iax_message
Definition chan_iax2.c:805
int eff_auth_method
Definition chan_iax2.c:905
const ast_string_field secret
Definition chan_iax2.c:899
ast_aes_encrypt_key ecx
Definition chan_iax2.c:909
const ast_string_field dnid
Definition chan_iax2.c:899
const ast_string_field osptoken
Definition chan_iax2.c:899
struct iax2_peer * peerpoke
Definition chan_iax2.c:922
const ast_string_field peer
Definition chan_iax2.c:899
iax2_format chosenformat
Definition chan_iax2.c:828
struct chan_iax2_pvt::@124 dpentries
iax2_format capability
Definition chan_iax2.c:4698
char username[80]
Definition chan_iax2.c:4707
struct iax2_codec_pref prefs
Definition chan_iax2.c:4700
char timezone[80]
Definition chan_iax2.c:4710
char cid_name[80]
Definition chan_iax2.c:4712
char context[AST_MAX_CONTEXT]
Definition chan_iax2.c:4713
char peercontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:4714
char mohsuggest[MAX_MUSICCLASS]
Definition chan_iax2.c:4716
char mohinterpret[MAX_MUSICCLASS]
Definition chan_iax2.c:4715
char context[AST_MAX_EXTENSION]
Definition chan_iax2.c:9728
char callednum[AST_MAX_EXTENSION]
Definition chan_iax2.c:9729
char * callerid
Definition chan_iax2.c:9730
Definition file.c:70
char order[IAX2_CODEC_PREF_SIZE]
Definition codec_pref.h:36
char context[AST_MAX_CONTEXT]
Definition chan_iax2.c:530
struct iax2_context * next
Definition chan_iax2.c:531
int waiters[256]
Definition chan_iax2.c:1113
struct iax2_dpcache::@127 peer_list
struct timeval expiry
Definition chan_iax2.c:1110
char exten[AST_MAX_EXTENSION]
Definition chan_iax2.c:1108
unsigned short callno
Definition chan_iax2.c:1112
struct timeval orig
Definition chan_iax2.c:1109
struct iax2_dpcache::@126 cache_list
char peercontext[AST_MAX_CONTEXT]
Definition chan_iax2.c:1107
const ast_string_field peercontext
Definition chan_iax2.c:636
const ast_string_field mohinterpret
Definition chan_iax2.c:636
int pokefreqok
Definition chan_iax2.c:661
struct ast_sockaddr addr
Definition chan_iax2.c:639
struct ast_dnsmgr_entry * dnsmgr
Definition chan_iax2.c:638
const ast_string_field cid_num
Definition chan_iax2.c:636
const ast_string_field inkeys
Definition chan_iax2.c:636
const ast_string_field outkey
Definition chan_iax2.c:636
struct ast_mwi_subscriber * mwi_event_sub
Definition chan_iax2.c:667
enum calltoken_peer_enum calltoken_required
Definition chan_iax2.c:670
iax2_format capability
Definition chan_iax2.c:653
int pokefreqnotok
Definition chan_iax2.c:662
int historicms
Definition chan_iax2.c:663
int authmethods
Definition chan_iax2.c:648
const ast_string_field regexten
Definition chan_iax2.c:636
const ast_string_field mohsuggest
Definition chan_iax2.c:636
const ast_string_field username
Definition chan_iax2.c:636
const ast_string_field zonetag
Definition chan_iax2.c:636
struct ast_sockaddr defaddr
Definition chan_iax2.c:647
uint16_t maxcallno
Definition chan_iax2.c:665
const ast_string_field description
Definition chan_iax2.c:636
const ast_string_field context
Definition chan_iax2.c:636
struct iax2_codec_pref prefs
Definition chan_iax2.c:637
const ast_string_field parkinglot
Definition chan_iax2.c:636
uint64_t flags
Definition chan_iax2.c:644
const ast_string_field dbsecret
Definition chan_iax2.c:636
struct ast_sockaddr mask
Definition chan_iax2.c:642
int encmethods
Definition chan_iax2.c:649
struct ast_endpoint * endpoint
Definition chan_iax2.c:672
int pokeexpire
Definition chan_iax2.c:657
int formats
Definition chan_iax2.c:640
struct ast_acl_list * acl
Definition chan_iax2.c:669
const ast_string_field name
Definition chan_iax2.c:636
const ast_string_field cid_name
Definition chan_iax2.c:636
int smoothing
Definition chan_iax2.c:664
const ast_string_field secret
Definition chan_iax2.c:636
const ast_string_field mailbox
Definition chan_iax2.c:636
unsigned char buf[1]
Definition chan_iax2.c:1143
struct iax2_pkt_buf::@128 entry
struct ast_sockaddr addr
Definition chan_iax2.c:723
struct ast_dnsmgr_entry * dnsmgr
Definition chan_iax2.c:732
char hostname[]
Definition chan_iax2.c:735
enum iax_reg_state regstate
Definition chan_iax2.c:728
struct iax2_registry::@123 entry
char username[80]
Definition chan_iax2.c:724
char secret[80]
Definition chan_iax2.c:725
struct ast_sockaddr us
Definition chan_iax2.c:731
struct ast_sockaddr addr
Definition chan_iax2.c:1177
unsigned char readbuf[4096]
Definition chan_iax2.c:1161
ast_cond_t cond
Definition chan_iax2.c:1168
ast_cond_t init_cond
Definition chan_iax2.c:1170
time_t checktime
Definition chan_iax2.c:1166
struct iax2_thread::@130 ffinfo
unsigned char stop
Definition chan_iax2.c:1185
unsigned char csub
Definition chan_iax2.c:1179
pthread_t threadid
Definition chan_iax2.c:1158
unsigned short callno
Definition chan_iax2.c:1176
unsigned char type
Definition chan_iax2.c:1178
struct ast_sockaddr ioaddr
Definition chan_iax2.c:1160
ast_mutex_t init_lock
Definition chan_iax2.c:1169
struct iax2_thread::@129 list
struct iax2_thread::@131 full_frames
unsigned char * buf
Definition chan_iax2.c:1162
enum iax2_thread_iostate iostate
Definition chan_iax2.c:1149
ast_mutex_t lock
Definition chan_iax2.c:1167
const void * scheddata
Definition chan_iax2.c:1152
size_t buf_size
Definition chan_iax2.c:1164
enum iax2_thread_type type
Definition chan_iax2.c:1148
void(* schedfunc)(const void *)
Definition chan_iax2.c:1151
char curfunc[80]
Definition chan_iax2.c:1155
ssize_t buf_len
Definition chan_iax2.c:1163
struct ast_sockaddr addr
Definition chan_iax2.c:680
struct timeval lasttxtime
Definition chan_iax2.c:683
unsigned int lastsent
Definition chan_iax2.c:685
struct timeval rxtrunktime
Definition chan_iax2.c:682
struct iax2_trunk_peer::@122 list
unsigned int trunkdataalloc
Definition chan_iax2.c:689
unsigned int trunkdatalen
Definition chan_iax2.c:688
unsigned char * trunkdata
Definition chan_iax2.c:687
struct timeval trunkact
Definition chan_iax2.c:684
ast_mutex_t lock
Definition chan_iax2.c:678
struct timeval txtrunktime
Definition chan_iax2.c:681
const ast_string_field mohinterpret
Definition chan_iax2.c:598
struct ast_variable * vars
Definition chan_iax2.c:611
const ast_string_field language
Definition chan_iax2.c:598
const ast_string_field cid_num
Definition chan_iax2.c:598
const ast_string_field inkeys
Definition chan_iax2.c:598
struct iax2_context * contexts
Definition chan_iax2.c:610
enum calltoken_peer_enum calltoken_required
Definition chan_iax2.c:612
iax2_format capability
Definition chan_iax2.c:605
int authmethods
Definition chan_iax2.c:600
const ast_string_field mohsuggest
Definition chan_iax2.c:598
const ast_string_field accountcode
Definition chan_iax2.c:598
struct iax2_codec_pref prefs
Definition chan_iax2.c:608
const ast_string_field parkinglot
Definition chan_iax2.c:598
uint64_t flags
Definition chan_iax2.c:604
const ast_string_field dbsecret
Definition chan_iax2.c:598
int encmethods
Definition chan_iax2.c:601
int maxauthreq
Definition chan_iax2.c:606
int curauthreq
Definition chan_iax2.c:607
struct ast_acl_list * acl
Definition chan_iax2.c:609
const ast_string_field name
Definition chan_iax2.c:598
const ast_string_field cid_name
Definition chan_iax2.c:598
int amaflags
Definition chan_iax2.c:602
const ast_string_field secret
Definition chan_iax2.c:598
unsigned char semirand[32]
Definition parser.h:138
unsigned short dcallno
Definition parser.h:102
struct iax_frame::@144 list
unsigned int final
Definition parser.h:120
unsigned int sentyet
Definition parser.h:116
int retrans
Definition parser.h:130
unsigned int ts
Definition parser.h:110
unsigned char afdata[0]
Definition parser.h:146
unsigned int outoforder
Definition parser.h:114
void * data
Definition parser.h:104
unsigned short callno
Definition parser.h:100
int retries
Definition parser.h:108
int encmethods
Definition parser.h:132
int iseqno
Definition parser.h:128
size_t afdatalen
Definition parser.h:144
unsigned int direction
Definition parser.h:122
ast_aes_decrypt_key mydcx
Definition parser.h:136
struct iax_frame * next
Definition parser.h:140
int datalen
Definition parser.h:106
int retrytime
Definition parser.h:112
unsigned int transfer
Definition parser.h:118
ast_aes_encrypt_key ecx
Definition parser.h:134
struct ast_frame af
Definition parser.h:142
unsigned int cacheable
Definition parser.h:124
int oseqno
Definition parser.h:126
unsigned char buf[1024]
Definition parser.h:150
struct ast_sockaddr apparent_addr
Definition parser.h:52
unsigned short adsicpe
Definition parser.h:44
unsigned int rr_jitter
Definition parser.h:75
unsigned int provver
Definition parser.h:72
unsigned char * calltokendata
Definition parser.h:85
unsigned int rr_pkts
Definition parser.h:77
struct ast_variable * vars
Definition parser.h:81
unsigned char calltoken
Definition parser.h:84
unsigned char iax_unknown
Definition parser.h:58
int calling_ani2
Definition parser.h:35
unsigned int rr_loss
Definition parser.h:76
unsigned int authmethods
Definition parser.h:47
char * challenge
Definition parser.h:49
char * dnid
Definition parser.h:45
char * calling_name
Definition parser.h:31
iax2_format capability
Definition parser.h:39
char * called_context
Definition parser.h:36
char * calling_number
Definition parser.h:29
unsigned int fwdesc
Definition parser.h:67
char * calling_ani
Definition parser.h:30
int calling_ton
Definition parser.h:32
char * password
Definition parser.h:38
unsigned int transferid
Definition parser.h:62
unsigned int rr_dropped
Definition parser.h:79
unsigned char causecode
Definition parser.h:57
unsigned int ospblocklength[IAX_MAX_OSPBLOCK_NUM]
Definition parser.h:83
int msgcount
Definition parser.h:59
int calling_tns
Definition parser.h:33
char * called_number
Definition parser.h:28
unsigned short callno
Definition parser.h:55
char * md5_result
Definition parser.h:50
int provverpres
Definition parser.h:74
char * language
Definition parser.h:42
char * codec_prefs
Definition parser.h:41
iax2_format format
Definition parser.h:40
unsigned int encmethods
Definition parser.h:48
unsigned short dpstatus
Definition parser.h:54
char * username
Definition parser.h:37
char * rsa_result
Definition parser.h:51
int calling_pres
Definition parser.h:34
int version
Definition parser.h:43
char * cause
Definition parser.h:56
int musiconhold
Definition parser.h:61
unsigned short refresh
Definition parser.h:53
char * serviceident
Definition parser.h:65
unsigned int rr_ooo
Definition parser.h:80
char * devicetype
Definition parser.h:64
char * rdnis
Definition parser.h:46
unsigned short rr_delay
Definition parser.h:78
char * osptokenblock[IAX_MAX_OSPBLOCK_NUM]
Definition parser.h:82
int ooo
Definition chan_iax2.c:770
int losscnt
Definition chan_iax2.c:766
int delay
Definition chan_iax2.c:768
int losspct
Definition chan_iax2.c:765
int dropped
Definition chan_iax2.c:769
int jitter
Definition chan_iax2.c:764
int packets
Definition chan_iax2.c:767
Global IO variables are now in a struct in order to be made threadsafe.
Definition io.c:71
long target_extra
Definition jitterbuf.h:72
long max_jitterbuf
Definition jitterbuf.h:69
long resync_threshold
Definition jitterbuf.h:70
long max_contig_interp
Definition jitterbuf.h:71
long ms
Definition jitterbuf.h:104
void * data
Definition jitterbuf.h:102
long min
Definition jitterbuf.h:87
long current
Definition jitterbuf.h:88
long frames_in
Definition jitterbuf.h:79
long losspct
Definition jitterbuf.h:90
long frames_lost
Definition jitterbuf.h:82
long frames_ooo
Definition jitterbuf.h:84
long frames_dropped
Definition jitterbuf.h:83
long jitter
Definition jitterbuf.h:86
In case you didn't read that giant block of text above the mansession_session struct,...
Definition manager.c:323
Number structure.
struct ast_sockaddr addr
Definition chan_iax2.c:1067
unsigned char reg
Definition chan_iax2.c:1074
uint16_t limit
Definition chan_iax2.c:1071
uint16_t cur
Definition chan_iax2.c:1069
Scheduler ID holder.
Definition sched.c:70
Definition sched.c:76
Definition chan_iax2.c:978
struct ast_frame f
Definition chan_iax2.c:979
struct signaling_queue_entry * next
Definition chan_iax2.c:980
structure to hold users read from phoneprov_users.conf
list of users found in the config file
int value
Definition syslog.c:37
An API for managing task processing threads that can be shared across modules.
struct ast_taskprocessor * ast_taskprocessor_get(const char *name, enum ast_tps_options create)
Get a reference to a taskprocessor with the specified name and create the taskprocessor if necessary.
void * ast_taskprocessor_unreference(struct ast_taskprocessor *tps)
Unreference the specified taskprocessor and its reference count will decrement.
@ TPS_REF_DEFAULT
return a reference to a taskprocessor, create one if it does not exist
#define ast_taskprocessor_push(tps, task_exe, datap)
Test Framework API.
int done
static struct test_val a
static struct test_val c
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition time.h:282
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
Definition time.h:117
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compress two struct timeval instances returning -1, 0, 1 if the first arg is smaller,...
Definition time.h:137
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition extconf.c:2280
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition extconf.c:2295
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition time.h:159
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
Definition time.h:235
Timing source management.
void ast_timer_close(struct ast_timer *handle)
Close an opened timing handle.
Definition timing.c:154
int ast_timer_ack(const struct ast_timer *handle, unsigned int quantity)
Acknowledge a timer event.
Definition timing.c:171
int ast_timer_set_rate(const struct ast_timer *handle, unsigned int rate)
Set the timing tick rate.
Definition timing.c:166
struct ast_timer * ast_timer_open(void)
Open a timer.
Definition timing.c:122
int ast_timer_fd(const struct ast_timer *handle)
Get a poll()-able file descriptor for a timer.
Definition timing.c:161
Support for translation of data formats. translate.c.
int ast_translator_best_choice(struct ast_format_cap *dst_cap, struct ast_format_cap *src_cap, struct ast_format **dst_fmt_out, struct ast_format **src_fmt_out)
Chooses the best translation path.
Definition translate.c:1676
int error(const char *format,...)
Utility functions.
#define ast_test_flag(p, flag)
Definition utils.h:64
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition utils.h:981
#define ast_set2_flag64(p, value, flag)
Definition utils.h:171
#define ast_test_flag64(p, flag)
Definition utils.h:140
#define ast_assert(a)
Definition utils.h:779
#define ast_set_flags_to64(p, flag, value)
Definition utils.h:181
#define ast_clear_flag64(p, flag)
Definition utils.h:154
#define MIN(a, b)
Definition utils.h:252
#define ast_pthread_create_background(a, b, c, d)
Definition utils.h:632
#define ast_assert_return(a,...)
Definition utils.h:780
#define ast_clear_flag(p, flag)
Definition utils.h:78
long int ast_random(void)
Definition utils.c:2346
#define ast_pthread_create_detached(a, b, c, d)
Definition utils.h:628
#define ast_copy_flags64(dest, src, flagz)
Definition utils.h:161
#define ast_set_flag64(p, flag)
Definition utils.h:147
#define ast_set_flag(p, flag)
Definition utils.h:71
#define ARRAY_LEN(a)
Definition utils.h:706
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition utils.c:266