Asterisk - The Open Source Telephony Project GIT-master-754dea3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
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="secure_signaling">
228 <para>R/O Get the if the IAX channel is secured.</para>
229 </enum>
230 <enum name="secure_media">
231 <para>R/O Get the if the IAX channel is secured.</para>
232 </enum>
233 </enumlist>
234 </info>
235 <info name="Dial_Resource" language="en_US" tech="IAX2">
236 <para>The general syntax is:</para>
237 <para><literal>Dial(IAX2/[username[:password[:pubkey]]@]peer[:port][/exten[@context]][/options]</literal></para>
238 <para>The IAX username is optionally followed by either the secret or name of the keypair to use for RSA
239 authentication (within square brakcets). If both need to be provided (such as for encrypted calls that
240 are RSA authenticated), both may be specified in either order.</para>
241 <para>IAX2 optionally allows modifiers to be specified after the extension.</para>
242 <enumlist>
243 <enum name="a">
244 <para>Request auto answer (supporting equipment/configuration required)</para>
245 </enum>
246 </enumlist>
247 </info>
248 <manager name="IAXpeers" language="en_US">
249 <since>
250 <version>0.3.0</version>
251 </since>
252 <synopsis>
253 List IAX peers.
254 </synopsis>
255 <syntax>
256 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
257 </syntax>
258 <description>
259 </description>
260 </manager>
261 <manager name="IAXpeerlist" language="en_US">
262 <since>
263 <version>1.6.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 <para>List all the IAX peers.</para>
273 </description>
274 </manager>
275 <manager name="IAXnetstats" language="en_US">
276 <since>
277 <version>1.2.0</version>
278 </since>
279 <synopsis>
280 Show IAX Netstats.
281 </synopsis>
282 <syntax />
283 <description>
284 <para>Show IAX channels network statistics.</para>
285 </description>
286 </manager>
287 <manager name="IAXregistry" language="en_US">
288 <since>
289 <version>1.6.2.0</version>
290 </since>
291 <synopsis>
292 Show IAX registrations.
293 </synopsis>
294 <syntax>
295 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
296 </syntax>
297 <description>
298 <para>Show IAX registrations.</para>
299 </description>
300 </manager>
301 ***/
302
303/* Define SCHED_MULTITHREADED to run the scheduler in a special
304 multithreaded mode. */
305#define SCHED_MULTITHREADED
306
307/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
308 thread is actually doing. */
309#define DEBUG_SCHED_MULTITHREAD
310
311
312#ifdef SO_NO_CHECK
313static int nochecksums = 0;
314#endif
315
316#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
317#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
318
319#define DEFAULT_THREAD_COUNT 10
320#define DEFAULT_MAX_THREAD_COUNT 100
321#define DEFAULT_RETRY_TIME 1000
322#define MEMORY_SIZE 100
323#define DEFAULT_DROP 3
324
325#define DEBUG_SUPPORT
326
327#define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
328
329/* Sample over last 100 units to determine historic jitter */
330#define GAMMA (0.01)
331
333
334static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
335
336
337/*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
338 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
339#define MAX_TRUNK_MTU 1240
340
341static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
342static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
343
344#define DEFAULT_CONTEXT "default"
345
347
348static char language[MAX_LANGUAGE] = "";
349static char regcontext[AST_MAX_CONTEXT] = "";
350
351static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
352static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
354
355static int maxauthreq = 3;
356static int max_retries = 4;
357static int ping_time = 21;
358static int lagrq_time = 10;
359static int maxjitterbuffer=1000;
360static int resyncthreshold=1000;
361static int maxjitterinterps=10;
362static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
363
364#define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
365
366static int trunkfreq = 20;
368
369static int authdebug = 0;
370static int autokill = 0;
371static int iaxcompat = 0;
372static int last_authmethod = 0;
373
374static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
375
376static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
377
378static struct {
379 unsigned int tos;
380 unsigned int cos;
381} qos = { 0, 0 };
382
383static int min_reg_expire;
384static int max_reg_expire;
385
386static int srvlookup = 0;
387
388static struct ast_timer *timer; /* Timer for trunking */
389
391static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
392static int defaultsockfd = -1;
393
394static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
395
396/* Ethernet, etc */
397#define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
398/* T1, maybe ISDN */
399#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
400 ~AST_FORMAT_SLIN & \
401 ~AST_FORMAT_SLIN16 & \
402 ~AST_FORMAT_SIREN7 & \
403 ~AST_FORMAT_SIREN14 & \
404 ~AST_FORMAT_G719 & \
405 ~AST_FORMAT_ULAW & \
406 ~AST_FORMAT_ALAW & \
407 ~AST_FORMAT_G722)
408/* A modem */
409#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
410 ~AST_FORMAT_G726 & \
411 ~AST_FORMAT_G726_AAL2 & \
412 ~AST_FORMAT_ADPCM)
413
414#define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
415 ~AST_FORMAT_G723)
416
417
418#define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
419#define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
420#define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
421
422/*! \brief Name of effective auth method */
423static const char *auth_method_labels[] = {
424 [0] = "none",
425 [IAX_AUTH_PLAINTEXT] = "plaintext",
426 [IAX_AUTH_MD5] = "MD5",
427 [IAX_AUTH_RSA] = "RSA",
428};
429
430/* Max length is length of |RSA|MD5|plaintext (18 + 1 for NUL = 19) */
431#define AUTH_METHOD_NAMES_BUFSIZE 19
432
433/*!
434 * \brief Get names of all auth methods
435 * \param Bit field of auth methods
436 * \param[out] buf Buffer into which to write the names. Must be of size AUTH_METHOD_NAMES_BUFSIZE.
437 * \return Auth methods name
438 */
439static char *auth_method_names(int authmethods, char *restrict buf)
440{
441 char *pos = buf;
442
443 *pos = '\0';
444
445 if (authmethods & IAX_AUTH_RSA) {
446 pos += sprintf(pos, "|RSA");
447 }
448 if (authmethods & IAX_AUTH_MD5) {
449 pos += sprintf(pos, "|MD5");
450 }
451 if (authmethods & IAX_AUTH_PLAINTEXT) {
452 pos += sprintf(pos, "|plaintext");
453 }
454
455 if (pos == buf) { /* No auth methods */
456 strcpy(buf, "none");
457 return buf;
458 }
459
460 return buf + 1; /* Skip leading | */
461}
462
463/* if a pvt has encryption setup done and is running on the call */
464#define IAX_CALLENCRYPTED(pvt) \
465 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
466
467#define IAX_DEBUGDIGEST(msg, key) do { \
468 int idx; \
469 char digest[33] = ""; \
470 \
471 if (!iaxdebug) \
472 break; \
473 \
474 for (idx = 0; idx < 16; idx++) \
475 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
476 \
477 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
478 } while(0)
479
480static struct io_context *io;
482
484
485static int iaxdebug = 0;
486
487static int iaxtrunkdebug = 0;
488
489static int test_losspct = 0;
490#ifdef IAXTESTS
491static int test_late = 0;
492static int test_resync = 0;
493static int test_jit = 0;
494static int test_jitpct = 0;
495#endif /* IAXTESTS */
496
500static int amaflags = 0;
501static int adsi = 0;
502static int delayreject = 0;
503static int iax2_encryption = 0;
504static int iax2_authmethods = 0;
505
506static struct ast_flags64 globalflags = { 0 };
507
509
513 IAX_STATE_TBD = (1 << 2),
514};
515
519};
520
521
522#define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
523#define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
524#define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
525#define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
526#define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
527#define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
528#define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
529#define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
530#define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
531#define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
532#define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
533#define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
534#define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
535#define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
536#define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
537#define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
538#define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
539#define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
540#define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
541#define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
542#define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
543#define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
544#define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
545#define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
546#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 */
547#define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
548#define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
549#define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
550#define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
551#define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
552#define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
553static int global_rtautoclear = 120;
554
555static int reload_config(int forced_reload);
556
557/*!
558 * \brief Call token validation settings.
559 */
561 /*! \brief Default calltoken required unless the ip is in the ignorelist */
563 /*! \brief Require call token validation. */
565 /*! \brief Require call token validation after a successful registration
566 * using call token validation occurs. */
568 /*! \brief Do not require call token validation. */
570};
571
572struct iax2_user {
580 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
584 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
585 );
586
590 int adsi;
591 uint64_t flags;
593 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
594 int curauthreq; /*!< Current number of outstanding AUTHREQs */
599 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
600};
601
602struct iax2_peer {
606 AST_STRING_FIELD(description); /*!< Description of the peer */
609 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
610
611 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
612 AST_STRING_FIELD(context); /*!< For transfers only */
613 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
614 AST_STRING_FIELD(mailbox); /*!< Mailbox */
617 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
618 /* Suggested caller id if registering */
619 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
620 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
621 AST_STRING_FIELD(zonetag); /*!< Time Zone */
622 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
623 );
625 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
628 int sockfd; /*!< Socket to use for transmission */
630 int adsi;
631 uint64_t flags;
632
633 /* Dynamic Registration fields */
634 struct ast_sockaddr defaddr; /*!< Default address if there is one */
635 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
636 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
637
638 int expire; /*!< Schedule entry for expiry */
639 int expiry; /*!< How soon to expire */
640 iax2_format capability; /*!< Capability */
641
642 /* Qualification */
643 int callno; /*!< Call number of POKE request */
644 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
645 int lastms; /*!< How long last response took (in ms), or -1 for no response */
646 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
647
648 int pokefreqok; /*!< How often to check if the host is up */
649 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
650 int historicms; /*!< How long recent average responses took */
651 int smoothing; /*!< Sample over how many units to determine historic ms */
652 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
653
654 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
655
657 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
658
659 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
660};
661
662#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
663
668 struct timeval txtrunktime; /*!< Transmit trunktime */
669 struct timeval rxtrunktime; /*!< Receive trunktime */
670 struct timeval lasttxtime; /*!< Last transmitted trunktime */
671 struct timeval trunkact; /*!< Last trunk activity */
672 unsigned int lastsent; /*!< Last sent time */
673 /* Trunk data and length */
674 unsigned char *trunkdata;
675 unsigned int trunkdatalen;
676 unsigned int trunkdataalloc;
679 int calls;
681};
682
684
694
708
710 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
711 char username[80];
712 char secret[80]; /*!< Password or key name in []'s */
713 int expire; /*!< Sched ID of expiration */
714 int refresh; /*!< How often to refresh */
716 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
717 int callno; /*!< Associated call number if applicable */
718 struct ast_sockaddr us; /*!< Who the server thinks we are */
719 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
721 int port;
722 char hostname[];
723};
724
726
727/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
728#define MIN_RETRY_TIME 100
729#define MAX_RETRY_TIME 10000
730
731#define MAX_JITTER_BUFFER 50
732#define MIN_JITTER_BUFFER 10
733
734#define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
735
736#define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
737
738/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
739#define TS_GAP_FOR_JB_RESYNC 5000
740
741/* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
742#define MARK_IAX_SUBCLASS_TX 0x8000
743
747static int iaxdynamicthreadnum = 0;
748static int iaxactivethreadcount = 0;
749
750struct iax_rr {
755 int delay;
757 int ooo;
758};
759
760struct iax2_pvt_ref;
761
762/* We use the high order bit as the validated flag, and the lower 15 as the
763 * actual call number */
764typedef uint16_t callno_entry;
765
767 /*! Socket to send/receive on for this call */
769 /*! ast_callid bound to dialog */
771 /*! Last received voice format */
773 /*! Last received video format */
775 /*! Last sent voice format */
777 /*! Last sent video format */
779 /*! What we are capable of sending */
781 /*! Last received timestamp */
782 unsigned int last;
783 /*! Last sent timestamp - never send the same timestamp twice in a single call */
784 unsigned int lastsent;
785 /*! Timestamp of the last video frame sent */
786 unsigned int lastvsent;
787 /*! Next outgoing timestamp if everything is good */
788 unsigned int nextpred;
789 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
791 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
793 /*! True if the last voice we transmitted was not silence/CNG */
794 unsigned int notsilenttx:1;
795 /*! Ping time */
796 unsigned int pingtime;
797 /*! Max time for initial response */
799 /*! Peer Address */
801 /*! Actual used codec preferences */
803 /*! Requested codec preferences */
805 /*! Our call number */
806 unsigned short callno;
807 /*! Our callno_entry entry */
809 /*! Peer callno */
810 unsigned short peercallno;
811 /*! Negotiated format, this is only used to remember what format was
812 chosen for an unauthenticated call so that the channel can get
813 created later using the right format. We also use it for
814 authenticated calls to check the format from __get_from_jb. */
816 /*! Peer selected format */
818 /*! Peer capability */
820 /*! timeval that we base our transmission on */
821 struct timeval offset;
822 /*! timeval that we base our delivery on */
823 struct timeval rxcore;
824 /*! The jitterbuffer */
826 /*! active jb read scheduler id */
827 int jbid;
828 /*! LAG */
829 int lag;
830 /*! Error, as discovered by the manager */
831 int error;
832 /*! Owner if we have one */
834 /*! What's our state? */
836 /*! Expiry (optional) */
838 /*! Next outgoing sequence number */
839 unsigned char oseqno;
840 /*! Next sequence number they have not yet acknowledged */
841 unsigned char rseqno;
842 /*! Next incoming sequence number */
843 unsigned char iseqno;
844 /*! Last incoming sequence number we have acknowledged */
845 unsigned char aseqno;
846
848 /*! Peer name */
850 /*! Default Context */
852 /*! Caller ID if available */
855 /*! Hidden Caller ID (i.e. ANI) if appropriate */
857 /*! DNID */
859 /*! RDNIS */
861 /*! Requested Extension */
863 /*! Expected Username */
865 /*! Expected Secret */
867 /*! MD5 challenge */
869 /*! Public keys permitted keys for incoming authentication */
871 /*! Private key for outgoing authentication */
873 /*! Preferred language */
875 /*! Hostname/peername for naming purposes */
877
882 /*! received OSP token */
884 /*! Default parkinglot */
886 );
887 /*! AUTHREJ all AUTHREP frames */
889 /*! permitted authentication methods */
891 /*! effective authentication method */
893 /*! permitted encryption methods */
895 /*! Encryption AES-128 Key */
897 /*! Decryption AES-128 Key corresponding to ecx */
899 /*! Decryption AES-128 Key used to decrypt peer frames */
901 /*! scheduler id associated with iax_key_rotate
902 * for encrypted calls*/
904 /*! 32 bytes of semi-random data */
905 unsigned char semirand[32];
906 /*! Associated registry */
908 /*! Associated peer for poking */
910 /*! IAX_ flags */
911 uint64_t flags;
912 int adsi;
913
914 /*! Transferring status */
916 /*! Transfer identifier */
918 /*! Who we are IAX transferring to */
920 /*! What's the new call number for the transfer */
921 unsigned short transfercallno;
922 /*! Transfer encrypt AES-128 Key */
924
925 /*! Status of knowledge of peer ADSI capability */
927
928 /*! Callno of native bridge peer. (Valid if nonzero) */
929 unsigned short bridgecallno;
930
931 int pingid; /*!< Transmit PING request */
932 int lagid; /*!< Retransmit lag request */
933 int autoid; /*!< Auto hangup for Dialplan requestor */
934 int authid; /*!< Authentication rejection ID */
935 int authfail; /*!< Reason to report failure */
936 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
943 /*! variables inherited from the user definition */
945 /*! variables transmitted in a NEW packet */
947 /*! last received remote rr */
949 /*! Current base time: (just for stats) */
950 int min;
951 /*! Dropped frame count: (just for stats) */
953 /*! received frame count: (just for stats) */
955 /*! Destroying this call initiated. */
957 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
958 unsigned char calltoken_ie_len;
959 /*! hold all signaling frames from the pbx thread until we have a destination callno */
961 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
963};
964
966 struct ast_frame f;
968};
969
973};
974
975#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
976#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
977
978#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
979#define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
980#define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
981
983 size_t capacity;
984 size_t available;
986};
987
989
990/*! table of available call numbers */
992
993/*! table of available trunk call numbers */
995
996/*!
997 * \brief a list of frames that may need to be retransmitted
998 *
999 * \note The contents of this list do not need to be explicitly destroyed
1000 * on module unload. This is because all active calls are destroyed, and
1001 * all frames in this queue will get destroyed as a part of that process.
1002 *
1003 * \note Contents protected by the iaxsl[] locks
1004 */
1006
1008
1010
1011static time_t max_calltoken_delay = 10;
1012
1013/*!
1014 * This module will get much higher performance when doing a lot of
1015 * user and peer lookups if the number of buckets is increased from 1.
1016 * However, to maintain old behavior for Asterisk 1.4, these are set to
1017 * 1 by default. When using multiple buckets, search order through these
1018 * containers is considered random, so you will not be able to depend on
1019 * the order the entries are specified in iax.conf for matching order. */
1020#ifdef LOW_MEMORY
1021#define MAX_PEER_BUCKETS 17
1022#else
1023#define MAX_PEER_BUCKETS 563
1024#endif
1025static struct ao2_container *peers;
1026
1027#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
1028static struct ao2_container *users;
1029
1030/*! Table containing peercnt objects for every ip address consuming a callno */
1032
1033/*! Table containing custom callno limit rules for a range of ip addresses. */
1035
1036/*! Table containing ip addresses not requiring calltoken validation */
1038
1039static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
1040
1041static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
1042
1043static uint16_t global_maxcallno;
1044
1045/*! Total num of call numbers allowed to be allocated without calltoken validation */
1047
1048static uint16_t total_nonval_callno_used = 0;
1049
1050/*! peer connection private, keeps track of all the call numbers
1051 * consumed by a single ip address */
1052struct peercnt {
1053 /*! ip address consuming call numbers */
1055 /*! Number of call numbers currently used by this ip address */
1056 uint16_t cur;
1057 /*! Max call numbers allowed for this ip address */
1058 uint16_t limit;
1059 /*! Specifies whether limit is set by a registration or not, if so normal
1060 * limit setting rules do not apply to this address. */
1061 unsigned char reg;
1062};
1063
1064/*! used by both callno_limits and calltoken_ignores containers */
1066 /*! ip address range for custom callno limit rule */
1067 struct ast_ha ha;
1068 /*! callno limit for this ip address range, only used in callno_limits container */
1069 uint16_t limit;
1070 /*! delete me marker for reloads */
1071 unsigned char delme;
1072};
1073
1074enum {
1075 /*! Extension exists */
1077 /*! Extension is nonexistent */
1079 /*! Extension can exist */
1081 /*! Waiting to hear back response */
1083 /*! Timed out */
1085 /*! Request transmitted */
1087 /*! Timeout */
1089 /*! Matchmore */
1091};
1092
1096 struct timeval orig;
1097 struct timeval expiry;
1099 unsigned short callno;
1100 int waiters[256];
1103};
1104
1106
1107static void reg_source_db(struct iax2_peer *p);
1108static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1109static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1110
1111static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1112static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1113static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1114
1120};
1121
1125};
1126
1129 size_t len;
1130 unsigned char buf[1];
1131};
1132
1137#ifdef SCHED_MULTITHREADED
1138 void (*schedfunc)(const void *);
1139 const void *scheddata;
1140#endif
1141#ifdef DEBUG_SCHED_MULTITHREAD
1142 char curfunc[80];
1143#endif
1145 pthread_t threadid;
1148 unsigned char readbuf[4096];
1149 unsigned char *buf;
1150 ssize_t buf_len;
1151 size_t buf_size;
1152 int iofd;
1158 /*! if this thread is processing a full frame,
1159 some information about that frame will be stored
1160 here, so we can avoid dispatching any more full
1161 frames for that callno to other threads */
1162 struct {
1163 unsigned short callno;
1165 unsigned char type;
1166 unsigned char csub;
1168 /*! Queued up full frames for processing. If more full frames arrive for
1169 * a call which this thread is already processing a full frame for, they
1170 * are queued up here. */
1172 unsigned char stop;
1173};
1174
1175/* Thread lists */
1179
1180static void *iax2_process_thread(void *data);
1181static void iax2_destroy(int callno);
1182
1184{
1188}
1189
1190/*!
1191 * \brief an array of iax2 pvt structures
1192 *
1193 * The container for active chan_iax2_pvt structures is implemented as an
1194 * array for extremely quick direct access to the correct pvt structure
1195 * based on the local call number. The local call number is used as the
1196 * index into the array where the associated pvt structure is stored.
1197 */
1199
1201{
1202 return iaxs[callno]->callid;
1203}
1204
1206{
1208}
1209
1211{
1213 char buffer[AST_CALLID_BUFFER_LENGTH];
1214 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1216}
1217
1218/*!
1219 * \brief Another container of iax2_pvt structures
1220 *
1221 * Active IAX2 pvt structs are also stored in this container, if they are a part
1222 * of an active call where we know the remote side's call number. The reason
1223 * for this is that incoming media frames do not contain our call number. So,
1224 * instead of having to iterate the entire iaxs array, we use this container to
1225 * look up calls where the remote side is using a given call number.
1226 */
1228
1229/*!
1230 * \brief chan_iax2_pvt structure locks
1231 *
1232 * These locks are used when accessing a pvt structure in the iaxs array.
1233 * The index used here is the same as used in the iaxs array. It is the
1234 * local call number for the associated pvt struct.
1235 */
1237
1238/*!
1239 * \brief Another container of iax2_pvt structures
1240 *
1241 * Active IAX2 pvt structs used during transferring a call are stored here.
1242 */
1244
1245/* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1246 but keeps the division between trunked and non-trunked better. */
1247#define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1248
1249/* Debug routines... */
1251
1252static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1253{
1254 if (iaxdebug ||
1255 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1258 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1259
1260 if (iaxdebug) {
1261 iax_showframe(f, fhi, rx, addr, datalen);
1262 } else {
1263 iaxdebug = 1;
1264 iax_showframe(f, fhi, rx, addr, datalen);
1265 iaxdebug = 0;
1266 }
1267 }
1268}
1269
1270static void iax_debug_output(const char *data)
1271{
1272 if (iaxdebug)
1273 ast_verbose("%s", data);
1274}
1275
1276static void iax_error_output(const char *data)
1277{
1278 ast_log(LOG_WARNING, "%s", data);
1279}
1280
1281static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1282{
1283 va_list args;
1284 char buf[1024];
1285
1286 va_start(args, fmt);
1287 vsnprintf(buf, sizeof(buf), fmt, args);
1288 va_end(args);
1289
1290 ast_log(LOG_ERROR, "%s", buf);
1291}
1292
1293static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1294{
1295 va_list args;
1296 char buf[1024];
1297
1298 va_start(args, fmt);
1299 vsnprintf(buf, sizeof(buf), fmt, args);
1300 va_end(args);
1301
1302 ast_log(LOG_WARNING, "%s", buf);
1303}
1304
1305static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1306{
1307 va_list args;
1308 char buf[1024];
1309
1310 va_start(args, fmt);
1311 vsnprintf(buf, sizeof(buf), fmt, args);
1312 va_end(args);
1313
1314 ast_verbose("%s", buf);
1315}
1316
1317static int expire_registry(const void *data);
1318static int iax2_answer(struct ast_channel *c);
1319static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1320static int iax2_devicestate(const char *data);
1321static int iax2_digit_begin(struct ast_channel *c, char digit);
1322static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1323static int iax2_do_register(struct iax2_registry *reg);
1324static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1325static int iax2_hangup(struct ast_channel *c);
1326static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1327static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1328static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1329static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1330static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1331static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1332static int iax2_sendtext(struct ast_channel *c, const char *text);
1333static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1334static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1335static int iax2_transfer(struct ast_channel *c, const char *dest);
1336static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1337static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1338
1339static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1340static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1341static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1342static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1343static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1344static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1345static 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);
1346static struct ast_frame *iax2_read(struct ast_channel *c);
1347static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1348static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1349static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1350static void *iax2_dup_variable_datastore(void *);
1351static void prune_peers(void);
1352static void prune_users(void);
1353static void iax2_free_variable_datastore(void *);
1354
1355static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1356static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1357static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1358static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1359static void build_rand_pad(unsigned char *buf, ssize_t len);
1360static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1361static int replace_callno(const void *obj);
1362static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1363static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1364static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1365
1367 .type = "IAX2",
1368 .description = tdesc,
1369 .properties = AST_CHAN_TP_WANTSJITTER,
1370 .requester = iax2_request,
1371 .devicestate = iax2_devicestate,
1372 .send_digit_begin = iax2_digit_begin,
1373 .send_digit_end = iax2_digit_end,
1374 .send_text = iax2_sendtext,
1375 .send_image = iax2_sendimage,
1376 .send_html = iax2_sendhtml,
1377 .call = iax2_call,
1378 .hangup = iax2_hangup,
1379 .answer = iax2_answer,
1380 .read = iax2_read,
1381 .write = iax2_write,
1382 .write_video = iax2_write,
1383 .indicate = iax2_indicate,
1384 .setoption = iax2_setoption,
1385 .queryoption = iax2_queryoption,
1386 .transfer = iax2_transfer,
1387 .fixup = iax2_fixup,
1388 .func_channel_read = acf_channel_read,
1389};
1390
1391/*!
1392 * \internal
1393 * \brief Obtain the owner channel lock if the owner exists.
1394 *
1395 * \param callno IAX2 call id.
1396 *
1397 * \note Assumes the iaxsl[callno] lock is already obtained.
1398 *
1399 * \note
1400 * IMPORTANT NOTE!!! Any time this function is used, even if
1401 * iaxs[callno] was valid before calling it, it may no longer be
1402 * valid after calling it. This function may unlock and lock
1403 * the mutex associated with this callno, meaning that another
1404 * thread may grab it and destroy the call.
1405 */
1406static void iax2_lock_owner(int callno)
1407{
1408 for (;;) {
1409 if (!iaxs[callno] || !iaxs[callno]->owner) {
1410 /* There is no owner lock to get. */
1411 break;
1412 }
1413 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1414 /* We got the lock */
1415 break;
1416 }
1417 /* Avoid deadlock by pausing and trying again */
1418 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1419 }
1420}
1421
1422/*!
1423 * \internal
1424 * \brief Check if a control subtype is allowed on the wire.
1425 *
1426 * \param subtype Control frame subtype to check if allowed to/from the wire.
1427 *
1428 * \retval non-zero if allowed.
1429 */
1430static int iax2_is_control_frame_allowed(int subtype)
1431{
1432 enum ast_control_frame_type control = subtype;
1433 int is_allowed;
1434
1435 /*
1436 * Note: If we compare the enumeration type, which does not have any
1437 * negative constants, the compiler may optimize this code away.
1438 * Therefore, we must perform an integer comparison here.
1439 */
1440 if (subtype == -1) {
1441 return -1;
1442 }
1443
1444 /* Default to not allowing control frames to pass. */
1445 is_allowed = 0;
1446
1447 /*
1448 * The switch default is not present in order to take advantage
1449 * of the compiler complaining of a missing enum case.
1450 */
1451 switch (control) {
1452 /*
1453 * These control frames make sense to send/receive across the link.
1454 */
1455 case AST_CONTROL_HANGUP:
1456 case AST_CONTROL_RING:
1458 case AST_CONTROL_ANSWER:
1459 case AST_CONTROL_BUSY:
1463 case AST_CONTROL_FLASH:
1464 case AST_CONTROL_WINK:
1465 case AST_CONTROL_OPTION:
1470 case AST_CONTROL_HOLD:
1471 case AST_CONTROL_UNHOLD:
1476 case AST_CONTROL_AOC:
1478 case AST_CONTROL_MCID:
1479 is_allowed = -1;
1480 break;
1481
1482 /*
1483 * These control frames do not make sense to send/receive across the link.
1484 */
1486 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1488 /* Across an IAX link the source is still the same. */
1490 /* A success/fail status report from calling ast_transfer() on this machine. */
1491 case AST_CONTROL_CC:
1492 /* The payload contains pointers that are valid for the sending machine only. */
1494 /* Across an IAX link the source is still the same. */
1496 /* The action can only be done by the sending machine. */
1498 /* This frame would cause the call to unexpectedly hangup. */
1500 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1502 /* Intended only for the sending machine's local channel structure. */
1504 /* Intended only for masquerades when calling ast_indicate_data(). */
1506 /* Intended only for internal stream topology manipulation. */
1508 /* Intended only for internal stream topology change notification. */
1515 /* None of these playback stream control frames should go across the link. */
1520 /* None of these media recording control frames should go across the link. */
1521 break;
1522 }
1523 return is_allowed;
1524}
1525
1527{
1528 if (!network_change_sub) {
1533 }
1534}
1535
1537{
1539}
1540
1542{
1543 if (!acl_change_sub) {
1548 }
1549}
1550
1552{
1554}
1555
1556static int network_change_sched_cb(const void *data)
1557{
1558 struct iax2_registry *reg;
1562 iax2_do_register(reg);
1563 }
1565
1566 return 0;
1567}
1568
1569static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1570 struct stasis_message *message)
1571{
1572 /* This callback is only concerned with network change messages from the system topic. */
1574 return;
1575 }
1576
1577 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1578 if (network_change_sched_id == -1) {
1580 }
1581}
1582
1583static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1584 struct stasis_message *message)
1585{
1587 return;
1588 }
1589
1590 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1591 reload_config(1);
1592}
1593
1595 .type = "IAX2_VARIABLE",
1596 .duplicate = iax2_dup_variable_datastore,
1598};
1599
1600static void *iax2_dup_variable_datastore(void *old)
1601{
1602 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1603 struct ast_var_t *oldvar, *newvar;
1604
1605 newlist = ast_calloc(sizeof(*newlist), 1);
1606 if (!newlist) {
1607 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1608 return NULL;
1609 }
1610
1611 AST_LIST_HEAD_INIT(newlist);
1612 AST_LIST_LOCK(oldlist);
1613 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1614 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1615 if (newvar)
1616 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1617 else
1618 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1619 }
1620 AST_LIST_UNLOCK(oldlist);
1621 return newlist;
1622}
1623
1624static void iax2_free_variable_datastore(void *old)
1625{
1626 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1627 struct ast_var_t *oldvar;
1628
1629 AST_LIST_LOCK(oldlist);
1630 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1631 ast_free(oldvar);
1632 }
1633 AST_LIST_UNLOCK(oldlist);
1634 AST_LIST_HEAD_DESTROY(oldlist);
1635 ast_free(oldlist);
1636}
1637
1638
1639/* WARNING: insert_idle_thread should only ever be called within the
1640 * context of an iax2_process_thread() thread.
1641 */
1643{
1644 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1648 } else {
1652 }
1653
1654 return;
1655}
1656
1657static struct iax2_thread *find_idle_thread(void)
1658{
1659 struct iax2_thread *thread = NULL;
1660
1661 /* Pop the head of the idle list off */
1665
1666 /* If we popped a thread off the idle list, just return it */
1667 if (thread) {
1668 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1669 return thread;
1670 }
1671
1672 /* Pop the head of the dynamic list off */
1676
1677 /* If we popped a thread off the dynamic list, just return it */
1678 if (thread) {
1679 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1680 return thread;
1681 }
1682
1683 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1685 return NULL;
1686
1687 /* Set default values */
1691
1692 /* Initialize lock and condition */
1693 ast_mutex_init(&thread->lock);
1694 ast_cond_init(&thread->cond, NULL);
1695 ast_mutex_init(&thread->init_lock);
1696 ast_cond_init(&thread->init_cond, NULL);
1697 ast_mutex_lock(&thread->init_lock);
1698
1699 /* Create thread and send it on it's way */
1701 ast_cond_destroy(&thread->cond);
1702 ast_mutex_destroy(&thread->lock);
1703 ast_mutex_unlock(&thread->init_lock);
1704 ast_cond_destroy(&thread->init_cond);
1705 ast_mutex_destroy(&thread->init_lock);
1707 return NULL;
1708 }
1709
1710 /* this thread is not processing a full frame (since it is idle),
1711 so ensure that the field for the full frame call number is empty */
1712 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1713
1714 /* Wait for the thread to be ready before returning it to the caller */
1715 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1716
1717 /* Done with init_lock */
1718 ast_mutex_unlock(&thread->init_lock);
1719
1720 return thread;
1721}
1722
1723#ifdef SCHED_MULTITHREADED
1724static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1725{
1726 struct iax2_thread *thread;
1727 static time_t lasterror;
1728 time_t t;
1729
1731 if (thread != NULL) {
1732 thread->schedfunc = func;
1733 thread->scheddata = data;
1734 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1735#ifdef DEBUG_SCHED_MULTITHREAD
1736 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1737#endif
1738 signal_condition(&thread->lock, &thread->cond);
1739 return 0;
1740 }
1741 time(&t);
1742 if (t != lasterror) {
1743 lasterror = t;
1744 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1745 }
1746
1747 return -1;
1748}
1749#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1750#endif
1751
1752static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1753 ast_sched_cb callback, const void *data)
1754{
1755 return ast_sched_replace(id, con, when, callback, data);
1756}
1757
1758static int iax2_sched_add(struct ast_sched_context *con, int when,
1759 ast_sched_cb callback, const void *data)
1760{
1761 return ast_sched_add(con, when, callback, data);
1762}
1763
1764/*!
1765 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1766 * \param callno Call number to lock.
1767 * \retval 0 If call disappeared or has ongoing hangup procedure.
1768 * \retval 1 If call found and mutex is locked.
1769 */
1771{
1773
1774 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1775 * or destroy initiated (in middle of hang up procedure. */
1776 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1777 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1779 return 0;
1780 }
1781
1782 /* Lock acquired, and callno is alive and kicking. */
1783 return 1;
1784}
1785
1786static int send_ping(const void *data);
1787
1788static void __send_ping(const void *data)
1789{
1790 int callno = PTR_TO_CALLNO(data);
1791
1793 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1794 return;
1795 }
1796
1797 /* Mark pingid as invalid scheduler id. */
1798 iaxs[callno]->pingid = -1;
1799
1800 /* callno is now locked. */
1801 if (iaxs[callno]->peercallno) {
1802 /* Send PING packet. */
1804
1805 /* Schedule sending next ping. */
1807 }
1808
1810}
1811
1812static int send_ping(const void *data)
1813{
1814#ifdef SCHED_MULTITHREADED
1815 if (schedule_action(__send_ping, data))
1816#endif
1817 __send_ping(data);
1818
1819 return 0;
1820}
1821
1822static void encmethods_to_str(int e, struct ast_str **buf)
1823{
1824 ast_str_set(buf, 0, "(");
1825 if (e & IAX_ENCRYPT_AES128) {
1826 ast_str_append(buf, 0, "aes128");
1827 }
1828 if (e & IAX_ENCRYPT_KEYROTATE) {
1829 ast_str_append(buf, 0, ",keyrotate");
1830 }
1831 if (ast_str_strlen(*buf) > 1) {
1832 ast_str_append(buf, 0, ")");
1833 } else {
1834 ast_str_set(buf, 0, "No");
1835 }
1836}
1837
1838static int get_encrypt_methods(const char *s)
1839{
1840 int e;
1841 if (!strcasecmp(s, "aes128"))
1843 else if (ast_true(s))
1845 else
1846 e = 0;
1847 return e;
1848}
1849
1850static int send_lagrq(const void *data);
1851
1852static void __send_lagrq(const void *data)
1853{
1854 int callno = PTR_TO_CALLNO(data);
1855
1857 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1858 return;
1859 }
1860
1861 /* Mark lagid as invalid scheduler id. */
1862 iaxs[callno]->lagid = -1;
1863
1864 /* callno is now locked. */
1865 if (iaxs[callno]->peercallno) {
1866 /* Send LAGRQ packet. */
1868
1869 /* Schedule sending next lagrq. */
1871 }
1872
1874}
1875
1876static int send_lagrq(const void *data)
1877{
1878#ifdef SCHED_MULTITHREADED
1879 if (schedule_action(__send_lagrq, data))
1880#endif
1881 __send_lagrq(data);
1882 return 0;
1883}
1884
1885static unsigned char compress_subclass(iax2_format subclass)
1886{
1887 int x;
1888 int power=-1;
1889 /* If it's 64 or smaller, just return it */
1890 if (subclass < IAX_FLAG_SC_LOG)
1891 return subclass;
1892 /* Otherwise find its power */
1893 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1894 if (subclass & (1LL << x)) {
1895 if (power > -1) {
1896 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1897 return 0;
1898 } else
1899 power = x;
1900 }
1901 }
1902 return power | IAX_FLAG_SC_LOG;
1903}
1904
1906{
1907 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1908 if (csub & IAX_FLAG_SC_LOG) {
1909 /* special case for 'compressed' -1 */
1910 if (csub == 0xff)
1911 return -1;
1912 else
1913 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1914 }
1915 else
1916 return csub;
1917}
1918
1919static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1920{
1921 int x;
1922 struct ast_format *found_format = NULL;
1923
1924 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1925 struct ast_format *pref_format;
1926 uint64_t pref_bitfield;
1927
1928 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1929 if (!pref_bitfield) {
1930 break;
1931 }
1932
1933 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1934 if (!pref_format) {
1935 /* The bitfield is not associated with any format. */
1936 continue;
1937 }
1938 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1939 if (found_format) {
1940 break;
1941 }
1942 }
1943
1944 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1945 return found_format;
1946 }
1947
1948 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1949 ao2_cleanup(found_format);
1950 return NULL;
1951}
1952
1954{
1955 struct ast_format_cap *cap;
1956 struct ast_format *tmpfmt;
1957 iax2_format format = 0;
1958
1961 tmpfmt = codec_choose_from_prefs(pref, cap);
1962 if (!tmpfmt) {
1963 ao2_ref(cap, -1);
1964 return 0;
1965 }
1966
1968 ao2_ref(tmpfmt, -1);
1969 ao2_ref(cap, -1);
1970 }
1971
1972 return format;
1973}
1974
1976{
1977 struct ast_format *tmpfmt;
1978
1980 if (!tmpfmt) {
1981 return "Unknown";
1982 }
1983
1984 return ast_format_get_name(tmpfmt);
1985}
1986
1987static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1988{
1990
1991 if (!cap) {
1992 return "(Nothing)";
1993 }
1995 ast_format_cap_get_names(cap, codec_buf);
1996 ao2_ref(cap, -1);
1997
1998 return ast_str_buffer(*codec_buf);
1999}
2000
2001static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
2002{
2003 int res, i;
2004 struct ast_format_cap *cap;
2005
2006 /* We want to add the formats to the cap in the preferred order */
2008 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
2009 ao2_cleanup(cap);
2010 return 1;
2011 }
2012
2013 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
2014
2015 /* Adjust formats bitfield and pref list to match. */
2018
2019 for (i = 0; i < ast_format_cap_count(cap); i++) {
2020 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
2021
2023 ao2_ref(fmt, -1);
2024 }
2025
2026 ao2_ref(cap, -1);
2027
2028 return res;
2029}
2030
2031/*!
2032 * \note The only member of the peer passed here guaranteed to be set is the name field
2033 */
2034static int peer_hash_cb(const void *obj, const int flags)
2035{
2036 const struct iax2_peer *peer = obj;
2037 const char *name = obj;
2038
2039 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
2040}
2041
2042/*!
2043 * \note The only member of the peer passed here guaranteed to be set is the name field
2044 */
2045static int peer_cmp_cb(void *obj, void *arg, int flags)
2046{
2047 struct iax2_peer *peer = obj, *peer2 = arg;
2048 const char *name = arg;
2049
2050 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
2051 CMP_MATCH | CMP_STOP : 0;
2052}
2053
2054/*!
2055 * \note The only member of the user passed here guaranteed to be set is the name field
2056 */
2057static int user_hash_cb(const void *obj, const int flags)
2058{
2059 const struct iax2_user *user = obj;
2060 const char *name = obj;
2061
2062 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2063}
2064
2065/*!
2066 * \note The only member of the user passed here guaranteed to be set is the name field
2067 */
2068static int user_cmp_cb(void *obj, void *arg, int flags)
2069{
2070 struct iax2_user *user = obj, *user2 = arg;
2071 const char *name = arg;
2072
2073 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2074 CMP_MATCH | CMP_STOP : 0;
2075}
2076
2077/*!
2078 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2079 * so do not call it with a pvt lock held.
2080 */
2081static struct iax2_peer *find_peer(const char *name, int realtime)
2082{
2083 struct iax2_peer *peer = NULL;
2084
2085 peer = ao2_find(peers, name, OBJ_KEY);
2086
2087 /* Now go for realtime if applicable */
2088 if (!peer && realtime) {
2089 peer = realtime_peer(name, NULL);
2090 }
2091 return peer;
2092}
2093
2094static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2095{
2096 ao2_ref(peer, +1);
2097 return peer;
2098}
2099
2100static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2101{
2102 ao2_ref(peer, -1);
2103 return NULL;
2104}
2105
2106static struct iax2_user *find_user(const char *name)
2107{
2108 return ao2_find(users, name, OBJ_KEY);
2109}
2110
2111static inline struct iax2_user *user_unref(struct iax2_user *user)
2112{
2113 ao2_ref(user, -1);
2114 return NULL;
2115}
2116
2117static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2118{
2119 struct iax2_peer *peer = NULL;
2120 int res = 0;
2121 struct ao2_iterator i;
2122
2123 i = ao2_iterator_init(peers, 0);
2124 while ((peer = ao2_iterator_next(&i))) {
2125
2126 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2127 ast_copy_string(host, peer->name, len);
2128 peer_unref(peer);
2129 res = 1;
2130 break;
2131 }
2132 peer_unref(peer);
2133 }
2135
2136 if (!peer) {
2137 peer = realtime_peer(NULL, &addr);
2138 if (peer) {
2139 ast_copy_string(host, peer->name, len);
2140 peer_unref(peer);
2141 res = 1;
2142 }
2143 }
2144
2145 return res;
2146}
2147
2148/* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2149static int iax2_delete_from_sched(const void* data)
2150{
2151 int sched_id = (int)(long)data;
2152
2154
2155 return 0;
2156}
2157
2158/*!\note Assumes the lock on the pvt is already held, when
2159 * iax2_destroy_helper() is called. */
2160static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2161{
2162 /* Decrement AUTHREQ count if needed */
2163 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2164 struct iax2_user *user;
2165
2167 if (user) {
2168 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2170 }
2171
2173 }
2174
2175
2176 /* Mark call destroy initiated flag. */
2177 pvt->destroy_initiated = 1;
2178
2179 /*
2180 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2181 * Already running tasks will be terminated because of destroy_initiated.
2182 *
2183 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2184 * it leads to a deadlock between the scheduler thread callback locking
2185 * the callno mutex and this thread which holds the callno mutex one or
2186 * more times. It is better to have another thread delete the scheduled
2187 * callbacks which doesn't lock the callno mutex.
2188 */
2189 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2190 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2191
2192 pvt->pingid = -1;
2193 pvt->lagid = -1;
2194
2195 AST_SCHED_DEL(sched, pvt->autoid);
2196 AST_SCHED_DEL(sched, pvt->authid);
2197 AST_SCHED_DEL(sched, pvt->initid);
2198 AST_SCHED_DEL(sched, pvt->jbid);
2200}
2201
2202static void iax2_frame_free(struct iax_frame *fr)
2203{
2205 iax_frame_free(fr);
2206}
2207
2208static int scheduled_destroy(const void *vid)
2209{
2210 unsigned short callno = PTR_TO_CALLNO(vid);
2211 ast_mutex_lock(&iaxsl[callno]);
2212 if (iaxs[callno]) {
2213 ast_debug(1, "Really destroying %d now...\n", callno);
2214 iax2_destroy(callno);
2215 }
2216 ast_mutex_unlock(&iaxsl[callno]);
2217 return 0;
2218}
2219
2221{
2222 if (s->f.datalen) {
2223 ast_free(s->f.data.ptr);
2224 }
2225 ast_free(s);
2226}
2227
2228/*! \brief This function must be called once we are sure the other side has
2229 * given us a call number. All signaling is held here until that point. */
2230static void send_signaling(struct chan_iax2_pvt *pvt)
2231{
2232 struct signaling_queue_entry *s = NULL;
2233
2234 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2235 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2237 }
2238 pvt->hold_signaling = 0;
2239}
2240
2241/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2242 * we have received a destination call number. */
2243static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2244{
2245 struct signaling_queue_entry *qe;
2246
2247 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2248 return 1; /* do not queue this frame */
2249 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2250 return -1; /* out of memory */
2251 }
2252
2253 /* copy ast_frame into our queue entry */
2254 qe->f = *f;
2255 if (qe->f.datalen) {
2256 /* if there is data in this frame copy it over as well */
2257 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2259 return -1;
2260 }
2261 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2262 }
2264
2265 return 0;
2266}
2267
2268static void pvt_destructor(void *obj)
2269{
2270 struct chan_iax2_pvt *pvt = obj;
2271 struct iax_frame *cur = NULL;
2272 struct signaling_queue_entry *s = NULL;
2273
2274 ast_mutex_lock(&iaxsl[pvt->callno]);
2275
2277
2279 pvt->callno_entry = 0;
2280
2281 /* Already gone */
2283
2284 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2285 /* Cancel any pending transmissions */
2286 cur->retries = -1;
2287 }
2288
2290
2291 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2293 }
2294
2295 if (pvt->reg) {
2296 pvt->reg->callno = 0;
2297 }
2298
2299 if (!pvt->owner) {
2300 jb_frame frame;
2301 if (pvt->vars) {
2303 pvt->vars = NULL;
2304 }
2305
2306 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2307 iax2_frame_free(frame.data);
2308 }
2309
2310 jb_destroy(pvt->jb);
2312 }
2313}
2314
2315static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2316{
2317 struct chan_iax2_pvt *tmp;
2318 jb_conf jbconf;
2319
2320 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2321 return NULL;
2322 }
2323
2324 tmp->pingid = -1;
2325 tmp->lagid = -1;
2326 tmp->autoid = -1;
2327 tmp->authid = -1;
2328 tmp->initid = -1;
2329 tmp->keyrotateid = -1;
2330 tmp->jbid = -1;
2331
2332 if (ast_string_field_init(tmp, 32)) {
2333 ao2_ref(tmp, -1);
2334 tmp = NULL;
2335 return NULL;
2336 }
2337
2338 tmp->prefs = prefs_global;
2339
2340 ast_string_field_set(tmp,exten, "s");
2342
2343 tmp->jb = jb_new();
2348 jb_setconf(tmp->jb,&jbconf);
2349
2351
2352 tmp->hold_signaling = 1;
2354
2355 return tmp;
2356}
2357
2358static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2359{
2361 if (new) {
2362 size_t afdatalen = new->afdatalen;
2363 memcpy(new, fr, sizeof(*new));
2364 iax_frame_wrap(new, &fr->af);
2365 new->afdatalen = afdatalen;
2366 new->data = NULL;
2367 new->datalen = 0;
2368 new->direction = DIRECTION_INGRESS;
2369 new->retrans = -1;
2370 }
2371 return new;
2372}
2373/* keep these defined in this order. They are used in find_callno to
2374 * determine whether or not a new call number should be allowed. */
2375enum {
2376 /* do not allow a new call number, only search ones in use for match */
2378 /* search for match first, then allow a new one to be allocated */
2380 /* do not search for match, force a new call number */
2382 /* do not search for match, force a new call number. Signifies call number
2383 * has been calltoken validated */
2385};
2386
2387static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2388{
2389 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2390 /* This is the main host */
2391 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2392 (check_dcallno ? dcallno == cur->callno : 1) ) {
2393 /* That's us. Be sure we keep track of the peer call number */
2394 return 1;
2395 }
2396 }
2397 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2398 /* We're transferring */
2399 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2400 return 1;
2401 }
2402 return 0;
2403}
2404
2405static int make_trunk(unsigned short callno, int locked)
2406{
2407 int x;
2408 int res= 0;
2409 callno_entry entry;
2410 if (iaxs[callno]->oseqno) {
2411 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2412 return -1;
2413 }
2414 if (callno >= TRUNK_CALL_START) {
2415 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2416 return -1;
2417 }
2418
2422 &entry)) {
2423 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2424 return -1;
2425 }
2426
2427 x = CALLNO_ENTRY_GET_CALLNO(entry);
2428 ast_mutex_lock(&iaxsl[x]);
2429
2430 /*!
2431 * \note We delete these before switching the slot, because if
2432 * they fire in the meantime, they will generate a warning.
2433 */
2434 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2435 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2436 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2437 iaxs[x] = iaxs[callno];
2438 iaxs[x]->callno = x;
2439
2440 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2441 * before assigning the new one */
2442 if (iaxs[x]->callno_entry) {
2444 sched,
2445 MIN_REUSE_TIME * 1000,
2448
2449 }
2450 iaxs[x]->callno_entry = entry;
2451
2452 iaxs[callno] = NULL;
2453 /* Update the two timers that should have been started */
2455 ping_time * 1000, send_ping, (void *)(long)x);
2457 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2458
2459 if (locked)
2461 res = x;
2462 if (!locked)
2464
2465 /* We moved this call from a non-trunked to a trunked call */
2466 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2467
2468 return res;
2469}
2470
2472{
2473 if (!pvt->transfercallno) {
2474 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2475 return;
2476 }
2477
2479}
2480
2482{
2483 if (!pvt->transfercallno) {
2484 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2485 return;
2486 }
2487
2489}
2490static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2491{
2492 if (!pvt->peercallno) {
2493 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2494 return;
2495 }
2496
2498}
2499
2500static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2501{
2502 if (!pvt->peercallno) {
2503 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2504 return;
2505 }
2506
2508}
2509
2510static int addr_range_delme_cb(void *obj, void *arg, int flags)
2511{
2512 struct addr_range *lim = obj;
2513 lim->delme = 1;
2514 return 0;
2515}
2516
2517static int addr_range_hash_cb(const void *obj, const int flags)
2518{
2519 const struct addr_range *lim = obj;
2520 return abs(ast_sockaddr_hash(&lim->ha.addr));
2521}
2522
2523static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2524{
2525 struct addr_range *lim1 = obj, *lim2 = arg;
2526 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2527 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2528 CMP_MATCH | CMP_STOP : 0;
2529}
2530
2531static int peercnt_hash_cb(const void *obj, const int flags)
2532{
2533 const struct peercnt *peercnt = obj;
2534
2536 return 0;
2537 }
2538 return ast_sockaddr_hash(&peercnt->addr);
2539}
2540
2541static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2542{
2543 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2544 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2545}
2546
2547static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2548{
2549 struct addr_range *addr_range = obj;
2550 struct ast_sockaddr *addr = arg;
2551 struct ast_sockaddr tmp_addr;
2552
2553 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2554
2555 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2556 return CMP_MATCH | CMP_STOP;
2557 }
2558 return 0;
2559}
2560
2561/*!
2562 * \internal
2563 *
2564 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2565 */
2566static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2567{
2568 struct addr_range *addr_range;
2569 struct iax2_peer *peer = NULL;
2570 struct iax2_user *user = NULL;
2571 /* if no username is given, check for guest accounts */
2572 const char *find = S_OR(name, "guest");
2573 int res = 1; /* required by default */
2574 int optional = 0;
2576 /* There are only two cases in which calltoken validation is not required.
2577 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2578 * the peer definition has not set the requirecalltoken option.
2579 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2580 */
2581
2582 /* ----- Case 1 ----- */
2584 ao2_ref(addr_range, -1);
2585 optional = 1;
2586 }
2587
2588 /* ----- Case 2 ----- */
2589 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2590 calltoken_required = user->calltoken_required;
2591 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2592 calltoken_required = user->calltoken_required;
2593 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2595 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2597 }
2598
2599 if (peer) {
2600 peer_unref(peer);
2601 }
2602 if (user) {
2604 }
2605
2606 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);
2608 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2609 res = 0;
2610 }
2611
2612 return res;
2613}
2614
2615/*!
2616 * \internal
2617 *
2618 * \brief set peercnt callno limit.
2619 *
2620 * \details
2621 * First looks in custom definitions. If not found, global limit
2622 * is used. Entries marked as reg already have
2623 * a custom limit set by a registration and are not modified.
2624 */
2626{
2627 uint16_t limit = global_maxcallno;
2628 struct addr_range *addr_range;
2629 struct ast_sockaddr addr;
2630
2631 ast_sockaddr_copy(&addr, &peercnt->addr);
2632
2633 if (peercnt->reg && peercnt->limit) {
2634 return; /* this peercnt has a custom limit set by a registration */
2635 }
2636
2638 limit = addr_range->limit;
2639 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2640 ao2_ref(addr_range, -1);
2641 }
2642
2643 peercnt->limit = limit;
2644}
2645
2646/*!
2647 * \internal
2648 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2649 */
2650static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2651{
2652 struct peercnt *peercnt = obj;
2653
2655 ast_debug(1, "Reset limits for peercnts table\n");
2656
2657 return 0;
2658}
2659
2660/*!
2661 * \internal
2662 * \brief returns match if delme is set.
2663 */
2664static int prune_addr_range_cb(void *obj, void *arg, int flags)
2665{
2666 struct addr_range *addr_range = obj;
2667
2668 return addr_range->delme ? CMP_MATCH : 0;
2669}
2670
2671/*!
2672 * \internal
2673 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2674 */
2675static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2676{
2677 /* this function turns off and on custom callno limits set by peer registration */
2678 struct peercnt *peercnt;
2679 struct peercnt tmp;
2680
2681 ast_sockaddr_copy(&tmp.addr, sockaddr);
2682
2683 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2684 peercnt->reg = reg;
2685 if (limit) {
2686 peercnt->limit = limit;
2687 } else {
2689 }
2690 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2691 ao2_ref(peercnt, -1); /* decrement ref from find */
2692 }
2693}
2694
2695/*!
2696 * \internal
2697 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2698 *
2699 * \details First searches for the address in the peercnts table. If found
2700 * the current count is incremented. If not found a new peercnt is allocated
2701 * and linked into the peercnts table with a call number count of 1.
2702 */
2703static int peercnt_add(struct ast_sockaddr *addr)
2704{
2705 struct peercnt *peercnt;
2706 int res = 0;
2707 struct peercnt tmp;
2708
2710
2711 /* Reasoning for peercnts container lock: Two identical ip addresses
2712 * could be added by different threads at the "same time". Without the container
2713 * lock, both threads could alloc space for the same object and attempt
2714 * to link to table. With the lock, one would create the object and link
2715 * to table while the other would find the already created peercnt object
2716 * rather than creating a new one. */
2718 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2720 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2722 /* create and set defaults */
2725 /* guarantees it does not go away after unlocking table
2726 * ao2_find automatically adds this */
2728 } else {
2730 return -1;
2731 }
2732
2733 /* check to see if the address has hit its callno limit. If not increment cur. */
2734 if (peercnt->limit > peercnt->cur) {
2735 peercnt->cur++;
2736 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2737 } else { /* max num call numbers for this peer has been reached! */
2738 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2739 res = -1;
2740 }
2741
2742 /* clean up locks and ref count */
2745 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2746
2747 return res;
2748}
2749
2750/*!
2751 * \internal
2752 * \brief decrements a peercnts table entry
2753 */
2754static void peercnt_remove(struct peercnt *peercnt)
2755{
2756 struct ast_sockaddr addr;
2757
2758 ast_sockaddr_copy(&addr, &peercnt->addr);
2759
2760 /*
2761 * Container locked here since peercnt may be unlinked from
2762 * list. If left unlocked, peercnt_add could try and grab this
2763 * entry from the table and modify it at the "same time" this
2764 * thread attempts to unlink it.
2765 */
2767 peercnt->cur--;
2768 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2769 /* if this was the last connection from the peer remove it from table */
2770 if (peercnt->cur == 0) {
2771 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2772 }
2774}
2775
2776/*!
2777 * \internal
2778 * \brief called by scheduler to decrement object
2779 */
2780static int peercnt_remove_cb(const void *obj)
2781{
2782 struct peercnt *peercnt = (struct peercnt *) obj;
2783
2785 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2786
2787 return 0;
2788}
2789
2790/*!
2791 * \internal
2792 * \brief decrements peercnts connection count, finds by addr
2793 */
2795{
2796 struct peercnt *peercnt;
2797 struct peercnt tmp;
2798
2800
2801 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2803 ao2_ref(peercnt, -1); /* decrement ref from find */
2804 }
2805 return 0;
2806}
2807
2808/*!
2809 * \internal
2810 * \brief Create callno_limit entry based on configuration
2811 */
2812static void build_callno_limits(struct ast_variable *v)
2813{
2814 struct addr_range *addr_range = NULL;
2815 struct addr_range tmp;
2816 struct ast_ha *ha;
2817 int limit;
2818 int error;
2819 int found;
2820
2821 for (; v; v = v->next) {
2822 limit = -1;
2823 error = 0;
2824 found = 0;
2825 ha = ast_append_ha("permit", v->name, NULL, &error);
2826
2827 /* check for valid config information */
2828 if (error) {
2829 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2830 continue;
2831 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2832 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2833 ast_free_ha(ha);
2834 continue;
2835 }
2836
2837 ast_copy_ha(ha, &tmp.ha);
2838 /* find or create the addr_range */
2839 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2841 found = 1;
2842 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2843 ast_free_ha(ha);
2844 return; /* out of memory */
2845 }
2846
2847 /* copy over config data into addr_range object */
2848 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2849 ast_free_ha(ha); /* cleanup the tmp ha */
2850 addr_range->limit = limit;
2851 addr_range->delme = 0;
2852
2853 /* cleanup */
2854 if (found) {
2856 } else {
2858 }
2859 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2860 }
2861}
2862
2863/*!
2864 * \internal
2865 * \brief Create calltoken_ignores entry based on configuration
2866 */
2867static int add_calltoken_ignore(const char *addr)
2868{
2869 struct addr_range tmp;
2870 struct addr_range *addr_range = NULL;
2871 struct ast_ha *ha = NULL;
2872 int error = 0;
2873
2874 if (ast_strlen_zero(addr)) {
2875 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2876 return -1;
2877 }
2878
2879 ha = ast_append_ha("permit", addr, NULL, &error);
2880
2881 /* check for valid config information */
2882 if (error) {
2883 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2884 return -1;
2885 }
2886
2887 ast_copy_ha(ha, &tmp.ha);
2888 /* find or create the addr_range */
2891 addr_range->delme = 0;
2893 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2894 /* copy over config data into addr_range object */
2895 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2897 } else {
2898 ast_free_ha(ha);
2899 return -1;
2900 }
2901
2902 ast_free_ha(ha);
2903 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2904
2905 return 0;
2906}
2907
2908static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2909{
2910 struct ao2_iterator i;
2911 struct peercnt *peercnt;
2912 struct ast_sockaddr addr;
2913 int found = 0;
2914
2915 switch (cmd) {
2916 case CLI_INIT:
2917 e->command = "iax2 show callnumber usage";
2918 e->usage =
2919 "Usage: iax2 show callnumber usage [IP address]\n"
2920 " Shows current IP addresses which are consuming iax2 call numbers\n";
2921 return NULL;
2922 case CLI_GENERATE:
2923 return NULL;
2924 case CLI_HANDLER:
2925 if (a->argc < 4 || a->argc > 5)
2926 return CLI_SHOWUSAGE;
2927
2928 if (a->argc == 4) {
2929 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2930 }
2931
2933 while ((peercnt = ao2_iterator_next(&i))) {
2934 ast_sockaddr_copy(&addr, &peercnt->addr);
2935
2936 if (a->argc == 5) {
2937 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2938 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2939 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2940 ao2_ref(peercnt, -1);
2941 found = 1;
2942 break;
2943 }
2944 } else {
2945 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2946 }
2947 ao2_ref(peercnt, -1);
2948 }
2950
2951 if (a->argc == 4) {
2952 size_t pool_avail = callno_pool.available;
2953 size_t trunk_pool_avail = callno_pool_trunk.available;
2954
2955 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2956 "Non-CallToken Validated Callno Used: %d\n",
2959
2960 ast_cli(a->fd, "Total Available Callno: %zu\n"
2961 "Regular Callno Available: %zu\n"
2962 "Trunk Callno Available: %zu\n",
2963 pool_avail + trunk_pool_avail,
2964 pool_avail,
2965 trunk_pool_avail);
2966 } else if (a->argc == 5 && !found) {
2967 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2968 }
2969
2970
2971 return CLI_SUCCESS;
2972 default:
2973 return NULL;
2974 }
2975}
2976
2977static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2978{
2979 struct call_number_pool *pool = NULL;
2980 callno_entry swap;
2981 size_t choice;
2982
2983 switch (type) {
2984 case CALLNO_TYPE_NORMAL:
2985 pool = &callno_pool;
2986 break;
2987 case CALLNO_TYPE_TRUNK:
2988 pool = &callno_pool_trunk;
2989 break;
2990 default:
2991 ast_assert(0);
2992 break;
2993 }
2994
2995 /* If we fail, make sure this has a defined value */
2996 *entry = 0;
2997
2998 /* We lock here primarily to ensure thread safety of the
2999 * total_nonval_callno_used check and increment */
3001
3002 /* Bail out if we don't have any available call numbers */
3003 if (!pool->available) {
3004 ast_log(LOG_WARNING, "Out of call numbers\n");
3006 return 1;
3007 }
3008
3009 /* Only a certain number of non-validated call numbers should be allocated.
3010 * If there ever is an attack, this separates the calltoken validating users
3011 * from the non-calltoken validating users. */
3014 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
3018 return 1;
3019 }
3020
3021 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
3022 * available call numbers. The array of call numbers begins as an ordered
3023 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
3024 * - let's call that x. When a call number is needed we pick a random index
3025 * into the array between 0 and x and use that as our call number. In a
3026 * typical FYD shuffle, we would swap the value that we are extracting with
3027 * the number at x, but in our case we swap and don't touch the value at x
3028 * because it is effectively invisible. We rely on the rest of the IAX2 core
3029 * to return the number to us at some point. Finally, we decrement x by 1
3030 * which establishes our new unused range.
3031 *
3032 * When numbers are returned to the pool, we put them just past x and bump x
3033 * by 1 so that this number is now available for re-use. */
3034
3035 choice = ast_random() % pool->available;
3036
3037 *entry = pool->numbers[choice];
3038 swap = pool->numbers[pool->available - 1];
3039
3040 pool->numbers[choice] = swap;
3041 pool->available--;
3042
3043 if (validated) {
3045 } else {
3047 }
3048
3050
3051 return 0;
3052}
3053
3054static int replace_callno(const void *obj)
3055{
3056 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
3057 struct call_number_pool *pool;
3058
3059 /* We lock here primarily to ensure thread safety of the
3060 * total_nonval_callno_used check and decrement */
3062
3063 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
3066 } else {
3068 "Attempted to decrement total non calltoken validated "
3069 "callnumbers below zero. Callno is: %d\n",
3071 }
3072 }
3073
3075 pool = &callno_pool;
3076 } else {
3077 pool = &callno_pool_trunk;
3078 }
3079
3080 ast_assert(pool->capacity > pool->available);
3081
3082 /* This clears the validated flag */
3083 entry = CALLNO_ENTRY_GET_CALLNO(entry);
3084
3085 pool->numbers[pool->available] = entry;
3086 pool->available++;
3087
3089
3090 return 0;
3091}
3092
3093static int create_callno_pools(void)
3094{
3095 uint16_t i;
3096
3098
3099 /* We start at 2. 0 and 1 are reserved. */
3100 for (i = 2; i < TRUNK_CALL_START; i++) {
3103 }
3104
3105 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3108 }
3109
3112
3114
3115 return 0;
3116}
3117
3118/*!
3119 * \internal
3120 * \brief Schedules delayed removal of iax2_pvt call number data
3121 *
3122 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3123 * available again, and the address from the previous connection must be decremented
3124 * from the peercnts table. This function schedules these operations to take place.
3125 */
3126static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3127{
3128 int i;
3129 struct peercnt *peercnt;
3130 struct peercnt tmp;
3131
3133
3134 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3135 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3136 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3138 if (i == -1) {
3139 ao2_ref(peercnt, -1);
3140 }
3141 }
3142
3144 sched,
3145 MIN_REUSE_TIME * 1000,
3147 CALLNO_ENTRY_TO_PTR(entry));
3148}
3149
3150/*!
3151 * \internal
3152 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3153 *
3154 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3155 * a new callno.
3156 */
3157static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3158{
3159 if (frametype != AST_FRAME_IAX) {
3160 return 0;
3161 }
3162 switch (subclass) {
3163 case IAX_COMMAND_NEW:
3164 case IAX_COMMAND_REGREQ:
3166 case IAX_COMMAND_REGREL:
3167 return 1;
3168 case IAX_COMMAND_POKE:
3169 if (!inbound) {
3170 return 1;
3171 }
3172 break;
3173 }
3174 return 0;
3175}
3176
3177/*!
3178 * \note Calling this function while holding another pvt lock can cause a deadlock.
3179 */
3180static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3181{
3182 int res = 0;
3183 int x;
3184 /* this call is calltoken validated as long as it is either NEW_FORCE
3185 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3186 int validated = (new > NEW_ALLOW) ? 1 : 0;
3187 char host[80];
3188
3189 if (new <= NEW_ALLOW) {
3190 if (callno) {
3191 struct chan_iax2_pvt *pvt;
3192 struct chan_iax2_pvt tmp_pvt = {
3193 .callno = dcallno,
3194 .peercallno = callno,
3195 .transfercallno = callno,
3196 /* hack!! */
3197 .frames_received = check_dcallno,
3198 };
3199
3200 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3201 /* this works for finding normal call numbers not involving transferring */
3202 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3203 if (return_locked) {
3204 ast_mutex_lock(&iaxsl[pvt->callno]);
3205 }
3206 res = pvt->callno;
3207 ao2_ref(pvt, -1);
3208 pvt = NULL;
3209 return res;
3210 }
3211 /* this searches for transfer call numbers that might not get caught otherwise */
3212 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3213 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3214 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3215 if (return_locked) {
3216 ast_mutex_lock(&iaxsl[pvt->callno]);
3217 }
3218 res = pvt->callno;
3219 ao2_ref(pvt, -1);
3220 pvt = NULL;
3221 return res;
3222 }
3223 }
3224 /* This will occur on the first response to a message that we initiated,
3225 * such as a PING. */
3226 if (dcallno) {
3227 ast_mutex_lock(&iaxsl[dcallno]);
3228 }
3229 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3230 iaxs[dcallno]->peercallno = callno;
3231 res = dcallno;
3232 store_by_peercallno(iaxs[dcallno]);
3233 if (!res || !return_locked) {
3234 ast_mutex_unlock(&iaxsl[dcallno]);
3235 }
3236 return res;
3237 }
3238 if (dcallno) {
3239 ast_mutex_unlock(&iaxsl[dcallno]);
3240 }
3241 }
3242 if (!res && (new >= NEW_ALLOW)) {
3243 callno_entry entry;
3244
3245 /* It may seem odd that we look through the peer list for a name for
3246 * this *incoming* call. Well, it is weird. However, users don't
3247 * have an IP address/port number that we can match against. So,
3248 * this is just checking for a peer that has that IP/port and
3249 * assuming that we have a user of the same name. This isn't always
3250 * correct, but it will be changed if needed after authentication. */
3251 if (!iax2_getpeername(*addr, host, sizeof(host)))
3252 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3253
3254 if (peercnt_add(addr)) {
3255 /* This address has hit its callnumber limit. When the limit
3256 * is reached, the connection is not added to the peercnts table.*/
3257 return 0;
3258 }
3259
3260 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3261 /* since we ran out of space, remove the peercnt
3262 * entry we added earlier */
3264 ast_log(LOG_WARNING, "No more space\n");
3265 return 0;
3266 }
3267 x = CALLNO_ENTRY_GET_CALLNO(entry);
3268 ast_mutex_lock(&iaxsl[x]);
3269
3270 iaxs[x] = new_iax(addr, host);
3271 if (iaxs[x]) {
3272 if (iaxdebug)
3273 ast_debug(1, "Creating new call structure %d\n", x);
3274 iaxs[x]->callno_entry = entry;
3275 iaxs[x]->sockfd = sockfd;
3277 iaxs[x]->peercallno = callno;
3278 iaxs[x]->callno = x;
3281 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3282 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3283 iaxs[x]->amaflags = amaflags;
3289
3290 if (iaxs[x]->peercallno) {
3292 }
3293 } else {
3294 ast_log(LOG_WARNING, "Out of resources\n");
3297 return 0;
3298 }
3299 if (!return_locked)
3301 res = x;
3302 }
3303 return res;
3304}
3305
3306static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3307 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3308}
3309
3310static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3311
3312 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3313}
3314
3315/*!
3316 * \brief Queue a frame to a call's owning asterisk channel
3317 *
3318 * \pre This function assumes that iaxsl[callno] is locked when called.
3319 *
3320 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3321 * was valid before calling it, it may no longer be valid after calling it.
3322 * This function may unlock and lock the mutex associated with this callno,
3323 * meaning that another thread may grab it and destroy the call.
3324 */
3325static int iax2_queue_frame(int callno, struct ast_frame *f)
3326{
3328 if (iaxs[callno] && iaxs[callno]->owner) {
3331 }
3332 return 0;
3333}
3334
3335/*!
3336 * \brief Queue a hold frame on the ast_channel owner
3337 *
3338 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3339 * is active for the given call number.
3340 *
3341 * \pre Assumes lock for callno is already held.
3342 *
3343 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3344 * was valid before calling it, it may no longer be valid after calling it.
3345 * This function may unlock and lock the mutex associated with this callno,
3346 * meaning that another thread may grab it and destroy the call.
3347 */
3348static int iax2_queue_hold(int callno, const char *musicclass)
3349{
3351 if (iaxs[callno] && iaxs[callno]->owner) {
3352 ast_queue_hold(iaxs[callno]->owner, musicclass);
3354 }
3355 return 0;
3356}
3357
3358/*!
3359 * \brief Queue an unhold frame on the ast_channel owner
3360 *
3361 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3362 * is active for the given call number.
3363 *
3364 * \pre Assumes lock for callno is already held.
3365 *
3366 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3367 * was valid before calling it, it may no longer be valid after calling it.
3368 * This function may unlock and lock the mutex associated with this callno,
3369 * meaning that another thread may grab it and destroy the call.
3370 */
3372{
3374 if (iaxs[callno] && iaxs[callno]->owner) {
3377 }
3378 return 0;
3379}
3380
3381/*!
3382 * \brief Queue a hangup frame on the ast_channel owner
3383 *
3384 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3385 * is active for the given call number.
3386 *
3387 * \pre Assumes lock for callno is already held.
3388 *
3389 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3390 * was valid before calling it, it may no longer be valid after calling it.
3391 * This function may unlock and lock the mutex associated with this callno,
3392 * meaning that another thread may grab it and destroy the call.
3393 */
3395{
3397 if (iaxs[callno] && iaxs[callno]->owner) {
3400 }
3401 return 0;
3402}
3403
3404/*!
3405 * \note This function assumes that iaxsl[callno] is locked when called.
3406 *
3407 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3408 * was valid before calling it, it may no longer be valid after calling it.
3409 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3410 * associated with this callno, meaning that another thread may grab it and destroy the call.
3411 */
3412static int __do_deliver(void *data)
3413{
3414 /* Just deliver the packet by using queueing. This is called by
3415 the IAX thread with the iaxsl lock held. */
3416 struct iax_frame *fr = data;
3417 fr->retrans = -1;
3420 iax2_queue_frame(fr->callno, &fr->af);
3421 /* Free our iax frame */
3422 iax2_frame_free(fr);
3423 /* And don't run again */
3424 return 0;
3425}
3426
3427static int handle_error(void)
3428{
3429 /* XXX Ideally we should figure out why an error occurred and then abort those
3430 rather than continuing to try. Unfortunately, the published interface does
3431 not seem to work XXX */
3432#if 0
3433 struct sockaddr_in *sin;
3434 int res;
3435 struct msghdr m;
3436 struct sock_extended_err e;
3437 m.msg_name = NULL;
3438 m.msg_namelen = 0;
3439 m.msg_iov = NULL;
3440 m.msg_control = &e;
3441 m.msg_controllen = sizeof(e);
3442 m.msg_flags = 0;
3443 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3444 if (res < 0)
3445 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3446 else {
3447 if (m.msg_controllen) {
3448 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3449 if (sin)
3450 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3451 else
3452 ast_log(LOG_WARNING, "No address detected??\n");
3453 } else {
3454 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3455 }
3456 }
3457#endif
3458 return 0;
3459}
3460
3461static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3462{
3463 int res;
3464 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3465
3466 if (res < 0) {
3467 ast_debug(1, "Received error: %s\n", strerror(errno));
3468 handle_error();
3469 } else
3470 res = 0;
3471 return res;
3472}
3473
3474static int send_packet(struct iax_frame *f)
3475{
3476 int res;
3477 int callno = f->callno;
3478
3479 /* Don't send if there was an error, but return error instead */
3480 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3481 return -1;
3482
3483 /* Called with iaxsl held */
3484 if (iaxdebug) {
3485 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3486 }
3487 if (f->transfer) {
3488 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3489 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3490 } else {
3491 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3492 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3493 }
3494 if (res < 0) {
3495 if (iaxdebug)
3496 ast_debug(1, "Received error: %s\n", strerror(errno));
3497 handle_error();
3498 } else
3499 res = 0;
3500
3501 return res;
3502}
3503
3504/*!
3505 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3506 * for the given call number may disappear during its execution.
3507 */
3508static int iax2_predestroy(int callno)
3509{
3510 struct ast_channel *c = NULL;
3511 struct chan_iax2_pvt *pvt = iaxs[callno];
3512
3513 if (!pvt)
3514 return -1;
3515
3516 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3519 }
3520
3521 if ((c = pvt->owner)) {
3524 pvt->owner = NULL;
3526 }
3527
3528 return 0;
3529}
3530
3531static void iax2_destroy(int callno)
3532{
3533 struct chan_iax2_pvt *pvt = NULL;
3534 struct ast_channel *owner = NULL;
3535
3536retry:
3537 if ((pvt = iaxs[callno])) {
3538#if 0
3539 /* iax2_destroy_helper gets called from this function later on. When
3540 * called twice, we get the (previously) familiar FRACK! errors in
3541 * devmode, from the scheduler. An alternative to this approach is to
3542 * reset the scheduler entries to -1 when they're deleted in
3543 * iax2_destroy_helper(). That approach was previously decided to be
3544 * "wrong" because "the memory is going to be deallocated anyway. Why
3545 * should we be resetting those values?" */
3547#endif
3548 }
3549
3550 owner = pvt ? pvt->owner : NULL;
3551
3552 if (owner) {
3553 if (ast_channel_trylock(owner)) {
3554 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3555 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3556 goto retry;
3557 }
3558 }
3559
3560 if (!owner) {
3561 iaxs[callno] = NULL;
3562 }
3563
3564 if (pvt) {
3565 if (!owner) {
3566 pvt->owner = NULL;
3567 } else {
3568 /* If there's an owner, prod it to give up */
3569 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3570 * because we already hold the owner channel lock. */
3571 ast_queue_hangup(owner);
3572 }
3573
3574 if (pvt->peercallno) {
3576 }
3577
3578 if (pvt->transfercallno) {
3580 }
3581
3582 if (!owner) {
3583 ao2_ref(pvt, -1);
3584 pvt = NULL;
3585 }
3586 }
3587
3588 if (owner) {
3589 ast_channel_unlock(owner);
3590 }
3591}
3592
3593static int update_packet(struct iax_frame *f)
3594{
3595 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3596 struct ast_iax2_full_hdr *fh = f->data;
3597 struct ast_frame af;
3598
3599 /* if frame is encrypted. decrypt before updating it. */
3600 if (f->encmethods) {
3601 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3602 }
3603 /* Mark this as a retransmission */
3604 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3605 /* Update iseqno */
3606 f->iseqno = iaxs[f->callno]->iseqno;
3607 fh->iseqno = f->iseqno;
3608
3609 /* Now re-encrypt the frame */
3610 if (f->encmethods) {
3611 /* since this is a retransmit frame, create a new random padding
3612 * before re-encrypting. */
3613 build_rand_pad(f->semirand, sizeof(f->semirand));
3614 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3615 }
3616 return 0;
3617}
3618
3619static int attempt_transmit(const void *data);
3620static void __attempt_transmit(const void *data)
3621{
3622 /* Attempt to transmit the frame to the remote peer...
3623 Called without iaxsl held. */
3624 struct iax_frame *f = (struct iax_frame *)data;
3625 int freeme = 0;
3626 int callno = f->callno;
3627
3628 /* Make sure this call is still active */
3629 if (callno)
3631 if (callno && iaxs[callno]) {
3632 if (f->retries < 0) {
3633 /* Already ACK'd */
3634 freeme = 1;
3635 } else if (f->retries >= max_retries) {
3636 /* Too many attempts. Record an error. */
3637 if (f->transfer) {
3638 /* Transfer timeout */
3640 } else if (f->final) {
3642 } else {
3643 if (iaxs[callno]->owner) {
3644 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3647 f->af.frametype,
3648 f->af.subclass.integer,
3649 f->ts,
3650 f->oseqno);
3651 }
3652 iaxs[callno]->error = ETIMEDOUT;
3653 if (iaxs[callno]->owner) {
3655 /* Hangup the fd */
3656 iax2_queue_frame(callno, &fr); /* XXX */
3657 /* Remember, owner could disappear */
3658 if (iaxs[callno] && iaxs[callno]->owner)
3660 } else {
3661 if (iaxs[callno]->reg) {
3662 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3663 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3665 }
3666 iax2_destroy(callno);
3667 }
3668 }
3669 freeme = 1;
3670 } else {
3671 /* Update it if it needs it */
3672 update_packet(f);
3673 /* Attempt transmission */
3674 send_packet(f);
3675 f->retries++;
3676 /* Try again later after 10 times as long */
3677 f->retrytime *= 10;
3678 if (f->retrytime > MAX_RETRY_TIME)
3680 /* Transfer messages max out at one second */
3681 if (f->transfer && (f->retrytime > 1000))
3682 f->retrytime = 1000;
3684 }
3685 } else {
3686 /* Make sure it gets freed */
3687 f->retries = -1;
3688 freeme = 1;
3689 }
3690
3691 if (freeme) {
3692 /* Don't attempt delivery, just remove it from the queue */
3693 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3694 ast_mutex_unlock(&iaxsl[callno]);
3695 f->retrans = -1; /* this is safe because this is the scheduled function */
3696 /* Free the IAX frame */
3697 iax2_frame_free(f);
3698 } else if (callno) {
3699 ast_mutex_unlock(&iaxsl[callno]);
3700 }
3701}
3702
3703static int attempt_transmit(const void *data)
3704{
3705#ifdef SCHED_MULTITHREADED
3707#endif
3709 return 0;
3710}
3711
3712static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3713{
3714 struct iax2_peer *peer = NULL;
3715 struct iax2_user *user = NULL;
3716 static const char * const choices[] = { "all", NULL };
3717 char *cmplt;
3718
3719 switch (cmd) {
3720 case CLI_INIT:
3721 e->command = "iax2 prune realtime";
3722 e->usage =
3723 "Usage: iax2 prune realtime [<peername>|all]\n"
3724 " Prunes object(s) from the cache\n";
3725 return NULL;
3726 case CLI_GENERATE:
3727 if (a->pos == 3) {
3728 cmplt = ast_cli_complete(a->word, choices, a->n);
3729 if (!cmplt)
3730 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3731 return cmplt;
3732 }
3733 return NULL;
3734 }
3735 if (a->argc != 4)
3736 return CLI_SHOWUSAGE;
3737 if (!strcmp(a->argv[3], "all")) {
3738 prune_users();
3739 prune_peers();
3740 ast_cli(a->fd, "Cache flushed successfully.\n");
3741 return CLI_SUCCESS;
3742 }
3743 peer = find_peer(a->argv[3], 0);
3744 user = find_user(a->argv[3]);
3745 if (peer || user) {
3746 if (peer) {
3750 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3751 } else {
3752 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3753 }
3754 peer_unref(peer);
3755 }
3756 if (user) {
3759 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3760 } else {
3761 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3762 }
3765 }
3766 } else {
3767 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3768 }
3769
3770 return CLI_SUCCESS;
3771}
3772
3773static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3774{
3775 switch (cmd) {
3776 case CLI_INIT:
3777 e->command = "iax2 test losspct";
3778 e->usage =
3779 "Usage: iax2 test losspct <percentage>\n"
3780 " For testing, throws away <percentage> percent of incoming packets\n";
3781 return NULL;
3782 case CLI_GENERATE:
3783 return NULL;
3784 }
3785 if (a->argc != 4)
3786 return CLI_SHOWUSAGE;
3787
3788 test_losspct = atoi(a->argv[3]);
3789
3790 return CLI_SUCCESS;
3791}
3792
3793#ifdef IAXTESTS
3794static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3795{
3796 switch (cmd) {
3797 case CLI_INIT:
3798 e->command = "iax2 test late";
3799 e->usage =
3800 "Usage: iax2 test late <ms>\n"
3801 " For testing, count the next frame as <ms> ms late\n";
3802 return NULL;
3803 case CLI_GENERATE:
3804 return NULL;
3805 }
3806
3807 if (a->argc != 4)
3808 return CLI_SHOWUSAGE;
3809
3810 test_late = atoi(a->argv[3]);
3811
3812 return CLI_SUCCESS;
3813}
3814
3815static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3816{
3817 switch (cmd) {
3818 case CLI_INIT:
3819 e->command = "iax2 test resync";
3820 e->usage =
3821 "Usage: iax2 test resync <ms>\n"
3822 " For testing, adjust all future frames by <ms> ms\n";
3823 return NULL;
3824 case CLI_GENERATE:
3825 return NULL;
3826 }
3827
3828 if (a->argc != 4)
3829 return CLI_SHOWUSAGE;
3830
3831 test_resync = atoi(a->argv[3]);
3832
3833 return CLI_SUCCESS;
3834}
3835
3836static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3837{
3838 switch (cmd) {
3839 case CLI_INIT:
3840 e->command = "iax2 test jitter";
3841 e->usage =
3842 "Usage: iax2 test jitter <ms> <pct>\n"
3843 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3844 " percentage of packets. If <pct> is not specified, adds\n"
3845 " jitter to all packets.\n";
3846 return NULL;
3847 case CLI_GENERATE:
3848 return NULL;
3849 }
3850
3851 if (a->argc < 4 || a->argc > 5)
3852 return CLI_SHOWUSAGE;
3853
3854 test_jit = atoi(a->argv[3]);
3855 if (a->argc == 5)
3856 test_jitpct = atoi(a->argv[4]);
3857
3858 return CLI_SUCCESS;
3859}
3860#endif /* IAXTESTS */
3861
3862/*! \brief peer_status: Report Peer status in character string */
3863/* returns 1 if peer is online, -1 if unmonitored */
3864static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3865{
3866 int res = 0;
3867 if (peer->maxms) {
3868 if (peer->lastms < 0) {
3869 ast_copy_string(status, "UNREACHABLE", statuslen);
3870 } else if (peer->lastms > peer->maxms) {
3871 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3872 res = 1;
3873 } else if (peer->lastms) {
3874 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3875 res = 1;
3876 } else {
3877 ast_copy_string(status, "UNKNOWN", statuslen);
3878 }
3879 } else {
3880 ast_copy_string(status, "Unmonitored", statuslen);
3881 res = -1;
3882 }
3883 return res;
3884}
3885
3886/*! \brief Show one peer in detail */
3887static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3888{
3889 char status[64];
3890 char cbuf[256];
3891 struct iax2_peer *peer;
3892 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3893 struct ast_str *encmethods = ast_str_alloca(256);
3894 int load_realtime = 0;
3895
3896 switch (cmd) {
3897 case CLI_INIT:
3898 e->command = "iax2 show peer";
3899 e->usage =
3900 "Usage: iax2 show peer <name>\n"
3901 " Display details on specific IAX peer\n";
3902 return NULL;
3903 case CLI_GENERATE:
3904 if (a->pos == 3)
3905 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3906 return NULL;
3907 }
3908
3909 if (a->argc < 4)
3910 return CLI_SHOWUSAGE;
3911
3912 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3913
3914 peer = find_peer(a->argv[3], load_realtime);
3915 if (peer) {
3916 char *str_addr, *str_defaddr;
3917 char *str_port, *str_defport;
3918
3919 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3920 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3921 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3922 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3923
3924 encmethods_to_str(peer->encmethods, &encmethods);
3925 ast_cli(a->fd, "\n\n");
3926 ast_cli(a->fd, " * Name : %s\n", peer->name);
3927 ast_cli(a->fd, " Description : %s\n", peer->description);
3928 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3929 ast_cli(a->fd, " Context : %s\n", peer->context);
3930 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3931 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3932 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3933 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3934 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3935 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3936 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3937 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3938 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3939 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3940 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3941 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3942 ast_cli(a->fd, " Username : %s\n", peer->username);
3943 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3944
3945 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3946 strcpy(cbuf, "Error"); /* Safe */
3947 }
3948 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3949
3950 peer_status(peer, status, sizeof(status));
3951 ast_cli(a->fd, " Status : %s\n", status);
3952 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");
3953 ast_cli(a->fd, "\n");
3954 peer_unref(peer);
3955 } else {
3956 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3957 ast_cli(a->fd, "\n");
3958 }
3959
3960 return CLI_SUCCESS;
3961}
3962
3963static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3964{
3965 int which = 0;
3966 struct iax2_peer *peer;
3967 char *res = NULL;
3968 int wordlen = strlen(word);
3969 struct ao2_iterator i;
3970
3971 i = ao2_iterator_init(peers, 0);
3972 while ((peer = ao2_iterator_next(&i))) {
3973 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3974 && (!flags || ast_test_flag64(peer, flags))) {
3975 res = ast_strdup(peer->name);
3976 peer_unref(peer);
3977 break;
3978 }
3979 peer_unref(peer);
3980 }
3982
3983 return res;
3984}
3985
3986static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3987{
3988 struct iax_frame *cur;
3989 int cnt = 0, dead = 0, final = 0, i = 0;
3990
3991 switch (cmd) {
3992 case CLI_INIT:
3993 e->command = "iax2 show stats";
3994 e->usage =
3995 "Usage: iax2 show stats\n"
3996 " Display statistics on IAX channel driver.\n";
3997 return NULL;
3998 case CLI_GENERATE:
3999 return NULL;
4000 }
4001
4002 if (a->argc != 3)
4003 return CLI_SHOWUSAGE;
4004
4005 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
4006 ast_mutex_lock(&iaxsl[i]);
4008 if (cur->retries < 0)
4009 dead++;
4010 if (cur->final)
4011 final++;
4012 cnt++;
4013 }
4015 }
4016
4017 ast_cli(a->fd, " IAX Statistics\n");
4018 ast_cli(a->fd, "---------------------\n");
4019 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
4020 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
4022 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
4023
4027
4028 return CLI_SUCCESS;
4029}
4030
4031/*! \brief Set trunk MTU from CLI */
4032static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4033{
4034 int mtuv;
4035
4036 switch (cmd) {
4037 case CLI_INIT:
4038 e->command = "iax2 set mtu";
4039 e->usage =
4040 "Usage: iax2 set mtu <value>\n"
4041 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
4042 " zero to disable. Disabling means that the operating system\n"
4043 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
4044 " packet exceeds the UDP payload size. This is substantially\n"
4045 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4046 " greater for G.711 samples.\n";
4047 return NULL;
4048 case CLI_GENERATE:
4049 return NULL;
4050 }
4051
4052 if (a->argc != 4)
4053 return CLI_SHOWUSAGE;
4054 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4055 mtuv = MAX_TRUNK_MTU;
4056 else
4057 mtuv = atoi(a->argv[3]);
4058
4059 if (mtuv == 0) {
4060 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4062 return CLI_SUCCESS;
4063 }
4064 if (mtuv < 172 || mtuv > 4000) {
4065 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4066 return CLI_SHOWUSAGE;
4067 }
4068 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4069 global_max_trunk_mtu = mtuv;
4070 return CLI_SUCCESS;
4071}
4072
4073static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4074{
4075 struct iax2_dpcache *dp = NULL;
4076 char tmp[1024], *pc = NULL;
4077 int s, x, y;
4078 struct timeval now = ast_tvnow();
4079
4080 switch (cmd) {
4081 case CLI_INIT:
4082 e->command = "iax2 show cache";
4083 e->usage =
4084 "Usage: iax2 show cache\n"
4085 " Display currently cached IAX Dialplan results.\n";
4086 return NULL;
4087 case CLI_GENERATE:
4088 return NULL;
4089 }
4090
4092
4093 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4094
4095 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4096 s = dp->expiry.tv_sec - now.tv_sec;
4097 tmp[0] = '\0';
4098 if (dp->flags & CACHE_FLAG_EXISTS)
4099 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4100 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4101 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4102 if (dp->flags & CACHE_FLAG_CANEXIST)
4103 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4104 if (dp->flags & CACHE_FLAG_PENDING)
4105 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4106 if (dp->flags & CACHE_FLAG_TIMEOUT)
4107 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4108 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4109 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4110 if (dp->flags & CACHE_FLAG_MATCHMORE)
4111 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4112 if (dp->flags & CACHE_FLAG_UNKNOWN)
4113 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4114 /* Trim trailing pipe */
4115 if (!ast_strlen_zero(tmp)) {
4116 tmp[strlen(tmp) - 1] = '\0';
4117 } else {
4118 ast_copy_string(tmp, "(none)", sizeof(tmp));
4119 }
4120 y = 0;
4121 pc = strchr(dp->peercontext, '@');
4122 if (!pc) {
4123 pc = dp->peercontext;
4124 } else {
4125 pc++;
4126 }
4127 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4128 if (dp->waiters[x] > -1)
4129 y++;
4130 }
4131 if (s > 0) {
4132 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4133 } else {
4134 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4135 }
4136 }
4137
4139
4140 return CLI_SUCCESS;
4141}
4142
4143static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4144
4145static void unwrap_timestamp(struct iax_frame *fr)
4146{
4147 /* Video mini frames only encode the lower 15 bits of the session
4148 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4149 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4150 const int lower_mask = (1 << ts_shift) - 1;
4151 const int upper_mask = ~lower_mask;
4152 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4153
4154 if ( (fr->ts & upper_mask) == last_upper ) {
4155 const int x = fr->ts - iaxs[fr->callno]->last;
4156 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4157
4158 if (x < -threshold) {
4159 /* Sudden big jump backwards in timestamp:
4160 What likely happened here is that miniframe timestamp has circled but we haven't
4161 gotten the update from the main packet. We'll just pretend that we did, and
4162 update the timestamp appropriately. */
4163 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4164 if (iaxdebug)
4165 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4166 } else if (x > threshold) {
4167 /* Sudden apparent big jump forwards in timestamp:
4168 What's likely happened is this is an old miniframe belonging to the previous
4169 top 15 or 16-bit timestamp that has turned up out of order.
4170 Adjust the timestamp appropriately. */
4171 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4172 if (iaxdebug)
4173 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4174 }
4175 }
4176}
4177
4178static int get_from_jb(const void *p);
4179
4180static void update_jbsched(struct chan_iax2_pvt *pvt)
4181{
4182 int when;
4183
4184 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4185
4186 when = jb_next(pvt->jb) - when;
4187
4188 if (when <= 0) {
4189 /* XXX should really just empty until when > 0.. */
4190 when = 1;
4191 }
4192
4193 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4194 CALLNO_TO_PTR(pvt->callno));
4195}
4196
4197static void __get_from_jb(const void *p)
4198{
4199 int callno = PTR_TO_CALLNO(p);
4200 struct chan_iax2_pvt *pvt = NULL;
4201 struct iax_frame *fr;
4202 jb_frame frame;
4203 int ret;
4204 long ms;
4205 long next;
4206 struct timeval now = ast_tvnow();
4207 struct ast_format *voicefmt;
4208
4209 /* Make sure we have a valid private structure before going on */
4210 ast_mutex_lock(&iaxsl[callno]);
4211 pvt = iaxs[callno];
4212 if (!pvt) {
4213 /* No go! */
4214 ast_mutex_unlock(&iaxsl[callno]);
4215 return;
4216 }
4217
4218 pvt->jbid = -1;
4219
4220 /* round up a millisecond since ast_sched_runq does; */
4221 /* prevents us from spinning while waiting for our now */
4222 /* to catch up with runq's now */
4223 now.tv_usec += 1000;
4224
4225 ms = ast_tvdiff_ms(now, pvt->rxcore);
4226 if (ms >= (next = jb_next(pvt->jb))) {
4228 if (!voicefmt) {
4229 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4230 * In this case, fall back to using the format negotiated during call setup,
4231 * so we don't stall the jitterbuffer completely. */
4233 if (!voicefmt) {
4234 /* As a last resort, we can use pvt->chosenformat.
4235 * This is set when we receive a call (either authenticated or unauthenticated),
4236 * so even if we haven't received any voice frames yet, we can still use the
4237 * right format.
4238 *
4239 * If we have to do this, in most cases, we aren't even processing voice frames
4240 * anyways, it's likely a non-voice frame. In that case, the format doesn't
4241 * really matter so much, because we could just pass 20 to jb_get instead
4242 * of calling ast_format_get_default_ms. However, until jb_get returns,
4243 * we don't actually know what kind of frame it is for sure, so use
4244 * the right format just to be safe. */
4246 }
4247 }
4248 if (!voicefmt) {
4249 /* This should never happen, since we should always be able to have an acceptable format to use. */
4250 ast_log(LOG_ERROR, "No voice, peer, or chosen format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4251 goto cleanup; /* Don't crash if there's no voice format */
4252 }
4253 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4254 switch(ret) {
4255 case JB_OK:
4256 fr = frame.data;
4257 __do_deliver(fr);
4258 /* __do_deliver() can cause the call to disappear */
4259 pvt = iaxs[callno];
4260 break;
4261 case JB_INTERP:
4262 {
4263 struct ast_frame af = { 0, };
4264
4265 /* create an interpolation frame */
4267 af.subclass.format = voicefmt;
4268 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4269 af.src = "IAX2 JB interpolation";
4270 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4272
4273 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4274 * which we'd need to malloc, and then it would free it. That seems like a drag */
4275 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4276 iax2_queue_frame(callno, &af);
4277 /* iax2_queue_frame() could cause the call to disappear */
4278 pvt = iaxs[callno];
4279 }
4280 }
4281 break;
4282 case JB_DROP:
4283 iax2_frame_free(frame.data);
4284 break;
4285 case JB_NOFRAME:
4286 case JB_EMPTY:
4287 /* do nothing */
4288 break;
4289 default:
4290 /* shouldn't happen */
4291 break;
4292 }
4293 }
4294cleanup:
4295 if (pvt)
4296 update_jbsched(pvt);
4297 ast_mutex_unlock(&iaxsl[callno]);
4298}
4299
4300static int get_from_jb(const void *data)
4301{
4302#ifdef SCHED_MULTITHREADED
4304#endif
4306 return 0;
4307}
4308
4309/*!
4310 * \note This function assumes fr->callno is locked
4311 *
4312 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4313 * was valid before calling it, it may no longer be valid after calling it.
4314 */
4315static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4316{
4317 int type, len;
4318 int ret;
4319 int needfree = 0;
4320
4321 /*
4322 * Clear fr->af.data if there is no data in the buffer. Things
4323 * like AST_CONTROL_HOLD without a suggested music class must
4324 * have a NULL pointer.
4325 */
4326 if (!fr->af.datalen) {
4327 memset(&fr->af.data, 0, sizeof(fr->af.data));
4328 }
4329
4330 /* Attempt to recover wrapped timestamps */
4331 unwrap_timestamp(fr);
4332
4333 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4334 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4335 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4336 else {
4337#if 0
4338 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4339#endif
4340 fr->af.delivery = ast_tv(0,0);
4341 }
4342
4344 len = 0;
4345
4346 if(fr->af.frametype == AST_FRAME_VOICE) {
4349 } else if(fr->af.frametype == AST_FRAME_CNG) {
4351 }
4352
4353 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4354 if (tsout)
4355 *tsout = fr->ts;
4356 __do_deliver(fr);
4357 return -1;
4358 }
4359
4360 /* insert into jitterbuffer */
4361 /* TODO: Perhaps we could act immediately if it's not droppable and late */
4362 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4363 calc_rxstamp(iaxs[fr->callno],fr->ts));
4364 if (ret == JB_DROP) {
4365 needfree++;
4366 } else if (ret == JB_SCHED) {
4368 }
4369 if (tsout)
4370 *tsout = fr->ts;
4371 if (needfree) {
4372 /* Free our iax frame */
4373 iax2_frame_free(fr);
4374 return -1;
4375 }
4376 return 0;
4377}
4378
4379static int transmit_frame(void *data)
4380{
4381 struct iax_frame *fr = data;
4382
4384
4385 fr->sentyet = 1;
4386
4387 if (iaxs[fr->callno]) {
4388 send_packet(fr);
4389 }
4390
4391 if (fr->retries < 0) {
4393 /* No retransmit requested */
4394 iax_frame_free(fr);
4395 } else {
4396 /* We need reliable delivery. Schedule a retransmission */
4398 fr->retries++;
4401 }
4402
4403 return 0;
4404}
4405
4406static int iax2_transmit(struct iax_frame *fr)
4407{
4408 fr->sentyet = 0;
4409
4411}
4412
4413static int iax2_digit_begin(struct ast_channel *c, char digit)
4414{
4416}
4417
4418static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4419{
4421}
4422
4423static int iax2_sendtext(struct ast_channel *c, const char *text)
4424{
4425
4427 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4428}
4429
4430static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4431{
4433}
4434
4435static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4436{
4437 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4438}
4439
4440static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4441{
4442 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4444 if (iaxs[callno])
4445 iaxs[callno]->owner = newchan;
4446 else
4447 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4449 return 0;
4450}
4451
4452/*!
4453 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4454 * so do not call this with a pvt lock held.
4455 */
4456static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4457{
4458 struct ast_variable *var = NULL;
4459 struct ast_variable *tmp;
4460 struct iax2_peer *peer=NULL;
4461 time_t regseconds = 0, nowtime;
4462 int dynamic=0;
4463 char *str_addr, *str_port;
4464
4467
4468 if (peername) {
4469 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4470 if (!var && !ast_sockaddr_isnull(addr)) {
4471 var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4472 }
4473 } else if (!ast_sockaddr_isnull(addr)) {
4474 var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4475 if (var) {
4476 /* We'll need the peer name in order to build the structure! */
4477 for (tmp = var; tmp; tmp = tmp->next) {
4478 if (!strcasecmp(tmp->name, "name"))
4479 peername = tmp->value;
4480 }
4481 }
4482 }
4483 if (!var && peername) { /* Last ditch effort */
4484 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4485 /*!\note
4486 * If this one loaded something, then we need to ensure that the host
4487 * field matched. The only reason why we can't have this as a criteria
4488 * is because we only have the IP address and the host field might be
4489 * set as a name (and the reverse PTR might not match).
4490 */
4491 if (var && !ast_sockaddr_isnull(addr)) {
4492 for (tmp = var; tmp; tmp = tmp->next) {
4493 if (!strcasecmp(tmp->name, "host")) {
4494 struct ast_sockaddr *hostaddr = NULL;
4495
4497 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4498 /* No match */
4500 var = NULL;
4501 }
4502 ast_free(hostaddr);
4503 break;
4504 }
4505 }
4506 }
4507 }
4508 if (!var)
4509 return NULL;
4510
4511 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4512
4513 if (!peer) {
4515 return NULL;
4516 }
4517
4518 for (tmp = var; tmp; tmp = tmp->next) {
4519 /* Make sure it's not a user only... */
4520 if (!strcasecmp(tmp->name, "type")) {
4521 if (strcasecmp(tmp->value, "friend") &&
4522 strcasecmp(tmp->value, "peer")) {
4523 /* Whoops, we weren't supposed to exist! */
4524 peer = peer_unref(peer);
4525 break;
4526 }
4527 } else if (!strcasecmp(tmp->name, "regseconds")) {
4528 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4529 } else if (!strcasecmp(tmp->name, "ipaddr")) {
4530 int setport = ast_sockaddr_port(&peer->addr);
4532 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4533 } else {
4534 ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4535 }
4536 ast_sockaddr_set_port(&peer->addr, setport);
4537 } else if (!strcasecmp(tmp->name, "port")) {
4538 int bindport;
4539 if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4540 bindport = IAX_DEFAULT_PORTNO;
4541 }
4542 ast_sockaddr_set_port(&peer->addr, bindport);
4543 } else if (!strcasecmp(tmp->name, "host")) {
4544 if (!strcasecmp(tmp->value, "dynamic"))
4545 dynamic = 1;
4546 }
4547 }
4548
4550
4553 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4554 if (peer->expire > -1) {
4555 if (!AST_SCHED_DEL(sched, peer->expire)) {
4556 peer->expire = -1;
4557 peer_unref(peer);
4558 }
4559 }
4561 if (peer->expire == -1)
4562 peer_unref(peer);
4563 }
4564 ao2_link(peers, peer);
4565 if (ast_test_flag64(peer, IAX_DYNAMIC))
4566 reg_source_db(peer);
4567 } else {
4569 }
4570
4572 time(&nowtime);
4573 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4574 memset(&peer->addr, 0, sizeof(peer->addr));
4575 realtime_update_peer(peer->name, &peer->addr, 0);
4576 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4577 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4578 }
4579 else {
4580 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4581 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4582 }
4583 }
4584
4585 return peer;
4586}
4587
4588static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4589{
4590 struct ast_variable *var;
4591 struct ast_variable *tmp;
4592 struct iax2_user *user=NULL;
4593 char *str_addr, *str_port;
4594
4595 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4596 str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4597
4598 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4599 if (!var)
4600 var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4601 if (!var && !ast_sockaddr_isnull(addr)) {
4602 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4603 if (!var)
4604 var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4605 }
4606 if (!var) { /* Last ditch effort */
4607 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4608 /*!\note
4609 * If this one loaded something, then we need to ensure that the host
4610 * field matched. The only reason why we can't have this as a criteria
4611 * is because we only have the IP address and the host field might be
4612 * set as a name (and the reverse PTR might not match).
4613 */
4614 if (var) {
4615 for (tmp = var; tmp; tmp = tmp->next) {
4616 if (!strcasecmp(tmp->name, "host")) {
4617 struct ast_sockaddr *hostaddr = NULL;
4618
4620 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4621 /* No match */
4623 var = NULL;
4624 }
4625 ast_free(hostaddr);
4626 break;
4627 }
4628 }
4629 }
4630 }
4631 if (!var)
4632 return NULL;
4633
4634 tmp = var;
4635 while(tmp) {
4636 /* Make sure it's not a peer only... */
4637 if (!strcasecmp(tmp->name, "type")) {
4638 if (strcasecmp(tmp->value, "friend") &&
4639 strcasecmp(tmp->value, "user")) {
4640 return NULL;
4641 }
4642 }
4643 tmp = tmp->next;
4644 }
4645
4647
4649
4650 if (!user)
4651 return NULL;
4652
4656 } else {
4658 }
4659
4660 return user;
4661}
4662
4663static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4664{
4665 char regseconds[20];
4666 const char *sysname = ast_config_AST_SYSTEM_NAME;
4667 char *syslabel = NULL;
4668 char *port;
4669
4670 if (ast_strlen_zero(sysname)) /* No system name, disable this */
4671 sysname = NULL;
4673 syslabel = "regserver";
4674
4675 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4676 port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4677 ast_update_realtime("iaxpeers", "name", peername,
4678 "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4679 "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4680 "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslabel can be NULL */
4681}
4682
4685 uint64_t flags;
4692 int adsi;
4693 char username[80];
4694 char secret[80];
4695 char outkey[80];
4696 char timezone[80];
4697 char cid_num[80];
4698 char cid_name[80];
4703};
4704
4705static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4706{
4707 struct iax2_peer *peer;
4708 int res = -1;
4709
4711 cai->sockfd = defaultsockfd;
4712 cai->maxtime = 0;
4713
4714 if (!(peer = find_peer(peername, 1))) {
4715 struct ast_sockaddr peer_addr;
4716
4717 peer_addr.ss.ss_family = AST_AF_UNSPEC;
4718 cai->found = 0;
4719 if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4720 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4721 return -1;
4722 }
4723
4724 if (!ast_sockaddr_port(&peer_addr)) {
4726 }
4727
4728 ast_sockaddr_copy(addr, &peer_addr);
4729 /*
4730 * Use The global iax prefs for unknown peer/user.
4731 * However, move the calling channel's native codec to
4732 * the top of the preference list.
4733 */
4734 cai->prefs = prefs_global;
4735 if (c) {
4736 int i;
4737
4738 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4739 struct ast_format *format = ast_format_cap_get_format(
4741 iax2_codec_pref_prepend(&cai->prefs, format,
4743 1);
4744 ao2_ref(format, -1);
4745 }
4746 }
4747 return 0;
4748 }
4749
4750 cai->found = 1;
4751
4752 /* if the peer has no address (current or default), return failure */
4753 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4754 goto return_unref;
4755 }
4756
4757 /* if the peer is being monitored and is currently unreachable, return failure */
4758 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4759 goto return_unref;
4760
4762 cai->maxtime = peer->maxms;
4763 cai->capability = peer->capability;
4764 cai->encmethods = peer->encmethods;
4765 cai->authmethods = peer->authmethods;
4766 cai->sockfd = peer->sockfd;
4767 cai->adsi = peer->adsi;
4768 cai->prefs = peer->prefs;
4769 /* Move the calling channel's native codec to the top of the preference list */
4770 if (c) {
4771 int i;
4772
4773 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4774 struct ast_format *tmpfmt = ast_format_cap_get_format(
4776 iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4778 1);
4779 ao2_ref(tmpfmt, -1);
4780 }
4781 }
4782 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4783 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4784 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4785 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4786 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4787 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4788 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4789 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4790 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4791 if (ast_strlen_zero(peer->dbsecret)) {
4792 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4793 } else {
4794 char *family;
4795 char *key = NULL;
4796
4797 family = ast_strdupa(peer->dbsecret);
4798 key = strchr(family, '/');
4799 if (key)
4800 *key++ = '\0';
4801 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4802 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4803 goto return_unref;
4804 }
4805 }
4806
4807 if (!ast_sockaddr_isnull(&peer->addr)) {
4808 ast_sockaddr_copy(addr, &peer->addr);
4809 } else {
4810 ast_sockaddr_copy(addr, &peer->defaddr);
4811 }
4812
4813 res = 0;
4814
4815return_unref:
4816 peer_unref(peer);
4817
4818 return res;
4819}
4820
4821static void __auto_congest(const void *nothing)
4822{
4823 int callno = PTR_TO_CALLNO(nothing);
4825 ast_mutex_lock(&iaxsl[callno]);
4826 if (iaxs[callno]) {
4827 iaxs[callno]->initid = -1;
4828 iax2_queue_frame(callno, &f);
4829 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4830 }
4831 ast_mutex_unlock(&iaxsl[callno]);
4832}
4833
4834static int auto_congest(const void *data)
4835{
4836#ifdef SCHED_MULTITHREADED
4838#endif
4840 return 0;
4841}
4842
4843static unsigned int iax2_datetime(const char *tz)
4844{
4845 struct timeval t = ast_tvnow();
4846 struct ast_tm tm;
4847 unsigned int tmp;
4848 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4849 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4850 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4851 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4852 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4853 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4854 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4855 return tmp;
4856}
4857
4861 char *key;
4862 char *peer;
4863 char *port;
4864 char *exten;
4865 char *context;
4866 char *options;
4867};
4868
4869static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4870 struct ast_sockaddr *addr, int command, int ts, unsigned char seqno,
4871 int sockfd, struct iax_ie_data *ied)
4872{
4873 struct {
4874 struct ast_iax2_full_hdr f;
4875 struct iax_ie_data ied;
4876 } data;
4877 size_t size = sizeof(struct ast_iax2_full_hdr);
4878
4879 if (ied) {
4880 size += ied->pos;
4881 memcpy(&data.ied, ied->buf, ied->pos);
4882 }
4883
4884 data.f.scallno = htons(0x8000 | callno);
4885 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4886 data.f.ts = htonl(ts);
4887 data.f.iseqno = seqno;
4888 data.f.oseqno = 0;
4889 data.f.type = AST_FRAME_IAX;
4890 data.f.csub = compress_subclass(command);
4891
4892 iax_outputframe(NULL, &data.f, 0, addr, size - sizeof(struct ast_iax2_full_hdr));
4893
4894 return ast_sendto(sockfd, &data, size, 0, addr);
4895}
4896
4897static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4898{
4899 /* first make sure their are two empty bytes left in ied->buf */
4900 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4901 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4902 ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4903 pvt->calltoken_ie_len = 2;
4904 }
4905}
4906
4907static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4908{
4909 struct chan_iax2_pvt *pvt = iaxs[callno];
4910 int frametype = f->af.frametype;
4911 int subclass = f->af.subclass.integer;
4912 struct {
4913 struct ast_iax2_full_hdr fh;
4914 struct iax_ie_data ied;
4915 } data = {
4916 .ied.buf = { 0 },
4917 .ied.pos = 0,
4918 };
4919 /* total len - header len gives us the frame's IE len */
4920 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4921
4922 if (!pvt) {
4923 return; /* this should not be possible if called from socket_process() */
4924 }
4925
4926 /*
4927 * Check to make sure last frame sent is valid for call token resend
4928 * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4929 * 2. Frame should _NOT_ already have a destination callno
4930 * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4931 * 4. Pvt must have a calltoken_ie_len which represents the number of
4932 * bytes at the end of the frame used for the previous calltoken ie.
4933 * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4934 * 6. Total length of f->data must be _LESS_ than size of our data struct
4935 * because f->data must be able to fit within data.
4936 */
4937 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4938 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4939 (f->datalen > sizeof(data))) {
4940
4941 return; /* ignore resend, token was not valid for the dialog */
4942 }
4943
4944 /* token is valid
4945 * 1. Copy frame data over
4946 * 2. Redo calltoken IE, it will always be the last ie in the frame.
4947 * NOTE: Having the ie always be last is not protocol specified,
4948 * it is only an implementation choice. Since we only expect the ie to
4949 * be last for frames we have sent, this can no way be affected by
4950 * another end point.
4951 * 3. Remove frame from queue
4952 * 4. Free old frame
4953 * 5. Clear previous seqnos
4954 * 6. Resend with CALLTOKEN ie.
4955 */
4956
4957 /* ---1.--- */
4958 memcpy(&data, f->data, f->datalen);
4959 data.ied.pos = ie_data_pos;
4960
4961 /* ---2.--- */
4962 /* move to the beginning of the calltoken ie so we can write over it */
4963 data.ied.pos -= pvt->calltoken_ie_len;
4964 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4965
4966 /* make sure to update token length incase it ever has to be stripped off again */
4967 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4968
4969 /* ---3.--- */
4970 AST_LIST_REMOVE(&frame_queue[callno], f, list);
4971
4972 /* ---4.--- */
4973 iax2_frame_free(f);
4974
4975 /* ---5.--- */
4976 pvt->oseqno = 0;
4977 pvt->rseqno = 0;
4978 pvt->iseqno = 0;
4979 pvt->aseqno = 0;
4980 if (pvt->peercallno) {
4982 pvt->peercallno = 0;
4983 }
4984
4985 /* ---6.--- */
4986 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
4987}
4988
4989static void requirecalltoken_mark_auto(const char *name, int subclass)
4990{
4991 struct iax2_user *user = NULL;
4992 struct iax2_peer *peer = NULL;
4993
4994 if (ast_strlen_zero(name)) {
4995 return; /* no username given */
4996 }
4997
4998 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
4999 user->calltoken_required = CALLTOKEN_YES;
5000 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
5002 }
5003
5004 if (peer) {
5005 peer_unref(peer);
5006 }
5007 if (user) {
5009 }
5010}
5011
5012/*!
5013 * \internal
5014 *
5015 * \brief handles calltoken logic for a received iax_frame.
5016 *
5017 * \note frametype must be AST_FRAME_IAX.
5018 *
5019 * \note
5020 * Three different cases are possible here.
5021 * Case 1. An empty calltoken is provided. This means the client supports
5022 * calltokens but has not yet received one from us. In this case
5023 * a full calltoken IE is created and sent in a calltoken fullframe.
5024 * Case 2. A full calltoken is received and must be checked for validity.
5025 * Case 3. No calltoken is received indicating that the client does not
5026 * support calltokens. In this case it is up to the configuration
5027 * to decide how this should be handled (reject or permit without calltoken)
5028 */
5029static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
5030 struct ast_sockaddr *addr, int fd)
5031{
5032#define CALLTOKEN_HASH_FORMAT "%s%u%d" /* address + port + ts + randomcalldata */
5033#define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
5034 struct ast_str *buf = ast_str_alloca(256);
5035 time_t t = time(NULL);
5036 char hash[41]; /* 40 char sha1 hash */
5037 int subclass = uncompress_subclass(fh->csub);
5038
5039 /* ----- Case 1 ----- */
5040 if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
5041 struct iax_ie_data ied = {
5042 .buf = { 0 },
5043 .pos = 0,
5044 };
5045
5046 /* create the hash with their address data and our timestamp */
5049
5050 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
5052 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
5053
5054 return 1;
5055
5056 /* ----- Case 2 ----- */
5057 } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
5058 char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
5059 char *rec_ts = NULL; /* received timestamp */
5060 unsigned int rec_time; /* received time_t */
5061
5062 /* split the timestamp from the hash data */
5063 rec_hash = strchr((char *) ies->calltokendata, '?');
5064 if (rec_hash) {
5065 *rec_hash++ = '\0';
5066 rec_ts = (char *) ies->calltokendata;
5067 }
5068
5069 /* check that we have valid data before we do any comparisons */
5070 if (!rec_hash || !rec_ts) {
5071 goto reject;
5072 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
5073 goto reject;
5074 }
5075
5076 /* create a hash with their address and the _TOKEN'S_ timestamp */
5079
5080 /* compare hashes and then check timestamp delay */
5081 if (strcmp(hash, rec_hash)) {
5082 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_sockaddr_stringify(addr));
5083 goto reject; /* received hash does not match ours, reject */
5084 } else if ((t < rec_time) || ((t - rec_time) >= max_calltoken_delay)) {
5085 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_sockaddr_stringify(addr));
5086 goto reject; /* too much delay, reject */
5087 }
5088
5089 /* at this point the call token is valid, returning 0
5090 * will allow socket_process to continue as usual */
5091 requirecalltoken_mark_auto(ies->username, subclass);
5092 return 0;
5093
5094 /* ----- Case 3 ----- */
5095 } else { /* calltokens are not supported for this client, how do we respond? */
5096 if (calltoken_required(addr, ies->username, subclass)) {
5097 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"));
5098 goto reject;
5099 }
5100 return 0; /* calltoken is not required for this addr, so permit it. */
5101 }
5102
5103reject:
5104 /* received frame has failed calltoken inspection, send apathetic reject messages */
5105 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5106 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5107 } else {
5108 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5109 }
5110
5111 return 1;
5112}
5113
5114/*!
5115 * \brief Parses an IAX dial string into its component parts.
5116 * \param data the string to be parsed
5117 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5118 *
5119 * This function parses the string and fills the structure
5120 * with pointers to its component parts. The input string
5121 * will be modified.
5122 *
5123 * \note This function supports both plaintext passwords and RSA
5124 * key names; if the password string is formatted as '[keyname]',
5125 * then the keyname will be placed into the key field, and the
5126 * password field will be set to NULL.
5127 *
5128 * \note The dial string format is:
5129 * \verbatim [username[:password]@]peer[:port][/exten[@context]][/options] \endverbatim
5130 */
5131static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5132{
5133 char *outkey = NULL;
5134
5135 if (ast_strlen_zero(data))
5136 return;
5137
5138 pds->peer = strsep(&data, "/");
5139 pds->exten = strsep(&data, "/");
5140 pds->options = data;
5141
5142 if (pds->exten) {
5143 data = pds->exten;
5144 pds->exten = strsep(&data, "@");
5145 pds->context = data;
5146 }
5147
5148 if (strchr(pds->peer, '@')) {
5149 data = pds->peer;
5150 pds->username = strsep(&data, "@");
5151 pds->peer = data;
5152 }
5153
5154 if (pds->username) {
5155 data = pds->username;
5156 pds->username = strsep(&data, ":");
5157 pds->password = strsep(&data, ":");
5158 outkey = data;
5159 }
5160
5161 data = pds->peer;
5162 pds->peer = strsep(&data, ":");
5163 pds->port = data;
5164
5165 /*
5166 * Check for a key name wrapped in [] in the password position.
5167 * If found, move it to the key field instead.
5168 * Also allow for both key and secret to be specified, now that
5169 * encryption is possible with RSA authentication.
5170 */
5171
5172 if (pds->password && (pds->password[0] == '[')) { /* key (then maybe secret) */
5173 pds->key = ast_strip_quoted(pds->password, "[", "]");
5174 if (ast_strlen_zero(outkey)) {
5175 pds->password = NULL;
5176 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5177 } else {
5178 pds->password = outkey;
5179 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5180 }
5181 } else if (outkey && (outkey[0] == '[')) { /* secret, then key */
5182 pds->key = ast_strip_quoted(outkey, "[", "]");
5183 if (ast_strlen_zero(pds->password)) {
5184 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5185 } else {
5186 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5187 }
5188 }
5189}
5190
5191static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
5192{
5193 struct ast_sockaddr addr;
5194 char *l=NULL, *n=NULL, *tmpstr;
5195 struct iax_ie_data ied;
5196 char *defaultrdest = "s";
5197 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5198 struct parsed_dial_string pds;
5199 struct create_addr_info cai;
5200 struct ast_var_t *var;
5202 const char* osp_token_ptr;
5203 unsigned int osp_token_length;
5204 unsigned char osp_block_index;
5205 unsigned int osp_block_length;
5206 unsigned char osp_buffer[256];
5207 char encoded_prefs[32];
5208 iax2_format iax2_tmpfmt;
5209
5211 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
5212 return -1;
5213 }
5214
5215 memset(&cai, 0, sizeof(cai));
5218
5219 memset(&pds, 0, sizeof(pds));
5220 tmpstr = ast_strdupa(dest);
5221 parse_dial_string(tmpstr, &pds);
5222
5223 if (ast_strlen_zero(pds.peer)) {
5224 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5225 return -1;
5226 }
5227 if (!pds.exten) {
5228 pds.exten = defaultrdest;
5229 }
5230 if (create_addr(pds.peer, c, &addr, &cai)) {
5231 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5232 return -1;
5233 }
5234
5237 if (!cai.encmethods) {
5238 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5240 return -1;
5241 }
5242 if (((cai.authmethods & IAX_AUTH_RSA) || (cai.authmethods & IAX_AUTH_MD5) || (cai.authmethods & IAX_AUTH_PLAINTEXT)) &&
5244 ast_log(LOG_WARNING, "Call terminated. Encryption forced but no secret provided\n");
5245 return -1;
5246 }
5247 }
5248
5249 if (!pds.username && !ast_strlen_zero(cai.username))
5250 pds.username = cai.username;
5251 if (!pds.password && !ast_strlen_zero(cai.secret))
5252 pds.password = cai.secret;
5253 if (!pds.key && !ast_strlen_zero(cai.outkey))
5254 pds.key = cai.outkey;
5255 if (!pds.context && !ast_strlen_zero(cai.peercontext))
5256 pds.context = cai.peercontext;
5257
5258 /* Keep track of the context for outgoing calls too */
5260
5261 if (pds.port) {
5262 int bindport;
5263 if (ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
5264 ast_sockaddr_set_port(&addr, bindport);
5265 }
5266 }
5267
5270
5271 /* Now build request */
5272 memset(&ied, 0, sizeof(ied));
5273
5274 /* On new call, first IE MUST be IAX version of caller */
5277 if (pds.options && strchr(pds.options, 'a')) {
5278 /* Request auto answer */
5280 }
5281
5282 /* WARNING: this breaks down at 190 bits! */
5283 iax2_codec_pref_convert(&cai.prefs, encoded_prefs, sizeof(encoded_prefs), 1);
5284 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, encoded_prefs);
5285
5286 if (l) {
5290 } else if (n) {
5293 } else {
5295 }
5296
5298 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
5300
5301 if (n)
5303 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5304 && ast_channel_connected(c)->ani.number.valid
5305 && ast_channel_connected(c)->ani.number.str) {
5307 }
5308
5313 }
5314 if (ast_channel_redirecting(c)->from.number.valid
5315 && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
5316 iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
5317 }
5318
5319 if (pds.context)
5321
5322 if (pds.username)
5324
5325 if (cai.encmethods)
5327
5328 ast_mutex_lock(&iaxsl[callno]);
5329
5332
5333 if (pds.username)
5334 ast_string_field_set(iaxs[callno], username, pds.username);
5335
5336 iaxs[callno]->encmethods = cai.encmethods;
5337
5338 iaxs[callno]->adsi = cai.adsi;
5339
5342
5343 if (pds.key)
5344 ast_string_field_set(iaxs[callno], outkey, pds.key);
5345 if (pds.password)
5346 ast_string_field_set(iaxs[callno], secret, pds.password);
5347
5349 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
5350 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
5351
5352 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5353 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
5356
5357 if (iaxs[callno]->maxtime) {
5358 /* Initialize pingtime and auto-congest time */
5359 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5360 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5361 } else if (autokill) {
5362 iaxs[callno]->pingtime = autokill / 2;
5364 }
5365
5366 /* Check if there is an OSP token */
5367 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5368 if (!ast_strlen_zero(osp_token_ptr)) {
5369 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5370 osp_block_index = 0;
5371 while (osp_token_length > 0) {
5372 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5373 osp_buffer[0] = osp_block_index;
5374 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5375 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5376 osp_block_index++;
5377 osp_token_ptr += osp_block_length;
5378 osp_token_length -= osp_block_length;
5379 }
5380 } else
5381 ast_log(LOG_WARNING, "OSP token is too long\n");
5382 } else if (iaxdebug)
5383 ast_debug(1, "OSP token is undefined\n");
5384
5385 /* send the command using the appropriate socket for this peer */
5386 iaxs[callno]->sockfd = cai.sockfd;
5387
5388 /* Add remote vars */
5389 if (variablestore) {
5390 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5391 ast_debug(1, "Found an IAX variable store on this channel\n");
5392 AST_LIST_LOCK(variablelist);
5393 AST_LIST_TRAVERSE(variablelist, var, entries) {
5394 char tmp[256];
5395 int i;
5396 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5397 /* Automatically divide the value up into sized chunks */
5398 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5399 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5401 }
5402 }
5403 AST_LIST_UNLOCK(variablelist);
5404 }
5405
5406 /* Transmit the string in a "NEW" request */
5407 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5408 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5409
5410 ast_mutex_unlock(&iaxsl[callno]);
5412
5413 return 0;
5414}
5415
5416static int iax2_hangup(struct ast_channel *c)
5417{
5418 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5419 struct iax_ie_data ied;
5420 int alreadygone;
5421 memset(&ied, 0, sizeof(ied));
5422 ast_mutex_lock(&iaxsl[callno]);
5423 if (callno && iaxs[callno]) {
5424 ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
5425 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5426 /* Send the hangup unless we have had a transmission error or are already gone */
5428 if (!iaxs[callno]->error && !alreadygone) {
5429 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5430 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5431 }
5432 if (!iaxs[callno]) {
5433 ast_mutex_unlock(&iaxsl[callno]);
5434 return 0;
5435 }
5436 }
5437 /* Explicitly predestroy it */
5438 iax2_predestroy(callno);
5439 /* If we were already gone to begin with, destroy us now */
5440 if (iaxs[callno] && alreadygone) {
5441 ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
5442 iax2_destroy(callno);
5443 } else if (iaxs[callno]) {
5444 if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5445 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5446 iax2_destroy(callno);
5447 }
5448 }
5449 } else if (ast_channel_tech_pvt(c)) {
5450 /* If this call no longer exists, but the channel still
5451 * references it we need to set the channel's tech_pvt to null
5452 * to avoid ast_channel_free() trying to free it.
5453 */
5455 }
5456 ast_mutex_unlock(&iaxsl[callno]);
5457 ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
5458 return 0;
5459}
5460
5461/*!
5462 * \note expects the pvt to be locked
5463 */
5464static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5465{
5466 unsigned short callno = pvt->callno;
5467
5468 if (!pvt->peercallno) {
5469 /* We don't know the remote side's call number, yet. :( */
5470 int count = 10;
5471 while (count-- && pvt && !pvt->peercallno) {
5472 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5473 pvt = iaxs[callno];
5474 }
5475 if (!pvt || !pvt->peercallno) {
5476 return -1;
5477 }
5478 }
5479
5480 return 0;
5481}
5482
5483static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5484{
5485 struct ast_option_header *h;
5486 int res;
5487
5488 switch (option) {
5489 case AST_OPTION_TXGAIN:
5490 case AST_OPTION_RXGAIN:
5491 /* these two cannot be sent, because they require a result */
5492 errno = ENOSYS;
5493 return -1;
5494 case AST_OPTION_OPRMODE:
5495 errno = EINVAL;
5496 return -1;
5499 {
5500 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5501 ast_mutex_lock(&iaxsl[callno]);
5502 if ((*(int *) data)) {
5504 } else {
5506 }
5507 ast_mutex_unlock(&iaxsl[callno]);
5508 return 0;
5509 }
5510 /* These options are sent to the other side across the network where
5511 * they will be passed to whatever channel is bridged there. Don't
5512 * do anything silly like pass an option that transmits pointers to
5513 * memory on this machine to a remote machine to use */
5515 case AST_OPTION_TDD:
5520 {
5521 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5522 struct chan_iax2_pvt *pvt;
5523
5525 pvt = iaxs[callno];
5526
5527 if (wait_for_peercallno(pvt)) {
5529 return -1;
5530 }
5531
5533
5534 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5535 return -1;
5536 }
5537
5538 h->flag = AST_OPTION_FLAG_REQUEST;
5539 h->option = htons(option);
5540 memcpy(h->data, data, datalen);
5542 AST_CONTROL_OPTION, 0, (unsigned char *) h,
5543 datalen + sizeof(*h), -1);
5544 ast_free(h);
5545 return res;
5546 }
5547 default:
5548 return -1;
5549 }
5550
5551 /* Just in case someone does a break instead of a return */
5552 return -1;
5553}
5554
5555static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5556{
5557 switch (option) {
5560 {
5561 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5563 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5565 return 0;
5566 }
5567 default:
5568 return -1;
5569 }
5570}
5571
5572static struct ast_frame *iax2_read(struct ast_channel *c)
5573{
5574 ast_debug(1, "I should never be called!\n");
5575 return &ast_null_frame;
5576}
5577
5578static int iax2_key_rotate(const void *vpvt)
5579{
5580 int res = 0;
5581 struct chan_iax2_pvt *pvt = (void *) vpvt;
5582 struct MD5Context md5;
5583 char key[17] = "";
5584 struct iax_ie_data ied = {
5585 .pos = 0,
5586 };
5587
5588 ast_mutex_lock(&iaxsl[pvt->callno]);
5589 pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5590
5591 snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5592
5593 MD5Init(&md5);
5594 MD5Update(&md5, (unsigned char *) key, strlen(key));
5595 MD5Final((unsigned char *) key, &md5);
5596
5597 IAX_DEBUGDIGEST("Sending", key);
5598
5599 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5600
5601 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5602
5603 build_ecx_key((unsigned char *) key, pvt);
5604
5606
5607 return res;
5608}
5609
5610#if defined(IAX2_NATIVE_BRIDGING)
5611static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5612{
5613 int res;
5614 struct iax_ie_data ied0;
5615 struct iax_ie_data ied1;
5616 unsigned int transferid = (unsigned int)ast_random();
5617
5618 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5619 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5622 return 0;
5623 }
5624
5625 memset(&ied0, 0, sizeof(ied0));
5626 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5627 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5628 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5629
5630 memset(&ied1, 0, sizeof(ied1));
5631 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5632 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5633 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5634
5635 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5636 if (res)
5637 return -1;
5638 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5639 if (res)
5640 return -1;
5641 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5642 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5643 return 0;
5644}
5645#endif /* defined(IAX2_NATIVE_BRIDGING) */
5646
5647#if defined(IAX2_NATIVE_BRIDGING)
5648static void lock_both(unsigned short callno0, unsigned short callno1)
5649{
5650 ast_mutex_lock(&iaxsl[callno0]);
5651 while (ast_mutex_trylock(&iaxsl[callno1])) {
5652 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5653 }
5654}
5655#endif /* defined(IAX2_NATIVE_BRIDGING) */
5656
5657#if defined(IAX2_NATIVE_BRIDGING)
5658static void unlock_both(unsigned short callno0, unsigned short callno1)
5659{
5660 ast_mutex_unlock(&iaxsl[callno1]);
5661 ast_mutex_unlock(&iaxsl[callno0]);
5662}
5663#endif /* defined(IAX2_NATIVE_BRIDGING) */
5664
5665#if defined(IAX2_NATIVE_BRIDGING)
5666static 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)
5667{
5668 struct ast_channel *cs[3];
5669 struct ast_channel *who, *other;
5670 int to = -1;
5671 int res = -1;
5672 int transferstarted=0;
5673 struct ast_frame *f;
5674 unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
5675 unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
5676 struct timeval waittimer = {0, 0};
5677
5678 /* We currently do not support native bridging if a timeoutms value has been provided */
5679 if (timeoutms > 0) {
5680 return AST_BRIDGE_FAILED;
5681 }
5682
5683 timeoutms = -1;
5684
5685 lock_both(callno0, callno1);
5686 if (!iaxs[callno0] || !iaxs[callno1]) {
5687 unlock_both(callno0, callno1);
5688 return AST_BRIDGE_FAILED;
5689 }
5690 /* Put them in native bridge mode */
5692 iaxs[callno0]->bridgecallno = callno1;
5693 iaxs[callno1]->bridgecallno = callno0;
5694 }
5695 unlock_both(callno0, callno1);
5696
5697 /* If not, try to bridge until we can execute a transfer, if we can */
5698 cs[0] = c0;
5699 cs[1] = c1;
5700 for (/* ever */;;) {
5701 /* Check in case we got masqueraded into */
5702 if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
5703 ast_verb(3, "Can't masquerade, we're different...\n");
5704 /* Remove from native mode */
5705 if (ast_channel_tech(c0) == &iax2_tech) {
5706 ast_mutex_lock(&iaxsl[callno0]);
5707 iaxs[callno0]->bridgecallno = 0;
5708 ast_mutex_unlock(&iaxsl[callno0]);
5709 }
5710 if (ast_channel_tech(c1) == &iax2_tech) {
5711 ast_mutex_lock(&iaxsl[callno1]);
5712 iaxs[callno1]->bridgecallno = 0;
5713 ast_mutex_unlock(&iaxsl[callno1]);
5714 }
5716 }
5720
5721 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n",
5724
5725 /* Remove from native mode */
5726 lock_both(callno0, callno1);
5727 if (iaxs[callno0])
5728 iaxs[callno0]->bridgecallno = 0;
5729 if (iaxs[callno1])
5730 iaxs[callno1]->bridgecallno = 0;
5731 unlock_both(callno0, callno1);
5733 }
5734 /* check if transferred and if we really want native bridging */
5735 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5736 /* Try the transfer */
5737 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5739 ast_log(LOG_WARNING, "Unable to start the transfer\n");
5740 transferstarted = 1;
5741 }
5742 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5743 /* Call has been transferred. We're no longer involved */
5744 struct timeval now = ast_tvnow();
5745 if (ast_tvzero(waittimer)) {
5746 waittimer = now;
5747 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5750 *fo = NULL;
5751 *rc = c0;
5752 res = AST_BRIDGE_COMPLETE;
5753 break;
5754 }
5755 }
5756 to = 1000;
5757 who = ast_waitfor_n(cs, 2, &to);
5758 /* XXX This will need to be updated to calculate
5759 * timeout correctly once timeoutms is allowed to be
5760 * > 0. Right now, this can go badly if the waitfor
5761 * times out in less than a millisecond
5762 */
5763 if (timeoutms > -1) {
5764 timeoutms -= (1000 - to);
5765 if (timeoutms < 0)
5766 timeoutms = 0;
5767 }
5768 if (!who) {
5769 if (!timeoutms) {
5770 res = AST_BRIDGE_RETRY;
5771 break;
5772 }
5773 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5774 res = AST_BRIDGE_FAILED;
5775 break;
5776 }
5777 continue;
5778 }
5779 f = ast_read(who);
5780 if (!f) {
5781 *fo = NULL;
5782 *rc = who;
5783 res = AST_BRIDGE_COMPLETE;
5784 break;
5785 }
5786 other = (who == c0) ? c1 : c0; /* the 'other' channel */
5787 if (f->frametype == AST_FRAME_CONTROL) {
5788 switch (f->subclass.integer) {
5793 ast_write(other, f);
5794 break;
5797 break;
5798 default:
5799 *fo = f;
5800 *rc = who;
5801 res = AST_BRIDGE_COMPLETE;
5802 break;
5803 }
5804 if (res == AST_BRIDGE_COMPLETE) {
5805 break;
5806 }
5807 } else if (f->frametype == AST_FRAME_VOICE
5808 || f->frametype == AST_FRAME_TEXT
5809 || f->frametype == AST_FRAME_VIDEO
5810 || f->frametype == AST_FRAME_IMAGE) {
5811 ast_write(other, f);
5812 } else if (f->frametype == AST_FRAME_DTMF) {
5813 /* monitored dtmf take out of the bridge.
5814 * check if we monitor the specific source.
5815 */
5816 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5817
5818 if (flags & monitored_source) {
5819 *rc = who;
5820 *fo = f;
5821 res = AST_BRIDGE_COMPLETE;
5822 /* Remove from native mode */
5823 break;
5824 }
5825 ast_write(other, f);
5826 }
5827 ast_frfree(f);
5828 /* Swap who gets priority */
5829 cs[2] = cs[0];
5830 cs[0] = cs[1];
5831 cs[1] = cs[2];
5832 }
5833 lock_both(callno0, callno1);
5834 if(iaxs[callno0])
5835 iaxs[callno0]->bridgecallno = 0;
5836 if(iaxs[callno1])
5837 iaxs[callno1]->bridgecallno = 0;
5838 unlock_both(callno0, callno1);
5839 return res;
5840}
5841#endif /* defined(IAX2_NATIVE_BRIDGING) */
5842
5843static int iax2_answer(struct ast_channel *c)
5844{
5845 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5846 ast_debug(1, "Answering IAX2 call\n");
5848}
5849
5850static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5851{
5852 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5853 struct chan_iax2_pvt *pvt;
5854 int res = 0;
5855
5856 if (iaxdebug)
5857 ast_debug(1, "Indicating condition %d\n", condition);
5858
5860 pvt = iaxs[callno];
5861
5862 if (wait_for_peercallno(pvt)) {
5863 res = -1;
5864 goto done;
5865 }
5866
5867 switch (condition) {
5868 case AST_CONTROL_HOLD:
5869 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5870 ast_moh_start(c, data, pvt->mohinterpret);
5871 goto done;
5872 }
5873 break;
5874 case AST_CONTROL_UNHOLD:
5875 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5876 ast_moh_stop(c);
5877 goto done;
5878 }
5879 break;
5883 /* We are not configured to allow sending these updates. */
5884 ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5885 callno, condition);
5886 goto done;
5887 }
5888 break;
5891 res = -1;
5892 goto done;
5893 }
5894
5895 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5896
5897done:
5899
5900 return res;
5901}
5902
5903static int iax2_transfer(struct ast_channel *c, const char *dest)
5904{
5905 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5906 struct iax_ie_data ied = { "", };
5907 char tmp[256], *context;
5909 ast_copy_string(tmp, dest, sizeof(tmp));
5910 context = strchr(tmp, '@');
5911 if (context) {
5912 *context = '\0';
5913 context++;
5914 }
5916 if (context)
5918 ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
5920 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5921}
5922
5923static int iax2_getpeertrunk(struct ast_sockaddr addr)
5924{
5925 struct iax2_peer *peer;
5926 int res = 0;
5927 struct ao2_iterator i;
5928
5929 i = ao2_iterator_init(peers, 0);
5930 while ((peer = ao2_iterator_next(&i))) {
5931
5932 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
5933 res = ast_test_flag64(peer, IAX_TRUNK);
5934 peer_unref(peer);
5935 break;
5936 }
5937 peer_unref(peer);
5938 }
5940
5941 return res;
5942}
5943
5944/*! \brief Create new call, interface with the PBX core */
5945static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability,
5946 struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids,
5947 const struct ast_channel *requestor, unsigned int cachable)
5948{
5949 struct ast_channel *tmp = NULL;
5950 struct chan_iax2_pvt *i;
5951 struct iax2_peer *peer;
5952 struct ast_variable *v = NULL;
5953 struct ast_format_cap *native;
5954 struct ast_format *tmpfmt;
5955 ast_callid callid;
5956 char *peer_name = NULL;
5957
5958 if (!(i = iaxs[callno])) {
5959 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5960 return NULL;
5961 }
5962
5963 if (!capability) {
5964 ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5965 i->host, i->callno);
5966 return NULL;
5967 }
5969 if (!native) {
5970 return NULL;
5971 }
5972 if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5973 || !ast_format_cap_count(native)) {
5974 ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5975 i->host, i->callno);
5976 ao2_ref(native, -1);
5977 return NULL;
5978 }
5979
5980 if (!ast_strlen_zero(i->peer)) {
5981 peer_name = ast_strdupa(i->peer);
5982 } else if (!ast_strlen_zero(i->host)) {
5983 peer_name = ast_strdupa(i->host);
5984 }
5985
5986 /* Don't hold call lock while making a channel or looking up a peer */
5987 ast_mutex_unlock(&iaxsl[callno]);
5988
5989 if (!ast_strlen_zero(peer_name)) {
5990 peer = find_peer(peer_name, 1);
5991 if (peer && peer->endpoint) {
5993 i->accountcode, i->exten, i->context, assignedids, requestor,
5994 i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
5995 }
5996 ao2_cleanup(peer);
5997 }
5998
5999 if (!tmp) {
6000 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
6001 i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
6002 i->host, i->callno);
6003 }
6004
6005 ast_mutex_lock(&iaxsl[callno]);
6006 if (i != iaxs[callno]) {
6007 if (tmp) {
6008 /* unlock and relock iaxsl[callno] to preserve locking order */
6009 ast_mutex_unlock(&iaxsl[callno]);
6010 ast_channel_unlock(tmp);
6011 tmp = ast_channel_release(tmp);
6012 ast_mutex_lock(&iaxsl[callno]);
6013 }
6014 ao2_ref(native, -1);
6015 return NULL;
6016 }
6017 if (!tmp) {
6018 ao2_ref(native, -1);
6019 return NULL;
6020 }
6021
6023
6024 if ((callid = iaxs[callno]->callid)) {
6025 ast_channel_callid_set(tmp, callid);
6026 }
6027
6029
6030 /* We can support any format by default, until we get restricted */
6031 ast_channel_nativeformats_set(tmp, native);
6032 tmpfmt = ast_format_cap_get_format(native, 0);
6033
6034 ast_channel_set_readformat(tmp, tmpfmt);
6035 ast_channel_set_rawreadformat(tmp, tmpfmt);
6036 ast_channel_set_writeformat(tmp, tmpfmt);
6037 ast_channel_set_rawwriteformat(tmp, tmpfmt);
6038
6039 ao2_ref(tmpfmt, -1);
6040 ao2_ref(native, -1);
6041
6043
6044 if (!ast_strlen_zero(i->parkinglot))
6045 ast_channel_parkinglot_set(tmp, i->parkinglot);
6046 /* Don't use ast_set_callerid() here because it will
6047 * generate a NewCallerID event before the NewChannel event */
6048 if (!ast_strlen_zero(i->ani)) {
6051 } else if (!ast_strlen_zero(i->cid_num)) {
6054 }
6056 if (!ast_strlen_zero(i->rdnis)) {
6059 }
6065 if (!ast_strlen_zero(i->language))
6066 ast_channel_language_set(tmp, i->language);
6068 ast_channel_accountcode_set(tmp, i->accountcode);
6069 if (i->amaflags)
6073 if (i->adsi)
6075 else
6077 i->owner = tmp;
6078 i->capability = capability;
6079
6080 if (!cachable) {
6082 }
6083
6084 /* Set inherited variables */
6085 if (i->vars) {
6086 for (v = i->vars ; v ; v = v->next)
6088 }
6089 if (i->iaxvars) {
6090 struct ast_datastore *variablestore;
6091 struct ast_variable *var, *prev = NULL;
6092 AST_LIST_HEAD(, ast_var_t) *varlist;
6093 ast_debug(1, "Loading up the channel with IAXVARs\n");
6094 varlist = ast_calloc(1, sizeof(*varlist));
6096 if (variablestore && varlist) {
6097 variablestore->data = varlist;
6098 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6099 AST_LIST_HEAD_INIT(varlist);
6100 for (var = i->iaxvars; var; var = var->next) {
6101 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6102 if (prev)
6103 ast_free(prev);
6104 prev = var;
6105 if (!newvar) {
6106 /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
6107 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6108 } else {
6109 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6110 }
6111 }
6112 if (prev)
6113 ast_free(prev);
6114 i->iaxvars = NULL;
6115 ast_channel_datastore_add(i->owner, variablestore);
6116 } else {
6117 if (variablestore) {
6118 ast_datastore_free(variablestore);
6119 }
6120 if (varlist) {
6121 ast_free(varlist);
6122 }
6123 }
6124 }
6125
6127 ast_channel_unlock(tmp);
6128
6129 if (state != AST_STATE_DOWN) {
6130 if (ast_pbx_start(tmp)) {
6131 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6132 /* unlock and relock iaxsl[callno] to preserve locking order */
6133 ast_mutex_unlock(&iaxsl[callno]);
6134 ast_hangup(tmp);
6135 ast_mutex_lock(&iaxsl[callno]);
6136 return NULL;
6137 }
6138 }
6139
6141 return tmp;
6142}
6143
6144static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
6145{
6146 unsigned long int mssincetx; /* unsigned to handle overflows */
6147 long int ms, pred;
6148
6149 tpeer->trunkact = *now;
6150 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
6151 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
6152 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
6153 tpeer->txtrunktime = *now;
6154 tpeer->lastsent = 999999;
6155 }
6156 /* Update last transmit time now */
6157 tpeer->lasttxtime = *now;
6158
6159 /* Calculate ms offset */
6160 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
6161 /* Predict from last value */
6162 pred = tpeer->lastsent + sampms;
6163 if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
6164 ms = pred;
6165
6166 /* We never send the same timestamp twice, so fudge a little if we must */
6167 if (ms == tpeer->lastsent)
6168 ms = tpeer->lastsent + 1;
6169 tpeer->lastsent = ms;
6170 return ms;
6171}
6172
6173static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
6174{
6175 long ms; /* NOT unsigned */
6176 if (ast_tvzero(iaxs[callno]->rxcore)) {
6177 /* Initialize rxcore time if appropriate */
6178 iaxs[callno]->rxcore = ast_tvnow();
6179 /* Round to nearest 20ms so traces look pretty */
6180 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6181 }
6182 /* Calculate difference between trunk and channel */
6183 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6184 /* Return as the sum of trunk time and the difference between trunk and real time */
6185 return ms + ts;
6186}
6187
6188static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6189{
6190 int ms;
6191 int voice = 0;
6192 int genuine = 0;
6193 int adjust;
6194 int rate = 0;
6195 struct timeval *delivery = NULL;
6196
6197
6198 /* What sort of frame do we have?: voice is self-explanatory
6199 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6200 non-genuine frames are CONTROL frames [ringing etc], DTMF
6201 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6202 the others need a timestamp slaved to the voice frames so that they go in sequence
6203 */
6204 if (f->frametype == AST_FRAME_VOICE) {
6205 voice = 1;
6206 rate = ast_format_get_sample_rate(f->subclass.format) / 1000;
6207 delivery = &f->delivery;
6208 } else if (f->frametype == AST_FRAME_IAX) {
6209 genuine = 1;
6210 } else if (f->frametype == AST_FRAME_CNG) {
6211 p->notsilenttx = 0;
6212 }
6213
6214 if (ast_tvzero(p->offset)) {
6215 p->offset = ast_tvnow();
6216 /* Round to nearest 20ms for nice looking traces */
6217 p->offset.tv_usec -= p->offset.tv_usec % 20000;
6218 }
6219 /* If the timestamp is specified, just send it as is */
6220 if (ts)
6221 return ts;
6222 /* If we have a time that the frame arrived, always use it to make our timestamp */
6223 if (delivery && !ast_tvzero(*delivery)) {
6224 ms = ast_tvdiff_ms(*delivery, p->offset);
6225 if (ms < 0) {
6226 ms = 0;
6227 }
6228 if (iaxdebug)
6229 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6230 } else {
6231 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6232 if (ms < 0)
6233 ms = 0;
6234 if (voice) {
6235 /* On a voice frame, use predicted values if appropriate */
6236 adjust = (ms - p->nextpred);
6237 if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6238 /* Adjust our txcore, keeping voice and non-voice synchronized */
6239 /* AN EXPLANATION:
6240 When we send voice, we usually send "calculated" timestamps worked out
6241 on the basis of the number of samples sent. When we send other frames,
6242 we usually send timestamps worked out from the real clock.
6243 The problem is that they can tend to drift out of step because the
6244 source channel's clock and our clock may not be exactly at the same rate.
6245 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6246 for this call. Moving it adjusts timestamps for non-voice frames.
6247 We make the adjustment in the style of a moving average. Each time we
6248 adjust p->offset by 10% of the difference between our clock-derived
6249 timestamp and the predicted timestamp. That's why you see "10000"
6250 below even though IAX2 timestamps are in milliseconds.
6251 The use of a moving average avoids offset moving too radically.
6252 Generally, "adjust" roams back and forth around 0, with offset hardly
6253 changing at all. But if a consistent different starts to develop it
6254 will be eliminated over the course of 10 frames (200-300msecs)
6255 */
6256 if (adjust < 0)
6257 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6258 else if (adjust > 0)
6259 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6260
6261 if (!p->nextpred) {
6262 p->nextpred = ms; /*f->samples / rate;*/
6263 if (p->nextpred <= p->lastsent)
6264 p->nextpred = p->lastsent + 3;
6265 }
6266 ms = p->nextpred;
6267 } else {
6268 /* in this case, just use the actual
6269 * time, since we're either way off
6270 * (shouldn't happen), or we're ending a
6271 * silent period -- and seed the next
6272 * predicted time. Also, round ms to the
6273 * next multiple of frame size (so our
6274 * silent periods are multiples of
6275 * frame size too) */
6276
6277 if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
6278 ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6279 abs(adjust), MAX_TIMESTAMP_SKEW);
6280
6281 if (f->samples >= rate) /* check to make sure we don't core dump */
6282 {
6283 int diff = ms % (f->samples / rate);
6284 if (diff)
6285 ms += f->samples/rate - diff;
6286 }
6287
6288 p->nextpred = ms;
6289 p->notsilenttx = 1;
6290 }
6291 } else if ( f->frametype == AST_FRAME_VIDEO ) {
6292 /*
6293 * IAX2 draft 03 says that timestamps MUST be in order.
6294 * It does not say anything about several frames having the same timestamp
6295 * When transporting video, we can have a frame that spans multiple iax packets
6296 * (so called slices), so it would make sense to use the same timestamp for all of
6297 * them
6298 * We do want to make sure that frames don't go backwards though
6299 */
6300 if ( (unsigned int)ms < p->lastsent )
6301 ms = p->lastsent;
6302 } else {
6303 /* On a dataframe, use last value + 3 (to accommodate jitter buffer shrinking) if appropriate unless
6304 it's a genuine frame */
6305 adjust = (ms - p->lastsent);
6306 if (genuine) {
6307 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6308 if (ms <= p->lastsent)
6309 ms = p->lastsent + 3;
6310 } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6311 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6312 ms = p->lastsent + 3;
6313 }
6314 }
6315 }
6316 p->lastsent = ms;
6317 if (voice) {
6318 p->nextpred = p->nextpred + f->samples / rate;
6319 }
6320 return ms;
6321}
6322
6323static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6324{
6325 /* Returns where in "receive time" we are. That is, how many ms
6326 since we received (or would have received) the frame with timestamp 0 */
6327 int ms;
6328#ifdef IAXTESTS
6329 int jit;
6330#endif /* IAXTESTS */
6331 /* Setup rxcore if necessary */
6332 if (ast_tvzero(p->rxcore)) {
6333 p->rxcore = ast_tvnow();
6334 if (iaxdebug)
6335 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6336 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6337 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6338#if 1
6339 if (iaxdebug)
6340 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6341 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6342#endif
6343 }
6344
6345 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6346#ifdef IAXTESTS
6347 if (test_jit) {
6348 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6349 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6350 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6351 jit = -jit;
6352 ms += jit;
6353 }
6354 }
6355 if (test_late) {
6356 ms += test_late;
6357 test_late = 0;
6358 }
6359#endif /* IAXTESTS */
6360 return ms;
6361}
6362
6363static struct iax2_trunk_peer *find_tpeer(struct ast_sockaddr *addr, int fd)
6364{
6365 struct iax2_trunk_peer *tpeer = NULL;
6366
6367 /* Finds and locks trunk peer */
6369
6370 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6371 if (!ast_sockaddr_cmp(&tpeer->addr, addr)) {
6372 ast_mutex_lock(&tpeer->lock);
6373 break;
6374 }
6375 }
6376
6377 if (!tpeer) {
6378 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6379 ast_mutex_init(&tpeer->lock);
6380 tpeer->lastsent = 9999;
6381 ast_sockaddr_copy(&tpeer->addr, addr);
6382 tpeer->trunkact = ast_tvnow();
6383 ast_mutex_lock(&tpeer->lock);
6384 tpeer->sockfd = fd;
6385
6386#ifdef SO_NO_CHECK
6387 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6388#endif
6389 ast_debug(1, "Created trunk peer for '%s'\n", ast_sockaddr_stringify(&tpeer->addr));
6391 }
6392 }
6393
6395
6396 return tpeer;
6397}
6398
6399static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6400{
6401 struct ast_frame *f;
6402 struct iax2_trunk_peer *tpeer;
6403 void *tmp, *ptr;
6404 struct timeval now;
6405 struct ast_iax2_meta_trunk_entry *met;
6406 struct ast_iax2_meta_trunk_mini *mtm;
6407
6408 f = &fr->af;
6409 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6410 if (tpeer) {
6411
6412 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6413 /* Need to reallocate space */
6414 if (tpeer->trunkdataalloc < trunkmaxsize) {
6415 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6416 ast_mutex_unlock(&tpeer->lock);
6417 return -1;
6418 }
6419
6421 tpeer->trunkdata = tmp;
6422 ast_debug(1, "Expanded trunk '%s' to %u bytes\n", ast_sockaddr_stringify(&tpeer->addr), tpeer->trunkdataalloc);
6423 } else {
6424 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s\n", ast_sockaddr_stringify(&tpeer->addr));
6425 ast_mutex_unlock(&tpeer->lock);
6426 return -1;
6427 }
6428 }
6429
6430 /* Append to meta frame */
6431 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6433 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6434 mtm->len = htons(f->datalen);
6435 mtm->mini.callno = htons(pvt->callno);
6436 mtm->mini.ts = htons(0xffff & fr->ts);
6437 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6438 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6439 } else {
6440 met = (struct ast_iax2_meta_trunk_entry *)ptr;
6441 /* Store call number and length in meta header */
6442 met->callno = htons(pvt->callno);
6443 met->len = htons(f->datalen);
6444 /* Advance pointers/decrease length past trunk entry header */
6445 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6446 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6447 }
6448 /* Copy actual trunk data */
6449 memcpy(ptr, f->data.ptr, f->datalen);
6450 tpeer->trunkdatalen += f->datalen;
6451
6452 tpeer->calls++;
6453
6454 /* track the largest mtu we actually have sent */
6455 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6456 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6457
6458 /* if we have enough for a full MTU, ship it now without waiting */
6459 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6460 now = ast_tvnow();
6461 send_trunk(tpeer, &now);
6462 trunk_untimed ++;
6463 }
6464
6465 ast_mutex_unlock(&tpeer->lock);
6466 }
6467 return 0;
6468}
6469
6470/* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6471 * before the encryption data. This function randomizes that data. */
6472static void build_rand_pad(unsigned char *buf, ssize_t len)
6473{
6474 long tmp;
6475 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6476 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6477 buf += sizeof(tmp);
6478 len -= sizeof(tmp);
6479 }
6480}
6481
6483{
6484#ifdef HAVE_OPENSSL
6485 int i;
6486 for (i = 0; i < 60; i++) {
6487 if (ecx->raw[i]) {
6488 return 0; /* stop if we encounter anything non-zero */
6489 }
6490 }
6491 /* if ast_aes_encrypt or ast_aes_decrypt is called, then we'll crash when calling AES_encrypt or AES_decrypt */
6492 return -1;
6493#else
6494 return 0; /* Can't verify, but doesn't matter anyways */
6495#endif
6496}
6497
6498static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6499{
6500 build_ecx_key(digest, pvt);
6501 ast_aes_set_decrypt_key(digest, &pvt->dcx);
6502}
6503
6504static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6505{
6506 /* it is required to hold the corresponding decrypt key to our encrypt key
6507 * in the pvt struct because queued frames occasionally need to be decrypted and
6508 * re-encrypted when updated for a retransmission */
6509 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6510 ast_aes_set_encrypt_key(digest, &pvt->ecx);
6511 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6512}
6513
6514static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6515{
6516#if 0
6517 /* Debug with "fake encryption" */
6518 int x;
6519 if (len % 16)
6520 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6521 for (x=0;x<len;x++)
6522 dst[x] = src[x] ^ 0xff;
6523#else
6524 unsigned char lastblock[16] = { 0 };
6525 int x;
6526 while(len > 0) {
6527 ast_aes_decrypt(src, dst, dcx);
6528 for (x=0;x<16;x++)
6529 dst[x] ^= lastblock[x];
6530 memcpy(lastblock, src, sizeof(lastblock));
6531 dst += 16;
6532 src += 16;
6533 len -= 16;
6534 }
6535#endif
6536}
6537
6538static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6539{
6540#if 0
6541 /* Debug with "fake encryption" */
6542 int x;
6543 if (len % 16)
6544 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6545 for (x=0;x<len;x++)
6546 dst[x] = src[x] ^ 0xff;
6547#else
6548 unsigned char curblock[16] = { 0 };
6549 int x;
6550 while(len > 0) {
6551 for (x=0;x<16;x++)
6552 curblock[x] ^= src[x];
6553 ast_aes_encrypt(curblock, dst, ecx);
6554 memcpy(curblock, dst, sizeof(curblock));
6555 dst += 16;
6556 src += 16;
6557 len -= 16;
6558 }
6559#endif
6560}
6561
6562static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6563{
6564 int padding;
6565 unsigned char *workspace;
6566
6567 workspace = ast_alloca(*datalen);
6568 memset(f, 0, sizeof(*f));
6569 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6570 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6571 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6572 return -1;
6573 /* Decrypt */
6574 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6575
6576 padding = 16 + (workspace[15] & 0x0f);
6577 if (iaxdebug)
6578 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
6579 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6580 return -1;
6581
6582 *datalen -= padding;
6583 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6584 f->frametype = fh->type;
6585 if (f->frametype == AST_FRAME_VIDEO) {
6587 if (!f->subclass.format) {
6589 }
6590 } else if (f->frametype == AST_FRAME_VOICE) {
6592 if (!f->subclass.format) {
6594 }
6595 } else {
6597 }
6598 } else {
6599 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6600 if (iaxdebug)
6601 ast_debug(5, "Decoding mini with length %d\n", *datalen);
6602 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6603 return -1;
6604 /* Decrypt */
6605 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6606 padding = 16 + (workspace[15] & 0x0f);
6607 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6608 return -1;
6609 *datalen -= padding;
6610 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6611 }
6612 return 0;
6613}
6614
6615static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6616{
6617 int padding;
6618 unsigned char *workspace;
6619 workspace = ast_alloca(*datalen + 32);
6620 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6621 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6622 if (iaxdebug)
6623 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6624 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6625 padding = 16 + (padding & 0xf);
6626 memcpy(workspace, poo, padding);
6627 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6628 workspace[15] &= 0xf0;
6629 workspace[15] |= (padding & 0xf);
6630 if (iaxdebug)
6631 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
6632 *datalen += padding;
6633 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6634 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6635 memcpy(poo, workspace + *datalen - 32, 32);
6636 } else {
6637 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6638 if (iaxdebug)
6639 ast_debug(5, "Encoding mini frame with length %d\n", *datalen);
6640 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6641 padding = 16 + (padding & 0xf);
6642 memcpy(workspace, poo, padding);
6643 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6644 workspace[15] &= 0xf0;
6645 workspace[15] |= (padding & 0x0f);
6646 *datalen += padding;
6647 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6648 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6649 memcpy(poo, workspace + *datalen - 32, 32);
6650 }
6651 return 0;
6652}
6653
6654static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6655{
6656 int res=-1;
6658 /* Search for possible keys, given secrets */
6659 struct MD5Context md5;
6660 unsigned char digest[16];
6661 char *tmppw, *stringp;
6662
6663 tmppw = ast_strdupa(iaxs[callno]->secret);
6664 stringp = tmppw;
6665 while ((tmppw = strsep(&stringp, ";"))) {
6666 MD5Init(&md5);
6667 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6668 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6669 MD5Final(digest, &md5);
6670 build_encryption_keys(digest, iaxs[callno]);
6671 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6672 if (!res) {
6674 break;
6675 }
6676 }
6677 } else
6678 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6679 return res;
6680}
6681
6682static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6683{
6684 /* Queue a packet for delivery on a given private structure. Use "ts" for
6685 timestamp, or calculate if ts is 0. Send immediately without retransmission
6686 or delayed, with retransmission */
6687 struct ast_iax2_full_hdr *fh;
6688 struct ast_iax2_mini_hdr *mh;
6689 struct ast_iax2_video_hdr *vh;
6690 struct {
6691 struct iax_frame fr2;
6692 unsigned char buffer[4096];
6693 } frb;
6694 struct iax_frame *fr;
6695 int res;
6696 int sendmini=0;
6697 unsigned int lastsent;
6698 unsigned int fts;
6699
6700 frb.fr2.afdatalen = sizeof(frb.buffer);
6701
6702 if (!pvt) {
6703 ast_log(LOG_WARNING, "No private structure for packet?\n");
6704 return -1;
6705 }
6706
6707 lastsent = pvt->lastsent;
6708
6709 /* Calculate actual timestamp */
6710 fts = calc_timestamp(pvt, ts, f);
6711
6712 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6713 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6714 * increment the "predicted timestamps" for voice, if we're predicting */
6715 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6716 return 0;
6717#if 0
6719 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6720 *("=!" + (f->frametype == AST_FRAME_VOICE)),
6721 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6722 pvt->keyrotateid != -1 ? "" : "no "
6723 );
6724#endif
6725 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6726 iax2_key_rotate(pvt);
6727 }
6728
6729 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6730 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6731 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6732 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6734 /* is a voice frame */ &&
6737 /* is the same type */ ) {
6738 /* Force immediate rather than delayed transmission */
6739 now = 1;
6740 /* Mark that mini-style frame is appropriate */
6741 sendmini = 1;
6742 }
6743 if ( f->frametype == AST_FRAME_VIDEO ) {
6744 /*
6745 * If the lower 15 bits of the timestamp roll over, or if
6746 * the video format changed then send a full frame.
6747 * Otherwise send a mini video frame
6748 */
6749 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6752 ) {
6753 now = 1;
6754 sendmini = 1;
6755 } else {
6756 now = 0;
6757 sendmini = 0;
6758 }
6759 pvt->lastvsent = fts;
6760 }
6761 if (f->frametype == AST_FRAME_IAX) {
6762 /* 0x8000 marks this message as TX:, this bit will be stripped later */
6764 if (!pvt->first_iax_message) {
6766 }
6767 }
6768 /* Allocate an iax_frame */
6769 if (now) {
6770 fr = &frb.fr2;
6771 } else
6773 if (!fr) {
6774 ast_log(LOG_WARNING, "Out of memory\n");
6775 return -1;
6776 }
6777 /* Copy our prospective frame into our immediate or retransmitted wrapper */
6778 iax_frame_wrap(fr, f);
6779
6780 fr->ts = fts;
6781 fr->callno = pvt->callno;
6782 fr->transfer = transfer;
6783 fr->final = final;
6784 fr->encmethods = 0;
6785 if (!sendmini) {
6786 /* We need a full frame */
6787 if (seqno > -1)
6788 fr->oseqno = seqno;
6789 else
6790 fr->oseqno = pvt->oseqno++;
6791 fr->iseqno = pvt->iseqno;
6792 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6793 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6794 fh->ts = htonl(fr->ts);
6795 fh->oseqno = fr->oseqno;
6796 if (transfer) {
6797 fh->iseqno = 0;
6798 } else
6799 fh->iseqno = fr->iseqno;
6800 /* Keep track of the last thing we've acknowledged */
6801 if (!transfer)
6802 pvt->aseqno = fr->iseqno;
6803 fh->type = fr->af.frametype & 0xFF;
6804
6805 if (fr->af.frametype == AST_FRAME_VIDEO) {
6807 tmpfmt |= fr->af.subclass.frame_ending ? 0x1LL : 0;
6808 fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
6809 } else if (fr->af.frametype == AST_FRAME_VOICE) {
6811 } else {
6813 }
6814
6815 if (transfer) {
6816 fr->dcallno = pvt->transfercallno;
6817 } else
6818 fr->dcallno = pvt->peercallno;
6819 fh->dcallno = htons(fr->dcallno);
6820 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6821 fr->data = fh;
6822 fr->retries = 0;
6823 /* Retry after 2x the ping time has passed */
6824 fr->retrytime = pvt->pingtime * 2;
6825 if (fr->retrytime < MIN_RETRY_TIME)
6827 if (fr->retrytime > MAX_RETRY_TIME)
6829 /* Acks' don't get retried */
6831 fr->retries = -1;
6832 else if (f->frametype == AST_FRAME_VOICE)
6834 else if (f->frametype == AST_FRAME_VIDEO)
6836 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6838 if (fr->transfer)
6839 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6840 else
6841 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6842 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6843 fr->encmethods = pvt->encmethods;
6844 fr->ecx = pvt->ecx;
6845 fr->mydcx = pvt->mydcx;
6846 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6847 } else
6848 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6849 }
6850
6851 if (now) {
6852 res = send_packet(fr);
6853 } else
6854 res = iax2_transmit(fr);
6855 } else {
6856 if (ast_test_flag64(pvt, IAX_TRUNK)) {
6857 iax2_trunk_queue(pvt, fr);
6858 res = 0;
6859 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6860 /* Video frame have no sequence number */
6861 fr->oseqno = -1;
6862 fr->iseqno = -1;
6863 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6864 vh->zeros = 0;
6865 vh->callno = htons(0x8000 | fr->callno);
6866 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.frame_ending ? 0x8000 : 0));
6867 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6868 fr->data = vh;
6869 fr->retries = -1;
6870 res = send_packet(fr);
6871 } else {
6872 /* Mini-frames have no sequence number */
6873 fr->oseqno = -1;
6874 fr->iseqno = -1;
6875 /* Mini frame will do */
6876 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6877 mh->callno = htons(fr->callno);
6878 mh->ts = htons(fr->ts & 0xFFFF);
6879 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6880 fr->data = mh;
6881 fr->retries = -1;
6882 if (pvt->transferring == TRANSFER_MEDIAPASS)
6883 fr->transfer = 1;
6884 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6886 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6887 } else
6888 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6889 }
6890 res = send_packet(fr);
6891 }
6892 }
6893 return res;
6894}
6895
6896static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6897{
6898 regex_t regexbuf;
6899 int havepattern = 0;
6900
6901#define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6902#define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6903
6904 struct iax2_user *user = NULL;
6905 char auth[90];
6906 char *pstr = "";
6907 struct ao2_iterator i;
6908
6909 switch (cmd) {
6910 case CLI_INIT:
6911 e->command = "iax2 show users [like]";
6912 e->usage =
6913 "Usage: iax2 show users [like <pattern>]\n"
6914 " Lists all known IAX2 users.\n"
6915 " Optional regular expression pattern is used to filter the user list.\n";
6916 return NULL;
6917 case CLI_GENERATE:
6918 return NULL;
6919 }
6920
6921 switch (a->argc) {
6922 case 5:
6923 if (!strcasecmp(a->argv[3], "like")) {
6924 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6925 return CLI_SHOWUSAGE;
6926 havepattern = 1;
6927 } else
6928 return CLI_SHOWUSAGE;
6929 case 3:
6930 break;
6931 default:
6932 return CLI_SHOWUSAGE;
6933 }
6934
6935 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6936 i = ao2_iterator_init(users, 0);
6937 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6938 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6939 continue;
6940
6941 if (!ast_strlen_zero(user->secret)) {
6942 ast_copy_string(auth,user->secret, sizeof(auth));
6943 } else if (!ast_strlen_zero(user->inkeys)) {
6944 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6945 } else
6946 ast_copy_string(auth, "-no secret-", sizeof(auth));
6947
6949 pstr = "REQ Only";
6951 pstr = "Disabled";
6952 else
6953 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6954
6955 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6956 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6957 ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
6958 }
6960
6961 if (havepattern)
6962 regfree(&regexbuf);
6963
6964 return CLI_SUCCESS;
6965#undef FORMAT
6966#undef FORMAT2
6967}
6968
6970 regex_t regexbuf;
6972 char idtext[256];
6979};
6980
6981#define PEERS_FORMAT2 "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
6982#define PEERS_FORMAT "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
6983
6984static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
6985{
6986 char name[256] = "";
6987 char status[64];
6988 int retstatus;
6989 struct ast_str *encmethods = ast_str_alloca(256);
6990
6991 char *tmp_host, *tmp_mask, *tmp_port;
6992
6993 tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
6994 tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
6995 tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
6996
6997 if (!ast_strlen_zero(peer->username)) {
6998 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
6999 } else {
7000 ast_copy_string(name, peer->name, sizeof(name));
7001 }
7002
7003 encmethods_to_str(peer->encmethods, &encmethods);
7004 retstatus = peer_status(peer, status, sizeof(status));
7005 if (retstatus > 0) {
7006 cont->online_peers++;
7007 } else if (!retstatus) {
7008 cont->offline_peers++;
7009 } else {
7010 cont->unmonitored_peers++;
7011 }
7012
7013 if (s) {
7014 if (cont->peerlist) { /* IAXpeerlist */
7015 astman_append(s,
7016 "Event: PeerEntry\r\n%s"
7017 "Channeltype: IAX\r\n",
7018 cont->idtext);
7019 if (!ast_strlen_zero(peer->username)) {
7020 astman_append(s,
7021 "ObjectName: %s\r\n"
7022 "ObjectUsername: %s\r\n",
7023 peer->name,
7024 peer->username);
7025 } else {
7026 astman_append(s,
7027 "ObjectName: %s\r\n",
7028 name);
7029 }
7030 } else { /* IAXpeers */
7031 astman_append(s,
7032 "Event: PeerEntry\r\n%s"
7033 "Channeltype: IAX2\r\n"
7034 "ObjectName: %s\r\n",
7035 cont->idtext,
7036 name);
7037 }
7038 astman_append(s,
7039 "ChanObjectType: peer\r\n"
7040 "IPaddress: %s\r\n",
7041 tmp_host);
7042 if (cont->peerlist) { /* IAXpeerlist */
7043 astman_append(s,
7044 "Mask: %s\r\n"
7045 "Port: %s\r\n",
7046 tmp_mask,
7047 tmp_port);
7048 } else { /* IAXpeers */
7049 astman_append(s,
7050 "IPport: %s\r\n",
7051 tmp_port);
7052 }
7053 astman_append(s,
7054 "Dynamic: %s\r\n"
7055 "Trunk: %s\r\n"
7056 "Encryption: %s\r\n"
7057 "Status: %s\r\n",
7058 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
7059 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
7060 peer->encmethods ? ast_str_buffer(encmethods) : "no",
7061 status);
7062 if (cont->peerlist) { /* IAXpeerlist */
7063 astman_append(s, "\r\n");
7064 } else { /* IAXpeers */
7065 astman_append(s,
7066 "Description: %s\r\n\r\n",
7067 peer->description);
7068 }
7069 } else {
7071 name,
7072 tmp_host,
7073 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
7074 tmp_mask,
7075 tmp_port,
7076 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
7077 peer->encmethods ? "(E)" : " ",
7078 status,
7079 peer->description);
7080 }
7081
7082 cont->total_peers++;
7083}
7084
7085static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
7086{
7087 struct show_peers_context cont = {
7088 .havepattern = 0,
7089 .idtext = "",
7090 .registeredonly = 0,
7091
7092 .peerlist = 0,
7093
7094 .total_peers = 0,
7095 .online_peers = 0,
7096 .offline_peers = 0,
7097 .unmonitored_peers = 0,
7098 };
7099
7100 struct ao2_iterator i;
7101
7102 struct iax2_peer *peer = NULL;
7103
7104 switch (argc) {
7105 case 6:
7106 if (!strcasecmp(argv[3], "registered"))
7107 cont.registeredonly = 1;
7108 else
7109 return RESULT_SHOWUSAGE;
7110 if (!strcasecmp(argv[4], "like")) {
7111 if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
7112 return RESULT_SHOWUSAGE;
7113 cont.havepattern = 1;
7114 } else
7115 return RESULT_SHOWUSAGE;
7116 break;
7117 case 5:
7118 if (!strcasecmp(argv[3], "like")) {
7119 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
7120 return RESULT_SHOWUSAGE;
7121 cont.havepattern = 1;
7122 } else
7123 return RESULT_SHOWUSAGE;
7124 break;
7125 case 4:
7126 if (!strcasecmp(argv[3], "registered")) {
7127 cont.registeredonly = 1;
7128 } else {
7129 return RESULT_SHOWUSAGE;
7130 }
7131 break;
7132 case 3:
7133 break;
7134 default:
7135 return RESULT_SHOWUSAGE;
7136 }
7137
7138
7139 if (!s) {
7140 ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7141 }
7142
7143 i = ao2_iterator_init(peers, 0);
7144 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7145
7146 if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7147 continue;
7148 }
7149 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7150 continue;
7151 }
7152
7153 _iax2_show_peers_one(fd, s, &cont, peer);
7154
7155 }
7157
7158 if (!s) {
7159 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7161 }
7162
7163 if (cont.havepattern) {
7164 regfree(&cont.regexbuf);
7165 }
7166
7167 if (total) {
7168 *total = cont.total_peers;
7169 }
7170
7171 return RESULT_SUCCESS;
7172
7173}
7174#undef PEERS_FORMAT2
7175#undef PEERS_FORMAT
7176
7177static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7178{
7179 struct iax2_thread *thread = NULL;
7180 time_t t;
7181 int threadcount = 0, dynamiccount = 0;
7182 char type;
7183
7184 switch (cmd) {
7185 case CLI_INIT:
7186 e->command = "iax2 show threads";
7187 e->usage =
7188 "Usage: iax2 show threads\n"
7189 " Lists status of IAX helper threads\n";
7190 return NULL;
7191 case CLI_GENERATE:
7192 return NULL;
7193 }
7194 if (a->argc != 3)
7195 return CLI_SHOWUSAGE;
7196
7197 ast_cli(a->fd, "IAX2 Thread Information\n");
7198 time(&t);
7199 ast_cli(a->fd, "Idle Threads:\n");
7202#ifdef DEBUG_SCHED_MULTITHREAD
7203 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7204 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7205#else
7206 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7207 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7208#endif
7209 threadcount++;
7210 }
7212 ast_cli(a->fd, "Active Threads:\n");
7215 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
7216 type = 'D';
7217 else
7218 type = 'P';
7219#ifdef DEBUG_SCHED_MULTITHREAD
7220 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
7221 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7222#else
7223 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
7224 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7225#endif
7226 threadcount++;
7227 }
7229 ast_cli(a->fd, "Dynamic Threads:\n");
7232#ifdef DEBUG_SCHED_MULTITHREAD
7233 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7234 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7235#else
7236 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7237 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7238#endif
7239 dynamiccount++;
7240 }
7242 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
7243 return CLI_SUCCESS;
7244}
7245
7246static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7247{
7248 struct iax2_peer *p;
7249
7250 switch (cmd) {
7251 case CLI_INIT:
7252 e->command = "iax2 unregister";
7253 e->usage =
7254 "Usage: iax2 unregister <peername>\n"
7255 " Unregister (force expiration) an IAX2 peer from the registry.\n";
7256 return NULL;
7257 case CLI_GENERATE:
7258 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
7259 }
7260
7261 if (a->argc != 3)
7262 return CLI_SHOWUSAGE;
7263
7264 p = find_peer(a->argv[2], 1);
7265 if (p) {
7266 if (p->expire > -1) {
7267 struct iax2_peer *peer;
7268
7269 peer = ao2_find(peers, a->argv[2], OBJ_KEY);
7270 if (peer) {
7271 expire_registry(peer_ref(peer)); /* will release its own reference when done */
7272 peer_unref(peer); /* ref from ao2_find() */
7273 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
7274 } else {
7275 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
7276 }
7277 } else {
7278 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7279 }
7280 peer_unref(p);
7281 } else {
7282 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7283 }
7284 return CLI_SUCCESS;
7285}
7286
7287static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7288{
7289 int which = 0;
7290 struct iax2_peer *p = NULL;
7291 char *res = NULL;
7292 int wordlen = strlen(word);
7293
7294 /* 0 - iax2; 1 - unregister; 2 - <peername> */
7295 if (pos == 2) {
7296 struct ao2_iterator i = ao2_iterator_init(peers, 0);
7297 while ((p = ao2_iterator_next(&i))) {
7298 if (!strncasecmp(p->name, word, wordlen) &&
7299 ++which > state && p->expire > -1) {
7300 res = ast_strdup(p->name);
7301 peer_unref(p);
7302 break;
7303 }
7304 peer_unref(p);
7305 }
7307 }
7308
7309 return res;
7310}
7311
7312static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7313{
7314 switch (cmd) {
7315 case CLI_INIT:
7316 e->command = "iax2 show peers";
7317 e->usage =
7318 "Usage: iax2 show peers [registered] [like <pattern>]\n"
7319 " Lists all known IAX2 peers.\n"
7320 " Optional 'registered' argument lists only peers with known addresses.\n"
7321 " Optional regular expression pattern is used to filter the peer list.\n";
7322 return NULL;
7323 case CLI_GENERATE:
7324 return NULL;
7325 }
7326
7327 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7328 case RESULT_SHOWUSAGE:
7329 return CLI_SHOWUSAGE;
7330 case RESULT_FAILURE:
7331 return CLI_FAILURE;
7332 default:
7333 return CLI_SUCCESS;
7334 }
7335}
7336
7337static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7338{
7339 ast_cli_netstats(s, -1, 0);
7340 astman_append(s, "\r\n");
7341 return RESULT_SUCCESS;
7342}
7343
7345 void *user_data)
7346{
7347 int *fd = user_data;
7348
7349 ast_cli(*fd, "%-15.15s %-15d %-15d\n",
7350 header->devname,
7351 ntohs(header->version),
7352 (int) ntohl(header->datalen));
7353
7354 return 0;
7355}
7356
7357static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7358{
7359 switch (cmd) {
7360 case CLI_INIT:
7361 e->command = "iax2 show firmware";
7362 e->usage =
7363 "Usage: iax2 show firmware\n"
7364 " Lists all known IAX firmware images.\n";
7365 return NULL;
7366 case CLI_GENERATE:
7367 return NULL;
7368 }
7369
7370 if (a->argc != 3 && a->argc != 4)
7371 return CLI_SHOWUSAGE;
7372
7373 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7374
7376 a->argc == 3 ? NULL : a->argv[3],
7378 (void *) &a->fd);
7379
7380 return CLI_SUCCESS;
7381}
7382
7383/*! \brief callback to display iax peers in manager */
7384static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7385{
7386 static const char * const a[] = { "iax2", "show", "peers" };
7387 const char *id = astman_get_header(m,"ActionID");
7388 char idtext[256] = "";
7389 int total = 0;
7390
7391 if (!ast_strlen_zero(id))
7392 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7393
7394 astman_send_listack(s, m, "Peer status list will follow", "start");
7395
7396 /* List the peers in separate manager events */
7397 __iax2_show_peers(-1, &total, s, 3, a);
7398
7399 /* Send final confirmation */
7400 astman_send_list_complete_start(s, m, "PeerlistComplete", total);
7402 return 0;
7403}
7404
7405/*! \brief callback to display iax peers in manager format */
7406static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7407{
7408 struct show_peers_context cont = {
7409 .havepattern = 0,
7410 .idtext = "",
7411 .registeredonly = 0,
7412
7413 .peerlist = 1,
7414
7415 .total_peers = 0,
7416 .online_peers = 0,
7417 .offline_peers = 0,
7418 .unmonitored_peers = 0,
7419 };
7420
7421 struct iax2_peer *peer = NULL;
7422 struct ao2_iterator i;
7423
7424 const char *id = astman_get_header(m,"ActionID");
7425
7426 if (!ast_strlen_zero(id)) {
7427 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
7428 }
7429
7430 astman_send_listack(s, m, "IAX Peer status list will follow", "start");
7431
7432 i = ao2_iterator_init(peers, 0);
7433 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7434 _iax2_show_peers_one(-1, s, &cont, peer);
7435 }
7437
7438 astman_send_list_complete_start(s, m, "PeerlistComplete", cont.total_peers);
7440
7441 return RESULT_SUCCESS;
7442}
7443
7444
7445static char *regstate2str(int regstate)
7446{
7447 switch(regstate) {
7449 return "Unregistered";
7450 case REG_STATE_REGSENT:
7451 return "Request Sent";
7452 case REG_STATE_AUTHSENT:
7453 return "Auth. Sent";
7455 return "Registered";
7456 case REG_STATE_REJECTED:
7457 return "Rejected";
7458 case REG_STATE_TIMEOUT:
7459 return "Timeout";
7460 case REG_STATE_NOAUTH:
7461 return "No Authentication";
7462 default:
7463 return "Unknown";
7464 }
7465}
7466
7467static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7468{
7469#define FORMAT2 "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
7470#define FORMAT "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
7471
7472 struct iax2_registry *reg = NULL;
7473 char host[80];
7474 char perceived[80];
7475 int counter = 0;
7476
7477 switch (cmd) {
7478 case CLI_INIT:
7479 e->command = "iax2 show registry";
7480 e->usage =
7481 "Usage: iax2 show registry\n"
7482 " Lists all registration requests and status.\n";
7483 return NULL;
7484 case CLI_GENERATE:
7485 return NULL;
7486 }
7487 if (a->argc != 3)
7488 return CLI_SHOWUSAGE;
7489 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7492 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7493
7494 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7495
7496 ast_cli(a->fd, FORMAT, host,
7497 (reg->dnsmgr) ? "Y" : "N",
7498 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7499 counter++;
7500 }
7502 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7503 return CLI_SUCCESS;
7504#undef FORMAT
7505#undef FORMAT2
7506}
7507
7508static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7509{
7510 const char *id = astman_get_header(m, "ActionID");
7511 struct iax2_registry *reg = NULL;
7512 char idtext[256] = "";
7513 char host[80] = "";
7514 char perceived[80] = "";
7515 int total = 0;
7516
7517 if (!ast_strlen_zero(id))
7518 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7519
7520 astman_send_listack(s, m, "Registrations will follow", "start");
7521
7524 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7525
7526 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7527
7528 astman_append(s,
7529 "Event: RegistryEntry\r\n"
7530 "%s"
7531 "Host: %s\r\n"
7532 "DNSmanager: %s\r\n"
7533 "Username: %s\r\n"
7534 "Perceived: %s\r\n"
7535 "Refresh: %d\r\n"
7536 "State: %s\r\n"
7537 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7538 reg->refresh, regstate2str(reg->regstate));
7539
7540 total++;
7541 }
7543
7544 astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
7546
7547 return 0;
7548}
7549
7550static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7551{
7552#define FORMAT2 "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7553#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"
7554#define FORMATB "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7555 int x;
7556 int numchans = 0;
7557 char first_message[10] = { 0, };
7558 char last_message[10] = { 0, };
7559
7560 switch (cmd) {
7561 case CLI_INIT:
7562 e->command = "iax2 show channels";
7563 e->usage =
7564 "Usage: iax2 show channels\n"
7565 " Lists all currently active IAX channels.\n";
7566 return NULL;
7567 case CLI_GENERATE:
7568 return NULL;
7569 }
7570
7571 if (a->argc != 3)
7572 return CLI_SHOWUSAGE;
7573 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7574 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7575 ast_mutex_lock(&iaxsl[x]);
7576 if (iaxs[x]) {
7577 int lag, jitter, localdelay;
7578 jb_info jbinfo;
7580 jb_getinfo(iaxs[x]->jb, &jbinfo);
7581 jitter = jbinfo.jitter;
7582 localdelay = jbinfo.current - jbinfo.min;
7583 } else {
7584 jitter = -1;
7585 localdelay = 0;
7586 }
7587
7588 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7589 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7590 lag = iaxs[x]->remote_rr.delay;
7591 ast_cli(a->fd, FORMAT,
7592 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7594 S_OR(iaxs[x]->username, "(None)"),
7595 iaxs[x]->callno, iaxs[x]->peercallno,
7596 iaxs[x]->oseqno, iaxs[x]->iseqno,
7597 lag,
7598 jitter,
7599 localdelay,
7600 iax2_getformatname(iaxs[x]->voiceformat),
7601 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7602 first_message,
7603 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7604 last_message);
7605 numchans++;
7606 }
7608 }
7609 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7610 return CLI_SUCCESS;
7611#undef FORMAT
7612#undef FORMAT2
7613#undef FORMATB
7614}
7615
7616static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7617{
7618 int x;
7619 int numchans = 0;
7620 char first_message[10] = { 0, };
7621 char last_message[10] = { 0, };
7622#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"
7623#define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7624 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7625 ast_mutex_lock(&iaxsl[x]);
7626 if (iaxs[x]) {
7627 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7628 jb_info jbinfo;
7629 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7630 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7631
7633 jb_getinfo(iaxs[x]->jb, &jbinfo);
7634 localjitter = jbinfo.jitter;
7635 localdelay = jbinfo.current - jbinfo.min;
7636 locallost = jbinfo.frames_lost;
7637 locallosspct = jbinfo.losspct/1000;
7638 localdropped = jbinfo.frames_dropped;
7639 localooo = jbinfo.frames_ooo;
7640 } else {
7641 localjitter = -1;
7642 localdelay = 0;
7643 locallost = -1;
7644 locallosspct = -1;
7645 localdropped = 0;
7646 localooo = -1;
7647 }
7648 if (s)
7649 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7650 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7651 iaxs[x]->pingtime,
7652 localjitter,
7653 localdelay,
7654 locallost,
7655 locallosspct,
7656 localdropped,
7657 localooo,
7658 iaxs[x]->frames_received/1000,
7659 iaxs[x]->remote_rr.jitter,
7660 iaxs[x]->remote_rr.delay,
7664 iaxs[x]->remote_rr.ooo,
7665 iaxs[x]->remote_rr.packets/1000,
7666 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7667 first_message,
7668 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7669 last_message);
7670 else
7671 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7672 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7673 iaxs[x]->pingtime,
7674 localjitter,
7675 localdelay,
7676 locallost,
7677 locallosspct,
7678 localdropped,
7679 localooo,
7680 iaxs[x]->frames_received/1000,
7681 iaxs[x]->remote_rr.jitter,
7682 iaxs[x]->remote_rr.delay,
7686 iaxs[x]->remote_rr.ooo,
7687 iaxs[x]->remote_rr.packets/1000,
7688 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7689 first_message,
7690 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7691 last_message);
7692 numchans++;
7693 }
7695 }
7696
7697 return numchans;
7698}
7699
7700static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7701{
7702 int numchans = 0;
7703
7704 switch (cmd) {
7705 case CLI_INIT:
7706 e->command = "iax2 show netstats";
7707 e->usage =
7708 "Usage: iax2 show netstats\n"
7709 " Lists network status for all currently active IAX channels.\n";
7710 return NULL;
7711 case CLI_GENERATE:
7712 return NULL;
7713 }
7714 if (a->argc != 3)
7715 return CLI_SHOWUSAGE;
7716 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7717 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7718 numchans = ast_cli_netstats(NULL, a->fd, 1);
7719 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7720 return CLI_SUCCESS;
7721}
7722
7723static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7724{
7725 switch (cmd) {
7726 case CLI_INIT:
7727 e->command = "iax2 set debug {on|off|peer}";
7728 e->usage =
7729 "Usage: iax2 set debug {on|off|peer peername}\n"
7730 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7731 return NULL;
7732 case CLI_GENERATE:
7733 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7734 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7735 return NULL;
7736 }
7737
7738 if (a->argc < e->args || a->argc > e->args + 1)
7739 return CLI_SHOWUSAGE;
7740
7741 if (!strcasecmp(a->argv[3], "peer")) {
7742 struct iax2_peer *peer;
7743
7744 if (a->argc != e->args + 1)
7745 return CLI_SHOWUSAGE;
7746
7747 peer = find_peer(a->argv[4], 1);
7748
7749 if (!peer) {
7750 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7751 return CLI_FAILURE;
7752 }
7753
7755
7756 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_port(&debugaddr));
7757
7758 ao2_ref(peer, -1);
7759 } else if (!strncasecmp(a->argv[3], "on", 2)) {
7760 iaxdebug = 1;
7761 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7762 } else {
7763 iaxdebug = 0;
7764 memset(&debugaddr, 0, sizeof(debugaddr));
7765 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7766 }
7767 return CLI_SUCCESS;
7768}
7769
7770static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7771{
7772 switch (cmd) {
7773 case CLI_INIT:
7774 e->command = "iax2 set debug trunk {on|off}";
7775 e->usage =
7776 "Usage: iax2 set debug trunk {on|off}\n"
7777 " Enables/Disables debugging of IAX trunking\n";
7778 return NULL;
7779 case CLI_GENERATE:
7780 return NULL;
7781 }
7782
7783 if (a->argc != e->args)
7784 return CLI_SHOWUSAGE;
7785
7786 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7787 iaxtrunkdebug = 1;
7788 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7789 } else {
7790 iaxtrunkdebug = 0;
7791 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7792 }
7793 return CLI_SUCCESS;
7794}
7795
7796static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7797{
7798 switch (cmd) {
7799 case CLI_INIT:
7800 e->command = "iax2 set debug jb {on|off}";
7801 e->usage =
7802 "Usage: iax2 set debug jb {on|off}\n"
7803 " Enables/Disables jitterbuffer debugging information\n";
7804 return NULL;
7805 case CLI_GENERATE:
7806 return NULL;
7807 }
7808
7809 if (a->argc != e->args)
7810 return CLI_SHOWUSAGE;
7811
7812 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7814 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7815 } else {
7817 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7818 }
7819 return CLI_SUCCESS;
7820}
7821
7822static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7823{
7824 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
7825 int res = -1;
7827 if (iaxs[callno]) {
7828 /* If there's an outstanding error, return failure now */
7829 if (!iaxs[callno]->error) {
7831 res = 0;
7832 /* Don't waste bandwidth sending null frames */
7833 else if (f->frametype == AST_FRAME_NULL)
7834 res = 0;
7836 res = 0;
7838 res = 0;
7839 else
7840 /* Simple, just queue for transmission */
7841 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7842 } else {
7843 ast_debug(1, "Write error: %s\n", strerror(errno));
7844 }
7845 }
7846 /* If it's already gone, just return */
7848 return res;
7849}
7850
7851static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7852 int now, int transfer, int final)
7853{
7854 struct ast_frame f = { 0, };
7855 int res = 0;
7856
7857 f.frametype = type;
7858 f.subclass.integer = command;
7859 f.datalen = datalen;
7860 f.src = __FUNCTION__;
7861 f.data.ptr = (void *) data;
7862
7863 if ((res = queue_signalling(i, &f)) <= 0) {
7864 return res;
7865 }
7866
7867 return iax2_send(i, &f, ts, seqno, now, transfer, final);
7868}
7869
7870static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7871{
7873 /* Control frame should not go out on the wire. */
7874 ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7875 i->callno, command);
7876 return 0;
7877 }
7878 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7879}
7880
7881static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7882{
7883 int res;
7884 ast_mutex_lock(&iaxsl[callno]);
7885 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7886 ast_mutex_unlock(&iaxsl[callno]);
7887 return res;
7888}
7889
7890/*!
7891 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7892 * the pvt struct for the given call number may disappear during its
7893 * execution.
7894 */
7895static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7896{
7897 int call_num = i->callno;
7898 /* It is assumed that the callno has already been locked */
7900 if (!iaxs[call_num])
7901 return -1;
7902 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7903}
7904
7905static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7906{
7907 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7908}
7909
7910static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7911{
7912 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7913}
7914
7915static int apply_context(struct iax2_context *con, const char *context)
7916{
7917 while(con) {
7918 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7919 return -1;
7920 con = con->next;
7921 }
7922 return 0;
7923}
7924
7925
7926static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
7927{
7928 /* Start pessimistic */
7929 int res = -1;
7930 int version = 2;
7931 struct iax2_user *user = NULL, *best = NULL;
7932 int bestscore = 0;
7933 int gotcapability = 0;
7934 struct ast_variable *v = NULL, *tmpvar = NULL;
7935 struct ao2_iterator i;
7936
7937 if (!iaxs[callno])
7938 return res;
7939 if (ies->called_number)
7940 ast_string_field_set(iaxs[callno], exten, ies->called_number);
7941 if (ies->calling_number) {
7944 }
7945 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7946 }
7947 if (ies->calling_name)
7948 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7949 if (ies->calling_ani)
7950 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7951 if (ies->dnid)
7952 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7953 if (ies->rdnis)
7954 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7955 if (ies->called_context)
7957 if (ies->language)
7959 if (ies->username)
7960 ast_string_field_set(iaxs[callno], username, ies->username);
7961 if (ies->calling_ton > -1)
7962 iaxs[callno]->calling_ton = ies->calling_ton;
7963 if (ies->calling_tns > -1)
7964 iaxs[callno]->calling_tns = ies->calling_tns;
7965 if (ies->calling_pres > -1)
7966 iaxs[callno]->calling_pres = ies->calling_pres;
7967 if (ies->calling_ani2 > -1)
7968 iaxs[callno]->calling_ani2 = ies->calling_ani2;
7969 if (ies->format)
7970 iaxs[callno]->peerformat = ies->format;
7971 if (ies->adsicpe)
7972 iaxs[callno]->peeradsicpe = ies->adsicpe;
7973 if (ies->capability) {
7974 gotcapability = 1;
7975 iaxs[callno]->peercapability = ies->capability;
7976 }
7977 if (ies->version)
7978 version = ies->version;
7979
7980 /* Use provided preferences until told otherwise for actual preferences */
7981 if (ies->codec_prefs) {
7982 iax2_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7983 } else {
7984 memset(&iaxs[callno]->rprefs, 0, sizeof(iaxs[callno]->rprefs));
7985 }
7986 iaxs[callno]->prefs = iaxs[callno]->rprefs;
7987
7988 if (!gotcapability) {
7989 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
7990 }
7991 if (version > IAX_PROTO_VERSION) {
7992 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
7994 return res;
7995 }
7996 /* Search the userlist for a compatible entry, and fill in the rest */
7997 i = ao2_iterator_init(users, 0);
7998 while ((user = ao2_iterator_next(&i))) {
7999 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
8000 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
8001 && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
8002 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
8003 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
8004 if (!ast_strlen_zero(iaxs[callno]->username)) {
8005 /* Exact match, stop right now. */
8006 if (best)
8007 user_unref(best);
8008 best = user;
8009 break;
8010 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
8011 /* No required authentication */
8012 if (user->acl) {
8013 /* There was host authentication and we passed, bonus! */
8014 if (bestscore < 4) {
8015 bestscore = 4;
8016 if (best)
8017 user_unref(best);
8018 best = user;
8019 continue;
8020 }
8021 } else {
8022 /* No host access, but no secret, either, not bad */
8023 if (bestscore < 3) {
8024 bestscore = 3;
8025 if (best)
8026 user_unref(best);
8027 best = user;
8028 continue;
8029 }
8030 }
8031 } else {
8032 if (user->acl) {
8033 /* Authentication, but host access too, eh, it's something.. */
8034 if (bestscore < 2) {
8035 bestscore = 2;
8036 if (best)
8037 user_unref(best);
8038 best = user;
8039 continue;
8040 }
8041 } else {
8042 /* Authentication and no host access... This is our baseline */
8043 if (bestscore < 1) {
8044 bestscore = 1;
8045 if (best)
8046 user_unref(best);
8047 best = user;
8048 continue;
8049 }
8050 }
8051 }
8052 }
8054 }
8056 user = best;
8057 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
8058 user = realtime_user(iaxs[callno]->username, addr);
8059 if (user && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
8060 || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
8061 !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
8062 user = user_unref(user);
8063 }
8064 }
8065 if (user) {
8066 /* We found our match (use the first) */
8067 /* copy vars */
8068 for (v = user->vars ; v ; v = v->next) {
8069 if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
8070 if (ast_variable_list_replace(&iaxs[callno]->vars, tmpvar)) {
8071 tmpvar->next = iaxs[callno]->vars;
8072 iaxs[callno]->vars = tmpvar;
8073 }
8074 }
8075 }
8076 /* If a max AUTHREQ restriction is in place, activate it */
8077 if (user->maxauthreq > 0)
8079 iaxs[callno]->prefs = user->prefs;
8081 iaxs[callno]->encmethods = user->encmethods;
8082 /* Store the requested username if not specified */
8083 if (ast_strlen_zero(iaxs[callno]->username))
8084 ast_string_field_set(iaxs[callno], username, user->name);
8085 /* Store whether this is a trunked call, too, of course, and move if appropriate */
8087 iaxs[callno]->capability = user->capability;
8088 /* And use the default context */
8089 if (ast_strlen_zero(iaxs[callno]->context)) {
8090 if (user->contexts)
8091 ast_string_field_set(iaxs[callno], context, user->contexts->context);
8092 else
8094 }
8095 /* And any input keys */
8096 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
8097 /* And the permitted authentication methods */
8098 iaxs[callno]->authmethods = user->authmethods;
8099 iaxs[callno]->adsi = user->adsi;
8100 /* If the user has callerid, override the remote caller id. */
8102 iaxs[callno]->calling_tns = 0;
8103 iaxs[callno]->calling_ton = 0;
8104 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
8105 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
8106 ast_string_field_set(iaxs[callno], ani, user->cid_num);
8108 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
8110 } /* else user is allowed to set their own CID settings */
8111 if (!ast_strlen_zero(user->accountcode))
8112 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
8113 if (!ast_strlen_zero(user->mohinterpret))
8114 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
8115 if (!ast_strlen_zero(user->mohsuggest))
8116 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
8117 if (!ast_strlen_zero(user->parkinglot))
8118 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
8119 if (user->amaflags)
8120 iaxs[callno]->amaflags = user->amaflags;
8121 if (!ast_strlen_zero(user->language))
8122 ast_string_field_set(iaxs[callno], language, user->language);
8124 /* Keep this check last */
8125 if (!ast_strlen_zero(user->dbsecret)) {
8126 char *family, *key=NULL;
8127 char buf[80];
8128 family = ast_strdupa(user->dbsecret);
8129 key = strchr(family, '/');
8130 if (key) {
8131 *key = '\0';
8132 key++;
8133 }
8134 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
8135 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
8136 else
8137 ast_string_field_set(iaxs[callno], secret, buf);
8138 } else
8139 ast_string_field_set(iaxs[callno], secret, user->secret);
8140 res = 0;
8141 user = user_unref(user);
8142 } else {
8143 /* user was not found, but we should still fake an AUTHREQ.
8144 * Set authmethods to the last known authmethod used by the system
8145 * Set a fake secret, it's not looked at, just required to attempt authentication.
8146 * Set authrej so the AUTHREP is rejected without even looking at its contents */
8148 ast_string_field_set(iaxs[callno], secret, "badsecret");
8149 iaxs[callno]->authrej = 1;
8150 if (!ast_strlen_zero(iaxs[callno]->username)) {
8151 /* only send the AUTHREQ if a username was specified. */
8152 res = 0;
8153 }
8154 }
8156 return res;
8157}
8158
8159static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
8160{
8161 struct ast_iax2_full_hdr fh;
8162 fh.scallno = htons(src | IAX_FLAG_FULL);
8163 fh.dcallno = htons(dst);
8164 fh.ts = 0;
8165 fh.oseqno = 0;
8166 fh.iseqno = 0;
8167 fh.type = AST_FRAME_IAX;
8169 iax_outputframe(NULL, &fh, 0, addr, 0);
8170
8171 ast_debug(1, "Raw Hangup %s, src=%d, dst=%d\n", ast_sockaddr_stringify(addr), src, dst);
8172 return ast_sendto(sockfd, &fh, sizeof(fh), 0, addr);
8173}
8174
8175static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
8176{
8177 /* Select exactly one common encryption if there are any */
8178 p->encmethods &= enc;
8179 if (p->encmethods) {
8180 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
8181 p->keyrotateid = -2;
8182 }
8185 else
8186 p->encmethods = 0;
8187 }
8188}
8189
8190/*!
8191 * \pre iaxsl[call_num] is locked
8192 *
8193 * \note Since this function calls send_command_final(), the pvt struct for the given
8194 * call number may disappear while executing this function.
8195 */
8196static int authenticate_request(int call_num)
8197{
8198 struct iax_ie_data ied;
8199 int res = -1, authreq_restrict = 0;
8200 char challenge[10];
8201 struct chan_iax2_pvt *p = iaxs[call_num];
8202
8203 memset(&ied, 0, sizeof(ied));
8204
8205 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8207 struct iax2_user *user;
8208
8210 if (user) {
8211 if (user->curauthreq == user->maxauthreq)
8212 authreq_restrict = 1;
8213 else
8214 user->curauthreq++;
8215 user = user_unref(user);
8216 }
8217 }
8218
8219 /* If the AUTHREQ limit test failed, send back an error */
8220 if (authreq_restrict) {
8221 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8224 return 0;
8225 }
8226
8228 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8229 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8231 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8233 }
8234 if (p->encmethods)
8236
8238
8239 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8240
8241 if (p->encmethods)
8243
8244 return res;
8245}
8246
8247static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
8248{
8249 char requeststr[256];
8250 char md5secret[256] = "";
8251 char secret[256] = "";
8252 char rsasecret[256] = "";
8253 int res = -1;
8254 int x;
8255 struct iax2_user *user;
8256
8257 if (p->authrej) {
8258 return res;
8259 }
8260
8262 if (user) {
8264 ast_atomic_fetchadd_int(&user->curauthreq, -1);
8266 }
8267 ast_string_field_set(p, host, user->name);
8268 user = user_unref(user);
8269 }
8271 ast_log(LOG_WARNING, "Call Terminated, incoming call is unencrypted while force encrypt is enabled.\n");
8272 return res;
8273 }
8275 return res;
8276 if (ies->password)
8277 ast_copy_string(secret, ies->password, sizeof(secret));
8278 if (ies->md5_result)
8279 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8280 if (ies->rsa_result)
8281 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8282 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8283 struct ast_key *key;
8284 char *keyn;
8285 char *tmpkey;
8286 char *stringp=NULL;
8287 if (!(tmpkey = ast_strdup(p->inkeys))) {
8288 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8289 return res;
8290 }
8291 stringp = tmpkey;
8292 keyn = strsep(&stringp, ":");
8293 while(keyn) {
8294 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8295 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8296 res = 0;
8298 break;
8299 } else if (!key) {
8300 ast_log(LOG_WARNING, "Requested inkey '%s' for RSA authentication does not exist\n", keyn);
8301 }
8302 keyn = strsep(&stringp, ":");
8303 }
8304 ast_free(tmpkey);
8305 if (res && authdebug) {
8306 ast_log(LOG_WARNING, "No RSA public keys on file matched incoming call\n");
8307 }
8308 } else if (p->authmethods & IAX_AUTH_MD5) {
8309 struct MD5Context md5;
8310 unsigned char digest[16];
8311 char *tmppw, *stringp;
8312 tmppw = ast_strdupa(p->secret);
8313 stringp = tmppw;
8314 while((tmppw = strsep(&stringp, ";"))) {
8315 MD5Init(&md5);
8316 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8317 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8318 MD5Final(digest, &md5);
8319 /* If they support md5, authenticate with it. */
8320 for (x=0;x<16;x++)
8321 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8322 if (!strcasecmp(requeststr, md5secret)) {
8323 res = 0;
8325 break;
8326 } else if (authdebug) {
8327 ast_log(LOG_WARNING, "MD5 secret mismatch\n");
8328 }
8329 }
8330 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8331 if (!strcmp(secret, p->secret)) {
8332 res = 0;
8334 } else if (authdebug) {
8335 ast_log(LOG_WARNING, "Plaintext secret mismatch\n");
8336 }
8337 }
8338 return res;
8339}
8340
8341/*! \brief Verify inbound registration */
8342static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
8343{
8344 char requeststr[256] = "";
8345 char peer[256] = "";
8346 char md5secret[256] = "";
8347 char rsasecret[256] = "";
8348 char secret[256] = "";
8349 struct iax2_peer *p = NULL;
8350 struct ast_key *key;
8351 char *keyn;
8352 int x;
8353 int expire = 0;
8354 int res = -1;
8355
8357 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8358 if (ies->username)
8359 ast_copy_string(peer, ies->username, sizeof(peer));
8360 if (ies->password)
8361 ast_copy_string(secret, ies->password, sizeof(secret));
8362 if (ies->md5_result)
8363 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8364 if (ies->rsa_result)
8365 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8366 if (ies->refresh)
8367 expire = ies->refresh;
8368
8369 if (ast_strlen_zero(peer)) {
8370 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_sockaddr_stringify_addr(addr));
8371 return -1;
8372 }
8373
8374 /* SLD: first call to lookup peer during registration */
8375 ast_mutex_unlock(&iaxsl[callno]);
8376 p = find_peer(peer, 1);
8377 ast_mutex_lock(&iaxsl[callno]);
8378 if (!p || !iaxs[callno]) {
8379 if (iaxs[callno]) {
8380 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8381 /* Anything, as long as it's non-blank */
8382 ast_string_field_set(iaxs[callno], secret, "badsecret");
8383 /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8384 * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8385 * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8386 * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8387 * to be plaintext, indicating it is an authmethod used by other peers on the system.
8388 *
8389 * If none of these cases exist, res will be returned as 0 without authentication indicating
8390 * an AUTHREQ needs to be sent out. */
8391
8392 if (ast_strlen_zero(iaxs[callno]->challenge) &&
8393 !(!ast_strlen_zero(secret) && plaintext)) {
8394 /* by setting res to 0, an REGAUTH will be sent */
8395 res = 0;
8396 }
8397 }
8398 if (authdebug && !p)
8399 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8400 goto return_unref;
8401 }
8402
8403 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8404 if (authdebug)
8405 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8406 goto return_unref;
8407 }
8408
8409 if (!ast_apply_acl(p->acl, addr, "IAX2 Peer ACL: ")) {
8410 if (authdebug)
8411 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8412 goto return_unref;
8413 }
8414 ast_string_field_set(iaxs[callno], secret, p->secret);
8415 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8416 /* Check secret against what we have on file */
8417 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8418 if (!ast_strlen_zero(p->inkeys)) {
8419 char *tmpkey;
8420 char *stringp=NULL;
8421 if (!(tmpkey = ast_strdup(p->inkeys))) {
8422 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8423 goto return_unref;
8424 }
8425 stringp = tmpkey;
8426 keyn = strsep(&stringp, ":");
8427 while(keyn) {
8428 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8429 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8431 break;
8432 } else if (!key)
8433 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8434 keyn = strsep(&stringp, ":");
8435 }
8436 ast_free(tmpkey);
8437 if (!keyn) {
8438 if (authdebug)
8439 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8440 goto return_unref;
8441 }
8442 } else {
8443 if (authdebug)
8444 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8445 goto return_unref;
8446 }
8447 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8448 struct MD5Context md5;
8449 unsigned char digest[16];
8450 char *tmppw, *stringp;
8451
8452 tmppw = ast_strdupa(p->secret);
8453 stringp = tmppw;
8454 while((tmppw = strsep(&stringp, ";"))) {
8455 MD5Init(&md5);
8456 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8457 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8458 MD5Final(digest, &md5);
8459 for (x=0;x<16;x++)
8460 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8461 if (!strcasecmp(requeststr, md5secret))
8462 break;
8463 }
8464 if (tmppw) {
8466 } else {
8467 if (authdebug)
8468 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_sockaddr_stringify_addr(addr), p->name, requeststr, md5secret);
8469 goto return_unref;
8470 }
8471 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8472 /* They've provided a plain text password and we support that */
8473 if (strcmp(secret, p->secret)) {
8474 if (authdebug)
8475 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8476 goto return_unref;
8477 } else
8479 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8480 /* if challenge has been sent, but no challenge response if given, reject. */
8481 goto return_unref;
8482 }
8483 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8484
8485 /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8486 res = 0;
8487
8488return_unref:
8489 if (iaxs[callno]) {
8490 ast_string_field_set(iaxs[callno], peer, peer);
8491
8492 /* Choose lowest expiry number */
8493 if (expire && (expire < iaxs[callno]->expiry)) {
8494 iaxs[callno]->expiry = expire;
8495 }
8496 }
8497
8498 if (p) {
8499 peer_unref(p);
8500 }
8501 return res;
8502}
8503
8504static 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)
8505{
8506 int res = -1;
8507 int x;
8508 if (!ast_strlen_zero(keyn)) {
8509 if (!(authmethods & IAX_AUTH_RSA)) {
8510 if (ast_strlen_zero(secret)) {
8511 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));
8512 }
8513 } else if (ast_strlen_zero(challenge)) {
8514 ast_log(LOG_WARNING, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8515 } else {
8516 char sig[256];
8517 struct ast_key *key;
8518 key = ast_key_get(keyn, AST_KEY_PRIVATE);
8519 if (!key) {
8520 ast_log(LOG_WARNING, "Unable to find private key '%s'\n", keyn);
8521 } else {
8522 if (ast_sign(key, (char*)challenge, sig)) {
8523 ast_log(LOG_WARNING, "Unable to sign challenge with key\n");
8524 res = -1;
8525 } else {
8527 if (pvt) {
8529 }
8530 res = 0;
8531 }
8532 }
8533
8534 if (pvt && !ast_strlen_zero(secret)) {
8535 struct MD5Context md5;
8536 unsigned char digest[16];
8537
8538 MD5Init(&md5);
8539 MD5Update(&md5, (unsigned char *) challenge, strlen(challenge));
8540 MD5Update(&md5, (unsigned char *) secret, strlen(secret));
8541 MD5Final(digest, &md5);
8542
8543 build_encryption_keys(digest, pvt);
8544 }
8545 }
8546 }
8547 /* Fall back */
8548 if (res && !ast_strlen_zero(secret)) {
8549 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8550 struct MD5Context md5;
8551 unsigned char digest[16];
8552 char digres[128];
8553 MD5Init(&md5);
8554 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8555 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8556 MD5Final(digest, &md5);
8557 /* If they support md5, authenticate with it. */
8558 for (x=0;x<16;x++)
8559 sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8560 if (pvt) {
8561 build_encryption_keys(digest, pvt);
8563 }
8565 res = 0;
8566 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8567 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8568 if (pvt) {
8570 }
8571 res = 0;
8572 } else
8573 ast_log(LOG_WARNING, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8574 }
8575 return res;
8576}
8577
8578/*!
8579 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8580 * so do not call this function with a pvt lock held.
8581 */
8582static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
8583{
8584 struct iax2_peer *peer = NULL;
8585 /* Start pessimistic */
8586 int res = -1;
8587 int authmethods = 0;
8588 struct iax_ie_data ied;
8589 uint16_t callno = p->callno;
8590
8591 memset(&ied, 0, sizeof(ied));
8592
8593 if (ies->username)
8594 ast_string_field_set(p, username, ies->username);
8595 if (ies->challenge)
8597 if (ies->authmethods)
8598 authmethods = ies->authmethods;
8599 if (authmethods & IAX_AUTH_MD5)
8601 else
8602 p->encmethods = 0;
8603
8604 /* Check for override RSA authentication first */
8605 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8606 /* Normal password authentication */
8607 res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8608 } else {
8609 struct ao2_iterator i = ao2_iterator_init(peers, 0);
8610 while ((peer = ao2_iterator_next(&i))) {
8611 struct ast_sockaddr peer_addr;
8612 struct ast_sockaddr tmp_sockaddr1;
8613 struct ast_sockaddr tmp_sockaddr2;
8614
8615 ast_sockaddr_copy(&peer_addr, &peer->addr);
8616
8617 ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8618 ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8619
8620 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8621 /* No peer specified at our end, or this is the peer */
8622 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8623 /* No username specified in peer rule, or this is the right username */
8624 && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8625 /* No specified host, or this is our host */
8626 ) {
8627 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8628 if (!res) {
8629 peer_unref(peer);
8630 break;
8631 }
8632 }
8633 peer_unref(peer);
8634 }
8636 if (!peer) {
8637 /* We checked our list and didn't find one. It's unlikely, but possible,
8638 that we're trying to authenticate *to* a realtime peer */
8639 const char *peer_name = ast_strdupa(p->peer);
8640 ast_mutex_unlock(&iaxsl[callno]);
8641 if ((peer = realtime_peer(peer_name, NULL))) {
8642 ast_mutex_lock(&iaxsl[callno]);
8643 if (!(p = iaxs[callno])) {
8644 peer_unref(peer);
8645 return -1;
8646 }
8647 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8648 peer_unref(peer);
8649 }
8650 if (!peer) {
8651 ast_mutex_lock(&iaxsl[callno]);
8652 if (!(p = iaxs[callno]))
8653 return -1;
8654 }
8655 }
8656 }
8657
8658 if (!(ies->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT)) && (ies->authmethods & IAX_AUTH_RSA) && ast_strlen_zero(okey)) {
8659 /* If the only thing available is RSA, and we don't have an outkey, we can't do it... */
8660 ast_log(LOG_WARNING, "Call terminated. RSA authentication requires an outkey\n");
8661 return -1;
8662 }
8663
8664 if (ies->encmethods) {
8665 if (ast_strlen_zero(p->secret) &&
8667 ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8668 return -1;
8669 }
8670 /* Don't even THINK about trying to encrypt or decrypt anything if we don't have valid keys, for some reason... */
8671 /* If either of these happens, it's our fault, not the user's. But we should abort rather than crash. */
8675 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8676 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8677 return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8678 }
8679 if (!res) {
8680 struct ast_datastore *variablestore;
8681 struct ast_variable *var, *prev = NULL;
8682 AST_LIST_HEAD(, ast_var_t) *varlist;
8683 varlist = ast_calloc(1, sizeof(*varlist));
8685 if (variablestore && varlist && p->owner) {
8686 variablestore->data = varlist;
8687 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8688 AST_LIST_HEAD_INIT(varlist);
8689 for (var = ies->vars; var; var = var->next) {
8690 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8691 if (prev)
8692 ast_free(prev);
8693 prev = var;
8694 if (!newvar) {
8695 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8696 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8697 } else {
8698 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8699 }
8700 }
8701 if (prev)
8702 ast_free(prev);
8703 ies->vars = NULL;
8704 ast_channel_datastore_add(p->owner, variablestore);
8705 } else {
8706 if (p->owner)
8707 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8708 if (variablestore)
8709 ast_datastore_free(variablestore);
8710 if (varlist)
8711 ast_free(varlist);
8712 }
8713 }
8714
8715 if (!res)
8716 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8717 return res;
8718}
8719
8720static int iax2_do_register(struct iax2_registry *reg);
8721
8722static void __iax2_do_register_s(const void *data)
8723{
8724 struct iax2_registry *reg = (struct iax2_registry *)data;
8725
8726 if (ast_sockaddr_isnull(&reg->addr)) {
8727 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8728 ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8729 if (!ast_sockaddr_port(&reg->addr)) {
8730 ast_sockaddr_set_port(&reg->addr, reg->port);
8731 } else {
8732 reg->port = ast_sockaddr_port(&reg->addr);
8733 }
8734 }
8735
8736 reg->expire = -1;
8737 iax2_do_register(reg);
8738}
8739
8740static int iax2_do_register_s(const void *data)
8741{
8742#ifdef SCHED_MULTITHREADED
8744#endif
8746 return 0;
8747}
8748
8749static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8750{
8751 int newcall = 0;
8752 struct iax_ie_data ied;
8753 struct ast_sockaddr new = { {0,} };
8754
8755 memset(&ied, 0, sizeof(ied));
8756 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8757 ast_sockaddr_copy(&new, &ies->apparent_addr);
8758 }
8759 if (ies->callno) {
8760 newcall = ies->callno;
8761 }
8762 if (!newcall || ast_sockaddr_isnull(&new)) {
8763 ast_log(LOG_WARNING, "Invalid transfer request\n");
8764 return -1;
8765 }
8766 pvt->transfercallno = newcall;
8767 ast_sockaddr_copy(&pvt->transfer, &new);
8768 pvt->transferid = ies->transferid;
8769 /* only store by transfercallno if this is a new transfer,
8770 * just in case we get a duplicate TXREQ */
8771 if (pvt->transferring == TRANSFER_NONE) {
8773 }
8775
8776 if (ies->transferid) {
8778 }
8780 return 0;
8781}
8782
8783static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8784{
8785 char exten[256] = "";
8786 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8787 struct iax2_dpcache *dp = NULL;
8788
8789 if (ies->called_number)
8790 ast_copy_string(exten, ies->called_number, sizeof(exten));
8791
8792 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8794 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8796 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8798
8799 if (ies->refresh)
8800 expiry = ies->refresh;
8803
8806 if (strcmp(dp->exten, exten))
8807 continue;
8809 dp->callno = 0;
8810 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8811 if (dp->flags & CACHE_FLAG_PENDING) {
8812 dp->flags &= ~CACHE_FLAG_PENDING;
8813 dp->flags |= status;
8814 dp->flags |= matchmore;
8815 }
8816 /* Wake up waiters */
8817 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8818 if (dp->waiters[x] > -1) {
8819 if (write(dp->waiters[x], "asdf", 4) < 0) {
8820 }
8821 }
8822 }
8823 }
8826
8827 return 0;
8828}
8829
8830static int complete_transfer(int callno, struct iax_ies *ies)
8831{
8832 int peercallno = 0;
8833 struct chan_iax2_pvt *pvt = iaxs[callno];
8834 struct iax_frame *cur;
8835 jb_frame frame;
8836
8837 if (ies->callno)
8838 peercallno = ies->callno;
8839
8840 if (peercallno < 1) {
8841 ast_log(LOG_WARNING, "Invalid transfer request\n");
8842 return -1;
8843 }
8845 /* since a transfer has taken place, the address will change.
8846 * This must be accounted for in the peercnts table. Remove
8847 * the old address and add the new one */
8849 peercnt_add(&pvt->transfer);
8850 /* now copy over the new address */
8851 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8852 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8853 /* Reset sequence numbers */
8854 pvt->oseqno = 0;
8855 pvt->rseqno = 0;
8856 pvt->iseqno = 0;
8857 pvt->aseqno = 0;
8858
8859 if (pvt->peercallno) {
8861 }
8862 pvt->peercallno = peercallno;
8863 /*this is where the transferring call switches hash tables */
8866 pvt->svoiceformat = -1;
8867 pvt->voiceformat = 0;
8868 pvt->svideoformat = -1;
8869 pvt->videoformat = 0;
8870 pvt->transfercallno = 0;
8871 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8872 memset(&pvt->offset, 0, sizeof(pvt->offset));
8873 /* reset jitterbuffer */
8874 while(jb_getall(pvt->jb,&frame) == JB_OK)
8875 iax2_frame_free(frame.data);
8876 jb_reset(pvt->jb);
8877 pvt->lag = 0;
8878 pvt->last = 0;
8879 pvt->lastsent = 0;
8880 pvt->nextpred = 0;
8883 /* We must cancel any packets that would have been transmitted
8884 because now we're talking to someone new. It's okay, they
8885 were transmitted to someone that didn't care anyway. */
8886 cur->retries = -1;
8887 }
8888 return 0;
8889}
8890
8891static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
8892{
8893 ast_system_publish_registry("IAX2", username, domain, status, cause);
8894}
8895
8896/*! \brief Acknowledgment received for OUR registration */
8897static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
8898{
8899 struct iax2_registry *reg;
8900 /* Start pessimistic */
8901 char peer[256] = "";
8902 char msgstatus[60];
8903 int refresh = 60;
8904 char ourip[256] = "<Unspecified>";
8905 struct ast_sockaddr oldus;
8906 struct ast_sockaddr us;
8907 int oldmsgs;
8908
8909 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8910 ast_sockaddr_copy(&us, &ies->apparent_addr);
8911 }
8912 if (ies->username) {
8913 ast_copy_string(peer, ies->username, sizeof(peer));
8914 }
8915 if (ies->refresh) {
8916 refresh = ies->refresh;
8917 }
8918 if (ies->calling_number) {
8919 /* We don't do anything with it really, but maybe we should */
8920 }
8921 reg = iaxs[callno]->reg;
8922 if (!reg) {
8923 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8924 return -1;
8925 }
8926 ast_sockaddr_copy(&oldus, &reg->us);
8927 oldmsgs = reg->messages;
8928 if (ast_sockaddr_cmp(&reg->addr, addr)) {
8929 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_sockaddr_stringify(addr));
8930 return -1;
8931 }
8932 ast_sockaddr_copy(&reg->us, &us);
8933 if (ies->msgcount >= 0) {
8934 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8935 }
8936 /* always refresh the registration at the interval requested by the server
8937 we are registering to
8938 */
8939 reg->refresh = refresh;
8941 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8942 if (ast_sockaddr_cmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8943
8944 if (reg->messages > 255) {
8945 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8946 } else if (reg->messages > 1) {
8947 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8948 } else if (reg->messages > 0) {
8949 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8950 } else {
8951 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8952 }
8953
8954 snprintf(ourip, sizeof(ourip), "%s", ast_sockaddr_stringify(&reg->us));
8955
8956 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_sockaddr_stringify(addr), ourip, msgstatus);
8957 iax2_publish_registry(reg->username, ast_sockaddr_stringify(addr), "Registered", NULL);
8958 }
8960 return 0;
8961}
8962
8963static int iax2_append_register(const char *hostname, const char *username,
8964 const char *secret, const char *porta)
8965{
8966 struct iax2_registry *reg;
8967
8968 if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
8969 return -1;
8970 }
8971
8972 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8973 if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8974 ast_free(reg);
8975 return -1;
8976 }
8977
8978 ast_copy_string(reg->username, username, sizeof(reg->username));
8979 strcpy(reg->hostname, hostname); /* Note: This is safe */
8980
8981 if (secret) {
8982 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8983 }
8984
8985 reg->expire = -1;
8987
8988 reg->port = ast_sockaddr_port(&reg->addr);
8989
8990 if (!porta && !reg->port) {
8991 reg->port = IAX_DEFAULT_PORTNO;
8992 } else if (porta) {
8993 sscanf(porta, "%5d", &reg->port);
8994 }
8995
8996 ast_sockaddr_set_port(&reg->addr, reg->port);
8997
9001
9002 return 0;
9003}
9004
9005static int iax2_register(const char *value, int lineno)
9006{
9007 char copy[256];
9008 char *username, *hostname, *secret;
9009 char *porta;
9010 char *stringp=NULL;
9011
9012 if (!value)
9013 return -1;
9014
9015 ast_copy_string(copy, value, sizeof(copy));
9016 stringp = copy;
9017 username = strsep(&stringp, "@");
9018 hostname = strsep(&stringp, "@");
9019
9020 if (!hostname) {
9021 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
9022 return -1;
9023 }
9024
9025 stringp = username;
9026 username = strsep(&stringp, ":");
9027 secret = strsep(&stringp, ":");
9028 stringp = hostname;
9029 hostname = strsep(&stringp, ":");
9030 porta = strsep(&stringp, ":");
9031
9032 if (porta && !atoi(porta)) {
9033 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
9034 return -1;
9035 }
9036
9038}
9039
9040
9041static void register_peer_exten(struct iax2_peer *peer, int onoff)
9042{
9043 char multi[256];
9044 char *stringp, *ext;
9046 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
9047 stringp = multi;
9048 while((ext = strsep(&stringp, "&"))) {
9049 if (onoff) {
9052 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
9053 } else
9055 }
9056 }
9057}
9058static void prune_peers(void);
9059
9060static void unlink_peer(struct iax2_peer *peer)
9061{
9062 if (peer->expire > -1) {
9063 if (!AST_SCHED_DEL(sched, peer->expire)) {
9064 peer->expire = -1;
9065 peer_unref(peer);
9066 }
9067 }
9068
9069 if (peer->pokeexpire > -1) {
9070 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
9071 peer->pokeexpire = -1;
9072 peer_unref(peer);
9073 }
9074 }
9075
9076 ao2_unlink(peers, peer);
9077}
9078
9079static void __expire_registry(const void *data)
9080{
9081 struct iax2_peer *peer = (struct iax2_peer *) data;
9082 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9083
9084 if (!peer)
9085 return;
9086 if (peer->expire == -1) {
9087 /* Removed already (possibly through CLI), ignore */
9088 return;
9089 }
9090
9091 peer->expire = -1;
9092
9093 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
9095 realtime_update_peer(peer->name, &peer->addr, 0);
9097 blob = ast_json_pack("{s: s, s: s}",
9098 "peer_status", "Unregistered",
9099 "cause", "Expired");
9101 /* modify entry in peercnts table as _not_ registered */
9102 peercnt_modify((unsigned char) 0, 0, &peer->addr);
9103 /* Reset the address */
9104 ast_sockaddr_setnull(&peer->addr);
9105 /* Reset expiry value */
9106 peer->expiry = min_reg_expire;
9107 if (!ast_test_flag64(peer, IAX_TEMPONLY))
9108 ast_db_del("IAX/Registry", peer->name);
9109 register_peer_exten(peer, 0);
9110 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
9111 if (iax2_regfunk)
9112 iax2_regfunk(peer->name, 0);
9113
9115 unlink_peer(peer);
9116
9117 peer_unref(peer);
9118}
9119
9120static int expire_registry(const void *data)
9121{
9122#ifdef SCHED_MULTITHREADED
9124#endif
9125 __expire_registry(data);
9126 return 0;
9127}
9128
9129static void reg_source_db(struct iax2_peer *p)
9130{
9131 char data[80];
9132 char *expiry;
9133
9134 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
9135 return;
9136 }
9137
9138 expiry = strrchr(data, ':');
9139 if (!expiry) {
9140 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
9141 return;
9142 }
9143 *expiry++ = '\0';
9144
9145 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
9146 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
9147 return;
9148 }
9149
9150 p->expiry = atoi(expiry);
9151
9152 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
9154
9155 iax2_poke_peer(p, 0);
9156 if (p->expire > -1) {
9157 if (!AST_SCHED_DEL(sched, p->expire)) {
9158 p->expire = -1;
9159 peer_unref(p);
9160 }
9161 }
9162
9163 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9164
9165 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9166 if (p->expire == -1) {
9167 peer_unref(p);
9168 }
9169
9170 if (iax2_regfunk) {
9171 iax2_regfunk(p->name, 1);
9172 }
9173
9174 register_peer_exten(p, 1);
9175}
9176
9177/*!
9178 * \pre iaxsl[callno] is locked
9179 *
9180 * \note Since this function calls send_command_final(), the pvt struct for
9181 * the given call number may disappear while executing this function.
9182 */
9183static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
9184{
9185
9186 /* Called from IAX thread only, with proper iaxsl lock */
9187 struct iax_ie_data ied = {
9188 .pos = 0,
9189 };
9190 struct iax2_peer *p;
9191 int msgcount;
9192 char data[80];
9193 uint16_t version;
9194 const char *peer_name;
9195 int res = -1;
9196 char *str_addr;
9197
9198 peer_name = ast_strdupa(iaxs[callno]->peer);
9199
9200 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
9202 if (!(p = find_peer(peer_name, 1))) {
9204 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
9205 return -1;
9206 }
9208 if (!iaxs[callno])
9209 goto return_unref;
9210
9212 if (!ast_sockaddr_isnull(addr)) {
9213 time_t nowtime;
9214 time(&nowtime);
9215 realtime_update_peer(peer_name, addr, nowtime);
9216 } else {
9217 realtime_update_peer(peer_name, addr, 0);
9218 }
9219 }
9220
9221 /* treat an unspecified refresh interval as the minimum */
9222 if (!refresh) {
9224 }
9225 if (refresh > max_reg_expire) {
9226 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9229 } else if (refresh < min_reg_expire) {
9230 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9233 } else {
9234 p->expiry = refresh;
9235 }
9236
9237 if (ast_sockaddr_cmp(&p->addr, addr)) {
9238 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9239
9240 if (iax2_regfunk) {
9241 iax2_regfunk(p->name, 1);
9242 }
9243
9244 /* modify entry in peercnts table as _not_ registered */
9245 peercnt_modify((unsigned char) 0, 0, &p->addr);
9246
9247 /* Stash the IP address from which they registered */
9249
9251
9252 snprintf(data, sizeof(data), "%s:%d", ast_sockaddr_stringify(addr), p->expiry);
9253
9255 ast_db_put("IAX/Registry", p->name, data);
9256 ast_verb(3, "Registered IAX2 '%s' (%s) at %s\n",
9257 p->name,
9258 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED",
9261 blob = ast_json_pack("{s: s, s: s, s: i}",
9262 "peer_status", "Registered",
9263 "address", str_addr,
9264 "port", ast_sockaddr_port(addr));
9265 register_peer_exten(p, 1);
9266 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9267 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
9268 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n",
9269 p->name,
9270 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
9272 blob = ast_json_pack("{s: s}",
9273 "peer_status", "Unregistered");
9274 register_peer_exten(p, 0);
9275 ast_db_del("IAX/Registry", p->name);
9276 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9277 }
9278
9280
9281 /* Update the host */
9282 /* Verify that the host is really there */
9284 }
9285
9286 /* modify entry in peercnts table as registered */
9287 if (p->maxcallno) {
9288 peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
9289 }
9290
9291 /* Make sure our call still exists, an INVAL at the right point may make it go away */
9292 if (!iaxs[callno]) {
9293 res = -1;
9294 goto return_unref;
9295 }
9296
9297 /* Store socket fd */
9298 p->sockfd = fd;
9299 /* Setup the expiry */
9300 if (p->expire > -1) {
9301 if (!AST_SCHED_DEL(sched, p->expire)) {
9302 p->expire = -1;
9303 peer_unref(p);
9304 }
9305 }
9306
9307 if (p->expiry && !ast_sockaddr_isnull(addr)) {
9308 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9309 if (p->expire == -1)
9310 peer_unref(p);
9311 }
9314 if (!ast_sockaddr_isnull(addr)) {
9315 struct ast_sockaddr peer_addr;
9316
9317 ast_sockaddr_copy(&peer_addr, &p->addr);
9318
9320 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
9321 if (!ast_strlen_zero(p->mailbox)) {
9322 int new, old;
9323 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
9324
9326 if (msg) {
9327 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
9328 new = mwi_state->new_msgs;
9329 old = mwi_state->old_msgs;
9330 } else { /* Fall back on checking the mailbox directly */
9331 ast_app_inboxcount(p->mailbox, &new, &old);
9332 }
9333
9334 if (new > 255) {
9335 new = 255;
9336 }
9337 if (old > 255) {
9338 old = 255;
9339 }
9340 msgcount = (old << 8) | new;
9341
9342 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
9343 }
9347 }
9348 }
9349 if (iax_firmware_get_version(devtype, &version)) {
9351 }
9352
9353 res = 0;
9354
9355return_unref:
9356 peer_unref(p);
9357
9358 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9359}
9360
9361static int registry_authrequest(int callno)
9362{
9363 struct iax_ie_data ied;
9364 struct iax2_peer *p;
9365 char challenge[10];
9366 const char *peer_name;
9367 int sentauthmethod;
9368
9369 peer_name = ast_strdupa(iaxs[callno]->peer);
9370
9371 /* SLD: third call to find_peer in registration */
9373 if ((p = find_peer(peer_name, 1))) {
9375 }
9376
9378 if (!iaxs[callno])
9379 goto return_unref;
9380
9381 memset(&ied, 0, sizeof(ied));
9382 /* The selection of which delayed reject is sent may leak information,
9383 * if it sets a static response. For example, if a host is known to only
9384 * use MD5 authentication, then an RSA response would indicate that the
9385 * peer does not exist, and vice-versa.
9386 * Therefore, we use whatever the last peer used (which may vary over the
9387 * course of a server, which should leak minimal information). */
9388 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : IAX_AUTH_MD5;
9389 if (!p) {
9390 iaxs[callno]->authmethods = sentauthmethod;
9391 }
9392 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9393 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9394 /* Build the challenge */
9395 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9398 }
9399 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9400
9401return_unref:
9402 if (p) {
9403 peer_unref(p);
9404 }
9405
9406 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9407}
9408
9409static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
9410{
9411 struct iax2_registry *reg;
9412 /* Start pessimistic */
9413 struct iax_ie_data ied;
9414 char peer[256] = "";
9415 char challenge[256] = "";
9416 int res;
9417 int authmethods = 0;
9418 if (ies->authmethods)
9419 authmethods = ies->authmethods;
9420 if (ies->username)
9421 ast_copy_string(peer, ies->username, sizeof(peer));
9422 if (ies->challenge)
9424 memset(&ied, 0, sizeof(ied));
9425 reg = iaxs[callno]->reg;
9426 if (reg) {
9427
9428 if (ast_sockaddr_cmp(&reg->addr, addr)) {
9429 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_sockaddr_stringify(addr));
9430 return -1;
9431 }
9432 if (ast_strlen_zero(reg->secret)) {
9433 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9435 return -1;
9436 }
9439 if (reg->secret[0] == '[') {
9440 char tmpkey[256];
9441 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9442 tmpkey[strlen(tmpkey) - 1] = '\0';
9443 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, addr, NULL);
9444 } else
9445 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, addr, NULL);
9446 if (!res) {
9448 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9449 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9450 } else
9451 return -1;
9452 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
9453 } else
9454 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9455 return -1;
9456}
9457
9458static void stop_stuff(int callno)
9459{
9460 iax2_destroy_helper(iaxs[callno]);
9461}
9462
9463static void __auth_reject(const void *nothing)
9464{
9465 /* Called from IAX thread only, without iaxs lock */
9466 int callno = (int)(long)(nothing);
9467 struct iax_ie_data ied;
9468 ast_mutex_lock(&iaxsl[callno]);
9469 if (iaxs[callno]) {
9470 memset(&ied, 0, sizeof(ied));
9471 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9472 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9474 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9475 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9477 }
9478 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9479 }
9480 ast_mutex_unlock(&iaxsl[callno]);
9481}
9482
9483static int auth_reject(const void *data)
9484{
9485 int callno = (int)(long)(data);
9486 ast_mutex_lock(&iaxsl[callno]);
9487 if (iaxs[callno])
9488 iaxs[callno]->authid = -1;
9489 ast_mutex_unlock(&iaxsl[callno]);
9490#ifdef SCHED_MULTITHREADED
9491 if (schedule_action(__auth_reject, data))
9492#endif
9493 __auth_reject(data);
9494 return 0;
9495}
9496
9497static int auth_fail(int callno, int failcode)
9498{
9499 /* Schedule sending the authentication failure in one second, to prevent
9500 guessing */
9501 if (iaxs[callno]) {
9502 iaxs[callno]->authfail = failcode;
9503 if (delayreject) {
9504 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9505 sched, 1000, auth_reject, (void *)(long)callno);
9506 } else
9507 auth_reject((void *)(long)callno);
9508 }
9509 return 0;
9510}
9511
9512static void __auto_hangup(const void *nothing)
9513{
9514 /* Called from IAX thread only, without iaxs lock */
9515 int callno = (int)(long)(nothing);
9516 struct iax_ie_data ied;
9517 ast_mutex_lock(&iaxsl[callno]);
9518 if (iaxs[callno]) {
9519 memset(&ied, 0, sizeof(ied));
9520 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9522 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9523 }
9524 ast_mutex_unlock(&iaxsl[callno]);
9525}
9526
9527static int auto_hangup(const void *data)
9528{
9529 int callno = (int)(long)(data);
9530 ast_mutex_lock(&iaxsl[callno]);
9531 if (iaxs[callno]) {
9532 iaxs[callno]->autoid = -1;
9533 }
9534 ast_mutex_unlock(&iaxsl[callno]);
9535#ifdef SCHED_MULTITHREADED
9536 if (schedule_action(__auto_hangup, data))
9537#endif
9538 __auto_hangup(data);
9539 return 0;
9540}
9541
9542static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9543{
9544 struct iax_ie_data ied;
9545 /* Auto-hangup with 30 seconds of inactivity */
9546 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9547 sched, 30000, auto_hangup, (void *)(long)callno);
9548 memset(&ied, 0, sizeof(ied));
9550 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9552}
9553
9554static int iax2_vnak(int callno)
9555{
9556 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9557}
9558
9559static void vnak_retransmit(int callno, int last)
9560{
9561 struct iax_frame *f;
9562
9564 /* Send a copy immediately */
9565 if (((unsigned char) (f->oseqno - last) < 128) &&
9566 (f->retries >= 0)) {
9567 send_packet(f);
9568 }
9569 }
9570}
9571
9572static void __iax2_poke_peer_s(const void *data)
9573{
9574 struct iax2_peer *peer = (struct iax2_peer *)data;
9575 iax2_poke_peer(peer, 0);
9576 peer_unref(peer);
9577}
9578
9579static int iax2_poke_peer_s(const void *data)
9580{
9581 struct iax2_peer *peer = (struct iax2_peer *)data;
9582 peer->pokeexpire = -1;
9583#ifdef SCHED_MULTITHREADED
9585#endif
9586 __iax2_poke_peer_s(data);
9587 return 0;
9588}
9589
9590static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9591{
9592 int res = 0;
9593 struct iax_frame *fr;
9594 struct ast_iax2_meta_hdr *meta;
9595 struct ast_iax2_meta_trunk_hdr *mth;
9596 int calls = 0;
9597
9598 /* Point to frame */
9599 fr = (struct iax_frame *)tpeer->trunkdata;
9600 /* Point to meta data */
9601 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9602 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9603 if (tpeer->trunkdatalen) {
9604 /* We're actually sending a frame, so fill the meta trunk header and meta header */
9605 meta->zeros = 0;
9606 meta->metacmd = IAX_META_TRUNK;
9608 meta->cmddata = IAX_META_TRUNK_MINI;
9609 else
9610 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
9611 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9612 /* And the rest of the ast_iax2 header */
9614 fr->retrans = -1;
9615 fr->transfer = 0;
9616 /* Any appropriate call will do */
9617 fr->data = fr->afdata;
9618 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9619 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9620 calls = tpeer->calls;
9621#if 0
9622 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));
9623#endif
9624 /* Reset transmit trunk side data */
9625 tpeer->trunkdatalen = 0;
9626 tpeer->calls = 0;
9627 }
9628 if (res < 0)
9629 return res;
9630 return calls;
9631}
9632
9633static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9634{
9635 /* Drop when trunk is about 5 seconds idle */
9636 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9637 return 1;
9638 return 0;
9639}
9640
9641static int timing_read(int *id, int fd, short events, void *cbdata)
9642{
9643 int res, processed = 0, totalcalls = 0;
9644 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9645 struct timeval now = ast_tvnow();
9646
9647 if (iaxtrunkdebug) {
9648 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9649 }
9650
9651 if (timer) {
9652 if (ast_timer_ack(timer, 1) < 0) {
9653 ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9654 return 0;
9655 }
9656 }
9657
9658 /* For each peer that supports trunking... */
9660 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9661 processed++;
9662 res = 0;
9663 ast_mutex_lock(&tpeer->lock);
9664 /* We can drop a single tpeer per pass. That makes all this logic
9665 substantially easier */
9666 if (!drop && iax2_trunk_expired(tpeer, &now)) {
9667 /* Take it out of the list, but don't free it yet, because it
9668 could be in use */
9670 drop = tpeer;
9671 } else {
9672 res = send_trunk(tpeer, &now);
9673 trunk_timed++;
9674 if (iaxtrunkdebug) {
9675 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",
9677 res,
9678 (res != 1) ? "s" : "",
9679 tpeer->trunkdatalen,
9680 tpeer->trunkdataalloc);
9681 }
9682 }
9683 totalcalls += res;
9684 res = 0;
9685 ast_mutex_unlock(&tpeer->lock);
9686 }
9689
9690 if (drop) {
9691 ast_mutex_lock(&drop->lock);
9692 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9693 because by the time they could get tpeerlock, we've already grabbed it */
9694 ast_debug(1, "Dropping unused iax2 trunk peer '%s'\n", ast_sockaddr_stringify(&drop->addr));
9695 if (drop->trunkdata) {
9696 ast_free(drop->trunkdata);
9697 drop->trunkdata = NULL;
9698 }
9699 ast_mutex_unlock(&drop->lock);
9700 ast_mutex_destroy(&drop->lock);
9701 ast_free(drop);
9702 }
9703
9704 if (iaxtrunkdebug) {
9705 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9706 }
9707 iaxtrunkdebug = 0;
9708
9709 return 1;
9710}
9711
9717};
9718
9719static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9720{
9721 unsigned short dpstatus = 0;
9722 struct iax_ie_data ied1;
9723 int mm;
9724
9725 memset(&ied1, 0, sizeof(ied1));
9726 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9727 /* Must be started */
9728 if (ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9729 dpstatus = IAX_DPSTATUS_EXISTS;
9730 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9731 dpstatus = IAX_DPSTATUS_CANEXIST;
9732 } else {
9733 dpstatus = IAX_DPSTATUS_NONEXISTENT;
9734 }
9735 if (ast_ignore_pattern(context, callednum))
9736 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9737 if (mm)
9738 dpstatus |= IAX_DPSTATUS_MATCHMORE;
9739 if (!skiplock)
9740 ast_mutex_lock(&iaxsl[callno]);
9741 if (iaxs[callno]) {
9742 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9743 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9745 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9746 }
9747 if (!skiplock)
9748 ast_mutex_unlock(&iaxsl[callno]);
9749}
9750
9751static void *dp_lookup_thread(void *data)
9752{
9753 /* Look up for dpreq */
9754 struct dpreq_data *dpr = data;
9755 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9756 if (dpr->callerid)
9757 ast_free(dpr->callerid);
9758 ast_free(dpr);
9759 return NULL;
9760}
9761
9762static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9763{
9764 pthread_t newthread;
9765 struct dpreq_data *dpr;
9766
9767 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9768 return;
9769
9770 dpr->callno = callno;
9771 ast_copy_string(dpr->context, context, sizeof(dpr->context));
9772 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9773 if (callerid)
9775 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9776 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9777 }
9778}
9779
9780static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
9781{
9782 unsigned int ourver;
9783 char rsi[80];
9784 snprintf(rsi, sizeof(rsi), "si-%s", si);
9785 if (iax_provision_version(&ourver, rsi, 1))
9786 return 0;
9787 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9788 if (ourver != ver)
9789 iax2_provision(addr, sockfd, NULL, rsi, 1);
9790 return 0;
9791}
9792
9793static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9794{
9795 jb_info stats;
9796 jb_getinfo(pvt->jb, &stats);
9797
9798 memset(iep, 0, sizeof(*iep));
9799
9801 if(stats.frames_in == 0) stats.frames_in = 1;
9802 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9804 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9807}
9808
9809static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9810{
9811 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9812 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9813 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9814 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9815 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9816 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9817 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9818}
9819
9820static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9821{
9822 int i;
9823 unsigned int length, offset = 0;
9824 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9825
9826 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9827 length = ies->ospblocklength[i];
9828 if (length != 0) {
9829 if (length > IAX_MAX_OSPBLOCK_SIZE) {
9830 /* OSP token block length wrong, clear buffer */
9831 offset = 0;
9832 break;
9833 } else {
9834 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9835 offset += length;
9836 }
9837 } else {
9838 break;
9839 }
9840 }
9841 *(full_osptoken + offset) = '\0';
9842 if (strlen(full_osptoken) != offset) {
9843 /* OSP token length wrong, clear buffer */
9844 *full_osptoken = '\0';
9845 }
9846
9847 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9848}
9849
9850static void log_jitterstats(unsigned short callno)
9851{
9852 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9853 jb_info jbinfo;
9854
9856 if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
9858 jb_getinfo(iaxs[callno]->jb, &jbinfo);
9859 localjitter = jbinfo.jitter;
9860 localdelay = jbinfo.current - jbinfo.min;
9861 locallost = jbinfo.frames_lost;
9862 locallosspct = jbinfo.losspct/1000;
9863 localdropped = jbinfo.frames_dropped;
9864 localooo = jbinfo.frames_ooo;
9865 localpackets = jbinfo.frames_in;
9866 }
9867 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",
9868 ast_channel_name(iaxs[callno]->owner),
9869 iaxs[callno]->pingtime,
9870 localjitter,
9871 localdelay,
9872 locallost,
9873 locallosspct,
9874 localdropped,
9875 localooo,
9876 localpackets,
9877 iaxs[callno]->remote_rr.jitter,
9884 }
9886}
9887
9888static int socket_process(struct iax2_thread *thread);
9889
9890/*!
9891 * \brief Handle any deferred full frames for this thread
9892 */
9894{
9895 struct iax2_pkt_buf *pkt_buf;
9896
9897 ast_mutex_lock(&thread->lock);
9898
9899 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9900 ast_mutex_unlock(&thread->lock);
9901
9902 thread->buf = pkt_buf->buf;
9903 thread->buf_len = pkt_buf->len;
9904 thread->buf_size = pkt_buf->len + 1;
9905
9907
9908 thread->buf = NULL;
9909 ast_free(pkt_buf);
9910
9911 ast_mutex_lock(&thread->lock);
9912 }
9913
9914 ast_mutex_unlock(&thread->lock);
9915}
9916
9917/*!
9918 * \brief Queue the last read full frame for processing by a certain thread
9919 *
9920 * If there are already any full frames queued, they are sorted
9921 * by sequence number.
9922 */
9923static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9924{
9925 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9926 struct ast_iax2_full_hdr *fh, *cur_fh;
9927
9928 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9929 return;
9930
9931 pkt_buf->len = from_here->buf_len;
9932 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9933
9934 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9935 ast_mutex_lock(&to_here->lock);
9936 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9937 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9938 if (fh->oseqno < cur_fh->oseqno) {
9939 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9940 break;
9941 }
9942 }
9944
9945 if (!cur_pkt_buf)
9946 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9947
9948 to_here->iostate = IAX_IOSTATE_READY;
9949 ast_cond_signal(&to_here->cond);
9950
9951 ast_mutex_unlock(&to_here->lock);
9952}
9953
9954static int socket_read(int *id, int fd, short events, void *cbdata)
9955{
9956 struct iax2_thread *thread;
9957 time_t t;
9958 static time_t last_errtime = 0;
9959 struct ast_iax2_full_hdr *fh;
9960
9961 if (!(thread = find_idle_thread())) {
9962 time(&t);
9963 if (t != last_errtime) {
9964 last_errtime = t;
9965 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9966 }
9967 usleep(1);
9968 return 1;
9969 }
9970
9971 thread->iofd = fd;
9972 thread->buf_len = ast_recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, &thread->ioaddr);
9973 thread->buf_size = sizeof(thread->readbuf);
9974 thread->buf = thread->readbuf;
9975 if (thread->buf_len < 0) {
9976 if (errno != ECONNREFUSED && errno != EAGAIN)
9977 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9978 handle_error();
9979 thread->iostate = IAX_IOSTATE_IDLE;
9980 signal_condition(&thread->lock, &thread->cond);
9981 return 1;
9982 }
9983 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9984 thread->iostate = IAX_IOSTATE_IDLE;
9985 signal_condition(&thread->lock, &thread->cond);
9986 return 1;
9987 }
9988
9989 /* Determine if this frame is a full frame; if so, and any thread is currently
9990 processing a full frame for the same callno from this peer, then drop this
9991 frame (and the peer will retransmit it) */
9992 fh = (struct ast_iax2_full_hdr *) thread->buf;
9993 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
9994 struct iax2_thread *cur = NULL;
9995 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
9996
9999 if ((cur->ffinfo.callno == callno) &&
10000 !ast_sockaddr_cmp_addr(&cur->ffinfo.addr, &thread->ioaddr))
10001 break;
10002 }
10003 if (cur) {
10004 /* we found another thread processing a full frame for this call,
10005 so queue it up for processing later. */
10008 thread->iostate = IAX_IOSTATE_IDLE;
10009 signal_condition(&thread->lock, &thread->cond);
10010 return 1;
10011 } else {
10012 /* this thread is going to process this frame, so mark it */
10013 thread->ffinfo.callno = callno;
10014 ast_sockaddr_copy(&thread->ffinfo.addr, &thread->ioaddr);
10015 thread->ffinfo.type = fh->type;
10016 thread->ffinfo.csub = fh->csub;
10018 }
10020 }
10021
10022 /* Mark as ready and send on its way */
10023 thread->iostate = IAX_IOSTATE_READY;
10024#ifdef DEBUG_SCHED_MULTITHREAD
10025 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
10026#endif
10027 signal_condition(&thread->lock, &thread->cond);
10028
10029 return 1;
10030}
10031
10032static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd,
10033 struct iax_frame *fr)
10034{
10035 unsigned char metatype;
10036 struct ast_iax2_meta_trunk_mini *mtm;
10037 struct ast_iax2_meta_trunk_hdr *mth;
10038 struct ast_iax2_meta_trunk_entry *mte;
10039 struct iax2_trunk_peer *tpeer;
10040 unsigned int ts;
10041 void *ptr;
10042 struct timeval rxtrunktime;
10043 struct ast_frame f = { 0, };
10044
10045 if (packet_len < sizeof(*meta)) {
10046 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a meta frame but is too short\n",
10048 return 1;
10049 }
10050
10051 if (meta->metacmd != IAX_META_TRUNK)
10052 return 1;
10053
10054 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
10055 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
10056 (int) (sizeof(*meta) + sizeof(*mth)));
10057 return 1;
10058 }
10059 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
10060 ts = ntohl(mth->ts);
10061 metatype = meta->cmddata;
10062 packet_len -= (sizeof(*meta) + sizeof(*mth));
10063 ptr = mth->data;
10064 tpeer = find_tpeer(addr, sockfd);
10065 if (!tpeer) {
10066 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s': No matching peer\n",
10068 return 1;
10069 }
10070 tpeer->trunkact = ast_tvnow();
10071 if (!ts || ast_tvzero(tpeer->rxtrunktime))
10072 tpeer->rxtrunktime = tpeer->trunkact;
10073 rxtrunktime = tpeer->rxtrunktime;
10074 ast_mutex_unlock(&tpeer->lock);
10075 while (packet_len >= sizeof(*mte)) {
10076 /* Process channels */
10077 unsigned short callno, trunked_ts, len;
10078
10079 if (metatype == IAX_META_TRUNK_MINI) {
10080 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
10081 ptr += sizeof(*mtm);
10082 packet_len -= sizeof(*mtm);
10083 len = ntohs(mtm->len);
10084 callno = ntohs(mtm->mini.callno);
10085 trunked_ts = ntohs(mtm->mini.ts);
10086 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
10087 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
10088 ptr += sizeof(*mte);
10089 packet_len -= sizeof(*mte);
10090 len = ntohs(mte->len);
10091 callno = ntohs(mte->callno);
10092 trunked_ts = 0;
10093 } else {
10094 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s': dropping\n", ast_sockaddr_stringify(addr));
10095 break;
10096 }
10097 /* Stop if we don't have enough data */
10098 if (len > packet_len)
10099 break;
10100 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, addr, NEW_PREVENT, sockfd, 0);
10101 if (!fr->callno)
10102 continue;
10103
10104 /* If it's a valid call, deliver the contents. If not, we
10105 drop it, since we don't have a scallno to use for an INVAL */
10106 /* Process as a mini frame */
10107 memset(&f, 0, sizeof(f));
10109 if (!iaxs[fr->callno]) {
10110 /* drop it */
10111 } else if (iaxs[fr->callno]->voiceformat == 0) {
10112 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
10113 iax2_vnak(fr->callno);
10115 iaxs[fr->callno]->voiceformat))) {
10116 f.datalen = len;
10117 if (f.datalen >= 0) {
10118 if (f.datalen)
10119 f.data.ptr = ptr;
10120 else
10121 f.data.ptr = NULL;
10122 if (trunked_ts)
10123 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
10124 else
10125 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
10126 /* Don't pass any packets until we're started */
10128 struct iax_frame *duped_fr;
10129
10130 /* Common things */
10131 f.src = "IAX2";
10132 f.mallocd = 0;
10133 f.offset = 0;
10134 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
10136 else
10137 f.samples = 0;
10138 fr->outoforder = 0;
10139 iax_frame_wrap(fr, &f);
10140 duped_fr = iaxfrdup2(fr);
10141 if (duped_fr)
10142 schedule_delivery(duped_fr, 1, 1, &fr->ts);
10143 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
10144 iaxs[fr->callno]->last = fr->ts;
10145 }
10146 } else {
10147 ast_log(LOG_WARNING, "Datalen < 0?\n");
10148 }
10149 }
10151 ptr += len;
10152 packet_len -= len;
10153 }
10154
10155 return 1;
10156}
10157
10158static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
10159{
10160 struct ast_datastore *variablestore;
10161 AST_LIST_HEAD(, ast_var_t) *varlist;
10162 struct ast_var_t *var;
10163
10164 if (!chan) {
10165 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10166 return -1;
10167 }
10168
10170 if (!variablestore) {
10171 *buf = '\0';
10172 return 0;
10173 }
10174 varlist = variablestore->data;
10175
10176 AST_LIST_LOCK(varlist);
10177 AST_LIST_TRAVERSE(varlist, var, entries) {
10178 if (strcmp(var->name, data) == 0) {
10179 ast_copy_string(buf, var->value, len);
10180 break;
10181 }
10182 }
10183 AST_LIST_UNLOCK(varlist);
10184 return 0;
10185}
10186
10187static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10188{
10189 struct ast_datastore *variablestore;
10190 AST_LIST_HEAD(, ast_var_t) *varlist;
10191 struct ast_var_t *var;
10192
10193 if (!chan) {
10194 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10195 return -1;
10196 }
10197
10199 if (!variablestore) {
10201 if (!variablestore) {
10202 ast_log(LOG_ERROR, "Memory allocation error\n");
10203 return -1;
10204 }
10205 varlist = ast_calloc(1, sizeof(*varlist));
10206 if (!varlist) {
10207 ast_datastore_free(variablestore);
10208 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10209 return -1;
10210 }
10211
10212 AST_LIST_HEAD_INIT(varlist);
10213 variablestore->data = varlist;
10214 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10215 ast_channel_datastore_add(chan, variablestore);
10216 } else
10217 varlist = variablestore->data;
10218
10219 AST_LIST_LOCK(varlist);
10221 if (strcmp(var->name, data) == 0) {
10224 break;
10225 }
10226 }
10228 var = ast_var_assign(data, value);
10229 if (var)
10230 AST_LIST_INSERT_TAIL(varlist, var, entries);
10231 else
10232 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10233 AST_LIST_UNLOCK(varlist);
10234 return 0;
10235}
10236
10238 .name = "IAXVAR",
10239 .read = acf_iaxvar_read,
10240 .write = acf_iaxvar_write,
10241};
10242
10243static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10244{
10245 iax2_lock_owner(callno);
10246 if (iaxs[callno] && iaxs[callno]->owner) {
10247 struct ast_channel *owner;
10248 const char *name;
10249
10250 owner = iaxs[callno]->owner;
10251 if (causecode) {
10252 ast_channel_hangupcause_set(owner, causecode);
10253 }
10255 ast_channel_ref(owner);
10256 ast_channel_unlock(owner);
10257 ast_mutex_unlock(&iaxsl[callno]);
10258 ast_set_hangupsource(owner, name, 0);
10259 ast_channel_unref(owner);
10260 ast_mutex_lock(&iaxsl[callno]);
10261 }
10262}
10263
10265{
10266 struct ast_sockaddr addr;
10267 int res;
10268 int updatehistory=1;
10269 int new = NEW_PREVENT;
10270 int dcallno = 0;
10271 char decrypted = 0;
10272 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10273 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10274 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10275 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10276 struct iax_frame *fr;
10277 struct iax_frame *cur;
10278 struct ast_frame f = { 0, };
10279 struct ast_channel *c = NULL;
10280 struct iax2_dpcache *dp;
10281 struct iax2_peer *peer;
10282 struct iax_ies ies;
10283 struct iax_ie_data ied0, ied1;
10284 iax2_format format;
10285 int fd;
10286 int exists;
10287 int minivid = 0;
10288 char empty[32]=""; /* Safety measure */
10289 struct iax_frame *duped_fr;
10290 char host_pref_buf[128];
10291 char caller_pref_buf[128];
10292 struct iax2_codec_pref pref;
10293 char *using_prefs = "mine";
10294
10295 /* allocate an iax_frame with 4096 bytes of data buffer */
10296 fr = ast_alloca(sizeof(*fr) + 4096);
10297 memset(fr, 0, sizeof(*fr));
10298 fr->afdatalen = 4096; /* From ast_alloca() above */
10299
10300 /* Copy frequently used parameters to the stack */
10301 res = thread->buf_len;
10302 fd = thread->iofd;
10303 ast_sockaddr_copy(&addr, &thread->ioaddr);
10304
10305 if (res < sizeof(*mh)) {
10306 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10307 return 1;
10308 }
10309 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10310 if (res < sizeof(*vh)) {
10311 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a video frame but is too short\n",
10312 ast_sockaddr_stringify(&addr));
10313 return 1;
10314 }
10315
10316 /* This is a video frame, get call number */
10317 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &addr, new, fd, 0);
10318 minivid = 1;
10319 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10320 return socket_process_meta(res, meta, &addr, fd, fr);
10321
10322#ifdef DEBUG_SUPPORT
10323 if (res >= sizeof(*fh))
10324 iax_outputframe(NULL, fh, 1, &addr, res - sizeof(*fh));
10325#endif
10326 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10327 if (res < sizeof(*fh)) {
10328 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a full frame but is too short\n",
10329 ast_sockaddr_stringify(&addr));
10330 return 1;
10331 }
10332
10333 /* Get the destination call number */
10334 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10335
10336
10337 /* check to make sure this full frame isn't encrypted before we attempt
10338 * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10339 * callno is not found here, that just means one hasn't been allocated for
10340 * this connection yet. */
10341 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, NEW_PREVENT, fd, 1))) {
10343 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10344 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10345 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10347 return 1;
10348 }
10349 decrypted = 1;
10350 }
10352 }
10353
10354 /* Retrieve the type and subclass */
10355 f.frametype = fh->type;
10356 if (f.frametype == AST_FRAME_VIDEO) {
10358 if (!f.subclass.format) {
10359 return 1;
10360 }
10361 if ((fh->csub >> 6) & 0x1) {
10362 f.subclass.frame_ending = 1;
10363 }
10364 } else if (f.frametype == AST_FRAME_VOICE) {
10366 if (!f.subclass.format) {
10367 return 1;
10368 }
10369 } else {
10371 }
10372
10373 /* Deal with POKE/PONG without allocating a callno */
10375 /* Reply back with a PONG, but don't care about the result. */
10376 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10377 return 1;
10378 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10379 /* Ignore */
10380 return 1;
10381 }
10382
10383 f.datalen = res - sizeof(*fh);
10384 if (f.datalen) {
10385 if (f.frametype == AST_FRAME_IAX) {
10386 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10387 char subclass[40];
10388 iax_frame_subclass2str(f.subclass.integer, subclass, sizeof(subclass));
10389 ast_log(LOG_WARNING, "Undecodable %s frame received from '%s'\n", subclass, ast_sockaddr_stringify(&addr));
10391 return 1;
10392 }
10393 f.data.ptr = NULL;
10394 f.datalen = 0;
10395 } else {
10396 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10397 memset(&ies, 0, sizeof(ies));
10398 }
10399 } else {
10400 if (f.frametype == AST_FRAME_IAX)
10401 f.data.ptr = NULL;
10402 else
10403 f.data.ptr = empty;
10404 memset(&ies, 0, sizeof(ies));
10405 }
10406
10407 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10408 /* only set NEW_ALLOW if calltoken checks out */
10409 if (handle_call_token(fh, &ies, &addr, fd)) {
10411 return 1;
10412 }
10413
10414 if (ies.calltoken && ies.calltokendata) {
10415 /* if we've gotten this far, and the calltoken ie data exists,
10416 * then calltoken validation _MUST_ have taken place. If calltoken
10417 * data is provided, it is always validated regardless of any
10418 * calltokenoptional or requirecalltoken options */
10420 } else {
10421 new = NEW_ALLOW;
10422 }
10423 }
10424 } else {
10425 /* Don't know anything about it yet */
10427 f.subclass.integer = 0;
10428 memset(&ies, 0, sizeof(ies));
10429 }
10430
10431 if (!fr->callno) {
10432 int check_dcallno = 0;
10433
10434 /*
10435 * We enforce accurate destination call numbers for ACKs. This forces the other
10436 * end to know the destination call number before call setup can complete.
10437 *
10438 * Discussed in the following thread:
10439 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10440 */
10441
10442 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10443 check_dcallno = 1;
10444 }
10445
10446 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, new, fd, check_dcallno))) {
10447 ast_debug(1, "Received frame without existent call number (%d)\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10449 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10451 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10452 } else {
10453 ast_log(LOG_WARNING, "Silently dropping frame without existent call number: %d\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10454 }
10456 return 1;
10457 }
10458 }
10459
10460 if (fr->callno > 0) {
10461 ast_callid mount_callid;
10463 if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10464 /* Bind to thread */
10465 ast_callid_threadassoc_add(mount_callid);
10466 }
10467 }
10468
10469 if (!fr->callno || !iaxs[fr->callno]) {
10470 /* A call arrived for a nonexistent destination. Unless it's an "inval"
10471 frame, reply with an inval */
10472 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10473 /* We can only raw hangup control frames */
10474 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10478 (f.frametype != AST_FRAME_IAX))
10479 raw_hangup(&addr, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10480 fd);
10481 }
10482 if (fr->callno > 0){
10484 }
10486 return 1;
10487 }
10488 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10489 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10490 ast_log(LOG_WARNING, "Packet Decrypt Failed!\n");
10493 return 1;
10494 }
10495 decrypted = 1;
10496 }
10497
10498#ifdef DEBUG_SUPPORT
10499 if (decrypted) {
10500 iax_outputframe(NULL, fh, 3, &addr, res - sizeof(*fh));
10501 }
10502#endif
10503
10504 if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10505 (fh->csub == IAX_COMMAND_HANGUP
10506 || fh->csub == IAX_COMMAND_REJECT
10507 || fh->csub == IAX_COMMAND_REGREJ
10508 || fh->csub == IAX_COMMAND_TXREJ)) {
10509 struct ast_control_pvt_cause_code *cause_code;
10510 int data_size = sizeof(*cause_code);
10511 char subclass[40] = "";
10512
10513 /* get subclass text */
10514 iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10515
10516 /* add length of "IAX2 " */
10517 data_size += 5;
10518 /* for IAX hangup frames, add length of () and number */
10519 data_size += 3;
10520 if (ies.causecode > 9) {
10521 data_size++;
10522 }
10523 if (ies.causecode > 99) {
10524 data_size++;
10525 }
10526 /* add length of subclass */
10527 data_size += strlen(subclass);
10528
10529 cause_code = ast_alloca(data_size);
10530 memset(cause_code, 0, data_size);
10532
10533 cause_code->ast_cause = ies.causecode;
10534 snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10535
10537 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10538 ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10539 ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10541 }
10542 if (!iaxs[fr->callno]) {
10545 return 1;
10546 }
10547 }
10548
10549 /* count this frame */
10550 iaxs[fr->callno]->frames_received++;
10551
10552 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) && !minivid &&
10553 f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10554 f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10555 unsigned short new_peercallno;
10556
10557 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10558 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10559 if (iaxs[fr->callno]->peercallno) {
10561 }
10562 iaxs[fr->callno]->peercallno = new_peercallno;
10564 }
10565 }
10566 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10567 if (iaxdebug)
10568 ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10569 /* Check if it's out of order (and not an ACK or INVAL) */
10570 fr->oseqno = fh->oseqno;
10571 fr->iseqno = fh->iseqno;
10572 fr->ts = ntohl(fh->ts);
10573#ifdef IAXTESTS
10574 if (test_resync) {
10575 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10576 fr->ts += test_resync;
10577 }
10578#endif /* IAXTESTS */
10579#if 0
10580 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10581 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10582 (f.subclass == IAX_COMMAND_NEW ||
10585 f.subclass == IAX_COMMAND_REJECT)) ) )
10586#endif
10587 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10588 updatehistory = 0;
10589 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10590 (iaxs[fr->callno]->iseqno ||
10592 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10593 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10594 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10596 (f.frametype != AST_FRAME_IAX))) {
10597 if (
10601 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10602 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10603 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10606 (f.frametype != AST_FRAME_IAX)) {
10607 /* If it's not an ACK packet, it's out of order. */
10608 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10609 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10610 /* Check to see if we need to request retransmission,
10611 * and take sequence number wraparound into account */
10612 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10613 /* If we've already seen it, ack it XXX There's a border condition here XXX */
10614 if ((f.frametype != AST_FRAME_IAX) ||
10616 ast_debug(1, "Acking anyway\n");
10617 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10618 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10620 }
10621 } else {
10622 /* Send a VNAK requesting retransmission */
10623 iax2_vnak(fr->callno);
10624 }
10627 return 1;
10628 }
10629 } else {
10630 /* Increment unless it's an ACK or VNAK */
10631 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10636 (f.frametype != AST_FRAME_IAX))
10637 iaxs[fr->callno]->iseqno++;
10638 }
10639 /* Ensure text frames are NULL-terminated */
10640 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10641 if (res < thread->buf_size)
10642 thread->buf[res++] = '\0';
10643 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10644 thread->buf[res - 1] = '\0';
10645 }
10646
10647 /* Handle implicit ACKing unless this is an INVAL, and only if this is
10648 from the real peer, not the transfer peer */
10649 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10651 (f.frametype != AST_FRAME_IAX))) {
10652 unsigned char x;
10653 int call_to_destroy;
10654 /* First we have to qualify that the ACKed value is within our window */
10655 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10656 x = fr->iseqno;
10657 else
10658 x = iaxs[fr->callno]->oseqno;
10659 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10660 /* The acknowledgement is within our window. Time to acknowledge everything
10661 that it says to */
10662 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10663 /* Ack the packet with the given timestamp */
10664 if (iaxdebug)
10665 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10666 call_to_destroy = 0;
10667 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10668 /* If it's our call, and our timestamp, mark -1 retries */
10669 if (x == cur->oseqno) {
10670 cur->retries = -1;
10671 /* Destroy call if this is the end */
10672 if (cur->final)
10673 call_to_destroy = fr->callno;
10674 }
10675 }
10676 if (call_to_destroy) {
10677 if (iaxdebug)
10678 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10679 ast_mutex_lock(&iaxsl[call_to_destroy]);
10680 iax2_destroy(call_to_destroy);
10681 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10682 }
10683 }
10684 /* Note how much we've received acknowledgement for */
10685 if (iaxs[fr->callno])
10686 iaxs[fr->callno]->rseqno = fr->iseqno;
10687 else {
10688 /* Stop processing now */
10691 return 1;
10692 }
10693 } else {
10694 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10695 }
10696 }
10697 if (ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10698 ((f.frametype != AST_FRAME_IAX) ||
10701 /* Only messages we accept from a transfer host are TXACC and TXCNT */
10704 return 1;
10705 }
10706
10707 /* when we receive the first full frame for a new incoming channel,
10708 it is safe to start the PBX on the channel because we have now
10709 completed a 3-way handshake with the peer */
10710 if ((f.frametype == AST_FRAME_VOICE) ||
10711 (f.frametype == AST_FRAME_VIDEO) ||
10712 (f.frametype == AST_FRAME_IAX)) {
10720 return 1;
10721 }
10722 }
10723
10724 if (ies.vars) {
10725 struct ast_datastore *variablestore = NULL;
10726 struct ast_variable *var, *prev = NULL;
10727 AST_LIST_HEAD(, ast_var_t) *varlist;
10728
10730 if (!iaxs[fr->callno]) {
10733 return 1;
10734 }
10735 if ((c = iaxs[fr->callno]->owner)) {
10736 varlist = ast_calloc(1, sizeof(*varlist));
10738
10739 if (variablestore && varlist) {
10740 variablestore->data = varlist;
10741 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10742 AST_LIST_HEAD_INIT(varlist);
10743 ast_debug(1, "I can haz IAX vars?\n");
10744 for (var = ies.vars; var; var = var->next) {
10745 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10746 if (prev) {
10747 ast_free(prev);
10748 }
10749 prev = var;
10750 if (!newvar) {
10751 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10752 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10753 } else {
10754 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10755 }
10756 }
10757 if (prev) {
10758 ast_free(prev);
10759 }
10760 ies.vars = NULL;
10761 ast_channel_datastore_add(c, variablestore);
10762 } else {
10763 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10764 if (variablestore) {
10765 ast_datastore_free(variablestore);
10766 }
10767 if (varlist) {
10768 ast_free(varlist);
10769 }
10770 }
10772 } else {
10773 /* No channel yet, so transfer the variables directly over to the pvt,
10774 * for later inheritance. */
10775 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10776 for (var = ies.vars; var && var->next; var = var->next);
10777 if (var) {
10778 var->next = iaxs[fr->callno]->iaxvars;
10779 iaxs[fr->callno]->iaxvars = ies.vars;
10780 ies.vars = NULL;
10781 }
10782 }
10783 }
10784
10785 if (ies.vars) {
10786 ast_debug(1, "I have IAX variables, but they were not processed\n");
10787 }
10788 }
10789
10790 /* once we receive our first IAX Full Frame that is not CallToken related, send all
10791 * queued signaling frames that were being held. */
10794 }
10795
10796 if (f.frametype == AST_FRAME_VOICE) {
10799 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_format_get_name(f.subclass.format));
10800 if (iaxs[fr->callno]->owner) {
10802 if (iaxs[fr->callno]) {
10803 if (iaxs[fr->callno]->owner) {
10805 if (native) {
10810 }
10811 ao2_ref(native, -1);
10812 }
10814 }
10815 } else {
10816 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10817 /* Free remote variables (if any) */
10818 if (ies.vars) {
10820 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10821 ies.vars = NULL;
10822 }
10824 return 1;
10825 }
10826 }
10827 }
10828 }
10829 if (f.frametype == AST_FRAME_VIDEO) {
10831 ast_debug(1, "Ooh, video format changed to %s\n", ast_format_get_name(f.subclass.format));
10833 }
10834 }
10835 if (f.frametype == AST_FRAME_IAX) {
10837 /* Handle the IAX pseudo frame itself */
10838 if (iaxdebug)
10839 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10840
10841 /* Update last ts unless the frame's timestamp originated with us. */
10842 if (iaxs[fr->callno]->last < fr->ts &&
10846 iaxs[fr->callno]->last = fr->ts;
10847 if (iaxdebug)
10848 ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10849 }
10851 if (!iaxs[fr->callno]->first_iax_message) {
10853 }
10854 switch(f.subclass.integer) {
10855 case IAX_COMMAND_ACK:
10856 /* Do nothing */
10857 break;
10858 case IAX_COMMAND_QUELCH:
10861 if (ies.musiconhold) {
10862 const char *moh_suggest;
10863
10865 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10866 break;
10867 }
10868
10869 /*
10870 * We already hold the owner lock so we do not
10871 * need to check iaxs[fr->callno] after it returns.
10872 */
10873 moh_suggest = iaxs[fr->callno]->mohsuggest;
10874 iax2_queue_hold(fr->callno, moh_suggest);
10876 }
10877 }
10878 break;
10882 if (!iaxs[fr->callno]) {
10883 break;
10884 }
10885
10887 if (!iaxs[fr->callno]->owner) {
10888 break;
10889 }
10890
10891 /*
10892 * We already hold the owner lock so we do not
10893 * need to check iaxs[fr->callno] after it returns.
10894 */
10897 }
10898 break;
10899 case IAX_COMMAND_TXACC:
10900 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10901 /* Ack the packet with the given timestamp */
10902 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10903 /* Cancel any outstanding txcnt's */
10904 if (cur->transfer) {
10905 cur->retries = -1;
10906 }
10907 }
10908 memset(&ied1, 0, sizeof(ied1));
10910 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10912 }
10913 break;
10914 case IAX_COMMAND_NEW:
10915 /* Ignore if it's already up */
10917 break;
10918 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
10920 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
10922 if (!iaxs[fr->callno]) {
10923 break;
10924 }
10925 }
10926 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10927 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10928 int new_callno;
10929 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10930 fr->callno = new_callno;
10931 }
10932 /* For security, always ack immediately */
10933 if (delayreject)
10935 if (check_access(fr->callno, &addr, &ies)) {
10936 /* They're not allowed on */
10938 if (authdebug) {
10939 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n",
10941 }
10942 break;
10943 }
10946 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10947 break;
10948 }
10949 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10950 const char *context, *exten, *cid_num;
10951
10953 exten = ast_strdupa(iaxs[fr->callno]->exten);
10954 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10955
10956 /* This might re-enter the IAX code and need the lock */
10958 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10960
10961 if (!iaxs[fr->callno]) {
10962 break;
10963 }
10964 } else
10965 exists = 0;
10966 /* Get OSP token if it does exist */
10967 save_osptoken(fr, &ies);
10969 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10970 memset(&ied0, 0, sizeof(ied0));
10971 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10974 if (!iaxs[fr->callno]) {
10975 break;
10976 }
10977 if (authdebug) {
10978 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
10980 }
10981 } else {
10982 /* Select an appropriate format */
10983
10986 using_prefs = "reqonly";
10987 } else {
10988 using_prefs = "disabled";
10989 }
10990 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10991 memset(&pref, 0, sizeof(pref));
10992 strcpy(caller_pref_buf, "disabled");
10993 strcpy(host_pref_buf, "disabled");
10994 } else {
10995 struct ast_format *tmpfmt;
10996 using_prefs = "mine";
10997 /* If the information elements are in here... use them */
10998 if (ies.codec_prefs)
11000 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11001 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
11003 pref = iaxs[fr->callno]->rprefs;
11004 using_prefs = "caller";
11005 } else {
11006 pref = iaxs[fr->callno]->prefs;
11007 }
11008 } else
11009 pref = iaxs[fr->callno]->prefs;
11010
11011 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11012 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11013 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11014 }
11015 if (!format) {
11017 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11018 if (!format) {
11019 memset(&ied0, 0, sizeof(ied0));
11020 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11023 if (!iaxs[fr->callno]) {
11024 break;
11025 }
11026 if (authdebug) {
11029 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11030
11032 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11034 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11036 } else {
11037 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11039 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11042 }
11043 }
11044 } else {
11045 /* Pick one... */
11047 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11048 format = 0;
11049 } else {
11051 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11052 memset(&pref, 0, sizeof(pref));
11054 strcpy(caller_pref_buf,"disabled");
11055 strcpy(host_pref_buf,"disabled");
11056 } else {
11057 struct ast_format *tmpfmt;
11058 using_prefs = "mine";
11059 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11060 /* Do the opposite of what we tried above. */
11062 pref = iaxs[fr->callno]->prefs;
11063 } else {
11064 pref = iaxs[fr->callno]->rprefs;
11065 using_prefs = "caller";
11066 }
11067 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11068 } else /* if no codec_prefs IE do it the old way */
11070 }
11071 }
11072
11073 if (!format) {
11076 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11077
11078 memset(&ied0, 0, sizeof(ied0));
11079 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11081 ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11083 if (!iaxs[fr->callno]) {
11084 break;
11085 }
11086 if (authdebug) {
11087 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11089 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11092 }
11094 break;
11095 }
11096 }
11097 }
11098 if (format) {
11099 /* No authentication required, let them in */
11100 memset(&ied1, 0, sizeof(ied1));
11101 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11103 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11104 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11106 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
11107 "%srequested format = %s,\n"
11108 "%srequested prefs = %s,\n"
11109 "%sactual format = %s,\n"
11110 "%shost prefs = %s,\n"
11111 "%spriority = %s\n",
11116 caller_pref_buf,
11118 iax2_getformatname(format),
11120 host_pref_buf,
11122 using_prefs);
11123
11124 iaxs[fr->callno]->chosenformat = format;
11125
11126 /* Since this is a new call, we should go ahead and set the callid for it. */
11129 } else {
11131 /* If this is a TBD call, we're ready but now what... */
11132 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_sockaddr_stringify(&addr));
11133 }
11134 }
11135 }
11136 break;
11137 }
11140 else
11141 iaxs[fr->callno]->encmethods = 0;
11142 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
11144 break;
11145 case IAX_COMMAND_DPREQ:
11146 /* Request status in the dialplan */
11149 if (iaxcompat) {
11150 /* Spawn a thread for the lookup */
11152 } else {
11153 /* Just look it up */
11154 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
11155 }
11156 }
11157 break;
11158 case IAX_COMMAND_HANGUP:
11160 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
11161 /* Set hangup cause according to remote and hangupsource */
11162 if (iaxs[fr->callno]->owner) {
11164 if (!iaxs[fr->callno]) {
11165 break;
11166 }
11167 }
11168
11169 /* Send ack immediately, before we destroy */
11171 iax2_destroy(fr->callno);
11172 break;
11173 case IAX_COMMAND_REJECT:
11174 /* Set hangup cause according to remote and hangup source */
11175 if (iaxs[fr->callno]->owner) {
11177 if (!iaxs[fr->callno]) {
11178 break;
11179 }
11180 }
11181
11183 if (iaxs[fr->callno]->owner && authdebug)
11184 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
11186 ies.cause ? ies.cause : "<Unknown>");
11187 ast_debug(1, "Immediately destroying %d, having received reject\n",
11188 fr->callno);
11189 }
11190 /* Send ack immediately, before we destroy */
11192 fr->ts, NULL, 0, fr->iseqno);
11194 iaxs[fr->callno]->error = EPERM;
11195 iax2_destroy(fr->callno);
11196 break;
11198 {
11200 if (!iaxs[fr->callno]) {
11201 /* Initiating call went away before we could transfer. */
11202 break;
11203 }
11204 if (iaxs[fr->callno]->owner) {
11205 struct ast_channel *owner = iaxs[fr->callno]->owner;
11206 char *context = ast_strdupa(iaxs[fr->callno]->context);
11207
11208 ast_channel_ref(owner);
11209 ast_channel_unlock(owner);
11211
11212 if (ast_bridge_transfer_blind(1, owner, ies.called_number,
11214 ast_log(LOG_WARNING, "Blind transfer of '%s' to '%s@%s' failed\n",
11215 ast_channel_name(owner), ies.called_number,
11216 context);
11217 }
11218
11219 ast_channel_unref(owner);
11221 }
11222
11223 break;
11224 }
11225 case IAX_COMMAND_ACCEPT:
11226 /* Ignore if call is already up or needs authentication or is a TBD */
11228 break;
11230 /* Send ack immediately, before we destroy */
11232 iax2_destroy(fr->callno);
11233 break;
11234 }
11235 if (ies.format) {
11236 iaxs[fr->callno]->peerformat = ies.format;
11237 } else {
11238 if (iaxs[fr->callno]->owner)
11240 else
11242 }
11243 ast_verb(3, "Call accepted by %s (format %s)\n", ast_sockaddr_stringify(&addr),
11245 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11246 memset(&ied0, 0, sizeof(ied0));
11247 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11250 if (!iaxs[fr->callno]) {
11251 break;
11252 }
11253 if (authdebug) {
11256
11257 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11261 }
11262 } else {
11264
11267 if (iaxs[fr->callno] && iaxs[fr->callno]->owner && native) {
11269
11270 /* Switch us to use a compatible format */
11272 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11273 native);
11275 ast_verb(3, "Format for call is %s\n", ast_format_cap_get_names(ast_channel_nativeformats(iaxs[fr->callno]->owner), &cap_buf));
11276
11277 /* Setup read/write formats properly. */
11283 }
11284
11285 ao2_cleanup(native);
11286 }
11287 if (iaxs[fr->callno]) {
11289 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11290 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11291 iax2_dprequest(dp, fr->callno);
11293 }
11294 break;
11295 case IAX_COMMAND_POKE:
11296 /* Send back a pong packet with the original timestamp */
11298 break;
11299 case IAX_COMMAND_PING:
11300 {
11301 struct iax_ie_data pingied;
11302 construct_rr(iaxs[fr->callno], &pingied);
11303 /* Send back a pong packet with the original timestamp */
11304 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11305 }
11306 break;
11307 case IAX_COMMAND_PONG:
11308 /* Calculate ping time */
11309 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11310 /* save RR info */
11311 save_rr(fr, &ies);
11312
11313 /* Good time to write jb stats for this call */
11315
11316 if (iaxs[fr->callno]->peerpoke) {
11317 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
11318 peer = iaxs[fr->callno]->peerpoke;
11319 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11320 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11321 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11323 blob = ast_json_pack("{s: s, s: I}",
11324 "peer_status", "Reachable",
11325 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11326 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11327 }
11328 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11329 if (iaxs[fr->callno]->pingtime > peer->maxms) {
11330 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11332 blob = ast_json_pack("{s: s, s: I}",
11333 "peer_status", "Lagged",
11334 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11335 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11336 }
11337 }
11339 peer->lastms = iaxs[fr->callno]->pingtime;
11340 if (peer->smoothing && (peer->lastms > -1))
11341 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11342 else if (peer->smoothing && peer->lastms < 0)
11343 peer->historicms = (0 + peer->historicms) / 2;
11344 else
11345 peer->historicms = iaxs[fr->callno]->pingtime;
11346
11347 /* Remove scheduled iax2_poke_noanswer */
11348 if (peer->pokeexpire > -1) {
11349 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11350 peer_unref(peer);
11351 peer->pokeexpire = -1;
11352 }
11353 }
11354 /* Schedule the next cycle */
11355 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11357 else
11359 if (peer->pokeexpire == -1)
11360 peer_unref(peer);
11361 /* and finally send the ack */
11363 /* And wrap up the qualify call */
11364 iax2_destroy(fr->callno);
11365 peer->callno = 0;
11366 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11367 }
11368 break;
11369 case IAX_COMMAND_LAGRQ:
11370 case IAX_COMMAND_LAGRP:
11371 f.src = "LAGRQ";
11372 f.mallocd = 0;
11373 f.offset = 0;
11374 f.samples = 0;
11375 iax_frame_wrap(fr, &f);
11377 /* Received a LAGRQ - echo back a LAGRP */
11379 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11380 } else {
11381 /* Received LAGRP in response to our LAGRQ */
11382 unsigned int ts;
11383 /* This is a reply we've been given, actually measure the difference */
11384 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11385 iaxs[fr->callno]->lag = ts - fr->ts;
11386 if (iaxdebug)
11387 ast_debug(1, "Peer %s lag measured as %dms\n",
11388 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->lag);
11389 }
11390 break;
11393 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>");
11394 break;
11395 }
11396 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11397 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11398 .subclass.integer = AST_CONTROL_HANGUP,
11399 };
11401 "I don't know how to authenticate %s to %s\n",
11402 ies.username ? ies.username : "<unknown>", ast_sockaddr_stringify(&addr));
11403 iax2_queue_frame(fr->callno, &hangup_fr);
11404 }
11405 break;
11407 /* For security, always ack immediately */
11408 if (delayreject)
11410 /* Ignore once we've started */
11412 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>");
11413 break;
11414 }
11415 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11416 if (authdebug)
11417 ast_log(LOG_WARNING, "Host %s failed to authenticate as %s\n", ast_sockaddr_stringify(&addr),
11418 iaxs[fr->callno]->username);
11419 memset(&ied0, 0, sizeof(ied0));
11421 break;
11422 }
11423 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11424 /* This might re-enter the IAX code and need the lock */
11426 } else
11427 exists = 0;
11428 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11429 if (authdebug)
11430 ast_log(LOG_WARNING, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
11432 iaxs[fr->callno]->exten,
11433 iaxs[fr->callno]->context);
11434 memset(&ied0, 0, sizeof(ied0));
11435 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11438 if (!iaxs[fr->callno]) {
11439 break;
11440 }
11441 } else {
11442 /* Select an appropriate format */
11445 using_prefs = "reqonly";
11446 } else {
11447 using_prefs = "disabled";
11448 }
11449 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11450 memset(&pref, 0, sizeof(pref));
11451 strcpy(caller_pref_buf, "disabled");
11452 strcpy(host_pref_buf, "disabled");
11453 } else {
11454 struct ast_format *tmpfmt;
11455 using_prefs = "mine";
11456 if (ies.codec_prefs)
11458 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11460 pref = iaxs[fr->callno]->rprefs;
11461 using_prefs = "caller";
11462 } else {
11463 pref = iaxs[fr->callno]->prefs;
11464 }
11465 } else /* if no codec_prefs IE do it the old way */
11466 pref = iaxs[fr->callno]->prefs;
11467 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11468 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11469 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11470 }
11471 if (!format) {
11474 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11475
11477 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11480 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11481 }
11482 if (!format) {
11483 if (authdebug) {
11485 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11487 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11489 } else {
11490 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11492 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11495 }
11496 }
11497 memset(&ied0, 0, sizeof(ied0));
11498 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11501 if (!iaxs[fr->callno]) {
11502 break;
11503 }
11504 } else {
11505 /* Pick one... */
11507 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11508 format = 0;
11509 } else {
11511 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11512 memset(&pref, 0, sizeof(pref));
11514 ? iaxs[fr->callno]->peerformat
11516 strcpy(caller_pref_buf,"disabled");
11517 strcpy(host_pref_buf,"disabled");
11518 } else {
11519 struct ast_format *tmpfmt;
11520 using_prefs = "mine";
11521 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11522 /* Do the opposite of what we tried above. */
11524 pref = iaxs[fr->callno]->prefs;
11525 } else {
11526 pref = iaxs[fr->callno]->rprefs;
11527 using_prefs = "caller";
11528 }
11529 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11530 } else /* if no codec_prefs IE do it the old way */
11532 }
11533 }
11534 if (!format) {
11537 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11538
11539 ast_log(LOG_ERROR, "No best format in %s???\n",
11541 if (authdebug) {
11543 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11545 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11547 } else {
11548 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11550 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11553 }
11554 }
11555 memset(&ied0, 0, sizeof(ied0));
11556 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11559 if (!iaxs[fr->callno]) {
11560 break;
11561 }
11562 }
11563 }
11564 }
11565 if (format) {
11566 /* Authentication received */
11567 memset(&ied1, 0, sizeof(ied1));
11568 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11570 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11571 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11572 char authmethodnames[AUTH_METHOD_NAMES_BUFSIZE];
11574 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11575 "%srequested auth methods = (%s),\n"
11576 "%sactual auth method = %s,\n"
11577 "%sencrypted = %s,\n"
11578 "%srequested format = %s,\n"
11579 "%srequested prefs = %s,\n"
11580 "%sactual format = %s,\n"
11581 "%shost prefs = %s,\n"
11582 "%spriority = %s\n",
11585 auth_method_names(iaxs[fr->callno]->authmethods, authmethodnames),
11589 IAX_CALLENCRYPTED(iaxs[fr->callno]) ? "yes" : "no",
11593 caller_pref_buf,
11595 iax2_getformatname(format),
11597 host_pref_buf,
11599 using_prefs);
11600
11601 /* Unlike unauthenticated calls, we don't need to store
11602 * the chosen format for channel creation.
11603 * However, this is helpful for __get_from_jb. */
11604 iaxs[fr->callno]->chosenformat = format;
11605
11607 c = ast_iax2_new(fr->callno, AST_STATE_RING, format,
11608 &iaxs[fr->callno]->rprefs, NULL, NULL, 1);
11609 if (!c) {
11610 iax2_destroy(fr->callno);
11611 } else if (ies.vars) {
11612 struct ast_datastore *variablestore;
11613 struct ast_variable *var, *prev = NULL;
11614 AST_LIST_HEAD(, ast_var_t) *varlist;
11615 varlist = ast_calloc(1, sizeof(*varlist));
11617 if (variablestore && varlist) {
11618 variablestore->data = varlist;
11619 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11620 AST_LIST_HEAD_INIT(varlist);
11621 ast_debug(1, "I can haz IAX vars? w00t\n");
11622 for (var = ies.vars; var; var = var->next) {
11623 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11624 if (prev)
11625 ast_free(prev);
11626 prev = var;
11627 if (!newvar) {
11628 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11629 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11630 } else {
11631 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11632 }
11633 }
11634 if (prev)
11635 ast_free(prev);
11636 ies.vars = NULL;
11637 ast_channel_datastore_add(c, variablestore);
11638 } else {
11639 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11640 if (variablestore)
11641 ast_datastore_free(variablestore);
11642 if (varlist)
11643 ast_free(varlist);
11644 }
11645 }
11646 } else {
11648 /* If this is a TBD call, we're ready but now what... */
11649 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_sockaddr_stringify(&addr));
11651 goto immediatedial;
11652 }
11653 }
11654 }
11655 }
11656 break;
11657 case IAX_COMMAND_DIAL:
11658immediatedial:
11661 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11662 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11663 if (authdebug)
11664 ast_log(LOG_WARNING, "Rejected dial attempt from %s, request '%s@%s' does not exist\n",
11666 iaxs[fr->callno]->exten,
11667 iaxs[fr->callno]->context);
11668 memset(&ied0, 0, sizeof(ied0));
11669 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11672 if (!iaxs[fr->callno]) {
11673 break;
11674 }
11675 } else {
11678 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11684 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11685 NULL, NULL, 1);
11686 if (!c) {
11687 iax2_destroy(fr->callno);
11688 } else if (ies.vars) {
11689 struct ast_datastore *variablestore;
11690 struct ast_variable *var, *prev = NULL;
11691 AST_LIST_HEAD(, ast_var_t) *varlist;
11692 varlist = ast_calloc(1, sizeof(*varlist));
11694 ast_debug(1, "I can haz IAX vars? w00t\n");
11695 if (variablestore && varlist) {
11696 variablestore->data = varlist;
11697 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11698 AST_LIST_HEAD_INIT(varlist);
11699 for (var = ies.vars; var; var = var->next) {
11700 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11701 if (prev)
11702 ast_free(prev);
11703 prev = var;
11704 if (!newvar) {
11705 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11706 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11707 } else {
11708 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11709 }
11710 }
11711 if (prev)
11712 ast_free(prev);
11713 ies.vars = NULL;
11714 ast_channel_datastore_add(c, variablestore);
11715 } else {
11716 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11717 if (variablestore)
11718 ast_datastore_free(variablestore);
11719 if (varlist)
11720 ast_free(varlist);
11721 }
11722 }
11723 }
11724 }
11725 break;
11726 case IAX_COMMAND_INVAL:
11727 iaxs[fr->callno]->error = ENOTCONN;
11728 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11729 iax2_destroy(fr->callno);
11730 ast_debug(1, "Destroying call %d\n", fr->callno);
11731 break;
11732 case IAX_COMMAND_VNAK:
11733 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11734 /* Force retransmission */
11735 vnak_retransmit(fr->callno, fr->iseqno);
11736 break;
11737 case IAX_COMMAND_REGREQ:
11738 case IAX_COMMAND_REGREL:
11739 /* For security, always ack immediately */
11740 if (delayreject)
11742 if (register_verify(fr->callno, &addr, &ies)) {
11743 if (!iaxs[fr->callno]) {
11744 break;
11745 }
11746 /* Send delayed failure */
11748 break;
11749 }
11750 if (!iaxs[fr->callno]) {
11751 break;
11752 }
11755
11757 ast_sockaddr_setnull(&addr);
11758 }
11759 if (update_registry(&addr, fr->callno, ies.devicetype, fd, ies.refresh)) {
11760 ast_log(LOG_WARNING, "Registry error\n");
11761 }
11762 if (!iaxs[fr->callno]) {
11763 break;
11764 }
11765 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
11767 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
11769 }
11770 break;
11771 }
11773 break;
11774 case IAX_COMMAND_REGACK:
11775 if (iax2_ack_registry(&ies, &addr, fr->callno)) {
11776 ast_log(LOG_WARNING, "Registration failure\n");
11777 }
11778 /* Send ack immediately, before we destroy */
11780 iax2_destroy(fr->callno);
11781 break;
11782 case IAX_COMMAND_REGREJ:
11783 if (iaxs[fr->callno]->reg) {
11784 if (authdebug) {
11785 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n",
11786 iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>",
11787 ast_sockaddr_stringify(&addr));
11788 }
11789 iax2_publish_registry(iaxs[fr->callno]->reg->username, ast_sockaddr_stringify(&addr), "Rejected", S_OR(ies.cause, "<unknown>"));
11791 }
11792 /* Send ack immediately, before we destroy */
11794 iax2_destroy(fr->callno);
11795 break;
11797 /* Authentication request */
11798 if (registry_rerequest(&ies, fr->callno, &addr)) {
11799 memset(&ied0, 0, sizeof(ied0));
11800 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11803 }
11804 break;
11805 case IAX_COMMAND_TXREJ:
11806 while (iaxs[fr->callno]
11807 && iaxs[fr->callno]->bridgecallno
11810 }
11811 if (!iaxs[fr->callno]) {
11812 break;
11813 }
11814
11816 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11817 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11818
11819 if (!iaxs[fr->callno]->bridgecallno) {
11820 break;
11821 }
11822
11823 if (iaxs[iaxs[fr->callno]->bridgecallno]
11827 }
11829 break;
11831 while (iaxs[fr->callno]
11832 && iaxs[fr->callno]->bridgecallno
11835 }
11836 if (!iaxs[fr->callno]) {
11837 break;
11838 }
11839
11840 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11842 } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11844 } else {
11845 if (iaxs[fr->callno]->bridgecallno) {
11847 }
11848 break;
11849 }
11850 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11851
11852 if (!iaxs[fr->callno]->bridgecallno) {
11853 break;
11854 }
11855
11856 if (!iaxs[iaxs[fr->callno]->bridgecallno]
11860 break;
11861 }
11862
11863 /* Both sides are ready */
11864
11865 /* XXX what isn't checked here is that both sides match transfer types. */
11866
11867 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11868 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11870
11873
11874 memset(&ied0, 0, sizeof(ied0));
11875 memset(&ied1, 0, sizeof(ied1));
11878 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11880 } else {
11881 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11883
11888
11889 /* Stop doing lag & ping requests */
11890 stop_stuff(fr->callno);
11892
11893 memset(&ied0, 0, sizeof(ied0));
11894 memset(&ied1, 0, sizeof(ied1));
11897 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11899 }
11901 break;
11902 case IAX_COMMAND_TXREQ:
11903 try_transfer(iaxs[fr->callno], &ies);
11904 break;
11905 case IAX_COMMAND_TXCNT:
11906 if (iaxs[fr->callno]->transferring)
11908 break;
11909 case IAX_COMMAND_TXREL:
11910 /* Send ack immediately, rather than waiting until we've changed addresses */
11912 complete_transfer(fr->callno, &ies);
11913 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11914 break;
11916 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11917 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11918 /* Cancel any outstanding frames and start anew */
11919 if (cur->transfer) {
11920 cur->retries = -1;
11921 }
11922 }
11923 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11925 }
11926 break;
11927 case IAX_COMMAND_RTKEY:
11928 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11930 "we've been told to rotate our encryption key, "
11931 "but this isn't an encrypted call. bad things will happen.\n"
11932 );
11933 break;
11934 }
11935
11936 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11937
11938 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11939 break;
11940 case IAX_COMMAND_DPREP:
11941 complete_dpreply(iaxs[fr->callno], &ies);
11942 break;
11944 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11945 break;
11947 /* Firmware download */
11950 break;
11951 }
11952 memset(&ied0, 0, sizeof(ied0));
11953 res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
11954 if (res < 0)
11956 else if (res > 0)
11958 else
11959 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11960 break;
11962 {
11963 struct iax_frame *cur;
11964 /* find last sent frame */
11965 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11966 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11967 }
11968 break;
11969 }
11970 default:
11971 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11972 memset(&ied0, 0, sizeof(ied0));
11975 }
11976 /* Free remote variables (if any) */
11977 if (ies.vars) {
11979 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11980 ies.vars = NULL;
11981 }
11982
11983 /* Don't actually pass these frames along */
11984 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11989 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
11991 }
11992 }
11994 return 1;
11995 }
11996 /* Unless this is an ACK or INVAL frame, ack it */
11997 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11999 } else if (minivid) {
12001 if (iaxs[fr->callno]->videoformat > 0) {
12002 if (ntohs(vh->ts) & 0x8000LL) {
12003 f.subclass.frame_ending = 1;
12004 }
12006 if (!f.subclass.format) {
12009 return 1;
12010 }
12011 } else {
12012 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
12013 iax2_vnak(fr->callno);
12016 return 1;
12017 }
12018 f.datalen = res - sizeof(*vh);
12019 if (f.datalen)
12020 f.data.ptr = thread->buf + sizeof(*vh);
12021 else
12022 f.data.ptr = NULL;
12023#ifdef IAXTESTS
12024 if (test_resync) {
12025 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
12026 } else
12027#endif /* IAXTESTS */
12028 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
12029 } else {
12030 /* A mini frame */
12032 if (iaxs[fr->callno]->voiceformat > 0) {
12034 if (!f.subclass.format) {
12037 return 1;
12038 }
12039 } else {
12040 ast_debug(1, "Received mini frame before first full voice frame\n");
12041 iax2_vnak(fr->callno);
12044 return 1;
12045 }
12046 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
12047 if (f.datalen < 0) {
12048 ast_log(LOG_WARNING, "Datalen < 0?\n");
12051 return 1;
12052 }
12053 if (f.datalen)
12054 f.data.ptr = thread->buf + sizeof(*mh);
12055 else
12056 f.data.ptr = NULL;
12057#ifdef IAXTESTS
12058 if (test_resync) {
12059 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
12060 } else
12061#endif /* IAXTESTS */
12062 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
12063 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
12064 }
12065
12066 /* Don't pass any packets until we're started */
12067 if (!iaxs[fr->callno]
12071 return 1;
12072 }
12073
12074 if (f.frametype == AST_FRAME_CONTROL) {
12076 /* Control frame not allowed to come from the wire. */
12077 ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
12078 fr->callno, f.subclass.integer);
12081 return 1;
12082 }
12085 if (iaxs[fr->callno]
12087 /* We are not configured to allow receiving these updates. */
12088 ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
12089 fr->callno, f.subclass.integer);
12092 return 1;
12093 }
12094 }
12095
12097 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12100 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
12102 }
12104 }
12105 }
12106
12109 && iaxs[fr->callno]) {
12111
12112 /*
12113 * Process a received connected line update.
12114 *
12115 * Initialize defaults.
12116 */
12118 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
12119 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
12120
12122 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
12123 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
12125
12127 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12129 S_COR(connected.id.number.valid, connected.id.number.str, ""),
12130 S_COR(connected.id.name.valid, connected.id.name.str, ""),
12131 NULL);
12132 ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
12133 ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
12135 }
12136 }
12138 }
12139
12140 /* Common things */
12141 f.src = "IAX2";
12142 f.mallocd = 0;
12143 f.offset = 0;
12144 f.len = 0;
12145 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
12147 /* We need to byteswap incoming slinear samples from network byte order */
12150 } else
12151 f.samples = 0;
12152 iax_frame_wrap(fr, &f);
12153
12154 /* If this is our most recent packet, use it as our basis for timestamping */
12155 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12156 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
12157 fr->outoforder = 0;
12158 } else {
12159 if (iaxdebug && iaxs[fr->callno]) {
12160 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);
12161 }
12162 fr->outoforder = 1;
12163 }
12165 if (iaxs[fr->callno]) {
12166 duped_fr = iaxfrdup2(fr);
12167 if (duped_fr) {
12168 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
12169 }
12170 }
12171 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12172 iaxs[fr->callno]->last = fr->ts;
12173#if 1
12174 if (iaxdebug)
12175 ast_debug(8, "For call=%d, set last=%u\n", fr->callno, fr->ts);
12176#endif
12177 }
12178
12179 /* Always run again */
12182 return 1;
12183}
12184
12186{
12187 int res = socket_process_helper(thread);
12190 }
12191 return res;
12192}
12193
12194/* Function to clean up process thread if it is cancelled */
12195static void iax2_process_thread_cleanup(void *data)
12196{
12197 struct iax2_thread *thread = data;
12198 ast_mutex_destroy(&thread->lock);
12199 ast_cond_destroy(&thread->cond);
12200 ast_mutex_destroy(&thread->init_lock);
12201 ast_cond_destroy(&thread->init_cond);
12203 /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
12205}
12206
12207static void *iax2_process_thread(void *data)
12208{
12209 struct iax2_thread *thread = data;
12210 struct timeval wait;
12211 struct timespec ts;
12212 int put_into_idle = 0;
12213 int first_time = 1;
12214 int old_state;
12215
12217
12218 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12219 pthread_cleanup_push(iax2_process_thread_cleanup, data);
12220
12221 for (;;) {
12222 /* Wait for something to signal us to be awake */
12223 ast_mutex_lock(&thread->lock);
12224
12225 if (thread->stop) {
12226 ast_mutex_unlock(&thread->lock);
12227 break;
12228 }
12229
12230 /* Flag that we're ready to accept signals */
12231 if (first_time) {
12232 signal_condition(&thread->init_lock, &thread->init_cond);
12233 first_time = 0;
12234 }
12235
12236 /* Put into idle list if applicable */
12237 if (put_into_idle) {
12239 }
12240
12241 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12242 struct iax2_thread *t = NULL;
12243 /* Wait to be signalled or time out */
12244 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12245 ts.tv_sec = wait.tv_sec;
12246 ts.tv_nsec = wait.tv_usec * 1000;
12247 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12248 /* This thread was never put back into the available dynamic
12249 * thread list, so just go away. */
12250 if (!put_into_idle || thread->stop) {
12251 ast_mutex_unlock(&thread->lock);
12252 break;
12253 }
12255 /* Account for the case where this thread is acquired *right* after a timeout */
12259 if (t) {
12260 /* This dynamic thread timed out waiting for a task and was
12261 * not acquired immediately after the timeout,
12262 * so it's time to go away. */
12263 ast_mutex_unlock(&thread->lock);
12264 break;
12265 }
12266 /* Someone grabbed our thread *right* after we timed out.
12267 * Wait for them to set us up with something to do and signal
12268 * us to continue. */
12269 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12270 ts.tv_sec = wait.tv_sec;
12271 ts.tv_nsec = wait.tv_usec * 1000;
12272 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12273 ast_mutex_unlock(&thread->lock);
12274 break;
12275 }
12276 }
12277 } else {
12278 ast_cond_wait(&thread->cond, &thread->lock);
12279 }
12280
12281 /* Go back into our respective list */
12282 put_into_idle = 1;
12283
12284 ast_mutex_unlock(&thread->lock);
12285
12286 if (thread->stop) {
12287 break;
12288 }
12289
12290 /* See what we need to do */
12291 switch (thread->iostate) {
12292 case IAX_IOSTATE_IDLE:
12293 continue;
12294 case IAX_IOSTATE_READY:
12295 thread->actions++;
12296 thread->iostate = IAX_IOSTATE_PROCESSING;
12299 break;
12301 thread->actions++;
12302 thread->iostate = IAX_IOSTATE_PROCESSING;
12303#ifdef SCHED_MULTITHREADED
12304 thread->schedfunc(thread->scheddata);
12305#endif
12306 break;
12307 default:
12308 break;
12309 }
12310
12311 /* The network thread added us to the active_thread list when we were given
12312 * frames to process, Now that we are done, we must remove ourselves from
12313 * the active list, and return to the idle list */
12317
12318 /* Make sure another frame didn't sneak in there after we thought we were done. */
12320
12321 time(&thread->checktime);
12322 thread->iostate = IAX_IOSTATE_IDLE;
12323#ifdef DEBUG_SCHED_MULTITHREAD
12324 thread->curfunc[0]='\0';
12325#endif
12326 }
12327
12328 /*!
12329 * \note For some reason, idle threads are exiting without being
12330 * removed from an idle list, which is causing memory
12331 * corruption. Forcibly remove it from the list, if it's there.
12332 */
12336
12340
12341 if (!thread->stop) {
12342 /* Nobody asked me to stop so nobody is waiting to join me. */
12343 pthread_detach(pthread_self());
12344 }
12345
12346 /* I am exiting here on my own volition, I need to clean up my own data structures
12347 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12348 */
12349 pthread_cleanup_pop(1);
12350 return NULL;
12351}
12352
12353static int iax2_do_register(struct iax2_registry *reg)
12354{
12355 struct iax_ie_data ied;
12356 if (iaxdebug)
12357 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12358
12359 if (reg->dnsmgr &&
12360 ((reg->regstate == REG_STATE_TIMEOUT) || ast_sockaddr_isnull(&reg->addr))) {
12361 /* Maybe the IP has changed, force DNS refresh */
12363 }
12364
12365 /*
12366 * if IP has Changed, free allocated call to create a new one with new IP
12367 * call has the pointer to IP and must be updated to the new one
12368 */
12369 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12370 int callno = reg->callno;
12371 ast_mutex_lock(&iaxsl[callno]);
12372 iax2_destroy(callno);
12373 ast_mutex_unlock(&iaxsl[callno]);
12374 reg->callno = 0;
12375 }
12376 if (ast_sockaddr_isnull(&reg->addr)) {
12377 if (iaxdebug)
12378 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12379 /* Setup the next registration attempt */
12381 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12382 return -1;
12383 }
12384 if (!ast_sockaddr_port(&reg->addr) && reg->port) {
12385 ast_sockaddr_set_port(&reg->addr, reg->port);
12386 }
12387
12388 if (!reg->callno) {
12389
12390 ast_debug(3, "Allocate call number\n");
12391
12392 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
12393 if (reg->callno < 1) {
12394 ast_log(LOG_WARNING, "Unable to create call for registration\n");
12395 return -1;
12396 } else
12397 ast_debug(3, "Registration created on call %d\n", reg->callno);
12398 iaxs[reg->callno]->reg = reg;
12400 }
12401 /* Setup the next registration a little early */
12403 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12404 /* Send the request */
12405 memset(&ied, 0, sizeof(ied));
12408 add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12411 return 0;
12412}
12413
12414static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
12415{
12416 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12417 is found for template */
12418 struct iax_ie_data provdata;
12419 struct iax_ie_data ied;
12420 unsigned int sig;
12421 struct ast_sockaddr addr;
12422 int callno;
12423 struct create_addr_info cai;
12424
12425 memset(&cai, 0, sizeof(cai));
12426
12427 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12428
12429 if (iax_provision_build(&provdata, &sig, template, force)) {
12430 ast_debug(1, "No provisioning found for template '%s'\n", template);
12431 return 0;
12432 }
12433
12434 if (end) {
12435 ast_sockaddr_copy(&addr, end);
12436 cai.sockfd = sockfd;
12437 } else if (create_addr(dest, NULL, &addr, &cai))
12438 return -1;
12439
12440 /* Build the rest of the message */
12441 memset(&ied, 0, sizeof(ied));
12442 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12443
12444 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12445 if (!callno)
12446 return -1;
12447
12448 if (iaxs[callno]) {
12449 /* Schedule autodestruct in case they don't ever give us anything back */
12450 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12451 sched, 15000, auto_hangup, (void *)(long)callno);
12453 /* Got a call number now, so go ahead and send the provisioning information */
12454 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12455 }
12456 ast_mutex_unlock(&iaxsl[callno]);
12457
12458 return 1;
12459}
12460
12461static char *papp = "IAX2Provision";
12462
12463/*! iax2provision
12464\ingroup applications
12465*/
12466static int iax2_prov_app(struct ast_channel *chan, const char *data)
12467{
12468 int res;
12469 char *sdata;
12470 char *opts;
12471 int force =0;
12472 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12473 if (ast_strlen_zero(data))
12474 data = "default";
12475 sdata = ast_strdupa(data);
12476 opts = strchr(sdata, '|');
12477 if (opts)
12478 *opts='\0';
12479
12480 if (ast_channel_tech(chan) != &iax2_tech) {
12481 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12482 return -1;
12483 }
12484 if (!callno || !iaxs[callno] || ast_sockaddr_isnull(&iaxs[callno]->addr)) {
12485 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12486 return -1;
12487 }
12488 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12489 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12490 ast_sockaddr_stringify(&iaxs[callno]->addr),
12491 sdata, res);
12492 return res;
12493}
12494
12495static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12496{
12497 int force = 0;
12498 int res;
12499
12500 switch (cmd) {
12501 case CLI_INIT:
12502 e->command = "iax2 provision";
12503 e->usage =
12504 "Usage: iax2 provision <host> <template> [forced]\n"
12505 " Provisions the given peer or IP address using a template\n"
12506 " matching either 'template' or '*' if the template is not\n"
12507 " found. If 'forced' is specified, even empty provisioning\n"
12508 " fields will be provisioned as empty fields.\n";
12509 return NULL;
12510 case CLI_GENERATE:
12511 if (a->pos == 3)
12512 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12513 return NULL;
12514 }
12515
12516 if (a->argc < 4)
12517 return CLI_SHOWUSAGE;
12518 if (a->argc > 4) {
12519 if (!strcasecmp(a->argv[4], "forced"))
12520 force = 1;
12521 else
12522 return CLI_SHOWUSAGE;
12523 }
12524 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12525 if (res < 0)
12526 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12527 else if (res < 1)
12528 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12529 else
12530 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12531 return CLI_SUCCESS;
12532}
12533
12534static void __iax2_poke_noanswer(const void *data)
12535{
12536 struct iax2_peer *peer = (struct iax2_peer *)data;
12537 int callno;
12538
12539 if (peer->lastms > -1) {
12540 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12541
12542 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12544 blob = ast_json_pack("{s: s, s: i}",
12545 "peer_status", "Unreachable",
12546 "time", peer->lastms);
12548 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12549 }
12550 if ((callno = peer->callno) > 0) {
12554 }
12555 peer->callno = 0;
12556 peer->lastms = -1;
12557 /* Try again quickly */
12559 if (peer->pokeexpire == -1)
12560 peer_unref(peer);
12561}
12562
12563static int iax2_poke_noanswer(const void *data)
12564{
12565 struct iax2_peer *peer = (struct iax2_peer *)data;
12566 peer->pokeexpire = -1;
12567#ifdef SCHED_MULTITHREADED
12569#endif
12571 peer_unref(peer);
12572 return 0;
12573}
12574
12575static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12576{
12577 struct iax2_peer *peer = obj;
12578
12579 iax2_poke_peer(peer, 0);
12580
12581 return 0;
12582}
12583
12584static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12585{
12586 int callno;
12587 int poke_timeout;
12588
12589 if (!peer->maxms || (ast_sockaddr_isnull(&peer->addr) && !peer->dnsmgr)) {
12590 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12591 immediately after clearing things out */
12592 peer->lastms = 0;
12593 peer->historicms = 0;
12594 peer->pokeexpire = -1;
12595 peer->callno = 0;
12596 return 0;
12597 }
12598
12599 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12600 if ((callno = peer->callno) > 0) {
12601 ast_log(LOG_NOTICE, "Still have a callno...\n");
12605 }
12606 if (heldcall)
12607 ast_mutex_unlock(&iaxsl[heldcall]);
12608 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
12609 if (heldcall)
12610 ast_mutex_lock(&iaxsl[heldcall]);
12611 if (callno < 1) {
12612 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12613 return -1;
12614 }
12615
12616 if (peer->pokeexpire > -1) {
12617 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12618 peer->pokeexpire = -1;
12619 peer_unref(peer);
12620 }
12621 }
12622
12623 if (peer->lastms < 0){
12624 /* If the host is already unreachable then use time less than the unreachable
12625 * interval. 5/6 is arbitrary multiplier to get value less than
12626 * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
12627 * current POKE before starting new POKE (which is scheduled after
12628 * peer->pokefreqnotok). */
12629 poke_timeout = peer->pokefreqnotok * 5 / 6;
12630 } else {
12631 /* If the host is reachable, use timeout large enough to allow for multiple
12632 * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
12633 * multiplier to get value less than peer->pokefreqok. Value less than
12634 * peer->pokefreqok is used to expire current POKE before starting new POKE
12635 * (which is scheduled after peer->pokefreqok). */
12636 poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
12637 }
12638
12639 /* Queue up a new task to handle no reply */
12640 peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
12641
12642 if (peer->pokeexpire == -1)
12643 peer_unref(peer);
12644
12645 /* And send the poke */
12647 if (iaxs[callno]) {
12648 struct iax_ie_data ied = {
12649 .buf = { 0 },
12650 .pos = 0,
12651 };
12652
12653 /* Speed up retransmission times for this qualify call */
12654 iaxs[callno]->pingtime = peer->maxms / 8;
12655 iaxs[callno]->peerpoke = peer;
12656
12657 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12658 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12659 }
12660 ast_mutex_unlock(&iaxsl[callno]);
12661
12662 return 0;
12663}
12664
12665static void free_context(struct iax2_context *con)
12666{
12667 struct iax2_context *conl;
12668 while(con) {
12669 conl = con;
12670 con = con->next;
12671 ast_free(conl);
12672 }
12673}
12674
12675static 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)
12676{
12677 int callno;
12678 int res;
12679 struct ast_sockaddr addr;
12680 struct ast_channel *c;
12681 struct parsed_dial_string pds;
12682 struct create_addr_info cai;
12683 char *tmpstr;
12684 ast_callid callid;
12685
12686 memset(&pds, 0, sizeof(pds));
12687 tmpstr = ast_strdupa(data);
12688 parse_dial_string(tmpstr, &pds);
12689
12691
12692 if (ast_strlen_zero(pds.peer)) {
12693 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12694 return NULL;
12695 }
12696 memset(&cai, 0, sizeof(cai));
12698
12700
12701 /* Populate our address from the given */
12702 if (create_addr(pds.peer, NULL, &addr, &cai)) {
12703 *cause = AST_CAUSE_UNREGISTERED;
12704 return NULL;
12705 }
12706
12707 if (pds.port) {
12708 int bindport;
12709 ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535);
12710 ast_sockaddr_set_port(&addr, bindport);
12711 }
12712
12713 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12714 if (callno < 1) {
12715 ast_log(LOG_WARNING, "Unable to create call\n");
12716 *cause = AST_CAUSE_CONGESTION;
12717 return NULL;
12718 }
12719
12720 /* If this is a trunk, update it now */
12722 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12723 int new_callno;
12724 if ((new_callno = make_trunk(callno, 1)) != -1)
12725 callno = new_callno;
12726 }
12727 iaxs[callno]->maxtime = cai.maxtime;
12728 if (callid) {
12729 iax_pvt_callid_set(callno, callid);
12730 }
12731
12732 if (cai.found) {
12733 ast_string_field_set(iaxs[callno], host, pds.peer);
12734 }
12735
12736 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, &cai.prefs, assignedids,
12737 requestor, cai.found);
12738
12739 ast_mutex_unlock(&iaxsl[callno]);
12740
12741 if (c) {
12742 struct ast_format_cap *joint;
12743 struct ast_format *format;
12744 if (callid) {
12746 ast_channel_callid_set(c, callid);
12748 }
12749
12751 if (!joint) {
12752 ast_hangup(c);
12753 return NULL;
12754 }
12755
12757
12758 /* If there is no joint format find one through translation */
12759 if (!ast_format_cap_count(joint)) {
12760 struct ast_format *best_fmt_cap = NULL;
12761 struct ast_format *best_fmt_native = NULL;
12762
12763 res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12764 if (res < 0) {
12765 struct ast_str *native_cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12767
12768 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12770 ast_format_cap_get_names(cap, &cap_buf),
12772 ast_hangup(c);
12773 ao2_ref(joint, -1);
12774 return NULL;
12775 }
12776 ast_format_cap_append(joint, best_fmt_native, 0);
12777 ao2_ref(best_fmt_cap, -1);
12778 ao2_ref(best_fmt_native, -1);
12779 }
12784
12785 ao2_ref(joint, -1);
12786 ao2_ref(format, -1);
12787 }
12788
12789 return c;
12790}
12791
12792static void *network_thread(void *ignore)
12793{
12794 int res;
12795
12796 if (timer) {
12798 }
12799
12800 for (;;) {
12801 pthread_testcancel();
12802 /* Wake up once a second just in case SIGURG was sent while
12803 * we weren't in poll(), to make sure we don't hang when trying
12804 * to unload. */
12805 res = ast_io_wait(io, 1000);
12806 /* Timeout(=0), and EINTR is not a thread exit condition. We do
12807 * not want to exit the thread loop on these conditions. */
12808 if (res < 0 && errno != -EINTR) {
12809 ast_log(LOG_ERROR, "IAX2 network thread unexpected exit: %s\n", strerror(errno));
12810 break;
12811 }
12812 }
12813
12814 return NULL;
12815}
12816
12817static int start_network_thread(void)
12818{
12819 struct iax2_thread *thread;
12820 int threadcount = 0;
12821 int x;
12822 for (x = 0; x < iaxthreadcount; x++) {
12823 thread = ast_calloc(1, sizeof(*thread));
12824 if (thread) {
12826 thread->threadnum = ++threadcount;
12827 ast_mutex_init(&thread->lock);
12828 ast_cond_init(&thread->cond, NULL);
12829 ast_mutex_init(&thread->init_lock);
12830 ast_cond_init(&thread->init_cond, NULL);
12831
12832 ast_mutex_lock(&thread->init_lock);
12833
12835 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12836 ast_mutex_destroy(&thread->lock);
12837 ast_cond_destroy(&thread->cond);
12838 ast_mutex_unlock(&thread->init_lock);
12839 ast_mutex_destroy(&thread->init_lock);
12840 ast_cond_destroy(&thread->init_cond);
12842 thread = NULL;
12843 continue;
12844 }
12845 /* Wait for the thread to be ready */
12846 ast_cond_wait(&thread->init_cond, &thread->init_lock);
12847
12848 /* Done with init_lock */
12849 ast_mutex_unlock(&thread->init_lock);
12850
12854 }
12855 }
12857 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12858 return -1;
12859 }
12860 ast_verb(2, "%d helper threads started\n", threadcount);
12861 return 0;
12862}
12863
12864static struct iax2_context *build_context(const char *context)
12865{
12866 struct iax2_context *con;
12867
12868 if ((con = ast_calloc(1, sizeof(*con))))
12869 ast_copy_string(con->context, context, sizeof(con->context));
12870
12871 return con;
12872}
12873
12874static int get_auth_methods(const char *value)
12875{
12876 int methods = 0;
12877 if (strstr(value, "rsa"))
12879 if (strstr(value, "md5"))
12881 if (strstr(value, "plaintext"))
12883 return methods;
12884}
12885
12886
12887/*! \brief Check if address can be used as packet source.
12888 \retval 0 address available
12889 \retval 1 address unavailable
12890 \retval -1 error
12891*/
12892static int check_srcaddr(struct ast_sockaddr *addr)
12893{
12894 int sd;
12895
12896 sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12897 if (sd < 0) {
12898 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12899 return -1;
12900 }
12901
12902 if (ast_bind(sd, addr) < 0) {
12903 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12904 close(sd);
12905 return 1;
12906 }
12907
12908 close(sd);
12909 return 0;
12910}
12911
12912/*! \brief Parse the "sourceaddress" value,
12913 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12914 not found. */
12915static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12916{
12917 struct ast_sockaddr addr;
12918 int nonlocal = 1;
12919 int port = IAX_DEFAULT_PORTNO;
12920 int sockfd = defaultsockfd;
12921 char *tmp;
12922 char *host;
12923 char *portstr;
12924
12925 tmp = ast_strdupa(srcaddr);
12926 ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12927
12928 if (portstr) {
12929 port = atoi(portstr);
12930 if (port < 1)
12931 port = IAX_DEFAULT_PORTNO;
12932 }
12933
12934 addr.ss.ss_family = AST_AF_UNSPEC;
12935 if (!ast_get_ip(&addr, host)) {
12936 struct ast_netsock *sock;
12937
12938 if (check_srcaddr(&addr) == 0) {
12939 /* ip address valid. */
12940 ast_sockaddr_set_port(&addr, port);
12941
12942 if (!(sock = ast_netsock_find(netsock, &addr)))
12943 sock = ast_netsock_find(outsock, &addr);
12944 if (sock) {
12945 sockfd = ast_netsock_sockfd(sock);
12946 nonlocal = 0;
12947 } else {
12948 /* INADDR_ANY matches anyway! */
12949 ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12950 ast_sockaddr_set_port(&addr, port);
12951 if (ast_netsock_find(netsock, &addr)) {
12952 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12953 if (sock) {
12954 sockfd = ast_netsock_sockfd(sock);
12955 ast_netsock_unref(sock);
12956 nonlocal = 0;
12957 } else {
12958 nonlocal = 2;
12959 }
12960 }
12961 }
12962 }
12963 }
12964
12965 peer->sockfd = sockfd;
12966
12967 if (nonlocal == 1) {
12969 "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12970 srcaddr,
12971 peer->name);
12972 return -1;
12973 } else if (nonlocal == 2) {
12975 "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12976 srcaddr,
12977 peer->name);
12978 return -1;
12979 } else {
12980 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12981 return 0;
12982 }
12983}
12984
12985static void peer_destructor(void *obj)
12986{
12987 struct iax2_peer *peer = obj;
12988 int callno = peer->callno;
12989
12990 ast_free_acl_list(peer->acl);
12991
12992 if (callno > 0) {
12996 }
12997
12998 register_peer_exten(peer, 0);
12999
13000 if (peer->dnsmgr)
13002
13003 if (peer->mwi_event_sub) {
13005 }
13006
13008
13010}
13011
13012/*! \brief Create peer structure based on configuration */
13013static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13014{
13015 struct iax2_peer *peer = NULL;
13016 struct ast_acl_list *oldacl = NULL;
13017 int maskfound = 0;
13018 int found = 0;
13019 int firstpass = 1;
13020 int subscribe_acl_change = 0;
13021
13022 if (!temponly) {
13023 peer = ao2_find(peers, name, OBJ_KEY);
13024 if (peer && !ast_test_flag64(peer, IAX_DELME))
13025 firstpass = 0;
13026 }
13027
13028 if (peer) {
13029 found++;
13030 if (firstpass) {
13031 oldacl = peer->acl;
13032 peer->acl = NULL;
13033 }
13034 unlink_peer(peer);
13035 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
13036 peer->expire = -1;
13037 peer->pokeexpire = -1;
13038 peer->sockfd = defaultsockfd;
13039 if (ast_string_field_init(peer, 32))
13040 peer = peer_unref(peer);
13041 if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
13042 peer = peer_unref(peer);
13043 }
13044 }
13045
13046 if (peer) {
13047 if (firstpass) {
13051 peer->adsi = adsi;
13052 ast_string_field_set(peer, secret, "");
13053 if (!found) {
13055 ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
13057 peer->expiry = min_reg_expire;
13058 }
13059 peer->prefs = prefs_global;
13061 peer->smoothing = 0;
13064 peer->maxcallno = 0;
13065 peercnt_modify((unsigned char) 0, 0, &peer->addr);
13068 ast_string_field_set(peer,peercontext,"");
13070 ast_string_field_set(peer, cid_name, "");
13071 ast_string_field_set(peer, cid_num, "");
13074 }
13075
13076 if (!v) {
13077 v = alt;
13078 alt = NULL;
13079 }
13080 while(v) {
13081 if (!strcasecmp(v->name, "secret")) {
13082 ast_string_field_set(peer, secret, v->value);
13083 } else if (!strcasecmp(v->name, "mailbox")) {
13085 } else if (!strcasecmp(v->name, "hasvoicemail")) {
13086 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
13087 /*
13088 * hasvoicemail is a users.conf legacy voicemail enable method.
13089 * hasvoicemail is only going to work for app_voicemail mailboxes.
13090 */
13091 if (strchr(name, '@')) {
13093 } else {
13094 ast_string_field_build(peer, mailbox, "%s@default", name);
13095 }
13096 }
13097 } else if (!strcasecmp(v->name, "mohinterpret")) {
13099 } else if (!strcasecmp(v->name, "mohsuggest")) {
13101 } else if (!strcasecmp(v->name, "dbsecret")) {
13102 ast_string_field_set(peer, dbsecret, v->value);
13103 } else if (!strcasecmp(v->name, "description")) {
13104 ast_string_field_set(peer, description, v->value);
13105 } else if (!strcasecmp(v->name, "trunk")) {
13107 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
13108 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
13110 }
13111 } else if (!strcasecmp(v->name, "auth")) {
13113 if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
13114 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);
13115 }
13116 } else if (!strcasecmp(v->name, "encryption")) {
13118 if (!peer->encmethods) {
13120 }
13121 } else if (!strcasecmp(v->name, "forceencryption")) {
13122 if (ast_false(v->value)) {
13124 } else {
13126 if (peer->encmethods) {
13128 }
13129 }
13130 } else if (!strcasecmp(v->name, "transfer")) {
13131 if (!strcasecmp(v->value, "mediaonly")) {
13133 } else if (ast_true(v->value)) {
13135 } else
13137 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13139 } else if (!strcasecmp(v->name, "host")) {
13140 if (!strcasecmp(v->value, "dynamic")) {
13141 /* They'll register with us */
13143 if (!found) {
13144 int peer_port = ast_sockaddr_port(&peer->addr);
13145 if (peer_port) {
13146 ast_sockaddr_set_port(&peer->defaddr, peer_port);
13147 }
13148 ast_sockaddr_setnull(&peer->addr);
13149 }
13150 } else {
13151 /* Non-dynamic. Make sure we become that way if we're not */
13152 AST_SCHED_DEL(sched, peer->expire);
13154 if (peer->dnsmgr) {
13155 // Make sure we refresh dnsmgr if we're using it
13157 } else {
13158 // Or just invalidate the address
13159 peer->addr.ss.ss_family = AST_AF_UNSPEC;
13160 }
13161 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
13162 return peer_unref(peer);
13163 }
13164 if (!ast_sockaddr_port(&peer->addr)) {
13166 }
13167 }
13168 } else if (!strcasecmp(v->name, "defaultip")) {
13169 struct ast_sockaddr peer_defaddr_tmp;
13170 peer_defaddr_tmp.ss.ss_family = AF_UNSPEC;
13171 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
13172 return peer_unref(peer);
13173 }
13174 ast_sockaddr_set_port(&peer_defaddr_tmp, ast_sockaddr_port(&peer->defaddr));
13175 ast_sockaddr_copy(&peer->defaddr, &peer_defaddr_tmp);
13176 } else if (!strcasecmp(v->name, "sourceaddress")) {
13177 peer_set_srcaddr(peer, v->value);
13178 } else if (!strcasecmp(v->name, "permit") ||
13179 !strcasecmp(v->name, "deny") ||
13180 !strcasecmp(v->name, "acl")) {
13181 ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
13182 } else if (!strcasecmp(v->name, "mask")) {
13183 maskfound++;
13184 ast_sockaddr_parse(&peer->mask, v->value, 0);
13185 } else if (!strcasecmp(v->name, "context")) {
13187 } else if (!strcasecmp(v->name, "regexten")) {
13188 ast_string_field_set(peer, regexten, v->value);
13189 } else if (!strcasecmp(v->name, "peercontext")) {
13190 ast_string_field_set(peer, peercontext, v->value);
13191 } else if (!strcasecmp(v->name, "port")) {
13192 int bindport;
13193 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
13194 bindport = IAX_DEFAULT_PORTNO;
13195 }
13196 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
13197 ast_sockaddr_set_port(&peer->defaddr, bindport);
13198 } else {
13199 ast_sockaddr_set_port(&peer->addr, bindport);
13200 }
13201 } else if (!strcasecmp(v->name, "username")) {
13202 ast_string_field_set(peer, username, v->value);
13203 } else if (!strcasecmp(v->name, "allow")) {
13204 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
13205 } else if (!strcasecmp(v->name, "disallow")) {
13206 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
13207 } else if (!strcasecmp(v->name, "callerid")) {
13208 if (!ast_strlen_zero(v->value)) {
13209 char name2[80];
13210 char num2[80];
13211 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13212 ast_string_field_set(peer, cid_name, name2);
13213 ast_string_field_set(peer, cid_num, num2);
13214 } else {
13215 ast_string_field_set(peer, cid_name, "");
13216 ast_string_field_set(peer, cid_num, "");
13217 }
13219 } else if (!strcasecmp(v->name, "fullname")) {
13220 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
13222 } else if (!strcasecmp(v->name, "cid_number")) {
13223 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
13225 } else if (!strcasecmp(v->name, "sendani")) {
13227 } else if (!strcasecmp(v->name, "inkeys")) {
13228 ast_string_field_set(peer, inkeys, v->value);
13229 } else if (!strcasecmp(v->name, "outkey")) {
13230 ast_string_field_set(peer, outkey, v->value);
13231 } else if (!strcasecmp(v->name, "qualify")) {
13232 if (!strcasecmp(v->value, "no")) {
13233 peer->maxms = 0;
13234 } else if (!strcasecmp(v->value, "yes")) {
13235 peer->maxms = DEFAULT_MAXMS;
13236 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
13237 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);
13238 peer->maxms = 0;
13239 }
13240 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
13241 peer->smoothing = ast_true(v->value);
13242 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
13243 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
13244 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);
13245 }
13246 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
13247 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
13248 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);
13249 }
13250 } else if (!strcasecmp(v->name, "timezone")) {
13252 } else if (!strcasecmp(v->name, "adsi")) {
13253 peer->adsi = ast_true(v->value);
13254 } else if (!strcasecmp(v->name, "connectedline")) {
13255 if (ast_true(v->value)) {
13257 } else if (!strcasecmp(v->value, "send")) {
13260 } else if (!strcasecmp(v->value, "receive")) {
13263 } else {
13265 }
13266 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13267 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13268 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13269 } else {
13270 peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13271 }
13272 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13273 /* default is required unless in optional ip list */
13274 if (ast_false(v->value)) {
13276 } else if (!strcasecmp(v->value, "auto")) {
13278 } else if (ast_true(v->value)) {
13280 } else {
13281 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13282 }
13283 } /* else if (strcasecmp(v->name,"type")) */
13284 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13285 v = v->next;
13286 if (!v) {
13287 v = alt;
13288 alt = NULL;
13289 }
13290 }
13291 if (!peer->authmethods)
13292 peer->authmethods = IAX_AUTH_MD5;
13294 }
13295
13296 if (!maskfound && !ast_sockaddr_isnull(&peer->addr)) {
13297 if (ast_sockaddr_is_ipv4_mapped(&peer->addr)) {
13298 ast_sockaddr_parse(&peer->mask, "::ffff:ffff:ffff", 0);
13299 } else if (ast_sockaddr_is_ipv6(&peer->addr)) {
13300 ast_sockaddr_parse(&peer->mask, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0);
13301 } else {
13302 ast_sockaddr_parse(&peer->mask, "255.255.255.255", 0);
13303 }
13304 }
13305
13306 if (oldacl) {
13307 ast_free_acl_list(oldacl);
13308 }
13309
13310 if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
13311 /* The MWI subscriptions exist just so the core knows we care about those
13312 * mailboxes. However, we just grab the events out of the cache when it
13313 * is time to send MWI, since it is only sent with a REGACK. */
13315 }
13316
13317 if (subscribe_acl_change) {
13319 }
13320
13321 return peer;
13322}
13323
13324static void user_destructor(void *obj)
13325{
13326 struct iax2_user *user = obj;
13327
13328 ast_free_acl_list(user->acl);
13329 free_context(user->contexts);
13330 if(user->vars) {
13332 user->vars = NULL;
13333 }
13335}
13336
13337/*! \brief Create in-memory user structure from configuration */
13338static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13339{
13340 struct iax2_user *user = NULL;
13341 struct iax2_context *con, *conl = NULL;
13342 struct ast_acl_list *oldacl = NULL;
13343 struct iax2_context *oldcon = NULL;
13344 int format;
13345 int firstpass=1;
13346 int oldcurauthreq = 0;
13347 int subscribe_acl_change = 0;
13348 char *varname = NULL, *varval = NULL;
13349 struct ast_variable *tmpvar = NULL;
13350
13351 if (!temponly) {
13354 firstpass = 0;
13355 }
13356
13357 if (user) {
13358 if (firstpass) {
13359 oldcurauthreq = user->curauthreq;
13360 oldacl = user->acl;
13361 oldcon = user->contexts;
13362 user->acl = NULL;
13363 user->contexts = NULL;
13364 }
13365 /* Already in the list, remove it and it will be added back (or FREE'd) */
13367 } else {
13368 user = ao2_alloc(sizeof(*user), user_destructor);
13369 }
13370
13371 if (user) {
13372 if (firstpass) {
13374 memset(user, 0, sizeof(struct iax2_user));
13375 if (ast_string_field_init(user, 32)) {
13376 user = user_unref(user);
13377 goto cleanup;
13378 }
13379 user->maxauthreq = maxauthreq;
13380 user->curauthreq = oldcurauthreq;
13381 user->prefs = prefs_global;
13382 user->capability = iax2_capability;
13383 user->encmethods = iax2_encryption;
13384 user->authmethods = iax2_authmethods;
13385 user->adsi = adsi;
13386 user->calltoken_required = CALLTOKEN_DEFAULT;
13391 ast_string_field_set(user, cid_name, "");
13392 ast_string_field_set(user, cid_num, "");
13396 }
13397 if (!v) {
13398 v = alt;
13399 alt = NULL;
13400 }
13401 while(v) {
13402 if (!strcasecmp(v->name, "context")) {
13403 con = build_context(v->value);
13404 if (con) {
13405 if (conl)
13406 conl->next = con;
13407 else
13408 user->contexts = con;
13409 conl = con;
13410 }
13411 } else if (!strcasecmp(v->name, "permit") ||
13412 !strcasecmp(v->name, "deny") ||
13413 !strcasecmp(v->name, "acl")) {
13414 ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13415 } else if (!strcasecmp(v->name, "setvar")) {
13416 varname = ast_strdupa(v->value);
13417 if ((varval = strchr(varname, '='))) {
13418 *varval = '\0';
13419 varval++;
13420 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
13421 if (ast_variable_list_replace(&user->vars, tmpvar)) {
13422 tmpvar->next = user->vars;
13423 user->vars = tmpvar;
13424 }
13425 }
13426 }
13427 } else if (!strcasecmp(v->name, "allow")) {
13428 iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13429 } else if (!strcasecmp(v->name, "disallow")) {
13430 iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13431 } else if (!strcasecmp(v->name, "trunk")) {
13433 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13434 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13436 }
13437 } else if (!strcasecmp(v->name, "auth")) {
13438 user->authmethods = get_auth_methods(v->value);
13439 if (user->authmethods & IAX_AUTH_PLAINTEXT) {
13440 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);
13441 }
13442 } else if (!strcasecmp(v->name, "encryption")) {
13443 user->encmethods |= get_encrypt_methods(v->value);
13444 if (!user->encmethods) {
13446 }
13447 } else if (!strcasecmp(v->name, "forceencryption")) {
13448 if (ast_false(v->value)) {
13450 } else {
13451 user->encmethods |= get_encrypt_methods(v->value);
13452 if (user->encmethods) {
13454 }
13455 }
13456 } else if (!strcasecmp(v->name, "transfer")) {
13457 if (!strcasecmp(v->value, "mediaonly")) {
13459 } else if (ast_true(v->value)) {
13461 } else
13463 } else if (!strcasecmp(v->name, "codecpriority")) {
13464 if(!strcasecmp(v->value, "caller"))
13466 else if(!strcasecmp(v->value, "disabled"))
13468 else if(!strcasecmp(v->value, "reqonly")) {
13471 }
13472 } else if (!strcasecmp(v->name, "immediate")) {
13474 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13476 } else if (!strcasecmp(v->name, "dbsecret")) {
13477 ast_string_field_set(user, dbsecret, v->value);
13478 } else if (!strcasecmp(v->name, "secret")) {
13479 if (!ast_strlen_zero(user->secret)) {
13480 char *old = ast_strdupa(user->secret);
13481
13482 ast_string_field_build(user, secret, "%s;%s", old, v->value);
13483 } else
13484 ast_string_field_set(user, secret, v->value);
13485 } else if (!strcasecmp(v->name, "callerid")) {
13486 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13487 char name2[80];
13488 char num2[80];
13489 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13490 ast_string_field_set(user, cid_name, name2);
13491 ast_string_field_set(user, cid_num, num2);
13493 } else {
13495 ast_string_field_set(user, cid_name, "");
13496 ast_string_field_set(user, cid_num, "");
13497 }
13498 } else if (!strcasecmp(v->name, "fullname")) {
13499 if (!ast_strlen_zero(v->value)) {
13500 ast_string_field_set(user, cid_name, v->value);
13502 } else {
13503 ast_string_field_set(user, cid_name, "");
13504 if (ast_strlen_zero(user->cid_num))
13506 }
13507 } else if (!strcasecmp(v->name, "cid_number")) {
13508 if (!ast_strlen_zero(v->value)) {
13509 ast_string_field_set(user, cid_num, v->value);
13511 } else {
13512 ast_string_field_set(user, cid_num, "");
13513 if (ast_strlen_zero(user->cid_name))
13515 }
13516 } else if (!strcasecmp(v->name, "accountcode")) {
13518 } else if (!strcasecmp(v->name, "mohinterpret")) {
13520 } else if (!strcasecmp(v->name, "mohsuggest")) {
13522 } else if (!strcasecmp(v->name, "parkinglot")) {
13523 ast_string_field_set(user, parkinglot, v->value);
13524 } else if (!strcasecmp(v->name, "language")) {
13526 } else if (!strcasecmp(v->name, "amaflags")) {
13527 format = ast_channel_string2amaflag(v->value);
13528 if (format < 0) {
13529 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13530 } else {
13531 user->amaflags = format;
13532 }
13533 } else if (!strcasecmp(v->name, "inkeys")) {
13534 ast_string_field_set(user, inkeys, v->value);
13535 } else if (!strcasecmp(v->name, "maxauthreq")) {
13536 user->maxauthreq = atoi(v->value);
13537 if (user->maxauthreq < 0)
13538 user->maxauthreq = 0;
13539 } else if (!strcasecmp(v->name, "adsi")) {
13540 user->adsi = ast_true(v->value);
13541 } else if (!strcasecmp(v->name, "connectedline")) {
13542 if (ast_true(v->value)) {
13544 } else if (!strcasecmp(v->value, "send")) {
13547 } else if (!strcasecmp(v->value, "receive")) {
13550 } else {
13552 }
13553 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13554 /* default is required unless in optional ip list */
13555 if (ast_false(v->value)) {
13556 user->calltoken_required = CALLTOKEN_NO;
13557 } else if (!strcasecmp(v->value, "auto")) {
13558 user->calltoken_required = CALLTOKEN_AUTO;
13559 } else if (ast_true(v->value)) {
13560 user->calltoken_required = CALLTOKEN_YES;
13561 } else {
13562 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13563 }
13564 } /* else if (strcasecmp(v->name,"type")) */
13565 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13566 v = v->next;
13567 if (!v) {
13568 v = alt;
13569 alt = NULL;
13570 }
13571 }
13572 if (!user->authmethods) {
13573 if (!ast_strlen_zero(user->secret)) {
13574 user->authmethods = IAX_AUTH_MD5;
13575 if (!ast_strlen_zero(user->inkeys))
13576 user->authmethods |= IAX_AUTH_RSA;
13577 } else if (!ast_strlen_zero(user->inkeys)) {
13578 user->authmethods = IAX_AUTH_RSA;
13579 } else {
13580 user->authmethods = IAX_AUTH_MD5;
13581 }
13582 }
13584 }
13585cleanup:
13586 if (oldacl) {
13587 ast_free_acl_list(oldacl);
13588 }
13589 if (oldcon) {
13590 free_context(oldcon);
13591 }
13592
13593 if (subscribe_acl_change) {
13595 }
13596
13597 return user;
13598}
13599
13600static int peer_delme_cb(void *obj, void *arg, int flags)
13601{
13602 struct iax2_peer *peer = obj;
13603
13605
13606 return 0;
13607}
13608
13609static int user_delme_cb(void *obj, void *arg, int flags)
13610{
13611 struct iax2_user *user = obj;
13612
13614
13615 return 0;
13616}
13617
13618static void delete_users(void)
13619{
13620 struct iax2_registry *reg;
13621
13623
13625 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13626 if (sched) {
13627 AST_SCHED_DEL(sched, reg->expire);
13628 }
13629 if (reg->callno) {
13630 int callno = reg->callno;
13632 if (iaxs[callno]) {
13633 iaxs[callno]->reg = NULL;
13635 }
13637 }
13638 if (reg->dnsmgr)
13640 ast_free(reg);
13641 }
13643
13645}
13646
13647static void prune_users(void)
13648{
13649 struct iax2_user *user;
13650 struct ao2_iterator i;
13651
13652 i = ao2_iterator_init(users, 0);
13653 while ((user = ao2_iterator_next(&i))) {
13656 }
13658 }
13660}
13661
13662/* Prune peers who still are supposed to be deleted */
13663static void prune_peers(void)
13664{
13665 struct iax2_peer *peer;
13666 struct ao2_iterator i;
13667
13668 i = ao2_iterator_init(peers, 0);
13669 while ((peer = ao2_iterator_next(&i))) {
13671 unlink_peer(peer);
13672 }
13673 peer_unref(peer);
13674 }
13676}
13677
13678static void set_config_destroy(void)
13679{
13680 strcpy(accountcode, "");
13681 strcpy(language, "");
13682 strcpy(mohinterpret, "");
13683 strcpy(mohsuggest, "");
13685 amaflags = 0;
13686 delayreject = 0;
13689 delete_users();
13692}
13693
13694/*! \brief Load configuration */
13695static int set_config(const char *config_file, int reload, int forced)
13696{
13697 struct ast_config *cfg, *ucfg;
13698 iax2_format capability;
13699 struct ast_variable *v;
13700 char *cat;
13701 const char *utype;
13702 const char *tosval;
13703 int format;
13704 int portno = IAX_DEFAULT_PORTNO;
13705 int x;
13706 int mtuv;
13707 int subscribe_network_change = 1;
13708 struct iax2_user *user;
13709 struct iax2_peer *peer;
13710 struct ast_netsock *ns;
13711 struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13712 struct ast_sockaddr bindaddr;
13713 struct iax2_codec_pref prefs_new;
13714
13715 cfg = ast_config_load(config_file, config_flags);
13716
13717 if (!cfg) {
13718 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13719 return -1;
13720 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13721 ucfg = ast_config_load("users.conf", config_flags);
13722 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13723 return 0;
13724 /* Otherwise we need to reread both files */
13726 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13727 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13728 ast_config_destroy(ucfg);
13729 return 0;
13730 }
13731 if (!cfg) {
13732 /* should have been able to load the config here */
13733 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13734 return -1;
13735 }
13736 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13737 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13738 return 0;
13739 } else { /* iax.conf changed, gotta reread users.conf, too */
13741 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13742 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13743 ast_config_destroy(cfg);
13744 return 0;
13745 }
13746 }
13747
13748 if (reload) {
13750 }
13751
13752 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
13753
13754 /* Setup new codec prefs */
13756
13757 /* Reset Global Flags */
13758 memset(&globalflags, 0, sizeof(globalflags));
13761
13762#ifdef SO_NO_CHECK
13763 nochecksums = 0;
13764#endif
13765 /* Reset default parking lot */
13766 default_parkinglot[0] = '\0';
13767
13773
13774 maxauthreq = 3;
13775
13776 srvlookup = 0;
13777 iax2_authmethods = 0;
13778
13779 v = ast_variable_browse(cfg, "general");
13780
13781 /* Seed initial tos value */
13782 tosval = ast_variable_retrieve(cfg, "general", "tos");
13783 if (tosval) {
13784 if (ast_str2tos(tosval, &qos.tos))
13785 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13786 }
13787 /* Seed initial cos value */
13788 tosval = ast_variable_retrieve(cfg, "general", "cos");
13789 if (tosval) {
13790 if (ast_str2cos(tosval, &qos.cos))
13791 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13792 }
13793 while(v) {
13794 if (!strcasecmp(v->name, "bindport")) {
13795 if (reload) {
13796 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13797 }
13798 else if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &portno, 1024, 65535)) {
13799 portno = IAX_DEFAULT_PORTNO;
13800 }
13801 } else if (!strcasecmp(v->name, "pingtime")){
13802 ping_time = atoi(v->value);
13803 }
13804 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13805 if (reload) {
13806 if (atoi(v->value) != iaxthreadcount)
13807 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13808 } else {
13809 iaxthreadcount = atoi(v->value);
13810 if (iaxthreadcount < 1) {
13811 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13812 iaxthreadcount = 1;
13813 } else if (iaxthreadcount > 256) {
13814 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13815 iaxthreadcount = 256;
13816 }
13817 }
13818 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13819 if (reload) {
13821 iaxmaxthreadcount = atoi(v->value);
13823 } else {
13824 iaxmaxthreadcount = atoi(v->value);
13825 if (iaxmaxthreadcount < 0) {
13826 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13828 } else if (iaxmaxthreadcount > 256) {
13829 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13830 iaxmaxthreadcount = 256;
13831 }
13832 }
13833 } else if (!strcasecmp(v->name, "nochecksums")) {
13834#ifdef SO_NO_CHECK
13835 if (ast_true(v->value))
13836 nochecksums = 1;
13837 else
13838 nochecksums = 0;
13839#else
13840 if (ast_true(v->value))
13841 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13842#endif
13843 }
13844 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13845 maxjitterbuffer = atoi(v->value);
13846 else if (!strcasecmp(v->name, "resyncthreshold"))
13847 resyncthreshold = atoi(v->value);
13848 else if (!strcasecmp(v->name, "maxjitterinterps"))
13849 maxjitterinterps = atoi(v->value);
13850 else if (!strcasecmp(v->name, "jittertargetextra"))
13851 jittertargetextra = atoi(v->value);
13852 else if (!strcasecmp(v->name, "lagrqtime"))
13853 lagrq_time = atoi(v->value);
13854 else if (!strcasecmp(v->name, "maxregexpire"))
13855 max_reg_expire = atoi(v->value);
13856 else if (!strcasecmp(v->name, "minregexpire"))
13857 min_reg_expire = atoi(v->value);
13858 else if (!strcasecmp(v->name, "bindaddr")) {
13859 if (reload) {
13860 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13861 } else {
13862
13863 if (!ast_parse_arg(v->value, PARSE_ADDR, NULL)) {
13864
13866
13867 if (!ast_sockaddr_port(&bindaddr)) {
13869 }
13870
13871 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13872 ast_log(LOG_WARNING, "Unable to apply binding to '%s' at line %d\n", v->value, v->lineno);
13873 } else {
13874 ast_verb(2, "Binding IAX2 to address %s\n", ast_sockaddr_stringify(&bindaddr));
13875
13876 if (defaultsockfd < 0) {
13878 }
13880 }
13881
13882 } else {
13883 ast_log(LOG_WARNING, "Invalid address '%s' specified, at line %d\n", v->value, v->lineno);
13884 }
13885 }
13886 } else if (!strcasecmp(v->name, "auth")) {
13889 ast_log(LOG_WARNING, "Default auth method is set to deprecated 'plaintext' at line %d of iax.conf\n", v->lineno);
13890 }
13891 } else if (!strcasecmp(v->name, "authdebug")) {
13892 authdebug = ast_true(v->value);
13893 } else if (!strcasecmp(v->name, "encryption")) {
13895 if (!iax2_encryption) {
13897 }
13898 } else if (!strcasecmp(v->name, "forceencryption")) {
13899 if (ast_false(v->value)) {
13901 } else {
13903 if (iax2_encryption) {
13905 }
13906 }
13907 } else if (!strcasecmp(v->name, "transfer")) {
13908 if (!strcasecmp(v->value, "mediaonly")) {
13910 } else if (ast_true(v->value)) {
13912 } else
13914 } else if (!strcasecmp(v->name, "codecpriority")) {
13915 if(!strcasecmp(v->value, "caller"))
13917 else if(!strcasecmp(v->value, "disabled"))
13919 else if(!strcasecmp(v->value, "reqonly")) {
13922 }
13923 } else if (!strcasecmp(v->name, "jitterbuffer"))
13925 else if (!strcasecmp(v->name, "delayreject"))
13927 else if (!strcasecmp(v->name, "allowfwdownload"))
13929 else if (!strcasecmp(v->name, "rtcachefriends"))
13931 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13933 else if (!strcasecmp(v->name, "rtupdate"))
13935 else if (!strcasecmp(v->name, "rtsavesysname"))
13937 else if (!strcasecmp(v->name, "trunktimestamps"))
13939 else if (!strcasecmp(v->name, "rtautoclear")) {
13940 int i = atoi(v->value);
13941 if(i > 0)
13943 else
13944 i = 0;
13946 } else if (!strcasecmp(v->name, "trunkfreq")) {
13947 trunkfreq = atoi(v->value);
13948 if (trunkfreq < 10) {
13949 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13950 trunkfreq = 10;
13951 } else if (trunkfreq > 1000) {
13952 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13953 trunkfreq = 1000;
13954 }
13955 if (timer) {
13957 }
13958 } else if (!strcasecmp(v->name, "trunkmtu")) {
13959 mtuv = atoi(v->value);
13960 if (mtuv == 0 )
13962 else if (mtuv >= 172 && mtuv < 4000)
13963 global_max_trunk_mtu = mtuv;
13964 else
13965 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13966 mtuv, v->lineno);
13967 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13968 trunkmaxsize = atoi(v->value);
13969 if (trunkmaxsize == 0)
13971 } else if (!strcasecmp(v->name, "autokill")) {
13972 if (sscanf(v->value, "%30d", &x) == 1) {
13973 if (x >= 0)
13974 autokill = x;
13975 else
13976 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13977 } else if (ast_true(v->value)) {
13979 } else {
13980 autokill = 0;
13981 }
13982 } else if (!strcasecmp(v->name, "bandwidth")) {
13983 if (!strcasecmp(v->value, "low")) {
13984 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13986 } else if (!strcasecmp(v->value, "medium")) {
13987 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13989 } else if (!strcasecmp(v->value, "high")) {
13990 capability = iax2_codec_pref_from_bitfield(&prefs_new,
13992 } else {
13993 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13994 }
13995 } else if (!strcasecmp(v->name, "allow")) {
13996 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 1);
13997 } else if (!strcasecmp(v->name, "disallow")) {
13998 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 0);
13999 } else if (!strcasecmp(v->name, "register")) {
14000 iax2_register(v->value, v->lineno);
14001 } else if (!strcasecmp(v->name, "iaxcompat")) {
14002 iaxcompat = ast_true(v->value);
14003 } else if (!strcasecmp(v->name, "regcontext")) {
14005 /* Create context if it doesn't exist already */
14007 } else if (!strcasecmp(v->name, "tos")) {
14008 if (ast_str2tos(v->value, &qos.tos))
14009 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
14010 } else if (!strcasecmp(v->name, "cos")) {
14011 if (ast_str2cos(v->value, &qos.cos))
14012 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
14013 } else if (!strcasecmp(v->name, "parkinglot")) {
14015 } else if (!strcasecmp(v->name, "accountcode")) {
14017 } else if (!strcasecmp(v->name, "mohinterpret")) {
14019 } else if (!strcasecmp(v->name, "mohsuggest")) {
14021 } else if (!strcasecmp(v->name, "amaflags")) {
14022 format = ast_channel_string2amaflag(v->value);
14023 if (format < 0) {
14024 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
14025 } else {
14026 amaflags = format;
14027 }
14028 } else if (!strcasecmp(v->name, "language")) {
14029 ast_copy_string(language, v->value, sizeof(language));
14030 } else if (!strcasecmp(v->name, "maxauthreq")) {
14031 maxauthreq = atoi(v->value);
14032 if (maxauthreq < 0)
14033 maxauthreq = 0;
14034 } else if (!strcasecmp(v->name, "adsi")) {
14035 adsi = ast_true(v->value);
14036 } else if (!strcasecmp(v->name, "srvlookup")) {
14037 srvlookup = ast_true(v->value);
14038 } else if (!strcasecmp(v->name, "connectedline")) {
14039 if (ast_true(v->value)) {
14041 } else if (!strcasecmp(v->value, "send")) {
14044 } else if (!strcasecmp(v->value, "receive")) {
14047 } else {
14049 }
14050 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
14051 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
14052 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
14053 }
14054 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
14055 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
14056 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);
14057 }
14058 } else if (!strcasecmp(v->name, "calltokenoptional")) {
14059 if (add_calltoken_ignore(v->value)) {
14060 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
14061 return -1;
14062 }
14063 } else if (!strcasecmp(v->name, "calltokenexpiration")) {
14064 int temp = -1;
14065 sscanf(v->value, "%u", &temp);
14066 if( temp <= 0 ){
14067 ast_log(LOG_WARNING, "Invalid calltokenexpiration value %s. Should be integer greater than 0.\n", v->value);
14068 } else {
14069 max_calltoken_delay = temp;
14070 }
14071 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
14072 if (ast_true(v->value)) {
14073 subscribe_network_change = 1;
14074 } else if (ast_false(v->value)) {
14075 subscribe_network_change = 0;
14076 } else {
14077 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
14078 }
14079 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
14080 if (ast_true(v->value)) {
14082 } else if (ast_false(v->value)) {
14084 } else {
14085 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
14086 }
14087 }/*else if (strcasecmp(v->name,"type")) */
14088 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
14089 v = v->next;
14090 }
14091
14092 if (subscribe_network_change) {
14094 } else {
14096 }
14097
14098 if (defaultsockfd < 0) {
14099
14101
14102 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
14103 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
14104 } else {
14105 ast_verb(2, "Binding IAX2 to default address %s\n", ast_sockaddr_stringify(&bindaddr));
14108 }
14109 }
14110 if (reload) {
14113 if (!outsock) {
14114 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14115 return -1;
14116 }
14118 }
14119
14121 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
14124 }
14125 prefs_global = prefs_new;
14126 iax2_capability = capability;
14127
14128 if (ucfg) {
14129 struct ast_variable *gen;
14130 int genhasiax;
14131 int genregisteriax;
14132 const char *hasiax, *registeriax;
14133
14134 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
14135 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
14136 gen = ast_variable_browse(ucfg, "general");
14137 cat = ast_category_browse(ucfg, NULL);
14138 while (cat) {
14139 if (strcasecmp(cat, "general")) {
14140 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
14141 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
14142 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
14143 /* Start with general parameters, then specific parameters, user and peer */
14144 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
14145 if (user) {
14147 user = user_unref(user);
14148 }
14149 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
14150 if (peer) {
14151 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
14152 reg_source_db(peer);
14153 }
14154 ao2_link(peers, peer);
14155 peer = peer_unref(peer);
14156 }
14157 }
14158 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
14159 char tmp[256];
14160 const char *host = ast_variable_retrieve(ucfg, cat, "host");
14161 const char *username = ast_variable_retrieve(ucfg, cat, "username");
14162 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
14163 if (!host)
14164 host = ast_variable_retrieve(ucfg, "general", "host");
14165 if (!username)
14166 username = ast_variable_retrieve(ucfg, "general", "username");
14167 if (!secret)
14168 secret = ast_variable_retrieve(ucfg, "general", "secret");
14169 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
14170 if (!ast_strlen_zero(secret))
14171 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
14172 else
14173 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
14174 iax2_register(tmp, 0);
14175 }
14176 }
14177 }
14178 cat = ast_category_browse(ucfg, cat);
14179 }
14180 ast_config_destroy(ucfg);
14181 }
14182
14183 cat = ast_category_browse(cfg, NULL);
14184 while(cat) {
14185 if (strcasecmp(cat, "general")) {
14186 utype = ast_variable_retrieve(cfg, cat, "type");
14187 if (!strcasecmp(cat, "callnumberlimits")) {
14189 } else if (utype) {
14190 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
14191 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
14192 if (user) {
14194 user = user_unref(user);
14195 }
14196 }
14197 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
14198 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
14199 if (peer) {
14200 if (ast_test_flag64(peer, IAX_DYNAMIC))
14201 reg_source_db(peer);
14202 ao2_link(peers, peer);
14203 peer = peer_unref(peer);
14204 }
14205 } else if (strcasecmp(utype, "user")) {
14206 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
14207 }
14208 } else
14209 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
14210 }
14211 cat = ast_category_browse(cfg, cat);
14212 }
14213 ast_config_destroy(cfg);
14214 return 1;
14215}
14216
14217static void poke_all_peers(void)
14218{
14219 struct ao2_iterator i;
14220 struct iax2_peer *peer;
14221
14222 i = ao2_iterator_init(peers, 0);
14223 while ((peer = ao2_iterator_next(&i))) {
14224 iax2_poke_peer(peer, 0);
14225 peer_unref(peer);
14226 }
14228}
14229static int reload_config(int forced_reload)
14230{
14231 static const char config[] = "iax.conf";
14232 struct iax2_registry *reg;
14233
14234 if (set_config(config, 1, forced_reload) > 0) {
14235 prune_peers();
14236 prune_users();
14242 memset(&debugaddr, '\0', sizeof(debugaddr));
14243
14246 iax2_do_register(reg);
14248
14249 /* Qualify hosts, too */
14251 }
14252
14255 ast_unload_realtime("iaxpeers");
14256
14257 return 0;
14258}
14259
14260static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14261{
14262 switch (cmd) {
14263 case CLI_INIT:
14264 e->command = "iax2 reload";
14265 e->usage =
14266 "Usage: iax2 reload\n"
14267 " Reloads IAX configuration from iax.conf\n";
14268 return NULL;
14269 case CLI_GENERATE:
14270 return NULL;
14271 }
14272
14273 reload_config(0);
14274
14275 return CLI_SUCCESS;
14276}
14277
14278static int reload(void)
14279{
14280 return reload_config(0);
14281}
14282
14283static int cache_get_callno_locked(const char *data)
14284{
14285 struct ast_sockaddr addr;
14286 int x;
14287 int callno;
14288 struct iax_ie_data ied;
14289 struct create_addr_info cai;
14290 struct parsed_dial_string pds;
14291 char *tmpstr;
14292
14293 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14294 /* Look for an *exact match* call. Once a call is negotiated, it can only
14295 look up entries for a single context */
14296 if (!ast_mutex_trylock(&iaxsl[x])) {
14297 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14298 return x;
14300 }
14301 }
14302
14303 /* No match found, we need to create a new one */
14304
14305 memset(&cai, 0, sizeof(cai));
14306 memset(&ied, 0, sizeof(ied));
14307 memset(&pds, 0, sizeof(pds));
14308
14309 tmpstr = ast_strdupa(data);
14310 parse_dial_string(tmpstr, &pds);
14311
14312 if (ast_strlen_zero(pds.peer)) {
14313 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14314 return -1;
14315 }
14316
14317 /* Populate our address from the given */
14318 if (create_addr(pds.peer, NULL, &addr, &cai))
14319 return -1;
14320
14321 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14322 pds.peer, pds.username, pds.password, pds.context);
14323
14324 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
14325 if (callno < 1) {
14326 ast_log(LOG_WARNING, "Unable to create call\n");
14327 return -1;
14328 }
14329
14330 ast_string_field_set(iaxs[callno], dproot, data);
14332
14335 /* the string format is slightly different from a standard dial string,
14336 because the context appears in the 'exten' position
14337 */
14338 if (pds.exten)
14340 if (pds.username)
14344 /* Keep password handy */
14345 if (pds.password)
14346 ast_string_field_set(iaxs[callno], secret, pds.password);
14347 if (pds.key)
14348 ast_string_field_set(iaxs[callno], outkey, pds.key);
14349 /* Start the call going */
14350 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14351 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14352
14353 return callno;
14354}
14355
14356static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14357{
14358 struct iax2_dpcache *dp = NULL;
14359 struct timeval now = ast_tvnow();
14360 int x, com[2], timeout, doabort, callno;
14361
14362 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14363 if (ast_tvcmp(now, dp->expiry) > 0) {
14364 AST_LIST_REMOVE_CURRENT(cache_list);
14365 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14366 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14367 else
14368 ast_free(dp);
14369 continue;
14370 }
14371 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14372 break;
14373 }
14375
14376 if (!dp) {
14377 /* No matching entry. Create a new one. */
14378 /* First, can we make a callno? */
14379 if ((callno = cache_get_callno_locked(data)) < 0) {
14380 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14381 return NULL;
14382 }
14383 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14384 ast_mutex_unlock(&iaxsl[callno]);
14385 return NULL;
14386 }
14387 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14388 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14389 dp->expiry = ast_tvnow();
14390 dp->orig = dp->expiry;
14391 /* Expires in 30 mins by default */
14392 dp->expiry.tv_sec += iaxdefaultdpcache;
14394 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14395 dp->waiters[x] = -1;
14396 /* Insert into the lists */
14397 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14398 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14399 /* Send the request if we're already up */
14400 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14401 iax2_dprequest(dp, callno);
14402 ast_mutex_unlock(&iaxsl[callno]);
14403 }
14404
14405 /* By here we must have a dp */
14406 if (dp->flags & CACHE_FLAG_PENDING) {
14407 int res;
14408 struct pollfd pfd;
14409 /* Okay, here it starts to get nasty. We need a pipe now to wait
14410 for a reply to come back so long as it's pending */
14411 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14412 /* Find an empty slot */
14413 if (dp->waiters[x] < 0)
14414 break;
14415 }
14416 if (x >= ARRAY_LEN(dp->waiters)) {
14417 ast_log(LOG_WARNING, "No more waiter positions available\n");
14418 return NULL;
14419 }
14420 if (pipe(com)) {
14421 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14422 return NULL;
14423 }
14424 dp->waiters[x] = com[1];
14425 /* Okay, now we wait */
14426 timeout = iaxdefaulttimeout * 1000;
14427 /* Temporarily unlock */
14429 doabort = 0;
14430
14431 /* chan is in autoservice here, so do NOT service it here! */
14432 pfd.fd = com[0];
14433 pfd.events = POLLIN;
14434 pfd.revents = 0;
14435 /* Wait for pipe activity... if the channel hangs up, we'll catch it on the way out. */
14436 res = ast_poll(&pfd, 1, timeout);
14437 if (res < 0) {
14438 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
14439 return NULL;
14440 } else if (!pfd.revents) {
14441 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14442 }
14443
14444 if (chan && ast_check_hangup(chan)) {
14445 doabort = 1;
14446 }
14447
14449 dp->waiters[x] = -1;
14450 close(com[1]);
14451 close(com[0]);
14452 if (doabort) {
14453 /* Don't interpret anything, just abort. */
14454 return NULL;
14455 }
14456 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14457 /* Now to do non-independent analysis the results of our wait */
14458 if (dp->flags & CACHE_FLAG_PENDING) {
14459 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
14460 pending. Don't let it take as long to timeout. */
14461 dp->flags &= ~CACHE_FLAG_PENDING;
14463 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14464 systems without leaving it unavailable once the server comes back online */
14465 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14466 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14467 if (dp->waiters[x] > -1) {
14468 if (write(dp->waiters[x], "asdf", 4) < 0) {
14469 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14470 }
14471 }
14472 }
14473 }
14474 }
14475 /* Our caller will obtain the rest */
14476 }
14477 return dp;
14478}
14479
14480/*! \brief Part of the IAX2 switch interface */
14481static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14482{
14483 int res = 0;
14484 struct iax2_dpcache *dp = NULL;
14485#if 0
14486 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14487#endif
14488 if ((priority != 1) && (priority != 2))
14489 return 0;
14490
14492 if ((dp = find_cache(chan, data, context, exten, priority))) {
14493 if (dp->flags & CACHE_FLAG_EXISTS)
14494 res = 1;
14495 } else {
14496 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14497 }
14499
14500 return res;
14501}
14502
14503/*! \brief part of the IAX2 dial plan switch interface */
14504static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14505{
14506 int res = 0;
14507 struct iax2_dpcache *dp = NULL;
14508#if 0
14509 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14510#endif
14511 if ((priority != 1) && (priority != 2))
14512 return 0;
14513
14515 if ((dp = find_cache(chan, data, context, exten, priority))) {
14516 if (dp->flags & CACHE_FLAG_CANEXIST)
14517 res = 1;
14518 } else {
14519 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14520 }
14522
14523 return res;
14524}
14525
14526/*! \brief Part of the IAX2 Switch interface */
14527static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14528{
14529 int res = 0;
14530 struct iax2_dpcache *dp = NULL;
14531#if 0
14532 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14533#endif
14534 if ((priority != 1) && (priority != 2))
14535 return 0;
14536
14538 if ((dp = find_cache(chan, data, context, exten, priority))) {
14539 if (dp->flags & CACHE_FLAG_MATCHMORE)
14540 res = 1;
14541 } else {
14542 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14543 }
14545
14546 return res;
14547}
14548
14549/*! \brief Execute IAX2 dialplan switch */
14550static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14551{
14552 char odata[256];
14553 char req[sizeof(odata) + AST_MAX_CONTEXT + AST_MAX_EXTENSION + sizeof("IAX2//@")];
14554 char *ncontext;
14555 struct iax2_dpcache *dp = NULL;
14556 struct ast_app *dial = NULL;
14557#if 0
14558 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);
14559#endif
14560 if (priority == 2) {
14561 /* Indicate status, can be overridden in dialplan */
14562 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14563 if (dialstatus) {
14564 dial = pbx_findapp(dialstatus);
14565 if (dial)
14566 pbx_exec(chan, dial, "");
14567 }
14568 return -1;
14569 } else if (priority != 1)
14570 return -1;
14571
14573 if ((dp = find_cache(chan, data, context, exten, priority))) {
14574 if (dp->flags & CACHE_FLAG_EXISTS) {
14575 ast_copy_string(odata, data, sizeof(odata));
14576 ncontext = strchr(odata, '/');
14577 if (ncontext) {
14578 *ncontext = '\0';
14579 ncontext++;
14580 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14581 } else {
14582 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14583 }
14584 ast_verb(3, "Executing Dial('%s')\n", req);
14585 } else {
14587 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14588 return -1;
14589 }
14590 }
14592
14593 if ((dial = pbx_findapp("Dial")))
14594 return pbx_exec(chan, dial, req);
14595 else
14596 ast_log(LOG_WARNING, "No dial application registered\n");
14597
14598 return -1;
14599}
14600
14601static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14602{
14603 struct iax2_peer *peer;
14604 char *peername, *colname;
14605
14606 peername = ast_strdupa(data);
14607
14608 /* if our channel, return the IP address of the endpoint of current channel */
14609 if (!strcmp(peername,"CURRENTCHANNEL")) {
14610 unsigned short callno;
14611 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14612 return -1;
14613 }
14616 return 0;
14617 }
14618
14619 if ((colname = strchr(peername, ',')))
14620 *colname++ = '\0';
14621 else
14622 colname = "ip";
14623
14624 if (!(peer = find_peer(peername, 1)))
14625 return -1;
14626
14627 if (!strcasecmp(colname, "ip")) {
14629 } else if (!strcasecmp(colname, "status")) {
14630 peer_status(peer, buf, len);
14631 } else if (!strcasecmp(colname, "mailbox")) {
14632 ast_copy_string(buf, peer->mailbox, len);
14633 } else if (!strcasecmp(colname, "context")) {
14634 ast_copy_string(buf, peer->context, len);
14635 } else if (!strcasecmp(colname, "expire")) {
14636 snprintf(buf, len, "%d", peer->expire);
14637 } else if (!strcasecmp(colname, "dynamic")) {
14638 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14639 } else if (!strcasecmp(colname, "callerid_name")) {
14641 } else if (!strcasecmp(colname, "callerid_num")) {
14642 ast_copy_string(buf, peer->cid_num, len);
14643 } else if (!strcasecmp(colname, "codecs")) {
14644 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
14645
14646 iax2_getformatname_multiple(peer->capability, &codec_buf);
14647 ast_copy_string(buf, ast_str_buffer(codec_buf), len);
14648 } else if (!strncasecmp(colname, "codec[", 6)) {
14649 char *codecnum, *ptr;
14650 struct ast_format *tmpfmt;
14651
14652 /* skip over "codec" to the '[' */
14653 codecnum = colname + 5;
14654 *codecnum = '\0';
14655 codecnum++;
14656 if ((ptr = strchr(codecnum, ']'))) {
14657 *ptr = '\0';
14658 }
14659 if((iax2_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14661 } else {
14662 buf[0] = '\0';
14663 }
14664 } else {
14665 buf[0] = '\0';
14666 }
14667
14668 peer_unref(peer);
14669
14670 return 0;
14671}
14672
14674 .name = "IAXPEER",
14675 .read = function_iaxpeer,
14676};
14677
14678static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14679{
14680 struct chan_iax2_pvt *pvt;
14681 unsigned int callno;
14682 int res = 0;
14683
14684 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14685 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14686 return -1;
14687 }
14688
14691 if (!(pvt = iaxs[callno])) {
14693 return -1;
14694 }
14695
14696 if (!strcasecmp(args, "osptoken")) {
14697 ast_copy_string(buf, pvt->osptoken, buflen);
14698 } else if (!strcasecmp(args, "peerip")) {
14700 } else if (!strcasecmp(args, "peername")) {
14701 ast_copy_string(buf, pvt->username, buflen);
14702 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14703 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14704 } else {
14705 res = -1;
14706 }
14707
14709
14710 return res;
14711}
14712
14713/*! \brief Part of the device state notification system ---*/
14714static int iax2_devicestate(const char *data)
14715{
14716 struct parsed_dial_string pds;
14717 char *tmp = ast_strdupa(data);
14718 struct iax2_peer *p;
14719 int res = AST_DEVICE_INVALID;
14720
14721 memset(&pds, 0, sizeof(pds));
14722 parse_dial_string(tmp, &pds);
14723
14724 if (ast_strlen_zero(pds.peer)) {
14725 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14726 return res;
14727 }
14728
14729 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14730
14731 /* SLD: FIXME: second call to find_peer during registration */
14732 if (!(p = find_peer(pds.peer, 1)))
14733 return res;
14734
14736
14737 ast_debug(3, "Found peer. What's device state of %s? addr=%s, defaddr=%s maxms=%d, lastms=%d\n",
14739
14740 if (((!ast_sockaddr_isnull(&p->addr)) || (!ast_sockaddr_isnull(&p->defaddr))) &&
14741 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14742 /* Peer is registered, or have default IP address
14743 and a valid registration */
14744 if (p->historicms == 0 || p->historicms <= p->maxms)
14745 /* let the core figure out whether it is in use or not */
14746 res = AST_DEVICE_UNKNOWN;
14747 }
14748
14749 peer_unref(p);
14750
14751 return res;
14752}
14753
14755{
14756 .name = "IAX2",
14757 .description = "IAX Remote Dialplan Switch",
14758 .exists = iax2_exists,
14759 .canmatch = iax2_canmatch,
14760 .exec = iax2_exec,
14761 .matchmore = iax2_matchmore,
14762};
14763
14764static struct ast_cli_entry cli_iax2[] = {
14765 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14766 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14767 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14768 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14769 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14770 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14771 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14772 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14773 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14774 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14775 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14776 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14777 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14778 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14779 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14780 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14781 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14782 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14783 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14784 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14785#ifdef IAXTESTS
14786 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14787 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14788 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14789#endif /* IAXTESTS */
14790};
14791
14792static void cleanup_thread_list(void *head)
14793{
14794 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14795 struct iax2_thread_list *list_head = head;
14796 struct iax2_thread *thread;
14797
14798 AST_LIST_LOCK(list_head);
14799 while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14800 pthread_t thread_id = thread->threadid;
14801
14802 thread->stop = 1;
14803 signal_condition(&thread->lock, &thread->cond);
14804
14805 AST_LIST_UNLOCK(list_head);
14806 pthread_join(thread_id, NULL);
14807 AST_LIST_LOCK(list_head);
14808 }
14809 AST_LIST_UNLOCK(list_head);
14810}
14811
14812static int __unload_module(void)
14813{
14814 int x;
14815
14818
14819 ast_manager_unregister("IAXpeers");
14820 ast_manager_unregister("IAXpeerlist");
14821 ast_manager_unregister("IAXnetstats");
14822 ast_manager_unregister("IAXregistry");
14827
14829 pthread_cancel(netthreadid);
14830 pthread_kill(netthreadid, SIGURG);
14831 pthread_join(netthreadid, NULL);
14832 }
14833
14834 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14835 if (iaxs[x]) {
14836 iax2_destroy(x);
14837 }
14838 }
14839
14840 /* Call for all threads to halt */
14844
14847 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14848 if (iaxs[x]) {
14849 iax2_destroy(x);
14850 }
14851 }
14852 ast_manager_unregister( "IAXpeers" );
14853 ast_manager_unregister( "IAXpeerlist" );
14854 ast_manager_unregister( "IAXnetstats" );
14855 ast_manager_unregister( "IAXregistry" );
14860 delete_users();
14863
14864 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14866 }
14867
14868 ao2_ref(peers, -1);
14869 ao2_ref(users, -1);
14874 if (timer) {
14876 timer = NULL;
14877 }
14879
14882 sched = NULL;
14883 ao2_ref(peercnts, -1);
14884
14886 ast_unload_realtime("iaxpeers");
14887
14890 return 0;
14891}
14892
14893static int unload_module(void)
14894{
14897 return __unload_module();
14898}
14899
14900static int peer_set_sock_cb(void *obj, void *arg, int flags)
14901{
14902 struct iax2_peer *peer = obj;
14903
14904 if (peer->sockfd < 0)
14905 peer->sockfd = defaultsockfd;
14906
14907 return 0;
14908}
14909
14910static int pvt_hash_cb(const void *obj, const int flags)
14911{
14912 const struct chan_iax2_pvt *pvt = obj;
14913
14914 return pvt->peercallno;
14915}
14916
14917static int pvt_cmp_cb(void *obj, void *arg, int flags)
14918{
14919 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14920
14921 /* The frames_received field is used to hold whether we're matching
14922 * against a full frame or not ... */
14923
14924 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14925 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14926}
14927
14928static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14929{
14930 const struct chan_iax2_pvt *pvt = obj;
14931
14932 return pvt->transfercallno;
14933}
14934
14935static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14936{
14937 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14938
14939 /* The frames_received field is used to hold whether we're matching
14940 * against a full frame or not ... */
14941
14942 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14943 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14944}
14945
14946static int load_objects(void)
14947{
14950
14953 if (!peers) {
14954 goto container_fail;
14955 }
14956
14959 if (!users) {
14960 goto container_fail;
14961 }
14962
14965 if (!iax_peercallno_pvts) {
14966 goto container_fail;
14967 }
14968
14972 goto container_fail;
14973 }
14974
14977 if (!peercnts) {
14978 goto container_fail;
14979 }
14980
14983 if (!callno_limits) {
14984 goto container_fail;
14985 }
14986
14989 if (!calltoken_ignores) {
14990 goto container_fail;
14991 }
14992
14993 if (create_callno_pools()) {
14994 goto container_fail;
14995 }
14996
14998 if (!transmit_processor) {
14999 goto container_fail;
15000 }
15001
15002 return 0;
15003
15004container_fail:
15005 if (peers) {
15006 ao2_ref(peers, -1);
15007 }
15008 if (users) {
15009 ao2_ref(users, -1);
15010 }
15011 if (iax_peercallno_pvts) {
15013 }
15016 }
15017 if (peercnts) {
15018 ao2_ref(peercnts, -1);
15019 }
15020 if (callno_limits) {
15022 }
15023 if (calltoken_ignores) {
15025 }
15026 return -1;
15027}
15028
15029/*!
15030 * \brief Load the module
15031 *
15032 * Module loading including tests for configuration or dependencies.
15033 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
15034 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
15035 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
15036 * configuration file or other non-critical problem return
15037 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
15038 */
15039static int load_module(void)
15040{
15041 static const char config[] = "iax.conf";
15042 int x = 0;
15043 struct iax2_registry *reg = NULL;
15044
15047 }
15049
15050 if (load_objects()) {
15054 }
15055
15056 memset(iaxs, 0, sizeof(iaxs));
15057
15058 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
15059 ast_mutex_init(&iaxsl[x]);
15060 }
15061
15062 if (!(sched = ast_sched_context_create())) {
15063 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
15067 }
15068
15073 sched = NULL;
15075 }
15076
15077 if (!(io = io_context_create())) {
15078 ast_log(LOG_ERROR, "Failed to create I/O context\n");
15082 sched = NULL;
15084 }
15085
15086 if (!(netsock = ast_netsock_list_alloc())) {
15087 ast_log(LOG_ERROR, "Failed to create netsock list\n");
15092 sched = NULL;
15094 }
15096
15098 if (!outsock) {
15099 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
15104 sched = NULL;
15106 }
15108
15110
15114
15115 if ((timer = ast_timer_open())) {
15117 }
15118
15119 if (set_config(config, 0, 0) == -1) {
15120 if (timer) {
15122 timer = NULL;
15123 }
15126 }
15127
15129
15131
15134
15139
15141 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15144 }
15145
15147 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15148 }
15149
15150 if (start_network_thread()) {
15151 ast_log(LOG_ERROR, "Unable to start network thread\n");
15154 } else {
15155 ast_verb(2, "IAX Ready and Listening\n");
15156 }
15157
15160 iax2_do_register(reg);
15162
15165
15166
15169
15170 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15171
15173
15175}
15176
15177AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15178 .support_level = AST_MODULE_SUPPORT_CORE,
15179 .load = load_module,
15180 .unload = unload_module,
15181 .reload = reload,
15182 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15183 .requires = "dnsmgr",
15184 .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
static const struct adsi_event events[]
Definition: app_adsiprog.c:88
char digit
static struct ast_generator gen
jack_status_t status
Definition: app_jack.c:149
char * text
Definition: app_queue.c:1809
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
if(!yyg->yy_init)
Definition: ast_expr2f.c:854
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:4494
@ 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 char * tz
Definition: cdr_pgsql.c:71
#define MAX_USER_BUCKETS
Definition: chan_iax2.c:1027
static int timing_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9641
#define IAX_TRUNKTIMESTAMPS
Definition: chan_iax2.c:543
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
Definition: chan_iax2.c:5850
static void set_peercnt_limit(struct peercnt *peercnt)
Definition: chan_iax2.c:2625
static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Definition: chan_iax2.c:7926
static int iaxthreadcount
Definition: chan_iax2.c:744
static int send_ping(const void *data)
Definition: chan_iax2.c:1812
static int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9633
iax2_thread_iostate
Definition: chan_iax2.c:1115
@ IAX_IOSTATE_PROCESSING
Definition: chan_iax2.c:1118
@ IAX_IOSTATE_SCHEDREADY
Definition: chan_iax2.c:1119
@ IAX_IOSTATE_IDLE
Definition: chan_iax2.c:1116
@ IAX_IOSTATE_READY
Definition: chan_iax2.c:1117
static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
callback to display iax peers in manager
Definition: chan_iax2.c:7384
static struct ao2_container * peercnts
Definition: chan_iax2.c:1031
static struct iax2_context * build_context(const char *context)
Definition: chan_iax2.c:12864
static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9809
static struct @116 qos
#define IAX_ALREADYGONE
Definition: chan_iax2.c:531
#define IAX_PROVISION
Definition: chan_iax2.c:532
static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
Definition: chan_iax2.c:9183
static int iax2_write(struct ast_channel *c, struct ast_frame *f)
Definition: chan_iax2.c:7822
#define AUTH_METHOD_NAMES_BUFSIZE
Definition: chan_iax2.c:431
static struct iax2_peer * realtime_peer(const char *peername, struct ast_sockaddr *addr)
Definition: chan_iax2.c:4456
static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd, struct iax_frame *fr)
Definition: chan_iax2.c:10032
static struct iax2_user * user_unref(struct iax2_user *user)
Definition: chan_iax2.c:2111
static int apply_context(struct iax2_context *con, const char *context)
Definition: chan_iax2.c:7915
static struct ast_channel_tech iax2_tech
Definition: chan_iax2.c:1366
static void __auto_hangup(const void *nothing)
Definition: chan_iax2.c:9512
static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:12575
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2160
static char * complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
Definition: chan_iax2.c:3963
static int autokill
Definition: chan_iax2.c:370
static int randomcalltokendata
Definition: chan_iax2.c:1009
static int iaxdynamicthreadcount
Definition: chan_iax2.c:746
static void iax2_lock_owner(int callno)
Definition: chan_iax2.c:1406
static int delayreject
Definition: chan_iax2.c:502
static int iax2_queue_hold(int callno, const char *musicclass)
Queue a hold frame on the ast_channel owner.
Definition: chan_iax2.c:3348
#define MAX_TIMESTAMP_SKEW
Definition: chan_iax2.c:736
static void acl_change_stasis_subscribe(void)
Definition: chan_iax2.c:1541
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2471
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:5945
static void jb_error_output(const char *fmt,...)
Definition: chan_iax2.c:1281
static int peer_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2034
@ NEW_PREVENT
Definition: chan_iax2.c:2377
@ NEW_ALLOW
Definition: chan_iax2.c:2379
@ NEW_FORCE
Definition: chan_iax2.c:2381
@ NEW_ALLOW_CALLTOKEN_VALIDATED
Definition: chan_iax2.c:2384
static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
Definition: chan_iax2.c:8891
static int replace_callno(const void *obj)
Definition: chan_iax2.c:3054
#define CALLNO_ENTRY_IS_VALIDATED(a)
Definition: chan_iax2.c:979
static int auto_congest(const void *data)
Definition: chan_iax2.c:4834
static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
Definition: chan_iax2.c:6144
static void __iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12534
static int iax2_predestroy(int callno)
Definition: chan_iax2.c:3508
static int update_packet(struct iax_frame *f)
Definition: chan_iax2.c:3593
static int iaxcompat
Definition: chan_iax2.c:371
static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
Definition: chan_iax2.c:6399
static char * handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3712
static int peercnt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2531
static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
Definition: chan_iax2.c:9780
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
Definition: chan_iax2.c:5483
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
Definition: chan_iax2.c:7910
static void unwrap_timestamp(struct iax_frame *fr)
Definition: chan_iax2.c:4145
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:5464
static int iax2_hangup(struct ast_channel *c)
Definition: chan_iax2.c:5416
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:2243
static int __schedule_action(void(*func)(const void *data), const void *data, const char *funcname)
Definition: chan_iax2.c:1724
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2547
static int maxjitterbuffer
Definition: chan_iax2.c:359
static int auth_fail(int callno, int failcode)
Definition: chan_iax2.c:9497
static char * handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3773
#define PEERS_FORMAT2
Definition: chan_iax2.c:6981
#define PTR_TO_CALLNO(a)
Definition: chan_iax2.c:316
unsigned int tos
Definition: chan_iax2.c:379
static int iax2_queue_hangup(int callno)
Queue a hangup frame on the ast_channel owner.
Definition: chan_iax2.c:3394
static int peercnt_remove_cb(const void *obj)
Definition: chan_iax2.c:2780
static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
Definition: chan_iax2.c:6173
static unsigned char compress_subclass(iax2_format subclass)
Definition: chan_iax2.c:1885
static int handle_error(void)
Definition: chan_iax2.c:3427
#define IAX_TRUNK
Definition: chan_iax2.c:525
static const char * auth_method_labels[]
Name of effective auth method.
Definition: chan_iax2.c:423
static int peer_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2045
static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
Definition: chan_iax2.c:4907
static int get_auth_methods(const char *value)
Definition: chan_iax2.c:12874
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:5029
static struct chan_iax2_pvt * new_iax(struct ast_sockaddr *addr, const char *host)
Definition: chan_iax2.c:2315
static char default_parkinglot[AST_MAX_CONTEXT]
Definition: chan_iax2.c:346
static struct iax2_trunk_peer * find_tpeer(struct ast_sockaddr *addr, int fd)
Definition: chan_iax2.c:6363
static void iax_error_output(const char *data)
Definition: chan_iax2.c:1276
static void vnak_retransmit(int callno, int last)
Definition: chan_iax2.c:9559
static int user_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13609
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7905
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
Definition: chan_iax2.c:14678
static struct ast_custom_function iaxvar_function
Definition: chan_iax2.c:10237
#define IAX_SHRINKCALLERID
Definition: chan_iax2.c:552
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:9923
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.
Definition: chan_iax2.c:14550
static int __unload_module(void)
Definition: chan_iax2.c:14812
static char * handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7723
static struct stasis_subscription * acl_change_sub
Definition: chan_iax2.c:352
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
Definition: chan_iax2.c:12584
static iax2_format iax2_capability
Definition: chan_iax2.c:483
#define DEFAULT_MAX_THREAD_COUNT
Definition: chan_iax2.c:320
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)]
chan_iax2_pvt structure locks
Definition: chan_iax2.c:1236
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
Definition: chan_iax2.c:4418
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL
Definition: chan_iax2.c:1041
static struct ast_sched_context * sched
Definition: chan_iax2.c:481
static void * dp_lookup_thread(void *data)
Definition: chan_iax2.c:9751
static uint16_t DEFAULT_MAXCALLNO_LIMIT
Definition: chan_iax2.c:1039
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
Definition: chan_iax2.c:2675
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
Definition: chan_iax2.c:3461
static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
Definition: chan_iax2.c:9409
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7870
static void encmethods_to_str(int e, struct ast_str **buf)
Definition: chan_iax2.c:1822
static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
Definition: chan_iax2.c:9793
static struct ast_custom_function iaxpeer_function
Definition: chan_iax2.c:14673
static int load_objects(void)
Definition: chan_iax2.c:14946
static int complete_transfer(int callno, struct iax_ies *ies)
Definition: chan_iax2.c:8830
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
Definition: chan_iax2.c:4440
static struct ast_format * codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Definition: chan_iax2.c:1919
static int prune_addr_range_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2664
static void iax_debug_output(const char *data)
Definition: chan_iax2.c:1270
#define IAX_CALLENCRYPTED(pvt)
Definition: chan_iax2.c:464
static char * handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:12495
static uint16_t global_maxcallno_nonval
Definition: chan_iax2.c:1046
static int maxjitterinterps
Definition: chan_iax2.c:361
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
Definition: chan_iax2.c:4315
#define IAX_ENCRYPTED
Definition: chan_iax2.c:534
static void jb_debug_output(const char *fmt,...)
Definition: chan_iax2.c:1305
#define IAX_CODEC_NOCAP
Definition: chan_iax2.c:538
static int ping_time
Definition: chan_iax2.c:357
static void iax_pvt_callid_new(int callno)
Definition: chan_iax2.c:1210
static char * regstate2str(int regstate)
Definition: chan_iax2.c:7445
static int last_authmethod
Definition: chan_iax2.c:372
#define IAX_NOTRANSFER
Definition: chan_iax2.c:526
static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
Definition: chan_iax2.c:7085
#define IAX_IMMEDIATE
Definition: chan_iax2.c:548
static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
Definition: chan_iax2.c:5191
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:4032
static int trunk_untimed
Definition: chan_iax2.c:342
static void pvt_destructor(void *obj)
Definition: chan_iax2.c:2268
static int addr_range_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2517
static int pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14910
static int iax2_queue_unhold(int callno)
Queue an unhold frame on the ast_channel owner.
Definition: chan_iax2.c:3371
#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:339
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
Definition: chan_iax2.c:2117
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.
Definition: chan_iax2.c:13013
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:3310
static void * iax2_process_thread(void *data)
Definition: chan_iax2.c:12207
static int iax2_digit_begin(struct ast_channel *c, char digit)
Definition: chan_iax2.c:4413
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.
Definition: chan_iax2.c:13338
static char regcontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:349
static int socket_process_helper(struct iax2_thread *thread)
Definition: chan_iax2.c:10264
#define IAX_CAPABILITY_FULLBANDWIDTH
Definition: chan_iax2.c:397
static struct ao2_container * peers
Definition: chan_iax2.c:1025
static int set_config(const char *config_file, int reload, int forced)
Load configuration.
Definition: chan_iax2.c:13695
static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8749
static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
Definition: chan_iax2.c:6984
static void __auto_congest(const void *nothing)
Definition: chan_iax2.c:4821
#define IAX_HASCALLERID
Definition: chan_iax2.c:522
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
Definition: chan_iax2.c:2220
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:7851
#define MARK_IAX_SUBCLASS_TX
Definition: chan_iax2.c:742
static int iax2_key_rotate(const void *vpvt)
Definition: chan_iax2.c:5578
#define schedule_action(func, data)
Definition: chan_iax2.c:1749
static int invalid_key(ast_aes_decrypt_key *ecx)
Definition: chan_iax2.c:6482
static int user_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2068
static void __expire_registry(const void *data)
Definition: chan_iax2.c:9079
static void reg_source_db(struct iax2_peer *p)
Definition: chan_iax2.c:9129
static int scheduled_destroy(const void *vid)
Definition: chan_iax2.c:2208
static void prune_peers(void)
Definition: chan_iax2.c:13663
static time_t max_calltoken_delay
Definition: chan_iax2.c:1011
static struct ao2_container * callno_limits
Definition: chan_iax2.c:1034
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
Definition: chan_iax2.c:2566
static struct ast_frame * iax2_read(struct ast_channel *c)
Definition: chan_iax2.c:5572
static struct ast_netsock_list * netsock
Definition: chan_iax2.c:390
static int min_reg_expire
Definition: chan_iax2.c:383
static int add_calltoken_ignore(const char *addr)
Definition: chan_iax2.c:2867
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:8582
@ CACHE_FLAG_TIMEOUT
Definition: chan_iax2.c:1084
@ CACHE_FLAG_EXISTS
Definition: chan_iax2.c:1076
@ CACHE_FLAG_UNKNOWN
Definition: chan_iax2.c:1088
@ CACHE_FLAG_MATCHMORE
Definition: chan_iax2.c:1090
@ CACHE_FLAG_CANEXIST
Definition: chan_iax2.c:1080
@ CACHE_FLAG_PENDING
Definition: chan_iax2.c:1082
@ CACHE_FLAG_NONEXISTENT
Definition: chan_iax2.c:1078
@ CACHE_FLAG_TRANSMITTED
Definition: chan_iax2.c:1086
#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:7357
static int iax2_transfer(struct ast_channel *c, const char *dest)
Definition: chan_iax2.c:5903
static int iax2_transmit(struct iax_frame *fr)
Definition: chan_iax2.c:4406
#define IAX_SENDANI
Definition: chan_iax2.c:529
struct iax_frame * last
Definition: chan_iax2.c:1005
static void __auth_reject(const void *nothing)
Definition: chan_iax2.c:9463
static int adsi
Definition: chan_iax2.c:501
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6504
iax2_thread_type
Definition: chan_iax2.c:1122
@ IAX_THREAD_TYPE_DYNAMIC
Definition: chan_iax2.c:1124
@ IAX_THREAD_TYPE_POOL
Definition: chan_iax2.c:1123
#define CALLNO_ENTRY_GET_CALLNO(a)
Definition: chan_iax2.c:980
static int iax2_getpeertrunk(struct ast_sockaddr addr)
Definition: chan_iax2.c:5923
static int attempt_transmit(const void *data)
Definition: chan_iax2.c:3703
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
Definition: chan_iax2.c:6615
static struct ast_netsock_list * outsock
Definition: chan_iax2.c:391
static void prune_users(void)
Definition: chan_iax2.c:13647
#define DEFAULT_CONTEXT
Definition: chan_iax2.c:344
static void user_destructor(void *obj)
Definition: chan_iax2.c:13324
static struct ao2_container * iax_transfercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1243
static struct iax2_user * find_user(const char *name)
Definition: chan_iax2.c:2106
static int resyncthreshold
Definition: chan_iax2.c:360
#define IAX_RECVCONNECTEDLINE
Definition: chan_iax2.c:550
static void register_peer_exten(struct iax2_peer *peer, int onoff)
Definition: chan_iax2.c:9041
static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14935
#define MAX_RETRY_TIME
Definition: chan_iax2.c:729
static int iaxdynamicthreadnum
Definition: chan_iax2.c:747
static ast_mutex_t callno_pool_lock
Definition: chan_iax2.c:988
#define TRUNK_CALL_START
Definition: chan_iax2.c:1247
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7895
#define MAX_TRUNKDATA
Definition: chan_iax2.c:364
static int trunk_maxmtu
Definition: chan_iax2.c:342
#define DEFAULT_FREQ_OK
Definition: chan_iax2.c:419
static void free_context(struct iax2_context *con)
Definition: chan_iax2.c:12665
static char * handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7550
#define CALLNO_ENTRY_SET_VALIDATED(a)
Definition: chan_iax2.c:978
static uint16_t total_nonval_callno_used
Definition: chan_iax2.c:1048
static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8783
#define IAX_DEBUGDIGEST(msg, key)
Definition: chan_iax2.c:467
static const char tdesc[]
Definition: chan_iax2.c:334
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:5131
static int global_rtautoclear
Definition: chan_iax2.c:553
static void iax2_destroy(int callno)
Definition: chan_iax2.c:3531
static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7337
static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
Definition: chan_iax2.c:9762
#define CALLNO_TO_PTR(a)
Definition: chan_iax2.c:317
static struct iax_frame * iaxfrdup2(struct iax_frame *fr)
Definition: chan_iax2.c:2358
static int transmit_frame(void *data)
Definition: chan_iax2.c:4379
static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
Definition: chan_iax2.c:10187
static int iax2_answer(struct ast_channel *c)
Definition: chan_iax2.c:5843
static int iax2_authmethods
Definition: chan_iax2.c:504
static const char * iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
Definition: chan_iax2.c:1987
static void set_hangup_source_and_cause(int callno, unsigned char causecode)
Definition: chan_iax2.c:10243
#define IAX_RTUPDATE
Definition: chan_iax2.c:540
#define IAX_QUELCH
Definition: chan_iax2.c:533
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
Definition: chan_iax2.c:14504
static void __send_ping(const void *data)
Definition: chan_iax2.c:1788
static struct iax2_peer * find_peer(const char *name, int realtime)
Definition: chan_iax2.c:2081
static char * handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7700
#define MIN_RETRY_TIME
Definition: chan_iax2.c:728
static int iaxactivethreadcount
Definition: chan_iax2.c:748
static int check_srcaddr(struct ast_sockaddr *addr)
Check if address can be used as packet source.
Definition: chan_iax2.c:12892
#define IAX_MAXAUTHREQ
Definition: chan_iax2.c:545
static void insert_idle_thread(struct iax2_thread *thread)
Definition: chan_iax2.c:1642
static void acl_change_stasis_unsubscribe(void)
Definition: chan_iax2.c:1551
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:2387
static int pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14917
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:8504
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition: chan_iax2.c:1569
static int iaxdefaulttimeout
Definition: chan_iax2.c:376
static struct ao2_container * users
Definition: chan_iax2.c:1028
static int auth_reject(const void *data)
Definition: chan_iax2.c:9483
static int create_callno_pools(void)
Definition: chan_iax2.c:3093
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:2230
#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:4073
#define IAX_FORCE_ENCRYPT
Definition: chan_iax2.c:551
static char * handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:14260
static void network_change_stasis_subscribe(void)
Definition: chan_iax2.c:1526
static struct ast_switch iax2_switch
Definition: chan_iax2.c:14754
iax_transfer_state
Definition: chan_iax2.c:695
@ TRANSFER_MEDIA
Definition: chan_iax2.c:705
@ TRANSFER_NONE
Definition: chan_iax2.c:696
@ TRANSFER_MPASSTHROUGH
Definition: chan_iax2.c:704
@ TRANSFER_MEDIAPASS
Definition: chan_iax2.c:706
@ TRANSFER_PASSTHROUGH
Definition: chan_iax2.c:700
@ TRANSFER_MRELEASED
Definition: chan_iax2.c:703
@ TRANSFER_BEGIN
Definition: chan_iax2.c:697
@ TRANSFER_MREADY
Definition: chan_iax2.c:702
@ TRANSFER_READY
Definition: chan_iax2.c:698
@ TRANSFER_MBEGIN
Definition: chan_iax2.c:701
@ TRANSFER_RELEASED
Definition: chan_iax2.c:699
static void poke_all_peers(void)
Definition: chan_iax2.c:14217
#define IAX_SENDCONNECTEDLINE
Definition: chan_iax2.c:549
static int(* iax2_regfunk)(const char *username, int onoff)
Definition: chan_iax2.c:394
static int network_change_sched_cb(const void *data)
Definition: chan_iax2.c:1556
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:3306
static int __do_deliver(void *data)
Definition: chan_iax2.c:3412
#define IAX_RTCACHEFRIENDS
Definition: chan_iax2.c:539
#define IAX_RTIGNOREREGEXPIRE
Definition: chan_iax2.c:542
static char * papp
Definition: chan_iax2.c:12461
static int socket_process(struct iax2_thread *thread)
Definition: chan_iax2.c:12185
static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7508
static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
Definition: chan_iax2.c:9719
static int iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12563
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
Definition: chan_iax2.c:2977
static char * handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:2908
static char * handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3986
static int authdebug
Definition: chan_iax2.c:369
static struct ast_taskprocessor * transmit_processor
Definition: chan_iax2.c:1007
static int iaxdefaultdpcache
Definition: chan_iax2.c:374
static int trunk_nmaxmtu
Definition: chan_iax2.c:342
static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:14601
#define DEFAULT_MAXMS
Definition: chan_iax2.c:418
static struct @117 frame_queue[IAX_MAX_CALLS]
a list of frames that may need to be retransmitted
static int send_lagrq(const void *data)
Definition: chan_iax2.c:1876
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...
Definition: chan_iax2.c:12915
static int reload_config(int forced_reload)
Definition: chan_iax2.c:14229
static int peercnt_add(struct ast_sockaddr *addr)
Definition: chan_iax2.c:2703
static int iax2_do_register(struct iax2_registry *reg)
Definition: chan_iax2.c:12353
static int iax2_register(const char *value, int lineno)
Definition: chan_iax2.c:9005
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
Definition: chan_iax2.c:4430
static struct ast_timer * timer
Definition: chan_iax2.c:388
static void __send_lagrq(const void *data)
Definition: chan_iax2.c:1852
static void unlink_peer(struct iax2_peer *peer)
Definition: chan_iax2.c:9060
static int authenticate_request(int call_num)
Definition: chan_iax2.c:8196
static struct iax2_peer * peer_unref(struct iax2_peer *peer)
Definition: chan_iax2.c:2100
static int iax2_append_register(const char *hostname, const char *username, const char *secret, const char *porta)
Definition: chan_iax2.c:8963
static int maxauthreq
Definition: chan_iax2.c:355
static int firmware_show_callback(struct ast_iax2_firmware_header *header, void *user_data)
Definition: chan_iax2.c:7344
static int get_from_jb(const void *p)
Definition: chan_iax2.c:4300
static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9820
static int max_reg_expire
Definition: chan_iax2.c:384
iax_reg_state
Definition: chan_iax2.c:685
@ REG_STATE_REGSENT
Definition: chan_iax2.c:687
@ REG_STATE_TIMEOUT
Definition: chan_iax2.c:691
@ REG_STATE_AUTHSENT
Definition: chan_iax2.c:688
@ REG_STATE_NOAUTH
Definition: chan_iax2.c:692
@ REG_STATE_REGISTERED
Definition: chan_iax2.c:689
@ REG_STATE_REJECTED
Definition: chan_iax2.c:690
@ REG_STATE_UNREGISTERED
Definition: chan_iax2.c:686
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
Definition: chan_iax2.c:5555
static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
Definition: chan_iax2.c:6188
#define ACN_FORMAT1
#define DEFAULT_RETRY_TIME
Definition: chan_iax2.c:321
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
peer_status: Report Peer status in character string
Definition: chan_iax2.c:3864
static void set_config_destroy(void)
Definition: chan_iax2.c:13678
static int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
Definition: chan_iax2.c:3157
#define IAX_RTSAVE_SYSNAME
Definition: chan_iax2.c:530
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
Definition: chan_iax2.c:1953
static int iax2_delete_from_sched(const void *data)
Definition: chan_iax2.c:2149
static int lagrq_time
Definition: chan_iax2.c:358
static char * handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7796
#define DEFAULT_FREQ_NOTOK
Definition: chan_iax2.c:420
static void update_jbsched(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:4180
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2490
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2650
static int trunkmaxsize
Definition: chan_iax2.c:367
static void handle_deferred_full_frames(struct iax2_thread *thread)
Handle any deferred full frames for this thread.
Definition: chan_iax2.c:9893
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
Definition: chan_iax2.c:7616
static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14928
static int test_losspct
Definition: chan_iax2.c:489
static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition: chan_iax2.c:6654
static int srvlookup
Definition: chan_iax2.c:386
static void iax_pvt_callid_set(int callno, ast_callid callid)
Definition: chan_iax2.c:1205
static void __get_from_jb(const void *p)
Definition: chan_iax2.c:4197
static int iax2_encryption
Definition: chan_iax2.c:503
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
Definition: chan_iax2.c:2794
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:6562
static struct call_number_pool callno_pool
Definition: chan_iax2.c:991
static pthread_t netthreadid
Definition: chan_iax2.c:508
#define CALLNO_ENTRY_TO_PTR(a)
Definition: chan_iax2.c:976
static int trunkfreq
Definition: chan_iax2.c:366
static void build_rand_pad(unsigned char *buf, ssize_t len)
Definition: chan_iax2.c:6472
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
Definition: chan_iax2.c:1183
static char * handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7770
static char * handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7467
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data)
Definition: chan_iax2.c:1758
static int socket_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9954
static int peer_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13600
static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
Definition: chan_iax2.c:4705
static char * auth_method_names(int authmethods, char *restrict buf)
Get names of all auth methods.
Definition: chan_iax2.c:439
static int user_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2057
static void peer_destructor(void *obj)
Definition: chan_iax2.c:12985
static void __iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8722
#define IAX_USEJITTERBUF
Definition: chan_iax2.c:527
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:4869
static void jb_warning_output(const char *fmt,...)
Definition: chan_iax2.c:1293
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.
Definition: chan_iax2.c:14481
calltoken_peer_enum
Call token validation settings.
Definition: chan_iax2.c:560
@ CALLTOKEN_DEFAULT
Default calltoken required unless the ip is in the ignorelist.
Definition: chan_iax2.c:562
@ CALLTOKEN_AUTO
Require call token validation after a successful registration using call token validation occurs.
Definition: chan_iax2.c:567
@ CALLTOKEN_NO
Do not require call token validation.
Definition: chan_iax2.c:569
@ CALLTOKEN_YES
Require call token validation.
Definition: chan_iax2.c:564
static int get_encrypt_methods(const char *s)
Definition: chan_iax2.c:1838
static int jittertargetextra
Definition: chan_iax2.c:362
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.
Definition: chan_iax2.c:14527
static struct ast_flags64 globalflags
Definition: chan_iax2.c:506
static struct iax2_dpcache * find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
Definition: chan_iax2.c:14356
static iax2_format uncompress_subclass(unsigned char csub)
Definition: chan_iax2.c:1905
static void * network_thread(void *ignore)
Definition: chan_iax2.c:12792
static char * handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7312
static int iax2_is_control_frame_allowed(int subtype)
Definition: chan_iax2.c:1430
static void network_change_stasis_unsubscribe(void)
Definition: chan_iax2.c:1536
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
Definition: chan_iax2.c:4663
static struct io_context * io
Definition: chan_iax2.c:480
static int trunk_timed
Definition: chan_iax2.c:342
static char * complete_iax2_unregister(const char *line, const char *word, int pos, int state)
Definition: chan_iax2.c:7287
static struct stasis_subscription * network_change_sub
Definition: chan_iax2.c:351
static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
Definition: chan_iax2.c:8159
#define PTR_TO_CALLNO_ENTRY(a)
Definition: chan_iax2.c:975
static struct ao2_container * calltoken_ignores
Definition: chan_iax2.c:1037
static void * iax2_dup_variable_datastore(void *)
Definition: chan_iax2.c:1600
static struct iax2_codec_pref prefs_global
Definition: chan_iax2.c:332
iax2_state
Definition: chan_iax2.c:510
@ IAX_STATE_TBD
Definition: chan_iax2.c:513
@ IAX_STATE_AUTHENTICATED
Definition: chan_iax2.c:512
@ IAX_STATE_STARTED
Definition: chan_iax2.c:511
static struct iax2_user * realtime_user(const char *username, struct ast_sockaddr *addr)
Definition: chan_iax2.c:4588
#define IAX2_TRUNK_PREFACE
Definition: chan_iax2.c:662
static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
Acknowledgment received for OUR registration.
Definition: chan_iax2.c:8897
static void __iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9572
static int load_module(void)
Load the module.
Definition: chan_iax2.c:15039
static int iax2_vnak(int callno)
Definition: chan_iax2.c:9554
#define IAX_CAPABILITY_MEDBANDWIDTH
Definition: chan_iax2.c:399
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
Definition: chan_iax2.c:2001
#define DEFAULT_TRUNKDATA
Definition: chan_iax2.c:734
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:3887
static void iax2_process_thread_cleanup(void *data)
Definition: chan_iax2.c:12195
#define IAX_TRANSFERMEDIA
Definition: chan_iax2.c:544
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
Definition: chan_iax2.c:4435
#define IAX_KEYPOPULATED
Definition: chan_iax2.c:535
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2523
#define IAX_RTAUTOCLEAR
Definition: chan_iax2.c:541
static int registry_authrequest(int callno)
Definition: chan_iax2.c:9361
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
Definition: chan_iax2.c:12414
#define FORMAT
const char * iax2_getformatname(iax2_format format)
iax2 wrapper function for ast_getformatname
Definition: chan_iax2.c:1975
#define DEFAULT_THREAD_COUNT
Definition: chan_iax2.c:319
static int iaxdebug
Definition: chan_iax2.c:485
static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:10158
static void iax2_free_variable_datastore(void *)
Definition: chan_iax2.c:1624
uint16_t callno_entry
Definition: chan_iax2.c:764
static int iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9579
static int addr_range_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2510
static struct iax2_thread * find_idle_thread(void)
Definition: chan_iax2.c:1657
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)
Definition: chan_iax2.c:12675
#define IAX_DYNAMIC
Definition: chan_iax2.c:528
static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
Definition: chan_iax2.c:4897
static int max_retries
Definition: chan_iax2.c:356
static void delete_users(void)
Definition: chan_iax2.c:13618
#define MIN_REUSE_TIME
Definition: chan_iax2.c:327
#define FORMAT2
#define IAX_TEMPONLY
Definition: chan_iax2.c:524
#define IAX_DELAYPBXSTART
Definition: chan_iax2.c:546
static int cache_get_callno_locked(const char *data)
Definition: chan_iax2.c:14283
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:1252
static int unload_module(void)
Definition: chan_iax2.c:14893
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2481
static struct chan_iax2_pvt * iaxs[IAX_MAX_CALLS]
an array of iax2 pvt structures
Definition: chan_iax2.c:1198
static int reload(void)
Definition: chan_iax2.c:14278
static int peer_set_sock_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14900
static int amaflags
Definition: chan_iax2.c:500
static void stop_stuff(int callno)
Definition: chan_iax2.c:9458
static char * handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:6896
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9590
static void log_jitterstats(unsigned short callno)
Definition: chan_iax2.c:9850
static struct iax2_peer * peer_ref(struct iax2_peer *peer)
Definition: chan_iax2.c:2094
static ast_callid iax_pvt_callid_get(int callno)
Definition: chan_iax2.c:1200
#define IAX_CAPABILITY_LOWBANDWIDTH
Definition: chan_iax2.c:409
static void cleanup_thread_list(void *head)
Definition: chan_iax2.c:14792
static int iaxtrunkdebug
Definition: chan_iax2.c:487
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:7406
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:3325
static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
Definition: chan_iax2.c:8247
static int iax2_sendtext(struct ast_channel *c, const char *text)
Definition: chan_iax2.c:4423
static struct ast_sockaddr debugaddr
Definition: chan_iax2.c:1250
static int send_packet(struct iax_frame *f)
Definition: chan_iax2.c:3474
static char language[MAX_LANGUAGE]
Definition: chan_iax2.c:348
static char accountcode[AST_MAX_ACCOUNT_CODE]
Definition: chan_iax2.c:497
static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
Definition: chan_iax2.c:8175
static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
Definition: chan_iax2.c:6514
static char * handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7246
#define IAX_ALLOWFWDOWNLOAD
Definition: chan_iax2.c:547
#define IAX_CODEC_USER_FIRST
Definition: chan_iax2.c:536
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:1770
static struct call_number_pool callno_pool_trunk
Definition: chan_iax2.c:994
static uint16_t global_maxcallno
Definition: chan_iax2.c:1043
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2500
#define CALLTOKEN_HASH_FORMAT
#define IAX_DELME
Definition: chan_iax2.c:523
static int start_network_thread(void)
Definition: chan_iax2.c:12817
#define PEERS_FORMAT
Definition: chan_iax2.c:6982
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
Definition: chan_iax2.c:6323
unsigned int cos
Definition: chan_iax2.c:380
callno_type
Definition: chan_iax2.c:970
@ CALLNO_TYPE_TRUNK
Definition: chan_iax2.c:972
@ CALLNO_TYPE_NORMAL
Definition: chan_iax2.c:971
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:1752
static char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:499
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:3180
static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6498
static void build_callno_limits(struct ast_variable *v)
Definition: chan_iax2.c:2812
static void __attempt_transmit(const void *data)
Definition: chan_iax2.c:3620
static struct ast_cli_entry cli_iax2[]
Definition: chan_iax2.c:14764
static unsigned int iax2_datetime(const char *tz)
Definition: chan_iax2.c:4843
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:6682
#define IAX_CODEC_NOPREFS
Definition: chan_iax2.c:537
static int auto_hangup(const void *data)
Definition: chan_iax2.c:9527
static char * handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7177
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition: chan_iax2.c:1583
static char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:498
static const struct ast_datastore_info iax2_variable_datastore_info
Definition: chan_iax2.c:1594
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
Definition: chan_iax2.c:3126
static int iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8740
static int iax2_devicestate(const char *data)
Part of the device state notification system —.
Definition: chan_iax2.c:14714
static void peercnt_remove(struct peercnt *peercnt)
Definition: chan_iax2.c:2754
static int network_change_sched_id
Definition: chan_iax2.c:353
static int expire_registry(const void *data)
Definition: chan_iax2.c:9120
#define MAX_PEER_BUCKETS
Definition: chan_iax2.c:1023
static void iax2_frame_free(struct iax_frame *fr)
Definition: chan_iax2.c:2202
static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
Definition: chan_iax2.c:6538
static void requirecalltoken_mark_auto(const char *name, int subclass)
Definition: chan_iax2.c:4989
static int defaultsockfd
Definition: chan_iax2.c:392
static int iaxmaxthreadcount
Definition: chan_iax2.c:745
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2541
static struct ao2_container * iax_peercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1227
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7881
static int make_trunk(unsigned short callno, int locked)
Definition: chan_iax2.c:2405
static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Verify inbound registration.
Definition: chan_iax2.c:8342
static int global_max_trunk_mtu
Definition: chan_iax2.c:341
static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
Definition: chan_iax2.c:9542
static const char type[]
Definition: chan_ooh323.c:109
struct ast_sockaddr bindaddr
Definition: chan_ooh323.c:353
static char version[AST_MAX_EXTENSION]
Definition: chan_ooh323.c:391
static const char config[]
Definition: chan_ooh323.c:111
static int transfer(void *data)
Definition: chan_pjsip.c:2133
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:2414
void ast_hangup(struct ast_channel *chan)
Hang up a channel.
Definition: channel.c:2570
#define AST_BRIDGE_DTMF_CHANNEL_0
Report DTMF on channel 0.
Definition: channel.h:2418
#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:1169
int ast_party_id_presentation(const struct ast_party_id *id)
Determine the overall presentation value for the given party.
Definition: channel.c:1848
#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:2099
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:3185
#define ast_channel_lock(chan)
Definition: channel.h:2970
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
@ AST_CHAN_TP_WANTSJITTER
Channels have this property if they can accept input with jitter; i.e. most VoIP channels.
Definition: channel.h:980
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:570
struct ast_flags * ast_channel_flags(struct ast_channel *chan)
#define ast_channel_ref(c)
Increase channel reference count.
Definition: channel.h:2995
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:1158
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:5161
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4274
#define AST_BRIDGE_DTMF_CHANNEL_1
Report DTMF on channel 1.
Definition: channel.h:2420
#define ast_channel_trylock(chan)
Definition: channel.h:2972
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:1265
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:7355
int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
Sets read format on channel chan.
Definition: channel.c:5779
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:8811
int ast_check_hangup(struct ast_channel *chan)
Check to see if a channel is needing hang up.
Definition: channel.c:445
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:1611
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:2528
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:4363
int ast_queue_unhold(struct ast_channel *chan)
Queue an unhold frame.
Definition: channel.c:1243
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:1218
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:539
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:3006
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
@ AST_FLAG_DISABLE_DEVSTATE_CACHE
Definition: channel.h:1049
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition: channel.c:5820
#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:2049
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:4377
const struct ast_channel_tech * ast_channel_tech(const struct ast_channel *chan)
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:2971
#define AST_MAX_EXTENSION
Definition: channel.h:134
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:2428
struct ast_format * ast_channel_readformat(struct ast_channel *chan)
@ AST_SOFTHANGUP_DEV
Definition: channel.h:1141
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
Definition: channelstate.h:35
@ AST_STATE_RING
Definition: channelstate.h:40
@ AST_STATE_RINGING
Definition: channelstate.h:41
@ AST_STATE_DOWN
Definition: channelstate.h:36
@ AST_STATE_RESERVED
Definition: channelstate.h:37
int ast_setstate(struct ast_channel *chan, enum ast_channel_state)
Change the state of a channel.
Definition: channel.c:7407
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:2471
Standard Command Line Interface.
#define CLI_SHOWUSAGE
Definition: cli.h:45
#define CLI_SUCCESS
Definition: cli.h:44
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Definition: clicompat.c:30
#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:1853
@ 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_aes_set_encrypt_key(const unsigned char *key, ast_aes_encrypt_key *ctx)
Set an encryption key.
Definition: res_crypto.c:700
struct ast_key * ast_key_get(const char *kname, int ktype)
Retrieve a key.
Definition: res_crypto.c:149
#define AST_KEY_PUBLIC
Definition: crypto.h:46
#define AST_KEY_PRIVATE
Definition: crypto.h:47
int 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_aes_encrypt(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *key)
AES encrypt data.
Definition: res_crypto.c:749
int ast_aes_decrypt(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *key)
AES decrypt data.
Definition: res_crypto.c:790
int 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_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
#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.
Definition: devicestate.c:513
@ 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:71
char connected
Definition: eagi_proxy.c:82
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.
void ast_verbose(const char *fmt,...)
Definition: extconf.c:2206
#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.
Definition: format_cache.c:41
struct ast_format * ast_format_none
Built-in "null" format.
Definition: format_cache.c:246
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:2028
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:2064
const char * astman_get_header(const struct message *m, char *var)
Get header from manager transaction.
Definition: manager.c:1647
void astman_send_list_complete_end(struct mansession *s)
End the list complete event.
Definition: manager.c:2072
void astman_append(struct mansession *s, const char *fmt,...)
Definition: manager.c:1907
int ast_manager_unregister(const char *action)
Unregister a registered manager command.
Definition: manager.c:7697
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)
Definition: chan_iax2.c:12466
const char * ext
Definition: http.c:150
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:3326
int ast_realtime_require_field(const char *family,...) attribute_sentinel
Inform realtime what fields that may be stored.
Definition: main/config.c:3769
@ CONFIG_FLAG_FILEUNCHANGED
#define ast_variable_new(name, value, filename)
int ast_unload_realtime(const char *family)
Release any resources cached for a realtime family.
Definition: main/config.c:3796
#define CONFIG_STATUS_FILEUNCHANGED
#define CONFIG_STATUS_FILEINVALID
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
Definition: main/config.c:4047
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
Definition: extconf.c:1289
int ast_variable_list_replace(struct ast_variable **head, struct ast_variable *replacement)
Replace a variable in the given list with a new value.
Definition: main/config.c:753
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
Definition: main/config.c:869
int ast_update_realtime(const char *family, const char *keyfield, const char *lookup,...) attribute_sentinel
Update realtime configuration.
Definition: main/config.c:3879
struct ast_variable * ast_load_realtime(const char *family,...) attribute_sentinel
Definition: main/config.c:3726
@ PARSE_PORT_REQUIRE
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition: extconf.c:1262
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition: extconf.c:1215
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_control_transfer
@ 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
#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_VIDEO
@ AST_FRAME_NULL
@ AST_FRAME_HTML
@ AST_FRAME_IMAGE
@ AST_FRAME_DTMF_END
@ AST_FRAME_DTMF_BEGIN
@ AST_FRAME_VOICE
@ AST_FRAME_CONTROL
@ AST_FRAME_TEXT
ast_control_frame_type
Internal control frame subtype field values.
@ AST_CONTROL_RING
@ AST_CONTROL_SRCUPDATE
@ AST_CONTROL_RECORD_CANCEL
@ AST_CONTROL_WINK
@ 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_BUSY
@ 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_MCID
@ AST_CONTROL_T38_PARAMETERS
@ AST_CONTROL_READ_ACTION
@ AST_CONTROL_RECORD_STOP
@ AST_CONTROL_CONGESTION
@ AST_CONTROL_CC
@ AST_CONTROL_ANSWER
@ AST_CONTROL_RECORD_MUTE
@ AST_CONTROL_RINGING
@ AST_CONTROL_HANGUP
@ AST_CONTROL_STREAM_STOP
@ AST_CONTROL_RADIO_KEY
@ AST_CONTROL_HOLD
@ 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_AOC
@ 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
@ AST_FRFLAG_HAS_TIMING_INFO
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:2263
#define ast_debug(level,...)
Log a DEBUG message.
ast_callid ast_read_threadstorage_callid(void)
extracts the callerid from the thread
Definition: logger.c:2273
int ast_callid_threadassoc_add(ast_callid callid)
Adds a known callid to thread storage of the calling thread.
Definition: logger.c:2295
#define AST_CALLID_BUFFER_LENGTH
ast_callid ast_create_callid(void)
factory function to create a new uniquely identifying callid.
Definition: logger.c:2268
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:2314
#define LOG_ERROR
#define ast_verb(level,...)
#define LOG_NOTICE
#define LOG_WARNING
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.
Definition: linkedlists.h:681
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:291
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
Definition: linkedlists.h:225
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
Definition: linkedlists.h:429
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:491
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
Definition: linkedlists.h:653
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:731
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:410
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
Definition: linkedlists.h:626
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
Definition: linkedlists.h:615
#define AST_LIST_INSERT_BEFORE_CURRENT(elm, field)
Inserts a list entry before the current entry during a traversal.
Definition: linkedlists.h:599
#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.
Definition: linkedlists.h:711
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
Definition: linkedlists.h:856
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
Definition: linkedlists.h:529
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:557
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:833
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:140
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
Definition: linkedlists.h:173
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:206
#define ast_cond_wait(cond, mutex)
Definition: lock.h:209
#define AST_PTHREADT_NULL
Definition: lock.h:70
#define ast_cond_init(cond, attr)
Definition: lock.h:205
#define ast_cond_timedwait(cond, mutex, time)
Definition: lock.h:210
#define ast_mutex_init(pmutex)
Definition: lock.h:190
#define DEADLOCK_AVOIDANCE(lock)
Definition: lock.h:483
#define ast_mutex_unlock(a)
Definition: lock.h:194
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:761
#define ast_mutex_trylock(a)
Definition: lock.h:195
pthread_cond_t ast_cond_t
Definition: lock.h:182
#define ast_mutex_destroy(a)
Definition: lock.h:192
#define ast_mutex_lock(a)
Definition: lock.h:193
#define AST_MUTEX_DEFINE_STATIC(mutex)
Definition: lock.h:524
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:771
#define ast_cond_signal(cond)
Definition: lock.h:207
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:192
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:392
@ 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:7787
void ast_moh_stop(struct ast_channel *chan)
Turn off music on hold on a given channel.
Definition: channel.c:7797
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
meta
below block is needed for mssql
Definition: cdr/env.py:22
def ignore(key=None, val=None, section=None, pjsip=None, nmapped=None, type='endpoint')
Definition: sip_to_pjsip.py:48
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
@ AST_AF_UNSPEC
Definition: netsock2.h:54
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:928
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:1351
#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:1296
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:1229
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:1352
#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:1350
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:170
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:6943
int ast_context_destroy_by_name(const char *context, const char *registrar)
Destroy a context by name.
Definition: pbx.c:8220
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:4190
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:6164
int pbx_exec(struct ast_channel *c, struct ast_app *app, const char *data)
Execute an application.
Definition: pbx_app.c:471
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:4963
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1559
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:4205
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:4723
int ast_ignore_pattern(const char *context, const char *pattern)
Checks to see if a number should be ignored.
Definition: pbx.c:6894
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:4210
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
static void * cleanup(void *unused)
Definition: pbx_realtime.c:124
#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 char user[512]
struct stasis_forward * sub
Definition: res_corosync.c:240
static struct @453 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.
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.
struct stasis_message_type * stasis_message_type(const struct stasis_message *msg)
Get the message type for a stasis_message.
@ 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:1050
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:1104
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:836
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:1161
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.
Definition: stasis_cache.c:686
#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.
Definition: stringfields.h:341
#define AST_STRING_FIELD(name)
Declare a string field.
Definition: stringfields.h:303
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:521
#define ast_string_field_init(x, size)
Initialize a field pool and fields.
Definition: stringfields.h:359
#define ast_string_field_build(x, field, fmt, args...)
Set a field to a complex (built) value.
Definition: stringfields.h:555
#define ast_string_field_free_memory(x)
free all memory - to be called before destroying the object
Definition: stringfields.h:374
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
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:761
#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:2199
#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:2446
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:2216
#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:1818
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
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:730
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
Definition: md5.h:30
struct ast_ha ha
Definition: chan_iax2.c:1067
unsigned char delme
Definition: chan_iax2.c:1071
uint16_t limit
Definition: chan_iax2.c:1069
Definition: crypto.h:39
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
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
char chan_name[AST_CHANNEL_NAME]
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:204
Structure used to handle boolean flags.
Definition: utils.h:199
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.
union ast_frame::@228 data
struct ast_frame_subclass subclass
struct timeval delivery
enum ast_frame_type frametype
struct ast_frame * next
const char * src
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:139
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
struct ast_party_dialed::@210 number
Dialed/Called number.
char * str
Subscriber phone number (Malloced)
Definition: channel.h:388
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:163
A ast_taskprocessor structure is a singleton by name.
Definition: taskprocessor.c:69
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::@213 entries
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
size_t available
Definition: chan_iax2.c:984
callno_entry numbers[IAX_MAX_CALLS/2+1]
Definition: chan_iax2.c:985
unsigned char semirand[32]
Definition: chan_iax2.c:905
int frames_dropped
Definition: chan_iax2.c:952
const ast_string_field mohinterpret
Definition: chan_iax2.c:886
int first_iax_message
Definition: chan_iax2.c:790
struct ast_sockaddr addr
Definition: chan_iax2.c:800
struct ast_variable * vars
Definition: chan_iax2.c:944
const ast_string_field language
Definition: chan_iax2.c:886
int frames_received
Definition: chan_iax2.c:954
int calling_ani2
Definition: chan_iax2.c:940
const ast_string_field cid_num
Definition: chan_iax2.c:886
struct chan_iax2_pvt::signaling_queue signaling_queue
iax2_format svideoformat
Definition: chan_iax2.c:778
unsigned int lastsent
Definition: chan_iax2.c:784
const ast_string_field inkeys
Definition: chan_iax2.c:886
const ast_string_field outkey
Definition: chan_iax2.c:886
unsigned int nextpred
Definition: chan_iax2.c:788
iax2_format capability
Definition: chan_iax2.c:780
struct chan_iax2_pvt::@122 dpentries
int destroy_initiated
Definition: chan_iax2.c:956
unsigned int pingtime
Definition: chan_iax2.c:796
const ast_string_field dproot
Definition: chan_iax2.c:886
const ast_string_field mohsuggest
Definition: chan_iax2.c:886
unsigned short bridgecallno
Definition: chan_iax2.c:929
const ast_string_field accountcode
Definition: chan_iax2.c:886
const ast_string_field username
Definition: chan_iax2.c:886
iax2_format peercapability
Definition: chan_iax2.c:819
struct ast_variable * iaxvars
Definition: chan_iax2.c:946
struct ast_flags state
Definition: chan_iax2.c:835
unsigned int notsilenttx
Definition: chan_iax2.c:794
unsigned int lastvsent
Definition: chan_iax2.c:786
ast_callid callid
Definition: chan_iax2.c:770
unsigned char iseqno
Definition: chan_iax2.c:843
char hold_signaling
Definition: chan_iax2.c:960
struct timeval rxcore
Definition: chan_iax2.c:823
struct ast_sockaddr transfer
Definition: chan_iax2.c:919
iax2_format voiceformat
Definition: chan_iax2.c:772
const ast_string_field context
Definition: chan_iax2.c:886
unsigned short peercallno
Definition: chan_iax2.c:810
struct iax2_codec_pref prefs
Definition: chan_iax2.c:802
unsigned short callno
Definition: chan_iax2.c:806
unsigned char calltoken_ie_len
Definition: chan_iax2.c:958
const ast_string_field parkinglot
Definition: chan_iax2.c:886
iax2_format videoformat
Definition: chan_iax2.c:774
unsigned char rseqno
Definition: chan_iax2.c:841
const ast_string_field host
Definition: chan_iax2.c:886
callno_entry callno_entry
Definition: chan_iax2.c:808
uint64_t flags
Definition: chan_iax2.c:911
unsigned short transfercallno
Definition: chan_iax2.c:921
struct ast_channel * owner
Definition: chan_iax2.c:833
const ast_string_field rdnis
Definition: chan_iax2.c:886
unsigned char oseqno
Definition: chan_iax2.c:839
struct timeval offset
Definition: chan_iax2.c:821
unsigned char aseqno
Definition: chan_iax2.c:845
iax2_format svoiceformat
Definition: chan_iax2.c:776
int calling_pres
Definition: chan_iax2.c:939
const ast_string_field challenge
Definition: chan_iax2.c:886
const ast_string_field exten
Definition: chan_iax2.c:886
ast_aes_decrypt_key dcx
Definition: chan_iax2.c:900
struct iax_rr remote_rr
Definition: chan_iax2.c:948
unsigned int last
Definition: chan_iax2.c:782
ast_aes_encrypt_key tdcx
Definition: chan_iax2.c:923
const ast_string_field ani
Definition: chan_iax2.c:886
iax2_format peerformat
Definition: chan_iax2.c:817
struct iax2_codec_pref rprefs
Definition: chan_iax2.c:804
jitterbuf * jb
Definition: chan_iax2.c:825
struct iax2_registry * reg
Definition: chan_iax2.c:907
ast_aes_decrypt_key mydcx
Definition: chan_iax2.c:898
const ast_string_field cid_name
Definition: chan_iax2.c:886
enum iax_transfer_state transferring
Definition: chan_iax2.c:915
int last_iax_message
Definition: chan_iax2.c:792
int eff_auth_method
Definition: chan_iax2.c:892
const ast_string_field secret
Definition: chan_iax2.c:886
ast_aes_encrypt_key ecx
Definition: chan_iax2.c:896
const ast_string_field dnid
Definition: chan_iax2.c:886
const ast_string_field osptoken
Definition: chan_iax2.c:886
struct iax2_peer * peerpoke
Definition: chan_iax2.c:909
const ast_string_field peer
Definition: chan_iax2.c:886
iax2_format chosenformat
Definition: chan_iax2.c:815
char outkey[80]
Definition: chan_iax2.c:4695
iax2_format capability
Definition: chan_iax2.c:4684
char username[80]
Definition: chan_iax2.c:4693
char cid_num[80]
Definition: chan_iax2.c:4697
struct iax2_codec_pref prefs
Definition: chan_iax2.c:4686
uint64_t flags
Definition: chan_iax2.c:4685
char timezone[80]
Definition: chan_iax2.c:4696
char secret[80]
Definition: chan_iax2.c:4694
char cid_name[80]
Definition: chan_iax2.c:4698
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4699
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4700
char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:4702
char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:4701
char context[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9714
char callednum[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9715
char * callerid
Definition: chan_iax2.c:9716
Definition: file.c:69
char order[IAX2_CODEC_PREF_SIZE]
Definition: codec_pref.h:36
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:517
struct iax2_context * next
Definition: chan_iax2.c:518
struct iax2_dpcache::@125 peer_list
int waiters[256]
Definition: chan_iax2.c:1100
struct timeval expiry
Definition: chan_iax2.c:1097
char exten[AST_MAX_EXTENSION]
Definition: chan_iax2.c:1095
unsigned short callno
Definition: chan_iax2.c:1099
struct iax2_dpcache::@124 cache_list
struct timeval orig
Definition: chan_iax2.c:1096
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:1094
const ast_string_field peercontext
Definition: chan_iax2.c:623
const ast_string_field mohinterpret
Definition: chan_iax2.c:623
int pokefreqok
Definition: chan_iax2.c:648
struct ast_sockaddr addr
Definition: chan_iax2.c:626
int callno
Definition: chan_iax2.c:643
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:625
const ast_string_field cid_num
Definition: chan_iax2.c:623
const ast_string_field inkeys
Definition: chan_iax2.c:623
const ast_string_field outkey
Definition: chan_iax2.c:623
struct ast_mwi_subscriber * mwi_event_sub
Definition: chan_iax2.c:654
int expire
Definition: chan_iax2.c:638
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:657
iax2_format capability
Definition: chan_iax2.c:640
int pokefreqnotok
Definition: chan_iax2.c:649
int historicms
Definition: chan_iax2.c:650
int authmethods
Definition: chan_iax2.c:635
const ast_string_field regexten
Definition: chan_iax2.c:623
const ast_string_field mohsuggest
Definition: chan_iax2.c:623
const ast_string_field username
Definition: chan_iax2.c:623
int lastms
Definition: chan_iax2.c:645
const ast_string_field zonetag
Definition: chan_iax2.c:623
int adsi
Definition: chan_iax2.c:630
struct ast_sockaddr defaddr
Definition: chan_iax2.c:634
uint16_t maxcallno
Definition: chan_iax2.c:652
const ast_string_field description
Definition: chan_iax2.c:623
const ast_string_field context
Definition: chan_iax2.c:623
struct iax2_codec_pref prefs
Definition: chan_iax2.c:624
const ast_string_field parkinglot
Definition: chan_iax2.c:623
uint64_t flags
Definition: chan_iax2.c:631
const ast_string_field dbsecret
Definition: chan_iax2.c:623
struct ast_sockaddr mask
Definition: chan_iax2.c:629
int encmethods
Definition: chan_iax2.c:636
struct ast_endpoint * endpoint
Definition: chan_iax2.c:659
int pokeexpire
Definition: chan_iax2.c:644
int formats
Definition: chan_iax2.c:627
struct ast_acl_list * acl
Definition: chan_iax2.c:656
int expiry
Definition: chan_iax2.c:639
const ast_string_field name
Definition: chan_iax2.c:623
const ast_string_field cid_name
Definition: chan_iax2.c:623
int maxms
Definition: chan_iax2.c:646
int sockfd
Definition: chan_iax2.c:628
int smoothing
Definition: chan_iax2.c:651
const ast_string_field secret
Definition: chan_iax2.c:623
const ast_string_field mailbox
Definition: chan_iax2.c:623
unsigned char buf[1]
Definition: chan_iax2.c:1130
size_t len
Definition: chan_iax2.c:1129
struct iax2_pkt_buf::@126 entry
struct ast_sockaddr addr
Definition: chan_iax2.c:710
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:719
char hostname[]
Definition: chan_iax2.c:722
enum iax_reg_state regstate
Definition: chan_iax2.c:715
char username[80]
Definition: chan_iax2.c:711
char secret[80]
Definition: chan_iax2.c:712
struct ast_sockaddr us
Definition: chan_iax2.c:718
struct iax2_registry::@121 entry
struct ast_sockaddr addr
Definition: chan_iax2.c:1164
unsigned char readbuf[4096]
Definition: chan_iax2.c:1148
ast_cond_t cond
Definition: chan_iax2.c:1155
ast_cond_t init_cond
Definition: chan_iax2.c:1157
time_t checktime
Definition: chan_iax2.c:1153
unsigned char stop
Definition: chan_iax2.c:1172
unsigned char csub
Definition: chan_iax2.c:1166
struct iax2_thread::@128 ffinfo
pthread_t threadid
Definition: chan_iax2.c:1145
unsigned short callno
Definition: chan_iax2.c:1163
unsigned char type
Definition: chan_iax2.c:1165
struct ast_sockaddr ioaddr
Definition: chan_iax2.c:1147
struct iax2_thread::@127 list
ast_mutex_t init_lock
Definition: chan_iax2.c:1156
unsigned char * buf
Definition: chan_iax2.c:1149
enum iax2_thread_iostate iostate
Definition: chan_iax2.c:1136
ast_mutex_t lock
Definition: chan_iax2.c:1154
const void * scheddata
Definition: chan_iax2.c:1139
size_t buf_size
Definition: chan_iax2.c:1151
enum iax2_thread_type type
Definition: chan_iax2.c:1135
void(* schedfunc)(const void *)
Definition: chan_iax2.c:1138
struct iax2_thread::@129 full_frames
char curfunc[80]
Definition: chan_iax2.c:1142
ssize_t buf_len
Definition: chan_iax2.c:1150
struct ast_sockaddr addr
Definition: chan_iax2.c:667
struct timeval lasttxtime
Definition: chan_iax2.c:670
unsigned int lastsent
Definition: chan_iax2.c:672
struct timeval rxtrunktime
Definition: chan_iax2.c:669
struct iax2_trunk_peer::@120 list
unsigned int trunkdataalloc
Definition: chan_iax2.c:676
unsigned int trunkdatalen
Definition: chan_iax2.c:675
unsigned char * trunkdata
Definition: chan_iax2.c:674
struct timeval trunkact
Definition: chan_iax2.c:671
ast_mutex_t lock
Definition: chan_iax2.c:665
struct timeval txtrunktime
Definition: chan_iax2.c:668
const ast_string_field mohinterpret
Definition: chan_iax2.c:585
struct ast_variable * vars
Definition: chan_iax2.c:598
const ast_string_field language
Definition: chan_iax2.c:585
const ast_string_field cid_num
Definition: chan_iax2.c:585
const ast_string_field inkeys
Definition: chan_iax2.c:585
struct iax2_context * contexts
Definition: chan_iax2.c:597
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:599
iax2_format capability
Definition: chan_iax2.c:592
int authmethods
Definition: chan_iax2.c:587
const ast_string_field mohsuggest
Definition: chan_iax2.c:585
const ast_string_field accountcode
Definition: chan_iax2.c:585
int adsi
Definition: chan_iax2.c:590
struct iax2_codec_pref prefs
Definition: chan_iax2.c:595
const ast_string_field parkinglot
Definition: chan_iax2.c:585
uint64_t flags
Definition: chan_iax2.c:591
const ast_string_field dbsecret
Definition: chan_iax2.c:585
int encmethods
Definition: chan_iax2.c:588
int maxauthreq
Definition: chan_iax2.c:593
int curauthreq
Definition: chan_iax2.c:594
struct ast_acl_list * acl
Definition: chan_iax2.c:596
const ast_string_field name
Definition: chan_iax2.c:585
const ast_string_field cid_name
Definition: chan_iax2.c:585
int amaflags
Definition: chan_iax2.c:589
const ast_string_field secret
Definition: chan_iax2.c:585
unsigned char semirand[32]
Definition: parser.h:138
unsigned short dcallno
Definition: parser.h:102
struct iax_frame::@139 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
int pos
Definition: parser.h:151
unsigned char buf[1024]
Definition: parser.h:150
Definition: parser.h:27
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:757
int losscnt
Definition: chan_iax2.c:753
int delay
Definition: chan_iax2.c:755
int losspct
Definition: chan_iax2.c:752
int dropped
Definition: chan_iax2.c:756
int jitter
Definition: chan_iax2.c:751
int packets
Definition: chan_iax2.c:754
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:327
Number structure.
Definition: app_followme.c:157
struct ast_sockaddr addr
Definition: chan_iax2.c:1054
unsigned char reg
Definition: chan_iax2.c:1061
uint16_t limit
Definition: chan_iax2.c:1058
uint16_t cur
Definition: chan_iax2.c:1056
Scheduler ID holder.
Definition: sched.c:70
Definition: sched.c:76
char idtext[256]
Definition: chan_iax2.c:6972
Definition: chan_iax2.c:965
struct ast_frame f
Definition: chan_iax2.c:966
struct signaling_queue_entry * next
Definition: chan_iax2.c:967
structure to hold users read from 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
Definition: taskprocessor.h:76
int ast_taskprocessor_push(struct ast_taskprocessor *tps, int(*task_exe)(void *datap), void *datap) attribute_warn_unused_result
Push a task into the specified taskprocessor queue and signal the taskprocessor thread.
Test Framework API.
int done
Definition: test_amihooks.c:48
const char * args
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:2282
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition: extconf.c:2297
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:1402
int error(const char *format,...)
Definition: utils/frame.c:999
Utility functions.
#define ast_test_flag(p, flag)
Definition: utils.h:63
#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:941
#define ast_set2_flag64(p, value, flag)
Definition: utils.h:151
#define ast_test_flag64(p, flag)
Definition: utils.h:120
#define ast_assert(a)
Definition: utils.h:739
#define ast_set_flags_to64(p, flag, value)
Definition: utils.h:161
#define ast_clear_flag64(p, flag)
Definition: utils.h:134
#define MIN(a, b)
Definition: utils.h:231
#define ast_pthread_create_background(a, b, c, d)
Definition: utils.h:592
#define ast_assert_return(a,...)
Definition: utils.h:740
#define ast_clear_flag(p, flag)
Definition: utils.h:77
long int ast_random(void)
Definition: utils.c:2312
#define ast_pthread_create_detached(a, b, c, d)
Definition: utils.h:588
#define ast_copy_flags64(dest, src, flagz)
Definition: utils.h:141
#define ast_set_flag64(p, flag)
Definition: utils.h:127
#define ast_set_flag(p, flag)
Definition: utils.h:70
#define ARRAY_LEN(a)
Definition: utils.h:666
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition: utils.c:266