Debian Codegraph @

channels/chan_iax2.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 <[email protected]>
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"
93 #include "asterisk/musiconhold.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"
99 #include "asterisk/devicestate.h"
100 #include "asterisk/stringfields.h"
101 #include "asterisk/linkedlists.h"
102 #include "asterisk/astobj2.h"
103 #include "asterisk/timing.h"
104 #include "asterisk/taskprocessor.h"
105 #include "asterisk/test.h"
106 #include "asterisk/security_events.h"
107 #include "asterisk/stasis_endpoints.h"
108 #include "asterisk/bridge.h"
109 #include "asterisk/stasis.h"
110 #include "asterisk/stasis_system.h"
111 #include "asterisk/stasis_channels.h"
112 #include "asterisk/format_cache.h"
113 #include "asterisk/format_compatibility.h"
114 #include "asterisk/format_cap.h"
115
116 #include "iax2/include/iax2.h"
117 #include "iax2/include/firmware.h"
118 #include "iax2/include/parser.h"
119 #include "iax2/include/provision.h"
120 #include "iax2/include/codec_pref.h"
121 #include "iax2/include/format_compatibility.h"
122 #include "iax2/include/netsock.h"
123
124 #include "jitterbuf.h"
125
126 /*** DOCUMENTATION
127 <application name="IAX2Provision" language="en_US">
128 <since>
129 <version>1.6.1.0</version>
130 </since>
131 <synopsis>
132 Provision a calling IAXy with a given template.
133 </synopsis>
134 <syntax>
135 <parameter name="template">
136 <para>If not specified, defaults to <literal>default</literal>.</para>
137 </parameter>
138 </syntax>
139 <description>
140 <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
141 given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
142 or <literal>0</literal> on success.</para>
143 </description>
144 </application>
145 <function name="IAXPEER" language="en_US">
146 <since>
147 <version>1.2.0</version>
148 </since>
149 <synopsis>
150 Gets IAX peer information.
151 </synopsis>
152 <syntax>
153 <parameter name="peername" required="true">
154 <enumlist>
155 <enum name="CURRENTCHANNEL">
156 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
157 endpoint of the current channel</para>
158 </enum>
159 </enumlist>
160 </parameter>
161 <parameter name="item">
162 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
163 <enumlist>
164 <enum name="ip">
165 <para>(default) The IP address.</para>
166 </enum>
167 <enum name="status">
168 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
169 </enum>
170 <enum name="mailbox">
171 <para>The configured mailbox.</para>
172 </enum>
173 <enum name="context">
174 <para>The configured context.</para>
175 </enum>
176 <enum name="expire">
177 <para>The epoch time of the next expire.</para>
178 </enum>
179 <enum name="dynamic">
180 <para>Is it dynamic? (yes/no).</para>
181 </enum>
182 <enum name="callerid_name">
183 <para>The configured Caller ID name.</para>
184 </enum>
185 <enum name="callerid_num">
186 <para>The configured Caller ID number.</para>
187 </enum>
188 <enum name="codecs">
189 <para>The configured codecs.</para>
190 </enum>
191 <enum name="codec[x]">
192 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
193 with <literal>0</literal>)</para>
194 </enum>
195 </enumlist>
196 </parameter>
197 </syntax>
198 <description>
199 <para>Gets information associated with the specified IAX2 peer.</para>
200 </description>
201 </function>
202 <function name="IAXVAR" language="en_US">
203 <since>
204 <version>1.6.0</version>
205 </since>
206 <synopsis>
207 Sets or retrieves a remote variable.
208 </synopsis>
209 <syntax>
210 <parameter name="varname" required="true" />
211 </syntax>
212 <description>
213 <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
214 </description>
215 </function>
216 <info name="CHANNEL" language="en_US" tech="IAX">
217 <enumlist>
218 <enum name="osptoken">
219 <para>R/O Get the peer's osptoken.</para>
220 </enum>
221 <enum name="peerip">
222 <para>R/O Get the peer's ip address.</para>
223 </enum>
224 <enum name="peername">
225 <para>R/O Get the peer's username.</para>
226 </enum>
227 <enum name="auth_method">
228 <para>R/O Get the authentication method used for the call.</para>
229 <enumlist>
230 <enum name="none"/>
231 <enum name="plaintext"/>
232 <enum name="MD5"/>
233 <enum name="RSA"/>
234 </enumlist>
235 </enum>
236 <enum name="secure_signaling">
237 <para>R/O Get if the IAX channel is secured (encryption used for the call).</para>
238 <para>Because IAX encryption applies to both signaling and media, this setting
239 provides the same value as <literal>secure_media</literal>.</para>
240 </enum>
241 <enum name="secure_media">
242 <para>R/O Get if the IAX channel is secured (encryption used for the call).</para>
243 <para>Because IAX encryption applies to both signaling and media, this setting
244 provides the same value as <literal>secure_signaling</literal>.</para>
245 </enum>
246 </enumlist>
247 </info>
248 <info name="Dial_Resource" language="en_US" tech="IAX2">
249 <para>The general syntax is:</para>
250 <para><literal>Dial(IAX2/[username[:password[:pubkey]]@]peer[:port][/exten[@context]][/options]</literal></para>
251 <para>The IAX username is optionally followed by either the secret or name of the keypair to use for RSA
252 authentication (within square brakcets). If both need to be provided (such as for encrypted calls that
253 are RSA authenticated), both may be specified in either order.</para>
254 <para>IAX2 optionally allows modifiers to be specified after the extension.</para>
255 <enumlist>
256 <enum name="a">
257 <para>Request auto answer (supporting equipment/configuration required)</para>
258 </enum>
259 </enumlist>
260 </info>
261 <manager name="IAXpeers" language="en_US">
262 <since>
263 <version>0.3.0</version>
264 </since>
265 <synopsis>
266 List IAX peers.
267 </synopsis>
268 <syntax>
269 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
270 </syntax>
271 <description>
272 </description>
273 </manager>
274 <manager name="IAXpeerlist" language="en_US">
275 <since>
276 <version>1.6.0</version>
277 </since>
278 <synopsis>
279 List IAX Peers.
280 </synopsis>
281 <syntax>
282 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
283 </syntax>
284 <description>
285 <para>List all the IAX peers.</para>
286 </description>
287 </manager>
288 <manager name="IAXnetstats" language="en_US">
289 <since>
290 <version>1.2.0</version>
291 </since>
292 <synopsis>
293 Show IAX Netstats.
294 </synopsis>
295 <syntax />
296 <description>
297 <para>Show IAX channels network statistics.</para>
298 </description>
299 </manager>
300 <manager name="IAXregistry" language="en_US">
301 <since>
302 <version>1.6.2.0</version>
303 </since>
304 <synopsis>
305 Show IAX registrations.
306 </synopsis>
307 <syntax>
308 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
309 </syntax>
310 <description>
311 <para>Show IAX registrations.</para>
312 </description>
313 </manager>
314 ***/
315
316 /* Define SCHED_MULTITHREADED to run the scheduler in a special
317 multithreaded mode. */
318 #define SCHED_MULTITHREADED
319
320 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
321 thread is actually doing. */
322 #define DEBUG_SCHED_MULTITHREAD
323
324
325 #ifdef SO_NO_CHECK
326 static int nochecksums = 0;
327 #endif
328
329 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
330 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
331
332 #define DEFAULT_THREAD_COUNT 10
333 #define DEFAULT_MAX_THREAD_COUNT 100
334 #define DEFAULT_RETRY_TIME 1000
335 #define MEMORY_SIZE 100
336 #define DEFAULT_DROP 3
337
338 #define DEBUG_SUPPORT
339
340 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
341
342 /* Sample over last 100 units to determine historic jitter */
343 #define GAMMA (0.01)
344
345 static struct iax2_codec_pref prefs_global;
346
347 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
348
349
350 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
351 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
352 #define MAX_TRUNK_MTU 1240
353
354 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
355 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
356
357 #define DEFAULT_CONTEXT "default"
358
359 static char default_parkinglot[AST_MAX_CONTEXT];
360
361 static char language[MAX_LANGUAGE] = "";
362 static char regcontext[AST_MAX_CONTEXT] = "";
363
364 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
365 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
366 static int network_change_sched_id = -1;
367
368 static int maxauthreq = 3;
369 static int max_retries = 4;
370 static int ping_time = 21;
371 static int lagrq_time = 10;
372 static int maxjitterbuffer=1000;
373 static int resyncthreshold=1000;
374 static int maxjitterinterps=10;
375 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
376
377 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
378
379 static int trunkfreq = 20;
380 static int trunkmaxsize = MAX_TRUNKDATA;
381
382 static int authdebug = 0;
383 static int autokill = 0;
384 static int iaxcompat = 0;
385 static int last_authmethod = 0;
386
387 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
388
389 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
390
391 static struct {
392 unsigned int tos;
393 unsigned int cos;
394 } qos = { 0, 0 };
395
396 static int min_reg_expire;
397 static int max_reg_expire;
398
399 static int srvlookup = 0;
400
401 static struct ast_timer *timer; /* Timer for trunking */
402
403 static struct ast_netsock_list *netsock;
404 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
405 static int defaultsockfd = -1;
406
407 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
408
409 /* Ethernet, etc */
410 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
411 /* T1, maybe ISDN */
412 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
413 ~AST_FORMAT_SLIN & \
414 ~AST_FORMAT_SLIN16 & \
415 ~AST_FORMAT_SIREN7 & \
416 ~AST_FORMAT_SIREN14 & \
417 ~AST_FORMAT_G719 & \
418 ~AST_FORMAT_ULAW & \
419 ~AST_FORMAT_ALAW & \
420 ~AST_FORMAT_G722)
421 /* A modem */
422 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
423 ~AST_FORMAT_G726 & \
424 ~AST_FORMAT_G726_AAL2 & \
425 ~AST_FORMAT_ADPCM)
426
427 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
428 ~AST_FORMAT_G723)
429
430
431 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
432 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
433 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
434
435 /*! \brief Name of effective auth method */
436 static const char *auth_method_labels[] = {
437 [0] = "none",
438 [IAX_AUTH_PLAINTEXT] = "plaintext",
439 [IAX_AUTH_MD5] = "MD5",
440 [IAX_AUTH_RSA] = "RSA",
441 };
442
443 /* Max length is length of |RSA|MD5|plaintext (18 + 1 for NUL = 19) */
444 #define AUTH_METHOD_NAMES_BUFSIZE 19
445
446 /*!
447 * \brief Get names of all auth methods
448 * \param Bit field of auth methods
449 * \param[out] buf Buffer into which to write the names. Must be of size AUTH_METHOD_NAMES_BUFSIZE.
450 * \return Auth methods name
451 */
452 static char *auth_method_names(int authmethods, char *restrict buf)
453 {
454 char *pos = buf;
455
456 *pos = '\0';
457
458 if (authmethods & IAX_AUTH_RSA) {
459 pos += sprintf(pos, "|RSA");
460 }
461 if (authmethods & IAX_AUTH_MD5) {
462 pos += sprintf(pos, "|MD5");
463 }
464 if (authmethods & IAX_AUTH_PLAINTEXT) {
465 pos += sprintf(pos, "|plaintext");
466 }
467
468 if (pos == buf) { /* No auth methods */
469 strcpy(buf, "none");
470 return buf;
471 }
472
473 return buf + 1; /* Skip leading | */
474 }
475
476 /* if a pvt has encryption setup done and is running on the call */
477 #define IAX_CALLENCRYPTED(pvt) \
478 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
479
480 #define IAX_DEBUGDIGEST(msg, key) do { \
481 int idx; \
482 char digest[33] = ""; \
483 \
484 if (!iaxdebug) \
485 break; \
486 \
487 for (idx = 0; idx < 16; idx++) \
488 sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
489 \
490 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
491 } while(0)
492
493 static struct io_context *io;
494 static struct ast_sched_context *sched;
495
496 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
497
498 static int iaxdebug = 0;
499
500 static int iaxtrunkdebug = 0;
501
502 static int test_losspct = 0;
503 #ifdef IAXTESTS
504 static int test_late = 0;
505 static int test_resync = 0;
506 static int test_jit = 0;
507 static int test_jitpct = 0;
508 #endif /* IAXTESTS */
509
510 static char accountcode[AST_MAX_ACCOUNT_CODE];
511 static char mohinterpret[MAX_MUSICCLASS];
512 static char mohsuggest[MAX_MUSICCLASS];
513 static int amaflags = 0;
514 static int adsi = 0;
515 static int delayreject = 0;
516 static int iax2_encryption = 0;
517 static int iax2_authmethods = 0;
518
519 static struct ast_flags64 globalflags = { 0 };
520
521 static pthread_t netthreadid = AST_PTHREADT_NULL;
522
523 enum iax2_state {
524 IAX_STATE_STARTED = (1 << 0),
525 IAX_STATE_AUTHENTICATED = (1 << 1),
526 IAX_STATE_TBD = (1 << 2),
527 };
528
529 struct iax2_context {
530 char context[AST_MAX_CONTEXT];
531 struct iax2_context *next;
532 };
533
534
535 #define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
536 #define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
537 #define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
538 #define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
539 #define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
540 #define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
541 #define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
542 #define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
543 #define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
544 #define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
545 #define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
546 #define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
547 #define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
548 #define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
549 #define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
550 #define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
551 #define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
552 #define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
553 #define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
554 #define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
555 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
556 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
557 #define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
558 #define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
559 #define IAX_DELAYPBXSTART (uint64_t)(1LLU << 25) /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
560 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
561 #define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
562 #define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
563 #define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
564 #define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
565 #define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
566 static int global_rtautoclear = 120;
567
568 static int reload_config(int forced_reload);
569
570 /*!
571 * \brief Call token validation settings.
572 */
573 enum calltoken_peer_enum {
574 /*! \brief Default calltoken required unless the ip is in the ignorelist */
575 CALLTOKEN_DEFAULT = 0,
576 /*! \brief Require call token validation. */
577 CALLTOKEN_YES = 1,
578 /*! \brief Require call token validation after a successful registration
579 * using call token validation occurs. */
580 CALLTOKEN_AUTO = 2,
581 /*! \brief Do not require call token validation. */
582 CALLTOKEN_NO = 3,
583 };
584
585 struct iax2_user {
586 AST_DECLARE_STRING_FIELDS(
587 AST_STRING_FIELD(name);
588 AST_STRING_FIELD(secret);
589 AST_STRING_FIELD(dbsecret);
590 AST_STRING_FIELD(accountcode);
591 AST_STRING_FIELD(mohinterpret);
592 AST_STRING_FIELD(mohsuggest);
593 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
594 AST_STRING_FIELD(language);
595 AST_STRING_FIELD(cid_num);
596 AST_STRING_FIELD(cid_name);
597 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
598 );
599
600 int authmethods;
601 int encmethods;
602 int amaflags;
603 int adsi;
604 uint64_t flags;
605 iax2_format capability;
606 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
607 int curauthreq; /*!< Current number of outstanding AUTHREQs */
608 struct iax2_codec_pref prefs;
609 struct ast_acl_list *acl;
610 struct iax2_context *contexts;
611 struct ast_variable *vars;
612 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
613 };
614
615 struct iax2_peer {
616 AST_DECLARE_STRING_FIELDS(
617 AST_STRING_FIELD(name);
618 AST_STRING_FIELD(username);
619 AST_STRING_FIELD(description); /*!< Description of the peer */
620 AST_STRING_FIELD(secret);
621 AST_STRING_FIELD(dbsecret);
622 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
623
624 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
625 AST_STRING_FIELD(context); /*!< For transfers only */
626 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
627 AST_STRING_FIELD(mailbox); /*!< Mailbox */
628 AST_STRING_FIELD(mohinterpret);
629 AST_STRING_FIELD(mohsuggest);
630 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
631 /* Suggested caller id if registering */
632 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
633 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
634 AST_STRING_FIELD(zonetag); /*!< Time Zone */
635 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
636 );
637 struct iax2_codec_pref prefs;
638 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
639 struct ast_sockaddr addr;
640 int formats;
641 int sockfd; /*!< Socket to use for transmission */
642 struct ast_sockaddr mask;
643 int adsi;
644 uint64_t flags;
645
646 /* Dynamic Registration fields */
647 struct ast_sockaddr defaddr; /*!< Default address if there is one */
648 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
649 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
650
651 int expire; /*!< Schedule entry for expiry */
652 int expiry; /*!< How soon to expire */
653 iax2_format capability; /*!< Capability */
654
655 /* Qualification */
656 int callno; /*!< Call number of POKE request */
657 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
658 int lastms; /*!< How long last response took (in ms), or -1 for no response */
659 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
660
661 int pokefreqok; /*!< How often to check if the host is up */
662 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
663 int historicms; /*!< How long recent average responses took */
664 int smoothing; /*!< Sample over how many units to determine historic ms */
665 uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
666
667 struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
668
669 struct ast_acl_list *acl;
670 enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
671
672 struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
673 };
674
675 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
676
677 struct iax2_trunk_peer {
678 ast_mutex_t lock;
679 int sockfd;
680 struct ast_sockaddr addr;
681 struct timeval txtrunktime; /*!< Transmit trunktime */
682 struct timeval rxtrunktime; /*!< Receive trunktime */
683 struct timeval lasttxtime; /*!< Last transmitted trunktime */
684 struct timeval trunkact; /*!< Last trunk activity */
685 unsigned int lastsent; /*!< Last sent time */
686 /* Trunk data and length */
687 unsigned char *trunkdata;
688 unsigned int trunkdatalen;
689 unsigned int trunkdataalloc;
690 int trunkmaxmtu;
691 int trunkerror;
692 int calls;
693 AST_LIST_ENTRY(iax2_trunk_peer) list;
694 };
695
696 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
697
698 enum iax_reg_state {
699 REG_STATE_UNREGISTERED = 0,
700 REG_STATE_REGSENT,
701 REG_STATE_AUTHSENT,
702 REG_STATE_REGISTERED,
703 REG_STATE_REJECTED,
704 REG_STATE_TIMEOUT,
705 REG_STATE_NOAUTH
706 };
707
708 enum iax_transfer_state {
709 TRANSFER_NONE = 0,
710 TRANSFER_BEGIN,
711 TRANSFER_READY,
712 TRANSFER_RELEASED,
713 TRANSFER_PASSTHROUGH,
714 TRANSFER_MBEGIN,
715 TRANSFER_MREADY,
716 TRANSFER_MRELEASED,
717 TRANSFER_MPASSTHROUGH,
718 TRANSFER_MEDIA,
719 TRANSFER_MEDIAPASS
720 };
721
722 struct iax2_registry {
723 struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
724 char username[80];
725 char secret[80]; /*!< Password or key name in []'s */
726 int expire; /*!< Sched ID of expiration */
727 int refresh; /*!< How often to refresh */
728 enum iax_reg_state regstate;
729 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
730 int callno; /*!< Associated call number if applicable */
731 struct ast_sockaddr us; /*!< Who the server thinks we are */
732 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
733 AST_LIST_ENTRY(iax2_registry) entry;
734 int port;
735 char hostname[];
736 };
737
738 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
739
740 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
741 #define MIN_RETRY_TIME 100
742 #define MAX_RETRY_TIME 10000
743
744 #define MAX_JITTER_BUFFER 50
745 #define MIN_JITTER_BUFFER 10
746
747 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
748
749 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
750
751 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
752 #define TS_GAP_FOR_JB_RESYNC 5000
753
754 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
755 #define MARK_IAX_SUBCLASS_TX 0x8000
756
757 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
758 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
759 static int iaxdynamicthreadcount = 0;
760 static int iaxdynamicthreadnum = 0;
761 static int iaxactivethreadcount = 0;
762
763 struct iax_rr {
764 int jitter;
765 int losspct;
766 int losscnt;
767 int packets;
768 int delay;
769 int dropped;
770 int ooo;
771 };
772
773 struct iax2_pvt_ref;
774
775 /* We use the high order bit as the validated flag, and the lower 15 as the
776 * actual call number */
777 typedef uint16_t callno_entry;
778
779 struct chan_iax2_pvt {
780 /*! Socket to send/receive on for this call */
781 int sockfd;
782 /*! ast_callid bound to dialog */
783 ast_callid callid;
784 /*! Last received voice format */
785 iax2_format voiceformat;
786 /*! Last received video format */
787 iax2_format videoformat;
788 /*! Last sent voice format */
789 iax2_format svoiceformat;
790 /*! Last sent video format */
791 iax2_format svideoformat;
792 /*! What we are capable of sending */
793 iax2_format capability;
794 /*! Last received timestamp */
795 unsigned int last;
796 /*! Last sent timestamp - never send the same timestamp twice in a single call */
797 unsigned int lastsent;
798 /*! Timestamp of the last video frame sent */
799 unsigned int lastvsent;
800 /*! Next outgoing timestamp if everything is good */
801 unsigned int nextpred;
802 /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
803 int first_iax_message;
804 /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
805 int last_iax_message;
806 /*! True if the last voice we transmitted was not silence/CNG */
807 unsigned int notsilenttx:1;
808 /*! Ping time */
809 unsigned int pingtime;
810 /*! Max time for initial response */
811 int maxtime;
812 /*! Peer Address */
813 struct ast_sockaddr addr;
814 /*! Actual used codec preferences */
815 struct iax2_codec_pref prefs;
816 /*! Requested codec preferences */
817 struct iax2_codec_pref rprefs;
818 /*! Our call number */
819 unsigned short callno;
820 /*! Our callno_entry entry */
821 callno_entry callno_entry;
822 /*! Peer callno */
823 unsigned short peercallno;
824 /*! Negotiated format, this is only used to remember what format was
825 chosen for an unauthenticated call so that the channel can get
826 created later using the right format. We also use it for
827 authenticated calls to check the format from __get_from_jb. */
828 iax2_format chosenformat;
829 /*! Peer selected format */
830 iax2_format peerformat;
831 /*! Peer capability */
832 iax2_format peercapability;
833 /*! timeval that we base our transmission on */
834 struct timeval offset;
835 /*! timeval that we base our delivery on */
836 struct timeval rxcore;
837 /*! The jitterbuffer */
838 jitterbuf *jb;
839 /*! active jb read scheduler id */
840 int jbid;
841 /*! LAG */
842 int lag;
843 /*! Error, as discovered by the manager */
844 int error;
845 /*! Owner if we have one */
846 struct ast_channel *owner;
847 /*! What's our state? */
848 struct ast_flags state;
849 /*! Expiry (optional) */
850 int expiry;
851 /*! Next outgoing sequence number */
852 unsigned char oseqno;
853 /*! Next sequence number they have not yet acknowledged */
854 unsigned char rseqno;
855 /*! Next incoming sequence number */
856 unsigned char iseqno;
857 /*! Last incoming sequence number we have acknowledged */
858 unsigned char aseqno;
859
860 AST_DECLARE_STRING_FIELDS(
861 /*! Peer name */
862 AST_STRING_FIELD(peer);
863 /*! Default Context */
864 AST_STRING_FIELD(context);
865 /*! Caller ID if available */
866 AST_STRING_FIELD(cid_num);
867 AST_STRING_FIELD(cid_name);
868 /*! Hidden Caller ID (i.e. ANI) if appropriate */
869 AST_STRING_FIELD(ani);
870 /*! DNID */
871 AST_STRING_FIELD(dnid);
872 /*! RDNIS */
873 AST_STRING_FIELD(rdnis);
874 /*! Requested Extension */
875 AST_STRING_FIELD(exten);
876 /*! Expected Username */
877 AST_STRING_FIELD(username);
878 /*! Expected Secret */
879 AST_STRING_FIELD(secret);
880 /*! MD5 challenge */
881 AST_STRING_FIELD(challenge);
882 /*! Public keys permitted keys for incoming authentication */
883 AST_STRING_FIELD(inkeys);
884 /*! Private key for outgoing authentication */
885 AST_STRING_FIELD(outkey);
886 /*! Preferred language */
887 AST_STRING_FIELD(language);
888 /*! Hostname/peername for naming purposes */
889 AST_STRING_FIELD(host);
890
891 AST_STRING_FIELD(dproot);
892 AST_STRING_FIELD(accountcode);
893 AST_STRING_FIELD(mohinterpret);
894 AST_STRING_FIELD(mohsuggest);
895 /*! received OSP token */
896 AST_STRING_FIELD(osptoken);
897 /*! Default parkinglot */
898 AST_STRING_FIELD(parkinglot);
899 );
900 /*! AUTHREJ all AUTHREP frames */
901 int authrej;
902 /*! permitted authentication methods */
903 int authmethods;
904 /*! effective authentication method */
905 int eff_auth_method;
906 /*! permitted encryption methods */
907 int encmethods;
908 /*! Encryption AES-128 Key */
909 ast_aes_encrypt_key ecx;
910 /*! Decryption AES-128 Key corresponding to ecx */
911 ast_aes_decrypt_key mydcx;
912 /*! Decryption AES-128 Key used to decrypt peer frames */
913 ast_aes_decrypt_key dcx;
914 /*! scheduler id associated with iax_key_rotate
915 * for encrypted calls*/
916 int keyrotateid;
917 /*! 32 bytes of semi-random data */
918 unsigned char semirand[32];
919 /*! Associated registry */
920 struct iax2_registry *reg;
921 /*! Associated peer for poking */
922 struct iax2_peer *peerpoke;
923 /*! IAX_ flags */
924 uint64_t flags;
925 int adsi;
926
927 /*! Transferring status */
928 enum iax_transfer_state transferring;
929 /*! Transfer identifier */
930 int transferid;
931 /*! Who we are IAX transferring to */
932 struct ast_sockaddr transfer;
933 /*! What's the new call number for the transfer */
934 unsigned short transfercallno;
935 /*! Transfer encrypt AES-128 Key */
936 ast_aes_encrypt_key tdcx;
937
938 /*! Status of knowledge of peer ADSI capability */
939 int peeradsicpe;
940
941 /*! Callno of native bridge peer. (Valid if nonzero) */
942 unsigned short bridgecallno;
943
944 int pingid; /*!< Transmit PING request */
945 int lagid; /*!< Retransmit lag request */
946 int autoid; /*!< Auto hangup for Dialplan requestor */
947 int authid; /*!< Authentication rejection ID */
948 int authfail; /*!< Reason to report failure */
949 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
950 int calling_ton;
951 int calling_tns;
952 int calling_pres;
953 int calling_ani2;
954 int amaflags;
955 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
956 /*! variables inherited from the user definition */
957 struct ast_variable *vars;
958 /*! variables transmitted in a NEW packet */
959 struct ast_variable *iaxvars;
960 /*! last received remote rr */
961 struct iax_rr remote_rr;
962 /*! Current base time: (just for stats) */
963 int min;
964 /*! Dropped frame count: (just for stats) */
965 int frames_dropped;
966 /*! received frame count: (just for stats) */
967 int frames_received;
968 /*! Destroying this call initiated. */
969 int destroy_initiated;
970 /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
971 unsigned char calltoken_ie_len;
972 /*! hold all signaling frames from the pbx thread until we have a destination callno */
973 char hold_signaling;
974 /*! frame queue for signaling frames from pbx thread waiting for destination callno */
975 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
976 };
977
978 struct signaling_queue_entry {
979 struct ast_frame f;
980 AST_LIST_ENTRY(signaling_queue_entry) next;
981 };
982
983 enum callno_type {
984 CALLNO_TYPE_NORMAL,
985 CALLNO_TYPE_TRUNK,
986 };
987
988 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
989 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
990
991 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
992 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
993 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
994
995 struct call_number_pool {
996 size_t capacity;
997 size_t available;
998 callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
999 };
1000
1001 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
1002
1003 /*! table of available call numbers */
1004 static struct call_number_pool callno_pool;
1005
1006 /*! table of available trunk call numbers */
1007 static struct call_number_pool callno_pool_trunk;
1008
1009 /*!
1010 * \brief a list of frames that may need to be retransmitted
1011 *
1012 * \note The contents of this list do not need to be explicitly destroyed
1013 * on module unload. This is because all active calls are destroyed, and
1014 * all frames in this queue will get destroyed as a part of that process.
1015 *
1016 * \note Contents protected by the iaxsl[] locks
1017 */
1018 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
1019
1020 static struct ast_taskprocessor *transmit_processor;
1021
1022 static int randomcalltokendata;
1023
1024 static time_t max_calltoken_delay = 10;
1025
1026 /*!
1027 * This module will get much higher performance when doing a lot of
1028 * user and peer lookups if the number of buckets is increased from 1.
1029 * However, to maintain old behavior for Asterisk 1.4, these are set to
1030 * 1 by default. When using multiple buckets, search order through these
1031 * containers is considered random, so you will not be able to depend on
1032 * the order the entries are specified in iax.conf for matching order. */
1033 #ifdef LOW_MEMORY
1034 #define MAX_PEER_BUCKETS 17
1035 #else
1036 #define MAX_PEER_BUCKETS 563
1037 #endif
1038 static struct ao2_container *peers;
1039
1040 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
1041 static struct ao2_container *users;
1042
1043 /*! Table containing peercnt objects for every ip address consuming a callno */
1044 static struct ao2_container *peercnts;
1045
1046 /*! Table containing custom callno limit rules for a range of ip addresses. */
1047 static struct ao2_container *callno_limits;
1048
1049 /*! Table containing ip addresses not requiring calltoken validation */
1050 static struct ao2_container *calltoken_ignores;
1051
1052 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
1053
1054 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
1055
1056 static uint16_t global_maxcallno;
1057
1058 /*! Total num of call numbers allowed to be allocated without calltoken validation */
1059 static uint16_t global_maxcallno_nonval;
1060
1061 static uint16_t total_nonval_callno_used = 0;
1062
1063 /*! peer connection private, keeps track of all the call numbers
1064 * consumed by a single ip address */
1065 struct peercnt {
1066 /*! ip address consuming call numbers */
1067 struct ast_sockaddr addr;
1068 /*! Number of call numbers currently used by this ip address */
1069 uint16_t cur;
1070 /*! Max call numbers allowed for this ip address */
1071 uint16_t limit;
1072 /*! Specifies whether limit is set by a registration or not, if so normal
1073 * limit setting rules do not apply to this address. */
1074 unsigned char reg;
1075 };
1076
1077 /*! used by both callno_limits and calltoken_ignores containers */
1078 struct addr_range {
1079 /*! ip address range for custom callno limit rule */
1080 struct ast_ha ha;
1081 /*! callno limit for this ip address range, only used in callno_limits container */
1082 uint16_t limit;
1083 /*! delete me marker for reloads */
1084 unsigned char delme;
1085 };
1086
1087 enum {
1088 /*! Extension exists */
1089 CACHE_FLAG_EXISTS = (1 << 0),
1090 /*! Extension is nonexistent */
1091 CACHE_FLAG_NONEXISTENT = (1 << 1),
1092 /*! Extension can exist */
1093 CACHE_FLAG_CANEXIST = (1 << 2),
1094 /*! Waiting to hear back response */
1095 CACHE_FLAG_PENDING = (1 << 3),
1096 /*! Timed out */
1097 CACHE_FLAG_TIMEOUT = (1 << 4),
1098 /*! Request transmitted */
1099 CACHE_FLAG_TRANSMITTED = (1 << 5),
1100 /*! Timeout */
1101 CACHE_FLAG_UNKNOWN = (1 << 6),
1102 /*! Matchmore */
1103 CACHE_FLAG_MATCHMORE = (1 << 7),
1104 };
1105
1106 struct iax2_dpcache {
1107 char peercontext[AST_MAX_CONTEXT];
1108 char exten[AST_MAX_EXTENSION];
1109 struct timeval orig;
1110 struct timeval expiry;
1111 int flags;
1112 unsigned short callno;
1113 int waiters[256];
1114 AST_LIST_ENTRY(iax2_dpcache) cache_list;
1115 AST_LIST_ENTRY(iax2_dpcache) peer_list;
1116 };
1117
1118 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1119
1120 static void reg_source_db(struct iax2_peer *p);
1121 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1122 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1123
1124 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1125 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1126 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1127
1128 enum iax2_thread_iostate {
1129 IAX_IOSTATE_IDLE,
1130 IAX_IOSTATE_READY,
1131 IAX_IOSTATE_PROCESSING,
1132 IAX_IOSTATE_SCHEDREADY,
1133 };
1134
1135 enum iax2_thread_type {
1136 IAX_THREAD_TYPE_POOL,
1137 IAX_THREAD_TYPE_DYNAMIC,
1138 };
1139
1140 struct iax2_pkt_buf {
1141 AST_LIST_ENTRY(iax2_pkt_buf) entry;
1142 size_t len;
1143 unsigned char buf[1];
1144 };
1145
1146 struct iax2_thread {
1147 AST_LIST_ENTRY(iax2_thread) list;
1148 enum iax2_thread_type type;
1149 enum iax2_thread_iostate iostate;
1150 #ifdef SCHED_MULTITHREADED
1151 void (*schedfunc)(const void *);
1152 const void *scheddata;
1153 #endif
1154 #ifdef DEBUG_SCHED_MULTITHREAD
1155 char curfunc[80];
1156 #endif
1157 int actions;
1158 pthread_t threadid;
1159 int threadnum;
1160 struct ast_sockaddr ioaddr;
1161 unsigned char readbuf[4096];
1162 unsigned char *buf;
1163 ssize_t buf_len;
1164 size_t buf_size;
1165 int iofd;
1166 time_t checktime;
1167 ast_mutex_t lock;
1168 ast_cond_t cond;
1169 ast_mutex_t init_lock;
1170 ast_cond_t init_cond;
1171 /*! if this thread is processing a full frame,
1172 some information about that frame will be stored
1173 here, so we can avoid dispatching any more full
1174 frames for that callno to other threads */
1175 struct {
1176 unsigned short callno;
1177 struct ast_sockaddr addr;
1178 unsigned char type;
1179 unsigned char csub;
1180 } ffinfo;
1181 /*! Queued up full frames for processing. If more full frames arrive for
1182 * a call which this thread is already processing a full frame for, they
1183 * are queued up here. */
1184 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1185 unsigned char stop;
1186 };
1187
1188 /* Thread lists */
1189 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1190 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1191 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1192
1193 static void *iax2_process_thread(void *data);
1194 static void iax2_destroy(int callno);
1195
1196 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1197 {
1198 ast_mutex_lock(lock);
1199 ast_cond_signal(cond);
1200 ast_mutex_unlock(lock);
1201 }
1202
1203 /*!
1204 * \brief an array of iax2 pvt structures
1205 *
1206 * The container for active chan_iax2_pvt structures is implemented as an
1207 * array for extremely quick direct access to the correct pvt structure
1208 * based on the local call number. The local call number is used as the
1209 * index into the array where the associated pvt structure is stored.
1210 */
1211 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1212
1213 static ast_callid iax_pvt_callid_get(int callno)
1214 {
1215 return iaxs[callno]->callid;
1216 }
1217
1218 static void iax_pvt_callid_set(int callno, ast_callid callid)
1219 {
1220 iaxs[callno]->callid = callid;
1221 }
1222
1223 static void iax_pvt_callid_new(int callno)
1224 {
1225 ast_callid callid = ast_create_callid();
1226 char buffer[AST_CALLID_BUFFER_LENGTH];
1227 ast_callid_strnprint(buffer, sizeof(buffer), callid);
1228 iax_pvt_callid_set(callno, callid);
1229 }
1230
1231 /*!
1232 * \brief Another container of iax2_pvt structures
1233 *
1234 * Active IAX2 pvt structs are also stored in this container, if they are a part
1235 * of an active call where we know the remote side's call number. The reason
1236 * for this is that incoming media frames do not contain our call number. So,
1237 * instead of having to iterate the entire iaxs array, we use this container to
1238 * look up calls where the remote side is using a given call number.
1239 */
1240 static struct ao2_container *iax_peercallno_pvts;
1241
1242 /*!
1243 * \brief chan_iax2_pvt structure locks
1244 *
1245 * These locks are used when accessing a pvt structure in the iaxs array.
1246 * The index used here is the same as used in the iaxs array. It is the
1247 * local call number for the associated pvt struct.
1248 */
1249 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1250
1251 /*!
1252 * \brief Another container of iax2_pvt structures
1253 *
1254 * Active IAX2 pvt structs used during transferring a call are stored here.
1255 */
1256 static struct ao2_container *iax_transfercallno_pvts;
1257
1258 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1259 but keeps the division between trunked and non-trunked better. */
1260 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1261
1262 /* Debug routines... */
1263 static struct ast_sockaddr debugaddr;
1264
1265 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1266 {
1267 if (iaxdebug ||
1268 (addr && !ast_sockaddr_isnull(&debugaddr) &&
1269 (!ast_sockaddr_port(&debugaddr) ||
1270 ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1271 !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1272
1273 if (iaxdebug) {
1274 iax_showframe(f, fhi, rx, addr, datalen);
1275 } else {
1276 iaxdebug = 1;
1277 iax_showframe(f, fhi, rx, addr, datalen);
1278 iaxdebug = 0;
1279 }
1280 }
1281 }
1282
1283 static void iax_debug_output(const char *data)
1284 {
1285 if (iaxdebug)
1286 ast_verbose("%s", data);
1287 }
1288
1289 static void iax_error_output(const char *data)
1290 {
1291 ast_log(LOG_WARNING, "%s", data);
1292 }
1293
1294 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1295 {
1296 va_list args;
1297 char buf[1024];
1298
1299 va_start(args, fmt);
1300 vsnprintf(buf, sizeof(buf), fmt, args);
1301 va_end(args);
1302
1303 ast_log(LOG_ERROR, "%s", buf);
1304 }
1305
1306 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1307 {
1308 va_list args;
1309 char buf[1024];
1310
1311 va_start(args, fmt);
1312 vsnprintf(buf, sizeof(buf), fmt, args);
1313 va_end(args);
1314
1315 ast_log(LOG_WARNING, "%s", buf);
1316 }
1317
1318 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1319 {
1320 va_list args;
1321 char buf[1024];
1322
1323 va_start(args, fmt);
1324 vsnprintf(buf, sizeof(buf), fmt, args);
1325 va_end(args);
1326
1327 ast_verbose("%s", buf);
1328 }
1329
1330 static int expire_registry(const void *data);
1331 static int iax2_answer(struct ast_channel *c);
1332 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1333 static int iax2_devicestate(const char *data);
1334 static int iax2_digit_begin(struct ast_channel *c, char digit);
1335 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1336 static int iax2_do_register(struct iax2_registry *reg);
1337 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1338 static int iax2_hangup(struct ast_channel *c);
1339 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1340 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1341 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1342 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1343 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1344 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1345 static int iax2_sendtext(struct ast_channel *c, const char *text);
1346 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1347 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1348 static int iax2_transfer(struct ast_channel *c, const char *dest);
1349 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1350 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1351
1352 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1353 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1354 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1355 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1356 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1357 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1358 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);
1359 static struct ast_frame *iax2_read(struct ast_channel *c);
1360 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1361 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1362 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1363 static void *iax2_dup_variable_datastore(void *);
1364 static void prune_peers(void);
1365 static void prune_users(void);
1366 static void iax2_free_variable_datastore(void *);
1367
1368 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1369 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1370 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1371 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1372 static void build_rand_pad(unsigned char *buf, ssize_t len);
1373 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1374 static int replace_callno(const void *obj);
1375 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1376 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1377 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1378
1379 static struct ast_channel_tech iax2_tech = {
1380 .type = "IAX2",
1381 .description = tdesc,
1382 .properties = AST_CHAN_TP_WANTSJITTER,
1383 .requester = iax2_request,
1384 .devicestate = iax2_devicestate,
1385 .send_digit_begin = iax2_digit_begin,
1386 .send_digit_end = iax2_digit_end,
1387 .send_text = iax2_sendtext,
1388 .send_image = iax2_sendimage,
1389 .send_html = iax2_sendhtml,
1390 .call = iax2_call,
1391 .hangup = iax2_hangup,
1392 .answer = iax2_answer,
1393 .read = iax2_read,
1394 .write = iax2_write,
1395 .write_video = iax2_write,
1396 .indicate = iax2_indicate,
1397 .setoption = iax2_setoption,
1398 .queryoption = iax2_queryoption,
1399 .transfer = iax2_transfer,
1400 .fixup = iax2_fixup,
1401 .func_channel_read = acf_channel_read,
1402 };
1403
1404 /*!
1405 * \internal
1406 * \brief Obtain the owner channel lock if the owner exists.
1407 *
1408 * \param callno IAX2 call id.
1409 *
1410 * \note Assumes the iaxsl[callno] lock is already obtained.
1411 *
1412 * \note
1413 * IMPORTANT NOTE!!! Any time this function is used, even if
1414 * iaxs[callno] was valid before calling it, it may no longer be
1415 * valid after calling it. This function may unlock and lock
1416 * the mutex associated with this callno, meaning that another
1417 * thread may grab it and destroy the call.
1418 */
1419 static void iax2_lock_owner(int callno)
1420 {
1421 for (;;) {
1422 if (!iaxs[callno] || !iaxs[callno]->owner) {
1423 /* There is no owner lock to get. */
1424 break;
1425 }
1426 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1427 /* We got the lock */
1428 break;
1429 }
1430 /* Avoid deadlock by pausing and trying again */
1431 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1432 }
1433 }
1434
1435 /*!
1436 * \internal
1437 * \brief Check if a control subtype is allowed on the wire.
1438 *
1439 * \param subtype Control frame subtype to check if allowed to/from the wire.
1440 *
1441 * \retval non-zero if allowed.
1442 */
1443 static int iax2_is_control_frame_allowed(int subtype)
1444 {
1445 enum ast_control_frame_type control = subtype;
1446 int is_allowed;
1447
1448 /*
1449 * Note: If we compare the enumeration type, which does not have any
1450 * negative constants, the compiler may optimize this code away.
1451 * Therefore, we must perform an integer comparison here.
1452 */
1453 if (subtype == -1) {
1454 return -1;
1455 }
1456
1457 /* Default to not allowing control frames to pass. */
1458 is_allowed = 0;
1459
1460 /*
1461 * The switch default is not present in order to take advantage
1462 * of the compiler complaining of a missing enum case.
1463 */
1464 switch (control) {
1465 /*
1466 * These control frames make sense to send/receive across the link.
1467 */
1468 case AST_CONTROL_HANGUP:
1469 case AST_CONTROL_RING:
1470 case AST_CONTROL_RINGING:
1471 case AST_CONTROL_ANSWER:
1472 case AST_CONTROL_BUSY:
1473 case AST_CONTROL_TAKEOFFHOOK:
1474 case AST_CONTROL_OFFHOOK:
1475 case AST_CONTROL_CONGESTION:
1476 case AST_CONTROL_FLASH:
1477 case AST_CONTROL_WINK:
1478 case AST_CONTROL_OPTION:
1479 case AST_CONTROL_RADIO_KEY:
1480 case AST_CONTROL_RADIO_UNKEY:
1481 case AST_CONTROL_PROGRESS:
1482 case AST_CONTROL_PROCEEDING:
1483 case AST_CONTROL_HOLD:
1484 case AST_CONTROL_UNHOLD:
1485 case AST_CONTROL_VIDUPDATE:
1486 case AST_CONTROL_CONNECTED_LINE:
1487 case AST_CONTROL_REDIRECTING:
1488 case AST_CONTROL_T38_PARAMETERS:
1489 case AST_CONTROL_AOC:
1490 case AST_CONTROL_INCOMPLETE:
1491 case AST_CONTROL_MCID:
1492 is_allowed = -1;
1493 break;
1494
1495 /*
1496 * These control frames do not make sense to send/receive across the link.
1497 */
1498 case _XXX_AST_CONTROL_T38:
1499 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1500 case AST_CONTROL_SRCUPDATE:
1501 /* Across an IAX link the source is still the same. */
1502 case AST_CONTROL_TRANSFER:
1503 /* A success/fail status report from calling ast_transfer() on this machine. */
1504 case AST_CONTROL_CC:
1505 /* The payload contains pointers that are valid for the sending machine only. */
1506 case AST_CONTROL_SRCCHANGE:
1507 /* Across an IAX link the source is still the same. */
1508 case AST_CONTROL_READ_ACTION:
1509 /* The action can only be done by the sending machine. */
1510 case AST_CONTROL_END_OF_Q:
1511 /* This frame would cause the call to unexpectedly hangup. */
1512 case AST_CONTROL_UPDATE_RTP_PEER:
1513 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1514 case AST_CONTROL_PVT_CAUSE_CODE:
1515 /* Intended only for the sending machine's local channel structure. */
1516 case AST_CONTROL_MASQUERADE_NOTIFY:
1517 /* Intended only for masquerades when calling ast_indicate_data(). */
1518 case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1519 /* Intended only for internal stream topology manipulation. */
1520 case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
1521 /* Intended only for internal stream topology change notification. */
1522 case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
1523 case AST_CONTROL_STREAM_STOP:
1524 case AST_CONTROL_STREAM_SUSPEND:
1525 case AST_CONTROL_STREAM_RESTART:
1526 case AST_CONTROL_STREAM_REVERSE:
1527 case AST_CONTROL_STREAM_FORWARD:
1528 case AST_CONTROL_PLAYBACK_BEGIN: /* Only supported by app_dial currently */
1529 /* None of these playback stream control frames should go across the link. */
1530 case AST_CONTROL_RECORD_CANCEL:
1531 case AST_CONTROL_RECORD_STOP:
1532 case AST_CONTROL_RECORD_SUSPEND:
1533 case AST_CONTROL_RECORD_MUTE:
1534 /* None of these media recording control frames should go across the link. */
1535 break;
1536 }
1537 return is_allowed;
1538 }
1539
1540 static void network_change_stasis_subscribe(void)
1541 {
1542 if (!network_change_sub) {
1543 network_change_sub = stasis_subscribe(ast_system_topic(),
1544 network_change_stasis_cb, NULL);
1545 stasis_subscription_accept_message_type(network_change_sub, ast_network_change_type());
1546 stasis_subscription_set_filter(network_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1547 }
1548 }
1549
1550 static void network_change_stasis_unsubscribe(void)
1551 {
1552 network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1553 }
1554
1555 static void acl_change_stasis_subscribe(void)
1556 {
1557 if (!acl_change_sub) {
1558 acl_change_sub = stasis_subscribe(ast_security_topic(),
1559 acl_change_stasis_cb, NULL);
1560 stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
1561 stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
1562 }
1563 }
1564
1565 static void acl_change_stasis_unsubscribe(void)
1566 {
1567 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1568 }
1569
1570 static int network_change_sched_cb(const void *data)
1571 {
1572 struct iax2_registry *reg;
1573 network_change_sched_id = -1;
1574 AST_LIST_LOCK(&registrations);
1575 AST_LIST_TRAVERSE(&registrations, reg, entry) {
1576 iax2_do_register(reg);
1577 }
1578 AST_LIST_UNLOCK(&registrations);
1579
1580 return 0;
1581 }
1582
1583 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1584 struct stasis_message *message)
1585 {
1586 /* This callback is only concerned with network change messages from the system topic. */
1587 if (stasis_message_type(message) != ast_network_change_type()) {
1588 return;
1589 }
1590
1591 ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1592 if (network_change_sched_id == -1) {
1593 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1594 }
1595 }
1596
1597 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1598 struct stasis_message *message)
1599 {
1600 if (stasis_message_type(message) != ast_named_acl_change_type()) {
1601 return;
1602 }
1603
1604 ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1605 reload_config(1);
1606 }
1607
1608 static const struct ast_datastore_info iax2_variable_datastore_info = {
1609 .type = "IAX2_VARIABLE",
1610 .duplicate = iax2_dup_variable_datastore,
1611 .destroy = iax2_free_variable_datastore,
1612 };
1613
1614 static void *iax2_dup_variable_datastore(void *old)
1615 {
1616 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1617 struct ast_var_t *oldvar, *newvar;
1618
1619 newlist = ast_calloc(sizeof(*newlist), 1);
1620 if (!newlist) {
1621 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1622 return NULL;
1623 }
1624
1625 AST_LIST_HEAD_INIT(newlist);
1626 AST_LIST_LOCK(oldlist);
1627 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1628 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1629 if (newvar)
1630 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1631 else
1632 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1633 }
1634 AST_LIST_UNLOCK(oldlist);
1635 return newlist;
1636 }
1637
1638 static void iax2_free_variable_datastore(void *old)
1639 {
1640 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1641 struct ast_var_t *oldvar;
1642
1643 AST_LIST_LOCK(oldlist);
1644 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1645 ast_free(oldvar);
1646 }
1647 AST_LIST_UNLOCK(oldlist);
1648 AST_LIST_HEAD_DESTROY(oldlist);
1649 ast_free(oldlist);
1650 }
1651
1652
1653 /* WARNING: insert_idle_thread should only ever be called within the
1654 * context of an iax2_process_thread() thread.
1655 */
1656 static void insert_idle_thread(struct iax2_thread *thread)
1657 {
1658 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1659 AST_LIST_LOCK(&dynamic_list);
1660 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1661 AST_LIST_UNLOCK(&dynamic_list);
1662 } else {
1663 AST_LIST_LOCK(&idle_list);
1664 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1665 AST_LIST_UNLOCK(&idle_list);
1666 }
1667
1668 return;
1669 }
1670
1671 static struct iax2_thread *find_idle_thread(void)
1672 {
1673 struct iax2_thread *thread = NULL;
1674
1675 /* Pop the head of the idle list off */
1676 AST_LIST_LOCK(&idle_list);
1677 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1678 AST_LIST_UNLOCK(&idle_list);
1679
1680 /* If we popped a thread off the idle list, just return it */
1681 if (thread) {
1682 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1683 return thread;
1684 }
1685
1686 /* Pop the head of the dynamic list off */
1687 AST_LIST_LOCK(&dynamic_list);
1688 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1689 AST_LIST_UNLOCK(&dynamic_list);
1690
1691 /* If we popped a thread off the dynamic list, just return it */
1692 if (thread) {
1693 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1694 return thread;
1695 }
1696
1697 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1698 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1699 return NULL;
1700
1701 /* Set default values */
1702 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1703 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1704 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1705
1706 /* Initialize lock and condition */
1707 ast_mutex_init(&thread->lock);
1708 ast_cond_init(&thread->cond, NULL);
1709 ast_mutex_init(&thread->init_lock);
1710 ast_cond_init(&thread->init_cond, NULL);
1711 ast_mutex_lock(&thread->init_lock);
1712
1713 /* Create thread and send it on it's way */
1714 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1715 ast_cond_destroy(&thread->cond);
1716 ast_mutex_destroy(&thread->lock);
1717 ast_mutex_unlock(&thread->init_lock);
1718 ast_cond_destroy(&thread->init_cond);
1719 ast_mutex_destroy(&thread->init_lock);
1720 ast_free(thread);
1721 return NULL;
1722 }
1723
1724 /* this thread is not processing a full frame (since it is idle),
1725 so ensure that the field for the full frame call number is empty */
1726 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1727
1728 /* Wait for the thread to be ready before returning it to the caller */
1729 ast_cond_wait(&thread->init_cond, &thread->init_lock);
1730
1731 /* Done with init_lock */
1732 ast_mutex_unlock(&thread->init_lock);
1733
1734 return thread;
1735 }
1736
1737 #ifdef SCHED_MULTITHREADED
1738 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1739 {
1740 struct iax2_thread *thread;
1741 static time_t lasterror;
1742 time_t t;
1743
1744 thread = find_idle_thread();
1745 if (thread != NULL) {
1746 thread->schedfunc = func;
1747 thread->scheddata = data;
1748 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1749 #ifdef DEBUG_SCHED_MULTITHREAD
1750 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1751 #endif
1752 signal_condition(&thread->lock, &thread->cond);
1753 return 0;
1754 }
1755 time(&t);
1756 if (t != lasterror) {
1757 lasterror = t;
1758 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1759 }
1760
1761 return -1;
1762 }
1763 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1764 #endif
1765
1766 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1767 ast_sched_cb callback, const void *data)
1768 {
1769 return ast_sched_replace(id, con, when, callback, data);
1770 }
1771
1772 static int iax2_sched_add(struct ast_sched_context *con, int when,
1773 ast_sched_cb callback, const void *data)
1774 {
1775 return ast_sched_add(con, when, callback, data);
1776 }
1777
1778 /*!
1779 * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1780 * \param callno Call number to lock.
1781 * \retval 0 If call disappeared or has ongoing hangup procedure.
1782 * \retval 1 If call found and mutex is locked.
1783 */
1784 static int iax2_lock_callno_unless_destroyed(int callno)
1785 {
1786 ast_mutex_lock(&iaxsl[callno]);
1787
1788 /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1789 * or destroy initiated (in middle of hang up procedure. */
1790 if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1791 ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1792 ast_mutex_unlock(&iaxsl[callno]);
1793 return 0;
1794 }
1795
1796 /* Lock acquired, and callno is alive and kicking. */
1797 return 1;
1798 }
1799
1800 static int send_ping(const void *data);
1801
1802 static void __send_ping(const void *data)
1803 {
1804 int callno = PTR_TO_CALLNO(data);
1805
1806 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1807 ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1808 return;
1809 }
1810
1811 /* Mark pingid as invalid scheduler id. */
1812 iaxs[callno]->pingid = -1;
1813
1814 /* callno is now locked. */
1815 if (iaxs[callno]->peercallno) {
1816 /* Send PING packet. */
1817 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1818
1819 /* Schedule sending next ping. */
1820 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1821 }
1822
1823 ast_mutex_unlock(&iaxsl[callno]);
1824 }
1825
1826 static int send_ping(const void *data)
1827 {
1828 #ifdef SCHED_MULTITHREADED
1829 if (schedule_action(__send_ping, data))
1830 #endif
1831 __send_ping(data);
1832
1833 return 0;
1834 }
1835
1836 static void encmethods_to_str(int e, struct ast_str **buf)
1837 {
1838 ast_str_set(buf, 0, "(");
1839 if (e & IAX_ENCRYPT_AES128) {
1840 ast_str_append(buf, 0, "aes128");
1841 }
1842 if (e & IAX_ENCRYPT_KEYROTATE) {
1843 ast_str_append(buf, 0, ",keyrotate");
1844 }
1845 if (ast_str_strlen(*buf) > 1) {
1846 ast_str_append(buf, 0, ")");
1847 } else {
1848 ast_str_set(buf, 0, "No");
1849 }
1850 }
1851
1852 static int get_encrypt_methods(const char *s)
1853 {
1854 int e;
1855 if (!strcasecmp(s, "aes128"))
1856 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1857 else if (ast_true(s))
1858 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1859 else
1860 e = 0;
1861 return e;
1862 }
1863
1864 static int send_lagrq(const void *data);
1865
1866 static void __send_lagrq(const void *data)
1867 {
1868 int callno = PTR_TO_CALLNO(data);
1869
1870 if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1871 ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1872 return;
1873 }
1874
1875 /* Mark lagid as invalid scheduler id. */
1876 iaxs[callno]->lagid = -1;
1877
1878 /* callno is now locked. */
1879 if (iaxs[callno]->peercallno) {
1880 /* Send LAGRQ packet. */
1881 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1882
1883 /* Schedule sending next lagrq. */
1884 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1885 }
1886
1887 ast_mutex_unlock(&iaxsl[callno]);
1888 }
1889
1890 static int send_lagrq(const void *data)
1891 {
1892 #ifdef SCHED_MULTITHREADED
1893 if (schedule_action(__send_lagrq, data))
1894 #endif
1895 __send_lagrq(data);
1896 return 0;
1897 }
1898
1899 static unsigned char compress_subclass(iax2_format subclass)
1900 {
1901 int x;
1902 int power=-1;
1903 /* If it's 64 or smaller, just return it */
1904 if (subclass < IAX_FLAG_SC_LOG)
1905 return subclass;
1906 /* Otherwise find its power */
1907 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1908 if (subclass & (1LL << x)) {
1909 if (power > -1) {
1910 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1911 return 0;
1912 } else
1913 power = x;
1914 }
1915 }
1916 return power | IAX_FLAG_SC_LOG;
1917 }
1918
1919 static iax2_format uncompress_subclass(unsigned char csub)
1920 {
1921 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1922 if (csub & IAX_FLAG_SC_LOG) {
1923 /* special case for 'compressed' -1 */
1924 if (csub == 0xff)
1925 return -1;
1926 else
1927 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1928 }
1929 else
1930 return csub;
1931 }
1932
1933 static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1934 {
1935 int x;
1936 struct ast_format *found_format = NULL;
1937
1938 for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1939 struct ast_format *pref_format;
1940 uint64_t pref_bitfield;
1941
1942 pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1943 if (!pref_bitfield) {
1944 break;
1945 }
1946
1947 pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1948 if (!pref_format) {
1949 /* The bitfield is not associated with any format. */
1950 continue;
1951 }
1952 found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1953 if (found_format) {
1954 break;
1955 }
1956 }
1957
1958 if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1959 return found_format;
1960 }
1961
1962 ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1963 ao2_cleanup(found_format);
1964 return NULL;
1965 }
1966
1967 static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
1968 {
1969 struct ast_format_cap *cap;
1970 struct ast_format *tmpfmt;
1971 iax2_format format = 0;
1972
1973 if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1974 iax2_format_compatibility_bitfield2cap(formats, cap);
1975 tmpfmt = codec_choose_from_prefs(pref, cap);
1976 if (!tmpfmt) {
1977 ao2_ref(cap, -1);
1978 return 0;
1979 }
1980
1981 format = ast_format_compatibility_format2bitfield(tmpfmt);
1982 ao2_ref(tmpfmt, -1);
1983 ao2_ref(cap, -1);
1984 }
1985
1986 return format;
1987 }
1988
1989 const char *iax2_getformatname(iax2_format format)
1990 {
1991 struct ast_format *tmpfmt;
1992
1993 tmpfmt = ast_format_compatibility_bitfield2format(format);
1994 if (!tmpfmt) {
1995 return "Unknown";
1996 }
1997
1998 return ast_format_get_name(tmpfmt);
1999 }
2000
2001 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
2002 {
2003 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2004
2005 if (!cap) {
2006 return "(Nothing)";
2007 }
2008 iax2_format_compatibility_bitfield2cap(format, cap);
2009 ast_format_cap_get_names(cap, codec_buf);
2010 ao2_ref(cap, -1);
2011
2012 return ast_str_buffer(*codec_buf);
2013 }
2014
2015 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
2016 {
2017 int res, i;
2018 struct ast_format_cap *cap;
2019
2020 /* We want to add the formats to the cap in the preferred order */
2021 cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2022 if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
2023 ao2_cleanup(cap);
2024 return 1;
2025 }
2026
2027 res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
2028
2029 /* Adjust formats bitfield and pref list to match. */
2030 *formats = iax2_format_compatibility_cap2bitfield(cap);
2031 iax2_codec_pref_remove_missing(pref, *formats);
2032
2033 for (i = 0; i < ast_format_cap_count(cap); i++) {
2034 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
2035
2036 iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
2037 ao2_ref(fmt, -1);
2038 }
2039
2040 ao2_ref(cap, -1);
2041
2042 return res;
2043 }
2044
2045 /*!
2046 * \note The only member of the peer passed here guaranteed to be set is the name field
2047 */
2048 static int peer_hash_cb(const void *obj, const int flags)
2049 {
2050 const struct iax2_peer *peer = obj;
2051 const char *name = obj;
2052
2053 return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
2054 }
2055
2056 /*!
2057 * \note The only member of the peer passed here guaranteed to be set is the name field
2058 */
2059 static int peer_cmp_cb(void *obj, void *arg, int flags)
2060 {
2061 struct iax2_peer *peer = obj, *peer2 = arg;
2062 const char *name = arg;
2063
2064 return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
2065 CMP_MATCH | CMP_STOP : 0;
2066 }
2067
2068 /*!
2069 * \note The only member of the user passed here guaranteed to be set is the name field
2070 */
2071 static int user_hash_cb(const void *obj, const int flags)
2072 {
2073 const struct iax2_user *user = obj;
2074 const char *name = obj;
2075
2076 return ast_str_hash(flags & OBJ_KEY ? name : user->name);
2077 }
2078
2079 /*!
2080 * \note The only member of the user passed here guaranteed to be set is the name field
2081 */
2082 static int user_cmp_cb(void *obj, void *arg, int flags)
2083 {
2084 struct iax2_user *user = obj, *user2 = arg;
2085 const char *name = arg;
2086
2087 return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2088 CMP_MATCH | CMP_STOP : 0;
2089 }
2090
2091 /*!
2092 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2093 * so do not call it with a pvt lock held.
2094 */
2095 static struct iax2_peer *find_peer(const char *name, int realtime)
2096 {
2097 struct iax2_peer *peer = NULL;
2098
2099 peer = ao2_find(peers, name, OBJ_KEY);
2100
2101 /* Now go for realtime if applicable */
2102 if (!peer && realtime) {
2103 peer = realtime_peer(name, NULL);
2104 }
2105 return peer;
2106 }
2107
2108 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2109 {
2110 ao2_ref(peer, +1);
2111 return peer;
2112 }
2113
2114 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2115 {
2116 ao2_ref(peer, -1);
2117 return NULL;
2118 }
2119
2120 static struct iax2_user *find_user(const char *name)
2121 {
2122 return ao2_find(users, name, OBJ_KEY);
2123 }
2124
2125 static inline struct iax2_user *user_unref(struct iax2_user *user)
2126 {
2127 ao2_ref(user, -1);
2128 return NULL;
2129 }
2130
2131 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2132 {
2133 struct iax2_peer *peer = NULL;
2134 int res = 0;
2135 struct ao2_iterator i;
2136
2137 i = ao2_iterator_init(peers, 0);
2138 while ((peer = ao2_iterator_next(&i))) {
2139
2140 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2141 ast_copy_string(host, peer->name, len);
2142 peer_unref(peer);
2143 res = 1;
2144 break;
2145 }
2146 peer_unref(peer);
2147 }
2148 ao2_iterator_destroy(&i);
2149
2150 if (!peer) {
2151 peer = realtime_peer(NULL, &addr);
2152 if (peer) {
2153 ast_copy_string(host, peer->name, len);
2154 peer_unref(peer);
2155 res = 1;
2156 }
2157 }
2158
2159 return res;
2160 }
2161
2162 /* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2163 static int iax2_delete_from_sched(const void* data)
2164 {
2165 int sched_id = (int)(long)data;
2166
2167 AST_SCHED_DEL(sched, sched_id);
2168
2169 return 0;
2170 }
2171
2172 /*!\note Assumes the lock on the pvt is already held, when
2173 * iax2_destroy_helper() is called. */
2174 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2175 {
2176 /* Decrement AUTHREQ count if needed */
2177 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2178 struct iax2_user *user;
2179
2180 user = ao2_find(users, pvt->username, OBJ_KEY);
2181 if (user) {
2182 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2183 user_unref(user);
2184 }
2185
2186 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2187 }
2188
2189
2190 /* Mark call destroy initiated flag. */
2191 pvt->destroy_initiated = 1;
2192
2193 /*
2194 * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2195 * Already running tasks will be terminated because of destroy_initiated.
2196 *
2197 * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2198 * it leads to a deadlock between the scheduler thread callback locking
2199 * the callno mutex and this thread which holds the callno mutex one or
2200 * more times. It is better to have another thread delete the scheduled
2201 * callbacks which doesn't lock the callno mutex.
2202 */
2203 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2204 iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2205
2206 pvt->pingid = -1;
2207 pvt->lagid = -1;
2208
2209 AST_SCHED_DEL(sched, pvt->autoid);
2210 AST_SCHED_DEL(sched, pvt->authid);
2211 AST_SCHED_DEL(sched, pvt->initid);
2212 AST_SCHED_DEL(sched, pvt->jbid);
2213 AST_SCHED_DEL(sched, pvt->keyrotateid);
2214 }
2215
2216 static void iax2_frame_free(struct iax_frame *fr)
2217 {
2218 AST_SCHED_DEL(sched, fr->retrans);
2219 iax_frame_free(fr);
2220 }
2221
2222 static int scheduled_destroy(const void *vid)
2223 {
2224 unsigned short callno = PTR_TO_CALLNO(vid);
2225 ast_mutex_lock(&iaxsl[callno]);
2226 if (iaxs[callno]) {
2227 ast_debug(1, "Really destroying %d now...\n", callno);
2228 iax2_destroy(callno);
2229 }
2230 ast_mutex_unlock(&iaxsl[callno]);
2231 return 0;
2232 }
2233
2234 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2235 {
2236 if (s->f.datalen) {
2237 ast_free(s->f.data.ptr);
2238 }
2239 ast_free(s);
2240 }
2241
2242 /*! \brief This function must be called once we are sure the other side has
2243 * given us a call number. All signaling is held here until that point. */
2244 static void send_signaling(struct chan_iax2_pvt *pvt)
2245 {
2246 struct signaling_queue_entry *s = NULL;
2247
2248 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2249 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2250 free_signaling_queue_entry(s);
2251 }
2252 pvt->hold_signaling = 0;
2253 }
2254
2255 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2256 * we have received a destination call number. */
2257 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2258 {
2259 struct signaling_queue_entry *qe;
2260
2261 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2262 return 1; /* do not queue this frame */
2263 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2264 return -1; /* out of memory */
2265 }
2266
2267 /* copy ast_frame into our queue entry */
2268 qe->f = *f;
2269 if (qe->f.datalen) {
2270 /* if there is data in this frame copy it over as well */
2271 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2272 free_signaling_queue_entry(qe);
2273 return -1;
2274 }
2275 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2276 }
2277 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2278
2279 return 0;
2280 }
2281
2282 static void pvt_destructor(void *obj)
2283 {
2284 struct chan_iax2_pvt *pvt = obj;
2285 struct iax_frame *cur = NULL;
2286 struct signaling_queue_entry *s = NULL;
2287
2288 ast_mutex_lock(&iaxsl[pvt->callno]);
2289
2290 iax2_destroy_helper(pvt);
2291
2292 sched_delay_remove(&pvt->addr, pvt->callno_entry);
2293 pvt->callno_entry = 0;
2294
2295 /* Already gone */
2296 ast_set_flag64(pvt, IAX_ALREADYGONE);
2297
2298 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2299 /* Cancel any pending transmissions */
2300 cur->retries = -1;
2301 }
2302
2303 ast_mutex_unlock(&iaxsl[pvt->callno]);
2304
2305 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2306 free_signaling_queue_entry(s);
2307 }
2308
2309 if (pvt->reg) {
2310 pvt->reg->callno = 0;
2311 }
2312
2313 if (!pvt->owner) {
2314 jb_frame frame;
2315 if (pvt->vars) {
2316 ast_variables_destroy(pvt->vars);
2317 pvt->vars = NULL;
2318 }
2319
2320 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2321 iax2_frame_free(frame.data);
2322 }
2323
2324 jb_destroy(pvt->jb);
2325 ast_string_field_free_memory(pvt);
2326 }
2327 }
2328
2329 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2330 {
2331 struct chan_iax2_pvt *tmp;
2332 jb_conf jbconf;
2333
2334 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2335 return NULL;
2336 }
2337
2338 tmp->pingid = -1;
2339 tmp->lagid = -1;
2340 tmp->autoid = -1;
2341 tmp->authid = -1;
2342 tmp->initid = -1;
2343 tmp->keyrotateid = -1;
2344 tmp->jbid = -1;
2345
2346 if (ast_string_field_init(tmp, 32)) {
2347 ao2_ref(tmp, -1);
2348 tmp = NULL;
2349 return NULL;
2350 }
2351
2352 tmp->prefs = prefs_global;
2353
2354 ast_string_field_set(tmp,exten, "s");
2355 ast_string_field_set(tmp,host, host);
2356
2357 tmp->jb = jb_new();
2358 jbconf.max_jitterbuf = maxjitterbuffer;
2359 jbconf.resync_threshold = resyncthreshold;
2360 jbconf.max_contig_interp = maxjitterinterps;
2361 jbconf.target_extra = jittertargetextra;
2362 jb_setconf(tmp->jb,&jbconf);
2363
2364 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2365
2366 tmp->hold_signaling = 1;
2367 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2368
2369 return tmp;
2370 }
2371
2372 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2373 {
2374 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2375 if (new) {
2376 size_t afdatalen = new->afdatalen;
2377 memcpy(new, fr, sizeof(*new));
2378 iax_frame_wrap(new, &fr->af);
2379 new->afdatalen = afdatalen;
2380 new->data = NULL;
2381 new->datalen = 0;
2382 new->direction = DIRECTION_INGRESS;
2383 new->retrans = -1;
2384 }
2385 return new;
2386 }
2387 /* keep these defined in this order. They are used in find_callno to
2388 * determine whether or not a new call number should be allowed. */
2389 enum {
2390 /* do not allow a new call number, only search ones in use for match */
2391 NEW_PREVENT = 0,
2392 /* search for match first, then allow a new one to be allocated */
2393 NEW_ALLOW = 1,
2394 /* do not search for match, force a new call number */
2395 NEW_FORCE = 2,
2396 /* do not search for match, force a new call number. Signifies call number
2397 * has been calltoken validated */
2398 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2399 };
2400
2401 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2402 {
2403 if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2404 /* This is the main host */
2405 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2406 (check_dcallno ? dcallno == cur->callno : 1) ) {
2407 /* That's us. Be sure we keep track of the peer call number */
2408 return 1;
2409 }
2410 }
2411 if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2412 /* We're transferring */
2413 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2414 return 1;
2415 }
2416 return 0;
2417 }
2418
2419 static int make_trunk(unsigned short callno, int locked)
2420 {
2421 int x;
2422 int res= 0;
2423 callno_entry entry;
2424 if (iaxs[callno]->oseqno) {
2425 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2426 return -1;
2427 }
2428 if (callno >= TRUNK_CALL_START) {
2429 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2430 return -1;
2431 }
2432
2433 if (get_unused_callno(
2434 CALLNO_TYPE_TRUNK,
2435 CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2436 &entry)) {
2437 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2438 return -1;
2439 }
2440
2441 x = CALLNO_ENTRY_GET_CALLNO(entry);
2442 ast_mutex_lock(&iaxsl[x]);
2443
2444 /*!
2445 * \note We delete these before switching the slot, because if
2446 * they fire in the meantime, they will generate a warning.
2447 */
2448 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2449 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2450 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2451 iaxs[x] = iaxs[callno];
2452 iaxs[x]->callno = x;
2453
2454 /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2455 * before assigning the new one */
2456 if (iaxs[x]->callno_entry) {
2457 iax2_sched_add(
2458 sched,
2459 MIN_REUSE_TIME * 1000,
2460 replace_callno,
2461 CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2462
2463 }
2464 iaxs[x]->callno_entry = entry;
2465
2466 iaxs[callno] = NULL;
2467 /* Update the two timers that should have been started */
2468 iaxs[x]->pingid = iax2_sched_add(sched,
2469 ping_time * 1000, send_ping, (void *)(long)x);
2470 iaxs[x]->lagid = iax2_sched_add(sched,
2471 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2472
2473 if (locked)
2474 ast_mutex_unlock(&iaxsl[callno]);
2475 res = x;
2476 if (!locked)
2477 ast_mutex_unlock(&iaxsl[x]);
2478
2479 /* We moved this call from a non-trunked to a trunked call */
2480 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2481
2482 return res;
2483 }
2484
2485 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2486 {
2487 if (!pvt->transfercallno) {
2488 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2489 return;
2490 }
2491
2492 ao2_link(iax_transfercallno_pvts, pvt);
2493 }
2494
2495 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2496 {
2497 if (!pvt->transfercallno) {
2498 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2499 return;
2500 }
2501
2502 ao2_unlink(iax_transfercallno_pvts, pvt);
2503 }
2504 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2505 {
2506 if (!pvt->peercallno) {
2507 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2508 return;
2509 }
2510
2511 ao2_link(iax_peercallno_pvts, pvt);
2512 }
2513
2514 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2515 {
2516 if (!pvt->peercallno) {
2517 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2518 return;
2519 }
2520
2521 ao2_unlink(iax_peercallno_pvts, pvt);
2522 }
2523
2524 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2525 {
2526 struct addr_range *lim = obj;
2527 lim->delme = 1;
2528 return 0;
2529 }
2530
2531 static int addr_range_hash_cb(const void *obj, const int flags)
2532 {
2533 const struct addr_range *lim = obj;
2534 return abs(ast_sockaddr_hash(&lim->ha.addr));
2535 }
2536
2537 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2538 {
2539 struct addr_range *lim1 = obj, *lim2 = arg;
2540 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2541 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2542 CMP_MATCH | CMP_STOP : 0;
2543 }
2544
2545 static int peercnt_hash_cb(const void *obj, const int flags)
2546 {
2547 const struct peercnt *peercnt = obj;
2548
2549 if (ast_sockaddr_isnull(&peercnt->addr)) {
2550 return 0;
2551 }
2552 return ast_sockaddr_hash(&peercnt->addr);
2553 }
2554
2555 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2556 {
2557 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2558 return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2559 }
2560
2561 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2562 {
2563 struct addr_range *addr_range = obj;
2564 struct ast_sockaddr *addr = arg;
2565 struct ast_sockaddr tmp_addr;
2566
2567 ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2568
2569 if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2570 return CMP_MATCH | CMP_STOP;
2571 }
2572 return 0;
2573 }
2574
2575 /*!
2576 * \internal
2577 *
2578 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2579 */
2580 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2581 {
2582 struct addr_range *addr_range;
2583 struct iax2_peer *peer = NULL;
2584 struct iax2_user *user = NULL;
2585 /* if no username is given, check for guest accounts */
2586 const char *find = S_OR(name, "guest");
2587 int res = 1; /* required by default */
2588 int optional = 0;
2589 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2590 /* There are only two cases in which calltoken validation is not required.
2591 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2592 * the peer definition has not set the requirecalltoken option.
2593 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2594 */
2595
2596 /* ----- Case 1 ----- */
2597 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2598 ao2_ref(addr_range, -1);
2599 optional = 1;
2600 }
2601
2602 /* ----- Case 2 ----- */
2603 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2604 calltoken_required = user->calltoken_required;
2605 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2606 calltoken_required = user->calltoken_required;
2607 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2608 calltoken_required = peer->calltoken_required;
2609 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2610 calltoken_required = peer->calltoken_required;
2611 }
2612
2613 if (peer) {
2614 peer_unref(peer);
2615 }
2616 if (user) {
2617 user_unref(user);
2618 }
2619
2620 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2621 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2622 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2623 res = 0;
2624 }
2625
2626 return res;
2627 }
2628
2629 /*!
2630 * \internal
2631 *
2632 * \brief set peercnt callno limit.
2633 *
2634 * \details
2635 * First looks in custom definitions. If not found, global limit
2636 * is used. Entries marked as reg already have
2637 * a custom limit set by a registration and are not modified.
2638 */
2639 static void set_peercnt_limit(struct peercnt *peercnt)
2640 {
2641 uint16_t limit = global_maxcallno;
2642 struct addr_range *addr_range;
2643 struct ast_sockaddr addr;
2644
2645 ast_sockaddr_copy(&addr, &peercnt->addr);
2646
2647 if (peercnt->reg && peercnt->limit) {
2648 return; /* this peercnt has a custom limit set by a registration */
2649 }
2650
2651 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2652 limit = addr_range->limit;
2653 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2654 ao2_ref(addr_range, -1);
2655 }
2656
2657 peercnt->limit = limit;
2658 }
2659
2660 /*!
2661 * \internal
2662 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2663 */
2664 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2665 {
2666 struct peercnt *peercnt = obj;
2667
2668 set_peercnt_limit(peercnt);
2669 ast_debug(1, "Reset limits for peercnts table\n");
2670
2671 return 0;
2672 }
2673
2674 /*!
2675 * \internal
2676 * \brief returns match if delme is set.
2677 */
2678 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2679 {
2680 struct addr_range *addr_range = obj;
2681
2682 return addr_range->delme ? CMP_MATCH : 0;
2683 }
2684
2685 /*!
2686 * \internal
2687 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2688 */
2689 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2690 {
2691 /* this function turns off and on custom callno limits set by peer registration */
2692 struct peercnt *peercnt;
2693 struct peercnt tmp;
2694
2695 ast_sockaddr_copy(&tmp.addr, sockaddr);
2696
2697 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2698 peercnt->reg = reg;
2699 if (limit) {
2700 peercnt->limit = limit;
2701 } else {
2702 set_peercnt_limit(peercnt);
2703 }
2704 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2705 ao2_ref(peercnt, -1); /* decrement ref from find */
2706 }
2707 }
2708
2709 /*!
2710 * \internal
2711 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2712 *
2713 * \details First searches for the address in the peercnts table. If found
2714 * the current count is incremented. If not found a new peercnt is allocated
2715 * and linked into the peercnts table with a call number count of 1.
2716 */
2717 static int peercnt_add(struct ast_sockaddr *addr)
2718 {
2719 struct peercnt *peercnt;
2720 int res = 0;
2721 struct peercnt tmp;
2722
2723 ast_sockaddr_copy(&tmp.addr, addr);
2724
2725 /* Reasoning for peercnts container lock: Two identical ip addresses
2726 * could be added by different threads at the "same time". Without the container
2727 * lock, both threads could alloc space for the same object and attempt
2728 * to link to table. With the lock, one would create the object and link
2729 * to table while the other would find the already created peercnt object
2730 * rather than creating a new one. */
2731 ao2_lock(peercnts);
2732 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2733 ao2_lock(peercnt);
2734 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2735 ao2_lock(peercnt);
2736 /* create and set defaults */
2737 ast_sockaddr_copy(&peercnt->addr, addr);
2738 set_peercnt_limit(peercnt);
2739 /* guarantees it does not go away after unlocking table
2740 * ao2_find automatically adds this */
2741 ao2_link(peercnts, peercnt);
2742 } else {
2743 ao2_unlock(peercnts);
2744 return -1;
2745 }
2746
2747 /* check to see if the address has hit its callno limit. If not increment cur. */
2748 if (peercnt->limit > peercnt->cur) {
2749 peercnt->cur++;
2750 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2751 } else { /* max num call numbers for this peer has been reached! */
2752 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2753 res = -1;
2754 }
2755
2756 /* clean up locks and ref count */
2757 ao2_unlock(peercnt);
2758 ao2_unlock(peercnts);
2759 ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2760
2761 return res;
2762 }
2763
2764 /*!
2765 * \internal
2766 * \brief decrements a peercnts table entry
2767 */
2768 static void peercnt_remove(struct peercnt *peercnt)
2769 {
2770 struct ast_sockaddr addr;
2771
2772 ast_sockaddr_copy(&addr, &peercnt->addr);
2773
2774 /*
2775 * Container locked here since peercnt may be unlinked from
2776 * list. If left unlocked, peercnt_add could try and grab this
2777 * entry from the table and modify it at the "same time" this
2778 * thread attempts to unlink it.
2779 */
2780 ao2_lock(peercnts);
2781 peercnt->cur--;
2782 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2783 /* if this was the last connection from the peer remove it from table */
2784 if (peercnt->cur == 0) {
2785 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2786 }
2787 ao2_unlock(peercnts);
2788 }
2789
2790 /*!
2791 * \internal
2792 * \brief called by scheduler to decrement object
2793 */
2794 static int peercnt_remove_cb(const void *obj)
2795 {
2796 struct peercnt *peercnt = (struct peercnt *) obj;
2797
2798 peercnt_remove(peercnt);
2799 ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2800
2801 return 0;
2802 }
2803
2804 /*!
2805 * \internal
2806 * \brief decrements peercnts connection count, finds by addr
2807 */
2808 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2809 {
2810 struct peercnt *peercnt;
2811 struct peercnt tmp;
2812
2813 ast_sockaddr_copy(&tmp.addr, addr);
2814
2815 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2816 peercnt_remove(peercnt);
2817 ao2_ref(peercnt, -1); /* decrement ref from find */
2818 }
2819 return 0;
2820 }
2821
2822 /*!
2823 * \internal
2824 * \brief Create callno_limit entry based on configuration
2825 */
2826 static void build_callno_limits(struct ast_variable *v)
2827 {
2828 struct addr_range *addr_range = NULL;
2829 struct addr_range tmp;
2830 struct ast_ha *ha;
2831 int limit;
2832 int error;
2833 int found;
2834
2835 for (; v; v = v->next) {
2836 limit = -1;
2837 error = 0;
2838 found = 0;
2839 ha = ast_append_ha("permit", v->name, NULL, &error);
2840
2841 /* check for valid config information */
2842 if (error) {
2843 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2844 continue;
2845 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2846 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2847 ast_free_ha(ha);
2848 continue;
2849 }
2850
2851 ast_copy_ha(ha, &tmp.ha);
2852 /* find or create the addr_range */
2853 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2854 ao2_lock(addr_range);
2855 found = 1;
2856 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2857 ast_free_ha(ha);
2858 return; /* out of memory */
2859 }
2860
2861 /* copy over config data into addr_range object */
2862 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2863 ast_free_ha(ha); /* cleanup the tmp ha */
2864 addr_range->limit = limit;
2865 addr_range->delme = 0;
2866
2867 /* cleanup */
2868 if (found) {
2869 ao2_unlock(addr_range);
2870 } else {
2871 ao2_link(callno_limits, addr_range);
2872 }
2873 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2874 }
2875 }
2876
2877 /*!
2878 * \internal
2879 * \brief Create calltoken_ignores entry based on configuration
2880 */
2881 static int add_calltoken_ignore(const char *addr)
2882 {
2883 struct addr_range tmp;
2884 struct addr_range *addr_range = NULL;
2885 struct ast_ha *ha = NULL;
2886 int error = 0;
2887
2888 if (ast_strlen_zero(addr)) {
2889 ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2890 return -1;
2891 }
2892
2893 ha = ast_append_ha("permit", addr, NULL, &error);
2894
2895 /* check for valid config information */
2896 if (error) {
2897 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2898 return -1;
2899 }
2900
2901 ast_copy_ha(ha, &tmp.ha);
2902 /* find or create the addr_range */
2903 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2904 ao2_lock(addr_range);
2905 addr_range->delme = 0;
2906 ao2_unlock(addr_range);
2907 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2908 /* copy over config data into addr_range object */
2909 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2910 ao2_link(calltoken_ignores, addr_range);
2911 } else {
2912 ast_free_ha(ha);
2913 return -1;
2914 }
2915
2916 ast_free_ha(ha);
2917 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2918
2919 return 0;
2920 }
2921
2922 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2923 {
2924 struct ao2_iterator i;
2925 struct peercnt *peercnt;
2926 struct ast_sockaddr addr;
2927 int found = 0;
2928
2929 switch (cmd) {
2930 case CLI_INIT:
2931 e->command = "iax2 show callnumber usage";
2932 e->usage =
2933 "Usage: iax2 show callnumber usage [IP address]\n"
2934 " Shows current IP addresses which are consuming iax2 call numbers\n";
2935 return NULL;
2936 case CLI_GENERATE:
2937 return NULL;
2938 case CLI_HANDLER:
2939 if (a->argc < 4 || a->argc > 5)
2940 return CLI_SHOWUSAGE;
2941
2942 if (a->argc == 4) {
2943 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2944 }
2945
2946 i = ao2_iterator_init(peercnts, 0);
2947 while ((peercnt = ao2_iterator_next(&i))) {
2948 ast_sockaddr_copy(&addr, &peercnt->addr);
2949
2950 if (a->argc == 5) {
2951 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2952 ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2953 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2954 ao2_ref(peercnt, -1);
2955 found = 1;
2956 break;
2957 }
2958 } else {
2959 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2960 }
2961 ao2_ref(peercnt, -1);
2962 }
2963 ao2_iterator_destroy(&i);
2964
2965 if (a->argc == 4) {
2966 size_t pool_avail = callno_pool.available;
2967 size_t trunk_pool_avail = callno_pool_trunk.available;
2968
2969 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2970 "Non-CallToken Validated Callno Used: %d\n",
2971 global_maxcallno_nonval,
2972 total_nonval_callno_used);
2973
2974 ast_cli(a->fd, "Total Available Callno: %zu\n"
2975 "Regular Callno Available: %zu\n"
2976 "Trunk Callno Available: %zu\n",
2977 pool_avail + trunk_pool_avail,
2978 pool_avail,
2979 trunk_pool_avail);
2980 } else if (a->argc == 5 && !found) {
2981 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2982 }
2983
2984
2985 return CLI_SUCCESS;
2986 default:
2987 return NULL;
2988 }
2989 }
2990
2991 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2992 {
2993 struct call_number_pool *pool = NULL;
2994 callno_entry swap;
2995 size_t choice;
2996
2997 switch (type) {
2998 case CALLNO_TYPE_NORMAL:
2999 pool = &callno_pool;
3000 break;
3001 case CALLNO_TYPE_TRUNK:
3002 pool = &callno_pool_trunk;
3003 break;
3004 default:
3005 ast_assert(0);
3006 break;
3007 }
3008
3009 /* If we fail, make sure this has a defined value */
3010 *entry = 0;
3011
3012 /* We lock here primarily to ensure thread safety of the
3013 * total_nonval_callno_used check and increment */
3014 ast_mutex_lock(&callno_pool_lock);
3015
3016 /* Bail out if we don't have any available call numbers */
3017 if (!pool->available) {
3018 ast_log(LOG_WARNING, "Out of call numbers\n");
3019 ast_mutex_unlock(&callno_pool_lock);
3020 return 1;
3021 }
3022
3023 /* Only a certain number of non-validated call numbers should be allocated.
3024 * If there ever is an attack, this separates the calltoken validating users
3025 * from the non-calltoken validating users. */
3026 if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
3027 ast_log(LOG_WARNING,
3028 "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
3029 total_nonval_callno_used,
3030 global_maxcallno_nonval);
3031 ast_mutex_unlock(&callno_pool_lock);
3032 return 1;
3033 }
3034
3035 /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
3036 * available call numbers. The array of call numbers begins as an ordered
3037 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
3038 * - let's call that x. When a call number is needed we pick a random index
3039 * into the array between 0 and x and use that as our call number. In a
3040 * typical FYD shuffle, we would swap the value that we are extracting with
3041 * the number at x, but in our case we swap and don't touch the value at x
3042 * because it is effectively invisible. We rely on the rest of the IAX2 core
3043 * to return the number to us at some point. Finally, we decrement x by 1
3044 * which establishes our new unused range.
3045 *
3046 * When numbers are returned to the pool, we put them just past x and bump x
3047 * by 1 so that this number is now available for re-use. */
3048
3049 choice = ast_random() % pool->available;
3050
3051 *entry = pool->numbers[choice];
3052 swap = pool->numbers[pool->available - 1];
3053
3054 pool->numbers[choice] = swap;
3055 pool->available--;
3056
3057 if (validated) {
3058 CALLNO_ENTRY_SET_VALIDATED(*entry);
3059 } else {
3060 total_nonval_callno_used++;
3061 }
3062
3063 ast_mutex_unlock(&callno_pool_lock);
3064
3065 return 0;
3066 }
3067
3068 static int replace_callno(const void *obj)
3069 {
3070 callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
3071 struct call_number_pool *pool;
3072
3073 /* We lock here primarily to ensure thread safety of the
3074 * total_nonval_callno_used check and decrement */
3075 ast_mutex_lock(&callno_pool_lock);
3076
3077 if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
3078 if (total_nonval_callno_used) {
3079 total_nonval_callno_used--;
3080 } else {
3081 ast_log(LOG_ERROR,
3082 "Attempted to decrement total non calltoken validated "
3083 "callnumbers below zero. Callno is: %d\n",
3084 CALLNO_ENTRY_GET_CALLNO(entry));
3085 }
3086 }
3087
3088 if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
3089 pool = &callno_pool;
3090 } else {
3091 pool = &callno_pool_trunk;
3092 }
3093
3094 ast_assert(pool->capacity > pool->available);
3095
3096 /* This clears the validated flag */
3097 entry = CALLNO_ENTRY_GET_CALLNO(entry);
3098
3099 pool->numbers[pool->available] = entry;
3100 pool->available++;
3101
3102 ast_mutex_unlock(&callno_pool_lock);
3103
3104 return 0;
3105 }
3106
3107 static int create_callno_pools(void)
3108 {
3109 uint16_t i;
3110
3111 callno_pool.available = callno_pool_trunk.available = 0;
3112
3113 /* We start at 2. 0 and 1 are reserved. */
3114 for (i = 2; i < TRUNK_CALL_START; i++) {
3115 callno_pool.numbers[callno_pool.available] = i;
3116 callno_pool.available++;
3117 }
3118
3119 for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3120 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
3121 callno_pool_trunk.available++;
3122 }
3123
3124 callno_pool.capacity = callno_pool.available;
3125 callno_pool_trunk.capacity = callno_pool_trunk.available;
3126
3127 ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
3128
3129 return 0;
3130 }
3131
3132 /*!
3133 * \internal
3134 * \brief Schedules delayed removal of iax2_pvt call number data
3135 *
3136 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3137 * available again, and the address from the previous connection must be decremented
3138 * from the peercnts table. This function schedules these operations to take place.
3139 */
3140 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3141 {
3142 int i;
3143 struct peercnt *peercnt;
3144 struct peercnt tmp;
3145
3146 ast_sockaddr_copy(&tmp.addr, addr);
3147
3148 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3149 /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3150 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3151 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3152 if (i == -1) {
3153 ao2_ref(peercnt, -1);
3154 }
3155 }
3156
3157 iax2_sched_add(
3158 sched,
3159 MIN_REUSE_TIME * 1000,
3160 replace_callno,
3161 CALLNO_ENTRY_TO_PTR(entry));
3162 }
3163
3164 /*!
3165 * \internal
3166 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3167 *
3168 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3169 * a new callno.
3170 */
3171 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3172 {
3173 if (frametype != AST_FRAME_IAX) {
3174 return 0;
3175 }
3176 switch (subclass) {
3177 case IAX_COMMAND_NEW:
3178 case IAX_COMMAND_REGREQ:
3179 case IAX_COMMAND_FWDOWNL:
3180 case IAX_COMMAND_REGREL:
3181 return 1;
3182 case IAX_COMMAND_POKE:
3183 if (!inbound) {
3184 return 1;
3185 }
3186 break;
3187 }
3188 return 0;
3189 }
3190
3191 /*!
3192 * \note Calling this function while holding another pvt lock can cause a deadlock.
3193 */
3194 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3195 {
3196 int res = 0;
3197 int x;
3198 /* this call is calltoken validated as long as it is either NEW_FORCE
3199 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3200 int validated = (new > NEW_ALLOW) ? 1 : 0;
3201 char host[80];
3202
3203 if (new <= NEW_ALLOW) {
3204 if (callno) {
3205 struct chan_iax2_pvt *pvt;
3206 struct chan_iax2_pvt tmp_pvt = {
3207 .callno = dcallno,
3208 .peercallno = callno,
3209 .transfercallno = callno,
3210 /* hack!! */
3211 .frames_received = check_dcallno,
3212 };
3213
3214 ast_sockaddr_copy(&tmp_pvt.addr, addr);
3215 /* this works for finding normal call numbers not involving transferring */
3216 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3217 if (return_locked) {
3218 ast_mutex_lock(&iaxsl[pvt->callno]);
3219 }
3220 res = pvt->callno;
3221 ao2_ref(pvt, -1);
3222 pvt = NULL;
3223 return res;
3224 }
3225 /* this searches for transfer call numbers that might not get caught otherwise */
3226 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3227 ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3228 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3229 if (return_locked) {
3230 ast_mutex_lock(&iaxsl[pvt->callno]);
3231 }
3232 res = pvt->callno;
3233 ao2_ref(pvt, -1);
3234 pvt = NULL;
3235 return res;
3236 }
3237 }
3238 /* This will occur on the first response to a message that we initiated,
3239 * such as a PING. */
3240 if (dcallno) {
3241 ast_mutex_lock(&iaxsl[dcallno]);
3242 }
3243 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3244 iaxs[dcallno]->peercallno = callno;
3245 res = dcallno;
3246 store_by_peercallno(iaxs[dcallno]);
3247 if (!res || !return_locked) {
3248 ast_mutex_unlock(&iaxsl[dcallno]);
3249 }
3250 return res;
3251 }
3252 if (dcallno) {
3253 ast_mutex_unlock(&iaxsl[dcallno]);
3254 }
3255 }
3256 if (!res && (new >= NEW_ALLOW)) {
3257 callno_entry entry;
3258
3259 /* It may seem odd that we look through the peer list for a name for
3260 * this *incoming* call. Well, it is weird. However, users don't
3261 * have an IP address/port number that we can match against. So,
3262 * this is just checking for a peer that has that IP/port and
3263 * assuming that we have a user of the same name. This isn't always
3264 * correct, but it will be changed if needed after authentication. */
3265 if (!iax2_getpeername(*addr, host, sizeof(host)))
3266 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3267
3268 if (peercnt_add(addr)) {
3269 /* This address has hit its callnumber limit. When the limit
3270 * is reached, the connection is not added to the peercnts table.*/
3271 return 0;
3272 }
3273
3274 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3275 /* since we ran out of space, remove the peercnt
3276 * entry we added earlier */
3277 peercnt_remove_by_addr(addr);
3278 ast_log(LOG_WARNING, "No more space\n");
3279 return 0;
3280 }
3281 x = CALLNO_ENTRY_GET_CALLNO(entry);
3282 ast_mutex_lock(&iaxsl[x]);
3283
3284 iaxs[x] = new_iax(addr, host);
3285 if (iaxs[x]) {
3286 if (iaxdebug)
3287 ast_debug(1, "Creating new call structure %d\n", x);
3288 iaxs[x]->callno_entry = entry;
3289 iaxs[x]->sockfd = sockfd;
3290 ast_sockaddr_copy(&iaxs[x]->addr, addr);
3291 iaxs[x]->peercallno = callno;
3292 iaxs[x]->callno = x;
3293 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3294 iaxs[x]->expiry = min_reg_expire;
3295 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3296 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3297 iaxs[x]->amaflags = amaflags;
3298 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3299 ast_string_field_set(iaxs[x], accountcode, accountcode);
3300 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3301 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3302 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3303
3304 if (iaxs[x]->peercallno) {
3305 store_by_peercallno(iaxs[x]);
3306 }
3307 } else {
3308 ast_log(LOG_WARNING, "Out of resources\n");
3309 ast_mutex_unlock(&iaxsl[x]);
3310 replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3311 return 0;
3312 }
3313 if (!return_locked)
3314 ast_mutex_unlock(&iaxsl[x]);
3315 res = x;
3316 }
3317 return res;
3318 }
3319
3320 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3321 return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3322 }
3323
3324 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3325
3326 return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3327 }
3328
3329 /*!
3330 * \brief Queue a frame to a call's owning asterisk channel
3331 *
3332 * \pre This function assumes that iaxsl[callno] is locked when called.
3333 *
3334 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3335 * was valid before calling it, it may no longer be valid after calling it.
3336 * This function may unlock and lock the mutex associated with this callno,
3337 * meaning that another thread may grab it and destroy the call.
3338 */
3339 static int iax2_queue_frame(int callno, struct ast_frame *f)
3340 {
3341 iax2_lock_owner(callno);
3342 if (iaxs[callno] && iaxs[callno]->owner) {
3343 ast_queue_frame(iaxs[callno]->owner, f);
3344 ast_channel_unlock(iaxs[callno]->owner);
3345 }
3346 return 0;
3347 }
3348
3349 /*!
3350 * \brief Queue a hold frame on the ast_channel owner
3351 *
3352 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3353 * is active for the given call number.
3354 *
3355 * \pre Assumes lock for callno is already held.
3356 *
3357 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3358 * was valid before calling it, it may no longer be valid after calling it.
3359 * This function may unlock and lock the mutex associated with this callno,
3360 * meaning that another thread may grab it and destroy the call.
3361 */
3362 static int iax2_queue_hold(int callno, const char *musicclass)
3363 {
3364 iax2_lock_owner(callno);
3365 if (iaxs[callno] && iaxs[callno]->owner) {
3366 ast_queue_hold(iaxs[callno]->owner, musicclass);
3367 ast_channel_unlock(iaxs[callno]->owner);
3368 }
3369 return 0;
3370 }
3371
3372 /*!
3373 * \brief Queue an unhold frame on the ast_channel owner
3374 *
3375 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3376 * is active for the given call number.
3377 *
3378 * \pre Assumes lock for callno is already held.
3379 *
3380 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3381 * was valid before calling it, it may no longer be valid after calling it.
3382 * This function may unlock and lock the mutex associated with this callno,
3383 * meaning that another thread may grab it and destroy the call.
3384 */
3385 static int iax2_queue_unhold(int callno)
3386 {
3387 iax2_lock_owner(callno);
3388 if (iaxs[callno] && iaxs[callno]->owner) {
3389 ast_queue_unhold(iaxs[callno]->owner);
3390 ast_channel_unlock(iaxs[callno]->owner);
3391 }
3392 return 0;
3393 }
3394
3395 /*!
3396 * \brief Queue a hangup frame on the ast_channel owner
3397 *
3398 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3399 * is active for the given call number.
3400 *
3401 * \pre Assumes lock for callno is already held.
3402 *
3403 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3404 * was valid before calling it, it may no longer be valid after calling it.
3405 * This function may unlock and lock the mutex associated with this callno,
3406 * meaning that another thread may grab it and destroy the call.
3407 */
3408 static int iax2_queue_hangup(int callno)
3409 {
3410 iax2_lock_owner(callno);
3411 if (iaxs[callno] && iaxs[callno]->owner) {
3412 ast_queue_hangup(iaxs[callno]->owner);
3413 ast_channel_unlock(iaxs[callno]->owner);
3414 }
3415 return 0;
3416 }
3417
3418 /*!
3419 * \note This function assumes that iaxsl[callno] is locked when called.
3420 *
3421 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3422 * was valid before calling it, it may no longer be valid after calling it.
3423 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3424 * associated with this callno, meaning that another thread may grab it and destroy the call.
3425 */
3426 static int __do_deliver(void *data)
3427 {
3428 /* Just deliver the packet by using queueing. This is called by
3429 the IAX thread with the iaxsl lock held. */
3430 struct iax_frame *fr = data;
3431 fr->retrans = -1;
3432 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3433 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3434 iax2_queue_frame(fr->callno, &fr->af);
3435 /* Free our iax frame */
3436 iax2_frame_free(fr);
3437 /* And don't run again */
3438 return 0;
3439 }
3440
3441 static int handle_error(void)
3442 {
3443 /* XXX Ideally we should figure out why an error occurred and then abort those
3444 rather than continuing to try. Unfortunately, the published interface does
3445 not seem to work XXX */
3446 #if 0
3447 struct sockaddr_in *sin;
3448 int res;
3449 struct msghdr m;
3450 struct sock_extended_err e;
3451 m.msg_name = NULL;
3452 m.msg_namelen = 0;
3453 m.msg_iov = NULL;
3454 m.msg_control = &e;
3455 m.msg_controllen = sizeof(e);
3456 m.msg_flags = 0;
3457 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3458 if (res < 0)
3459 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3460 else {
3461 if (m.msg_controllen) {
3462 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3463 if (sin)
3464 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3465 else
3466 ast_log(LOG_WARNING, "No address detected??\n");
3467 } else {
3468 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3469 }
3470 }
3471 #endif
3472 return 0;
3473 }
3474
3475 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3476 {
3477 int res;
3478 res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3479
3480 if (res < 0) {
3481 ast_debug(1, "Received error: %s\n", strerror(errno));
3482 handle_error();
3483 } else
3484 res = 0;
3485 return res;
3486 }
3487
3488 static int send_packet(struct iax_frame *f)
3489 {
3490 int res;
3491 int callno = f->callno;
3492
3493 /* Don't send if there was an error, but return error instead */
3494 if (!callno || !iaxs[callno] || iaxs[callno]->error)
3495 return -1;
3496
3497 /* Called with iaxsl held */
3498 if (iaxdebug) {
3499 ast_debug(8, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3500 }
3501 if (f->transfer) {
3502 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3503 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3504 } else {
3505 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3506 res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3507 }
3508 if (res < 0) {
3509 if (iaxdebug)
3510 ast_debug(1, "Received error: %s\n", strerror(errno));
3511 handle_error();
3512 } else
3513 res = 0;
3514
3515 return res;
3516 }
3517
3518 /*!
3519 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3520 * for the given call number may disappear during its execution.
3521 */
3522 static int iax2_predestroy(int callno)
3523 {
3524 struct ast_channel *c = NULL;
3525 struct chan_iax2_pvt *pvt = iaxs[callno];
3526
3527 if (!pvt)
3528 return -1;
3529
3530 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3531 iax2_destroy_helper(pvt);
3532 ast_set_flag64(pvt, IAX_ALREADYGONE);
3533 }
3534
3535 if ((c = pvt->owner)) {
3536 ast_channel_tech_pvt_set(c, NULL);
3537 iax2_queue_hangup(callno);
3538 pvt->owner = NULL;
3539 ast_module_unref(ast_module_info->self);
3540 }
3541
3542 return 0;
3543 }
3544
3545 static void iax2_destroy(int callno)
3546 {
3547 struct chan_iax2_pvt *pvt = NULL;
3548 struct ast_channel *owner = NULL;
3549
3550 retry:
3551 if ((pvt = iaxs[callno])) {
3552 #if 0
3553 /* iax2_destroy_helper gets called from this function later on. When
3554 * called twice, we get the (previously) familiar FRACK! errors in
3555 * devmode, from the scheduler. An alternative to this approach is to
3556 * reset the scheduler entries to -1 when they're deleted in
3557 * iax2_destroy_helper(). That approach was previously decided to be
3558 * "wrong" because "the memory is going to be deallocated anyway. Why
3559 * should we be resetting those values?" */
3560 iax2_destroy_helper(pvt);
3561 #endif
3562 }
3563
3564 owner = pvt ? pvt->owner : NULL;
3565
3566 if (owner) {
3567 if (ast_channel_trylock(owner)) {
3568 ast_debug(3, "Avoiding IAX destroy deadlock\n");
3569 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3570 goto retry;
3571 }
3572 }
3573
3574 if (!owner) {
3575 iaxs[callno] = NULL;
3576 }
3577
3578 if (pvt) {
3579 if (!owner) {
3580 pvt->owner = NULL;
3581 } else {
3582 /* If there's an owner, prod it to give up */
3583 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3584 * because we already hold the owner channel lock. */
3585 ast_queue_hangup(owner);
3586 }
3587
3588 if (pvt->peercallno) {
3589 remove_by_peercallno(pvt);
3590 }
3591
3592 if (pvt->transfercallno) {
3593 remove_by_transfercallno(pvt);
3594 }
3595
3596 if (!owner) {
3597 ao2_ref(pvt, -1);
3598 pvt = NULL;
3599 }
3600 }
3601
3602 if (owner) {
3603 ast_channel_unlock(owner);
3604 }
3605 }
3606
3607 static int update_packet(struct iax_frame *f)
3608 {
3609 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3610 struct ast_iax2_full_hdr *fh = f->data;
3611 struct ast_frame af;
3612
3613 /* if frame is encrypted. decrypt before updating it. */
3614 if (f->encmethods) {
3615 decode_frame(&f->mydcx, fh, &af, &f->datalen);
3616 }
3617 /* Mark this as a retransmission */
3618 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3619 /* Update iseqno */
3620 f->iseqno = iaxs[f->callno]->iseqno;
3621 fh->iseqno = f->iseqno;
3622
3623 /* Now re-encrypt the frame */
3624 if (f->encmethods) {
3625 /* since this is a retransmit frame, create a new random padding
3626 * before re-encrypting. */
3627 build_rand_pad(f->semirand, sizeof(f->semirand));
3628 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3629 }
3630 return 0;
3631 }
3632
3633 static int attempt_transmit(const void *data);
3634 static void __attempt_transmit(const void *data)
3635 {
3636 /* Attempt to transmit the frame to the remote peer...
3637 Called without iaxsl held. */
3638 struct iax_frame *f = (struct iax_frame *)data;
3639 int freeme = 0;
3640 int callno = f->callno;
3641
3642 /* Make sure this call is still active */
3643 if (callno)
3644 ast_mutex_lock(&iaxsl[callno]);
3645 if (callno && iaxs[callno]) {
3646 if (f->retries < 0) {
3647 /* Already ACK'd */
3648 freeme = 1;
3649 } else if (f->retries >= max_retries) {
3650 /* Too many attempts. Record an error. */
3651 if (f->transfer) {
3652 /* Transfer timeout */
3653 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3654 } else if (f->final) {
3655 iax2_destroy(callno);
3656 } else {
3657 if (iaxs[callno]->owner) {
3658 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3659 ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3660 ast_channel_name(iaxs[f->callno]->owner),
3661 f->af.frametype,
3662 f->af.subclass.integer,
3663 f->ts,
3664 f->oseqno);
3665 }
3666 iaxs[callno]->error = ETIMEDOUT;
3667 if (iaxs[callno]->owner) {
3668 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3669 /* Hangup the fd */
3670 iax2_queue_frame(callno, &fr); /* XXX */
3671 /* Remember, owner could disappear */
3672 if (iaxs[callno] && iaxs[callno]->owner)
3673 ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3674 } else {
3675 if (iaxs[callno]->reg) {
3676 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3677 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3678 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3679 }
3680 iax2_destroy(callno);
3681 }
3682 }
3683 freeme = 1;
3684 } else {
3685 /* Update it if it needs it */
3686 update_packet(f);
3687 /* Attempt transmission */
3688 send_packet(f);
3689 f->retries++;
3690 /* Try again later after 10 times as long */
3691 f->retrytime *= 10;
3692 if (f->retrytime > MAX_RETRY_TIME)
3693 f->retrytime = MAX_RETRY_TIME;
3694 /* Transfer messages max out at one second */
3695 if (f->transfer && (f->retrytime > 1000))
3696 f->retrytime = 1000;
3697 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3698 }
3699 } else {
3700 /* Make sure it gets freed */
3701 f->retries = -1;
3702 freeme = 1;
3703 }
3704
3705 if (freeme) {
3706 /* Don't attempt delivery, just remove it from the queue */
3707 AST_LIST_REMOVE(&frame_queue[callno], f, list);
3708 ast_mutex_unlock(&iaxsl[callno]);
3709 f->retrans = -1; /* this is safe because this is the scheduled function */
3710 /* Free the IAX frame */
3711 iax2_frame_free(f);
3712 } else if (callno) {
3713 ast_mutex_unlock(&iaxsl[callno]);
3714 }
3715 }
3716
3717 static int attempt_transmit(const void *data)
3718 {
3719 #ifdef SCHED_MULTITHREADED
3720 if (schedule_action(__attempt_transmit, data))
3721 #endif
3722 __attempt_transmit(data);
3723 return 0;
3724 }
3725
3726 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3727 {
3728 struct iax2_peer *peer = NULL;
3729 struct iax2_user *user = NULL;
3730 static const char * const choices[] = { "all", NULL };
3731 char *cmplt;
3732
3733 switch (cmd) {
3734 case CLI_INIT:
3735 e->command = "iax2 prune realtime";
3736 e->usage =
3737 "Usage: iax2 prune realtime [<peername>|all]\n"
3738 " Prunes object(s) from the cache\n";
3739 return NULL;
3740 case CLI_GENERATE:
3741 if (a->pos == 3) {
3742 cmplt = ast_cli_complete(a->word, choices, a->n);
3743 if (!cmplt)
3744 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3745 return cmplt;
3746 }
3747 return NULL;
3748 }
3749 if (a->argc != 4)
3750 return CLI_SHOWUSAGE;
3751 if (!strcmp(a->argv[3], "all")) {
3752 prune_users();
3753 prune_peers();
3754 ast_cli(a->fd, "Cache flushed successfully.\n");
3755 return CLI_SUCCESS;
3756 }
3757 peer = find_peer(a->argv[3], 0);
3758 user = find_user(a->argv[3]);
3759 if (peer || user) {
3760 if (peer) {
3761 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3762 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3763 expire_registry(peer_ref(peer));
3764 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3765 } else {
3766 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3767 }
3768 peer_unref(peer);
3769 }
3770 if (user) {
3771 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3772 ast_set_flag64(user, IAX_RTAUTOCLEAR);
3773 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3774 } else {
3775 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3776 }
3777 ao2_unlink(users,user);
3778 user_unref(user);
3779 }
3780 } else {
3781 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3782 }
3783
3784 return CLI_SUCCESS;
3785 }
3786
3787 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3788 {
3789 switch (cmd) {
3790 case CLI_INIT:
3791 e->command = "iax2 test losspct";
3792 e->usage =
3793 "Usage: iax2 test losspct <percentage>\n"
3794 " For testing, throws away <percentage> percent of incoming packets\n";
3795 return NULL;
3796 case CLI_GENERATE:
3797 return NULL;
3798 }
3799 if (a->argc != 4)
3800 return CLI_SHOWUSAGE;
3801
3802 test_losspct = atoi(a->argv[3]);
3803
3804 return CLI_SUCCESS;
3805 }
3806
3807 #ifdef IAXTESTS
3808 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3809 {
3810 switch (cmd) {
3811 case CLI_INIT:
3812 e->command = "iax2 test late";
3813 e->usage =
3814 "Usage: iax2 test late <ms>\n"
3815 " For testing, count the next frame as <ms> ms late\n";
3816 return NULL;
3817 case CLI_GENERATE:
3818 return NULL;
3819 }
3820
3821 if (a->argc != 4)
3822 return CLI_SHOWUSAGE;
3823
3824 test_late = atoi(a->argv[3]);
3825
3826 return CLI_SUCCESS;
3827 }
3828
3829 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3830 {
3831 switch (cmd) {
3832 case CLI_INIT:
3833 e->command = "iax2 test resync";
3834 e->usage =
3835 "Usage: iax2 test resync <ms>\n"
3836 " For testing, adjust all future frames by <ms> ms\n";
3837 return NULL;
3838 case CLI_GENERATE:
3839 return NULL;
3840 }
3841
3842 if (a->argc != 4)
3843 return CLI_SHOWUSAGE;
3844
3845 test_resync = atoi(a->argv[3]);
3846
3847 return CLI_SUCCESS;
3848 }
3849
3850 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3851 {
3852 switch (cmd) {
3853 case CLI_INIT:
3854 e->command = "iax2 test jitter";
3855 e->usage =
3856 "Usage: iax2 test jitter <ms> <pct>\n"
3857 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3858 " percentage of packets. If <pct> is not specified, adds\n"
3859 " jitter to all packets.\n";
3860 return NULL;
3861 case CLI_GENERATE:
3862 return NULL;
3863 }
3864
3865 if (a->argc < 4 || a->argc > 5)
3866 return CLI_SHOWUSAGE;
3867
3868 test_jit = atoi(a->argv[3]);
3869 if (a->argc == 5)
3870 test_jitpct = atoi(a->argv[4]);
3871
3872 return CLI_SUCCESS;
3873 }
3874 #endif /* IAXTESTS */
3875
3876 /*! \brief peer_status: Report Peer status in character string */
3877 /* returns 1 if peer is online, -1 if unmonitored */
3878 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3879 {
3880 int res = 0;
3881 if (peer->maxms) {
3882 if (peer->lastms < 0) {
3883 ast_copy_string(status, "UNREACHABLE", statuslen);
3884 } else if (peer->lastms > peer->maxms) {
3885 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3886 res = 1;
3887 } else if (peer->lastms) {
3888 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3889 res = 1;
3890 } else {
3891 ast_copy_string(status, "UNKNOWN", statuslen);
3892 }
3893 } else {
3894 ast_copy_string(status, "Unmonitored", statuslen);
3895 res = -1;
3896 }
3897 return res;
3898 }
3899
3900 /*! \brief Show one peer in detail */
3901 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3902 {
3903 char status[64];
3904 char cbuf[256];
3905 struct iax2_peer *peer;
3906 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3907 struct ast_str *encmethods = ast_str_alloca(256);
3908 int load_realtime = 0;
3909
3910 switch (cmd) {
3911 case CLI_INIT:
3912 e->command = "iax2 show peer";
3913 e->usage =
3914 "Usage: iax2 show peer <name>\n"
3915 " Display details on specific IAX peer\n";
3916 return NULL;
3917 case CLI_GENERATE:
3918 if (a->pos == 3)
3919 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3920 return NULL;
3921 }
3922
3923 if (a->argc < 4)
3924 return CLI_SHOWUSAGE;
3925
3926 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3927
3928 peer = find_peer(a->argv[3], load_realtime);
3929 if (peer) {
3930 char *str_addr, *str_defaddr;
3931 char *str_port, *str_defport;
3932
3933 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3934 str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3935 str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3936 str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3937
3938 encmethods_to_str(peer->encmethods, &encmethods);
3939 ast_cli(a->fd, "\n\n");
3940 ast_cli(a->fd, " * Name : %s\n", peer->name);
3941 ast_cli(a->fd, " Description : %s\n", peer->description);
3942 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3943 ast_cli(a->fd, " Context : %s\n", peer->context);
3944 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3945 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3946 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3947 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3948 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3949 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3950 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3951 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3952 ast_cli(a->fd, " Expire : %d\n", peer->expire);
3953 ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3954 ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3955 ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3956 ast_cli(a->fd, " Username : %s\n", peer->username);
3957 ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3958
3959 if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3960 strcpy(cbuf, "Error"); /* Safe */
3961 }
3962 ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3963
3964 peer_status(peer, status, sizeof(status));
3965 ast_cli(a->fd, " Status : %s\n", status);
3966 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3967 ast_cli(a->fd, "\n");
3968 peer_unref(peer);
3969 } else {
3970 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3971 ast_cli(a->fd, "\n");
3972 }
3973
3974 return CLI_SUCCESS;
3975 }
3976
3977 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3978 {
3979 int which = 0;
3980 struct iax2_peer *peer;
3981 char *res = NULL;
3982 int wordlen = strlen(word);
3983 struct ao2_iterator i;
3984
3985 i = ao2_iterator_init(peers, 0);
3986 while ((peer = ao2_iterator_next(&i))) {
3987 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3988 && (!flags || ast_test_flag64(peer, flags))) {
3989 res = ast_strdup(peer->name);
3990 peer_unref(peer);
3991 break;
3992 }
3993 peer_unref(peer);
3994 }
3995 ao2_iterator_destroy(&i);
3996
3997 return res;
3998 }
3999
4000 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4001 {
4002 struct iax_frame *cur;
4003 int cnt = 0, dead = 0, final = 0, i = 0;
4004
4005 switch (cmd) {
4006 case CLI_INIT:
4007 e->command = "iax2 show stats";
4008 e->usage =
4009 "Usage: iax2 show stats\n"
4010 " Display statistics on IAX channel driver.\n";
4011 return NULL;
4012 case CLI_GENERATE:
4013 return NULL;
4014 }
4015
4016 if (a->argc != 3)
4017 return CLI_SHOWUSAGE;
4018
4019 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
4020 ast_mutex_lock(&iaxsl[i]);
4021 AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
4022 if (cur->retries < 0)
4023 dead++;
4024 if (cur->final)
4025 final++;
4026 cnt++;
4027 }
4028 ast_mutex_unlock(&iaxsl[i]);
4029 }
4030
4031 ast_cli(a->fd, " IAX Statistics\n");
4032 ast_cli(a->fd, "---------------------\n");
4033 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
4034 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
4035 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
4036 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
4037
4038 trunk_timed = trunk_untimed = 0;
4039 if (trunk_maxmtu > trunk_nmaxmtu)
4040 trunk_nmaxmtu = trunk_maxmtu;
4041
4042 return CLI_SUCCESS;
4043 }
4044
4045 /*! \brief Set trunk MTU from CLI */
4046 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4047 {
4048 int mtuv;
4049
4050 switch (cmd) {
4051 case CLI_INIT:
4052 e->command = "iax2 set mtu";
4053 e->usage =
4054 "Usage: iax2 set mtu <value>\n"
4055 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
4056 " zero to disable. Disabling means that the operating system\n"
4057 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
4058 " packet exceeds the UDP payload size. This is substantially\n"
4059 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
4060 " greater for G.711 samples.\n";
4061 return NULL;
4062 case CLI_GENERATE:
4063 return NULL;
4064 }
4065
4066 if (a->argc != 4)
4067 return CLI_SHOWUSAGE;
4068 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
4069 mtuv = MAX_TRUNK_MTU;
4070 else
4071 mtuv = atoi(a->argv[3]);
4072
4073 if (mtuv == 0) {
4074 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
4075 global_max_trunk_mtu = 0;
4076 return CLI_SUCCESS;
4077 }
4078 if (mtuv < 172 || mtuv > 4000) {
4079 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
4080 return CLI_SHOWUSAGE;
4081 }
4082 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
4083 global_max_trunk_mtu = mtuv;
4084 return CLI_SUCCESS;
4085 }
4086
4087 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4088 {
4089 struct iax2_dpcache *dp = NULL;
4090 char tmp[1024], *pc = NULL;
4091 int s, x, y;
4092 struct timeval now = ast_tvnow();
4093
4094 switch (cmd) {
4095 case CLI_INIT:
4096 e->command = "iax2 show cache";
4097 e->usage =
4098 "Usage: iax2 show cache\n"
4099 " Display currently cached IAX Dialplan results.\n";
4100 return NULL;
4101 case CLI_GENERATE:
4102 return NULL;
4103 }
4104
4105 AST_LIST_LOCK(&dpcache);
4106
4107 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4108
4109 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4110 s = dp->expiry.tv_sec - now.tv_sec;
4111 tmp[0] = '\0';
4112 if (dp->flags & CACHE_FLAG_EXISTS)
4113 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4114 if (dp->flags & CACHE_FLAG_NONEXISTENT)
4115 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4116 if (dp->flags & CACHE_FLAG_CANEXIST)
4117 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4118 if (dp->flags & CACHE_FLAG_PENDING)
4119 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4120 if (dp->flags & CACHE_FLAG_TIMEOUT)
4121 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4122 if (dp->flags & CACHE_FLAG_TRANSMITTED)
4123 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4124 if (dp->flags & CACHE_FLAG_MATCHMORE)
4125 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4126 if (dp->flags & CACHE_FLAG_UNKNOWN)
4127 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4128 /* Trim trailing pipe */
4129 if (!ast_strlen_zero(tmp)) {
4130 tmp[strlen(tmp) - 1] = '\0';
4131 } else {
4132 ast_copy_string(tmp, "(none)", sizeof(tmp));
4133 }
4134 y = 0;
4135 pc = strchr(dp->peercontext, '@');
4136 if (!pc) {
4137 pc = dp->peercontext;
4138 } else {
4139 pc++;
4140 }
4141 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4142 if (dp->waiters[x] > -1)
4143 y++;
4144 }
4145 if (s > 0) {
4146 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4147 } else {
4148 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4149 }
4150 }
4151
4152 AST_LIST_UNLOCK(&dpcache);
4153
4154 return CLI_SUCCESS;
4155 }
4156
4157 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4158
4159 static void unwrap_timestamp(struct iax_frame *fr)
4160 {
4161 /* Video mini frames only encode the lower 15 bits of the session
4162 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4163 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4164 const int lower_mask = (1 << ts_shift) - 1;
4165 const int upper_mask = ~lower_mask;
4166 const int last_upper = iaxs[fr->callno]->last & upper_mask;
4167
4168 if ( (fr->ts & upper_mask) == last_upper ) {
4169 const int x = fr->ts - iaxs[fr->callno]->last;
4170 const int threshold = (ts_shift == 15) ? 25000 : 50000;
4171
4172 if (x < -threshold) {
4173 /* Sudden big jump backwards in timestamp:
4174 What likely happened here is that miniframe timestamp has circled but we haven't
4175 gotten the update from the main packet. We'll just pretend that we did, and
4176 update the timestamp appropriately. */
4177 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4178 if (iaxdebug)
4179 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4180 } else if (x > threshold) {
4181 /* Sudden apparent big jump forwards in timestamp:
4182 What's likely happened is this is an old miniframe belonging to the previous
4183 top 15 or 16-bit timestamp that has turned up out of order.
4184 Adjust the timestamp appropriately. */
4185 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4186 if (iaxdebug)
4187 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4188 }
4189 }
4190 }
4191
4192 static int get_from_jb(const void *p);
4193
4194 static void update_jbsched(struct chan_iax2_pvt *pvt)
4195 {
4196 int when;
4197
4198 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4199
4200 when = jb_next(pvt->jb) - when;
4201
4202 if (when <= 0) {
4203 /* XXX should really just empty until when > 0.. */
4204 when = 1;
4205 }
4206
4207 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4208 CALLNO_TO_PTR(pvt->callno));
4209 }
4210
4211 static void __get_from_jb(const void *p)
4212 {
4213 int callno = PTR_TO_CALLNO(p);
4214 struct chan_iax2_pvt *pvt = NULL;
4215 struct iax_frame *fr;
4216 jb_frame frame;
4217 int ret;
4218 long ms;
4219 long next;
4220 struct timeval now = ast_tvnow();
4221 struct ast_format *voicefmt;
4222
4223 /* Make sure we have a valid private structure before going on */
4224 ast_mutex_lock(&iaxsl[callno]);
4225 pvt = iaxs[callno];
4226 if (!pvt) {
4227 /* No go! */
4228 ast_mutex_unlock(&iaxsl[callno]);
4229 return;
4230 }
4231
4232 pvt->jbid = -1;
4233
4234 /* round up a millisecond since ast_sched_runq does; */
4235 /* prevents us from spinning while waiting for our now */
4236 /* to catch up with runq's now */
4237 now.tv_usec += 1000;
4238
4239 ms = ast_tvdiff_ms(now, pvt->rxcore);
4240 if (ms >= (next = jb_next(pvt->jb))) {
4241 voicefmt = ast_format_compatibility_bitfield2format(pvt->voiceformat);
4242 if (!voicefmt) {
4243 /* pvt->voiceformat won't be set if we haven't received any voice frames yet.
4244 * In this case, fall back to using the format negotiated during call setup,
4245 * so we don't stall the jitterbuffer completely. */
4246 voicefmt = ast_format_compatibility_bitfield2format(pvt->peerformat);
4247 if (!voicefmt) {
4248 /* As a last resort, we can use pvt->chosenformat.
4249 * This is set when we receive a call (either authenticated or unauthenticated),
4250 * so even if we haven't received any voice frames yet, we can still use the
4251 * right format.
4252 *
4253 * If we have to do this, in most cases, we aren't even processing voice frames
4254 * anyways, it's likely a non-voice frame. In that case, the format doesn't
4255 * really matter so much, because we could just pass 20 to jb_get instead
4256 * of calling ast_format_get_default_ms. However, until jb_get returns,
4257 * we don't actually know what kind of frame it is for sure, so use
4258 * the right format just to be safe. */
4259 voicefmt = ast_format_compatibility_bitfield2format(pvt->chosenformat);
4260 }
4261 }
4262 if (!voicefmt) {
4263 /* This should never happen, since we should always be able to have an acceptable format to use. */
4264 ast_log(LOG_ERROR, "No voice, peer, or chosen format available on %s, backlogging frame\n", ast_channel_name(pvt->owner));
4265 goto cleanup; /* Don't crash if there's no voice format */
4266 }
4267 ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4268 switch(ret) {
4269 case JB_OK:
4270 fr = frame.data;
4271 __do_deliver(fr);
4272 /* __do_deliver() can cause the call to disappear */
4273 pvt = iaxs[callno];
4274 break;
4275 case JB_INTERP:
4276 {
4277 struct ast_frame af = { 0, };
4278
4279 /* create an interpolation frame */
4280 af.frametype = AST_FRAME_VOICE;
4281 af.subclass.format = voicefmt;
4282 af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4283 af.src = "IAX2 JB interpolation";
4284 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4285 af.offset = AST_FRIENDLY_OFFSET;
4286
4287 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4288 * which we'd need to malloc, and then it would free it. That seems like a drag */
4289 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4290 iax2_queue_frame(callno, &af);
4291 /* iax2_queue_frame() could cause the call to disappear */
4292 pvt = iaxs[callno];
4293 }
4294 }
4295 break;
4296 case JB_DROP:
4297 iax2_frame_free(frame.data);
4298 break;
4299 case JB_NOFRAME:
4300 case JB_EMPTY:
4301 /* do nothing */
4302 break;
4303 default:
4304 /* shouldn't happen */
4305 break;
4306 }
4307 }
4308 cleanup:
4309 if (pvt)
4310 update_jbsched(pvt);
4311 ast_mutex_unlock(&iaxsl[callno]);
4312 }
4313
4314 static int get_from_jb(const void *data)
4315 {
4316 #ifdef SCHED_MULTITHREADED
4317 if (schedule_action(__get_from_jb, data))
4318 #endif
4319 __get_from_jb(data);
4320 return 0;
4321 }
4322
4323 /*!
4324 * \note This function assumes fr->callno is locked
4325 *
4326 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4327 * was valid before calling it, it may no longer be valid after calling it.
4328 */
4329 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4330 {
4331 int type, len;
4332 int ret;
4333 int needfree = 0;
4334
4335 /*
4336 * Clear fr->af.data if there is no data in the buffer. Things
4337 * like AST_CONTROL_HOLD without a suggested music class must
4338 * have a NULL pointer.
4339 */
4340 if (!fr->af.datalen) {
4341 memset(&fr->af.data, 0, sizeof(fr->af.data));
4342 }
4343
4344 /* Attempt to recover wrapped timestamps */
4345 unwrap_timestamp(fr);
4346
4347 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4348 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4349 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4350 else {
4351 #if 0
4352 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4353 #endif
4354 fr->af.delivery = ast_tv(0,0);
4355 }
4356
4357 type = JB_TYPE_CONTROL;
4358 len = 0;
4359
4360 if(fr->af.frametype == AST_FRAME_VOICE) {
4361 type = JB_TYPE_VOICE;
4362 len = ast_codec_samples_count(&fr->af) / (ast_format_get_sample_rate(fr->af.subclass.format) / 1000);
4363 } else if(fr->af.frametype == AST_FRAME_CNG) {
4364 type = JB_TYPE_SILENCE;
4365 }
4366
4367 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4368 if (tsout)
4369 *tsout = fr->ts;
4370 __do_deliver(fr);
4371 return -1;
4372 }
4373
4374 /* insert into jitterbuffer */
4375 /* TODO: Perhaps we could act immediately if it's not droppable and late */
4376 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4377 calc_rxstamp(iaxs[fr->callno],fr->ts));
4378 if (ret == JB_DROP) {
4379 needfree++;
4380 } else if (ret == JB_SCHED) {
4381 update_jbsched(iaxs[fr->callno]);
4382 }
4383 if (tsout)
4384 *tsout = fr->ts;
4385 if (needfree) {
4386 /* Free our iax frame */
4387 iax2_frame_free(fr);
4388 return -1;
4389 }
4390 return 0;
4391 }
4392
4393 static int transmit_frame(void *data)
4394 {
4395 struct iax_frame *fr = data;
4396
4397 ast_mutex_lock(&iaxsl[fr->callno]);
4398
4399 fr->sentyet = 1;
4400
4401 if (iaxs[fr->callno]) {
4402 send_packet(fr);
4403 }
4404
4405 if (fr->retries < 0) {
4406 ast_mutex_unlock(&iaxsl[fr->callno]);
4407 /* No retransmit requested */
4408 iax_frame_free(fr);
4409 } else {
4410 /* We need reliable delivery. Schedule a retransmission */
4411 AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
4412 fr->retries++;
4413 fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
4414 ast_mutex_unlock(&iaxsl[fr->callno]);
4415 }
4416
4417 return 0;
4418 }
4419
4420 static int iax2_transmit(struct iax_frame *fr)
4421 {
4422 fr->sentyet = 0;
4423
4424 return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
4425 }
4426
4427 static int iax2_digit_begin(struct ast_channel *c, char digit)
4428 {
4429 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
4430 }
4431
4432 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4433 {
4434 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
4435 }
4436
4437 static int iax2_sendtext(struct ast_channel *c, const char *text)
4438 {
4439
4440 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_TEXT,
4441 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4442 }
4443
4444 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4445 {
4446 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
4447 }
4448
4449 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4450 {
4451 return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4452 }
4453
4454 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4455 {
4456 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4457 ast_mutex_lock(&iaxsl[callno]);
4458 if (iaxs[callno])
4459 iaxs[callno]->owner = newchan;
4460 else
4461 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4462 ast_mutex_unlock(&iaxsl[callno]);
4463 return 0;
4464 }
4465
4466 /*!
4467 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4468 * so do not call this with a pvt lock held.
4469 */
4470 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4471 {
4472 struct ast_variable *var = NULL;
4473 struct ast_variable *tmp;
4474 struct iax2_peer *peer=NULL;
4475 time_t regseconds = 0, nowtime;
4476 int dynamic=0;
4477 char *str_addr, *str_port;
4478
4479 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4480 str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4481
4482 if (peername) {
4483 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4484 if (!var && !ast_sockaddr_isnull(addr)) {
4485 var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4486 }
4487 } else if (!ast_sockaddr_isnull(addr)) {
4488 var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4489 if (var) {
4490 /* We'll need the peer name in order to build the structure! */
4491 for (tmp = var; tmp; tmp = tmp->next) {
4492 if (!strcasecmp(tmp->name, "name"))
4493 peername = tmp->value;
4494 }
4495 }
4496 }
4497 if (!var && peername) { /* Last ditch effort */
4498 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4499 /*!\note
4500 * If this one loaded something, then we need to ensure that the host
4501 * field matched. The only reason why we can't have this as a criteria
4502 * is because we only have the IP address and the host field might be
4503 * set as a name (and the reverse PTR might not match).
4504 */
4505 if (var && !ast_sockaddr_isnull(addr)) {
4506 for (tmp = var; tmp; tmp = tmp->next) {
4507 if (!strcasecmp(tmp->name, "host")) {
4508 struct ast_sockaddr *hostaddr = NULL;
4509
4510 if (!ast_sockaddr_resolve(&hostaddr, tmp->value, PARSE_PORT_FORBID, AST_AF_UNSPEC)
4511 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4512 /* No match */
4513 ast_variables_destroy(var);
4514 var = NULL;
4515 }
4516 ast_free(hostaddr);
4517 break;
4518 }
4519 }
4520 }
4521 }
4522 if (!var)
4523 return NULL;
4524
4525 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4526
4527 if (!peer) {
4528 ast_variables_destroy(var);
4529 return NULL;
4530 }
4531
4532 for (tmp = var; tmp; tmp = tmp->next) {
4533 /* Make sure it's not a user only... */
4534 if (!strcasecmp(tmp->name, "type")) {
4535 if (strcasecmp(tmp->value, "friend") &&
4536 strcasecmp(tmp->value, "peer")) {
4537 /* Whoops, we weren't supposed to exist! */
4538 peer = peer_unref(peer);
4539 break;
4540 }
4541 } else if (!strcasecmp(tmp->name, "regseconds")) {
4542 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4543 } else if (!strcasecmp(tmp->name, "ipaddr")) {
4544 int setport = ast_sockaddr_port(&peer->addr);
4545 if (ast_parse_arg(tmp->value, PARSE_ADDR | PARSE_PORT_FORBID, NULL)) {
4546 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4547 } else {
4548 ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4549 }
4550 ast_sockaddr_set_port(&peer->addr, setport);
4551 } else if (!strcasecmp(tmp->name, "port")) {
4552 int bindport;
4553 if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4554 bindport = IAX_DEFAULT_PORTNO;
4555 }
4556 ast_sockaddr_set_port(&peer->addr, bindport);
4557 } else if (!strcasecmp(tmp->name, "host")) {
4558 if (!strcasecmp(tmp->value, "dynamic"))
4559 dynamic = 1;
4560 }
4561 }
4562
4563 ast_variables_destroy(var);
4564
4565 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4566 ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
4567 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4568 if (peer->expire > -1) {
4569 if (!AST_SCHED_DEL(sched, peer->expire)) {
4570 peer->expire = -1;
4571 peer_unref(peer);
4572 }
4573 }
4574 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
4575 if (peer->expire == -1)
4576 peer_unref(peer);
4577 }
4578 ao2_link(peers, peer);
4579 if (ast_test_flag64(peer, IAX_DYNAMIC))
4580 reg_source_db(peer);
4581 } else {
4582 ast_set_flag64(peer, IAX_TEMPONLY);
4583 }
4584
4585 if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
4586 time(&nowtime);
4587 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4588 memset(&peer->addr, 0, sizeof(peer->addr));
4589 realtime_update_peer(peer->name, &peer->addr, 0);
4590 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4591 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4592 }
4593 else {
4594 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4595 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4596 }
4597 }
4598
4599 return peer;
4600 }
4601
4602 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4603 {
4604 struct ast_variable *var;
4605 struct ast_variable *tmp;
4606 struct iax2_user *user=NULL;
4607 char *str_addr, *str_port;
4608
4609 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4610 str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4611
4612 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4613 if (!var)
4614 var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4615 if (!var && !ast_sockaddr_isnull(addr)) {
4616 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4617 if (!var)
4618 var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4619 }
4620 if (!var) { /* Last ditch effort */
4621 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4622 /*!\note
4623 * If this one loaded something, then we need to ensure that the host
4624 * field matched. The only reason why we can't have this as a criteria
4625 * is because we only have the IP address and the host field might be
4626 * set as a name (and the reverse PTR might not match).
4627 */
4628 if (var) {
4629 for (tmp = var; tmp; tmp = tmp->next) {
4630 if (!strcasecmp(tmp->name, "host")) {
4631 struct ast_sockaddr *hostaddr = NULL;
4632
4633 if (!ast_sockaddr_resolve(&hostaddr, tmp->value, PARSE_PORT_FORBID, AST_AF_UNSPEC)
4634 || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4635 /* No match */
4636 ast_variables_destroy(var);
4637 var = NULL;
4638 }
4639 ast_free(hostaddr);
4640 break;
4641 }
4642 }
4643 }
4644 }
4645 if (!var)
4646 return NULL;
4647
4648 tmp = var;
4649 while(tmp) {
4650 /* Make sure it's not a peer only... */
4651 if (!strcasecmp(tmp->name, "type")) {
4652 if (strcasecmp(tmp->value, "friend") &&
4653 strcasecmp(tmp->value, "user")) {
4654 return NULL;
4655 }
4656 }
4657 tmp = tmp->next;
4658 }
4659
4660 user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
4661
4662 ast_variables_destroy(var);
4663
4664 if (!user)
4665 return NULL;
4666
4667 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4668 ast_set_flag64(user, IAX_RTCACHEFRIENDS);
4669 ao2_link(users, user);
4670 } else {
4671 ast_set_flag64(user, IAX_TEMPONLY);
4672 }
4673
4674 return user;
4675 }
4676
4677 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4678 {
4679 char regseconds[20];
4680 const char *sysname = ast_config_AST_SYSTEM_NAME;
4681 char *syslabel = NULL;
4682 char *port;
4683
4684 if (ast_strlen_zero(sysname)) /* No system name, disable this */
4685 sysname = NULL;
4686 else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
4687 syslabel = "regserver";
4688
4689 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4690 port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4691 ast_update_realtime("iaxpeers", "name", peername,
4692 "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4693 "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4694 "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslabel can be NULL */
4695 }
4696
4697 struct create_addr_info {
4698 iax2_format capability;
4699 uint64_t flags;
4700 struct iax2_codec_pref prefs;
4701 int maxtime;
4702 int encmethods;
4703 int authmethods;
4704 int found;
4705 int sockfd;
4706 int adsi;
4707 char username[80];
4708 char secret[80];
4709 char outkey[80];
4710 char timezone[80];
4711 char cid_num[80];
4712 char cid_name[80];
4713 char context[AST_MAX_CONTEXT];
4714 char peercontext[AST_MAX_CONTEXT];
4715 char mohinterpret[MAX_MUSICCLASS];
4716 char mohsuggest[MAX_MUSICCLASS];
4717 };
4718
4719 static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4720 {
4721 struct iax2_peer *peer;
4722 int res = -1;
4723
4724 ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
4725 cai->sockfd = defaultsockfd;
4726 cai->maxtime = 0;
4727
4728 if (!(peer = find_peer(peername, 1))) {
4729 struct ast_sockaddr peer_addr;
4730
4731 peer_addr.ss.ss_family = AST_AF_UNSPEC;
4732 cai->found = 0;
4733 if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4734 ast_log(LOG_WARNING, "No such host: %s\n", peername);
4735 return -1;
4736 }
4737
4738 if (!ast_sockaddr_port(&peer_addr)) {
4739 ast_sockaddr_set_port(&peer_addr, IAX_DEFAULT_PORTNO);
4740 }
4741
4742 ast_sockaddr_copy(addr, &peer_addr);
4743 /*
4744 * Use The global iax prefs for unknown peer/user.
4745 * However, move the calling channel's native codec to
4746 * the top of the preference list.
4747 */
4748 cai->prefs = prefs_global;
4749 if (c) {
4750 int i;
4751
4752 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4753 struct ast_format *format = ast_format_cap_get_format(
4754 ast_channel_nativeformats(c), i);
4755 iax2_codec_pref_prepend(&cai->prefs, format,
4756 ast_format_cap_get_format_framing(ast_channel_nativeformats(c), format),
4757 1);
4758 ao2_ref(format, -1);
4759 }
4760 }
4761 return 0;
4762 }
4763
4764 cai->found = 1;
4765
4766 /* if the peer has no address (current or default), return failure */
4767 if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4768 goto return_unref;
4769 }
4770
4771 /* if the peer is being monitored and is currently unreachable, return failure */
4772 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4773 goto return_unref;
4774
4775 ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
4776 cai->maxtime = peer->maxms;
4777 cai->capability = peer->capability;
4778 cai->encmethods = peer->encmethods;
4779 cai->authmethods = peer->authmethods;
4780 cai->sockfd = peer->sockfd;
4781 cai->adsi = peer->adsi;
4782 cai->prefs = peer->prefs;
4783 /* Move the calling channel's native codec to the top of the preference list */
4784 if (c) {
4785 int i;
4786
4787 for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4788 struct ast_format *tmpfmt = ast_format_cap_get_format(
4789 ast_channel_nativeformats(c), i);
4790 iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4791 ast_format_cap_get_format_framing(ast_channel_nativeformats(c), tmpfmt),
4792 1);
4793 ao2_ref(tmpfmt, -1);
4794 }
4795 }
4796 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4797 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4798 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4799 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4800 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4801 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4802 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4803 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4804 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4805 if (ast_strlen_zero(peer->dbsecret)) {
4806 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4807 } else {
4808 char *family;
4809 char *key = NULL;
4810
4811 family = ast_strdupa(peer->dbsecret);
4812 key = strchr(family, '/');
4813 if (key)
4814 *key++ = '\0';
4815 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4816 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4817 goto return_unref;
4818 }
4819 }
4820
4821 if (!ast_sockaddr_isnull(&peer->addr)) {
4822 ast_sockaddr_copy(addr, &peer->addr);
4823 } else {
4824 ast_sockaddr_copy(addr, &peer->defaddr);
4825 }
4826
4827 res = 0;
4828
4829 return_unref:
4830 peer_unref(peer);
4831
4832 return res;
4833 }
4834
4835 static void __auto_congest(const void *nothing)
4836 {
4837 int callno = PTR_TO_CALLNO(nothing);
4838 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
4839 ast_mutex_lock(&iaxsl[callno]);
4840 if (iaxs[callno]) {
4841 iaxs[callno]->initid = -1;
4842 iax2_queue_frame(callno, &f);
4843 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4844 }
4845 ast_mutex_unlock(&iaxsl[callno]);
4846 }
4847
4848 static int auto_congest(const void *data)
4849 {
4850 #ifdef SCHED_MULTITHREADED
4851 if (schedule_action(__auto_congest, data))
4852 #endif
4853 __auto_congest(data);
4854 return 0;
4855 }
4856
4857 static unsigned int iax2_datetime(const char *tz)
4858 {
4859 struct timeval t = ast_tvnow();
4860 struct ast_tm tm;
4861 unsigned int tmp;
4862 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4863 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4864 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4865 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4866 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4867 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4868 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4869 return tmp;
4870 }
4871
4872 struct parsed_dial_string {
4873 char *username;
4874 char *password;
4875 char *key;
4876 char *peer;
4877 char *port;
4878 char *exten;
4879 char *context;
4880 char *options;
4881 };
4882
4883 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4884 struct ast_sockaddr *addr, int command, int ts, unsigned char seqno,
4885 int sockfd, struct iax_ie_data *ied)
4886 {
4887 struct {
4888 struct ast_iax2_full_hdr f;
4889 struct iax_ie_data ied;
4890 } data;
4891 size_t size = sizeof(struct ast_iax2_full_hdr);
4892
4893 if (ied) {
4894 size += ied->pos;
4895 memcpy(&data.ied, ied->buf, ied->pos);
4896 }
4897
4898 data.f.scallno = htons(0x8000 | callno);
4899 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4900 data.f.ts = htonl(ts);
4901 data.f.iseqno = seqno;
4902 data.f.oseqno = 0;
4903 data.f.type = AST_FRAME_IAX;
4904 data.f.csub = compress_subclass(command);
4905
4906 iax_outputframe(NULL, &data.f, 0, addr, size - sizeof(struct ast_iax2_full_hdr));
4907
4908 return ast_sendto(sockfd, &data, size, 0, addr);
4909 }
4910
4911 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4912 {
4913 /* first make sure their are two empty bytes left in ied->buf */
4914 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4915 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4916 ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4917 pvt->calltoken_ie_len = 2;
4918 }
4919 }
4920
4921 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4922 {
4923 struct chan_iax2_pvt *pvt = iaxs[callno];
4924 int frametype = f->af.frametype;
4925 int subclass = f->af.subclass.integer;
4926 struct {
4927 struct ast_iax2_full_hdr fh;
4928 struct iax_ie_data ied;
4929 } data = {
4930 .ied.buf = { 0 },
4931 .ied.pos = 0,
4932 };
4933 /* total len - header len gives us the frame's IE len */
4934 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4935
4936 if (!pvt) {
4937 return; /* this should not be possible if called from socket_process() */
4938 }
4939
4940 /*
4941 * Check to make sure last frame sent is valid for call token resend
4942 * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4943 * 2. Frame should _NOT_ already have a destination callno
4944 * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4945 * 4. Pvt must have a calltoken_ie_len which represents the number of
4946 * bytes at the end of the frame used for the previous calltoken ie.
4947 * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4948 * 6. Total length of f->data must be _LESS_ than size of our data struct
4949 * because f->data must be able to fit within data.
4950 */
4951 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4952 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4953 (f->datalen > sizeof(data))) {
4954
4955 return; /* ignore resend, token was not valid for the dialog */
4956 }
4957
4958 /* token is valid
4959 * 1. Copy frame data over
4960 * 2. Redo calltoken IE, it will always be the last ie in the frame.
4961 * NOTE: Having the ie always be last is not protocol specified,
4962 * it is only an implementation choice. Since we only expect the ie to
4963 * be last for frames we have sent, this can no way be affected by
4964 * another end point.
4965 * 3. Remove frame from queue
4966 * 4. Free old frame
4967 * 5. Clear previous seqnos
4968 * 6. Resend with CALLTOKEN ie.
4969 */
4970
4971 /* ---1.--- */
4972 memcpy(&data, f->data, f->datalen);
4973 data.ied.pos = ie_data_pos;
4974
4975 /* ---2.--- */
4976 /* move to the beginning of the calltoken ie so we can write over it */
4977 data.ied.pos -= pvt->calltoken_ie_len;
4978 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4979
4980 /* make sure to update token length incase it ever has to be stripped off again */
4981 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4982
4983 /* ---3.--- */
4984 AST_LIST_REMOVE(&frame_queue[callno], f, list);
4985
4986 /* ---4.--- */
4987 iax2_frame_free(f);
4988
4989 /* ---5.--- */
4990 pvt->oseqno = 0;
4991 pvt->rseqno = 0;
4992 pvt->iseqno = 0;
4993 pvt->aseqno = 0;
4994 if (pvt->peercallno) {
4995 remove_by_peercallno(pvt);
4996 pvt->peercallno = 0;
4997 }
4998
4999 /* ---6.--- */
5000 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
5001 }
5002
5003 static void requirecalltoken_mark_auto(const char *name, int subclass)
5004 {
5005 struct iax2_user *user = NULL;
5006 struct iax2_peer *peer = NULL;
5007
5008 if (ast_strlen_zero(name)) {
5009 return; /* no username given */
5010 }
5011
5012 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
5013 user->calltoken_required = CALLTOKEN_YES;
5014 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
5015 peer->calltoken_required = CALLTOKEN_YES;
5016 }
5017
5018 if (peer) {
5019 peer_unref(peer);
5020 }
5021 if (user) {
5022 user_unref(user);
5023 }
5024 }
5025
5026 /*!
5027 * \internal
5028 *
5029 * \brief handles calltoken logic for a received iax_frame.
5030 *
5031 * \note frametype must be AST_FRAME_IAX.
5032 *
5033 * \note
5034 * Three different cases are possible here.
5035 * Case 1. An empty calltoken is provided. This means the client supports
5036 * calltokens but has not yet received one from us. In this case
5037 * a full calltoken IE is created and sent in a calltoken fullframe.
5038 * Case 2. A full calltoken is received and must be checked for validity.
5039 * Case 3. No calltoken is received indicating that the client does not
5040 * support calltokens. In this case it is up to the configuration
5041 * to decide how this should be handled (reject or permit without calltoken)
5042 */
5043 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
5044 struct ast_sockaddr *addr, int fd)
5045 {
5046 #define CALLTOKEN_HASH_FORMAT "%s%u%d" /* address + port + ts + randomcalldata */
5047 #define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
5048 struct ast_str *buf = ast_str_alloca(256);
5049 time_t t = time(NULL);
5050 char hash[41]; /* 40 char sha1 hash */
5051 int subclass = uncompress_subclass(fh->csub);
5052
5053 /* ----- Case 1 ----- */
5054 if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
5055 struct iax_ie_data ied = {
5056 .buf = { 0 },
5057 .pos = 0,
5058 };
5059
5060 /* create the hash with their address data and our timestamp */
5061 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_sockaddr_stringify(addr), (unsigned int) t, randomcalltokendata);
5062 ast_sha1_hash(hash, ast_str_buffer(buf));
5063
5064 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
5065 iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
5066 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
5067
5068 return 1;
5069
5070 /* ----- Case 2 ----- */
5071 } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
5072 char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
5073 char *rec_ts = NULL; /* received timestamp */
5074 unsigned int rec_time; /* received time_t */
5075
5076 /* split the timestamp from the hash data */
5077 rec_hash = strchr((char *) ies->calltokendata, '?');
5078 if (rec_hash) {
5079 *rec_hash++ = '\0';
5080 rec_ts = (char *) ies->calltokendata;
5081 }
5082
5083 /* check that we have valid data before we do any comparisons */
5084 if (!rec_hash || !rec_ts) {
5085 goto reject;
5086 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
5087 goto reject;
5088 }
5089
5090 /* create a hash with their address and the _TOKEN'S_ timestamp */
5091 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_sockaddr_stringify(addr), (unsigned int) rec_time, randomcalltokendata);
5092 ast_sha1_hash(hash, ast_str_buffer(buf));
5093
5094 /* compare hashes and then check timestamp delay */
5095 if (strcmp(hash, rec_hash)) {
5096 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_sockaddr_stringify(addr));
5097 goto reject; /* received hash does not match ours, reject */
5098 } else if ((t < rec_time) || ((t - rec_time) >= max_calltoken_delay)) {
5099 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_sockaddr_stringify(addr));
5100 goto reject; /* too much delay, reject */
5101 }
5102
5103 /* at this point the call token is valid, returning 0
5104 * will allow socket_process to continue as usual */
5105 requirecalltoken_mark_auto(ies->username, subclass);
5106 return 0;
5107
5108 /* ----- Case 3 ----- */
5109 } else { /* calltokens are not supported for this client, how do we respond? */
5110 if (calltoken_required(addr, ies->username, subclass)) {
5111 ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_sockaddr_stringify(addr), S_OR(ies->username, "guest"));
5112 goto reject;
5113 }
5114 return 0; /* calltoken is not required for this addr, so permit it. */
5115 }
5116
5117 reject:
5118 /* received frame has failed calltoken inspection, send apathetic reject messages */
5119 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5120 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5121 } else {
5122 send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5123 }
5124
5125 return 1;
5126 }
5127
5128 /*!
5129 * \brief Parses an IAX dial string into its component parts.
5130 * \param data the string to be parsed
5131 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5132 *
5133 * This function parses the string and fills the structure
5134 * with pointers to its component parts. The input string
5135 * will be modified.
5136 *
5137 * \note This function supports both plaintext passwords and RSA
5138 * key names; if the password string is formatted as '[keyname]',
5139 * then the keyname will be placed into the key field, and the
5140 * password field will be set to NULL.
5141 *
5142 * \note The dial string format is:
5143 * \verbatim [username[:password]@]peer[:port][/exten[@context]][/options] \endverbatim
5144 */
5145 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5146 {
5147 char *outkey = NULL;
5148
5149 if (ast_strlen_zero(data))
5150 return;
5151
5152 pds->peer = strsep(&data, "/");
5153 pds->exten = strsep(&data, "/");
5154 pds->options = data;
5155
5156 if (pds->exten) {
5157 data = pds->exten;
5158 pds->exten = strsep(&data, "@");
5159 pds->context = data;
5160 }
5161
5162 if (strchr(pds->peer, '@')) {
5163 data = pds->peer;
5164 pds->username = strsep(&data, "@");
5165 pds->peer = data;
5166 }
5167
5168 if (pds->username) {
5169 data = pds->username;
5170 pds->username = strsep(&data, ":");
5171 pds->password = strsep(&data, ":");
5172 outkey = data;
5173 }
5174
5175 data = pds->peer;
5176 pds->peer = strsep(&data, ":");
5177 pds->port = data;
5178
5179 /*
5180 * Check for a key name wrapped in [] in the password position.
5181 * If found, move it to the key field instead.
5182 * Also allow for both key and secret to be specified, now that
5183 * encryption is possible with RSA authentication.
5184 */
5185
5186 if (pds->password && (pds->password[0] == '[')) { /* key (then maybe secret) */
5187 pds->key = ast_strip_quoted(pds->password, "[", "]");
5188 if (ast_strlen_zero(outkey)) {
5189 pds->password = NULL;
5190 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5191 } else {
5192 pds->password = outkey;
5193 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5194 }
5195 } else if (outkey && (outkey[0] == '[')) { /* secret, then key */
5196 pds->key = ast_strip_quoted(outkey, "[", "]");
5197 if (ast_strlen_zero(pds->password)) {
5198 ast_debug(1, "Outkey (%s), no secret\n", pds->key);
5199 } else {
5200 ast_debug(1, "Outkey (%s) and secret (%s)\n", pds->key, pds->password);
5201 }
5202 }
5203 }
5204
5205 static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
5206 {
5207 struct ast_sockaddr addr;
5208 char *l=NULL, *n=NULL, *tmpstr;
5209 struct iax_ie_data ied;
5210 char *defaultrdest = "s";
5211 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5212 struct parsed_dial_string pds;
5213 struct create_addr_info cai;
5214 struct ast_var_t *var;
5215 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
5216 const char* osp_token_ptr;
5217 unsigned int osp_token_length;
5218 unsigned char osp_block_index;
5219 unsigned int osp_block_length;
5220 unsigned char osp_buffer[256];
5221 char encoded_prefs[32];
5222 iax2_format iax2_tmpfmt;
5223
5224 if ((ast_channel_state(c) != AST_STATE_DOWN) && (ast_channel_state(c) != AST_STATE_RESERVED)) {
5225 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
5226 return -1;
5227 }
5228
5229 memset(&cai, 0, sizeof(cai));
5230 cai.encmethods = iax2_encryption;
5231 cai.authmethods = iax2_authmethods;
5232
5233 memset(&pds, 0, sizeof(pds));
5234 tmpstr = ast_strdupa(dest);
5235 parse_dial_string(tmpstr, &pds);
5236
5237 if (ast_strlen_zero(pds.peer)) {
5238 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5239 return -1;
5240 }
5241 if (!pds.exten) {
5242 pds.exten = defaultrdest;
5243 }
5244 if (create_addr(pds.peer, c, &addr, &cai)) {
5245 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5246 return -1;
5247 }
5248
5249 if (ast_test_flag64(&cai, IAX_FORCE_ENCRYPT) ||
5250 ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
5251 if (!cai.encmethods) {
5252 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5253 ast_channel_hangupcause_set(c, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
5254 return -1;
5255 }
5256 if (((cai.authmethods & IAX_AUTH_RSA) || (cai.authmethods & IAX_AUTH_MD5) || (cai.authmethods & IAX_AUTH_PLAINTEXT)) &&
5257 ast_strlen_zero(cai.secret) && ast_strlen_zero(pds.password)) {
5258 ast_log(LOG_WARNING, "Call terminated. Encryption forced but no secret provided\n");
5259 return -1;
5260 }
5261 }
5262
5263 if (!pds.username && !ast_strlen_zero(cai.username))
5264 pds.username = cai.username;
5265 if (!pds.password && !ast_strlen_zero(cai.secret))
5266 pds.password = cai.secret;
5267 if (!pds.key && !ast_strlen_zero(cai.outkey))
5268 pds.key = cai.outkey;
5269 if (!pds.context && !ast_strlen_zero(cai.peercontext))
5270 pds.context = cai.peercontext;
5271
5272 /* Keep track of the context for outgoing calls too */
5273 ast_channel_context_set(c, cai.context);
5274
5275 if (pds.port) {
5276 int bindport;
5277 if (ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
5278 ast_sockaddr_set_port(&addr, bindport);
5279 }
5280 }
5281
5282 l = ast_channel_connected(c)->id.number.valid ? ast_channel_connected(c)->id.number.str : NULL;
5283 n = ast_channel_connected(c)->id.name.valid ? ast_channel_connected(c)->id.name.str : NULL;
5284
5285 /* Now build request */
5286 memset(&ied, 0, sizeof(ied));
5287
5288 /* On new call, first IE MUST be IAX version of caller */
5289 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
5290 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
5291 if (pds.options && strchr(pds.options, 'a')) {
5292 /* Request auto answer */
5293 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
5294 }
5295
5296 /* WARNING: this breaks down at 190 bits! */
5297 iax2_codec_pref_convert(&cai.prefs, encoded_prefs, sizeof(encoded_prefs), 1);
5298 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, encoded_prefs);
5299
5300 if (l) {
5301 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
5302 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
5303 ast_party_id_presentation(&ast_channel_connected(c)->id));
5304 } else if (n) {
5305 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
5306 ast_party_id_presentation(&ast_channel_connected(c)->id));
5307 } else {
5308 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
5309 }
5310
5311 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, ast_channel_connected(c)->id.number.plan);
5312 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
5313 iax_ie_append_int(&ied, IAX_IE_CALLINGANI2, ast_channel_connected(c)->ani2);
5314
5315 if (n)
5316 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
5317 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5318 && ast_channel_connected(c)->ani.number.valid
5319 && ast_channel_connected(c)->ani.number.str) {
5320 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, ast_channel_connected(c)->ani.number.str);
5321 }
5322
5323 if (!ast_strlen_zero(ast_channel_language(c)))
5324 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, ast_channel_language(c));
5325 if (!ast_strlen_zero(ast_channel_dialed(c)->number.str)) {
5326 iax_ie_append_str(&ied, IAX_IE_DNID, ast_channel_dialed(c)->number.str);
5327 }
5328 if (ast_channel_redirecting(c)->from.number.valid
5329 && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
5330 iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
5331 }
5332
5333 if (pds.context)
5334 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
5335
5336 if (pds.username)
5337 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
5338
5339 if (cai.encmethods)
5340 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
5341
5342 ast_mutex_lock(&iaxsl[callno]);
5343
5344 if (!ast_strlen_zero(ast_channel_context(c)))
5345 ast_string_field_set(iaxs[callno], context, ast_channel_context(c));
5346
5347 if (pds.username)
5348 ast_string_field_set(iaxs[callno], username, pds.username);
5349
5350 iaxs[callno]->encmethods = cai.encmethods;
5351
5352 iaxs[callno]->adsi = cai.adsi;
5353
5354 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
5355 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
5356
5357 if (pds.key)
5358 ast_string_field_set(iaxs[callno], outkey, pds.key);
5359 if (pds.password)
5360 ast_string_field_set(iaxs[callno], secret, pds.password);
5361
5362 iax2_tmpfmt = iax2_format_compatibility_cap2bitfield(ast_channel_nativeformats(c));
5363 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
5364 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
5365
5366 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5367 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
5368 iax_ie_append_short(&ied, IAX_IE_ADSICPE, ast_channel_adsicpe(c));
5369 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
5370
5371 if (iaxs[callno]->maxtime) {
5372 /* Initialize pingtime and auto-congest time */
5373 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5374 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5375 } else if (autokill) {
5376 iaxs[callno]->pingtime = autokill / 2;
5377 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
5378 }
5379
5380 /* Check if there is an OSP token */
5381 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5382 if (!ast_strlen_zero(osp_token_ptr)) {
5383 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5384 osp_block_index = 0;
5385 while (osp_token_length > 0) {
5386 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5387 osp_buffer[0] = osp_block_index;
5388 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5389 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5390 osp_block_index++;
5391 osp_token_ptr += osp_block_length;
5392 osp_token_length -= osp_block_length;
5393 }
5394 } else
5395 ast_log(LOG_WARNING, "OSP token is too long\n");
5396 } else if (iaxdebug)
5397 ast_debug(1, "OSP token is undefined\n");
5398
5399 /* send the command using the appropriate socket for this peer */
5400 iaxs[callno]->sockfd = cai.sockfd;
5401
5402 /* Add remote vars */
5403 if (variablestore) {
5404 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5405 ast_debug(1, "Found an IAX variable store on this channel\n");
5406 AST_LIST_LOCK(variablelist);
5407 AST_LIST_TRAVERSE(variablelist, var, entries) {
5408 char tmp[256];
5409 int i;
5410 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5411 /* Automatically divide the value up into sized chunks */
5412 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5413 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5414 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
5415 }
5416 }
5417 AST_LIST_UNLOCK(variablelist);
5418 }
5419
5420 /* Transmit the string in a "NEW" request */
5421 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5422 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5423
5424 ast_mutex_unlock(&iaxsl[callno]);
5425 ast_setstate(c, AST_STATE_RINGING);
5426
5427 return 0;
5428 }
5429
5430 static int iax2_hangup(struct ast_channel *c)
5431 {
5432 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5433 struct iax_ie_data ied;
5434 int alreadygone;
5435 memset(&ied, 0, sizeof(ied));
5436 ast_mutex_lock(&iaxsl[callno]);
5437 if (callno && iaxs[callno]) {
5438 ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
5439 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5440 /* Send the hangup unless we have had a transmission error or are already gone */
5441 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)ast_channel_hangupcause(c));
5442 if (!iaxs[callno]->error && !alreadygone) {
5443 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5444 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5445 }
5446 if (!iaxs[callno]) {
5447 ast_mutex_unlock(&iaxsl[callno]);
5448 return 0;
5449 }
5450 }
5451 /* Explicitly predestroy it */
5452 iax2_predestroy(callno);
5453 /* If we were already gone to begin with, destroy us now */
5454 if (iaxs[callno] && alreadygone) {
5455 ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
5456 iax2_destroy(callno);
5457 } else if (iaxs[callno]) {
5458 if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5459 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5460 iax2_destroy(callno);
5461 }
5462 }
5463 } else if (ast_channel_tech_pvt(c)) {
5464 /* If this call no longer exists, but the channel still
5465 * references it we need to set the channel's tech_pvt to null
5466 * to avoid ast_channel_free() trying to free it.
5467 */
5468 ast_channel_tech_pvt_set(c, NULL);
5469 }
5470 ast_mutex_unlock(&iaxsl[callno]);
5471 ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
5472 return 0;
5473 }
5474
5475 /*!
5476 * \note expects the pvt to be locked
5477 */
5478 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5479 {
5480 unsigned short callno = pvt->callno;
5481
5482 if (!pvt->peercallno) {
5483 /* We don't know the remote side's call number, yet. :( */
5484 int count = 10;
5485 while (count-- && pvt && !pvt->peercallno) {
5486 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5487 pvt = iaxs[callno];
5488 }
5489 if (!pvt || !pvt->peercallno) {
5490 return -1;
5491 }
5492 }
5493
5494 return 0;
5495 }
5496
5497 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5498 {
5499 struct ast_option_header *h;
5500 int res;
5501
5502 switch (option) {
5503 case AST_OPTION_TXGAIN:
5504 case AST_OPTION_RXGAIN:
5505 /* these two cannot be sent, because they require a result */
5506 errno = ENOSYS;
5507 return -1;
5508 case AST_OPTION_OPRMODE:
5509 errno = EINVAL;
5510 return -1;
5511 case AST_OPTION_SECURE_SIGNALING:
5512 case AST_OPTION_SECURE_MEDIA:
5513 {
5514 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5515 ast_mutex_lock(&iaxsl[callno]);
5516 if ((*(int *) data)) {
5517 ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5518 } else {
5519 ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5520 }
5521 ast_mutex_unlock(&iaxsl[callno]);
5522 return 0;
5523 }
5524 /* These options are sent to the other side across the network where
5525 * they will be passed to whatever channel is bridged there. Don't
5526 * do anything silly like pass an option that transmits pointers to
5527 * memory on this machine to a remote machine to use */
5528 case AST_OPTION_TONE_VERIFY:
5529 case AST_OPTION_TDD:
5530 case AST_OPTION_RELAXDTMF:
5531 case AST_OPTION_AUDIO_MODE:
5532 case AST_OPTION_DIGIT_DETECT:
5533 case AST_OPTION_FAX_DETECT:
5534 {
5535 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5536 struct chan_iax2_pvt *pvt;
5537
5538 ast_mutex_lock(&iaxsl[callno]);
5539 pvt = iaxs[callno];
5540
5541 if (wait_for_peercallno(pvt)) {
5542 ast_mutex_unlock(&iaxsl[callno]);
5543 return -1;
5544 }
5545
5546 ast_mutex_unlock(&iaxsl[callno]);
5547
5548 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5549 return -1;
5550 }
5551
5552 h->flag = AST_OPTION_FLAG_REQUEST;
5553 h->option = htons(option);
5554 memcpy(h->data, data, datalen);
5555 res = send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_CONTROL,
5556 AST_CONTROL_OPTION, 0, (unsigned char *) h,
5557 datalen + sizeof(*h), -1);
5558 ast_free(h);
5559 return res;
5560 }
5561 default:
5562 return -1;
5563 }
5564
5565 /* Just in case someone does a break instead of a return */
5566 return -1;
5567 }
5568
5569 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5570 {
5571 switch (option) {
5572 case AST_OPTION_SECURE_SIGNALING:
5573 case AST_OPTION_SECURE_MEDIA:
5574 {
5575 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5576 ast_mutex_lock(&iaxsl[callno]);
5577 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5578 ast_mutex_unlock(&iaxsl[callno]);
5579 return 0;
5580 }
5581 default:
5582 return -1;
5583 }
5584 }
5585
5586 static struct ast_frame *iax2_read(struct ast_channel *c)
5587 {
5588 ast_debug(1, "I should never be called!\n");
5589 return &ast_null_frame;
5590 }
5591
5592 static int iax2_key_rotate(const void *vpvt)
5593 {
5594 int res = 0;
5595 struct chan_iax2_pvt *pvt = (void *) vpvt;
5596 struct MD5Context md5;
5597 char key[17] = "";
5598 struct iax_ie_data ied = {
5599 .pos = 0,
5600 };
5601
5602 ast_mutex_lock(&iaxsl[pvt->callno]);
5603 pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5604
5605 snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5606
5607 MD5Init(&md5);
5608 MD5Update(&md5, (unsigned char *) key, strlen(key));
5609 MD5Final((unsigned char *) key, &md5);
5610
5611 IAX_DEBUGDIGEST("Sending", key);
5612
5613 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5614
5615 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5616
5617 build_ecx_key((unsigned char *) key, pvt);
5618
5619 ast_mutex_unlock(&iaxsl[pvt->callno]);
5620
5621 return res;
5622 }
5623
5624 #if defined(IAX2_NATIVE_BRIDGING)
5625 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5626 {
5627 int res;
5628 struct iax_ie_data ied0;
5629 struct iax_ie_data ied1;
5630 unsigned int transferid = (unsigned int)ast_random();
5631
5632 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5633 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5634 ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
5635 ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
5636 return 0;
5637 }
5638
5639 memset(&ied0, 0, sizeof(ied0));
5640 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5641 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5642 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5643
5644 memset(&ied1, 0, sizeof(ied1));
5645 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5646 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5647 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5648
5649 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5650 if (res)
5651 return -1;
5652 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5653 if (res)
5654 return -1;
5655 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5656 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5657 return 0;
5658 }
5659 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5660
5661 #if defined(IAX2_NATIVE_BRIDGING)
5662 static void lock_both(unsigned short callno0, unsigned short callno1)
5663 {
5664 ast_mutex_lock(&iaxsl[callno0]);
5665 while (ast_mutex_trylock(&iaxsl[callno1])) {
5666 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5667 }
5668 }
5669 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5670
5671 #if defined(IAX2_NATIVE_BRIDGING)
5672 static void unlock_both(unsigned short callno0, unsigned short callno1)
5673 {
5674 ast_mutex_unlock(&iaxsl[callno1]);
5675 ast_mutex_unlock(&iaxsl[callno0]);
5676 }
5677 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5678
5679 #if defined(IAX2_NATIVE_BRIDGING)
5680 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
5681 {
5682 struct ast_channel *cs[3];
5683 struct ast_channel *who, *other;
5684 int to = -1;
5685 int res = -1;
5686 int transferstarted=0;
5687 struct ast_frame *f;
5688 unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
5689 unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
5690 struct timeval waittimer = {0, 0};
5691
5692 /* We currently do not support native bridging if a timeoutms value has been provided */
5693 if (timeoutms > 0) {
5694 return AST_BRIDGE_FAILED;
5695 }
5696
5697 timeoutms = -1;
5698
5699 lock_both(callno0, callno1);
5700 if (!iaxs[callno0] || !iaxs[callno1]) {
5701 unlock_both(callno0, callno1);
5702 return AST_BRIDGE_FAILED;
5703 }
5704 /* Put them in native bridge mode */
5705 if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
5706 iaxs[callno0]->bridgecallno = callno1;
5707 iaxs[callno1]->bridgecallno = callno0;
5708 }
5709 unlock_both(callno0, callno1);
5710
5711 /* If not, try to bridge until we can execute a transfer, if we can */
5712 cs[0] = c0;
5713 cs[1] = c1;
5714 for (/* ever */;;) {
5715 /* Check in case we got masqueraded into */
5716 if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
5717 ast_verb(3, "Can't masquerade, we're different...\n");
5718 /* Remove from native mode */
5719 if (ast_channel_tech(c0) == &iax2_tech) {
5720 ast_mutex_lock(&iaxsl[callno0]);
5721 iaxs[callno0]->bridgecallno = 0;
5722 ast_mutex_unlock(&iaxsl[callno0]);
5723 }
5724 if (ast_channel_tech(c1) == &iax2_tech) {
5725 ast_mutex_lock(&iaxsl[callno1]);
5726 iaxs[callno1]->bridgecallno = 0;
5727 ast_mutex_unlock(&iaxsl[callno1]);
5728 }
5729 return AST_BRIDGE_FAILED_NOWARN;
5730 }
5731 if (!(ast_format_cap_identical(ast_channel_nativeformats(c0), ast_channel_nativeformats(c1)))) {
5732 struct ast_str *c0_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5733 struct ast_str *c1_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
5734
5735 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n",
5736 ast_format_cap_get_names(ast_channel_nativeformats(c0), &c0_buf),
5737 ast_format_cap_get_names(ast_channel_nativeformats(c1), &c1_buf));
5738
5739 /* Remove from native mode */
5740 lock_both(callno0, callno1);
5741 if (iaxs[callno0])
5742 iaxs[callno0]->bridgecallno = 0;
5743 if (iaxs[callno1])
5744 iaxs[callno1]->bridgecallno = 0;
5745 unlock_both(callno0, callno1);
5746 return AST_BRIDGE_FAILED_NOWARN;
5747 }
5748 /* check if transferred and if we really want native bridging */
5749 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5750 /* Try the transfer */
5751 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5752 ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
5753 ast_log(LOG_WARNING, "Unable to start the transfer\n");
5754 transferstarted = 1;
5755 }
5756 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5757 /* Call has been transferred. We're no longer involved */
5758 struct timeval now = ast_tvnow();
5759 if (ast_tvzero(waittimer)) {
5760 waittimer = now;
5761 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5762 ast_channel_softhangup_internal_flag_add(c0, AST_SOFTHANGUP_DEV);
5763 ast_channel_softhangup_internal_flag_add(c1, AST_SOFTHANGUP_DEV);
5764 *fo = NULL;
5765 *rc = c0;
5766 res = AST_BRIDGE_COMPLETE;
5767 break;
5768 }
5769 }
5770 to = 1000;
5771 who = ast_waitfor_n(cs, 2, &to);
5772 /* XXX This will need to be updated to calculate
5773 * timeout correctly once timeoutms is allowed to be
5774 * > 0. Right now, this can go badly if the waitfor
5775 * times out in less than a millisecond
5776 */
5777 if (timeoutms > -1) {
5778 timeoutms -= (1000 - to);
5779 if (timeoutms < 0)
5780 timeoutms = 0;
5781 }
5782 if (!who) {
5783 if (!timeoutms) {
5784 res = AST_BRIDGE_RETRY;
5785 break;
5786 }
5787 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5788 res = AST_BRIDGE_FAILED;
5789 break;
5790 }
5791 continue;
5792 }
5793 f = ast_read(who);
5794 if (!f) {
5795 *fo = NULL;
5796 *rc = who;
5797 res = AST_BRIDGE_COMPLETE;
5798 break;
5799 }
5800 other = (who == c0) ? c1 : c0; /* the 'other' channel */
5801 if (f->frametype == AST_FRAME_CONTROL) {
5802 switch (f->subclass.integer) {
5803 case AST_CONTROL_VIDUPDATE:
5804 case AST_CONTROL_SRCUPDATE:
5805 case AST_CONTROL_SRCCHANGE:
5806 case AST_CONTROL_T38_PARAMETERS:
5807 ast_write(other, f);
5808 break;
5809 case AST_CONTROL_PVT_CAUSE_CODE:
5810 ast_channel_hangupcause_hash_set(other, f->data.ptr, f->datalen);
5811 break;
5812 default:
5813 *fo = f;
5814 *rc = who;
5815 res = AST_BRIDGE_COMPLETE;
5816 break;
5817 }
5818 if (res == AST_BRIDGE_COMPLETE) {
5819 break;
5820 }
5821 } else if (f->frametype == AST_FRAME_VOICE
5822 || f->frametype == AST_FRAME_TEXT
5823 || f->frametype == AST_FRAME_VIDEO
5824 || f->frametype == AST_FRAME_IMAGE) {
5825 ast_write(other, f);
5826 } else if (f->frametype == AST_FRAME_DTMF) {
5827 /* monitored dtmf take out of the bridge.
5828 * check if we monitor the specific source.
5829 */
5830 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5831
5832 if (flags & monitored_source) {
5833 *rc = who;
5834 *fo = f;
5835 res = AST_BRIDGE_COMPLETE;
5836 /* Remove from native mode */
5837 break;
5838 }
5839 ast_write(other, f);
5840 }
5841 ast_frfree(f);
5842 /* Swap who gets priority */
5843 cs[2] = cs[0];
5844 cs[0] = cs[1];
5845 cs[1] = cs[2];
5846 }
5847 lock_both(callno0, callno1);
5848 if(iaxs[callno0])
5849 iaxs[callno0]->bridgecallno = 0;
5850 if(iaxs[callno1])
5851 iaxs[callno1]->bridgecallno = 0;
5852 unlock_both(callno0, callno1);
5853 return res;
5854 }
5855 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5856
5857 static int iax2_answer(struct ast_channel *c)
5858 {
5859 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5860 ast_debug(1, "Answering IAX2 call\n");
5861 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
5862 }
5863
5864 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5865 {
5866 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5867 struct chan_iax2_pvt *pvt;
5868 int res = 0;
5869
5870 if (iaxdebug)
5871 ast_debug(1, "Indicating condition %d\n", condition);
5872
5873 ast_mutex_lock(&iaxsl[callno]);
5874 pvt = iaxs[callno];
5875
5876 if (wait_for_peercallno(pvt)) {
5877 res = -1;
5878 goto done;
5879 }
5880
5881 switch (condition) {
5882 case AST_CONTROL_HOLD:
5883 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5884 ast_moh_start(c, data, pvt->mohinterpret);
5885 goto done;
5886 }
5887 break;
5888 case AST_CONTROL_UNHOLD:
5889 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5890 ast_moh_stop(c);
5891 goto done;
5892 }
5893 break;
5894 case AST_CONTROL_CONNECTED_LINE:
5895 case AST_CONTROL_REDIRECTING:
5896 if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE)) {
5897 /* We are not configured to allow sending these updates. */
5898 ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5899 callno, condition);
5900 goto done;
5901 }
5902 break;
5903 case AST_CONTROL_PVT_CAUSE_CODE:
5904 case AST_CONTROL_MASQUERADE_NOTIFY:
5905 res = -1;
5906 goto done;
5907 }
5908
5909 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5910
5911 done:
5912 ast_mutex_unlock(&iaxsl[callno]);
5913
5914 return res;
5915 }
5916
5917 static int iax2_transfer(struct ast_channel *c, const char *dest)
5918 {
5919 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5920 struct iax_ie_data ied = { "", };
5921 char tmp[256], *context;
5922 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
5923 ast_copy_string(tmp, dest, sizeof(tmp));
5924 context = strchr(tmp, '@');
5925 if (context) {
5926 *context = '\0';
5927 context++;
5928 }
5929 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
5930 if (context)
5931 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
5932 ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
5933 ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
5934 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5935 }
5936
5937 static int iax2_getpeertrunk(struct ast_sockaddr addr)
5938 {
5939 struct iax2_peer *peer;
5940 int res = 0;
5941 struct ao2_iterator i;
5942
5943 i = ao2_iterator_init(peers, 0);
5944 while ((peer = ao2_iterator_next(&i))) {
5945
5946 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
5947 res = ast_test_flag64(peer, IAX_TRUNK);
5948 peer_unref(peer);
5949 break;
5950 }
5951 peer_unref(peer);
5952 }
5953 ao2_iterator_destroy(&i);
5954
5955 return res;
5956 }
5957
5958 /*! \brief Create new call, interface with the PBX core */
5959 static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability,
5960 struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids,
5961 const struct ast_channel *requestor, unsigned int cachable)
5962 {
5963 struct ast_channel *tmp = NULL;
5964 struct chan_iax2_pvt *i;
5965 struct iax2_peer *peer;
5966 struct ast_variable *v = NULL;
5967 struct ast_format_cap *native;
5968 struct ast_format *tmpfmt;
5969 ast_callid callid;
5970 char *peer_name = NULL;
5971
5972 if (!(i = iaxs[callno])) {
5973 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5974 return NULL;
5975 }
5976
5977 if (!capability) {
5978 ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5979 i->host, i->callno);
5980 return NULL;
5981 }
5982 native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
5983 if (!native) {
5984 return NULL;
5985 }
5986 if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5987 || !ast_format_cap_count(native)) {
5988 ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5989 i->host, i->callno);
5990 ao2_ref(native, -1);
5991 return NULL;
5992 }
5993
5994 if (!ast_strlen_zero(i->peer)) {
5995 peer_name = ast_strdupa(i->peer);
5996 } else if (!ast_strlen_zero(i->host)) {
5997 peer_name = ast_strdupa(i->host);
5998 }
5999
6000 /* Don't hold call lock while making a channel or looking up a peer */
6001 ast_mutex_unlock(&iaxsl[callno]);
6002
6003 if (!ast_strlen_zero(peer_name)) {
6004 peer = find_peer(peer_name, 1);
6005 if (peer && peer->endpoint) {
6006 tmp = ast_channel_alloc_with_endpoint(1, state, i->cid_num, i->cid_name,
6007 i->accountcode, i->exten, i->context, assignedids, requestor,
6008 i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
6009 }
6010 ao2_cleanup(peer);
6011 }
6012
6013 if (!tmp) {
6014 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
6015 i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
6016 i->host, i->callno);
6017 }
6018
6019 ast_mutex_lock(&iaxsl[callno]);
6020 if (i != iaxs[callno]) {
6021 if (tmp) {
6022 /* unlock and relock iaxsl[callno] to preserve locking order */
6023 ast_mutex_unlock(&iaxsl[callno]);
6024 ast_channel_unlock(tmp);
6025 tmp = ast_channel_release(tmp);
6026 ast_mutex_lock(&iaxsl[callno]);
6027 }
6028 ao2_ref(native, -1);
6029 return NULL;
6030 }
6031 if (!tmp) {
6032 ao2_ref(native, -1);
6033 return NULL;
6034 }
6035
6036 ast_channel_stage_snapshot(tmp);
6037
6038 if ((callid = iaxs[callno]->callid)) {
6039 ast_channel_callid_set(tmp, callid);
6040 }
6041
6042 ast_channel_tech_set(tmp, &iax2_tech);
6043
6044 /* We can support any format by default, until we get restricted */
6045 ast_channel_nativeformats_set(tmp, native);
6046 tmpfmt = ast_format_cap_get_format(native, 0);
6047
6048 ast_channel_set_readformat(tmp, tmpfmt);
6049 ast_channel_set_rawreadformat(tmp, tmpfmt);
6050 ast_channel_set_writeformat(tmp, tmpfmt);
6051 ast_channel_set_rawwriteformat(tmp, tmpfmt);
6052
6053 ao2_ref(tmpfmt, -1);
6054 ao2_ref(native, -1);
6055
6056 ast_channel_tech_pvt_set(tmp, CALLNO_TO_PTR(i->callno));
6057
6058 if (!ast_strlen_zero(i->parkinglot))
6059 ast_channel_parkinglot_set(tmp, i->parkinglot);
6060 /* Don't use ast_set_callerid() here because it will
6061 * generate a NewCallerID event before the NewChannel event */
6062 if (!ast_strlen_zero(i->ani)) {
6063 ast_channel_caller(tmp)->ani.number.valid = 1;
6064 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->ani);
6065 } else if (!ast_strlen_zero(i->cid_num)) {
6066 ast_channel_caller(tmp)->ani.number.valid = 1;
6067 ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
6068 }
6069 ast_channel_dialed(tmp)->number.str = ast_strdup(i->dnid);
6070 if (!ast_strlen_zero(i->rdnis)) {
6071 ast_channel_redirecting(tmp)->from.number.valid = 1;
6072 ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
6073 }
6074 ast_channel_caller(tmp)->ani2 = i->calling_ani2;
6075 ast_channel_caller(tmp)->id.name.presentation = i->calling_pres;
6076 ast_channel_caller(tmp)->id.number.presentation = i->calling_pres;
6077 ast_channel_caller(tmp)->id.number.plan = i->calling_ton;
6078 ast_channel_dialed(tmp)->transit_network_select = i->calling_tns;
6079 if (!ast_strlen_zero(i->language))
6080 ast_channel_language_set(tmp, i->language);
6081 if (!ast_strlen_zero(i->accountcode))
6082 ast_channel_accountcode_set(tmp, i->accountcode);
6083 if (i->amaflags)
6084 ast_channel_amaflags_set(tmp, i->amaflags);
6085 ast_channel_context_set(tmp, i->context);
6086 ast_channel_exten_set(tmp, i->exten);
6087 if (i->adsi)
6088 ast_channel_adsicpe_set(tmp, i->peeradsicpe);
6089 else
6090 ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
6091 i->owner = tmp;
6092 i->capability = capability;
6093
6094 if (!cachable) {
6095 ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
6096 }
6097
6098 /* Set inherited variables */
6099 if (i->vars) {
6100 for (v = i->vars ; v ; v = v->next)
6101 pbx_builtin_setvar_helper(tmp, v->name, v->value);
6102 }
6103 if (i->iaxvars) {
6104 struct ast_datastore *variablestore;
6105 struct ast_variable *var, *prev = NULL;
6106 AST_LIST_HEAD(, ast_var_t) *varlist;
6107 ast_debug(1, "Loading up the channel with IAXVARs\n");
6108 varlist = ast_calloc(1, sizeof(*varlist));
6109 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
6110 if (variablestore && varlist) {
6111 variablestore->data = varlist;
6112 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6113 AST_LIST_HEAD_INIT(varlist);
6114 for (var = i->iaxvars; var; var = var->next) {
6115 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6116 if (prev)
6117 ast_free(prev);
6118 prev = var;
6119 if (!newvar) {
6120 /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
6121 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6122 } else {
6123 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6124 }
6125 }
6126 if (prev)
6127 ast_free(prev);
6128 i->iaxvars = NULL;
6129 ast_channel_datastore_add(i->owner, variablestore);
6130 } else {
6131 if (variablestore) {
6132 ast_datastore_free(variablestore);
6133 }
6134 if (varlist) {
6135 ast_free(varlist);
6136 }
6137 }
6138 }
6139
6140 ast_channel_stage_snapshot_done(tmp);
6141 ast_channel_unlock(tmp);
6142
6143 if (state != AST_STATE_DOWN) {
6144 if (ast_pbx_start(tmp)) {
6145 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6146 /* unlock and relock iaxsl[callno] to preserve locking order */
6147 ast_mutex_unlock(&iaxsl[callno]);
6148 ast_hangup(tmp);
6149 ast_mutex_lock(&iaxsl[callno]);
6150 return NULL;
6151 }
6152 }
6153
6154 ast_module_ref(ast_module_info->self);
6155 return tmp;
6156 }
6157
6158 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
6159 {
6160 unsigned long int mssincetx; /* unsigned to handle overflows */
6161 long int ms, pred;
6162
6163 tpeer->trunkact = *now;
6164 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
6165 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
6166 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
6167 tpeer->txtrunktime = *now;
6168 tpeer->lastsent = 999999;
6169 }
6170 /* Update last transmit time now */
6171 tpeer->lasttxtime = *now;
6172
6173 /* Calculate ms offset */
6174 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
6175 /* Predict from last value */
6176 pred = tpeer->lastsent + sampms;
6177 if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
6178 ms = pred;
6179
6180 /* We never send the same timestamp twice, so fudge a little if we must */
6181 if (ms == tpeer->lastsent)
6182 ms = tpeer->lastsent + 1;
6183 tpeer->lastsent = ms;
6184 return ms;
6185 }
6186
6187 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
6188 {
6189 long ms; /* NOT unsigned */
6190 if (ast_tvzero(iaxs[callno]->rxcore)) {
6191 /* Initialize rxcore time if appropriate */
6192 iaxs[callno]->rxcore = ast_tvnow();
6193 /* Round to nearest 20ms so traces look pretty */
6194 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6195 }
6196 /* Calculate difference between trunk and channel */
6197 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6198 /* Return as the sum of trunk time and the difference between trunk and real time */
6199 return ms + ts;
6200 }
6201
6202 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6203 {
6204 int ms;
6205 int voice = 0;
6206 int genuine = 0;
6207 int adjust;
6208 int rate = 0;
6209 struct timeval *delivery = NULL;
6210
6211
6212 /* What sort of frame do we have?: voice is self-explanatory
6213 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6214 non-genuine frames are CONTROL frames [ringing etc], DTMF
6215 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6216 the others need a timestamp slaved to the voice frames so that they go in sequence
6217 */
6218 if (f->frametype == AST_FRAME_VOICE) {
6219 voice = 1;
6220 rate = ast_format_get_sample_rate(f->subclass.format) / 1000;
6221 delivery = &f->delivery;
6222 } else if (f->frametype == AST_FRAME_IAX) {
6223 genuine = 1;
6224 } else if (f->frametype == AST_FRAME_CNG) {
6225 p->notsilenttx = 0;
6226 }
6227
6228 if (ast_tvzero(p->offset)) {
6229 p->offset = ast_tvnow();
6230 /* Round to nearest 20ms for nice looking traces */
6231 p->offset.tv_usec -= p->offset.tv_usec % 20000;
6232 }
6233 /* If the timestamp is specified, just send it as is */
6234 if (ts)
6235 return ts;
6236 /* If we have a time that the frame arrived, always use it to make our timestamp */
6237 if (delivery && !ast_tvzero(*delivery)) {
6238 ms = ast_tvdiff_ms(*delivery, p->offset);
6239 if (ms < 0) {
6240 ms = 0;
6241 }
6242 if (iaxdebug)
6243 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6244 } else {
6245 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6246 if (ms < 0)
6247 ms = 0;
6248 if (voice) {
6249 /* On a voice frame, use predicted values if appropriate */
6250 adjust = (ms - p->nextpred);
6251 if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6252 /* Adjust our txcore, keeping voice and non-voice synchronized */
6253 /* AN EXPLANATION:
6254 When we send voice, we usually send "calculated" timestamps worked out
6255 on the basis of the number of samples sent. When we send other frames,
6256 we usually send timestamps worked out from the real clock.
6257 The problem is that they can tend to drift out of step because the
6258 source channel's clock and our clock may not be exactly at the same rate.
6259 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6260 for this call. Moving it adjusts timestamps for non-voice frames.
6261 We make the adjustment in the style of a moving average. Each time we
6262 adjust p->offset by 10% of the difference between our clock-derived
6263 timestamp and the predicted timestamp. That's why you see "10000"
6264 below even though IAX2 timestamps are in milliseconds.
6265 The use of a moving average avoids offset moving too radically.
6266 Generally, "adjust" roams back and forth around 0, with offset hardly
6267 changing at all. But if a consistent different starts to develop it
6268 will be eliminated over the course of 10 frames (200-300msecs)
6269 */
6270 if (adjust < 0)
6271 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6272 else if (adjust > 0)
6273 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6274
6275 if (!p->nextpred) {
6276 p->nextpred = ms; /*f->samples / rate;*/
6277 if (p->nextpred <= p->lastsent)
6278 p->nextpred = p->lastsent + 3;
6279 }
6280 ms = p->nextpred;
6281 } else {
6282 /* in this case, just use the actual
6283 * time, since we're either way off
6284 * (shouldn't happen), or we're ending a
6285 * silent period -- and seed the next
6286 * predicted time. Also, round ms to the
6287 * next multiple of frame size (so our
6288 * silent periods are multiples of
6289 * frame size too) */
6290
6291 if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
6292 ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6293 abs(adjust), MAX_TIMESTAMP_SKEW);
6294
6295 if (f->samples >= rate) /* check to make sure we don't core dump */
6296 {
6297 int diff = ms % (f->samples / rate);
6298 if (diff)
6299 ms += f->samples/rate - diff;
6300 }
6301
6302 p->nextpred = ms;
6303 p->notsilenttx = 1;
6304 }
6305 } else if ( f->frametype == AST_FRAME_VIDEO ) {
6306 /*
6307 * IAX2 draft 03 says that timestamps MUST be in order.
6308 * It does not say anything about several frames having the same timestamp
6309 * When transporting video, we can have a frame that spans multiple iax packets
6310 * (so called slices), so it would make sense to use the same timestamp for all of
6311 * them
6312 * We do want to make sure that frames don't go backwards though
6313 */
6314 if ( (unsigned int)ms < p->lastsent )
6315 ms = p->lastsent;
6316 } else {
6317 /* On a dataframe, use last value + 3 (to accommodate jitter buffer shrinking) if appropriate unless
6318 it's a genuine frame */
6319 adjust = (ms - p->lastsent);
6320 if (genuine) {
6321 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6322 if (ms <= p->lastsent)
6323 ms = p->lastsent + 3;
6324 } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6325 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6326 ms = p->lastsent + 3;
6327 }
6328 }
6329 }
6330 p->lastsent = ms;
6331 if (voice) {
6332 p->nextpred = p->nextpred + f->samples / rate;
6333 }
6334 return ms;
6335 }
6336
6337 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6338 {
6339 /* Returns where in "receive time" we are. That is, how many ms
6340 since we received (or would have received) the frame with timestamp 0 */
6341 int ms;
6342 #ifdef IAXTESTS
6343 int jit;
6344 #endif /* IAXTESTS */
6345 /* Setup rxcore if necessary */
6346 if (ast_tvzero(p->rxcore)) {
6347 p->rxcore = ast_tvnow();
6348 if (iaxdebug)
6349 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6350 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6351 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6352 #if 1
6353 if (iaxdebug)
6354 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6355 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6356 #endif
6357 }
6358
6359 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6360 #ifdef IAXTESTS
6361 if (test_jit) {
6362 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6363 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6364 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6365 jit = -jit;
6366 ms += jit;
6367 }
6368 }
6369 if (test_late) {
6370 ms += test_late;
6371 test_late = 0;
6372 }
6373 #endif /* IAXTESTS */
6374 return ms;
6375 }
6376
6377 static struct iax2_trunk_peer *find_tpeer(struct ast_sockaddr *addr, int fd)
6378 {
6379 struct iax2_trunk_peer *tpeer = NULL;
6380
6381 /* Finds and locks trunk peer */
6382 AST_LIST_LOCK(&tpeers);
6383
6384 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6385 if (!ast_sockaddr_cmp(&tpeer->addr, addr)) {
6386 ast_mutex_lock(&tpeer->lock);
6387 break;
6388 }
6389 }
6390
6391 if (!tpeer) {
6392 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6393 ast_mutex_init(&tpeer->lock);
6394 tpeer->lastsent = 9999;
6395 ast_sockaddr_copy(&tpeer->addr, addr);
6396 tpeer->trunkact = ast_tvnow();
6397 ast_mutex_lock(&tpeer->lock);
6398 tpeer->sockfd = fd;
6399
6400 #ifdef SO_NO_CHECK
6401 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6402 #endif
6403 ast_debug(1, "Created trunk peer for '%s'\n", ast_sockaddr_stringify(&tpeer->addr));
6404 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
6405 }
6406 }
6407
6408 AST_LIST_UNLOCK(&tpeers);
6409
6410 return tpeer;
6411 }
6412
6413 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6414 {
6415 struct ast_frame *f;
6416 struct iax2_trunk_peer *tpeer;
6417 void *tmp, *ptr;
6418 struct timeval now;
6419 struct ast_iax2_meta_trunk_entry *met;
6420 struct ast_iax2_meta_trunk_mini *mtm;
6421
6422 f = &fr->af;
6423 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6424 if (tpeer) {
6425
6426 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6427 /* Need to reallocate space */
6428 if (tpeer->trunkdataalloc < trunkmaxsize) {
6429 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6430 ast_mutex_unlock(&tpeer->lock);
6431 return -1;
6432 }
6433
6434 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
6435 tpeer->trunkdata = tmp;
6436 ast_debug(1, "Expanded trunk '%s' to %u bytes\n", ast_sockaddr_stringify(&tpeer->addr), tpeer->trunkdataalloc);
6437 } else {
6438 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s\n", ast_sockaddr_stringify(&tpeer->addr));
6439 ast_mutex_unlock(&tpeer->lock);
6440 return -1;
6441 }
6442 }
6443
6444 /* Append to meta frame */
6445 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6446 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
6447 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6448 mtm->len = htons(f->datalen);
6449 mtm->mini.callno = htons(pvt->callno);
6450 mtm->mini.ts = htons(0xffff & fr->ts);
6451 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6452 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6453 } else {
6454 met = (struct ast_iax2_meta_trunk_entry *)ptr;
6455 /* Store call number and length in meta header */
6456 met->callno = htons(pvt->callno);
6457 met->len = htons(f->datalen);
6458 /* Advance pointers/decrease length past trunk entry header */
6459 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6460 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6461 }
6462 /* Copy actual trunk data */
6463 memcpy(ptr, f->data.ptr, f->datalen);
6464 tpeer->trunkdatalen += f->datalen;
6465
6466 tpeer->calls++;
6467
6468 /* track the largest mtu we actually have sent */
6469 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6470 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6471
6472 /* if we have enough for a full MTU, ship it now without waiting */
6473 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6474 now = ast_tvnow();
6475 send_trunk(tpeer, &now);
6476 trunk_untimed ++;
6477 }
6478
6479 ast_mutex_unlock(&tpeer->lock);
6480 }
6481 return 0;
6482 }
6483
6484 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6485 * before the encryption data. This function randomizes that data. */
6486 static void build_rand_pad(unsigned char *buf, ssize_t len)
6487 {
6488 long tmp;
6489 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6490 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6491 buf += sizeof(tmp);
6492 len -= sizeof(tmp);
6493 }
6494 }
6495
6496 static int invalid_key(ast_aes_decrypt_key *ecx)
6497 {
6498 #ifdef HAVE_OPENSSL
6499 int i;
6500 for (i = 0; i < 60; i++) {
6501 if (ecx->raw[i]) {
6502 return 0; /* stop if we encounter anything non-zero */
6503 }
6504 }
6505 /* if ast_aes_encrypt or ast_aes_decrypt is called, then we'll crash when calling AES_encrypt or AES_decrypt */
6506 return -1;
6507 #else
6508 return 0; /* Can't verify, but doesn't matter anyways */
6509 #endif
6510 }
6511
6512 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6513 {
6514 build_ecx_key(digest, pvt);
6515 ast_aes_set_decrypt_key(digest, &pvt->dcx);
6516 }
6517
6518 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6519 {
6520 /* it is required to hold the corresponding decrypt key to our encrypt key
6521 * in the pvt struct because queued frames occasionally need to be decrypted and
6522 * re-encrypted when updated for a retransmission */
6523 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6524 ast_aes_set_encrypt_key(digest, &pvt->ecx);
6525 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6526 }
6527
6528 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6529 {
6530 #if 0
6531 /* Debug with "fake encryption" */
6532 int x;
6533 if (len % 16)
6534 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6535 for (x=0;x<len;x++)
6536 dst[x] = src[x] ^ 0xff;
6537 #else
6538 unsigned char lastblock[16] = { 0 };
6539 int x;
6540 while(len > 0) {
6541 ast_aes_decrypt(src, dst, dcx);
6542 for (x=0;x<16;x++)
6543 dst[x] ^= lastblock[x];
6544 memcpy(lastblock, src, sizeof(lastblock));
6545 dst += 16;
6546 src += 16;
6547 len -= 16;
6548 }
6549 #endif
6550 }
6551
6552 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6553 {
6554 #if 0
6555 /* Debug with "fake encryption" */
6556 int x;
6557 if (len % 16)
6558 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6559 for (x=0;x<len;x++)
6560 dst[x] = src[x] ^ 0xff;
6561 #else
6562 unsigned char curblock[16] = { 0 };
6563 int x;
6564 while(len > 0) {
6565 for (x=0;x<16;x++)
6566 curblock[x] ^= src[x];
6567 ast_aes_encrypt(curblock, dst, ecx);
6568 memcpy(curblock, dst, sizeof(curblock));
6569 dst += 16;
6570 src += 16;
6571 len -= 16;
6572 }
6573 #endif
6574 }
6575
6576 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6577 {
6578 int padding;
6579 unsigned char *workspace;
6580
6581 workspace = ast_alloca(*datalen);
6582 memset(f, 0, sizeof(*f));
6583 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6584 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6585 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6586 return -1;
6587 /* Decrypt */
6588 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6589
6590 padding = 16 + (workspace[15] & 0x0f);
6591 if (iaxdebug)
6592 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
6593 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6594 return -1;
6595
6596 *datalen -= padding;
6597 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6598 f->frametype = fh->type;
6599 if (f->frametype == AST_FRAME_VIDEO) {
6600 f->subclass.format = ast_format_compatibility_bitfield2format(uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1));
6601 if (!f->subclass.format) {
6602 f->subclass.format = ast_format_none;
6603 }
6604 } else if (f->frametype == AST_FRAME_VOICE) {
6605 f->subclass.format = ast_format_compatibility_bitfield2format(uncompress_subclass(fh->csub));
6606 if (!f->subclass.format) {
6607 f->subclass.format = ast_format_none;
6608 }
6609 } else {
6610 f->subclass.integer = uncompress_subclass(fh->csub);
6611 }
6612 } else {
6613 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6614 if (iaxdebug)
6615 ast_debug(5, "Decoding mini with length %d\n", *datalen);
6616 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6617 return -1;
6618 /* Decrypt */
6619 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6620 padding = 16 + (workspace[15] & 0x0f);
6621 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6622 return -1;
6623 *datalen -= padding;
6624 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6625 }
6626 return 0;
6627 }
6628
6629 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6630 {
6631 int padding;
6632 unsigned char *workspace;
6633 workspace = ast_alloca(*datalen + 32);
6634 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6635 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6636 if (iaxdebug)
6637 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6638 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6639 padding = 16 + (padding & 0xf);
6640 memcpy(workspace, poo, padding);
6641 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6642 workspace[15] &= 0xf0;
6643 workspace[15] |= (padding & 0xf);
6644 if (iaxdebug)
6645 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
6646 *datalen += padding;
6647 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6648 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6649 memcpy(poo, workspace + *datalen - 32, 32);
6650 } else {
6651 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6652 if (iaxdebug)
6653 ast_debug(5, "Encoding mini frame with length %d\n", *datalen);
6654 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6655 padding = 16 + (padding & 0xf);
6656 memcpy(workspace, poo, padding);
6657 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6658 workspace[15] &= 0xf0;
6659 workspace[15] |= (padding & 0x0f);
6660 *datalen += padding;
6661 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6662 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6663 memcpy(poo, workspace + *datalen - 32, 32);
6664 }
6665 return 0;
6666 }
6667
6668 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6669 {
6670 int res=-1;
6671 if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
6672 /* Search for possible keys, given secrets */
6673 struct MD5Context md5;
6674 unsigned char digest[16];
6675 char *tmppw, *stringp;
6676
6677 tmppw = ast_strdupa(iaxs[callno]->secret);
6678 stringp = tmppw;
6679 while ((tmppw = strsep(&stringp, ";"))) {
6680 MD5Init(&md5);
6681 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6682 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6683 MD5Final(digest, &md5);
6684 build_encryption_keys(digest, iaxs[callno]);
6685 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6686 if (!res) {
6687 ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
6688 break;
6689 }
6690 }
6691 } else
6692 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6693 return res;
6694 }
6695
6696 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6697 {
6698 /* Queue a packet for delivery on a given private structure. Use "ts" for
6699 timestamp, or calculate if ts is 0. Send immediately without retransmission
6700 or delayed, with retransmission */
6701 struct ast_iax2_full_hdr *fh;
6702 struct ast_iax2_mini_hdr *mh;
6703 struct ast_iax2_video_hdr *vh;
6704 struct {
6705 struct iax_frame fr2;
6706 unsigned char buffer[4096];
6707 } frb;
6708 struct iax_frame *fr;
6709 int res;
6710 int sendmini=0;
6711 unsigned int lastsent;
6712 unsigned int fts;
6713
6714 frb.fr2.afdatalen = sizeof(frb.buffer);
6715
6716 if (!pvt) {
6717 ast_log(LOG_WARNING, "No private structure for packet?\n");
6718 return -1;
6719 }
6720
6721 lastsent = pvt->lastsent;
6722
6723 /* Calculate actual timestamp */
6724 fts = calc_timestamp(pvt, ts, f);
6725
6726 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6727 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6728 * increment the "predicted timestamps" for voice, if we're predicting */
6729 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6730 return 0;
6731 #if 0
6732 ast_log(LOG_NOTICE,
6733 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6734 *("=!" + (f->frametype == AST_FRAME_VOICE)),
6735 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6736 pvt->keyrotateid != -1 ? "" : "no "
6737 );
6738 #endif
6739 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6740 iax2_key_rotate(pvt);
6741 }
6742
6743 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6744 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6745 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6746 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6747 (f->frametype == AST_FRAME_VOICE)
6748 /* is a voice frame */ &&
6749 (ast_format_cmp(f->subclass.format, ast_format_compatibility_bitfield2format(pvt->svoiceformat)) ==
6750 AST_FORMAT_CMP_EQUAL)
6751 /* is the same type */ ) {
6752 /* Force immediate rather than delayed transmission */
6753 now = 1;
6754 /* Mark that mini-style frame is appropriate */
6755 sendmini = 1;
6756 }
6757 if ( f->frametype == AST_FRAME_VIDEO ) {
6758 /*
6759 * If the lower 15 bits of the timestamp roll over, or if
6760 * the video format changed then send a full frame.
6761 * Otherwise send a mini video frame
6762 */
6763 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6764 (ast_format_cmp(f->subclass.format, ast_format_compatibility_bitfield2format(pvt->svideoformat)) ==
6765 AST_FORMAT_CMP_EQUAL)
6766 ) {
6767 now = 1;
6768 sendmini = 1;
6769 } else {
6770 now = 0;
6771 sendmini = 0;
6772 }
6773 pvt->lastvsent = fts;
6774 }
6775 if (f->frametype == AST_FRAME_IAX) {
6776 /* 0x8000 marks this message as TX:, this bit will be stripped later */
6777 pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
6778 if (!pvt->first_iax_message) {
6779 pvt->first_iax_message = pvt->last_iax_message;
6780 }
6781 }
6782 /* Allocate an iax_frame */
6783 if (now) {
6784 fr = &frb.fr2;
6785 } else
6786 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag64(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
6787 if (!fr) {
6788 ast_log(LOG_WARNING, "Out of memory\n");
6789 return -1;
6790 }
6791 /* Copy our prospective frame into our immediate or retransmitted wrapper */
6792 iax_frame_wrap(fr, f);
6793
6794 fr->ts = fts;
6795 fr->callno = pvt->callno;
6796 fr->transfer = transfer;
6797 fr->final = final;
6798 fr->encmethods = 0;
6799 if (!sendmini) {
6800 /* We need a full frame */
6801 if (seqno > -1)
6802 fr->oseqno = seqno;
6803 else
6804 fr->oseqno = pvt->oseqno++;
6805 fr->iseqno = pvt->iseqno;
6806 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6807 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6808 fh->ts = htonl(fr->ts);
6809 fh->oseqno = fr->oseqno;
6810 if (transfer) {
6811 fh->iseqno = 0;
6812 } else
6813 fh->iseqno = fr->iseqno;
6814 /* Keep track of the last thing we've acknowledged */
6815 if (!transfer)
6816 pvt->aseqno = fr->iseqno;
6817 fh->type = fr->af.frametype & 0xFF;
6818
6819 if (fr->af.frametype == AST_FRAME_VIDEO) {
6820 iax2_format tmpfmt = ast_format_compatibility_format2bitfield(fr->af.subclass.format);
6821 tmpfmt |= fr->af.subclass.frame_ending ? 0x1LL : 0;
6822 fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
6823 } else if (fr->af.frametype == AST_FRAME_VOICE) {
6824 fh->csub = compress_subclass(ast_format_compatibility_format2bitfield(fr->af.subclass.format));
6825 } else {
6826 fh->csub = compress_subclass(fr->af.subclass.integer);
6827 }
6828
6829 if (transfer) {
6830 fr->dcallno = pvt->transfercallno;
6831 } else
6832 fr->dcallno = pvt->peercallno;
6833 fh->dcallno = htons(fr->dcallno);
6834 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6835 fr->data = fh;
6836 fr->retries = 0;
6837 /* Retry after 2x the ping time has passed */
6838 fr->retrytime = pvt->pingtime * 2;
6839 if (fr->retrytime < MIN_RETRY_TIME)
6840 fr->retrytime = MIN_RETRY_TIME;
6841 if (fr->retrytime > MAX_RETRY_TIME)
6842 fr->retrytime = MAX_RETRY_TIME;
6843 /* Acks' don't get retried */
6844 if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
6845 fr->retries = -1;
6846 else if (f->frametype == AST_FRAME_VOICE)
6847 pvt->svoiceformat = ast_format_compatibility_format2bitfield(f->subclass.format);
6848 else if (f->frametype == AST_FRAME_VIDEO)
6849 pvt->svideoformat = ast_format_compatibility_format2bitfield(f->subclass.format);
6850 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6851 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6852 if (fr->transfer)
6853 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6854 else
6855 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6856 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6857 fr->encmethods = pvt->encmethods;
6858 fr->ecx = pvt->ecx;
6859 fr->mydcx = pvt->mydcx;
6860 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6861 } else
6862 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6863 }
6864
6865 if (now) {
6866 res = send_packet(fr);
6867 } else
6868 res = iax2_transmit(fr);
6869 } else {
6870 if (ast_test_flag64(pvt, IAX_TRUNK)) {
6871 iax2_trunk_queue(pvt, fr);
6872 res = 0;
6873 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6874 /* Video frame have no sequence number */
6875 fr->oseqno = -1;
6876 fr->iseqno = -1;
6877 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6878 vh->zeros = 0;
6879 vh->callno = htons(0x8000 | fr->callno);
6880 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.frame_ending ? 0x8000 : 0));
6881 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6882 fr->data = vh;
6883 fr->retries = -1;
6884 res = send_packet(fr);
6885 } else {
6886 /* Mini-frames have no sequence number */
6887 fr->oseqno = -1;
6888 fr->iseqno = -1;
6889 /* Mini frame will do */
6890 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6891 mh->callno = htons(fr->callno);
6892 mh->ts = htons(fr->ts & 0xFFFF);
6893 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6894 fr->data = mh;
6895 fr->retries = -1;
6896 if (pvt->transferring == TRANSFER_MEDIAPASS)
6897 fr->transfer = 1;
6898 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6899 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6900 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6901 } else
6902 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6903 }
6904 res = send_packet(fr);
6905 }
6906 }
6907 return res;
6908 }
6909
6910 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6911 {
6912 regex_t regexbuf;
6913 int havepattern = 0;
6914
6915 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6916 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6917
6918 struct iax2_user *user = NULL;
6919 char auth[90];
6920 char *pstr = "";
6921 struct ao2_iterator i;
6922
6923 switch (cmd) {
6924 case CLI_INIT:
6925 e->command = "iax2 show users [like]";
6926 e->usage =
6927 "Usage: iax2 show users [like <pattern>]\n"
6928 " Lists all known IAX2 users.\n"
6929 " Optional regular expression pattern is used to filter the user list.\n";
6930 return NULL;
6931 case CLI_GENERATE:
6932 return NULL;
6933 }
6934
6935 switch (a->argc) {
6936 case 5:
6937 if (!strcasecmp(a->argv[3], "like")) {
6938 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6939 return CLI_SHOWUSAGE;
6940 havepattern = 1;
6941 } else
6942 return CLI_SHOWUSAGE;
6943 case 3:
6944 break;
6945 default:
6946 return CLI_SHOWUSAGE;
6947 }
6948
6949 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6950 i = ao2_iterator_init(users, 0);
6951 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6952 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6953 continue;
6954
6955 if (!ast_strlen_zero(user->secret)) {
6956 ast_copy_string(auth,user->secret, sizeof(auth));
6957 } else if (!ast_strlen_zero(user->inkeys)) {
6958 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6959 } else
6960 ast_copy_string(auth, "-no secret-", sizeof(auth));
6961
6962 if(ast_test_flag64(user, IAX_CODEC_NOCAP))
6963 pstr = "REQ Only";
6964 else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
6965 pstr = "Disabled";
6966 else
6967 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6968
6969 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6970 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6971 ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
6972 }
6973 ao2_iterator_destroy(&i);
6974
6975 if (havepattern)
6976 regfree(&regexbuf);
6977
6978 return CLI_SUCCESS;
6979 #undef FORMAT
6980 #undef FORMAT2
6981 }
6982
6983 struct show_peers_context {
6984 regex_t regexbuf;
6985 int havepattern;
6986 char idtext[256];
6987 int registeredonly;
6988 int peerlist;
6989 int total_peers;
6990 int online_peers;
6991 int offline_peers;
6992 int unmonitored_peers;
6993 };
6994
6995 #define PEERS_FORMAT2 "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
6996 #define PEERS_FORMAT "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
6997
6998 static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
6999 {
7000 char name[256] = "";
7001 char status[64];
7002 int retstatus;
7003 struct ast_str *encmethods = ast_str_alloca(256);
7004
7005 char *tmp_host, *tmp_mask, *tmp_port;
7006
7007 tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
7008 tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
7009 tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
7010
7011 if (!ast_strlen_zero(peer->username)) {
7012 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
7013 } else {
7014 ast_copy_string(name, peer->name, sizeof(name));
7015 }
7016
7017 encmethods_to_str(peer->encmethods, &encmethods);
7018 retstatus = peer_status(peer, status, sizeof(status));
7019 if (retstatus > 0) {
7020 cont->online_peers++;
7021 } else if (!retstatus) {
7022 cont->offline_peers++;
7023 } else {
7024 cont->unmonitored_peers++;
7025 }
7026
7027 if (s) {
7028 if (cont->peerlist) { /* IAXpeerlist */
7029 astman_append(s,
7030 "Event: PeerEntry\r\n%s"
7031 "Channeltype: IAX\r\n",
7032 cont->idtext);
7033 if (!ast_strlen_zero(peer->username)) {
7034 astman_append(s,
7035 "ObjectName: %s\r\n"
7036 "ObjectUsername: %s\r\n",
7037 peer->name,
7038 peer->username);
7039 } else {
7040 astman_append(s,
7041 "ObjectName: %s\r\n",
7042 name);
7043 }
7044 } else { /* IAXpeers */
7045 astman_append(s,
7046 "Event: PeerEntry\r\n%s"
7047 "Channeltype: IAX2\r\n"
7048 "ObjectName: %s\r\n",
7049 cont->idtext,
7050 name);
7051 }
7052 astman_append(s,
7053 "ChanObjectType: peer\r\n"
7054 "IPaddress: %s\r\n",
7055 tmp_host);
7056 if (cont->peerlist) { /* IAXpeerlist */
7057 astman_append(s,
7058 "Mask: %s\r\n"
7059 "Port: %s\r\n",
7060 tmp_mask,
7061 tmp_port);
7062 } else { /* IAXpeers */
7063 astman_append(s,
7064 "IPport: %s\r\n",
7065 tmp_port);
7066 }
7067 astman_append(s,
7068 "Dynamic: %s\r\n"
7069 "Trunk: %s\r\n"
7070 "Encryption: %s\r\n"
7071 "Status: %s\r\n",
7072 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
7073 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
7074 peer->encmethods ? ast_str_buffer(encmethods) : "no",
7075 status);
7076 if (cont->peerlist) { /* IAXpeerlist */
7077 astman_append(s, "\r\n");
7078 } else { /* IAXpeers */
7079 astman_append(s,
7080 "Description: %s\r\n\r\n",
7081 peer->description);
7082 }
7083 } else {
7084 ast_cli(fd, PEERS_FORMAT,
7085 name,
7086 tmp_host,
7087 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
7088 tmp_mask,
7089 tmp_port,
7090 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
7091 peer->encmethods ? "(E)" : " ",
7092 status,
7093 peer->description);
7094 }
7095
7096 cont->total_peers++;
7097 }
7098
7099 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
7100 {
7101 struct show_peers_context cont = {
7102 .havepattern = 0,
7103 .idtext = "",
7104 .registeredonly = 0,
7105
7106 .peerlist = 0,
7107
7108 .total_peers = 0,
7109 .online_peers = 0,
7110 .offline_peers = 0,
7111 .unmonitored_peers = 0,
7112 };
7113
7114 struct ao2_iterator i;
7115
7116 struct iax2_peer *peer = NULL;
7117
7118 switch (argc) {
7119 case 6:
7120 if (!strcasecmp(argv[3], "registered"))
7121 cont.registeredonly = 1;
7122 else
7123 return RESULT_SHOWUSAGE;
7124 if (!strcasecmp(argv[4], "like")) {
7125 if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
7126 return RESULT_SHOWUSAGE;
7127 cont.havepattern = 1;
7128 } else
7129 return RESULT_SHOWUSAGE;
7130 break;
7131 case 5:
7132 if (!strcasecmp(argv[3], "like")) {
7133 if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
7134 return RESULT_SHOWUSAGE;
7135 cont.havepattern = 1;
7136 } else
7137 return RESULT_SHOWUSAGE;
7138 break;
7139 case 4:
7140 if (!strcasecmp(argv[3], "registered")) {
7141 cont.registeredonly = 1;
7142 } else {
7143 return RESULT_SHOWUSAGE;
7144 }
7145 break;
7146 case 3:
7147 break;
7148 default:
7149 return RESULT_SHOWUSAGE;
7150 }
7151
7152
7153 if (!s) {
7154 ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7155 }
7156
7157 i = ao2_iterator_init(peers, 0);
7158 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7159
7160 if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7161 continue;
7162 }
7163 if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7164 continue;
7165 }
7166
7167 _iax2_show_peers_one(fd, s, &cont, peer);
7168
7169 }
7170 ao2_iterator_destroy(&i);
7171
7172 if (!s) {
7173 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7174 cont.total_peers, cont.online_peers, cont.offline_peers, cont.unmonitored_peers);
7175 }
7176
7177 if (cont.havepattern) {
7178 regfree(&cont.regexbuf);
7179 }
7180
7181 if (total) {
7182 *total = cont.total_peers;
7183 }
7184
7185 return RESULT_SUCCESS;
7186
7187 }
7188 #undef PEERS_FORMAT2
7189 #undef PEERS_FORMAT
7190
7191 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7192 {
7193 struct iax2_thread *thread = NULL;
7194 time_t t;
7195 int threadcount = 0, dynamiccount = 0;
7196 char type;
7197
7198 switch (cmd) {
7199 case CLI_INIT:
7200 e->command = "iax2 show threads";
7201 e->usage =
7202 "Usage: iax2 show threads\n"
7203 " Lists status of IAX helper threads\n";
7204 return NULL;
7205 case CLI_GENERATE:
7206 return NULL;
7207 }
7208 if (a->argc != 3)
7209 return CLI_SHOWUSAGE;
7210
7211 ast_cli(a->fd, "IAX2 Thread Information\n");
7212 time(&t);
7213 ast_cli(a->fd, "Idle Threads:\n");
7214 AST_LIST_LOCK(&idle_list);
7215 AST_LIST_TRAVERSE(&idle_list, thread, list) {
7216 #ifdef DEBUG_SCHED_MULTITHREAD
7217 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7218 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7219 #else
7220 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7221 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7222 #endif
7223 threadcount++;
7224 }
7225 AST_LIST_UNLOCK(&idle_list);
7226 ast_cli(a->fd, "Active Threads:\n");
7227 AST_LIST_LOCK(&active_list);
7228 AST_LIST_TRAVERSE(&active_list, thread, list) {
7229 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
7230 type = 'D';
7231 else
7232 type = 'P';
7233 #ifdef DEBUG_SCHED_MULTITHREAD
7234 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
7235 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7236 #else
7237 ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
7238 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7239 #endif
7240 threadcount++;
7241 }
7242 AST_LIST_UNLOCK(&active_list);
7243 ast_cli(a->fd, "Dynamic Threads:\n");
7244 AST_LIST_LOCK(&dynamic_list);
7245 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
7246 #ifdef DEBUG_SCHED_MULTITHREAD
7247 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7248 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7249 #else
7250 ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7251 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7252 #endif
7253 dynamiccount++;
7254 }
7255 AST_LIST_UNLOCK(&dynamic_list);
7256 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
7257 return CLI_SUCCESS;
7258 }
7259
7260 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7261 {
7262 struct iax2_peer *p;
7263
7264 switch (cmd) {
7265 case CLI_INIT:
7266 e->command = "iax2 unregister";
7267 e->usage =
7268 "Usage: iax2 unregister <peername>\n"
7269 " Unregister (force expiration) an IAX2 peer from the registry.\n";
7270 return NULL;
7271 case CLI_GENERATE:
7272 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
7273 }
7274
7275 if (a->argc != 3)
7276 return CLI_SHOWUSAGE;
7277
7278 p = find_peer(a->argv[2], 1);
7279 if (p) {
7280 if (p->expire > -1) {
7281 struct iax2_peer *peer;
7282
7283 peer = ao2_find(peers, a->argv[2], OBJ_KEY);
7284 if (peer) {
7285 expire_registry(peer_ref(peer)); /* will release its own reference when done */
7286 peer_unref(peer); /* ref from ao2_find() */
7287 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
7288 } else {
7289 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
7290 }
7291 } else {
7292 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7293 }
7294 peer_unref(p);
7295 } else {
7296 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7297 }
7298 return CLI_SUCCESS;
7299 }
7300
7301 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7302 {
7303 int which = 0;
7304 struct iax2_peer *p = NULL;
7305 char *res = NULL;
7306 int wordlen = strlen(word);
7307
7308 /* 0 - iax2; 1 - unregister; 2 - <peername> */
7309 if (pos == 2) {
7310 struct ao2_iterator i = ao2_iterator_init(peers, 0);
7311 while ((p = ao2_iterator_next(&i))) {
7312 if (!strncasecmp(p->name, word, wordlen) &&
7313 ++which > state && p->expire > -1) {
7314 res = ast_strdup(p->name);
7315 peer_unref(p);
7316 break;
7317 }
7318 peer_unref(p);
7319 }
7320 ao2_iterator_destroy(&i);
7321 }
7322
7323 return res;
7324 }
7325
7326 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7327 {
7328 switch (cmd) {
7329 case CLI_INIT:
7330 e->command = "iax2 show peers";
7331 e->usage =
7332 "Usage: iax2 show peers [registered] [like <pattern>]\n"
7333 " Lists all known IAX2 peers.\n"
7334 " Optional 'registered' argument lists only peers with known addresses.\n"
7335 " Optional regular expression pattern is used to filter the peer list.\n";
7336 return NULL;
7337 case CLI_GENERATE:
7338 return NULL;
7339 }
7340
7341 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7342 case RESULT_SHOWUSAGE:
7343 return CLI_SHOWUSAGE;
7344 case RESULT_FAILURE:
7345 return CLI_FAILURE;
7346 default:
7347 return CLI_SUCCESS;
7348 }
7349 }
7350
7351 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7352 {
7353 ast_cli_netstats(s, -1, 0);
7354 astman_append(s, "\r\n");
7355 return RESULT_SUCCESS;
7356 }
7357
7358 static int firmware_show_callback(struct ast_iax2_firmware_header *header,
7359 void *user_data)
7360 {
7361 int *fd = user_data;
7362
7363 ast_cli(*fd, "%-15.15s %-15d %-15d\n",
7364 header->devname,
7365 ntohs(header->version),
7366 (int) ntohl(header->datalen));
7367
7368 return 0;
7369 }
7370
7371 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7372 {
7373 switch (cmd) {
7374 case CLI_INIT:
7375 e->command = "iax2 show firmware";
7376 e->usage =
7377 "Usage: iax2 show firmware\n"
7378 " Lists all known IAX firmware images.\n";
7379 return NULL;
7380 case CLI_GENERATE:
7381 return NULL;
7382 }
7383
7384 if (a->argc != 3 && a->argc != 4)
7385 return CLI_SHOWUSAGE;
7386
7387 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7388
7389 iax_firmware_traverse(
7390 a->argc == 3 ? NULL : a->argv[3],
7391 firmware_show_callback,
7392 (void *) &a->fd);
7393
7394 return CLI_SUCCESS;
7395 }
7396
7397 /*! \brief callback to display iax peers in manager */
7398 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7399 {
7400 static const char * const a[] = { "iax2", "show", "peers" };
7401 const char *id = astman_get_header(m,"ActionID");
7402 char idtext[256] = "";
7403 int total = 0;
7404
7405 if (!ast_strlen_zero(id))
7406 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7407
7408 astman_send_listack(s, m, "Peer status list will follow", "start");
7409
7410 /* List the peers in separate manager events */
7411 __iax2_show_peers(-1, &total, s, 3, a);
7412
7413 /* Send final confirmation */
7414 astman_send_list_complete_start(s, m, "PeerlistComplete", total);
7415 astman_send_list_complete_end(s);
7416 return 0;
7417 }
7418
7419 /*! \brief callback to display iax peers in manager format */
7420 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7421 {
7422 struct show_peers_context cont = {
7423 .havepattern = 0,
7424 .idtext = "",
7425 .registeredonly = 0,
7426
7427 .peerlist = 1,
7428
7429 .total_peers = 0,
7430 .online_peers = 0,
7431 .offline_peers = 0,
7432 .unmonitored_peers = 0,
7433 };
7434
7435 struct iax2_peer *peer = NULL;
7436 struct ao2_iterator i;
7437
7438 const char *id = astman_get_header(m,"ActionID");
7439
7440 if (!ast_strlen_zero(id)) {
7441 snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
7442 }
7443
7444 astman_send_listack(s, m, "IAX Peer status list will follow", "start");
7445
7446 i = ao2_iterator_init(peers, 0);
7447 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7448 _iax2_show_peers_one(-1, s, &cont, peer);
7449 }
7450 ao2_iterator_destroy(&i);
7451
7452 astman_send_list_complete_start(s, m, "PeerlistComplete", cont.total_peers);
7453 astman_send_list_complete_end(s);
7454
7455 return RESULT_SUCCESS;
7456 }
7457
7458
7459 static char *regstate2str(int regstate)
7460 {
7461 switch(regstate) {
7462 case REG_STATE_UNREGISTERED:
7463 return "Unregistered";
7464 case REG_STATE_REGSENT:
7465 return "Request Sent";
7466 case REG_STATE_AUTHSENT:
7467 return "Auth. Sent";
7468 case REG_STATE_REGISTERED:
7469 return "Registered";
7470 case REG_STATE_REJECTED:
7471 return "Rejected";
7472 case REG_STATE_TIMEOUT:
7473 return "Timeout";
7474 case REG_STATE_NOAUTH:
7475 return "No Authentication";
7476 default:
7477 return "Unknown";
7478 }
7479 }
7480
7481 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7482 {
7483 #define FORMAT2 "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
7484 #define FORMAT "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
7485
7486 struct iax2_registry *reg = NULL;
7487 char host[80];
7488 char perceived[80];
7489 int counter = 0;
7490
7491 switch (cmd) {
7492 case CLI_INIT:
7493 e->command = "iax2 show registry";
7494 e->usage =
7495 "Usage: iax2 show registry\n"
7496 " Lists all registration requests and status.\n";
7497 return NULL;
7498 case CLI_GENERATE:
7499 return NULL;
7500 }
7501 if (a->argc != 3)
7502 return CLI_SHOWUSAGE;
7503 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7504 AST_LIST_LOCK(&registrations);
7505 AST_LIST_TRAVERSE(&registrations, reg, entry) {
7506 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7507
7508 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7509
7510 ast_cli(a->fd, FORMAT, host,
7511 (reg->dnsmgr) ? "Y" : "N",
7512 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7513 counter++;
7514 }
7515 AST_LIST_UNLOCK(&registrations);
7516 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7517 return CLI_SUCCESS;
7518 #undef FORMAT
7519 #undef FORMAT2
7520 }
7521
7522 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7523 {
7524 const char *id = astman_get_header(m, "ActionID");
7525 struct iax2_registry *reg = NULL;
7526 char idtext[256] = "";
7527 char host[80] = "";
7528 char perceived[80] = "";
7529 int total = 0;
7530
7531 if (!ast_strlen_zero(id))
7532 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7533
7534 astman_send_listack(s, m, "Registrations will follow", "start");
7535
7536 AST_LIST_LOCK(&registrations);
7537 AST_LIST_TRAVERSE(&registrations, reg, entry) {
7538 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7539
7540 snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->us) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->us));
7541
7542 astman_append(s,
7543 "Event: RegistryEntry\r\n"
7544 "%s"
7545 "Host: %s\r\n"
7546 "DNSmanager: %s\r\n"
7547 "Username: %s\r\n"
7548 "Perceived: %s\r\n"
7549 "Refresh: %d\r\n"
7550 "State: %s\r\n"
7551 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7552 reg->refresh, regstate2str(reg->regstate));
7553
7554 total++;
7555 }
7556 AST_LIST_UNLOCK(&registrations);
7557
7558 astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
7559 astman_send_list_complete_end(s);
7560
7561 return 0;
7562 }
7563
7564 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7565 {
7566 #define FORMAT2 "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7567 #define FORMAT "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
7568 #define FORMATB "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7569 int x;
7570 int numchans = 0;
7571 char first_message[10] = { 0, };
7572 char last_message[10] = { 0, };
7573
7574 switch (cmd) {
7575 case CLI_INIT:
7576 e->command = "iax2 show channels";
7577 e->usage =
7578 "Usage: iax2 show channels\n"
7579 " Lists all currently active IAX channels.\n";
7580 return NULL;
7581 case CLI_GENERATE:
7582 return NULL;
7583 }
7584
7585 if (a->argc != 3)
7586 return CLI_SHOWUSAGE;
7587 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7588 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7589 ast_mutex_lock(&iaxsl[x]);
7590 if (iaxs[x]) {
7591 int lag, jitter, localdelay;
7592 jb_info jbinfo;
7593 if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7594 jb_getinfo(iaxs[x]->jb, &jbinfo);
7595 jitter = jbinfo.jitter;
7596 localdelay = jbinfo.current - jbinfo.min;
7597 } else {
7598 jitter = -1;
7599 localdelay = 0;
7600 }
7601
7602 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7603 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7604 lag = iaxs[x]->remote_rr.delay;
7605 ast_cli(a->fd, FORMAT,
7606 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7607 ast_sockaddr_stringify_addr(&iaxs[x]->addr),
7608 S_OR(iaxs[x]->username, "(None)"),
7609 iaxs[x]->callno, iaxs[x]->peercallno,
7610 iaxs[x]->oseqno, iaxs[x]->iseqno,
7611 lag,
7612 jitter,
7613 localdelay,
7614 iax2_getformatname(iaxs[x]->voiceformat),
7615 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7616 first_message,
7617 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7618 last_message);
7619 numchans++;
7620 }
7621 ast_mutex_unlock(&iaxsl[x]);
7622 }
7623 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7624 return CLI_SUCCESS;
7625 #undef FORMAT
7626 #undef FORMAT2
7627 #undef FORMATB
7628 }
7629
7630 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7631 {
7632 int x;
7633 int numchans = 0;
7634 char first_message[10] = { 0, };
7635 char last_message[10] = { 0, };
7636 #define ACN_FORMAT1 "%-24.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7637 #define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7638 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7639 ast_mutex_lock(&iaxsl[x]);
7640 if (iaxs[x]) {
7641 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7642 jb_info jbinfo;
7643 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7644 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7645
7646 if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7647 jb_getinfo(iaxs[x]->jb, &jbinfo);
7648 localjitter = jbinfo.jitter;
7649 localdelay = jbinfo.current - jbinfo.min;
7650 locallost = jbinfo.frames_lost;
7651 locallosspct = jbinfo.losspct/1000;
7652 localdropped = jbinfo.frames_dropped;
7653 localooo = jbinfo.frames_ooo;
7654 } else {
7655 localjitter = -1;
7656 localdelay = 0;
7657 locallost = -1;
7658 locallosspct = -1;
7659 localdropped = 0;
7660 localooo = -1;
7661 }
7662 if (s)
7663 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7664 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7665 iaxs[x]->pingtime,
7666 localjitter,
7667 localdelay,
7668 locallost,
7669 locallosspct,
7670 localdropped,
7671 localooo,
7672 iaxs[x]->frames_received/1000,
7673 iaxs[x]->remote_rr.jitter,
7674 iaxs[x]->remote_rr.delay,
7675 iaxs[x]->remote_rr.losscnt,
7676 iaxs[x]->remote_rr.losspct,
7677 iaxs[x]->remote_rr.dropped,
7678 iaxs[x]->remote_rr.ooo,
7679 iaxs[x]->remote_rr.packets/1000,
7680 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7681 first_message,
7682 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7683 last_message);
7684 else
7685 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7686 iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7687 iaxs[x]->pingtime,
7688 localjitter,
7689 localdelay,
7690 locallost,
7691 locallosspct,
7692 localdropped,
7693 localooo,
7694 iaxs[x]->frames_received/1000,
7695 iaxs[x]->remote_rr.jitter,
7696 iaxs[x]->remote_rr.delay,
7697 iaxs[x]->remote_rr.losscnt,
7698 iaxs[x]->remote_rr.losspct,
7699 iaxs[x]->remote_rr.dropped,
7700 iaxs[x]->remote_rr.ooo,
7701 iaxs[x]->remote_rr.packets/1000,
7702 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7703 first_message,
7704 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7705 last_message);
7706 numchans++;
7707 }
7708 ast_mutex_unlock(&iaxsl[x]);
7709 }
7710
7711 return numchans;
7712 }
7713
7714 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7715 {
7716 int numchans = 0;
7717
7718 switch (cmd) {
7719 case CLI_INIT:
7720 e->command = "iax2 show netstats";
7721 e->usage =
7722 "Usage: iax2 show netstats\n"
7723 " Lists network status for all currently active IAX channels.\n";
7724 return NULL;
7725 case CLI_GENERATE:
7726 return NULL;
7727 }
7728 if (a->argc != 3)
7729 return CLI_SHOWUSAGE;
7730 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7731 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7732 numchans = ast_cli_netstats(NULL, a->fd, 1);
7733 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7734 return CLI_SUCCESS;
7735 }
7736
7737 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7738 {
7739 switch (cmd) {
7740 case CLI_INIT:
7741 e->command = "iax2 set debug {on|off|peer}";
7742 e->usage =
7743 "Usage: iax2 set debug {on|off|peer peername}\n"
7744 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7745 return NULL;
7746 case CLI_GENERATE:
7747 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7748 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7749 return NULL;
7750 }
7751
7752 if (a->argc < e->args || a->argc > e->args + 1)
7753 return CLI_SHOWUSAGE;
7754
7755 if (!strcasecmp(a->argv[3], "peer")) {
7756 struct iax2_peer *peer;
7757
7758 if (a->argc != e->args + 1)
7759 return CLI_SHOWUSAGE;
7760
7761 peer = find_peer(a->argv[4], 1);
7762
7763 if (!peer) {
7764 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7765 return CLI_FAILURE;
7766 }
7767
7768 ast_sockaddr_copy(&debugaddr, &peer->addr);
7769
7770 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_port(&debugaddr));
7771
7772 ao2_ref(peer, -1);
7773 } else if (!strncasecmp(a->argv[3], "on", 2)) {
7774 iaxdebug = 1;
7775 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7776 } else {
7777 iaxdebug = 0;
7778 memset(&debugaddr, 0, sizeof(debugaddr));
7779 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7780 }
7781 return CLI_SUCCESS;
7782 }
7783
7784 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7785 {
7786 switch (cmd) {
7787 case CLI_INIT:
7788 e->command = "iax2 set debug trunk {on|off}";
7789 e->usage =
7790 "Usage: iax2 set debug trunk {on|off}\n"
7791 " Enables/Disables debugging of IAX trunking\n";
7792 return NULL;
7793 case CLI_GENERATE:
7794 return NULL;
7795 }
7796
7797 if (a->argc != e->args)
7798 return CLI_SHOWUSAGE;
7799
7800 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7801 iaxtrunkdebug = 1;
7802 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7803 } else {
7804 iaxtrunkdebug = 0;
7805 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7806 }
7807 return CLI_SUCCESS;
7808 }
7809
7810 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7811 {
7812 switch (cmd) {
7813 case CLI_INIT:
7814 e->command = "iax2 set debug jb {on|off}";
7815 e->usage =
7816 "Usage: iax2 set debug jb {on|off}\n"
7817 " Enables/Disables jitterbuffer debugging information\n";
7818 return NULL;
7819 case CLI_GENERATE:
7820 return NULL;
7821 }
7822
7823 if (a->argc != e->args)
7824 return CLI_SHOWUSAGE;
7825
7826 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7827 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
7828 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7829 } else {
7830 jb_setoutput(jb_error_output, jb_warning_output, NULL);
7831 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7832 }
7833 return CLI_SUCCESS;
7834 }
7835
7836 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7837 {
7838 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
7839 int res = -1;
7840 ast_mutex_lock(&iaxsl[callno]);
7841 if (iaxs[callno]) {
7842 /* If there's an outstanding error, return failure now */
7843 if (!iaxs[callno]->error) {
7844 if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
7845 res = 0;
7846 /* Don't waste bandwidth sending null frames */
7847 else if (f->frametype == AST_FRAME_NULL)
7848 res = 0;
7849 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
7850 res = 0;
7851 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
7852 res = 0;
7853 else
7854 /* Simple, just queue for transmission */
7855 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7856 } else {
7857 ast_debug(1, "Write error: %s\n", strerror(errno));
7858 }
7859 }
7860 /* If it's already gone, just return */
7861 ast_mutex_unlock(&iaxsl[callno]);
7862 return res;
7863 }
7864
7865 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7866 int now, int transfer, int final)
7867 {
7868 struct ast_frame f = { 0, };
7869 int res = 0;
7870
7871 f.frametype = type;
7872 f.subclass.integer = command;
7873 f.datalen = datalen;
7874 f.src = __FUNCTION__;
7875 f.data.ptr = (void *) data;
7876
7877 if ((res = queue_signalling(i, &f)) <= 0) {
7878 return res;
7879 }
7880
7881 return iax2_send(i, &f, ts, seqno, now, transfer, final);
7882 }
7883
7884 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7885 {
7886 if (type == AST_FRAME_CONTROL && !iax2_is_control_frame_allowed(command)) {
7887 /* Control frame should not go out on the wire. */
7888 ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7889 i->callno, command);
7890 return 0;
7891 }
7892 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7893 }
7894
7895 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7896 {
7897 int res;
7898 ast_mutex_lock(&iaxsl[callno]);
7899 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7900 ast_mutex_unlock(&iaxsl[callno]);
7901 return res;
7902 }
7903
7904 /*!
7905 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7906 * the pvt struct for the given call number may disappear during its
7907 * execution.
7908 */
7909 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7910 {
7911 int call_num = i->callno;
7912 /* It is assumed that the callno has already been locked */
7913 iax2_predestroy(i->callno);
7914 if (!iaxs[call_num])
7915 return -1;
7916 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7917 }
7918
7919 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7920 {
7921 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7922 }
7923
7924 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7925 {
7926 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7927 }
7928
7929 static int apply_context(struct iax2_context *con, const char *context)
7930 {
7931 while(con) {
7932 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7933 return -1;
7934 con = con->next;
7935 }
7936 return 0;
7937 }
7938
7939
7940 static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
7941 {
7942 /* Start pessimistic */
7943 int res = -1;
7944 int version = 2;
7945 struct iax2_user *user = NULL, *best = NULL;
7946 int bestscore = 0;
7947 int gotcapability = 0;
7948 struct ast_variable *v = NULL, *tmpvar = NULL;
7949 struct ao2_iterator i;
7950
7951 if (!iaxs[callno])
7952 return res;
7953 if (ies->called_number)
7954 ast_string_field_set(iaxs[callno], exten, ies->called_number);
7955 if (ies->calling_number) {
7956 if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
7957 ast_shrink_phone_number(ies->calling_number);
7958 }
7959 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7960 }
7961 if (ies->calling_name)
7962 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7963 if (ies->calling_ani)
7964 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7965 if (ies->dnid)
7966 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7967 if (ies->rdnis)
7968 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7969 if (ies->called_context)
7970 ast_string_field_set(iaxs[callno], context, ies->called_context);
7971 if (ies->language)
7972 ast_string_field_set(iaxs[callno], language, ies->language);
7973 if (ies->username)
7974 ast_string_field_set(iaxs[callno], username, ies->username);
7975 if (ies->calling_ton > -1)
7976 iaxs[callno]->calling_ton = ies->calling_ton;
7977 if (ies->calling_tns > -1)
7978 iaxs[callno]->calling_tns = ies->calling_tns;
7979 if (ies->calling_pres > -1)
7980 iaxs[callno]->calling_pres = ies->calling_pres;
7981 if (ies->calling_ani2 > -1)
7982 iaxs[callno]->calling_ani2 = ies->calling_ani2;
7983 if (ies->format)
7984 iaxs[callno]->peerformat = ies->format;
7985 if (ies->adsicpe)
7986 iaxs[callno]->peeradsicpe = ies->adsicpe;
7987 if (ies->capability) {
7988 gotcapability = 1;
7989 iaxs[callno]->peercapability = ies->capability;
7990 }
7991 if (ies->version)
7992 version = ies->version;
7993
7994 /* Use provided preferences until told otherwise for actual preferences */
7995 if (ies->codec_prefs) {
7996 iax2_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7997 } else {
7998 memset(&iaxs[callno]->rprefs, 0, sizeof(iaxs[callno]->rprefs));
7999 }
8000 iaxs[callno]->prefs = iaxs[callno]->rprefs;
8001
8002 if (!gotcapability) {
8003 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
8004 }
8005 if (version > IAX_PROTO_VERSION) {
8006 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
8007 ast_sockaddr_stringify_addr(addr), version);
8008 return res;
8009 }
8010 /* Search the userlist for a compatible entry, and fill in the rest */
8011 i = ao2_iterator_init(users, 0);
8012 while ((user = ao2_iterator_next(&i))) {
8013 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
8014 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
8015 && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
8016 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
8017 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
8018 if (!ast_strlen_zero(iaxs[callno]->username)) {
8019 /* Exact match, stop right now. */
8020 if (best)
8021 user_unref(best);
8022 best = user;
8023 break;
8024 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
8025 /* No required authentication */
8026 if (user->acl) {
8027 /* There was host authentication and we passed, bonus! */
8028 if (bestscore < 4) {
8029 bestscore = 4;
8030 if (best)
8031 user_unref(best);
8032 best = user;
8033 continue;
8034 }
8035 } else {
8036 /* No host access, but no secret, either, not bad */
8037 if (bestscore < 3) {
8038 bestscore = 3;
8039 if (best)
8040 user_unref(best);
8041 best = user;
8042 continue;
8043 }
8044 }
8045 } else {
8046 if (user->acl) {
8047 /* Authentication, but host access too, eh, it's something.. */
8048 if (bestscore < 2) {
8049 bestscore = 2;
8050 if (best)
8051 user_unref(best);
8052 best = user;
8053 continue;
8054 }
8055 } else {
8056 /* Authentication and no host access... This is our baseline */
8057 if (bestscore < 1) {
8058 bestscore = 1;
8059 if (best)
8060 user_unref(best);
8061 best = user;
8062 continue;
8063 }
8064 }
8065 }
8066 }
8067 user_unref(user);
8068 }
8069 ao2_iterator_destroy(&i);
8070 user = best;
8071 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
8072 user = realtime_user(iaxs[callno]->username, addr);
8073 if (user && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
8074 || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
8075 !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
8076 user = user_unref(user);
8077 }
8078 }
8079 if (user) {
8080 /* We found our match (use the first) */
8081 /* copy vars */
8082 for (v = user->vars ; v ; v = v->next) {
8083 if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
8084 if (ast_variable_list_replace(&iaxs[callno]->vars, tmpvar)) {
8085 tmpvar->next = iaxs[callno]->vars;
8086 iaxs[callno]->vars = tmpvar;
8087 }
8088 }
8089 }
8090 /* If a max AUTHREQ restriction is in place, activate it */
8091 if (user->maxauthreq > 0)
8092 ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
8093 iaxs[callno]->prefs = user->prefs;
8094 ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
8095 iaxs[callno]->encmethods = user->encmethods;
8096 /* Store the requested username if not specified */
8097 if (ast_strlen_zero(iaxs[callno]->username))
8098 ast_string_field_set(iaxs[callno], username, user->name);
8099 /* Store whether this is a trunked call, too, of course, and move if appropriate */
8100 ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
8101 iaxs[callno]->capability = user->capability;
8102 /* And use the default context */
8103 if (ast_strlen_zero(iaxs[callno]->context)) {
8104 if (user->contexts)
8105 ast_string_field_set(iaxs[callno], context, user->contexts->context);
8106 else
8107 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
8108 }
8109 /* And any input keys */
8110 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
8111 /* And the permitted authentication methods */
8112 iaxs[callno]->authmethods = user->authmethods;
8113 iaxs[callno]->adsi = user->adsi;
8114 /* If the user has callerid, override the remote caller id. */
8115 if (ast_test_flag64(user, IAX_HASCALLERID)) {
8116 iaxs[callno]->calling_tns = 0;
8117 iaxs[callno]->calling_ton = 0;
8118 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
8119 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
8120 ast_string_field_set(iaxs[callno], ani, user->cid_num);
8121 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
8122 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
8123 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
8124 } /* else user is allowed to set their own CID settings */
8125 if (!ast_strlen_zero(user->accountcode))
8126 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
8127 if (!ast_strlen_zero(user->mohinterpret))
8128 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
8129 if (!ast_strlen_zero(user->mohsuggest))
8130 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
8131 if (!ast_strlen_zero(user->parkinglot))
8132 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
8133 if (user->amaflags)
8134 iaxs[callno]->amaflags = user->amaflags;
8135 if (!ast_strlen_zero(user->language))
8136 ast_string_field_set(iaxs[callno], language, user->language);
8137 ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
8138 /* Keep this check last */
8139 if (!ast_strlen_zero(user->dbsecret)) {
8140 char *family, *key=NULL;
8141 char buf[80];
8142 family = ast_strdupa(user->dbsecret);
8143 key = strchr(family, '/');
8144 if (key) {
8145 *key = '\0';
8146 key++;
8147 }
8148 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
8149 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
8150 else
8151 ast_string_field_set(iaxs[callno], secret, buf);
8152 } else
8153 ast_string_field_set(iaxs[callno], secret, user->secret);
8154 res = 0;
8155 user = user_unref(user);
8156 } else {
8157 /* user was not found, but we should still fake an AUTHREQ.
8158 * Set authmethods to the last known authmethod used by the system
8159 * Set a fake secret, it's not looked at, just required to attempt authentication.
8160 * Set authrej so the AUTHREP is rejected without even looking at its contents */
8161 iaxs[callno]->authmethods = last_authmethod ? last_authmethod : IAX_AUTH_MD5;
8162 ast_string_field_set(iaxs[callno], secret, "badsecret");
8163 iaxs[callno]->authrej = 1;
8164 if (!ast_strlen_zero(iaxs[callno]->username)) {
8165 /* only send the AUTHREQ if a username was specified. */
8166 res = 0;
8167 }
8168 }
8169 ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*addr), IAX_TRUNK);
8170 return res;
8171 }
8172
8173 static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
8174 {
8175 struct ast_iax2_full_hdr fh;
8176 fh.scallno = htons(src | IAX_FLAG_FULL);
8177 fh.dcallno = htons(dst);
8178 fh.ts = 0;
8179 fh.oseqno = 0;
8180 fh.iseqno = 0;
8181 fh.type = AST_FRAME_IAX;
8182 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
8183 iax_outputframe(NULL, &fh, 0, addr, 0);
8184
8185 ast_debug(1, "Raw Hangup %s, src=%d, dst=%d\n", ast_sockaddr_stringify(addr), src, dst);
8186 return ast_sendto(sockfd, &fh, sizeof(fh), 0, addr);
8187 }
8188
8189 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
8190 {
8191 /* Select exactly one common encryption if there are any */
8192 p->encmethods &= enc;
8193 if (p->encmethods) {
8194 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
8195 p->keyrotateid = -2;
8196 }
8197 if (p->encmethods & IAX_ENCRYPT_AES128)
8198 p->encmethods = IAX_ENCRYPT_AES128;
8199 else
8200 p->encmethods = 0;
8201 }
8202 }
8203
8204 /*!
8205 * \pre iaxsl[call_num] is locked
8206 *
8207 * \note Since this function calls send_command_final(), the pvt struct for the given
8208 * call number may disappear while executing this function.
8209 */
8210 static int authenticate_request(int call_num)
8211 {
8212 struct iax_ie_data ied;
8213 int res = -1, authreq_restrict = 0;
8214 char challenge[10];
8215 struct chan_iax2_pvt *p = iaxs[call_num];
8216
8217 memset(&ied, 0, sizeof(ied));
8218
8219 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8220 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
8221 struct iax2_user *user;
8222
8223 user = ao2_find(users, p->username, OBJ_KEY);
8224 if (user) {
8225 if (user->curauthreq == user->maxauthreq)
8226 authreq_restrict = 1;
8227 else
8228 user->curauthreq++;
8229 user = user_unref(user);
8230 }
8231 }
8232
8233 /* If the AUTHREQ limit test failed, send back an error */
8234 if (authreq_restrict) {
8235 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8236 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
8237 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
8238 return 0;
8239 }
8240
8241 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
8242 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8243 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8244 ast_string_field_set(p, challenge, challenge);
8245 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8246 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
8247 }
8248 if (p->encmethods)
8249 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
8250
8251 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
8252
8253 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8254
8255 if (p->encmethods)
8256 ast_set_flag64(p, IAX_ENCRYPTED);
8257
8258 return res;
8259 }
8260
8261 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
8262 {
8263 char requeststr[256];
8264 char md5secret[256] = "";
8265 char secret[256] = "";
8266 char rsasecret[256] = "";
8267 int res = -1;
8268 int x;
8269 struct iax2_user *user;
8270
8271 if (p->authrej) {
8272 return res;
8273 }
8274
8275 user = ao2_find(users, p->username, OBJ_KEY);
8276 if (user) {
8277 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
8278 ast_atomic_fetchadd_int(&user->curauthreq, -1);
8279 ast_clear_flag64(p, IAX_MAXAUTHREQ);
8280 }
8281 ast_string_field_set(p, host, user->name);
8282 user = user_unref(user);
8283 }
8284 if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
8285 ast_log(LOG_WARNING, "Call Terminated, incoming call is unencrypted while force encrypt is enabled.\n");
8286 return res;
8287 }
8288 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
8289 return res;
8290 if (ies->password)
8291 ast_copy_string(secret, ies->password, sizeof(secret));
8292 if (ies->md5_result)
8293 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8294 if (ies->rsa_result)
8295 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8296 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8297 struct ast_key *key;
8298 char *keyn;
8299 char *tmpkey;
8300 char *stringp=NULL;
8301 if (!(tmpkey = ast_strdup(p->inkeys))) {
8302 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8303 return res;
8304 }
8305 stringp = tmpkey;
8306 keyn = strsep(&stringp, ":");
8307 while(keyn) {
8308 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8309 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8310 res = 0;
8311 p->eff_auth_method = IAX_AUTH_RSA;
8312 break;
8313 } else if (!key) {
8314 ast_log(LOG_WARNING, "Requested inkey '%s' for RSA authentication does not exist\n", keyn);
8315 }
8316 keyn = strsep(&stringp, ":");
8317 }
8318 ast_free(tmpkey);
8319 if (res && authdebug) {
8320 ast_log(LOG_WARNING, "No RSA public keys on file matched incoming call\n");
8321 }
8322 } else if (p->authmethods & IAX_AUTH_MD5) {
8323 struct MD5Context md5;
8324 unsigned char digest[16];
8325 char *tmppw, *stringp;
8326 tmppw = ast_strdupa(p->secret);
8327 stringp = tmppw;
8328 while((tmppw = strsep(&stringp, ";"))) {
8329 MD5Init(&md5);
8330 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8331 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8332 MD5Final(digest, &md5);
8333 /* If they support md5, authenticate with it. */
8334 for (x=0;x<16;x++)
8335 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8336 if (!strcasecmp(requeststr, md5secret)) {
8337 res = 0;
8338 p->eff_auth_method = IAX_AUTH_MD5;
8339 break;
8340 } else if (authdebug) {
8341 ast_log(LOG_WARNING, "MD5 secret mismatch\n");
8342 }
8343 }
8344 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8345 if (!strcmp(secret, p->secret)) {
8346 res = 0;
8347 p->eff_auth_method = IAX_AUTH_PLAINTEXT;
8348 } else if (authdebug) {
8349 ast_log(LOG_WARNING, "Plaintext secret mismatch\n");
8350 }
8351 }
8352 return res;
8353 }
8354
8355 /*! \brief Verify inbound registration */
8356 static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
8357 {
8358 char requeststr[256] = "";
8359 char peer[256] = "";
8360 char md5secret[256] = "";
8361 char rsasecret[256] = "";
8362 char secret[256] = "";
8363 struct iax2_peer *p = NULL;
8364 struct ast_key *key;
8365 char *keyn;
8366 int x;
8367 int expire = 0;
8368 int res = -1;
8369
8370 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8371 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8372 if (ies->username)
8373 ast_copy_string(peer, ies->username, sizeof(peer));
8374 if (ies->password)
8375 ast_copy_string(secret, ies->password, sizeof(secret));
8376 if (ies->md5_result)
8377 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8378 if (ies->rsa_result)
8379 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8380 if (ies->refresh)
8381 expire = ies->refresh;
8382
8383 if (ast_strlen_zero(peer)) {
8384 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_sockaddr_stringify_addr(addr));
8385 return -1;
8386 }
8387
8388 /* SLD: first call to lookup peer during registration */
8389 ast_mutex_unlock(&iaxsl[callno]);
8390 p = find_peer(peer, 1);
8391 ast_mutex_lock(&iaxsl[callno]);
8392 if (!p || !iaxs[callno]) {
8393 if (iaxs[callno]) {
8394 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8395 /* Anything, as long as it's non-blank */
8396 ast_string_field_set(iaxs[callno], secret, "badsecret");
8397 /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8398 * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8399 * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8400 * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8401 * to be plaintext, indicating it is an authmethod used by other peers on the system.
8402 *
8403 * If none of these cases exist, res will be returned as 0 without authentication indicating
8404 * an AUTHREQ needs to be sent out. */
8405
8406 if (ast_strlen_zero(iaxs[callno]->challenge) &&
8407 !(!ast_strlen_zero(secret) && plaintext)) {
8408 /* by setting res to 0, an REGAUTH will be sent */
8409 res = 0;
8410 }
8411 }
8412 if (authdebug && !p)
8413 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8414 goto return_unref;
8415 }
8416
8417 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8418 if (authdebug)
8419 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8420 goto return_unref;
8421 }
8422
8423 if (!ast_apply_acl(p->acl, addr, "IAX2 Peer ACL: ")) {
8424 if (authdebug)
8425 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8426 goto return_unref;
8427 }
8428 ast_string_field_set(iaxs[callno], secret, p->secret);
8429 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8430 /* Check secret against what we have on file */
8431 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8432 if (!ast_strlen_zero(p->inkeys)) {
8433 char *tmpkey;
8434 char *stringp=NULL;
8435 if (!(tmpkey = ast_strdup(p->inkeys))) {
8436 ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8437 goto return_unref;
8438 }
8439 stringp = tmpkey;
8440 keyn = strsep(&stringp, ":");
8441 while(keyn) {
8442 key = ast_key_get(keyn, AST_KEY_PUBLIC);
8443 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8444 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8445 break;
8446 } else if (!key)
8447 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8448 keyn = strsep(&stringp, ":");
8449 }
8450 ast_free(tmpkey);
8451 if (!keyn) {
8452 if (authdebug)
8453 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8454 goto return_unref;
8455 }
8456 } else {
8457 if (authdebug)
8458 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8459 goto return_unref;
8460 }
8461 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8462 struct MD5Context md5;
8463 unsigned char digest[16];
8464 char *tmppw, *stringp;
8465
8466 tmppw = ast_strdupa(p->secret);
8467 stringp = tmppw;
8468 while((tmppw = strsep(&stringp, ";"))) {
8469 MD5Init(&md5);
8470 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8471 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8472 MD5Final(digest, &md5);
8473 for (x=0;x<16;x++)
8474 sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8475 if (!strcasecmp(requeststr, md5secret))
8476 break;
8477 }
8478 if (tmppw) {
8479 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8480 } else {
8481 if (authdebug)
8482 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_sockaddr_stringify_addr(addr), p->name, requeststr, md5secret);
8483 goto return_unref;
8484 }
8485 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8486 /* They've provided a plain text password and we support that */
8487 if (strcmp(secret, p->secret)) {
8488 if (authdebug)
8489 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8490 goto return_unref;
8491 } else
8492 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8493 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8494 /* if challenge has been sent, but no challenge response if given, reject. */
8495 goto return_unref;
8496 }
8497 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8498
8499 /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8500 res = 0;
8501
8502 return_unref:
8503 if (iaxs[callno]) {
8504 ast_string_field_set(iaxs[callno], peer, peer);
8505
8506 /* Choose lowest expiry number */
8507 if (expire && (expire < iaxs[callno]->expiry)) {
8508 iaxs[callno]->expiry = expire;
8509 }
8510 }
8511
8512 if (p) {
8513 peer_unref(p);
8514 }
8515 return res;
8516 }
8517
8518 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)
8519 {
8520 int res = -1;
8521 int x;
8522 if (!ast_strlen_zero(keyn)) {
8523 if (!(authmethods & IAX_AUTH_RSA)) {
8524 if (ast_strlen_zero(secret)) {
8525 ast_log(LOG_WARNING, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_sockaddr_stringify_addr(addr));
8526 }
8527 } else if (ast_strlen_zero(challenge)) {
8528 ast_log(LOG_WARNING, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8529 } else {
8530 char sig[256];
8531 struct ast_key *key;
8532 key = ast_key_get(keyn, AST_KEY_PRIVATE);
8533 if (!key) {
8534 ast_log(LOG_WARNING, "Unable to find private key '%s'\n", keyn);
8535 } else {
8536 if (ast_sign(key, (char*)challenge, sig)) {
8537 ast_log(LOG_WARNING, "Unable to sign challenge with key\n");
8538 res = -1;
8539 } else {
8540 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
8541 if (pvt) {
8542 pvt->eff_auth_method = IAX_AUTH_RSA;
8543 }
8544 res = 0;
8545 }
8546 }
8547
8548 if (pvt && !ast_strlen_zero(secret)) {
8549 struct MD5Context md5;
8550 unsigned char digest[16];
8551
8552 MD5Init(&md5);
8553 MD5Update(&md5, (unsigned char *) challenge, strlen(challenge));
8554 MD5Update(&md5, (unsigned char *) secret, strlen(secret));
8555 MD5Final(digest, &md5);
8556
8557 build_encryption_keys(digest, pvt);
8558 }
8559 }
8560 }
8561 /* Fall back */
8562 if (res && !ast_strlen_zero(secret)) {
8563 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8564 struct MD5Context md5;
8565 unsigned char digest[16];
8566 char digres[128];
8567 MD5Init(&md5);
8568 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8569 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8570 MD5Final(digest, &md5);
8571 /* If they support md5, authenticate with it. */
8572 for (x=0;x<16;x++)
8573 sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8574 if (pvt) {
8575 build_encryption_keys(digest, pvt);
8576 pvt->eff_auth_method = IAX_AUTH_MD5;
8577 }
8578 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
8579 res = 0;
8580 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8581 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8582 if (pvt) {
8583 pvt->eff_auth_method = IAX_AUTH_PLAINTEXT;
8584 }
8585 res = 0;
8586 } else
8587 ast_log(LOG_WARNING, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8588 }
8589 return res;
8590 }
8591
8592 /*!
8593 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8594 * so do not call this function with a pvt lock held.
8595 */
8596 static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
8597 {
8598 struct iax2_peer *peer = NULL;
8599 /* Start pessimistic */
8600 int res = -1;
8601 int authmethods = 0;
8602 struct iax_ie_data ied;
8603 uint16_t callno = p->callno;
8604
8605 memset(&ied, 0, sizeof(ied));
8606
8607 if (ies->username)
8608 ast_string_field_set(p, username, ies->username);
8609 if (ies->challenge)
8610 ast_string_field_set(p, challenge, ies->challenge);
8611 if (ies->authmethods)
8612 authmethods = ies->authmethods;
8613 if (authmethods & IAX_AUTH_MD5)
8614 merge_encryption(p, ies->encmethods);
8615 else
8616 p->encmethods = 0;
8617
8618 /* Check for override RSA authentication first */
8619 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8620 /* Normal password authentication */
8621 res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8622 } else {
8623 struct ao2_iterator i = ao2_iterator_init(peers, 0);
8624 while ((peer = ao2_iterator_next(&i))) {
8625 struct ast_sockaddr peer_addr;
8626 struct ast_sockaddr tmp_sockaddr1;
8627 struct ast_sockaddr tmp_sockaddr2;
8628
8629 ast_sockaddr_copy(&peer_addr, &peer->addr);
8630
8631 ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8632 ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8633
8634 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8635 /* No peer specified at our end, or this is the peer */
8636 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8637 /* No username specified in peer rule, or this is the right username */
8638 && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8639 /* No specified host, or this is our host */
8640 ) {
8641 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8642 if (!res) {
8643 peer_unref(peer);
8644 break;
8645 }
8646 }
8647 peer_unref(peer);
8648 }
8649 ao2_iterator_destroy(&i);
8650 if (!peer) {
8651 /* We checked our list and didn't find one. It's unlikely, but possible,
8652 that we're trying to authenticate *to* a realtime peer */
8653 const char *peer_name = ast_strdupa(p->peer);
8654 ast_mutex_unlock(&iaxsl[callno]);
8655 if ((peer = realtime_peer(peer_name, NULL))) {
8656 ast_mutex_lock(&iaxsl[callno]);
8657 if (!(p = iaxs[callno])) {
8658 peer_unref(peer);
8659 return -1;
8660 }
8661 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8662 peer_unref(peer);
8663 }
8664 if (!peer) {
8665 ast_mutex_lock(&iaxsl[callno]);
8666 if (!(p = iaxs[callno]))
8667 return -1;
8668 }
8669 }
8670 }
8671
8672 if (!(ies->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT)) && (ies->authmethods & IAX_AUTH_RSA) && ast_strlen_zero(okey)) {
8673 /* If the only thing available is RSA, and we don't have an outkey, we can't do it... */
8674 ast_log(LOG_WARNING, "Call terminated. RSA authentication requires an outkey\n");
8675 return -1;
8676 }
8677
8678 if (ies->encmethods) {
8679 if (ast_strlen_zero(p->secret) &&
8680 ((ies->authmethods & IAX_AUTH_RSA) || (ies->authmethods & IAX_AUTH_MD5) || (ies->authmethods & IAX_AUTH_PLAINTEXT))) {
8681 ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8682 return -1;
8683 }
8684 /* Don't even THINK about trying to encrypt or decrypt anything if we don't have valid keys, for some reason... */
8685 /* If either of these happens, it's our fault, not the user's. But we should abort rather than crash. */
8686 ast_assert_return(!invalid_key(&p->ecx), -1);
8687 ast_assert_return(!invalid_key(&p->dcx), -1);
8688 ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
8689 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8690 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8691 return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8692 }
8693 if (!res) {
8694 struct ast_datastore *variablestore;
8695 struct ast_variable *var, *prev = NULL;
8696 AST_LIST_HEAD(, ast_var_t) *varlist;
8697 varlist = ast_calloc(1, sizeof(*varlist));
8698 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
8699 if (variablestore && varlist && p->owner) {
8700 variablestore->data = varlist;
8701 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8702 AST_LIST_HEAD_INIT(varlist);
8703 for (var = ies->vars; var; var = var->next) {
8704 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8705 if (prev)
8706 ast_free(prev);
8707 prev = var;
8708 if (!newvar) {
8709 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8710 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8711 } else {
8712 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8713 }
8714 }
8715 if (prev)
8716 ast_free(prev);
8717 ies->vars = NULL;
8718 ast_channel_datastore_add(p->owner, variablestore);
8719 } else {
8720 if (p->owner)
8721 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8722 if (variablestore)
8723 ast_datastore_free(variablestore);
8724 if (varlist)
8725 ast_free(varlist);
8726 }
8727 }
8728
8729 if (!res)
8730 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8731 return res;
8732 }
8733
8734 static int iax2_do_register(struct iax2_registry *reg);
8735
8736 static void __iax2_do_register_s(const void *data)
8737 {
8738 struct iax2_registry *reg = (struct iax2_registry *)data;
8739
8740 if (ast_sockaddr_isnull(&reg->addr)) {
8741 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8742 ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8743 if (!ast_sockaddr_port(&reg->addr)) {
8744 ast_sockaddr_set_port(&reg->addr, reg->port);
8745 } else {
8746 reg->port = ast_sockaddr_port(&reg->addr);
8747 }
8748 }
8749
8750 reg->expire = -1;
8751 iax2_do_register(reg);
8752 }
8753
8754 static int iax2_do_register_s(const void *data)
8755 {
8756 #ifdef SCHED_MULTITHREADED
8757 if (schedule_action(__iax2_do_register_s, data))
8758 #endif
8759 __iax2_do_register_s(data);
8760 return 0;
8761 }
8762
8763 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8764 {
8765 int newcall = 0;
8766 struct iax_ie_data ied;
8767 struct ast_sockaddr new = { {0,} };
8768
8769 memset(&ied, 0, sizeof(ied));
8770 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8771 ast_sockaddr_copy(&new, &ies->apparent_addr);
8772 }
8773 if (ies->callno) {
8774 newcall = ies->callno;
8775 }
8776 if (!newcall || ast_sockaddr_isnull(&new)) {
8777 ast_log(LOG_WARNING, "Invalid transfer request\n");
8778 return -1;
8779 }
8780 pvt->transfercallno = newcall;
8781 ast_sockaddr_copy(&pvt->transfer, &new);
8782 pvt->transferid = ies->transferid;
8783 /* only store by transfercallno if this is a new transfer,
8784 * just in case we get a duplicate TXREQ */
8785 if (pvt->transferring == TRANSFER_NONE) {
8786 store_by_transfercallno(pvt);
8787 }
8788 pvt->transferring = TRANSFER_BEGIN;
8789
8790 if (ies->transferid) {
8791 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
8792 }
8793 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
8794 return 0;
8795 }
8796
8797 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8798 {
8799 char exten[256] = "";
8800 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8801 struct iax2_dpcache *dp = NULL;
8802
8803 if (ies->called_number)
8804 ast_copy_string(exten, ies->called_number, sizeof(exten));
8805
8806 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8807 status = CACHE_FLAG_EXISTS;
8808 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8809 status = CACHE_FLAG_CANEXIST;
8810 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8811 status = CACHE_FLAG_NONEXISTENT;
8812
8813 if (ies->refresh)
8814 expiry = ies->refresh;
8815 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
8816 matchmore = CACHE_FLAG_MATCHMORE;
8817
8818 AST_LIST_LOCK(&dpcache);
8819 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
8820 if (strcmp(dp->exten, exten))
8821 continue;
8822 AST_LIST_REMOVE_CURRENT(peer_list);
8823 dp->callno = 0;
8824 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8825 if (dp->flags & CACHE_FLAG_PENDING) {
8826 dp->flags &= ~CACHE_FLAG_PENDING;
8827 dp->flags |= status;
8828 dp->flags |= matchmore;
8829 }
8830 /* Wake up waiters */
8831 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8832 if (dp->waiters[x] > -1) {
8833 if (write(dp->waiters[x], "asdf", 4) < 0) {
8834 }
8835 }
8836 }
8837 }
8838 AST_LIST_TRAVERSE_SAFE_END;
8839 AST_LIST_UNLOCK(&dpcache);
8840
8841 return 0;
8842 }
8843
8844 static int complete_transfer(int callno, struct iax_ies *ies)
8845 {
8846 int peercallno = 0;
8847 struct chan_iax2_pvt *pvt = iaxs[callno];
8848 struct iax_frame *cur;
8849 jb_frame frame;
8850
8851 if (ies->callno)
8852 peercallno = ies->callno;
8853
8854 if (peercallno < 1) {
8855 ast_log(LOG_WARNING, "Invalid transfer request\n");
8856 return -1;
8857 }
8858 remove_by_transfercallno(pvt);
8859 /* since a transfer has taken place, the address will change.
8860 * This must be accounted for in the peercnts table. Remove
8861 * the old address and add the new one */
8862 peercnt_remove_by_addr(&pvt->addr);
8863 peercnt_add(&pvt->transfer);
8864 /* now copy over the new address */
8865 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8866 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8867 /* Reset sequence numbers */
8868 pvt->oseqno = 0;
8869 pvt->rseqno = 0;
8870 pvt->iseqno = 0;
8871 pvt->aseqno = 0;
8872
8873 if (pvt->peercallno) {
8874 remove_by_peercallno(pvt);
8875 }
8876 pvt->peercallno = peercallno;
8877 /*this is where the transferring call switches hash tables */
8878 store_by_peercallno(pvt);
8879 pvt->transferring = TRANSFER_NONE;
8880 pvt->svoiceformat = -1;
8881 pvt->voiceformat = 0;
8882 pvt->svideoformat = -1;
8883 pvt->videoformat = 0;
8884 pvt->transfercallno = 0;
8885 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8886 memset(&pvt->offset, 0, sizeof(pvt->offset));
8887 /* reset jitterbuffer */
8888 while(jb_getall(pvt->jb,&frame) == JB_OK)
8889 iax2_frame_free(frame.data);
8890 jb_reset(pvt->jb);
8891 pvt->lag = 0;
8892 pvt->last = 0;
8893 pvt->lastsent = 0;
8894 pvt->nextpred = 0;
8895 pvt->pingtime = DEFAULT_RETRY_TIME;
8896 AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
8897 /* We must cancel any packets that would have been transmitted
8898 because now we're talking to someone new. It's okay, they
8899 were transmitted to someone that didn't care anyway. */
8900 cur->retries = -1;
8901 }
8902 return 0;
8903 }
8904
8905 static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
8906 {
8907 ast_system_publish_registry("IAX2", username, domain, status, cause);
8908 }
8909
8910 /*! \brief Acknowledgment received for OUR registration */
8911 static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
8912 {
8913 struct iax2_registry *reg;
8914 /* Start pessimistic */
8915 char peer[256] = "";
8916 char msgstatus[60];
8917 int refresh = 60;
8918 char ourip[256] = "<Unspecified>";
8919 struct ast_sockaddr oldus;
8920 struct ast_sockaddr us;
8921 int oldmsgs;
8922
8923 if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8924 ast_sockaddr_copy(&us, &ies->apparent_addr);
8925 }
8926 if (ies->username) {
8927 ast_copy_string(peer, ies->username, sizeof(peer));
8928 }
8929 if (ies->refresh) {
8930 refresh = ies->refresh;
8931 }
8932 if (ies->calling_number) {
8933 /* We don't do anything with it really, but maybe we should */
8934 }
8935 reg = iaxs[callno]->reg;
8936 if (!reg) {
8937 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8938 return -1;
8939 }
8940 ast_sockaddr_copy(&oldus, &reg->us);
8941 oldmsgs = reg->messages;
8942 if (ast_sockaddr_cmp(&reg->addr, addr)) {
8943 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_sockaddr_stringify(addr));
8944 return -1;
8945 }
8946 ast_sockaddr_copy(&reg->us, &us);
8947 if (ies->msgcount >= 0) {
8948 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8949 }
8950 /* always refresh the registration at the interval requested by the server
8951 we are registering to
8952 */
8953 reg->refresh = refresh;
8954 reg->expire = iax2_sched_replace(reg->expire, sched,
8955 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8956 if (ast_sockaddr_cmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8957
8958 if (reg->messages > 255) {
8959 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8960 } else if (reg->messages > 1) {
8961 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8962 } else if (reg->messages > 0) {
8963 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8964 } else {
8965 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8966 }
8967
8968 snprintf(ourip, sizeof(ourip), "%s", ast_sockaddr_stringify(&reg->us));
8969
8970 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_sockaddr_stringify(addr), ourip, msgstatus);
8971 iax2_publish_registry(reg->username, ast_sockaddr_stringify(addr), "Registered", NULL);
8972 }
8973 reg->regstate = REG_STATE_REGISTERED;
8974 return 0;
8975 }
8976
8977 static int iax2_append_register(const char *hostname, const char *username,
8978 const char *secret, const char *porta)
8979 {
8980 struct iax2_registry *reg;
8981
8982 if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
8983 return -1;
8984 }
8985
8986 reg->addr.ss.ss_family = AST_AF_UNSPEC;
8987 if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8988 ast_free(reg);
8989 return -1;
8990 }
8991
8992 ast_copy_string(reg->username, username, sizeof(reg->username));
8993 strcpy(reg->hostname, hostname); /* Note: This is safe */
8994
8995 if (secret) {
8996 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8997 }
8998
8999 reg->expire = -1;
9000 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
9001
9002 reg->port = ast_sockaddr_port(&reg->addr);
9003
9004 if (!porta && !reg->port) {
9005 reg->port = IAX_DEFAULT_PORTNO;
9006 } else if (porta) {
9007 sscanf(porta, "%5d", &reg->port);
9008 }
9009
9010 ast_sockaddr_set_port(&reg->addr, reg->port);
9011
9012 AST_LIST_LOCK(&registrations);
9013 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
9014 AST_LIST_UNLOCK(&registrations);
9015
9016 return 0;
9017 }
9018
9019 static int iax2_register(const char *value, int lineno)
9020 {
9021 char copy[256];
9022 char *username, *hostname, *secret;
9023 char *porta;
9024 char *stringp=NULL;
9025
9026 if (!value)
9027 return -1;
9028
9029 ast_copy_string(copy, value, sizeof(copy));
9030 stringp = copy;
9031 username = strsep(&stringp, "@");
9032 hostname = strsep(&stringp, "@");
9033
9034 if (!hostname) {
9035 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
9036 return -1;
9037 }
9038
9039 stringp = username;
9040 username = strsep(&stringp, ":");
9041 secret = strsep(&stringp, ":");
9042 stringp = hostname;
9043 hostname = strsep(&stringp, ":");
9044 porta = strsep(&stringp, ":");
9045
9046 if (porta && !atoi(porta)) {
9047 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
9048 return -1;
9049 }
9050
9051 return iax2_append_register(hostname, username, secret, porta);
9052 }
9053
9054
9055 static void register_peer_exten(struct iax2_peer *peer, int onoff)
9056 {
9057 char multi[256];
9058 char *stringp, *ext;
9059 if (!ast_strlen_zero(regcontext)) {
9060 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
9061 stringp = multi;
9062 while((ext = strsep(&stringp, "&"))) {
9063 if (onoff) {
9064 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
9065 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
9066 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
9067 } else
9068 ast_context_remove_extension(regcontext, ext, 1, NULL);
9069 }
9070 }
9071 }
9072 static void prune_peers(void);
9073
9074 static void unlink_peer(struct iax2_peer *peer)
9075 {
9076 if (peer->expire > -1) {
9077 if (!AST_SCHED_DEL(sched, peer->expire)) {
9078 peer->expire = -1;
9079 peer_unref(peer);
9080 }
9081 }
9082
9083 if (peer->pokeexpire > -1) {
9084 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
9085 peer->pokeexpire = -1;
9086 peer_unref(peer);
9087 }
9088 }
9089
9090 ao2_unlink(peers, peer);
9091 }
9092
9093 static void __expire_registry(const void *data)
9094 {
9095 struct iax2_peer *peer = (struct iax2_peer *) data;
9096 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9097
9098 if (!peer)
9099 return;
9100 if (peer->expire == -1) {
9101 /* Removed already (possibly through CLI), ignore */
9102 return;
9103 }
9104
9105 peer->expire = -1;
9106
9107 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
9108 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
9109 realtime_update_peer(peer->name, &peer->addr, 0);
9110 ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
9111 blob = ast_json_pack("{s: s, s: s}",
9112 "peer_status", "Unregistered",
9113 "cause", "Expired");
9114 ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
9115 /* modify entry in peercnts table as _not_ registered */
9116 peercnt_modify((unsigned char) 0, 0, &peer->addr);
9117 /* Reset the address */
9118 ast_sockaddr_setnull(&peer->addr);
9119 /* Reset expiry value */
9120 peer->expiry = min_reg_expire;
9121 if (!ast_test_flag64(peer, IAX_TEMPONLY))
9122 ast_db_del("IAX/Registry", peer->name);
9123 register_peer_exten(peer, 0);
9124 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
9125 if (iax2_regfunk)
9126 iax2_regfunk(peer->name, 0);
9127
9128 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
9129 unlink_peer(peer);
9130
9131 peer_unref(peer);
9132 }
9133
9134 static int expire_registry(const void *data)
9135 {
9136 #ifdef SCHED_MULTITHREADED
9137 if (schedule_action(__expire_registry, data))
9138 #endif
9139 __expire_registry(data);
9140 return 0;
9141 }
9142
9143 static void reg_source_db(struct iax2_peer *p)
9144 {
9145 char data[80];
9146 char *expiry;
9147
9148 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
9149 return;
9150 }
9151
9152 expiry = strrchr(data, ':');
9153 if (!expiry) {
9154 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
9155 return;
9156 }
9157 *expiry++ = '\0';
9158
9159 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
9160 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
9161 return;
9162 }
9163
9164 p->expiry = atoi(expiry);
9165
9166 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
9167 ast_sockaddr_stringify(&p->addr), p->expiry);
9168
9169 iax2_poke_peer(p, 0);
9170 if (p->expire > -1) {
9171 if (!AST_SCHED_DEL(sched, p->expire)) {
9172 p->expire = -1;
9173 peer_unref(p);
9174 }
9175 }
9176
9177 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9178
9179 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9180 if (p->expire == -1) {
9181 peer_unref(p);
9182 }
9183
9184 if (iax2_regfunk) {
9185 iax2_regfunk(p->name, 1);
9186 }
9187
9188 register_peer_exten(p, 1);
9189 }
9190
9191 /*!
9192 * \pre iaxsl[callno] is locked
9193 *
9194 * \note Since this function calls send_command_final(), the pvt struct for
9195 * the given call number may disappear while executing this function.
9196 */
9197 static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
9198 {
9199
9200 /* Called from IAX thread only, with proper iaxsl lock */
9201 struct iax_ie_data ied = {
9202 .pos = 0,
9203 };
9204 struct iax2_peer *p;
9205 int msgcount;
9206 char data[80];
9207 uint16_t version;
9208 const char *peer_name;
9209 int res = -1;
9210 char *str_addr;
9211
9212 peer_name = ast_strdupa(iaxs[callno]->peer);
9213
9214 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
9215 ast_mutex_unlock(&iaxsl[callno]);
9216 if (!(p = find_peer(peer_name, 1))) {
9217 ast_mutex_lock(&iaxsl[callno]);
9218 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
9219 return -1;
9220 }
9221 ast_mutex_lock(&iaxsl[callno]);
9222 if (!iaxs[callno])
9223 goto return_unref;
9224
9225 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
9226 if (!ast_sockaddr_isnull(addr)) {
9227 time_t nowtime;
9228 time(&nowtime);
9229 realtime_update_peer(peer_name, addr, nowtime);
9230 } else {
9231 realtime_update_peer(peer_name, addr, 0);
9232 }
9233 }
9234
9235 /* treat an unspecified refresh interval as the minimum */
9236 if (!refresh) {
9237 refresh = min_reg_expire;
9238 }
9239 if (refresh > max_reg_expire) {
9240 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9241 p->name, max_reg_expire, refresh);
9242 p->expiry = max_reg_expire;
9243 } else if (refresh < min_reg_expire) {
9244 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9245 p->name, min_reg_expire, refresh);
9246 p->expiry = min_reg_expire;
9247 } else {
9248 p->expiry = refresh;
9249 }
9250
9251 if (ast_sockaddr_cmp(&p->addr, addr)) {
9252 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9253
9254 if (iax2_regfunk) {
9255 iax2_regfunk(p->name, 1);
9256 }
9257
9258 /* modify entry in peercnts table as _not_ registered */
9259 peercnt_modify((unsigned char) 0, 0, &p->addr);
9260
9261 /* Stash the IP address from which they registered */
9262 ast_sockaddr_copy(&p->addr, addr);
9263
9264 str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
9265
9266 snprintf(data, sizeof(data), "%s:%d", ast_sockaddr_stringify(addr), p->expiry);
9267
9268 if (!ast_test_flag64(p, IAX_TEMPONLY) && !ast_sockaddr_isnull(addr)) {
9269 ast_db_put("IAX/Registry", p->name, data);
9270 ast_verb(3, "Registered IAX2 '%s' (%s) at %s\n",
9271 p->name,
9272 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED",
9273 ast_sockaddr_stringify(addr));
9274 ast_endpoint_set_state(p->endpoint, AST_ENDPOINT_ONLINE);
9275 blob = ast_json_pack("{s: s, s: s, s: i}",
9276 "peer_status", "Registered",
9277 "address", str_addr,
9278 "port", ast_sockaddr_port(addr));
9279 register_peer_exten(p, 1);
9280 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9281 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
9282 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n",
9283 p->name,
9284 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
9285 ast_endpoint_set_state(p->endpoint, AST_ENDPOINT_OFFLINE);
9286 blob = ast_json_pack("{s: s}",
9287 "peer_status", "Unregistered");
9288 register_peer_exten(p, 0);
9289 ast_db_del("IAX/Registry", p->name);
9290 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9291 }
9292
9293 ast_endpoint_blob_publish(p->endpoint, ast_endpoint_state_type(), blob);
9294
9295 /* Update the host */
9296 /* Verify that the host is really there */
9297 iax2_poke_peer(p, callno);
9298 }
9299
9300 /* modify entry in peercnts table as registered */
9301 if (p->maxcallno) {
9302 peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
9303 }
9304
9305 /* Make sure our call still exists, an INVAL at the right point may make it go away */
9306 if (!iaxs[callno]) {
9307 res = -1;
9308 goto return_unref;
9309 }
9310
9311 /* Store socket fd */
9312 p->sockfd = fd;
9313 /* Setup the expiry */
9314 if (p->expire > -1) {
9315 if (!AST_SCHED_DEL(sched, p->expire)) {
9316 p->expire = -1;
9317 peer_unref(p);
9318 }
9319 }
9320
9321 if (p->expiry && !ast_sockaddr_isnull(addr)) {
9322 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9323 if (p->expire == -1)
9324 peer_unref(p);
9325 }
9326 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
9327 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
9328 if (!ast_sockaddr_isnull(addr)) {
9329 struct ast_sockaddr peer_addr;
9330
9331 ast_sockaddr_copy(&peer_addr, &p->addr);
9332
9333 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
9334 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
9335 if (!ast_strlen_zero(p->mailbox)) {
9336 int new, old;
9337 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
9338
9339 msg = stasis_cache_get(ast_mwi_state_cache(), ast_mwi_state_type(), p->mailbox);
9340 if (msg) {
9341 struct ast_mwi_state *mwi_state = stasis_message_data(msg);
9342 new = mwi_state->new_msgs;
9343 old = mwi_state->old_msgs;
9344 } else { /* Fall back on checking the mailbox directly */
9345 ast_app_inboxcount(p->mailbox, &new, &old);
9346 }
9347
9348 if (new > 255) {
9349 new = 255;
9350 }
9351 if (old > 255) {
9352 old = 255;
9353 }
9354 msgcount = (old << 8) | new;
9355
9356 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
9357 }
9358 if (ast_test_flag64(p, IAX_HASCALLERID)) {
9359 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
9360 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
9361 }
9362 }
9363 if (iax_firmware_get_version(devtype, &version)) {
9364 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
9365 }
9366
9367 res = 0;
9368
9369 return_unref:
9370 peer_unref(p);
9371
9372 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9373 }
9374
9375 static int registry_authrequest(int callno)
9376 {
9377 struct iax_ie_data ied;
9378 struct iax2_peer *p;
9379 char challenge[10];
9380 const char *peer_name;
9381 int sentauthmethod;
9382
9383 peer_name = ast_strdupa(iaxs[callno]->peer);
9384
9385 /* SLD: third call to find_peer in registration */
9386 ast_mutex_unlock(&iaxsl[callno]);
9387 if ((p = find_peer(peer_name, 1))) {
9388 last_authmethod = p->authmethods;
9389 }
9390
9391 ast_mutex_lock(&iaxsl[callno]);
9392 if (!iaxs[callno])
9393 goto return_unref;
9394
9395 memset(&ied, 0, sizeof(ied));
9396 /* The selection of which delayed reject is sent may leak information,
9397 * if it sets a static response. For example, if a host is known to only
9398 * use MD5 authentication, then an RSA response would indicate that the
9399 * peer does not exist, and vice-versa.
9400 * Therefore, we use whatever the last peer used (which may vary over the
9401 * course of a server, which should leak minimal information). */
9402 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : IAX_AUTH_MD5;
9403 if (!p) {
9404 iaxs[callno]->authmethods = sentauthmethod;
9405 }
9406 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9407 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9408 /* Build the challenge */
9409 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9410 ast_string_field_set(iaxs[callno], challenge, challenge);
9411 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
9412 }
9413 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9414
9415 return_unref:
9416 if (p) {
9417 peer_unref(p);
9418 }
9419
9420 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9421 }
9422
9423 static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
9424 {
9425 struct iax2_registry *reg;
9426 /* Start pessimistic */
9427 struct iax_ie_data ied;
9428 char peer[256] = "";
9429 char challenge[256] = "";
9430 int res;
9431 int authmethods = 0;
9432 if (ies->authmethods)
9433 authmethods = ies->authmethods;
9434 if (ies->username)
9435 ast_copy_string(peer, ies->username, sizeof(peer));
9436 if (ies->challenge)
9437 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
9438 memset(&ied, 0, sizeof(ied));
9439 reg = iaxs[callno]->reg;
9440 if (reg) {
9441
9442 if (ast_sockaddr_cmp(&reg->addr, addr)) {
9443 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_sockaddr_stringify(addr));
9444 return -1;
9445 }
9446 if (ast_strlen_zero(reg->secret)) {
9447 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9448 reg->regstate = REG_STATE_NOAUTH;
9449 return -1;
9450 }
9451 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
9452 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
9453 if (reg->secret[0] == '[') {
9454 char tmpkey[256];
9455 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9456 tmpkey[strlen(tmpkey) - 1] = '\0';
9457 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, addr, NULL);
9458 } else
9459 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, addr, NULL);
9460 if (!res) {
9461 reg->regstate = REG_STATE_AUTHSENT;
9462 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9463 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9464 } else
9465 return -1;
9466 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
9467 } else
9468 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9469 return -1;
9470 }
9471
9472 static void stop_stuff(int callno)
9473 {
9474 iax2_destroy_helper(iaxs[callno]);
9475 }
9476
9477 static void __auth_reject(const void *nothing)
9478 {
9479 /* Called from IAX thread only, without iaxs lock */
9480 int callno = (int)(long)(nothing);
9481 struct iax_ie_data ied;
9482 ast_mutex_lock(&iaxsl[callno]);
9483 if (iaxs[callno]) {
9484 memset(&ied, 0, sizeof(ied));
9485 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9486 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9487 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
9488 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9489 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9490 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
9491 }
9492 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9493 }
9494 ast_mutex_unlock(&iaxsl[callno]);
9495 }
9496
9497 static int auth_reject(const void *data)
9498 {
9499 int callno = (int)(long)(data);
9500 ast_mutex_lock(&iaxsl[callno]);
9501 if (iaxs[callno])
9502 iaxs[callno]->authid = -1;
9503 ast_mutex_unlock(&iaxsl[callno]);
9504 #ifdef SCHED_MULTITHREADED
9505 if (schedule_action(__auth_reject, data))
9506 #endif
9507 __auth_reject(data);
9508 return 0;
9509 }
9510
9511 static int auth_fail(int callno, int failcode)
9512 {
9513 /* Schedule sending the authentication failure in one second, to prevent
9514 guessing */
9515 if (iaxs[callno]) {
9516 iaxs[callno]->authfail = failcode;
9517 if (delayreject) {
9518 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9519 sched, 1000, auth_reject, (void *)(long)callno);
9520 } else
9521 auth_reject((void *)(long)callno);
9522 }
9523 return 0;
9524 }
9525
9526 static void __auto_hangup(const void *nothing)
9527 {
9528 /* Called from IAX thread only, without iaxs lock */
9529 int callno = (int)(long)(nothing);
9530 struct iax_ie_data ied;
9531 ast_mutex_lock(&iaxsl[callno]);
9532 if (iaxs[callno]) {
9533 memset(&ied, 0, sizeof(ied));
9534 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9535 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
9536 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9537 }
9538 ast_mutex_unlock(&iaxsl[callno]);
9539 }
9540
9541 static int auto_hangup(const void *data)
9542 {
9543 int callno = (int)(long)(data);
9544 ast_mutex_lock(&iaxsl[callno]);
9545 if (iaxs[callno]) {
9546 iaxs[callno]->autoid = -1;
9547 }
9548 ast_mutex_unlock(&iaxsl[callno]);
9549 #ifdef SCHED_MULTITHREADED
9550 if (schedule_action(__auto_hangup, data))
9551 #endif
9552 __auto_hangup(data);
9553 return 0;
9554 }
9555
9556 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9557 {
9558 struct iax_ie_data ied;
9559 /* Auto-hangup with 30 seconds of inactivity */
9560 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9561 sched, 30000, auto_hangup, (void *)(long)callno);
9562 memset(&ied, 0, sizeof(ied));
9563 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
9564 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9565 dp->flags |= CACHE_FLAG_TRANSMITTED;
9566 }
9567
9568 static int iax2_vnak(int callno)
9569 {
9570 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9571 }
9572
9573 static void vnak_retransmit(int callno, int last)
9574 {
9575 struct iax_frame *f;
9576
9577 AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
9578 /* Send a copy immediately */
9579 if (((unsigned char) (f->oseqno - last) < 128) &&
9580 (f->retries >= 0)) {
9581 send_packet(f);
9582 }
9583 }
9584 }
9585
9586 static void __iax2_poke_peer_s(const void *data)
9587 {
9588 struct iax2_peer *peer = (struct iax2_peer *)data;
9589 iax2_poke_peer(peer, 0);
9590 peer_unref(peer);
9591 }
9592
9593 static int iax2_poke_peer_s(const void *data)
9594 {
9595 struct iax2_peer *peer = (struct iax2_peer *)data;
9596 peer->pokeexpire = -1;
9597 #ifdef SCHED_MULTITHREADED
9598 if (schedule_action(__iax2_poke_peer_s, data))
9599 #endif
9600 __iax2_poke_peer_s(data);
9601 return 0;
9602 }
9603
9604 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9605 {
9606 int res = 0;
9607 struct iax_frame *fr;
9608 struct ast_iax2_meta_hdr *meta;
9609 struct ast_iax2_meta_trunk_hdr *mth;
9610 int calls = 0;
9611
9612 /* Point to frame */
9613 fr = (struct iax_frame *)tpeer->trunkdata;
9614 /* Point to meta data */
9615 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9616 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9617 if (tpeer->trunkdatalen) {
9618 /* We're actually sending a frame, so fill the meta trunk header and meta header */
9619 meta->zeros = 0;
9620 meta->metacmd = IAX_META_TRUNK;
9621 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
9622 meta->cmddata = IAX_META_TRUNK_MINI;
9623 else
9624 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
9625 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9626 /* And the rest of the ast_iax2 header */
9627 fr->direction = DIRECTION_OUTGRESS;
9628 fr->retrans = -1;
9629 fr->transfer = 0;
9630 /* Any appropriate call will do */
9631 fr->data = fr->afdata;
9632 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9633 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9634 calls = tpeer->calls;
9635 #if 0
9636 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
9637 #endif
9638 /* Reset transmit trunk side data */
9639 tpeer->trunkdatalen = 0;
9640 tpeer->calls = 0;
9641 }
9642 if (res < 0)
9643 return res;
9644 return calls;
9645 }
9646
9647 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9648 {
9649 /* Drop when trunk is about 5 seconds idle */
9650 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9651 return 1;
9652 return 0;
9653 }
9654
9655 static int timing_read(int *id, int fd, short events, void *cbdata)
9656 {
9657 int res, processed = 0, totalcalls = 0;
9658 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9659 struct timeval now = ast_tvnow();
9660
9661 if (iaxtrunkdebug) {
9662 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9663 }
9664
9665 if (timer) {
9666 if (ast_timer_ack(timer, 1) < 0) {
9667 ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9668 return 0;
9669 }
9670 }
9671
9672 /* For each peer that supports trunking... */
9673 AST_LIST_LOCK(&tpeers);
9674 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9675 processed++;
9676 res = 0;
9677 ast_mutex_lock(&tpeer->lock);
9678 /* We can drop a single tpeer per pass. That makes all this logic
9679 substantially easier */
9680 if (!drop && iax2_trunk_expired(tpeer, &now)) {
9681 /* Take it out of the list, but don't free it yet, because it
9682 could be in use */
9683 AST_LIST_REMOVE_CURRENT(list);
9684 drop = tpeer;
9685 } else {
9686 res = send_trunk(tpeer, &now);
9687 trunk_timed++;
9688 if (iaxtrunkdebug) {
9689 ast_verbose(" - Trunk peer (%s) has %d call chunk%s in transit, %u bytes backlogged and has hit a high water mark of %u bytes\n",
9690 ast_sockaddr_stringify(&tpeer->addr),
9691 res,
9692 (res != 1) ? "s" : "",
9693 tpeer->trunkdatalen,
9694 tpeer->trunkdataalloc);
9695 }
9696 }
9697 totalcalls += res;
9698 res = 0;
9699 ast_mutex_unlock(&tpeer->lock);
9700 }
9701 AST_LIST_TRAVERSE_SAFE_END;
9702 AST_LIST_UNLOCK(&tpeers);
9703
9704 if (drop) {
9705 ast_mutex_lock(&drop->lock);
9706 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9707 because by the time they could get tpeerlock, we've already grabbed it */
9708 ast_debug(1, "Dropping unused iax2 trunk peer '%s'\n", ast_sockaddr_stringify(&drop->addr));
9709 if (drop->trunkdata) {
9710 ast_free(drop->trunkdata);
9711 drop->trunkdata = NULL;
9712 }
9713 ast_mutex_unlock(&drop->lock);
9714 ast_mutex_destroy(&drop->lock);
9715 ast_free(drop);
9716 }
9717
9718 if (iaxtrunkdebug) {
9719 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9720 }
9721 iaxtrunkdebug = 0;
9722
9723 return 1;
9724 }
9725
9726 struct dpreq_data {
9727 int callno;
9728 char context[AST_MAX_EXTENSION];
9729 char callednum[AST_MAX_EXTENSION];
9730 char *callerid;
9731 };
9732
9733 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9734 {
9735 unsigned short dpstatus = 0;
9736 struct iax_ie_data ied1;
9737 int mm;
9738
9739 memset(&ied1, 0, sizeof(ied1));
9740 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9741 /* Must be started */
9742 if (ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9743 dpstatus = IAX_DPSTATUS_EXISTS;
9744 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9745 dpstatus = IAX_DPSTATUS_CANEXIST;
9746 } else {
9747 dpstatus = IAX_DPSTATUS_NONEXISTENT;
9748 }
9749 if (ast_ignore_pattern(context, callednum))
9750 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9751 if (mm)
9752 dpstatus |= IAX_DPSTATUS_MATCHMORE;
9753 if (!skiplock)
9754 ast_mutex_lock(&iaxsl[callno]);
9755 if (iaxs[callno]) {
9756 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9757 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9758 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
9759 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9760 }
9761 if (!skiplock)
9762 ast_mutex_unlock(&iaxsl[callno]);
9763 }
9764
9765 static void *dp_lookup_thread(void *data)
9766 {
9767 /* Look up for dpreq */
9768 struct dpreq_data *dpr = data;
9769 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9770 if (dpr->callerid)
9771 ast_free(dpr->callerid);
9772 ast_free(dpr);
9773 return NULL;
9774 }
9775
9776 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9777 {
9778 pthread_t newthread;
9779 struct dpreq_data *dpr;
9780
9781 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9782 return;
9783
9784 dpr->callno = callno;
9785 ast_copy_string(dpr->context, context, sizeof(dpr->context));
9786 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9787 if (callerid)
9788 dpr->callerid = ast_strdup(callerid);
9789 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9790 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9791 }
9792 }
9793
9794 static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
9795 {
9796 unsigned int ourver;
9797 char rsi[80];
9798 snprintf(rsi, sizeof(rsi), "si-%s", si);
9799 if (iax_provision_version(&ourver, rsi, 1))
9800 return 0;
9801 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9802 if (ourver != ver)
9803 iax2_provision(addr, sockfd, NULL, rsi, 1);
9804 return 0;
9805 }
9806
9807 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9808 {
9809 jb_info stats;
9810 jb_getinfo(pvt->jb, &stats);
9811
9812 memset(iep, 0, sizeof(*iep));
9813
9814 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
9815 if(stats.frames_in == 0) stats.frames_in = 1;
9816 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9817 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
9818 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9819 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
9820 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
9821 }
9822
9823 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9824 {
9825 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9826 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9827 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9828 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9829 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9830 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9831 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9832 }
9833
9834 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9835 {
9836 int i;
9837 unsigned int length, offset = 0;
9838 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9839
9840 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9841 length = ies->ospblocklength[i];
9842 if (length != 0) {
9843 if (length > IAX_MAX_OSPBLOCK_SIZE) {
9844 /* OSP token block length wrong, clear buffer */
9845 offset = 0;
9846 break;
9847 } else {
9848 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9849 offset += length;
9850 }
9851 } else {
9852 break;
9853 }
9854 }
9855 *(full_osptoken + offset) = '\0';
9856 if (strlen(full_osptoken) != offset) {
9857 /* OSP token length wrong, clear buffer */
9858 *full_osptoken = '\0';
9859 }
9860
9861 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9862 }
9863
9864 static void log_jitterstats(unsigned short callno)
9865 {
9866 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9867 jb_info jbinfo;
9868
9869 ast_mutex_lock(&iaxsl[callno]);
9870 if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
9871 if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
9872 jb_getinfo(iaxs[callno]->jb, &jbinfo);
9873 localjitter = jbinfo.jitter;
9874 localdelay = jbinfo.current - jbinfo.min;
9875 locallost = jbinfo.frames_lost;
9876 locallosspct = jbinfo.losspct/1000;
9877 localdropped = jbinfo.frames_dropped;
9878 localooo = jbinfo.frames_ooo;
9879 localpackets = jbinfo.frames_in;
9880 }
9881 ast_debug(3, "JB STATS:%s ping=%u ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
9882 ast_channel_name(iaxs[callno]->owner),
9883 iaxs[callno]->pingtime,
9884 localjitter,
9885 localdelay,
9886 locallost,
9887 locallosspct,
9888 localdropped,
9889 localooo,
9890 localpackets,
9891 iaxs[callno]->remote_rr.jitter,
9892 iaxs[callno]->remote_rr.delay,
9893 iaxs[callno]->remote_rr.losscnt,
9894 iaxs[callno]->remote_rr.losspct/1000,
9895 iaxs[callno]->remote_rr.dropped,
9896 iaxs[callno]->remote_rr.ooo,
9897 iaxs[callno]->remote_rr.packets);
9898 }
9899 ast_mutex_unlock(&iaxsl[callno]);
9900 }
9901
9902 static int socket_process(struct iax2_thread *thread);
9903
9904 /*!
9905 * \brief Handle any deferred full frames for this thread
9906 */
9907 static void handle_deferred_full_frames(struct iax2_thread *thread)
9908 {
9909 struct iax2_pkt_buf *pkt_buf;
9910
9911 ast_mutex_lock(&thread->lock);
9912
9913 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9914 ast_mutex_unlock(&thread->lock);
9915
9916 thread->buf = pkt_buf->buf;
9917 thread->buf_len = pkt_buf->len;
9918 thread->buf_size = pkt_buf->len + 1;
9919
9920 socket_process(thread);
9921
9922 thread->buf = NULL;
9923 ast_free(pkt_buf);
9924
9925 ast_mutex_lock(&thread->lock);
9926 }
9927
9928 ast_mutex_unlock(&thread->lock);
9929 }
9930
9931 /*!
9932 * \brief Queue the last read full frame for processing by a certain thread
9933 *
9934 * If there are already any full frames queued, they are sorted
9935 * by sequence number.
9936 */
9937 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9938 {
9939 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9940 struct ast_iax2_full_hdr *fh, *cur_fh;
9941
9942 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9943 return;
9944
9945 pkt_buf->len = from_here->buf_len;
9946 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9947
9948 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9949 ast_mutex_lock(&to_here->lock);
9950 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9951 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9952 if (fh->oseqno < cur_fh->oseqno) {
9953 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9954 break;
9955 }
9956 }
9957 AST_LIST_TRAVERSE_SAFE_END
9958
9959 if (!cur_pkt_buf)
9960 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9961
9962 to_here->iostate = IAX_IOSTATE_READY;
9963 ast_cond_signal(&to_here->cond);
9964
9965 ast_mutex_unlock(&to_here->lock);
9966 }
9967
9968 static int socket_read(int *id, int fd, short events, void *cbdata)
9969 {
9970 struct iax2_thread *thread;
9971 time_t t;
9972 static time_t last_errtime = 0;
9973 struct ast_iax2_full_hdr *fh;
9974
9975 if (!(thread = find_idle_thread())) {
9976 time(&t);
9977 if (t != last_errtime) {
9978 last_errtime = t;
9979 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9980 }
9981 usleep(1);
9982 return 1;
9983 }
9984
9985 thread->iofd = fd;
9986 thread->buf_len = ast_recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, &thread->ioaddr);
9987 thread->buf_size = sizeof(thread->readbuf);
9988 thread->buf = thread->readbuf;
9989 if (thread->buf_len < 0) {
9990 if (errno != ECONNREFUSED && errno != EAGAIN)
9991 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9992 handle_error();
9993 thread->iostate = IAX_IOSTATE_IDLE;
9994 signal_condition(&thread->lock, &thread->cond);
9995 return 1;
9996 }
9997 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9998 thread->iostate = IAX_IOSTATE_IDLE;
9999 signal_condition(&thread->lock, &thread->cond);
10000 return 1;
10001 }
10002
10003 /* Determine if this frame is a full frame; if so, and any thread is currently
10004 processing a full frame for the same callno from this peer, then drop this
10005 frame (and the peer will retransmit it) */
10006 fh = (struct ast_iax2_full_hdr *) thread->buf;
10007 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
10008 struct iax2_thread *cur = NULL;
10009 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
10010
10011 AST_LIST_LOCK(&active_list);
10012 AST_LIST_TRAVERSE(&active_list, cur, list) {
10013 if ((cur->ffinfo.callno == callno) &&
10014 !ast_sockaddr_cmp_addr(&cur->ffinfo.addr, &thread->ioaddr))
10015 break;
10016 }
10017 if (cur) {
10018 /* we found another thread processing a full frame for this call,
10019 so queue it up for processing later. */
10020 defer_full_frame(thread, cur);
10021 AST_LIST_UNLOCK(&active_list);
10022 thread->iostate = IAX_IOSTATE_IDLE;
10023 signal_condition(&thread->lock, &thread->cond);
10024 return 1;
10025 } else {
10026 /* this thread is going to process this frame, so mark it */
10027 thread->ffinfo.callno = callno;
10028 ast_sockaddr_copy(&thread->ffinfo.addr, &thread->ioaddr);
10029 thread->ffinfo.type = fh->type;
10030 thread->ffinfo.csub = fh->csub;
10031 AST_LIST_INSERT_HEAD(&active_list, thread, list);
10032 }
10033 AST_LIST_UNLOCK(&active_list);
10034 }
10035
10036 /* Mark as ready and send on its way */
10037 thread->iostate = IAX_IOSTATE_READY;
10038 #ifdef DEBUG_SCHED_MULTITHREAD
10039 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
10040 #endif
10041 signal_condition(&thread->lock, &thread->cond);
10042
10043 return 1;
10044 }
10045
10046 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd,
10047 struct iax_frame *fr)
10048 {
10049 unsigned char metatype;
10050 struct ast_iax2_meta_trunk_mini *mtm;
10051 struct ast_iax2_meta_trunk_hdr *mth;
10052 struct ast_iax2_meta_trunk_entry *mte;
10053 struct iax2_trunk_peer *tpeer;
10054 unsigned int ts;
10055 void *ptr;
10056 struct timeval rxtrunktime;
10057 struct ast_frame f = { 0, };
10058
10059 if (packet_len < sizeof(*meta)) {
10060 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a meta frame but is too short\n",
10061 ast_sockaddr_stringify(addr));
10062 return 1;
10063 }
10064
10065 if (meta->metacmd != IAX_META_TRUNK)
10066 return 1;
10067
10068 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
10069 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
10070 (int) (sizeof(*meta) + sizeof(*mth)));
10071 return 1;
10072 }
10073 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
10074 ts = ntohl(mth->ts);
10075 metatype = meta->cmddata;
10076 packet_len -= (sizeof(*meta) + sizeof(*mth));
10077 ptr = mth->data;
10078 tpeer = find_tpeer(addr, sockfd);
10079 if (!tpeer) {
10080 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s': No matching peer\n",
10081 ast_sockaddr_stringify(addr));
10082 return 1;
10083 }
10084 tpeer->trunkact = ast_tvnow();
10085 if (!ts || ast_tvzero(tpeer->rxtrunktime))
10086 tpeer->rxtrunktime = tpeer->trunkact;
10087 rxtrunktime = tpeer->rxtrunktime;
10088 ast_mutex_unlock(&tpeer->lock);
10089 while (packet_len >= sizeof(*mte)) {
10090 /* Process channels */
10091 unsigned short callno, trunked_ts, len;
10092
10093 if (metatype == IAX_META_TRUNK_MINI) {
10094 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
10095 ptr += sizeof(*mtm);
10096 packet_len -= sizeof(*mtm);
10097 len = ntohs(mtm->len);
10098 callno = ntohs(mtm->mini.callno);
10099 trunked_ts = ntohs(mtm->mini.ts);
10100 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
10101 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
10102 ptr += sizeof(*mte);
10103 packet_len -= sizeof(*mte);
10104 len = ntohs(mte->len);
10105 callno = ntohs(mte->callno);
10106 trunked_ts = 0;
10107 } else {
10108 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s': dropping\n", ast_sockaddr_stringify(addr));
10109 break;
10110 }
10111 /* Stop if we don't have enough data */
10112 if (len > packet_len)
10113 break;
10114 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, addr, NEW_PREVENT, sockfd, 0);
10115 if (!fr->callno)
10116 continue;
10117
10118 /* If it's a valid call, deliver the contents. If not, we
10119 drop it, since we don't have a scallno to use for an INVAL */
10120 /* Process as a mini frame */
10121 memset(&f, 0, sizeof(f));
10122 f.frametype = AST_FRAME_VOICE;
10123 if (!iaxs[fr->callno]) {
10124 /* drop it */
10125 } else if (iaxs[fr->callno]->voiceformat == 0) {
10126 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
10127 iax2_vnak(fr->callno);
10128 } else if ((f.subclass.format = ast_format_compatibility_bitfield2format(
10129 iaxs[fr->callno]->voiceformat))) {
10130 f.datalen = len;
10131 if (f.datalen >= 0) {
10132 if (f.datalen)
10133 f.data.ptr = ptr;
10134 else
10135 f.data.ptr = NULL;
10136 if (trunked_ts)
10137 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
10138 else
10139 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
10140 /* Don't pass any packets until we're started */
10141 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10142 struct iax_frame *duped_fr;
10143
10144 /* Common things */
10145 f.src = "IAX2";
10146 f.mallocd = 0;
10147 f.offset = 0;
10148 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
10149 f.samples = ast_codec_samples_count(&f);
10150 else
10151 f.samples = 0;
10152 fr->outoforder = 0;
10153 iax_frame_wrap(fr, &f);
10154 duped_fr = iaxfrdup2(fr);
10155 if (duped_fr)
10156 schedule_delivery(duped_fr, 1, 1, &fr->ts);
10157 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
10158 iaxs[fr->callno]->last = fr->ts;
10159 }
10160 } else {
10161 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
10162 }
10163 }
10164 ast_mutex_unlock(&iaxsl[fr->callno]);
10165 ptr += len;
10166 packet_len -= len;
10167 }
10168
10169 return 1;
10170 }
10171
10172 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
10173 {
10174 struct ast_datastore *variablestore;
10175 AST_LIST_HEAD(, ast_var_t) *varlist;
10176 struct ast_var_t *var;
10177
10178 if (!chan) {
10179 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10180 return -1;
10181 }
10182
10183 variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
10184 if (!variablestore) {
10185 *buf = '\0';
10186 return 0;
10187 }
10188 varlist = variablestore->data;
10189
10190 AST_LIST_LOCK(varlist);
10191 AST_LIST_TRAVERSE(varlist, var, entries) {
10192 if (strcmp(var->name, data) == 0) {
10193 ast_copy_string(buf, var->value, len);
10194 break;
10195 }
10196 }
10197 AST_LIST_UNLOCK(varlist);
10198 return 0;
10199 }
10200
10201 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10202 {
10203 struct ast_datastore *variablestore;
10204 AST_LIST_HEAD(, ast_var_t) *varlist;
10205 struct ast_var_t *var;
10206
10207 if (!chan) {
10208 ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10209 return -1;
10210 }
10211
10212 variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
10213 if (!variablestore) {
10214 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10215 if (!variablestore) {
10216 ast_log(LOG_ERROR, "Memory allocation error\n");
10217 return -1;
10218 }
10219 varlist = ast_calloc(1, sizeof(*varlist));
10220 if (!varlist) {
10221 ast_datastore_free(variablestore);
10222 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10223 return -1;
10224 }
10225
10226 AST_LIST_HEAD_INIT(varlist);
10227 variablestore->data = varlist;
10228 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10229 ast_channel_datastore_add(chan, variablestore);
10230 } else
10231 varlist = variablestore->data;
10232
10233 AST_LIST_LOCK(varlist);
10234 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
10235 if (strcmp(var->name, data) == 0) {
10236 AST_LIST_REMOVE_CURRENT(entries);
10237 ast_var_delete(var);
10238 break;
10239 }
10240 }
10241 AST_LIST_TRAVERSE_SAFE_END;
10242 var = ast_var_assign(data, value);
10243 if (var)
10244 AST_LIST_INSERT_TAIL(varlist, var, entries);
10245 else
10246 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10247 AST_LIST_UNLOCK(varlist);
10248 return 0;
10249 }
10250
10251 static struct ast_custom_function iaxvar_function = {
10252 .name = "IAXVAR",
10253 .read = acf_iaxvar_read,
10254 .write = acf_iaxvar_write,
10255 };
10256
10257 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10258 {
10259 iax2_lock_owner(callno);
10260 if (iaxs[callno] && iaxs[callno]->owner) {
10261 struct ast_channel *owner;
10262 const char *name;
10263
10264 owner = iaxs[callno]->owner;
10265 if (causecode) {
10266 ast_channel_hangupcause_set(owner, causecode);
10267 }
10268 name = ast_strdupa(ast_channel_name(owner));
10269 ast_channel_ref(owner);
10270 ast_channel_unlock(owner);
10271 ast_mutex_unlock(&iaxsl[callno]);
10272 ast_set_hangupsource(owner, name, 0);
10273 ast_channel_unref(owner);
10274 ast_mutex_lock(&iaxsl[callno]);
10275 }
10276 }
10277
10278 static int socket_process_helper(struct iax2_thread *thread)
10279 {
10280 struct ast_sockaddr addr;
10281 int res;
10282 int updatehistory=1;
10283 int new = NEW_PREVENT;
10284 int dcallno = 0;
10285 char decrypted = 0;
10286 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10287 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10288 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10289 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10290 struct iax_frame *fr;
10291 struct iax_frame *cur;
10292 struct ast_frame f = { 0, };
10293 struct ast_channel *c = NULL;
10294 struct iax2_dpcache *dp;
10295 struct iax2_peer *peer;
10296 struct iax_ies ies;
10297 struct iax_ie_data ied0, ied1;
10298 iax2_format format;
10299 int fd;
10300 int exists;
10301 int minivid = 0;
10302 char empty[32]=""; /* Safety measure */
10303 struct iax_frame *duped_fr;
10304 char host_pref_buf[128];
10305 char caller_pref_buf[128];
10306 struct iax2_codec_pref pref;
10307 char *using_prefs = "mine";
10308
10309 /* allocate an iax_frame with 4096 bytes of data buffer */
10310 fr = ast_alloca(sizeof(*fr) + 4096);
10311 memset(fr, 0, sizeof(*fr));
10312 fr->afdatalen = 4096; /* From ast_alloca() above */
10313
10314 /* Copy frequently used parameters to the stack */
10315 res = thread->buf_len;
10316 fd = thread->iofd;
10317 ast_sockaddr_copy(&addr, &thread->ioaddr);
10318
10319 if (res < sizeof(*mh)) {
10320 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10321 return 1;
10322 }
10323 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10324 if (res < sizeof(*vh)) {
10325 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a video frame but is too short\n",
10326 ast_sockaddr_stringify(&addr));
10327 return 1;
10328 }
10329
10330 /* This is a video frame, get call number */
10331 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &addr, new, fd, 0);
10332 minivid = 1;
10333 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10334 return socket_process_meta(res, meta, &addr, fd, fr);
10335
10336 #ifdef DEBUG_SUPPORT
10337 if (res >= sizeof(*fh))
10338 iax_outputframe(NULL, fh, 1, &addr, res - sizeof(*fh));
10339 #endif
10340 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10341 if (res < sizeof(*fh)) {
10342 ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a full frame but is too short\n",
10343 ast_sockaddr_stringify(&addr));
10344 return 1;
10345 }
10346
10347 /* Get the destination call number */
10348 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10349
10350
10351 /* check to make sure this full frame isn't encrypted before we attempt
10352 * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10353 * callno is not found here, that just means one hasn't been allocated for
10354 * this connection yet. */
10355 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, NEW_PREVENT, fd, 1))) {
10356 ast_mutex_lock(&iaxsl[fr->callno]);
10357 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10358 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10359 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10360 ast_mutex_unlock(&iaxsl[fr->callno]);
10361 return 1;
10362 }
10363 decrypted = 1;
10364 }
10365 ast_mutex_unlock(&iaxsl[fr->callno]);
10366 }
10367
10368 /* Retrieve the type and subclass */
10369 f.frametype = fh->type;
10370 if (f.frametype == AST_FRAME_VIDEO) {
10371 f.subclass.format = ast_format_compatibility_bitfield2format(uncompress_subclass(fh->csub & ~0x40));
10372 if (!f.subclass.format) {
10373 return 1;
10374 }
10375 if ((fh->csub >> 6) & 0x1) {
10376 f.subclass.frame_ending = 1;
10377 }
10378 } else if (f.frametype == AST_FRAME_VOICE) {
10379 f.subclass.format = ast_format_compatibility_bitfield2format(uncompress_subclass(fh->csub));
10380 if (!f.subclass.format) {
10381 return 1;
10382 }
10383 } else {
10384 f.subclass.integer = uncompress_subclass(fh->csub);
10385 }
10386
10387 /* Deal with POKE/PONG without allocating a callno */
10388 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
10389 /* Reply back with a PONG, but don't care about the result. */
10390 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10391 return 1;
10392 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10393 /* Ignore */
10394 return 1;
10395 }
10396
10397 f.datalen = res - sizeof(*fh);
10398 if (f.datalen) {
10399 if (f.frametype == AST_FRAME_IAX) {
10400 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10401 char subclass[40];
10402 iax_frame_subclass2str(f.subclass.integer, subclass, sizeof(subclass));
10403 ast_log(LOG_WARNING, "Undecodable %s frame received from '%s'\n", subclass, ast_sockaddr_stringify(&addr));
10404 ast_variables_destroy(ies.vars);
10405 return 1;
10406 }
10407 f.data.ptr = NULL;
10408 f.datalen = 0;
10409 } else {
10410 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10411 memset(&ies, 0, sizeof(ies));
10412 }
10413 } else {
10414 if (f.frametype == AST_FRAME_IAX)
10415 f.data.ptr = NULL;
10416 else
10417 f.data.ptr = empty;
10418 memset(&ies, 0, sizeof(ies));
10419 }
10420
10421 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10422 /* only set NEW_ALLOW if calltoken checks out */
10423 if (handle_call_token(fh, &ies, &addr, fd)) {
10424 ast_variables_destroy(ies.vars);
10425 return 1;
10426 }
10427
10428 if (ies.calltoken && ies.calltokendata) {
10429 /* if we've gotten this far, and the calltoken ie data exists,
10430 * then calltoken validation _MUST_ have taken place. If calltoken
10431 * data is provided, it is always validated regardless of any
10432 * calltokenoptional or requirecalltoken options */
10433 new = NEW_ALLOW_CALLTOKEN_VALIDATED;
10434 } else {
10435 new = NEW_ALLOW;
10436 }
10437 }
10438 } else {
10439 /* Don't know anything about it yet */
10440 f.frametype = AST_FRAME_NULL;
10441 f.subclass.integer = 0;
10442 memset(&ies, 0, sizeof(ies));
10443 }
10444
10445 if (!fr->callno) {
10446 int check_dcallno = 0;
10447
10448 /*
10449 * We enforce accurate destination call numbers for ACKs. This forces the other
10450 * end to know the destination call number before call setup can complete.
10451 *
10452 * Discussed in the following thread:
10453 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10454 */
10455
10456 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10457 check_dcallno = 1;
10458 }
10459
10460 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, new, fd, check_dcallno))) {
10461 ast_debug(1, "Received frame without existent call number (%d)\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10462 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
10463 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10464 } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
10465 send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10466 } else {
10467 ast_log(LOG_WARNING, "Silently dropping frame without existent call number: %d\n", ntohs(mh->callno) & ~IAX_FLAG_FULL);
10468 }
10469 ast_variables_destroy(ies.vars);
10470 return 1;
10471 }
10472 }
10473
10474 if (fr->callno > 0) {
10475 ast_callid mount_callid;
10476 ast_mutex_lock(&iaxsl[fr->callno]);
10477 if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10478 /* Bind to thread */
10479 ast_callid_threadassoc_add(mount_callid);
10480 }
10481 }
10482
10483 if (!fr->callno || !iaxs[fr->callno]) {
10484 /* A call arrived for a nonexistent destination. Unless it's an "inval"
10485 frame, reply with an inval */
10486 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10487 /* We can only raw hangup control frames */
10488 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10489 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10490 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10491 (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
10492 (f.frametype != AST_FRAME_IAX))
10493 raw_hangup(&addr, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10494 fd);
10495 }
10496 if (fr->callno > 0){
10497 ast_mutex_unlock(&iaxsl[fr->callno]);
10498 }
10499 ast_variables_destroy(ies.vars);
10500 return 1;
10501 }
10502 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10503 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10504 ast_log(LOG_WARNING, "Packet Decrypt Failed!\n");
10505 ast_variables_destroy(ies.vars);
10506 ast_mutex_unlock(&iaxsl[fr->callno]);
10507 return 1;
10508 }
10509 decrypted = 1;
10510 }
10511
10512 #ifdef DEBUG_SUPPORT
10513 if (decrypted) {
10514 iax_outputframe(NULL, fh, 3, &addr, res - sizeof(*fh));
10515 }
10516 #endif
10517
10518 if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10519 (fh->csub == IAX_COMMAND_HANGUP
10520 || fh->csub == IAX_COMMAND_REJECT
10521 || fh->csub == IAX_COMMAND_REGREJ
10522 || fh->csub == IAX_COMMAND_TXREJ)) {
10523 struct ast_control_pvt_cause_code *cause_code;
10524 int data_size = sizeof(*cause_code);
10525 char subclass[40] = "";
10526
10527 /* get subclass text */
10528 iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10529
10530 /* add length of "IAX2 " */
10531 data_size += 5;
10532 /* for IAX hangup frames, add length of () and number */
10533 data_size += 3;
10534 if (ies.causecode > 9) {
10535 data_size++;
10536 }
10537 if (ies.causecode > 99) {
10538 data_size++;
10539 }
10540 /* add length of subclass */
10541 data_size += strlen(subclass);
10542
10543 cause_code = ast_alloca(data_size);
10544 memset(cause_code, 0, data_size);
10545 ast_copy_string(cause_code->chan_name, ast_channel_name(iaxs[fr->callno]->owner), AST_CHANNEL_NAME);
10546
10547 cause_code->ast_cause = ies.causecode;
10548 snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10549
10550 iax2_lock_owner(fr->callno);
10551 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10552 ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10553 ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10554 ast_channel_unlock(iaxs[fr->callno]->owner);
10555 }
10556 if (!iaxs[fr->callno]) {
10557 ast_variables_destroy(ies.vars);
10558 ast_mutex_unlock(&iaxsl[fr->callno]);
10559 return 1;
10560 }
10561 }
10562
10563 /* count this frame */
10564 iaxs[fr->callno]->frames_received++;
10565
10566 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) && !minivid &&
10567 f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10568 f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10569 unsigned short new_peercallno;
10570
10571 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10572 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10573 if (iaxs[fr->callno]->peercallno) {
10574 remove_by_peercallno(iaxs[fr->callno]);
10575 }
10576 iaxs[fr->callno]->peercallno = new_peercallno;
10577 store_by_peercallno(iaxs[fr->callno]);
10578 }
10579 }
10580 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10581 if (iaxdebug)
10582 ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10583 /* Check if it's out of order (and not an ACK or INVAL) */
10584 fr->oseqno = fh->oseqno;
10585 fr->iseqno = fh->iseqno;
10586 fr->ts = ntohl(fh->ts);
10587 #ifdef IAXTESTS
10588 if (test_resync) {
10589 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10590 fr->ts += test_resync;
10591 }
10592 #endif /* IAXTESTS */
10593 #if 0
10594 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10595 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10596 (f.subclass == IAX_COMMAND_NEW ||
10597 f.subclass == IAX_COMMAND_AUTHREQ ||
10598 f.subclass == IAX_COMMAND_ACCEPT ||
10599 f.subclass == IAX_COMMAND_REJECT)) ) )
10600 #endif
10601 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10602 updatehistory = 0;
10603 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10604 (iaxs[fr->callno]->iseqno ||
10605 ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10606 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10607 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10608 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10609 (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10610 (f.frametype != AST_FRAME_IAX))) {
10611 if (
10612 ((f.subclass.integer != IAX_COMMAND_ACK) &&
10613 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10614 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10615 (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10616 (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10617 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10618 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10619 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10620 (f.frametype != AST_FRAME_IAX)) {
10621 /* If it's not an ACK packet, it's out of order. */
10622 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10623 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10624 /* Check to see if we need to request retransmission,
10625 * and take sequence number wraparound into account */
10626 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10627 /* If we've already seen it, ack it XXX There's a border condition here XXX */
10628 if ((f.frametype != AST_FRAME_IAX) ||
10629 ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10630 ast_debug(1, "Acking anyway\n");
10631 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10632 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10633 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10634 }
10635 } else {
10636 /* Send a VNAK requesting retransmission */
10637 iax2_vnak(fr->callno);
10638 }
10639 ast_variables_destroy(ies.vars);
10640 ast_mutex_unlock(&iaxsl[fr->callno]);
10641 return 1;
10642 }
10643 } else {
10644 /* Increment unless it's an ACK or VNAK */
10645 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10646 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10647 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10648 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10649 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10650 (f.frametype != AST_FRAME_IAX))
10651 iaxs[fr->callno]->iseqno++;
10652 }
10653 /* Ensure text frames are NULL-terminated */
10654 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10655 if (res < thread->buf_size)
10656 thread->buf[res++] = '\0';
10657 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10658 thread->buf[res - 1] = '\0';
10659 }
10660
10661 /* Handle implicit ACKing unless this is an INVAL, and only if this is
10662 from the real peer, not the transfer peer */
10663 if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10664 ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10665 (f.frametype != AST_FRAME_IAX))) {
10666 unsigned char x;
10667 int call_to_destroy;
10668 /* First we have to qualify that the ACKed value is within our window */
10669 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10670 x = fr->iseqno;
10671 else
10672 x = iaxs[fr->callno]->oseqno;
10673 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10674 /* The acknowledgement is within our window. Time to acknowledge everything
10675 that it says to */
10676 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10677 /* Ack the packet with the given timestamp */
10678 if (iaxdebug)
10679 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10680 call_to_destroy = 0;
10681 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10682 /* If it's our call, and our timestamp, mark -1 retries */
10683 if (x == cur->oseqno) {
10684 cur->retries = -1;
10685 /* Destroy call if this is the end */
10686 if (cur->final)
10687 call_to_destroy = fr->callno;
10688 }
10689 }
10690 if (call_to_destroy) {
10691 if (iaxdebug)
10692 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10693 ast_mutex_lock(&iaxsl[call_to_destroy]);
10694 iax2_destroy(call_to_destroy);
10695 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10696 }
10697 }
10698 /* Note how much we've received acknowledgement for */
10699 if (iaxs[fr->callno])
10700 iaxs[fr->callno]->rseqno = fr->iseqno;
10701 else {
10702 /* Stop processing now */
10703 ast_variables_destroy(ies.vars);
10704 ast_mutex_unlock(&iaxsl[fr->callno]);
10705 return 1;
10706 }
10707 } else {
10708 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10709 }
10710 }
10711 if (ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10712 ((f.frametype != AST_FRAME_IAX) ||
10713 ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10714 (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10715 /* Only messages we accept from a transfer host are TXACC and TXCNT */
10716 ast_variables_destroy(ies.vars);
10717 ast_mutex_unlock(&iaxsl[fr->callno]);
10718 return 1;
10719 }
10720
10721 /* when we receive the first full frame for a new incoming channel,
10722 it is safe to start the PBX on the channel because we have now
10723 completed a 3-way handshake with the peer */
10724 if ((f.frametype == AST_FRAME_VOICE) ||
10725 (f.frametype == AST_FRAME_VIDEO) ||
10726 (f.frametype == AST_FRAME_IAX)) {
10727 if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10728 ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10729 if (!ast_iax2_new(fr->callno, AST_STATE_RING,
10730 iaxs[fr->callno]->chosenformat, &iaxs[fr->callno]->rprefs, NULL, NULL,
10731 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED))) {
10732 ast_variables_destroy(ies.vars);
10733 ast_mutex_unlock(&iaxsl[fr->callno]);
10734 return 1;
10735 }
10736 }
10737
10738 if (ies.vars) {
10739 struct ast_datastore *variablestore = NULL;
10740 struct ast_variable *var, *prev = NULL;
10741 AST_LIST_HEAD(, ast_var_t) *varlist;
10742
10743 iax2_lock_owner(fr->callno);
10744 if (!iaxs[fr->callno]) {
10745 ast_variables_destroy(ies.vars);
10746 ast_mutex_unlock(&iaxsl[fr->callno]);
10747 return 1;
10748 }
10749 if ((c = iaxs[fr->callno]->owner)) {
10750 varlist = ast_calloc(1, sizeof(*varlist));
10751 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10752
10753 if (variablestore && varlist) {
10754 variablestore->data = varlist;
10755 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10756 AST_LIST_HEAD_INIT(varlist);
10757 ast_debug(1, "I can haz IAX vars?\n");
10758 for (var = ies.vars; var; var = var->next) {
10759 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10760 if (prev) {
10761 ast_free(prev);
10762 }
10763 prev = var;
10764 if (!newvar) {
10765 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10766 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10767 } else {
10768 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10769 }
10770 }
10771 if (prev) {
10772 ast_free(prev);
10773 }
10774 ies.vars = NULL;
10775 ast_channel_datastore_add(c, variablestore);
10776 } else {
10777 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10778 if (variablestore) {
10779 ast_datastore_free(variablestore);
10780 }
10781 if (varlist) {
10782 ast_free(varlist);
10783 }
10784 }
10785 ast_channel_unlock(c);
10786 } else {
10787 /* No channel yet, so transfer the variables directly over to the pvt,
10788 * for later inheritance. */
10789 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10790 for (var = ies.vars; var && var->next; var = var->next);
10791 if (var) {
10792 var->next = iaxs[fr->callno]->iaxvars;
10793 iaxs[fr->callno]->iaxvars = ies.vars;
10794 ies.vars = NULL;
10795 }
10796 }
10797 }
10798
10799 if (ies.vars) {
10800 ast_debug(1, "I have IAX variables, but they were not processed\n");
10801 }
10802 }
10803
10804 /* once we receive our first IAX Full Frame that is not CallToken related, send all
10805 * queued signaling frames that were being held. */
10806 if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10807 send_signaling(iaxs[fr->callno]);
10808 }
10809
10810 if (f.frametype == AST_FRAME_VOICE) {
10811 if (ast_format_compatibility_format2bitfield(f.subclass.format) != iaxs[fr->callno]->voiceformat) {
10812 iaxs[fr->callno]->voiceformat = ast_format_compatibility_format2bitfield(f.subclass.format);
10813 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_format_get_name(f.subclass.format));
10814 if (iaxs[fr->callno]->owner) {
10815 iax2_lock_owner(fr->callno);
10816 if (iaxs[fr->callno]) {
10817 if (iaxs[fr->callno]->owner) {
10818 struct ast_format_cap *native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
10819 if (native) {
10820 ast_format_cap_append(native, f.subclass.format, 0);
10821 ast_channel_nativeformats_set(iaxs[fr->callno]->owner, native);
10822 if (ast_channel_readformat(iaxs[fr->callno]->owner)) {
10823 ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
10824 }
10825 ao2_ref(native, -1);
10826 }
10827 ast_channel_unlock(iaxs[fr->callno]->owner);
10828 }
10829 } else {
10830 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10831 /* Free remote variables (if any) */
10832 if (ies.vars) {
10833 ast_variables_destroy(ies.vars);
10834 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10835 ies.vars = NULL;
10836 }
10837 ast_mutex_unlock(&iaxsl[fr->callno]);
10838 return 1;
10839 }
10840 }
10841 }
10842 }
10843 if (f.frametype == AST_FRAME_VIDEO) {
10844 if (ast_format_compatibility_format2bitfield(f.subclass.format) != iaxs[fr->callno]->videoformat) {
10845 ast_debug(1, "Ooh, video format changed to %s\n", ast_format_get_name(f.subclass.format));
10846 iaxs[fr->callno]->videoformat = ast_format_compatibility_format2bitfield(f.subclass.format);
10847 }
10848 }
10849 if (f.frametype == AST_FRAME_IAX) {
10850 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
10851 /* Handle the IAX pseudo frame itself */
10852 if (iaxdebug)
10853 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10854
10855 /* Update last ts unless the frame's timestamp originated with us. */
10856 if (iaxs[fr->callno]->last < fr->ts &&
10857 f.subclass.integer != IAX_COMMAND_ACK &&
10858 f.subclass.integer != IAX_COMMAND_PONG &&
10859 f.subclass.integer != IAX_COMMAND_LAGRP) {
10860 iaxs[fr->callno]->last = fr->ts;
10861 if (iaxdebug)
10862 ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10863 }
10864 iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10865 if (!iaxs[fr->callno]->first_iax_message) {
10866 iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10867 }
10868 switch(f.subclass.integer) {
10869 case IAX_COMMAND_ACK:
10870 /* Do nothing */
10871 break;
10872 case IAX_COMMAND_QUELCH:
10873 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10874 ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10875 if (ies.musiconhold) {
10876 const char *moh_suggest;
10877
10878 iax2_lock_owner(fr->callno);
10879 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10880 break;
10881 }
10882
10883 /*
10884 * We already hold the owner lock so we do not
10885 * need to check iaxs[fr->callno] after it returns.
10886 */
10887 moh_suggest = iaxs[fr->callno]->mohsuggest;
10888 iax2_queue_hold(fr->callno, moh_suggest);
10889 ast_channel_unlock(iaxs[fr->callno]->owner);
10890 }
10891 }
10892 break;
10893 case IAX_COMMAND_UNQUELCH:
10894 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10895 iax2_lock_owner(fr->callno);
10896 if (!iaxs[fr->callno]) {
10897 break;
10898 }
10899
10900 ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10901 if (!iaxs[fr->callno]->owner) {
10902 break;
10903 }
10904
10905 /*
10906 * We already hold the owner lock so we do not
10907 * need to check iaxs[fr->callno] after it returns.
10908 */
10909 iax2_queue_unhold(fr->callno);
10910 ast_channel_unlock(iaxs[fr->callno]->owner);
10911 }
10912 break;
10913 case IAX_COMMAND_TXACC:
10914 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10915 /* Ack the packet with the given timestamp */
10916 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10917 /* Cancel any outstanding txcnt's */
10918 if (cur->transfer) {
10919 cur->retries = -1;
10920 }
10921 }
10922 memset(&ied1, 0, sizeof(ied1));
10923 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10924 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10925 iaxs[fr->callno]->transferring = TRANSFER_READY;
10926 }
10927 break;
10928 case IAX_COMMAND_NEW:
10929 /* Ignore if it's already up */
10930 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10931 break;
10932 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
10933 ast_mutex_unlock(&iaxsl[fr->callno]);
10934 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
10935 ast_mutex_lock(&iaxsl[fr->callno]);
10936 if (!iaxs[fr->callno]) {
10937 break;
10938 }
10939 }
10940 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10941 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10942 int new_callno;
10943 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10944 fr->callno = new_callno;
10945 }
10946 /* For security, always ack immediately */
10947 if (delayreject)
10948 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10949 if (check_access(fr->callno, &addr, &ies)) {
10950 /* They're not allowed on */
10951 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10952 if (authdebug) {
10953 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n",
10954 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10955 }
10956 break;
10957 }
10958 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10959 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10960 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10961 break;
10962 }
10963 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10964 const char *context, *exten, *cid_num;
10965
10966 context = ast_strdupa(iaxs[fr->callno]->context);
10967 exten = ast_strdupa(iaxs[fr->callno]->exten);
10968 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10969
10970 /* This might re-enter the IAX code and need the lock */
10971 ast_mutex_unlock(&iaxsl[fr->callno]);
10972 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10973 ast_mutex_lock(&iaxsl[fr->callno]);
10974
10975 if (!iaxs[fr->callno]) {
10976 break;
10977 }
10978 } else
10979 exists = 0;
10980 /* Get OSP token if it does exist */
10981 save_osptoken(fr, &ies);
10982 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10983 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10984 memset(&ied0, 0, sizeof(ied0));
10985 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10986 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10987 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10988 if (!iaxs[fr->callno]) {
10989 break;
10990 }
10991 if (authdebug) {
10992 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
10993 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10994 }
10995 } else {
10996 /* Select an appropriate format */
10997
10998 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10999 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11000 using_prefs = "reqonly";
11001 } else {
11002 using_prefs = "disabled";
11003 }
11004 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11005 memset(&pref, 0, sizeof(pref));
11006 strcpy(caller_pref_buf, "disabled");
11007 strcpy(host_pref_buf, "disabled");
11008 } else {
11009 struct ast_format *tmpfmt;
11010 using_prefs = "mine";
11011 /* If the information elements are in here... use them */
11012 if (ies.codec_prefs)
11013 iax2_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11014 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11015 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
11016 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11017 pref = iaxs[fr->callno]->rprefs;
11018 using_prefs = "caller";
11019 } else {
11020 pref = iaxs[fr->callno]->prefs;
11021 }
11022 } else
11023 pref = iaxs[fr->callno]->prefs;
11024
11025 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11026 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11027 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11028 }
11029 if (!format) {
11030 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
11031 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11032 if (!format) {
11033 memset(&ied0, 0, sizeof(ied0));
11034 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11035 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11036 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11037 if (!iaxs[fr->callno]) {
11038 break;
11039 }
11040 if (authdebug) {
11041 struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11042 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11043 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11044
11045 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11046 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11047 ast_sockaddr_stringify(&addr),
11048 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11049 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11050 } else {
11051 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11052 ast_sockaddr_stringify(&addr),
11053 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11054 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11055 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11056 }
11057 }
11058 } else {
11059 /* Pick one... */
11060 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11061 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11062 format = 0;
11063 } else {
11064 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11065 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11066 memset(&pref, 0, sizeof(pref));
11067 format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11068 strcpy(caller_pref_buf,"disabled");
11069 strcpy(host_pref_buf,"disabled");
11070 } else {
11071 struct ast_format *tmpfmt;
11072 using_prefs = "mine";
11073 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11074 /* Do the opposite of what we tried above. */
11075 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11076 pref = iaxs[fr->callno]->prefs;
11077 } else {
11078 pref = iaxs[fr->callno]->rprefs;
11079 using_prefs = "caller";
11080 }
11081 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11082 } else /* if no codec_prefs IE do it the old way */
11083 format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11084 }
11085 }
11086
11087 if (!format) {
11088 struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11089 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11090 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11091
11092 memset(&ied0, 0, sizeof(ied0));
11093 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11094 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11095 ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11096 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11097 if (!iaxs[fr->callno]) {
11098 break;
11099 }
11100 if (authdebug) {
11101 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11102 ast_sockaddr_stringify(&addr),
11103 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11104 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11105 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11106 }
11107 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11108 break;
11109 }
11110 }
11111 }
11112 if (format) {
11113 /* No authentication required, let them in */
11114 memset(&ied1, 0, sizeof(ied1));
11115 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11116 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11117 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11118 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11119 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11120 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
11121 "%srequested format = %s,\n"
11122 "%srequested prefs = %s,\n"
11123 "%sactual format = %s,\n"
11124 "%shost prefs = %s,\n"
11125 "%spriority = %s\n",
11126 ast_sockaddr_stringify(&addr),
11127 VERBOSE_PREFIX_4,
11128 iax2_getformatname(iaxs[fr->callno]->peerformat),
11129 VERBOSE_PREFIX_4,
11130 caller_pref_buf,
11131 VERBOSE_PREFIX_4,
11132 iax2_getformatname(format),
11133 VERBOSE_PREFIX_4,
11134 host_pref_buf,
11135 VERBOSE_PREFIX_4,
11136 using_prefs);
11137
11138 iaxs[fr->callno]->chosenformat = format;
11139
11140 /* Since this is a new call, we should go ahead and set the callid for it. */
11141 iax_pvt_callid_new(fr->callno);
11142 ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
11143 } else {
11144 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11145 /* If this is a TBD call, we're ready but now what... */
11146 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_sockaddr_stringify(&addr));
11147 }
11148 }
11149 }
11150 break;
11151 }
11152 if (iaxs[fr->callno]->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA))
11153 merge_encryption(iaxs[fr->callno], ies.encmethods);
11154 else
11155 iaxs[fr->callno]->encmethods = 0;
11156 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
11157 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
11158 break;
11159 case IAX_COMMAND_DPREQ:
11160 /* Request status in the dialplan */
11161 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
11162 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
11163 if (iaxcompat) {
11164 /* Spawn a thread for the lookup */
11165 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
11166 } else {
11167 /* Just look it up */
11168 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
11169 }
11170 }
11171 break;
11172 case IAX_COMMAND_HANGUP:
11173 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11174 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
11175 /* Set hangup cause according to remote and hangupsource */
11176 if (iaxs[fr->callno]->owner) {
11177 set_hangup_source_and_cause(fr->callno, ies.causecode);
11178 if (!iaxs[fr->callno]) {
11179 break;
11180 }
11181 }
11182
11183 /* Send ack immediately, before we destroy */
11184 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11185 iax2_destroy(fr->callno);
11186 break;
11187 case IAX_COMMAND_REJECT:
11188 /* Set hangup cause according to remote and hangup source */
11189 if (iaxs[fr->callno]->owner) {
11190 set_hangup_source_and_cause(fr->callno, ies.causecode);
11191 if (!iaxs[fr->callno]) {
11192 break;
11193 }
11194 }
11195
11196 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
11197 if (iaxs[fr->callno]->owner && authdebug)
11198 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
11199 ast_sockaddr_stringify(&addr),
11200 ies.cause ? ies.cause : "<Unknown>");
11201 ast_debug(1, "Immediately destroying %d, having received reject\n",
11202 fr->callno);
11203 }
11204 /* Send ack immediately, before we destroy */
11205 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
11206 fr->ts, NULL, 0, fr->iseqno);
11207 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
11208 iaxs[fr->callno]->error = EPERM;
11209 iax2_destroy(fr->callno);
11210 break;
11211 case IAX_COMMAND_TRANSFER:
11212 {
11213 iax2_lock_owner(fr->callno);
11214 if (!iaxs[fr->callno]) {
11215 /* Initiating call went away before we could transfer. */
11216 break;
11217 }
11218 if (iaxs[fr->callno]->owner) {
11219 struct ast_channel *owner = iaxs[fr->callno]->owner;
11220 char *context = ast_strdupa(iaxs[fr->callno]->context);
11221
11222 ast_channel_ref(owner);
11223 ast_channel_unlock(owner);
11224 ast_mutex_unlock(&iaxsl[fr->callno]);
11225
11226 if (ast_bridge_transfer_blind(1, owner, ies.called_number,
11227 context, NULL, NULL) != AST_BRIDGE_TRANSFER_SUCCESS) {
11228 ast_log(LOG_WARNING, "Blind transfer of '%s' to '%s@%s' failed\n",
11229 ast_channel_name(owner), ies.called_number,
11230 context);
11231 }
11232
11233 ast_channel_unref(owner);
11234 ast_mutex_lock(&iaxsl[fr->callno]);
11235 }
11236
11237 break;
11238 }
11239 case IAX_COMMAND_ACCEPT:
11240 /* Ignore if call is already up or needs authentication or is a TBD */
11241 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
11242 break;
11243 if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
11244 /* Send ack immediately, before we destroy */
11245 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11246 iax2_destroy(fr->callno);
11247 break;
11248 }
11249 if (ies.format) {
11250 iaxs[fr->callno]->peerformat = ies.format;
11251 } else {
11252 if (iaxs[fr->callno]->owner)
11253 iaxs[fr->callno]->peerformat = iax2_format_compatibility_cap2bitfield(ast_channel_nativeformats(iaxs[fr->callno]->owner));
11254 else
11255 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
11256 }
11257 ast_verb(3, "Call accepted by %s (format %s)\n", ast_sockaddr_stringify(&addr),
11258 iax2_getformatname(iaxs[fr->callno]->peerformat));
11259 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11260 memset(&ied0, 0, sizeof(ied0));
11261 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11262 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11263 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11264 if (!iaxs[fr->callno]) {
11265 break;
11266 }
11267 if (authdebug) {
11268 struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11269 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11270
11271 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11272 ast_sockaddr_stringify(&addr),
11273 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_buf),
11274 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11275 }
11276 } else {
11277 struct ast_format_cap *native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
11278
11279 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11280 iax2_lock_owner(fr->callno);
11281 if (iaxs[fr->callno] && iaxs[fr->callno]->owner && native) {
11282 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11283
11284 /* Switch us to use a compatible format */
11285 iax2_codec_pref_best_bitfield2cap(
11286 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11287 native);
11288 ast_channel_nativeformats_set(iaxs[fr->callno]->owner, native);
11289 ast_verb(3, "Format for call is %s\n", ast_format_cap_get_names(ast_channel_nativeformats(iaxs[fr->callno]->owner), &cap_buf));
11290
11291 /* Setup read/write formats properly. */
11292 if (ast_channel_writeformat(iaxs[fr->callno]->owner))
11293 ast_set_write_format(iaxs[fr->callno]->owner, ast_channel_writeformat(iaxs[fr->callno]->owner));
11294 if (ast_channel_readformat(iaxs[fr->callno]->owner))
11295 ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
11296 ast_channel_unlock(iaxs[fr->callno]->owner);
11297 }
11298
11299 ao2_cleanup(native);
11300 }
11301 if (iaxs[fr->callno]) {
11302 AST_LIST_LOCK(&dpcache);
11303 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11304 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11305 iax2_dprequest(dp, fr->callno);
11306 AST_LIST_UNLOCK(&dpcache);
11307 }
11308 break;
11309 case IAX_COMMAND_POKE:
11310 /* Send back a pong packet with the original timestamp */
11311 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
11312 break;
11313 case IAX_COMMAND_PING:
11314 {
11315 struct iax_ie_data pingied;
11316 construct_rr(iaxs[fr->callno], &pingied);
11317 /* Send back a pong packet with the original timestamp */
11318 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11319 }
11320 break;
11321 case IAX_COMMAND_PONG:
11322 /* Calculate ping time */
11323 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11324 /* save RR info */
11325 save_rr(fr, &ies);
11326
11327 /* Good time to write jb stats for this call */
11328 log_jitterstats(fr->callno);
11329
11330 if (iaxs[fr->callno]->peerpoke) {
11331 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
11332 peer = iaxs[fr->callno]->peerpoke;
11333 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11334 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11335 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11336 ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
11337 blob = ast_json_pack("{s: s, s: I}",
11338 "peer_status", "Reachable",
11339 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11340 ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11341 }
11342 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11343 if (iaxs[fr->callno]->pingtime > peer->maxms) {
11344 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11345 ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_ONLINE);
11346 blob = ast_json_pack("{s: s, s: I}",
11347 "peer_status", "Lagged",
11348 "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11349 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11350 }
11351 }
11352 ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
11353 peer->lastms = iaxs[fr->callno]->pingtime;
11354 if (peer->smoothing && (peer->lastms > -1))
11355 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11356 else if (peer->smoothing && peer->lastms < 0)
11357 peer->historicms = (0 + peer->historicms) / 2;
11358 else
11359 peer->historicms = iaxs[fr->callno]->pingtime;
11360
11361 /* Remove scheduled iax2_poke_noanswer */
11362 if (peer->pokeexpire > -1) {
11363 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11364 peer_unref(peer);
11365 peer->pokeexpire = -1;
11366 }
11367 }
11368 /* Schedule the next cycle */
11369 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11370 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11371 else
11372 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
11373 if (peer->pokeexpire == -1)
11374 peer_unref(peer);
11375 /* and finally send the ack */
11376 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11377 /* And wrap up the qualify call */
11378 iax2_destroy(fr->callno);
11379 peer->callno = 0;
11380 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11381 }
11382 break;
11383 case IAX_COMMAND_LAGRQ:
11384 case IAX_COMMAND_LAGRP:
11385 f.src = "LAGRQ";
11386 f.mallocd = 0;
11387 f.offset = 0;
11388 f.samples = 0;
11389 iax_frame_wrap(fr, &f);
11390 if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
11391 /* Received a LAGRQ - echo back a LAGRP */
11392 fr->af.subclass.integer = IAX_COMMAND_LAGRP;
11393 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11394 } else {
11395 /* Received LAGRP in response to our LAGRQ */
11396 unsigned int ts;
11397 /* This is a reply we've been given, actually measure the difference */
11398 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11399 iaxs[fr->callno]->lag = ts - fr->ts;
11400 if (iaxdebug)
11401 ast_debug(1, "Peer %s lag measured as %dms\n",
11402 ast_sockaddr_stringify(&addr), iaxs[fr->callno]->lag);
11403 }
11404 break;
11405 case IAX_COMMAND_AUTHREQ:
11406 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11407 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11408 break;
11409 }
11410 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11411 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11412 .subclass.integer = AST_CONTROL_HANGUP,
11413 };
11414 ast_log(LOG_WARNING,
11415 "I don't know how to authenticate %s to %s\n",
11416 ies.username ? ies.username : "<unknown>", ast_sockaddr_stringify(&addr));
11417 iax2_queue_frame(fr->callno, &hangup_fr);
11418 }
11419 break;
11420 case IAX_COMMAND_AUTHREP:
11421 /* For security, always ack immediately */
11422 if (delayreject)
11423 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11424 /* Ignore once we've started */
11425 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11426 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11427 break;
11428 }
11429 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11430 if (authdebug)
11431 ast_log(LOG_WARNING, "Host %s failed to authenticate as %s\n", ast_sockaddr_stringify(&addr),
11432 iaxs[fr->callno]->username);
11433 memset(&ied0, 0, sizeof(ied0));
11434 auth_fail(fr->callno, IAX_COMMAND_REJECT);
11435 break;
11436 }
11437 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11438 /* This might re-enter the IAX code and need the lock */
11439 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11440 } else
11441 exists = 0;
11442 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11443 if (authdebug)
11444 ast_log(LOG_WARNING, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
11445 ast_sockaddr_stringify(&addr),
11446 iaxs[fr->callno]->exten,
11447 iaxs[fr->callno]->context);
11448 memset(&ied0, 0, sizeof(ied0));
11449 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11450 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11451 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11452 if (!iaxs[fr->callno]) {
11453 break;
11454 }
11455 } else {
11456 /* Select an appropriate format */
11457 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11458 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11459 using_prefs = "reqonly";
11460 } else {
11461 using_prefs = "disabled";
11462 }
11463 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11464 memset(&pref, 0, sizeof(pref));
11465 strcpy(caller_pref_buf, "disabled");
11466 strcpy(host_pref_buf, "disabled");
11467 } else {
11468 struct ast_format *tmpfmt;
11469 using_prefs = "mine";
11470 if (ies.codec_prefs)
11471 iax2_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11472 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11473 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11474 pref = iaxs[fr->callno]->rprefs;
11475 using_prefs = "caller";
11476 } else {
11477 pref = iaxs[fr->callno]->prefs;
11478 }
11479 } else /* if no codec_prefs IE do it the old way */
11480 pref = iaxs[fr->callno]->prefs;
11481 format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11482 iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11483 iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11484 }
11485 if (!format) {
11486 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11487 struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11488 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11489
11490 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11491 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11492 iax2_getformatname(iaxs[fr->callno]->peerformat),
11493 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf));
11494 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11495 }
11496 if (!format) {
11497 if (authdebug) {
11498 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11499 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11500 ast_sockaddr_stringify(&addr),
11501 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11502 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11503 } else {
11504 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11505 ast_sockaddr_stringify(&addr),
11506 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11507 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11508 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11509 }
11510 }
11511 memset(&ied0, 0, sizeof(ied0));
11512 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11513 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11514 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11515 if (!iaxs[fr->callno]) {
11516 break;
11517 }
11518 } else {
11519 /* Pick one... */
11520 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11521 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11522 format = 0;
11523 } else {
11524 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11525 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11526 memset(&pref, 0, sizeof(pref));
11527 format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)
11528 ? iaxs[fr->callno]->peerformat
11529 : iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11530 strcpy(caller_pref_buf,"disabled");
11531 strcpy(host_pref_buf,"disabled");
11532 } else {
11533 struct ast_format *tmpfmt;
11534 using_prefs = "mine";
11535 if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11536 /* Do the opposite of what we tried above. */
11537 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11538 pref = iaxs[fr->callno]->prefs;
11539 } else {
11540 pref = iaxs[fr->callno]->rprefs;
11541 using_prefs = "caller";
11542 }
11543 format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11544 } else /* if no codec_prefs IE do it the old way */
11545 format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11546 }
11547 }
11548 if (!format) {
11549 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11550 struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11551 struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11552
11553 ast_log(LOG_ERROR, "No best format in %s???\n",
11554 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11555 if (authdebug) {
11556 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11557 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11558 ast_sockaddr_stringify(&addr),
11559 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11560 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11561 } else {
11562 ast_log(LOG_WARNING, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11563 ast_sockaddr_stringify(&addr),
11564 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11565 iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11566 iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11567 }
11568 }
11569 memset(&ied0, 0, sizeof(ied0));
11570 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11571 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11572 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11573 if (!iaxs[fr->callno]) {
11574 break;
11575 }
11576 }
11577 }
11578 }
11579 if (format) {
11580 /* Authentication received */
11581 memset(&ied1, 0, sizeof(ied1));
11582 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11583 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11584 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11585 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11586 char authmethodnames[AUTH_METHOD_NAMES_BUFSIZE];
11587 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11588 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11589 "%srequested auth methods = (%s),\n"
11590 "%sactual auth method = %s,\n"
11591 "%sencrypted = %s,\n"
11592 "%srequested format = %s,\n"
11593 "%srequested prefs = %s,\n"
11594 "%sactual format = %s,\n"
11595 "%shost prefs = %s,\n"
11596 "%spriority = %s\n",
11597 ast_sockaddr_stringify(&addr),
11598 VERBOSE_PREFIX_4,
11599 auth_method_names(iaxs[fr->callno]->authmethods, authmethodnames),
11600 VERBOSE_PREFIX_4,
11601 auth_method_labels[iaxs[fr->callno]->eff_auth_method],
11602 VERBOSE_PREFIX_4,
11603 IAX_CALLENCRYPTED(iaxs[fr->callno]) ? "yes" : "no",
11604 VERBOSE_PREFIX_4,
11605 iax2_getformatname(iaxs[fr->callno]->peerformat),
11606 VERBOSE_PREFIX_4,
11607 caller_pref_buf,
11608 VERBOSE_PREFIX_4,
11609 iax2_getformatname(format),
11610 VERBOSE_PREFIX_4,
11611 host_pref_buf,
11612 VERBOSE_PREFIX_4,
11613 using_prefs);
11614
11615 /* Unlike unauthenticated calls, we don't need to store
11616 * the chosen format for channel creation.
11617 * However, this is helpful for __get_from_jb. */
11618 iaxs[fr->callno]->chosenformat = format;
11619
11620 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11621 c = ast_iax2_new(fr->callno, AST_STATE_RING, format,
11622 &iaxs[fr->callno]->rprefs, NULL, NULL, 1);
11623 if (!c) {
11624 iax2_destroy(fr->callno);
11625 } else if (ies.vars) {
11626 struct ast_datastore *variablestore;
11627 struct ast_variable *var, *prev = NULL;
11628 AST_LIST_HEAD(, ast_var_t) *varlist;
11629 varlist = ast_calloc(1, sizeof(*varlist));
11630 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11631 if (variablestore && varlist) {
11632 variablestore->data = varlist;
11633 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11634 AST_LIST_HEAD_INIT(varlist);
11635 ast_debug(1, "I can haz IAX vars? w00t\n");
11636 for (var = ies.vars; var; var = var->next) {
11637 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11638 if (prev)
11639 ast_free(prev);
11640 prev = var;
11641 if (!newvar) {
11642 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11643 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11644 } else {
11645 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11646 }
11647 }
11648 if (prev)
11649 ast_free(prev);
11650 ies.vars = NULL;
11651 ast_channel_datastore_add(c, variablestore);
11652 } else {
11653 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11654 if (variablestore)
11655 ast_datastore_free(variablestore);
11656 if (varlist)
11657 ast_free(varlist);
11658 }
11659 }
11660 } else {
11661 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11662 /* If this is a TBD call, we're ready but now what... */
11663 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_sockaddr_stringify(&addr));
11664 if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11665 goto immediatedial;
11666 }
11667 }
11668 }
11669 }
11670 break;
11671 case IAX_COMMAND_DIAL:
11672 immediatedial:
11673 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11674 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11675 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11676 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11677 if (authdebug)
11678 ast_log(LOG_WARNING, "Rejected dial attempt from %s, request '%s@%s' does not exist\n",
11679 ast_sockaddr_stringify(&addr),
11680 iaxs[fr->callno]->exten,
11681 iaxs[fr->callno]->context);
11682 memset(&ied0, 0, sizeof(ied0));
11683 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11684 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11685 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11686 if (!iaxs[fr->callno]) {
11687 break;
11688 }
11689 } else {
11690 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11691 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11692 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11693 ast_sockaddr_stringify(&addr),
11694 iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &cap_buf));
11695 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11696 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11697 c = ast_iax2_new(fr->callno, AST_STATE_RING,
11698 iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11699 NULL, NULL, 1);
11700 if (!c) {
11701 iax2_destroy(fr->callno);
11702 } else if (ies.vars) {
11703 struct ast_datastore *variablestore;
11704 struct ast_variable *var, *prev = NULL;
11705 AST_LIST_HEAD(, ast_var_t) *varlist;
11706 varlist = ast_calloc(1, sizeof(*varlist));
11707 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11708 ast_debug(1, "I can haz IAX vars? w00t\n");
11709 if (variablestore && varlist) {
11710 variablestore->data = varlist;
11711 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11712 AST_LIST_HEAD_INIT(varlist);
11713 for (var = ies.vars; var; var = var->next) {
11714 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11715 if (prev)
11716 ast_free(prev);
11717 prev = var;
11718 if (!newvar) {
11719 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11720 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11721 } else {
11722 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11723 }
11724 }
11725 if (prev)
11726 ast_free(prev);
11727 ies.vars = NULL;
11728 ast_channel_datastore_add(c, variablestore);
11729 } else {
11730 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11731 if (variablestore)
11732 ast_datastore_free(variablestore);
11733 if (varlist)
11734 ast_free(varlist);
11735 }
11736 }
11737 }
11738 }
11739 break;
11740 case IAX_COMMAND_INVAL:
11741 iaxs[fr->callno]->error = ENOTCONN;
11742 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11743 iax2_destroy(fr->callno);
11744 ast_debug(1, "Destroying call %d\n", fr->callno);
11745 break;
11746 case IAX_COMMAND_VNAK:
11747 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11748 /* Force retransmission */
11749 vnak_retransmit(fr->callno, fr->iseqno);
11750 break;
11751 case IAX_COMMAND_REGREQ:
11752 case IAX_COMMAND_REGREL:
11753 /* For security, always ack immediately */
11754 if (delayreject)
11755 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11756 if (register_verify(fr->callno, &addr, &ies)) {
11757 if (!iaxs[fr->callno]) {
11758 break;
11759 }
11760 /* Send delayed failure */
11761 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11762 break;
11763 }
11764 if (!iaxs[fr->callno]) {
11765 break;
11766 }
11767 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11768 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11769
11770 if (f.subclass.integer == IAX_COMMAND_REGREL) {
11771 ast_sockaddr_setnull(&addr);
11772 }
11773 if (update_registry(&addr, fr->callno, ies.devicetype, fd, ies.refresh)) {
11774 ast_log(LOG_WARNING, "Registry error\n");
11775 }
11776 if (!iaxs[fr->callno]) {
11777 break;
11778 }
11779 if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
11780 ast_mutex_unlock(&iaxsl[fr->callno]);
11781 check_provisioning(&addr, fd, ies.serviceident, ies.provver);
11782 ast_mutex_lock(&iaxsl[fr->callno]);
11783 }
11784 break;
11785 }
11786 registry_authrequest(fr->callno);
11787 break;
11788 case IAX_COMMAND_REGACK:
11789 if (iax2_ack_registry(&ies, &addr, fr->callno)) {
11790 ast_log(LOG_WARNING, "Registration failure\n");
11791 }
11792 /* Send ack immediately, before we destroy */
11793 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11794 iax2_destroy(fr->callno);
11795 break;
11796 case IAX_COMMAND_REGREJ:
11797 if (iaxs[fr->callno]->reg) {
11798 if (authdebug) {
11799 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n",
11800 iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>",
11801 ast_sockaddr_stringify(&addr));
11802 }
11803 iax2_publish_registry(iaxs[fr->callno]->reg->username, ast_sockaddr_stringify(&addr), "Rejected", S_OR(ies.cause, "<unknown>"));
11804 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11805 }
11806 /* Send ack immediately, before we destroy */
11807 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11808 iax2_destroy(fr->callno);
11809 break;
11810 case IAX_COMMAND_REGAUTH:
11811 /* Authentication request */
11812 if (registry_rerequest(&ies, fr->callno, &addr)) {
11813 memset(&ied0, 0, sizeof(ied0));
11814 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11815 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11816 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11817 }
11818 break;
11819 case IAX_COMMAND_TXREJ:
11820 while (iaxs[fr->callno]
11821 && iaxs[fr->callno]->bridgecallno
11822 && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11823 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11824 }
11825 if (!iaxs[fr->callno]) {
11826 break;
11827 }
11828
11829 iaxs[fr->callno]->transferring = TRANSFER_NONE;
11830 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11831 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11832
11833 if (!iaxs[fr->callno]->bridgecallno) {
11834 break;
11835 }
11836
11837 if (iaxs[iaxs[fr->callno]->bridgecallno]
11838 && iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11839 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
11840 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11841 }
11842 ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11843 break;
11844 case IAX_COMMAND_TXREADY:
11845 while (iaxs[fr->callno]
11846 && iaxs[fr->callno]->bridgecallno
11847 && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11848 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11849 }
11850 if (!iaxs[fr->callno]) {
11851 break;
11852 }
11853
11854 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11855 iaxs[fr->callno]->transferring = TRANSFER_READY;
11856 } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11857 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11858 } else {
11859 if (iaxs[fr->callno]->bridgecallno) {
11860 ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11861 }
11862 break;
11863 }
11864 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11865
11866 if (!iaxs[fr->callno]->bridgecallno) {
11867 break;
11868 }
11869
11870 if (!iaxs[iaxs[fr->callno]->bridgecallno]
11871 || (iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_READY
11872 && iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_MREADY)) {
11873 ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11874 break;
11875 }
11876
11877 /* Both sides are ready */
11878
11879 /* XXX what isn't checked here is that both sides match transfer types. */
11880
11881 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11882 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11883 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11884
11885 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11886 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11887
11888 memset(&ied0, 0, sizeof(ied0));
11889 memset(&ied1, 0, sizeof(ied1));
11890 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11891 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11892 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11893 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11894 } else {
11895 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11896 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11897
11898 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11899 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11900 ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11901 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11902
11903 /* Stop doing lag & ping requests */
11904 stop_stuff(fr->callno);
11905 stop_stuff(iaxs[fr->callno]->bridgecallno);
11906
11907 memset(&ied0, 0, sizeof(ied0));
11908 memset(&ied1, 0, sizeof(ied1));
11909 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11910 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11911 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11912 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11913 }
11914 ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11915 break;
11916 case IAX_COMMAND_TXREQ:
11917 try_transfer(iaxs[fr->callno], &ies);
11918 break;
11919 case IAX_COMMAND_TXCNT:
11920 if (iaxs[fr->callno]->transferring)
11921 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11922 break;
11923 case IAX_COMMAND_TXREL:
11924 /* Send ack immediately, rather than waiting until we've changed addresses */
11925 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11926 complete_transfer(fr->callno, &ies);
11927 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11928 break;
11929 case IAX_COMMAND_TXMEDIA:
11930 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11931 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11932 /* Cancel any outstanding frames and start anew */
11933 if (cur->transfer) {
11934 cur->retries = -1;
11935 }
11936 }
11937 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11938 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11939 }
11940 break;
11941 case IAX_COMMAND_RTKEY:
11942 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11943 ast_log(LOG_WARNING,
11944 "we've been told to rotate our encryption key, "
11945 "but this isn't an encrypted call. bad things will happen.\n"
11946 );
11947 break;
11948 }
11949
11950 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11951
11952 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11953 break;
11954 case IAX_COMMAND_DPREP:
11955 complete_dpreply(iaxs[fr->callno], &ies);
11956 break;
11957 case IAX_COMMAND_UNSUPPORT:
11958 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11959 break;
11960 case IAX_COMMAND_FWDOWNL:
11961 /* Firmware download */
11962 if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11963 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11964 break;
11965 }
11966 memset(&ied0, 0, sizeof(ied0));
11967 res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
11968 if (res < 0)
11969 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11970 else if (res > 0)
11971 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11972 else
11973 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11974 break;
11975 case IAX_COMMAND_CALLTOKEN:
11976 {
11977 struct iax_frame *cur;
11978 /* find last sent frame */
11979 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11980 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11981 }
11982 break;
11983 }
11984 default:
11985 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11986 memset(&ied0, 0, sizeof(ied0));
11987 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11988 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11989 }
11990 /* Free remote variables (if any) */
11991 if (ies.vars) {
11992 ast_variables_destroy(ies.vars);
11993 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11994 ies.vars = NULL;
11995 }
11996
11997 /* Don't actually pass these frames along */
11998 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11999 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
12000 (f.subclass.integer != IAX_COMMAND_TXACC) &&
12001 (f.subclass.integer != IAX_COMMAND_INVAL) &&
12002 (f.subclass.integer != IAX_COMMAND_VNAK)) {
12003 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
12004 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
12005 }
12006 }
12007 ast_mutex_unlock(&iaxsl[fr->callno]);
12008 return 1;
12009 }
12010 /* Unless this is an ACK or INVAL frame, ack it */
12011 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
12012 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
12013 } else if (minivid) {
12014 f.frametype = AST_FRAME_VIDEO;
12015 if (iaxs[fr->callno]->videoformat > 0) {
12016 if (ntohs(vh->ts) & 0x8000LL) {
12017 f.subclass.frame_ending = 1;
12018 }
12019 f.subclass.format = ast_format_compatibility_bitfield2format(iaxs[fr->callno]->videoformat);
12020 if (!f.subclass.format) {
12021 ast_variables_destroy(ies.vars);
12022 ast_mutex_unlock(&iaxsl[fr->callno]);
12023 return 1;
12024 }
12025 } else {
12026 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
12027 iax2_vnak(fr->callno);
12028 ast_variables_destroy(ies.vars);
12029 ast_mutex_unlock(&iaxsl[fr->callno]);
12030 return 1;
12031 }
12032 f.datalen = res - sizeof(*vh);
12033 if (f.datalen < 0) {
12034 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12035 ast_variables_destroy(ies.vars);
12036 ast_mutex_unlock(&iaxsl[fr->callno]);
12037 return 1;
12038 }
12039 if (f.datalen)
12040 f.data.ptr = thread->buf + sizeof(*vh);
12041 else
12042 f.data.ptr = NULL;
12043 #ifdef IAXTESTS
12044 if (test_resync) {
12045 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
12046 } else
12047 #endif /* IAXTESTS */
12048 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
12049 } else {
12050 /* A mini frame */
12051 f.frametype = AST_FRAME_VOICE;
12052 if (iaxs[fr->callno]->voiceformat > 0) {
12053 f.subclass.format = ast_format_compatibility_bitfield2format(iaxs[fr->callno]->voiceformat);
12054 if (!f.subclass.format) {
12055 ast_variables_destroy(ies.vars);
12056 ast_mutex_unlock(&iaxsl[fr->callno]);
12057 return 1;
12058 }
12059 } else {
12060 ast_debug(1, "Received mini frame before first full voice frame\n");
12061 iax2_vnak(fr->callno);
12062 ast_variables_destroy(ies.vars);
12063 ast_mutex_unlock(&iaxsl[fr->callno]);
12064 return 1;
12065 }
12066 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
12067 if (f.datalen < 0) {
12068 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12069 ast_variables_destroy(ies.vars);
12070 ast_mutex_unlock(&iaxsl[fr->callno]);
12071 return 1;
12072 }
12073 if (f.datalen)
12074 f.data.ptr = thread->buf + sizeof(*mh);
12075 else
12076 f.data.ptr = NULL;
12077 #ifdef IAXTESTS
12078 if (test_resync) {
12079 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
12080 } else
12081 #endif /* IAXTESTS */
12082 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
12083 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
12084 }
12085
12086 /* Don't pass any packets until we're started */
12087 if (!iaxs[fr->callno]
12088 || !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
12089 ast_variables_destroy(ies.vars);
12090 ast_mutex_unlock(&iaxsl[fr->callno]);
12091 return 1;
12092 }
12093
12094 if (f.frametype == AST_FRAME_CONTROL) {
12095 if (!iax2_is_control_frame_allowed(f.subclass.integer)) {
12096 /* Control frame not allowed to come from the wire. */
12097 ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
12098 fr->callno, f.subclass.integer);
12099 ast_variables_destroy(ies.vars);
12100 ast_mutex_unlock(&iaxsl[fr->callno]);
12101 return 1;
12102 }
12103 if (f.subclass.integer == AST_CONTROL_CONNECTED_LINE
12104 || f.subclass.integer == AST_CONTROL_REDIRECTING) {
12105 if (iaxs[fr->callno]
12106 && !ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
12107 /* We are not configured to allow receiving these updates. */
12108 ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
12109 fr->callno, f.subclass.integer);
12110 ast_variables_destroy(ies.vars);
12111 ast_mutex_unlock(&iaxsl[fr->callno]);
12112 return 1;
12113 }
12114 }
12115
12116 iax2_lock_owner(fr->callno);
12117 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12118 if (f.subclass.integer == AST_CONTROL_BUSY) {
12119 ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_BUSY);
12120 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
12121 ast_channel_hangupcause_set(iaxs[fr->callno]->owner, AST_CAUSE_CONGESTION);
12122 }
12123 ast_channel_unlock(iaxs[fr->callno]->owner);
12124 }
12125 }
12126
12127 if (f.frametype == AST_FRAME_CONTROL
12128 && f.subclass.integer == AST_CONTROL_CONNECTED_LINE
12129 && iaxs[fr->callno]) {
12130 struct ast_party_connected_line connected;
12131
12132 /*
12133 * Process a received connected line update.
12134 *
12135 * Initialize defaults.
12136 */
12137 ast_party_connected_line_init(&connected);
12138 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
12139 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
12140
12141 if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
12142 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
12143 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
12144 iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
12145
12146 iax2_lock_owner(fr->callno);
12147 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
12148 ast_set_callerid(iaxs[fr->callno]->owner,
12149 S_COR(connected.id.number.valid, connected.id.number.str, ""),
12150 S_COR(connected.id.name.valid, connected.id.name.str, ""),
12151 NULL);
12152 ast_channel_caller(iaxs[fr->callno]->owner)->id.number.presentation = connected.id.number.presentation;
12153 ast_channel_caller(iaxs[fr->callno]->owner)->id.name.presentation = connected.id.name.presentation;
12154 ast_channel_unlock(iaxs[fr->callno]->owner);
12155 }
12156 }
12157 ast_party_connected_line_free(&connected);
12158 }
12159
12160 /* Common things */
12161 f.src = "IAX2";
12162 f.mallocd = 0;
12163 f.offset = 0;
12164 f.len = 0;
12165 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
12166 f.samples = ast_codec_samples_count(&f);
12167 /* We need to byteswap incoming slinear samples from network byte order */
12168 if (ast_format_cmp(f.subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL)
12169 ast_frame_byteswap_be(&f);
12170 } else
12171 f.samples = 0;
12172
12173 if (f.datalen < 0) {
12174 ast_log(LOG_ERROR, "Dropping malformed frame (datalen %d?)\n", f.datalen);
12175 ast_variables_destroy(ies.vars);
12176 ast_mutex_unlock(&iaxsl[fr->callno]);
12177 return 1;
12178 }
12179
12180 iax_frame_wrap(fr, &f);
12181
12182 /* If this is our most recent packet, use it as our basis for timestamping */
12183 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12184 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
12185 fr->outoforder = 0;
12186 } else {
12187 if (iaxdebug && iaxs[fr->callno]) {
12188 ast_debug(1, "Received out of order packet... (type=%u, subclass %d, ts = %u, last = %u)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
12189 }
12190 fr->outoforder = 1;
12191 }
12192 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
12193 if (iaxs[fr->callno]) {
12194 duped_fr = iaxfrdup2(fr);
12195 if (duped_fr) {
12196 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
12197 }
12198 }
12199 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
12200 iaxs[fr->callno]->last = fr->ts;
12201 #if 1
12202 if (iaxdebug)
12203 ast_debug(8, "For call=%d, set last=%u\n", fr->callno, fr->ts);
12204 #endif
12205 }
12206
12207 /* Always run again */
12208 ast_variables_destroy(ies.vars);
12209 ast_mutex_unlock(&iaxsl[fr->callno]);
12210 return 1;
12211 }
12212
12213 static int socket_process(struct iax2_thread *thread)
12214 {
12215 int res = socket_process_helper(thread);
12216 if (ast_read_threadstorage_callid()) {
12217 ast_callid_threadassoc_remove();
12218 }
12219 return res;
12220 }
12221
12222 /* Function to clean up process thread if it is cancelled */
12223 static void iax2_process_thread_cleanup(void *data)
12224 {
12225 struct iax2_thread *thread = data;
12226 ast_mutex_destroy(&thread->lock);
12227 ast_cond_destroy(&thread->cond);
12228 ast_mutex_destroy(&thread->init_lock);
12229 ast_cond_destroy(&thread->init_cond);
12230 ast_free(thread);
12231 /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
12232 ast_atomic_dec_and_test(&iaxactivethreadcount);
12233 }
12234
12235 static void *iax2_process_thread(void *data)
12236 {
12237 struct iax2_thread *thread = data;
12238 struct timeval wait;
12239 struct timespec ts;
12240 int put_into_idle = 0;
12241 int first_time = 1;
12242 int old_state;
12243
12244 ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
12245
12246 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12247 pthread_cleanup_push(iax2_process_thread_cleanup, data);
12248
12249 for (;;) {
12250 /* Wait for something to signal us to be awake */
12251 ast_mutex_lock(&thread->lock);
12252
12253 if (thread->stop) {
12254 ast_mutex_unlock(&thread->lock);
12255 break;
12256 }
12257
12258 /* Flag that we're ready to accept signals */
12259 if (first_time) {
12260 signal_condition(&thread->init_lock, &thread->init_cond);
12261 first_time = 0;
12262 }
12263
12264 /* Put into idle list if applicable */
12265 if (put_into_idle) {
12266 insert_idle_thread(thread);
12267 }
12268
12269 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12270 struct iax2_thread *t = NULL;
12271 /* Wait to be signalled or time out */
12272 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12273 ts.tv_sec = wait.tv_sec;
12274 ts.tv_nsec = wait.tv_usec * 1000;
12275 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12276 /* This thread was never put back into the available dynamic
12277 * thread list, so just go away. */
12278 if (!put_into_idle || thread->stop) {
12279 ast_mutex_unlock(&thread->lock);
12280 break;
12281 }
12282 AST_LIST_LOCK(&dynamic_list);
12283 /* Account for the case where this thread is acquired *right* after a timeout */
12284 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
12285 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
12286 AST_LIST_UNLOCK(&dynamic_list);
12287 if (t) {
12288 /* This dynamic thread timed out waiting for a task and was
12289 * not acquired immediately after the timeout,
12290 * so it's time to go away. */
12291 ast_mutex_unlock(&thread->lock);
12292 break;
12293 }
12294 /* Someone grabbed our thread *right* after we timed out.
12295 * Wait for them to set us up with something to do and signal
12296 * us to continue. */
12297 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12298 ts.tv_sec = wait.tv_sec;
12299 ts.tv_nsec = wait.tv_usec * 1000;
12300 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12301 ast_mutex_unlock(&thread->lock);
12302 break;
12303 }
12304 }
12305 } else {
12306 ast_cond_wait(&thread->cond, &thread->lock);
12307 }
12308
12309 /* Go back into our respective list */
12310 put_into_idle = 1;
12311
12312 ast_mutex_unlock(&thread->lock);
12313
12314 if (thread->stop) {
12315 break;
12316 }
12317
12318 /* See what we need to do */
12319 switch (thread->iostate) {
12320 case IAX_IOSTATE_IDLE:
12321 continue;
12322 case IAX_IOSTATE_READY:
12323 thread->actions++;
12324 thread->iostate = IAX_IOSTATE_PROCESSING;
12325 socket_process(thread);
12326 handle_deferred_full_frames(thread);
12327 break;
12328 case IAX_IOSTATE_SCHEDREADY:
12329 thread->actions++;
12330 thread->iostate = IAX_IOSTATE_PROCESSING;
12331 #ifdef SCHED_MULTITHREADED
12332 thread->schedfunc(thread->scheddata);
12333 #endif
12334 break;
12335 default:
12336 break;
12337 }
12338
12339 /* The network thread added us to the active_thread list when we were given
12340 * frames to process, Now that we are done, we must remove ourselves from
12341 * the active list, and return to the idle list */
12342 AST_LIST_LOCK(&active_list);
12343 AST_LIST_REMOVE(&active_list, thread, list);
12344 AST_LIST_UNLOCK(&active_list);
12345
12346 /* Make sure another frame didn't sneak in there after we thought we were done. */
12347 handle_deferred_full_frames(thread);
12348
12349 time(&thread->checktime);
12350 thread->iostate = IAX_IOSTATE_IDLE;
12351 #ifdef DEBUG_SCHED_MULTITHREAD
12352 thread->curfunc[0]='\0';
12353 #endif
12354 }
12355
12356 /*!
12357 * \note For some reason, idle threads are exiting without being
12358 * removed from an idle list, which is causing memory
12359 * corruption. Forcibly remove it from the list, if it's there.
12360 */
12361 AST_LIST_LOCK(&idle_list);
12362 AST_LIST_REMOVE(&idle_list, thread, list);
12363 AST_LIST_UNLOCK(&idle_list);
12364
12365 AST_LIST_LOCK(&dynamic_list);
12366 AST_LIST_REMOVE(&dynamic_list, thread, list);
12367 AST_LIST_UNLOCK(&dynamic_list);
12368
12369 if (!thread->stop) {
12370 /* Nobody asked me to stop so nobody is waiting to join me. */
12371 pthread_detach(pthread_self());
12372 }
12373
12374 /* I am exiting here on my own volition, I need to clean up my own data structures
12375 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12376 */
12377 pthread_cleanup_pop(1);
12378 return NULL;
12379 }
12380
12381 static int iax2_do_register(struct iax2_registry *reg)
12382 {
12383 struct iax_ie_data ied;
12384 if (iaxdebug)
12385 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12386
12387 if (reg->dnsmgr &&
12388 ((reg->regstate == REG_STATE_TIMEOUT) || ast_sockaddr_isnull(&reg->addr))) {
12389 /* Maybe the IP has changed, force DNS refresh */
12390 ast_dnsmgr_refresh(reg->dnsmgr);
12391 }
12392
12393 /*
12394 * if IP has Changed, free allocated call to create a new one with new IP
12395 * call has the pointer to IP and must be updated to the new one
12396 */
12397 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12398 int callno = reg->callno;
12399 ast_mutex_lock(&iaxsl[callno]);
12400 iax2_destroy(callno);
12401 ast_mutex_unlock(&iaxsl[callno]);
12402 reg->callno = 0;
12403 }
12404 if (ast_sockaddr_isnull(&reg->addr)) {
12405 if (iaxdebug)
12406 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12407 /* Setup the next registration attempt */
12408 reg->expire = iax2_sched_replace(reg->expire, sched,
12409 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12410 return -1;
12411 }
12412 if (!ast_sockaddr_port(&reg->addr) && reg->port) {
12413 ast_sockaddr_set_port(&reg->addr, reg->port);
12414 }
12415
12416 if (!reg->callno) {
12417
12418 ast_debug(3, "Allocate call number\n");
12419
12420 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
12421 if (reg->callno < 1) {
12422 ast_log(LOG_WARNING, "Unable to create call for registration\n");
12423 return -1;
12424 } else
12425 ast_debug(3, "Registration created on call %d\n", reg->callno);
12426 iaxs[reg->callno]->reg = reg;
12427 ast_mutex_unlock(&iaxsl[reg->callno]);
12428 }
12429 /* Setup the next registration a little early */
12430 reg->expire = iax2_sched_replace(reg->expire, sched,
12431 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12432 /* Send the request */
12433 memset(&ied, 0, sizeof(ied));
12434 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
12435 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
12436 add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12437 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
12438 reg->regstate = REG_STATE_REGSENT;
12439 return 0;
12440 }
12441
12442 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
12443 {
12444 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12445 is found for template */
12446 struct iax_ie_data provdata;
12447 struct iax_ie_data ied;
12448 unsigned int sig;
12449 struct ast_sockaddr addr;
12450 int callno;
12451 struct create_addr_info cai;
12452
12453 memset(&cai, 0, sizeof(cai));
12454
12455 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12456
12457 if (iax_provision_build(&provdata, &sig, template, force)) {
12458 ast_debug(1, "No provisioning found for template '%s'\n", template);
12459 return 0;
12460 }
12461
12462 if (end) {
12463 ast_sockaddr_copy(&addr, end);
12464 cai.sockfd = sockfd;
12465 } else if (create_addr(dest, NULL, &addr, &cai))
12466 return -1;
12467
12468 /* Build the rest of the message */
12469 memset(&ied, 0, sizeof(ied));
12470 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12471
12472 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12473 if (!callno)
12474 return -1;
12475
12476 if (iaxs[callno]) {
12477 /* Schedule autodestruct in case they don't ever give us anything back */
12478 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12479 sched, 15000, auto_hangup, (void *)(long)callno);
12480 ast_set_flag64(iaxs[callno], IAX_PROVISION);
12481 /* Got a call number now, so go ahead and send the provisioning information */
12482 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12483 }
12484 ast_mutex_unlock(&iaxsl[callno]);
12485
12486 return 1;
12487 }
12488
12489 static char *papp = "IAX2Provision";
12490
12491 /*! iax2provision
12492 \ingroup applications
12493 */
12494 static int iax2_prov_app(struct ast_channel *chan, const char *data)
12495 {
12496 int res;
12497 char *sdata;
12498 char *opts;
12499 int force =0;
12500 unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12501 if (ast_strlen_zero(data))
12502 data = "default";
12503 sdata = ast_strdupa(data);
12504 opts = strchr(sdata, '|');
12505 if (opts)
12506 *opts='\0';
12507
12508 if (ast_channel_tech(chan) != &iax2_tech) {
12509 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12510 return -1;
12511 }
12512 if (!callno || !iaxs[callno] || ast_sockaddr_isnull(&iaxs[callno]->addr)) {
12513 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12514 return -1;
12515 }
12516 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12517 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12518 ast_sockaddr_stringify(&iaxs[callno]->addr),
12519 sdata, res);
12520 return res;
12521 }
12522
12523 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12524 {
12525 int force = 0;
12526 int res;
12527
12528 switch (cmd) {
12529 case CLI_INIT:
12530 e->command = "iax2 provision";
12531 e->usage =
12532 "Usage: iax2 provision <host> <template> [forced]\n"
12533 " Provisions the given peer or IP address using a template\n"
12534 " matching either 'template' or '*' if the template is not\n"
12535 " found. If 'forced' is specified, even empty provisioning\n"
12536 " fields will be provisioned as empty fields.\n";
12537 return NULL;
12538 case CLI_GENERATE:
12539 if (a->pos == 3)
12540 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12541 return NULL;
12542 }
12543
12544 if (a->argc < 4)
12545 return CLI_SHOWUSAGE;
12546 if (a->argc > 4) {
12547 if (!strcasecmp(a->argv[4], "forced"))
12548 force = 1;
12549 else
12550 return CLI_SHOWUSAGE;
12551 }
12552 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12553 if (res < 0)
12554 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12555 else if (res < 1)
12556 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12557 else
12558 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12559 return CLI_SUCCESS;
12560 }
12561
12562 static void __iax2_poke_noanswer(const void *data)
12563 {
12564 struct iax2_peer *peer = (struct iax2_peer *)data;
12565 int callno;
12566
12567 if (peer->lastms > -1) {
12568 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12569
12570 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12571 ast_endpoint_set_state(peer->endpoint, AST_ENDPOINT_OFFLINE);
12572 blob = ast_json_pack("{s: s, s: i}",
12573 "peer_status", "Unreachable",
12574 "time", peer->lastms);
12575 ast_endpoint_blob_publish(peer->endpoint, ast_endpoint_state_type(), blob);
12576 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12577 }
12578 if ((callno = peer->callno) > 0) {
12579 ast_mutex_lock(&iaxsl[callno]);
12580 iax2_destroy(callno);
12581 ast_mutex_unlock(&iaxsl[callno]);
12582 }
12583 peer->callno = 0;
12584 peer->lastms = -1;
12585 /* Try again quickly */
12586 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12587 if (peer->pokeexpire == -1)
12588 peer_unref(peer);
12589 }
12590
12591 static int iax2_poke_noanswer(const void *data)
12592 {
12593 struct iax2_peer *peer = (struct iax2_peer *)data;
12594 peer->pokeexpire = -1;
12595 #ifdef SCHED_MULTITHREADED
12596 if (schedule_action(__iax2_poke_noanswer, data))
12597 #endif
12598 __iax2_poke_noanswer(data);
12599 peer_unref(peer);
12600 return 0;
12601 }
12602
12603 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12604 {
12605 struct iax2_peer *peer = obj;
12606
12607 iax2_poke_peer(peer, 0);
12608
12609 return 0;
12610 }
12611
12612 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12613 {
12614 int callno;
12615 int poke_timeout;
12616
12617 if (!peer->maxms || (ast_sockaddr_isnull(&peer->addr) && !peer->dnsmgr)) {
12618 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12619 immediately after clearing things out */
12620 peer->lastms = 0;
12621 peer->historicms = 0;
12622 peer->pokeexpire = -1;
12623 peer->callno = 0;
12624 return 0;
12625 }
12626
12627 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12628 if ((callno = peer->callno) > 0) {
12629 ast_log(LOG_NOTICE, "Still have a callno...\n");
12630 ast_mutex_lock(&iaxsl[callno]);
12631 iax2_destroy(callno);
12632 ast_mutex_unlock(&iaxsl[callno]);
12633 }
12634 if (heldcall)
12635 ast_mutex_unlock(&iaxsl[heldcall]);
12636 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
12637 if (heldcall)
12638 ast_mutex_lock(&iaxsl[heldcall]);
12639 if (callno < 1) {
12640 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12641 return -1;
12642 }
12643
12644 if (peer->pokeexpire > -1) {
12645 if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12646 peer->pokeexpire = -1;
12647 peer_unref(peer);
12648 }
12649 }
12650
12651 if (peer->lastms < 0){
12652 /* If the host is already unreachable then use time less than the unreachable
12653 * interval. 5/6 is arbitrary multiplier to get value less than
12654 * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
12655 * current POKE before starting new POKE (which is scheduled after
12656 * peer->pokefreqnotok). */
12657 poke_timeout = peer->pokefreqnotok * 5 / 6;
12658 } else {
12659 /* If the host is reachable, use timeout large enough to allow for multiple
12660 * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
12661 * multiplier to get value less than peer->pokefreqok. Value less than
12662 * peer->pokefreqok is used to expire current POKE before starting new POKE
12663 * (which is scheduled after peer->pokefreqok). */
12664 poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
12665 }
12666
12667 /* Queue up a new task to handle no reply */
12668 peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
12669
12670 if (peer->pokeexpire == -1)
12671 peer_unref(peer);
12672
12673 /* And send the poke */
12674 ast_mutex_lock(&iaxsl[callno]);
12675 if (iaxs[callno]) {
12676 struct iax_ie_data ied = {
12677 .buf = { 0 },
12678 .pos = 0,
12679 };
12680
12681 /* Speed up retransmission times for this qualify call */
12682 iaxs[callno]->pingtime = peer->maxms / 8;
12683 iaxs[callno]->peerpoke = peer;
12684
12685 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12686 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12687 }
12688 ast_mutex_unlock(&iaxsl[callno]);
12689
12690 return 0;
12691 }
12692
12693 static void free_context(struct iax2_context *con)
12694 {
12695 struct iax2_context *conl;
12696 while(con) {
12697 conl = con;
12698 con = con->next;
12699 ast_free(conl);
12700 }
12701 }
12702
12703 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)
12704 {
12705 int callno;
12706 int res;
12707 struct ast_sockaddr addr;
12708 struct ast_channel *c;
12709 struct parsed_dial_string pds;
12710 struct create_addr_info cai;
12711 char *tmpstr;
12712 ast_callid callid;
12713
12714 memset(&pds, 0, sizeof(pds));
12715 tmpstr = ast_strdupa(data);
12716 parse_dial_string(tmpstr, &pds);
12717
12718 callid = ast_read_threadstorage_callid();
12719
12720 if (ast_strlen_zero(pds.peer)) {
12721 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12722 return NULL;
12723 }
12724 memset(&cai, 0, sizeof(cai));
12725 cai.capability = iax2_capability;
12726
12727 ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12728
12729 /* Populate our address from the given */
12730 if (create_addr(pds.peer, NULL, &addr, &cai)) {
12731 *cause = AST_CAUSE_UNREGISTERED;
12732 return NULL;
12733 }
12734
12735 if (pds.port) {
12736 int bindport;
12737 ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535);
12738 ast_sockaddr_set_port(&addr, bindport);
12739 }
12740
12741 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12742 if (callno < 1) {
12743 ast_log(LOG_WARNING, "Unable to create call\n");
12744 *cause = AST_CAUSE_CONGESTION;
12745 return NULL;
12746 }
12747
12748 /* If this is a trunk, update it now */
12749 ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12750 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12751 int new_callno;
12752 if ((new_callno = make_trunk(callno, 1)) != -1)
12753 callno = new_callno;
12754 }
12755 iaxs[callno]->maxtime = cai.maxtime;
12756 if (callid) {
12757 iax_pvt_callid_set(callno, callid);
12758 }
12759
12760 if (cai.found) {
12761 ast_string_field_set(iaxs[callno], host, pds.peer);
12762 }
12763
12764 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, &cai.prefs, assignedids,
12765 requestor, cai.found);
12766
12767 ast_mutex_unlock(&iaxsl[callno]);
12768
12769 if (c) {
12770 struct ast_format_cap *joint;
12771 struct ast_format *format;
12772 if (callid) {
12773 ast_channel_lock(c);
12774 ast_channel_callid_set(c, callid);
12775 ast_channel_unlock(c);
12776 }
12777
12778 joint = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
12779 if (!joint) {
12780 ast_hangup(c);
12781 return NULL;
12782 }
12783
12784 ast_format_cap_get_compatible(ast_channel_nativeformats(c), cap, joint);
12785
12786 /* If there is no joint format find one through translation */
12787 if (!ast_format_cap_count(joint)) {
12788 struct ast_format *best_fmt_cap = NULL;
12789 struct ast_format *best_fmt_native = NULL;
12790
12791 res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12792 if (res < 0) {
12793 struct ast_str *native_cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12794 struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12795
12796 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12797 ast_format_cap_get_names(ast_channel_nativeformats(c), &native_cap_buf),
12798 ast_format_cap_get_names(cap, &cap_buf),
12799 ast_channel_name(c));
12800 ast_hangup(c);
12801 ao2_ref(joint, -1);
12802 return NULL;
12803 }
12804 ast_format_cap_append(joint, best_fmt_native, 0);
12805 ao2_ref(best_fmt_cap, -1);
12806 ao2_ref(best_fmt_native, -1);
12807 }
12808 ast_channel_nativeformats_set(c, joint);
12809 format = ast_format_cap_get_format(ast_channel_nativeformats(c), 0);
12810 ast_channel_set_readformat(c, format);
12811 ast_channel_set_writeformat(c, format);
12812
12813 ao2_ref(joint, -1);
12814 ao2_ref(format, -1);
12815 }
12816
12817 return c;
12818 }
12819
12820 static void *network_thread(void *ignore)
12821 {
12822 int res;
12823
12824 if (timer) {
12825 ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12826 }
12827
12828 for (;;) {
12829 pthread_testcancel();
12830 /* Wake up once a second just in case SIGURG was sent while
12831 * we weren't in poll(), to make sure we don't hang when trying
12832 * to unload. */
12833 res = ast_io_wait(io, 1000);
12834 /* Timeout(=0), and EINTR is not a thread exit condition. We do
12835 * not want to exit the thread loop on these conditions. */
12836 if (res < 0 && errno != -EINTR) {
12837 ast_log(LOG_ERROR, "IAX2 network thread unexpected exit: %s\n", strerror(errno));
12838 break;
12839 }
12840 }
12841
12842 return NULL;
12843 }
12844
12845 static int start_network_thread(void)
12846 {
12847 struct iax2_thread *thread;
12848 int threadcount = 0;
12849 int x;
12850 for (x = 0; x < iaxthreadcount; x++) {
12851 thread = ast_calloc(1, sizeof(*thread));
12852 if (thread) {
12853 thread->type = IAX_THREAD_TYPE_POOL;
12854 thread->threadnum = ++threadcount;
12855 ast_mutex_init(&thread->lock);
12856 ast_cond_init(&thread->cond, NULL);
12857 ast_mutex_init(&thread->init_lock);
12858 ast_cond_init(&thread->init_cond, NULL);
12859
12860 ast_mutex_lock(&thread->init_lock);
12861
12862 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12863 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12864 ast_mutex_destroy(&thread->lock);
12865 ast_cond_destroy(&thread->cond);
12866 ast_mutex_unlock(&thread->init_lock);
12867 ast_mutex_destroy(&thread->init_lock);
12868 ast_cond_destroy(&thread->init_cond);
12869 ast_free(thread);
12870 thread = NULL;
12871 continue;
12872 }
12873 /* Wait for the thread to be ready */
12874 ast_cond_wait(&thread->init_cond, &thread->init_lock);
12875
12876 /* Done with init_lock */
12877 ast_mutex_unlock(&thread->init_lock);
12878
12879 AST_LIST_LOCK(&idle_list);
12880 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12881 AST_LIST_UNLOCK(&idle_list);
12882 }
12883 }
12884 if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
12885 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12886 return -1;
12887 }
12888 ast_verb(2, "%d helper threads started\n", threadcount);
12889 return 0;
12890 }
12891
12892 static struct iax2_context *build_context(const char *context)
12893 {
12894 struct iax2_context *con;
12895
12896 if ((con = ast_calloc(1, sizeof(*con))))
12897 ast_copy_string(con->context, context, sizeof(con->context));
12898
12899 return con;
12900 }
12901
12902 static int get_auth_methods(const char *value)
12903 {
12904 int methods = 0;
12905 if (strstr(value, "rsa"))
12906 methods |= IAX_AUTH_RSA;
12907 if (strstr(value, "md5"))
12908 methods |= IAX_AUTH_MD5;
12909 if (strstr(value, "plaintext"))
12910 methods |= IAX_AUTH_PLAINTEXT;
12911 return methods;
12912 }
12913
12914
12915 /*! \brief Check if address can be used as packet source.
12916 \retval 0 address available
12917 \retval 1 address unavailable
12918 \retval -1 error
12919 */
12920 static int check_srcaddr(struct ast_sockaddr *addr)
12921 {
12922 int sd;
12923
12924 sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12925 if (sd < 0) {
12926 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12927 return -1;
12928 }
12929
12930 if (ast_bind(sd, addr) < 0) {
12931 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12932 close(sd);
12933 return 1;
12934 }
12935
12936 close(sd);
12937 return 0;
12938 }
12939
12940 /*! \brief Parse the "sourceaddress" value,
12941 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12942 not found. */
12943 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12944 {
12945 struct ast_sockaddr addr;
12946 int nonlocal = 1;
12947 int port = IAX_DEFAULT_PORTNO;
12948 int sockfd = defaultsockfd;
12949 char *tmp;
12950 char *host;
12951 char *portstr;
12952
12953 tmp = ast_strdupa(srcaddr);
12954 ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12955
12956 if (portstr) {
12957 port = atoi(portstr);
12958 if (port < 1)
12959 port = IAX_DEFAULT_PORTNO;
12960 }
12961
12962 addr.ss.ss_family = AST_AF_UNSPEC;
12963 if (!ast_get_ip(&addr, host)) {
12964 struct ast_netsock *sock;
12965
12966 if (check_srcaddr(&addr) == 0) {
12967 /* ip address valid. */
12968 ast_sockaddr_set_port(&addr, port);
12969
12970 if (!(sock = ast_netsock_find(netsock, &addr)))
12971 sock = ast_netsock_find(outsock, &addr);
12972 if (sock) {
12973 sockfd = ast_netsock_sockfd(sock);
12974 nonlocal = 0;
12975 } else {
12976 /* INADDR_ANY matches anyway! */
12977 ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12978 ast_sockaddr_set_port(&addr, port);
12979 if (ast_netsock_find(netsock, &addr)) {
12980 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12981 if (sock) {
12982 sockfd = ast_netsock_sockfd(sock);
12983 ast_netsock_unref(sock);
12984 nonlocal = 0;
12985 } else {
12986 nonlocal = 2;
12987 }
12988 }
12989 }
12990 }
12991 }
12992
12993 peer->sockfd = sockfd;
12994
12995 if (nonlocal == 1) {
12996 ast_log(LOG_WARNING,
12997 "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12998 srcaddr,
12999 peer->name);
13000 return -1;
13001 } else if (nonlocal == 2) {
13002 ast_log(LOG_WARNING,
13003 "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
13004 srcaddr,
13005 peer->name);
13006 return -1;
13007 } else {
13008 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
13009 return 0;
13010 }
13011 }
13012
13013 static void peer_destructor(void *obj)
13014 {
13015 struct iax2_peer *peer = obj;
13016 int callno = peer->callno;
13017
13018 ast_free_acl_list(peer->acl);
13019
13020 if (callno > 0) {
13021 ast_mutex_lock(&iaxsl[callno]);
13022 iax2_destroy(callno);
13023 ast_mutex_unlock(&iaxsl[callno]);
13024 }
13025
13026 register_peer_exten(peer, 0);
13027
13028 if (peer->dnsmgr)
13029 ast_dnsmgr_release(peer->dnsmgr);
13030
13031 if (peer->mwi_event_sub) {
13032 peer->mwi_event_sub = ast_mwi_unsubscribe(peer->mwi_event_sub);
13033 }
13034
13035 ast_string_field_free_memory(peer);
13036
13037 ast_endpoint_shutdown(peer->endpoint);
13038 }
13039
13040 /*! \brief Create peer structure based on configuration */
13041 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13042 {
13043 struct iax2_peer *peer = NULL;
13044 struct ast_acl_list *oldacl = NULL;
13045 int maskfound = 0;
13046 int found = 0;
13047 int firstpass = 1;
13048 int subscribe_acl_change = 0;
13049
13050 if (!temponly) {
13051 peer = ao2_find(peers, name, OBJ_KEY);
13052 if (peer && !ast_test_flag64(peer, IAX_DELME))
13053 firstpass = 0;
13054 }
13055
13056 if (peer) {
13057 found++;
13058 if (firstpass) {
13059 oldacl = peer->acl;
13060 peer->acl = NULL;
13061 }
13062 unlink_peer(peer);
13063 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
13064 peer->expire = -1;
13065 peer->pokeexpire = -1;
13066 peer->sockfd = defaultsockfd;
13067 if (ast_string_field_init(peer, 32))
13068 peer = peer_unref(peer);
13069 if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
13070 peer = peer_unref(peer);
13071 }
13072 }
13073
13074 if (peer) {
13075 if (firstpass) {
13076 ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
13077 peer->encmethods = iax2_encryption;
13078 peer->authmethods = iax2_authmethods;
13079 peer->adsi = adsi;
13080 ast_string_field_set(peer, secret, "");
13081 if (!found) {
13082 ast_string_field_set(peer, name, name);
13083 ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
13084 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
13085 peer->expiry = min_reg_expire;
13086 }
13087 peer->prefs = prefs_global;
13088 peer->capability = iax2_capability;
13089 peer->smoothing = 0;
13090 peer->pokefreqok = DEFAULT_FREQ_OK;
13091 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
13092 peer->maxcallno = 0;
13093 peercnt_modify((unsigned char) 0, 0, &peer->addr);
13094 peer->calltoken_required = CALLTOKEN_DEFAULT;
13095 ast_string_field_set(peer,context,"");
13096 ast_string_field_set(peer,peercontext,"");
13097 ast_clear_flag64(peer, IAX_HASCALLERID);
13098 ast_string_field_set(peer, cid_name, "");
13099 ast_string_field_set(peer, cid_num, "");
13100 ast_string_field_set(peer, mohinterpret, mohinterpret);
13101 ast_string_field_set(peer, mohsuggest, mohsuggest);
13102 }
13103
13104 if (!v) {
13105 v = alt;
13106 alt = NULL;
13107 }
13108 while(v) {
13109 if (!strcasecmp(v->name, "secret")) {
13110 ast_string_field_set(peer, secret, v->value);
13111 } else if (!strcasecmp(v->name, "mailbox")) {
13112 ast_string_field_set(peer, mailbox, v->value);
13113 } else if (!strcasecmp(v->name, "hasvoicemail")) {
13114 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
13115 /*
13116 * hasvoicemail is a users.conf legacy voicemail enable method.
13117 * hasvoicemail is only going to work for app_voicemail mailboxes.
13118 */
13119 if (strchr(name, '@')) {
13120 ast_string_field_set(peer, mailbox, name);
13121 } else {
13122 ast_string_field_build(peer, mailbox, "%s@default", name);
13123 }
13124 }
13125 } else if (!strcasecmp(v->name, "mohinterpret")) {
13126 ast_string_field_set(peer, mohinterpret, v->value);
13127 } else if (!strcasecmp(v->name, "mohsuggest")) {
13128 ast_string_field_set(peer, mohsuggest, v->value);
13129 } else if (!strcasecmp(v->name, "dbsecret")) {
13130 ast_string_field_set(peer, dbsecret, v->value);
13131 } else if (!strcasecmp(v->name, "description")) {
13132 ast_string_field_set(peer, description, v->value);
13133 } else if (!strcasecmp(v->name, "trunk")) {
13134 ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK);
13135 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
13136 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
13137 ast_clear_flag64(peer, IAX_TRUNK);
13138 }
13139 } else if (!strcasecmp(v->name, "auth")) {
13140 peer->authmethods = get_auth_methods(v->value);
13141 if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
13142 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);
13143 }
13144 } else if (!strcasecmp(v->name, "encryption")) {
13145 peer->encmethods |= get_encrypt_methods(v->value);
13146 if (!peer->encmethods) {
13147 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
13148 }
13149 } else if (!strcasecmp(v->name, "forceencryption")) {
13150 if (ast_false(v->value)) {
13151 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
13152 } else {
13153 peer->encmethods |= get_encrypt_methods(v->value);
13154 if (peer->encmethods) {
13155 ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
13156 }
13157 }
13158 } else if (!strcasecmp(v->name, "transfer")) {
13159 if (!strcasecmp(v->value, "mediaonly")) {
13160 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13161 } else if (ast_true(v->value)) {
13162 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13163 } else
13164 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13165 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13166 ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
13167 } else if (!strcasecmp(v->name, "host")) {
13168 if (!strcasecmp(v->value, "dynamic")) {
13169 /* They'll register with us */
13170 ast_set_flag64(peer, IAX_DYNAMIC);
13171 if (!found) {
13172 int peer_port = ast_sockaddr_port(&peer->addr);
13173 if (peer_port) {
13174 ast_sockaddr_set_port(&peer->defaddr, peer_port);
13175 }
13176 ast_sockaddr_setnull(&peer->addr);
13177 }
13178 } else {
13179 /* Non-dynamic. Make sure we become that way if we're not */
13180 AST_SCHED_DEL(sched, peer->expire);
13181 ast_clear_flag64(peer, IAX_DYNAMIC);
13182 if (peer->dnsmgr) {
13183 // Make sure we refresh dnsmgr if we're using it
13184 ast_dnsmgr_refresh(peer->dnsmgr);
13185 } else {
13186 // Or just invalidate the address
13187 peer->addr.ss.ss_family = AST_AF_UNSPEC;
13188 }
13189 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
13190 return peer_unref(peer);
13191 }
13192 if (!ast_sockaddr_port(&peer->addr)) {
13193 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
13194 }
13195 }
13196 } else if (!strcasecmp(v->name, "defaultip")) {
13197 struct ast_sockaddr peer_defaddr_tmp;
13198 peer_defaddr_tmp.ss.ss_family = AF_UNSPEC;
13199 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
13200 return peer_unref(peer);
13201 }
13202 ast_sockaddr_set_port(&peer_defaddr_tmp, ast_sockaddr_port(&peer->defaddr));
13203 ast_sockaddr_copy(&peer->defaddr, &peer_defaddr_tmp);
13204 } else if (!strcasecmp(v->name, "sourceaddress")) {
13205 peer_set_srcaddr(peer, v->value);
13206 } else if (!strcasecmp(v->name, "permit") ||
13207 !strcasecmp(v->name, "deny") ||
13208 !strcasecmp(v->name, "acl")) {
13209 ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
13210 } else if (!strcasecmp(v->name, "mask")) {
13211 maskfound++;
13212 ast_sockaddr_parse(&peer->mask, v->value, 0);
13213 } else if (!strcasecmp(v->name, "context")) {
13214 ast_string_field_set(peer, context, v->value);
13215 } else if (!strcasecmp(v->name, "regexten")) {
13216 ast_string_field_set(peer, regexten, v->value);
13217 } else if (!strcasecmp(v->name, "peercontext")) {
13218 ast_string_field_set(peer, peercontext, v->value);
13219 } else if (!strcasecmp(v->name, "port")) {
13220 int bindport;
13221 if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
13222 bindport = IAX_DEFAULT_PORTNO;
13223 }
13224 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
13225 ast_sockaddr_set_port(&peer->defaddr, bindport);
13226 } else {
13227 ast_sockaddr_set_port(&peer->addr, bindport);
13228 }
13229 } else if (!strcasecmp(v->name, "username")) {
13230 ast_string_field_set(peer, username, v->value);
13231 } else if (!strcasecmp(v->name, "allow")) {
13232 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
13233 } else if (!strcasecmp(v->name, "disallow")) {
13234 iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
13235 } else if (!strcasecmp(v->name, "callerid")) {
13236 if (!ast_strlen_zero(v->value)) {
13237 char name2[80];
13238 char num2[80];
13239 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13240 ast_string_field_set(peer, cid_name, name2);
13241 ast_string_field_set(peer, cid_num, num2);
13242 } else {
13243 ast_string_field_set(peer, cid_name, "");
13244 ast_string_field_set(peer, cid_num, "");
13245 }
13246 ast_set_flag64(peer, IAX_HASCALLERID);
13247 } else if (!strcasecmp(v->name, "fullname")) {
13248 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
13249 ast_set_flag64(peer, IAX_HASCALLERID);
13250 } else if (!strcasecmp(v->name, "cid_number")) {
13251 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
13252 ast_set_flag64(peer, IAX_HASCALLERID);
13253 } else if (!strcasecmp(v->name, "sendani")) {
13254 ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
13255 } else if (!strcasecmp(v->name, "inkeys")) {
13256 ast_string_field_set(peer, inkeys, v->value);
13257 } else if (!strcasecmp(v->name, "outkey")) {
13258 ast_string_field_set(peer, outkey, v->value);
13259 } else if (!strcasecmp(v->name, "qualify")) {
13260 if (!strcasecmp(v->value, "no")) {
13261 peer->maxms = 0;
13262 } else if (!strcasecmp(v->value, "yes")) {
13263 peer->maxms = DEFAULT_MAXMS;
13264 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
13265 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);
13266 peer->maxms = 0;
13267 }
13268 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
13269 peer->smoothing = ast_true(v->value);
13270 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
13271 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
13272 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);
13273 }
13274 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
13275 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
13276 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);
13277 }
13278 } else if (!strcasecmp(v->name, "timezone")) {
13279 ast_string_field_set(peer, zonetag, v->value);
13280 } else if (!strcasecmp(v->name, "adsi")) {
13281 peer->adsi = ast_true(v->value);
13282 } else if (!strcasecmp(v->name, "connectedline")) {
13283 if (ast_true(v->value)) {
13284 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13285 } else if (!strcasecmp(v->value, "send")) {
13286 ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
13287 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
13288 } else if (!strcasecmp(v->value, "receive")) {
13289 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
13290 ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
13291 } else {
13292 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13293 }
13294 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13295 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13296 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13297 } else {
13298 peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13299 }
13300 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13301 /* default is required unless in optional ip list */
13302 if (ast_false(v->value)) {
13303 peer->calltoken_required = CALLTOKEN_NO;
13304 } else if (!strcasecmp(v->value, "auto")) {
13305 peer->calltoken_required = CALLTOKEN_AUTO;
13306 } else if (ast_true(v->value)) {
13307 peer->calltoken_required = CALLTOKEN_YES;
13308 } else {
13309 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13310 }
13311 } /* else if (strcasecmp(v->name,"type")) */
13312 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13313 v = v->next;
13314 if (!v) {
13315 v = alt;
13316 alt = NULL;
13317 }
13318 }
13319 if (!peer->authmethods)
13320 peer->authmethods = IAX_AUTH_MD5;
13321 ast_clear_flag64(peer, IAX_DELME);
13322 }
13323
13324 if (!maskfound && !ast_sockaddr_isnull(&peer->addr)) {
13325 if (ast_sockaddr_is_ipv4_mapped(&peer->addr)) {
13326 ast_sockaddr_parse(&peer->mask, "::ffff:ffff:ffff", 0);
13327 } else if (ast_sockaddr_is_ipv6(&peer->addr)) {
13328 ast_sockaddr_parse(&peer->mask, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0);
13329 } else {
13330 ast_sockaddr_parse(&peer->mask, "255.255.255.255", 0);
13331 }
13332 }
13333
13334 if (oldacl) {
13335 ast_free_acl_list(oldacl);
13336 }
13337
13338 if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
13339 /* The MWI subscriptions exist just so the core knows we care about those
13340 * mailboxes. However, we just grab the events out of the cache when it
13341 * is time to send MWI, since it is only sent with a REGACK. */
13342 peer->mwi_event_sub = ast_mwi_subscribe_pool(peer->mailbox, stasis_subscription_cb_noop, NULL);
13343 }
13344
13345 if (subscribe_acl_change) {
13346 acl_change_stasis_subscribe();
13347 }
13348
13349 return peer;
13350 }
13351
13352 static void user_destructor(void *obj)
13353 {
13354 struct iax2_user *user = obj;
13355
13356 ast_free_acl_list(user->acl);
13357 free_context(user->contexts);
13358 if(user->vars) {
13359 ast_variables_destroy(user->vars);
13360 user->vars = NULL;
13361 }
13362 ast_string_field_free_memory(user);
13363 }
13364
13365 /*! \brief Create in-memory user structure from configuration */
13366 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13367 {
13368 struct iax2_user *user = NULL;
13369 struct iax2_context *con, *conl = NULL;
13370 struct ast_acl_list *oldacl = NULL;
13371 struct iax2_context *oldcon = NULL;
13372 int format;
13373 int firstpass=1;
13374 int oldcurauthreq = 0;
13375 int subscribe_acl_change = 0;
13376 char *varname = NULL, *varval = NULL;
13377 struct ast_variable *tmpvar = NULL;
13378
13379 if (!temponly) {
13380 user = ao2_find(users, name, OBJ_KEY);
13381 if (user && !ast_test_flag64(user, IAX_DELME))
13382 firstpass = 0;
13383 }
13384
13385 if (user) {
13386 if (firstpass) {
13387 oldcurauthreq = user->curauthreq;
13388 oldacl = user->acl;
13389 oldcon = user->contexts;
13390 user->acl = NULL;
13391 user->contexts = NULL;
13392 }
13393 /* Already in the list, remove it and it will be added back (or FREE'd) */
13394 ao2_unlink(users, user);
13395 } else {
13396 user = ao2_alloc(sizeof(*user), user_destructor);
13397 }
13398
13399 if (user) {
13400 if (firstpass) {
13401 ast_string_field_free_memory(user);
13402 memset(user, 0, sizeof(struct iax2_user));
13403 if (ast_string_field_init(user, 32)) {
13404 user = user_unref(user);
13405 goto cleanup;
13406 }
13407 user->maxauthreq = maxauthreq;
13408 user->curauthreq = oldcurauthreq;
13409 user->prefs = prefs_global;
13410 user->capability = iax2_capability;
13411 user->encmethods = iax2_encryption;
13412 user->authmethods = iax2_authmethods;
13413 user->adsi = adsi;
13414 user->calltoken_required = CALLTOKEN_DEFAULT;
13415 ast_string_field_set(user, name, name);
13416 ast_string_field_set(user, language, language);
13417 ast_copy_flags64(user, &globalflags, IAX_USEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
13418 ast_clear_flag64(user, IAX_HASCALLERID);
13419 ast_string_field_set(user, cid_name, "");
13420 ast_string_field_set(user, cid_num, "");
13421 ast_string_field_set(user, accountcode, accountcode);
13422 ast_string_field_set(user, mohinterpret, mohinterpret);
13423 ast_string_field_set(user, mohsuggest, mohsuggest);
13424 }
13425 if (!v) {
13426 v = alt;
13427 alt = NULL;
13428 }
13429 while(v) {
13430 if (!strcasecmp(v->name, "context")) {
13431 con = build_context(v->value);
13432 if (con) {
13433 if (conl)
13434 conl->next = con;
13435 else
13436 user->contexts = con;
13437 conl = con;
13438 }
13439 } else if (!strcasecmp(v->name, "permit") ||
13440 !strcasecmp(v->name, "deny") ||
13441 !strcasecmp(v->name, "acl")) {
13442 ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13443 } else if (!strcasecmp(v->name, "setvar")) {
13444 varname = ast_strdupa(v->value);
13445 if ((varval = strchr(varname, '='))) {
13446 *varval = '\0';
13447 varval++;
13448 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
13449 if (ast_variable_list_replace(&user->vars, tmpvar)) {
13450 tmpvar->next = user->vars;
13451 user->vars = tmpvar;
13452 }
13453 }
13454 }
13455 } else if (!strcasecmp(v->name, "allow")) {
13456 iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13457 } else if (!strcasecmp(v->name, "disallow")) {
13458 iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13459 } else if (!strcasecmp(v->name, "trunk")) {
13460 ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK);
13461 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13462 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13463 ast_clear_flag64(user, IAX_TRUNK);
13464 }
13465 } else if (!strcasecmp(v->name, "auth")) {
13466 user->authmethods = get_auth_methods(v->value);
13467 if (user->authmethods & IAX_AUTH_PLAINTEXT) {
13468 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);
13469 }
13470 } else if (!strcasecmp(v->name, "encryption")) {
13471 user->encmethods |= get_encrypt_methods(v->value);
13472 if (!user->encmethods) {
13473 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
13474 }
13475 } else if (!strcasecmp(v->name, "forceencryption")) {
13476 if (ast_false(v->value)) {
13477 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
13478 } else {
13479 user->encmethods |= get_encrypt_methods(v->value);
13480 if (user->encmethods) {
13481 ast_set_flag64(user, IAX_FORCE_ENCRYPT);
13482 }
13483 }
13484 } else if (!strcasecmp(v->name, "transfer")) {
13485 if (!strcasecmp(v->value, "mediaonly")) {
13486 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13487 } else if (ast_true(v->value)) {
13488 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13489 } else
13490 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13491 } else if (!strcasecmp(v->name, "codecpriority")) {
13492 if(!strcasecmp(v->value, "caller"))
13493 ast_set_flag64(user, IAX_CODEC_USER_FIRST);
13494 else if(!strcasecmp(v->value, "disabled"))
13495 ast_set_flag64(user, IAX_CODEC_NOPREFS);
13496 else if(!strcasecmp(v->value, "reqonly")) {
13497 ast_set_flag64(user, IAX_CODEC_NOCAP);
13498 ast_set_flag64(user, IAX_CODEC_NOPREFS);
13499 }
13500 } else if (!strcasecmp(v->name, "immediate")) {
13501 ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
13502 } else if (!strcasecmp(v->name, "jitterbuffer")) {
13503 ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
13504 } else if (!strcasecmp(v->name, "dbsecret")) {
13505 ast_string_field_set(user, dbsecret, v->value);
13506 } else if (!strcasecmp(v->name, "secret")) {
13507 if (!ast_strlen_zero(user->secret)) {
13508 char *old = ast_strdupa(user->secret);
13509
13510 ast_string_field_build(user, secret, "%s;%s", old, v->value);
13511 } else
13512 ast_string_field_set(user, secret, v->value);
13513 } else if (!strcasecmp(v->name, "callerid")) {
13514 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13515 char name2[80];
13516 char num2[80];
13517 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13518 ast_string_field_set(user, cid_name, name2);
13519 ast_string_field_set(user, cid_num, num2);
13520 ast_set_flag64(user, IAX_HASCALLERID);
13521 } else {
13522 ast_clear_flag64(user, IAX_HASCALLERID);
13523 ast_string_field_set(user, cid_name, "");
13524 ast_string_field_set(user, cid_num, "");
13525 }
13526 } else if (!strcasecmp(v->name, "fullname")) {
13527 if (!ast_strlen_zero(v->value)) {
13528 ast_string_field_set(user, cid_name, v->value);
13529 ast_set_flag64(user, IAX_HASCALLERID);
13530 } else {
13531 ast_string_field_set(user, cid_name, "");
13532 if (ast_strlen_zero(user->cid_num))
13533 ast_clear_flag64(user, IAX_HASCALLERID);
13534 }
13535 } else if (!strcasecmp(v->name, "cid_number")) {
13536 if (!ast_strlen_zero(v->value)) {
13537 ast_string_field_set(user, cid_num, v->value);
13538 ast_set_flag64(user, IAX_HASCALLERID);
13539 } else {
13540 ast_string_field_set(user, cid_num, "");
13541 if (ast_strlen_zero(user->cid_name))
13542 ast_clear_flag64(user, IAX_HASCALLERID);
13543 }
13544 } else if (!strcasecmp(v->name, "accountcode")) {
13545 ast_string_field_set(user, accountcode, v->value);
13546 } else if (!strcasecmp(v->name, "mohinterpret")) {
13547 ast_string_field_set(user, mohinterpret, v->value);
13548 } else if (!strcasecmp(v->name, "mohsuggest")) {
13549 ast_string_field_set(user, mohsuggest, v->value);
13550 } else if (!strcasecmp(v->name, "parkinglot")) {
13551 ast_string_field_set(user, parkinglot, v->value);
13552 } else if (!strcasecmp(v->name, "language")) {
13553 ast_string_field_set(user, language, v->value);
13554 } else if (!strcasecmp(v->name, "amaflags")) {
13555 format = ast_channel_string2amaflag(v->value);
13556 if (format < 0) {
13557 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13558 } else {
13559 user->amaflags = format;
13560 }
13561 } else if (!strcasecmp(v->name, "inkeys")) {
13562 ast_string_field_set(user, inkeys, v->value);
13563 } else if (!strcasecmp(v->name, "maxauthreq")) {
13564 user->maxauthreq = atoi(v->value);
13565 if (user->maxauthreq < 0)
13566 user->maxauthreq = 0;
13567 } else if (!strcasecmp(v->name, "adsi")) {
13568 user->adsi = ast_true(v->value);
13569 } else if (!strcasecmp(v->name, "connectedline")) {
13570 if (ast_true(v->value)) {
13571 ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13572 } else if (!strcasecmp(v->value, "send")) {
13573 ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
13574 ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
13575 } else if (!strcasecmp(v->value, "receive")) {
13576 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
13577 ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
13578 } else {
13579 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13580 }
13581 } else if (!strcasecmp(v->name, "requirecalltoken")) {
13582 /* default is required unless in optional ip list */
13583 if (ast_false(v->value)) {
13584 user->calltoken_required = CALLTOKEN_NO;
13585 } else if (!strcasecmp(v->value, "auto")) {
13586 user->calltoken_required = CALLTOKEN_AUTO;
13587 } else if (ast_true(v->value)) {
13588 user->calltoken_required = CALLTOKEN_YES;
13589 } else {
13590 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13591 }
13592 } /* else if (strcasecmp(v->name,"type")) */
13593 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13594 v = v->next;
13595 if (!v) {
13596 v = alt;
13597 alt = NULL;
13598 }
13599 }
13600 if (!user->authmethods) {
13601 if (!ast_strlen_zero(user->secret)) {
13602 user->authmethods = IAX_AUTH_MD5;
13603 if (!ast_strlen_zero(user->inkeys))
13604 user->authmethods |= IAX_AUTH_RSA;
13605 } else if (!ast_strlen_zero(user->inkeys)) {
13606 user->authmethods = IAX_AUTH_RSA;
13607 } else {
13608 user->authmethods = IAX_AUTH_MD5;
13609 }
13610 }
13611 ast_clear_flag64(user, IAX_DELME);
13612 }
13613 cleanup:
13614 if (oldacl) {
13615 ast_free_acl_list(oldacl);
13616 }
13617 if (oldcon) {
13618 free_context(oldcon);
13619 }
13620
13621 if (subscribe_acl_change) {
13622 acl_change_stasis_subscribe();
13623 }
13624
13625 return user;
13626 }
13627
13628 static int peer_delme_cb(void *obj, void *arg, int flags)
13629 {
13630 struct iax2_peer *peer = obj;
13631
13632 ast_set_flag64(peer, IAX_DELME);
13633
13634 return 0;
13635 }
13636
13637 static int user_delme_cb(void *obj, void *arg, int flags)
13638 {
13639 struct iax2_user *user = obj;
13640
13641 ast_set_flag64(user, IAX_DELME);
13642
13643 return 0;
13644 }
13645
13646 static void delete_users(void)
13647 {
13648 struct iax2_registry *reg;
13649
13650 ao2_callback(users, OBJ_NODATA, user_delme_cb, NULL);
13651
13652 AST_LIST_LOCK(&registrations);
13653 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13654 if (sched) {
13655 AST_SCHED_DEL(sched, reg->expire);
13656 }
13657 if (reg->callno) {
13658 int callno = reg->callno;
13659 ast_mutex_lock(&iaxsl[callno]);
13660 if (iaxs[callno]) {
13661 iaxs[callno]->reg = NULL;
13662 iax2_destroy(callno);
13663 }
13664 ast_mutex_unlock(&iaxsl[callno]);
13665 }
13666 if (reg->dnsmgr)
13667 ast_dnsmgr_release(reg->dnsmgr);
13668 ast_free(reg);
13669 }
13670 AST_LIST_UNLOCK(&registrations);
13671
13672 ao2_callback(peers, OBJ_NODATA, peer_delme_cb, NULL);
13673 }
13674
13675 static void prune_users(void)
13676 {
13677 struct iax2_user *user;
13678 struct ao2_iterator i;
13679
13680 i = ao2_iterator_init(users, 0);
13681 while ((user = ao2_iterator_next(&i))) {
13682 if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
13683 ao2_unlink(users, user);
13684 }
13685 user_unref(user);
13686 }
13687 ao2_iterator_destroy(&i);
13688 }
13689
13690 /* Prune peers who still are supposed to be deleted */
13691 static void prune_peers(void)
13692 {
13693 struct iax2_peer *peer;
13694 struct ao2_iterator i;
13695
13696 i = ao2_iterator_init(peers, 0);
13697 while ((peer = ao2_iterator_next(&i))) {
13698 if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
13699 unlink_peer(peer);
13700 }
13701 peer_unref(peer);
13702 }
13703 ao2_iterator_destroy(&i);
13704 }
13705
13706 static void set_config_destroy(void)
13707 {
13708 strcpy(accountcode, "");
13709 strcpy(language, "");
13710 strcpy(mohinterpret, "");
13711 strcpy(mohsuggest, "");
13712 trunkmaxsize = MAX_TRUNKDATA;
13713 amaflags = 0;
13714 delayreject = 0;
13715 ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
13716 IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13717 delete_users();
13718 ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13719 ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13720 }
13721
13722 /*! \brief Load configuration */
13723 static int set_config(const char *config_file, int reload, int forced)
13724 {
13725 struct ast_config *cfg, *ucfg;
13726 iax2_format capability;
13727 struct ast_variable *v;
13728 char *cat;
13729 const char *utype;
13730 const char *tosval;
13731 int format;
13732 int portno = IAX_DEFAULT_PORTNO;
13733 int x;
13734 int mtuv;
13735 int subscribe_network_change = 1;
13736 struct iax2_user *user;
13737 struct iax2_peer *peer;
13738 struct ast_netsock *ns;
13739 struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13740 struct ast_sockaddr bindaddr;
13741 struct iax2_codec_pref prefs_new;
13742
13743 cfg = ast_config_load(config_file, config_flags);
13744
13745 if (!cfg) {
13746 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13747 return -1;
13748 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13749 ucfg = ast_config_load("users.conf", config_flags);
13750 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13751 return 0;
13752 /* Otherwise we need to reread both files */
13753 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13754 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13755 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13756 ast_config_destroy(ucfg);
13757 return 0;
13758 }
13759 if (!cfg) {
13760 /* should have been able to load the config here */
13761 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13762 return -1;
13763 }
13764 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13765 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13766 return 0;
13767 } else { /* iax.conf changed, gotta reread users.conf, too */
13768 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13769 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13770 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13771 ast_config_destroy(cfg);
13772 return 0;
13773 }
13774 }
13775
13776 if (reload) {
13777 set_config_destroy();
13778 }
13779
13780 ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
13781
13782 /* Setup new codec prefs */
13783 capability = iax2_codec_pref_from_bitfield(&prefs_new, IAX_CAPABILITY_FULLBANDWIDTH);
13784
13785 /* Reset Global Flags */
13786 memset(&globalflags, 0, sizeof(globalflags));
13787 ast_set_flag64(&globalflags, IAX_RTUPDATE);
13788 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13789
13790 #ifdef SO_NO_CHECK
13791 nochecksums = 0;
13792 #endif
13793 /* Reset default parking lot */
13794 default_parkinglot[0] = '\0';
13795
13796 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13797 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13798 global_max_trunk_mtu = MAX_TRUNK_MTU;
13799 global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13800 global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13801
13802 maxauthreq = 3;
13803
13804 srvlookup = 0;
13805 iax2_authmethods = 0;
13806
13807 v = ast_variable_browse(cfg, "general");
13808
13809 /* Seed initial tos value */
13810 tosval = ast_variable_retrieve(cfg, "general", "tos");
13811 if (tosval) {
13812 if (ast_str2tos(tosval, &qos.tos))
13813 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13814 }
13815 /* Seed initial cos value */
13816 tosval = ast_variable_retrieve(cfg, "general", "cos");
13817 if (tosval) {
13818 if (ast_str2cos(tosval, &qos.cos))
13819 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13820 }
13821 while(v) {
13822 if (!strcasecmp(v->name, "bindport")) {
13823 if (reload) {
13824 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13825 }
13826 else if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &portno, 1024, 65535)) {
13827 portno = IAX_DEFAULT_PORTNO;
13828 }
13829 } else if (!strcasecmp(v->name, "pingtime")){
13830 ping_time = atoi(v->value);
13831 }
13832 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13833 if (reload) {
13834 if (atoi(v->value) != iaxthreadcount)
13835 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13836 } else {
13837 iaxthreadcount = atoi(v->value);
13838 if (iaxthreadcount < 1) {
13839 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13840 iaxthreadcount = 1;
13841 } else if (iaxthreadcount > 256) {
13842 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13843 iaxthreadcount = 256;
13844 }
13845 }
13846 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13847 if (reload) {
13848 AST_LIST_LOCK(&dynamic_list);
13849 iaxmaxthreadcount = atoi(v->value);
13850 AST_LIST_UNLOCK(&dynamic_list);
13851 } else {
13852 iaxmaxthreadcount = atoi(v->value);
13853 if (iaxmaxthreadcount < 0) {
13854 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13855 iaxmaxthreadcount = 0;
13856 } else if (iaxmaxthreadcount > 256) {
13857 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13858 iaxmaxthreadcount = 256;
13859 }
13860 }
13861 } else if (!strcasecmp(v->name, "nochecksums")) {
13862 #ifdef SO_NO_CHECK
13863 if (ast_true(v->value))
13864 nochecksums = 1;
13865 else
13866 nochecksums = 0;
13867 #else
13868 if (ast_true(v->value))
13869 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13870 #endif
13871 }
13872 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13873 maxjitterbuffer = atoi(v->value);
13874 else if (!strcasecmp(v->name, "resyncthreshold"))
13875 resyncthreshold = atoi(v->value);
13876 else if (!strcasecmp(v->name, "maxjitterinterps"))
13877 maxjitterinterps = atoi(v->value);
13878 else if (!strcasecmp(v->name, "jittertargetextra"))
13879 jittertargetextra = atoi(v->value);
13880 else if (!strcasecmp(v->name, "lagrqtime"))
13881 lagrq_time = atoi(v->value);
13882 else if (!strcasecmp(v->name, "maxregexpire"))
13883 max_reg_expire = atoi(v->value);
13884 else if (!strcasecmp(v->name, "minregexpire"))
13885 min_reg_expire = atoi(v->value);
13886 else if (!strcasecmp(v->name, "bindaddr")) {
13887 if (reload) {
13888 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13889 } else {
13890
13891 if (!ast_parse_arg(v->value, PARSE_ADDR, NULL)) {
13892
13893 ast_sockaddr_parse(&bindaddr, v->value, 0);
13894
13895 if (!ast_sockaddr_port(&bindaddr)) {
13896 ast_sockaddr_set_port(&bindaddr, portno);
13897 }
13898
13899 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13900 ast_log(LOG_WARNING, "Unable to apply binding to '%s' at line %d\n", v->value, v->lineno);
13901 } else {
13902 ast_verb(2, "Binding IAX2 to address %s\n", ast_sockaddr_stringify(&bindaddr));
13903
13904 if (defaultsockfd < 0) {
13905 defaultsockfd = ast_netsock_sockfd(ns);
13906 }
13907 ast_netsock_unref(ns);
13908 }
13909
13910 } else {
13911 ast_log(LOG_WARNING, "Invalid address '%s' specified, at line %d\n", v->value, v->lineno);
13912 }
13913 }
13914 } else if (!strcasecmp(v->name, "auth")) {
13915 iax2_authmethods = get_auth_methods(v->value);
13916 if (iax2_authmethods & IAX_AUTH_PLAINTEXT) {
13917 ast_log(LOG_WARNING, "Default auth method is set to deprecated 'plaintext' at line %d of iax.conf\n", v->lineno);
13918 }
13919 } else if (!strcasecmp(v->name, "authdebug")) {
13920 authdebug = ast_true(v->value);
13921 } else if (!strcasecmp(v->name, "encryption")) {
13922 iax2_encryption |= get_encrypt_methods(v->value);
13923 if (!iax2_encryption) {
13924 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13925 }
13926 } else if (!strcasecmp(v->name, "forceencryption")) {
13927 if (ast_false(v->value)) {
13928 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13929 } else {
13930 iax2_encryption |= get_encrypt_methods(v->value);
13931 if (iax2_encryption) {
13932 ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13933 }
13934 }
13935 } else if (!strcasecmp(v->name, "transfer")) {
13936 if (!strcasecmp(v->value, "mediaonly")) {
13937 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13938 } else if (ast_true(v->value)) {
13939 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13940 } else
13941 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13942 } else if (!strcasecmp(v->name, "codecpriority")) {
13943 if(!strcasecmp(v->value, "caller"))
13944 ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13945 else if(!strcasecmp(v->value, "disabled"))
13946 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13947 else if(!strcasecmp(v->value, "reqonly")) {
13948 ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13949 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13950 }
13951 } else if (!strcasecmp(v->name, "jitterbuffer"))
13952 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13953 else if (!strcasecmp(v->name, "delayreject"))
13954 delayreject = ast_true(v->value);
13955 else if (!strcasecmp(v->name, "allowfwdownload"))
13956 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13957 else if (!strcasecmp(v->name, "rtcachefriends"))
13958 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13959 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13960 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13961 else if (!strcasecmp(v->name, "rtupdate"))
13962 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13963 else if (!strcasecmp(v->name, "rtsavesysname"))
13964 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13965 else if (!strcasecmp(v->name, "trunktimestamps"))
13966 ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13967 else if (!strcasecmp(v->name, "rtautoclear")) {
13968 int i = atoi(v->value);
13969 if(i > 0)
13970 global_rtautoclear = i;
13971 else
13972 i = 0;
13973 ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13974 } else if (!strcasecmp(v->name, "trunkfreq")) {
13975 trunkfreq = atoi(v->value);
13976 if (trunkfreq < 10) {
13977 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13978 trunkfreq = 10;
13979 } else if (trunkfreq > 1000) {
13980 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13981 trunkfreq = 1000;
13982 }
13983 if (timer) {
13984 ast_timer_set_rate(timer, 1000 / trunkfreq);
13985 }
13986 } else if (!strcasecmp(v->name, "trunkmtu")) {
13987 mtuv = atoi(v->value);
13988 if (mtuv == 0 )
13989 global_max_trunk_mtu = 0;
13990 else if (mtuv >= 172 && mtuv < 4000)
13991 global_max_trunk_mtu = mtuv;
13992 else
13993 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13994 mtuv, v->lineno);
13995 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13996 trunkmaxsize = atoi(v->value);
13997 if (trunkmaxsize == 0)
13998 trunkmaxsize = MAX_TRUNKDATA;
13999 } else if (!strcasecmp(v->name, "autokill")) {
14000 if (sscanf(v->value, "%30d", &x) == 1) {
14001 if (x >= 0)
14002 autokill = x;
14003 else
14004 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
14005 } else if (ast_true(v->value)) {
14006 autokill = DEFAULT_MAXMS;
14007 } else {
14008 autokill = 0;
14009 }
14010 } else if (!strcasecmp(v->name, "bandwidth")) {
14011 if (!strcasecmp(v->value, "low")) {
14012 capability = iax2_codec_pref_from_bitfield(&prefs_new,
14013 IAX_CAPABILITY_LOWBANDWIDTH);
14014 } else if (!strcasecmp(v->value, "medium")) {
14015 capability = iax2_codec_pref_from_bitfield(&prefs_new,
14016 IAX_CAPABILITY_MEDBANDWIDTH);
14017 } else if (!strcasecmp(v->value, "high")) {
14018 capability = iax2_codec_pref_from_bitfield(&prefs_new,
14019 IAX_CAPABILITY_FULLBANDWIDTH);
14020 } else {
14021 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
14022 }
14023 } else if (!strcasecmp(v->name, "allow")) {
14024 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 1);
14025 } else if (!strcasecmp(v->name, "disallow")) {
14026 iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 0);
14027 } else if (!strcasecmp(v->name, "register")) {
14028 iax2_register(v->value, v->lineno);
14029 } else if (!strcasecmp(v->name, "iaxcompat")) {
14030 iaxcompat = ast_true(v->value);
14031 } else if (!strcasecmp(v->name, "regcontext")) {
14032 ast_copy_string(regcontext, v->value, sizeof(regcontext));
14033 /* Create context if it doesn't exist already */
14034 ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
14035 } else if (!strcasecmp(v->name, "tos")) {
14036 if (ast_str2tos(v->value, &qos.tos))
14037 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
14038 } else if (!strcasecmp(v->name, "cos")) {
14039 if (ast_str2cos(v->value, &qos.cos))
14040 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
14041 } else if (!strcasecmp(v->name, "parkinglot")) {
14042 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
14043 } else if (!strcasecmp(v->name, "accountcode")) {
14044 ast_copy_string(accountcode, v->value, sizeof(accountcode));
14045 } else if (!strcasecmp(v->name, "mohinterpret")) {
14046 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
14047 } else if (!strcasecmp(v->name, "mohsuggest")) {
14048 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
14049 } else if (!strcasecmp(v->name, "amaflags")) {
14050 format = ast_channel_string2amaflag(v->value);
14051 if (format < 0) {
14052 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
14053 } else {
14054 amaflags = format;
14055 }
14056 } else if (!strcasecmp(v->name, "language")) {
14057 ast_copy_string(language, v->value, sizeof(language));
14058 } else if (!strcasecmp(v->name, "maxauthreq")) {
14059 maxauthreq = atoi(v->value);
14060 if (maxauthreq < 0)
14061 maxauthreq = 0;
14062 } else if (!strcasecmp(v->name, "adsi")) {
14063 adsi = ast_true(v->value);
14064 } else if (!strcasecmp(v->name, "srvlookup")) {
14065 srvlookup = ast_true(v->value);
14066 } else if (!strcasecmp(v->name, "connectedline")) {
14067 if (ast_true(v->value)) {
14068 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
14069 } else if (!strcasecmp(v->value, "send")) {
14070 ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
14071 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
14072 } else if (!strcasecmp(v->value, "receive")) {
14073 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
14074 ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
14075 } else {
14076 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
14077 }
14078 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
14079 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
14080 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
14081 }
14082 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
14083 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
14084 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);
14085 }
14086 } else if (!strcasecmp(v->name, "calltokenoptional")) {
14087 if (add_calltoken_ignore(v->value)) {
14088 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
14089 return -1;
14090 }
14091 } else if (!strcasecmp(v->name, "calltokenexpiration")) {
14092 int temp = -1;
14093 sscanf(v->value, "%u", &temp);
14094 if( temp <= 0 ){
14095 ast_log(LOG_WARNING, "Invalid calltokenexpiration value %s. Should be integer greater than 0.\n", v->value);
14096 } else {
14097 max_calltoken_delay = temp;
14098 }
14099 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
14100 if (ast_true(v->value)) {
14101 subscribe_network_change = 1;
14102 } else if (ast_false(v->value)) {
14103 subscribe_network_change = 0;
14104 } else {
14105 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
14106 }
14107 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
14108 if (ast_true(v->value)) {
14109 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
14110 } else if (ast_false(v->value)) {
14111 ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
14112 } else {
14113 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
14114 }
14115 }/*else if (strcasecmp(v->name,"type")) */
14116 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
14117 v = v->next;
14118 }
14119
14120 if (subscribe_network_change) {
14121 network_change_stasis_subscribe();
14122 } else {
14123 network_change_stasis_unsubscribe();
14124 }
14125
14126 if (defaultsockfd < 0) {
14127
14128 ast_sockaddr_set_port(&bindaddr, portno);
14129
14130 if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
14131 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
14132 } else {
14133 ast_verb(2, "Binding IAX2 to default address %s\n", ast_sockaddr_stringify(&bindaddr));
14134 defaultsockfd = ast_netsock_sockfd(ns);
14135 ast_netsock_unref(ns);
14136 }
14137 }
14138 if (reload) {
14139 ast_netsock_release(outsock);
14140 outsock = ast_netsock_list_alloc();
14141 if (!outsock) {
14142 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14143 return -1;
14144 }
14145 ast_netsock_init(outsock);
14146 }
14147
14148 if (min_reg_expire > max_reg_expire) {
14149 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
14150 min_reg_expire, max_reg_expire, max_reg_expire);
14151 min_reg_expire = max_reg_expire;
14152 }
14153 prefs_global = prefs_new;
14154 iax2_capability = capability;
14155
14156 if (ucfg) {
14157 struct ast_variable *gen;
14158 int genhasiax;
14159 int genregisteriax;
14160 const char *hasiax, *registeriax;
14161
14162 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
14163 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
14164 gen = ast_variable_browse(ucfg, "general");
14165 cat = ast_category_browse(ucfg, NULL);
14166 while (cat) {
14167 if (strcasecmp(cat, "general")) {
14168 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
14169 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
14170 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
14171 /* Start with general parameters, then specific parameters, user and peer */
14172 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
14173 if (user) {
14174 ao2_link(users, user);
14175 user = user_unref(user);
14176 }
14177 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
14178 if (peer) {
14179 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
14180 reg_source_db(peer);
14181 }
14182 ao2_link(peers, peer);
14183 peer = peer_unref(peer);
14184 }
14185 }
14186 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
14187 char tmp[256];
14188 const char *host = ast_variable_retrieve(ucfg, cat, "host");
14189 const char *username = ast_variable_retrieve(ucfg, cat, "username");
14190 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
14191 if (!host)
14192 host = ast_variable_retrieve(ucfg, "general", "host");
14193 if (!username)
14194 username = ast_variable_retrieve(ucfg, "general", "username");
14195 if (!secret)
14196 secret = ast_variable_retrieve(ucfg, "general", "secret");
14197 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
14198 if (!ast_strlen_zero(secret))
14199 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
14200 else
14201 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
14202 iax2_register(tmp, 0);
14203 }
14204 }
14205 }
14206 cat = ast_category_browse(ucfg, cat);
14207 }
14208 ast_config_destroy(ucfg);
14209 }
14210
14211 cat = ast_category_browse(cfg, NULL);
14212 while(cat) {
14213 if (strcasecmp(cat, "general")) {
14214 utype = ast_variable_retrieve(cfg, cat, "type");
14215 if (!strcasecmp(cat, "callnumberlimits")) {
14216 build_callno_limits(ast_variable_browse(cfg, cat));
14217 } else if (utype) {
14218 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
14219 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
14220 if (user) {
14221 ao2_link(users, user);
14222 user = user_unref(user);
14223 }
14224 }
14225 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
14226 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
14227 if (peer) {
14228 if (ast_test_flag64(peer, IAX_DYNAMIC))
14229 reg_source_db(peer);
14230 ao2_link(peers, peer);
14231 peer = peer_unref(peer);
14232 }
14233 } else if (strcasecmp(utype, "user")) {
14234 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
14235 }
14236 } else
14237 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
14238 }
14239 cat = ast_category_browse(cfg, cat);
14240 }
14241 ast_config_destroy(cfg);
14242 return 1;
14243 }
14244
14245 static void poke_all_peers(void)
14246 {
14247 struct ao2_iterator i;
14248 struct iax2_peer *peer;
14249
14250 i = ao2_iterator_init(peers, 0);
14251 while ((peer = ao2_iterator_next(&i))) {
14252 iax2_poke_peer(peer, 0);
14253 peer_unref(peer);
14254 }
14255 ao2_iterator_destroy(&i);
14256 }
14257 static int reload_config(int forced_reload)
14258 {
14259 static const char config[] = "iax.conf";
14260 struct iax2_registry *reg;
14261
14262 if (set_config(config, 1, forced_reload) > 0) {
14263 prune_peers();
14264 prune_users();
14265 ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
14266 ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
14267 ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
14268 trunk_timed = trunk_untimed = 0;
14269 trunk_nmaxmtu = trunk_maxmtu = 0;
14270 memset(&debugaddr, '\0', sizeof(debugaddr));
14271
14272 AST_LIST_LOCK(&registrations);
14273 AST_LIST_TRAVERSE(&registrations, reg, entry)
14274 iax2_do_register(reg);
14275 AST_LIST_UNLOCK(&registrations);
14276
14277 /* Qualify hosts, too */
14278 poke_all_peers();
14279 }
14280
14281 iax_firmware_reload();
14282 iax_provision_reload(1);
14283 ast_unload_realtime("iaxpeers");
14284
14285 return 0;
14286 }
14287
14288 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14289 {
14290 switch (cmd) {
14291 case CLI_INIT:
14292 e->command = "iax2 reload";
14293 e->usage =
14294 "Usage: iax2 reload\n"
14295 " Reloads IAX configuration from iax.conf\n";
14296 return NULL;
14297 case CLI_GENERATE:
14298 return NULL;
14299 }
14300
14301 reload_config(0);
14302
14303 return CLI_SUCCESS;
14304 }
14305
14306 static int reload(void)
14307 {
14308 return reload_config(0);
14309 }
14310
14311 static int cache_get_callno_locked(const char *data)
14312 {
14313 struct ast_sockaddr addr;
14314 int x;
14315 int callno;
14316 struct iax_ie_data ied;
14317 struct create_addr_info cai;
14318 struct parsed_dial_string pds;
14319 char *tmpstr;
14320
14321 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14322 /* Look for an *exact match* call. Once a call is negotiated, it can only
14323 look up entries for a single context */
14324 if (!ast_mutex_trylock(&iaxsl[x])) {
14325 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14326 return x;
14327 ast_mutex_unlock(&iaxsl[x]);
14328 }
14329 }
14330
14331 /* No match found, we need to create a new one */
14332
14333 memset(&cai, 0, sizeof(cai));
14334 memset(&ied, 0, sizeof(ied));
14335 memset(&pds, 0, sizeof(pds));
14336
14337 tmpstr = ast_strdupa(data);
14338 parse_dial_string(tmpstr, &pds);
14339
14340 if (ast_strlen_zero(pds.peer)) {
14341 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14342 return -1;
14343 }
14344
14345 /* Populate our address from the given */
14346 if (create_addr(pds.peer, NULL, &addr, &cai))
14347 return -1;
14348
14349 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14350 pds.peer, pds.username, pds.password, pds.context);
14351
14352 callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
14353 if (callno < 1) {
14354 ast_log(LOG_WARNING, "Unable to create call\n");
14355 return -1;
14356 }
14357
14358 ast_string_field_set(iaxs[callno], dproot, data);
14359 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
14360
14361 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
14362 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
14363 /* the string format is slightly different from a standard dial string,
14364 because the context appears in the 'exten' position
14365 */
14366 if (pds.exten)
14367 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
14368 if (pds.username)
14369 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
14370 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
14371 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
14372 /* Keep password handy */
14373 if (pds.password)
14374 ast_string_field_set(iaxs[callno], secret, pds.password);
14375 if (pds.key)
14376 ast_string_field_set(iaxs[callno], outkey, pds.key);
14377 /* Start the call going */
14378 add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14379 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14380
14381 return callno;
14382 }
14383
14384 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14385 {
14386 struct iax2_dpcache *dp = NULL;
14387 struct timeval now = ast_tvnow();
14388 int x, com[2], timeout, doabort, callno;
14389
14390 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14391 if (ast_tvcmp(now, dp->expiry) > 0) {
14392 AST_LIST_REMOVE_CURRENT(cache_list);
14393 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14394 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14395 else
14396 ast_free(dp);
14397 continue;
14398 }
14399 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14400 break;
14401 }
14402 AST_LIST_TRAVERSE_SAFE_END;
14403
14404 if (!dp) {
14405 /* No matching entry. Create a new one. */
14406 /* First, can we make a callno? */
14407 if ((callno = cache_get_callno_locked(data)) < 0) {
14408 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14409 return NULL;
14410 }
14411 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14412 ast_mutex_unlock(&iaxsl[callno]);
14413 return NULL;
14414 }
14415 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14416 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14417 dp->expiry = ast_tvnow();
14418 dp->orig = dp->expiry;
14419 /* Expires in 30 mins by default */
14420 dp->expiry.tv_sec += iaxdefaultdpcache;
14421 dp->flags = CACHE_FLAG_PENDING;
14422 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14423 dp->waiters[x] = -1;
14424 /* Insert into the lists */
14425 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14426 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14427 /* Send the request if we're already up */
14428 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14429 iax2_dprequest(dp, callno);
14430 ast_mutex_unlock(&iaxsl[callno]);
14431 }
14432
14433 /* By here we must have a dp */
14434 if (dp->flags & CACHE_FLAG_PENDING) {
14435 int res;
14436 struct pollfd pfd;
14437 /* Okay, here it starts to get nasty. We need a pipe now to wait
14438 for a reply to come back so long as it's pending */
14439 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14440 /* Find an empty slot */
14441 if (dp->waiters[x] < 0)
14442 break;
14443 }
14444 if (x >= ARRAY_LEN(dp->waiters)) {
14445 ast_log(LOG_WARNING, "No more waiter positions available\n");
14446 return NULL;
14447 }
14448 if (pipe(com)) {
14449 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14450 return NULL;
14451 }
14452 dp->waiters[x] = com[1];
14453 /* Okay, now we wait */
14454 timeout = iaxdefaulttimeout * 1000;
14455 /* Temporarily unlock */
14456 AST_LIST_UNLOCK(&dpcache);
14457 doabort = 0;
14458
14459 /* chan is in autoservice here, so do NOT service it here! */
14460 pfd.fd = com[0];
14461 pfd.events = POLLIN;
14462 pfd.revents = 0;
14463 /* Wait for pipe activity... if the channel hangs up, we'll catch it on the way out. */
14464 res = ast_poll(&pfd, 1, timeout);
14465 if (res < 0) {
14466 ast_log(LOG_WARNING, "poll returned < 0: %s\n", strerror(errno));
14467 return NULL;
14468 } else if (!pfd.revents) {
14469 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14470 }
14471
14472 if (chan && ast_check_hangup(chan)) {
14473 doabort = 1;
14474 }
14475
14476 AST_LIST_LOCK(&dpcache);
14477 dp->waiters[x] = -1;
14478 close(com[1]);
14479 close(com[0]);
14480 if (doabort) {
14481 /* Don't interpret anything, just abort. */
14482 return NULL;
14483 }
14484 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14485 /* Now to do non-independent analysis the results of our wait */
14486 if (dp->flags & CACHE_FLAG_PENDING) {
14487 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
14488 pending. Don't let it take as long to timeout. */
14489 dp->flags &= ~CACHE_FLAG_PENDING;
14490 dp->flags |= CACHE_FLAG_TIMEOUT;
14491 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14492 systems without leaving it unavailable once the server comes back online */
14493 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14494 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14495 if (dp->waiters[x] > -1) {
14496 if (write(dp->waiters[x], "asdf", 4) < 0) {
14497 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14498 }
14499 }
14500 }
14501 }
14502 }
14503 /* Our caller will obtain the rest */
14504 }
14505 return dp;
14506 }
14507
14508 /*! \brief Part of the IAX2 switch interface */
14509 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14510 {
14511 int res = 0;
14512 struct iax2_dpcache *dp = NULL;
14513 #if 0
14514 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14515 #endif
14516 if ((priority != 1) && (priority != 2))
14517 return 0;
14518
14519 AST_LIST_LOCK(&dpcache);
14520 if ((dp = find_cache(chan, data, context, exten, priority))) {
14521 if (dp->flags & CACHE_FLAG_EXISTS)
14522 res = 1;
14523 } else {
14524 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14525 }
14526 AST_LIST_UNLOCK(&dpcache);
14527
14528 return res;
14529 }
14530
14531 /*! \brief part of the IAX2 dial plan switch interface */
14532 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14533 {
14534 int res = 0;
14535 struct iax2_dpcache *dp = NULL;
14536 #if 0
14537 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14538 #endif
14539 if ((priority != 1) && (priority != 2))
14540 return 0;
14541
14542 AST_LIST_LOCK(&dpcache);
14543 if ((dp = find_cache(chan, data, context, exten, priority))) {
14544 if (dp->flags & CACHE_FLAG_CANEXIST)
14545 res = 1;
14546 } else {
14547 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14548 }
14549 AST_LIST_UNLOCK(&dpcache);
14550
14551 return res;
14552 }
14553
14554 /*! \brief Part of the IAX2 Switch interface */
14555 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14556 {
14557 int res = 0;
14558 struct iax2_dpcache *dp = NULL;
14559 #if 0
14560 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14561 #endif
14562 if ((priority != 1) && (priority != 2))
14563 return 0;
14564
14565 AST_LIST_LOCK(&dpcache);
14566 if ((dp = find_cache(chan, data, context, exten, priority))) {
14567 if (dp->flags & CACHE_FLAG_MATCHMORE)
14568 res = 1;
14569 } else {
14570 ast_log(LOG_WARNING, "Unable to make DP cache\n");
14571 }
14572 AST_LIST_UNLOCK(&dpcache);
14573
14574 return res;
14575 }
14576
14577 /*! \brief Execute IAX2 dialplan switch */
14578 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14579 {
14580 char odata[256];
14581 char req[sizeof(odata) + AST_MAX_CONTEXT + AST_MAX_EXTENSION + sizeof("IAX2//@")];
14582 char *ncontext;
14583 struct iax2_dpcache *dp = NULL;
14584 struct ast_app *dial = NULL;
14585 #if 0
14586 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);
14587 #endif
14588 if (priority == 2) {
14589 /* Indicate status, can be overridden in dialplan */
14590 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14591 if (dialstatus) {
14592 dial = pbx_findapp(dialstatus);
14593 if (dial)
14594 pbx_exec(chan, dial, "");
14595 }
14596 return -1;
14597 } else if (priority != 1)
14598 return -1;
14599
14600 AST_LIST_LOCK(&dpcache);
14601 if ((dp = find_cache(chan, data, context, exten, priority))) {
14602 if (dp->flags & CACHE_FLAG_EXISTS) {
14603 ast_copy_string(odata, data, sizeof(odata));
14604 ncontext = strchr(odata, '/');
14605 if (ncontext) {
14606 *ncontext = '\0';
14607 ncontext++;
14608 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14609 } else {
14610 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14611 }
14612 ast_verb(3, "Executing Dial('%s')\n", req);
14613 } else {
14614 AST_LIST_UNLOCK(&dpcache);
14615 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14616 return -1;
14617 }
14618 }
14619 AST_LIST_UNLOCK(&dpcache);
14620
14621 if ((dial = pbx_findapp("Dial")))
14622 return pbx_exec(chan, dial, req);
14623 else
14624 ast_log(LOG_WARNING, "No dial application registered\n");
14625
14626 return -1;
14627 }
14628
14629 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14630 {
14631 struct iax2_peer *peer;
14632 char *peername, *colname;
14633
14634 peername = ast_strdupa(data);
14635
14636 /* if our channel, return the IP address of the endpoint of current channel */
14637 if (!strcmp(peername,"CURRENTCHANNEL")) {
14638 unsigned short callno;
14639 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14640 return -1;
14641 }
14642 callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
14643 ast_copy_string(buf, !ast_sockaddr_isnull(&iaxs[callno]->addr) ? ast_sockaddr_stringify_addr(&iaxs[callno]->addr) : "", len);
14644 return 0;
14645 }
14646
14647 if ((colname = strchr(peername, ',')))
14648 *colname++ = '\0';
14649 else
14650 colname = "ip";
14651
14652 if (!(peer = find_peer(peername, 1)))
14653 return -1;
14654
14655 if (!strcasecmp(colname, "ip")) {
14656 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
14657 } else if (!strcasecmp(colname, "status")) {
14658 peer_status(peer, buf, len);
14659 } else if (!strcasecmp(colname, "mailbox")) {
14660 ast_copy_string(buf, peer->mailbox, len);
14661 } else if (!strcasecmp(colname, "context")) {
14662 ast_copy_string(buf, peer->context, len);
14663 } else if (!strcasecmp(colname, "expire")) {
14664 snprintf(buf, len, "%d", peer->expire);
14665 } else if (!strcasecmp(colname, "dynamic")) {
14666 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14667 } else if (!strcasecmp(colname, "callerid_name")) {
14668 ast_copy_string(buf, peer->cid_name, len);
14669 } else if (!strcasecmp(colname, "callerid_num")) {
14670 ast_copy_string(buf, peer->cid_num, len);
14671 } else if (!strcasecmp(colname, "codecs")) {
14672 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
14673
14674 iax2_getformatname_multiple(peer->capability, &codec_buf);
14675 ast_copy_string(buf, ast_str_buffer(codec_buf), len);
14676 } else if (!strncasecmp(colname, "codec[", 6)) {
14677 char *codecnum, *ptr;
14678 struct ast_format *tmpfmt;
14679
14680 /* skip over "codec" to the '[' */
14681 codecnum = colname + 5;
14682 *codecnum = '\0';
14683 codecnum++;
14684 if ((ptr = strchr(codecnum, ']'))) {
14685 *ptr = '\0';
14686 }
14687 if((iax2_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14688 ast_copy_string(buf, ast_format_get_name(tmpfmt), len);
14689 } else {
14690 buf[0] = '\0';
14691 }
14692 } else {
14693 buf[0] = '\0';
14694 }
14695
14696 peer_unref(peer);
14697
14698 return 0;
14699 }
14700
14701 static struct ast_custom_function iaxpeer_function = {
14702 .name = "IAXPEER",
14703 .read = function_iaxpeer,
14704 };
14705
14706 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14707 {
14708 struct chan_iax2_pvt *pvt;
14709 unsigned int callno;
14710 int res = 0;
14711
14712 if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14713 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14714 return -1;
14715 }
14716
14717 callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
14718 ast_mutex_lock(&iaxsl[callno]);
14719 if (!(pvt = iaxs[callno])) {
14720 ast_mutex_unlock(&iaxsl[callno]);
14721 return -1;
14722 }
14723
14724 if (!strcasecmp(args, "osptoken")) {
14725 ast_copy_string(buf, pvt->osptoken, buflen);
14726 } else if (!strcasecmp(args, "peerip")) {
14727 ast_copy_string(buf, !ast_sockaddr_isnull(&pvt->addr) ? ast_sockaddr_stringify_addr(&pvt->addr) : "", buflen);
14728 } else if (!strcasecmp(args, "peername")) {
14729 ast_copy_string(buf, pvt->username, buflen);
14730 } else if (!strcasecmp(args, "auth_method")) {
14731 ast_copy_string(buf, auth_method_labels[pvt->eff_auth_method], buflen);
14732 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14733 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14734 } else {
14735 res = -1;
14736 }
14737
14738 ast_mutex_unlock(&iaxsl[callno]);
14739
14740 return res;
14741 }
14742
14743 /*! \brief Part of the device state notification system ---*/
14744 static int iax2_devicestate(const char *data)
14745 {
14746 struct parsed_dial_string pds;
14747 char *tmp = ast_strdupa(data);
14748 struct iax2_peer *p;
14749 int res = AST_DEVICE_INVALID;
14750
14751 memset(&pds, 0, sizeof(pds));
14752 parse_dial_string(tmp, &pds);
14753
14754 if (ast_strlen_zero(pds.peer)) {
14755 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14756 return res;
14757 }
14758
14759 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14760
14761 /* SLD: FIXME: second call to find_peer during registration */
14762 if (!(p = find_peer(pds.peer, 1)))
14763 return res;
14764
14765 res = AST_DEVICE_UNAVAILABLE;
14766
14767 ast_debug(3, "Found peer. What's device state of %s? addr=%s, defaddr=%s maxms=%d, lastms=%d\n",
14768 pds.peer, ast_sockaddr_stringify(&p->addr), ast_sockaddr_stringify(&p->defaddr), p->maxms, p->lastms);
14769
14770 if (((!ast_sockaddr_isnull(&p->addr)) || (!ast_sockaddr_isnull(&p->defaddr))) &&
14771 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14772 /* Peer is registered, or have default IP address
14773 and a valid registration */
14774 if (p->historicms == 0 || p->historicms <= p->maxms)
14775 /* let the core figure out whether it is in use or not */
14776 res = AST_DEVICE_UNKNOWN;
14777 }
14778
14779 peer_unref(p);
14780
14781 return res;
14782 }
14783
14784 static struct ast_switch iax2_switch =
14785 {
14786 .name = "IAX2",
14787 .description = "IAX Remote Dialplan Switch",
14788 .exists = iax2_exists,
14789 .canmatch = iax2_canmatch,
14790 .exec = iax2_exec,
14791 .matchmore = iax2_matchmore,
14792 };
14793
14794 static struct ast_cli_entry cli_iax2[] = {
14795 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14796 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14797 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14798 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14799 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14800 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14801 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14802 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14803 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14804 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14805 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14806 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14807 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14808 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14809 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14810 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14811 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14812 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14813 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14814 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14815 #ifdef IAXTESTS
14816 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14817 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14818 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14819 #endif /* IAXTESTS */
14820 };
14821
14822 static void cleanup_thread_list(void *head)
14823 {
14824 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14825 struct iax2_thread_list *list_head = head;
14826 struct iax2_thread *thread;
14827
14828 AST_LIST_LOCK(list_head);
14829 while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14830 pthread_t thread_id = thread->threadid;
14831
14832 thread->stop = 1;
14833 signal_condition(&thread->lock, &thread->cond);
14834
14835 AST_LIST_UNLOCK(list_head);
14836 pthread_join(thread_id, NULL);
14837 AST_LIST_LOCK(list_head);
14838 }
14839 AST_LIST_UNLOCK(list_head);
14840 }
14841
14842 static int __unload_module(void)
14843 {
14844 int x;
14845
14846 network_change_stasis_unsubscribe();
14847 acl_change_stasis_unsubscribe();
14848
14849 ast_manager_unregister("IAXpeers");
14850 ast_manager_unregister("IAXpeerlist");
14851 ast_manager_unregister("IAXnetstats");
14852 ast_manager_unregister("IAXregistry");
14853 ast_unregister_application(papp);
14854 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14855 ast_unregister_switch(&iax2_switch);
14856 ast_channel_unregister(&iax2_tech);
14857
14858 if (netthreadid != AST_PTHREADT_NULL) {
14859 pthread_cancel(netthreadid);
14860 pthread_kill(netthreadid, SIGURG);
14861 pthread_join(netthreadid, NULL);
14862 }
14863
14864 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14865 if (iaxs[x]) {
14866 iax2_destroy(x);
14867 }
14868 }
14869
14870 /* Call for all threads to halt */
14871 cleanup_thread_list(&active_list);
14872 cleanup_thread_list(&dynamic_list);
14873 cleanup_thread_list(&idle_list);
14874
14875 ast_netsock_release(netsock);
14876 ast_netsock_release(outsock);
14877 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14878 if (iaxs[x]) {
14879 iax2_destroy(x);
14880 }
14881 }
14882 ast_manager_unregister( "IAXpeers" );
14883 ast_manager_unregister( "IAXpeerlist" );
14884 ast_manager_unregister( "IAXnetstats" );
14885 ast_manager_unregister( "IAXregistry" );
14886 ast_unregister_application(papp);
14887 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14888 ast_unregister_switch(&iax2_switch);
14889 ast_channel_unregister(&iax2_tech);
14890 delete_users();
14891 iax_provision_unload();
14892 iax_firmware_unload();
14893
14894 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14895 ast_mutex_destroy(&iaxsl[x]);
14896 }
14897
14898 ao2_ref(peers, -1);
14899 ao2_ref(users, -1);
14900 ao2_ref(iax_peercallno_pvts, -1);
14901 ao2_ref(iax_transfercallno_pvts, -1);
14902 ao2_ref(callno_limits, -1);
14903 ao2_ref(calltoken_ignores, -1);
14904 if (timer) {
14905 ast_timer_close(timer);
14906 timer = NULL;
14907 }
14908 transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14909
14910 ast_sched_clean_by_callback(sched, peercnt_remove_cb, peercnt_remove_cb);
14911 ast_sched_context_destroy(sched);
14912 sched = NULL;
14913 ao2_ref(peercnts, -1);
14914
14915 ast_context_destroy_by_name(regcontext, "IAX2");
14916 ast_unload_realtime("iaxpeers");
14917
14918 ao2_ref(iax2_tech.capabilities, -1);
14919 iax2_tech.capabilities = NULL;
14920 return 0;
14921 }
14922
14923 static int unload_module(void)
14924 {
14925 ast_custom_function_unregister(&iaxpeer_function);
14926 ast_custom_function_unregister(&iaxvar_function);
14927 return __unload_module();
14928 }
14929
14930 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14931 {
14932 struct iax2_peer *peer = obj;
14933
14934 if (peer->sockfd < 0)
14935 peer->sockfd = defaultsockfd;
14936
14937 return 0;
14938 }
14939
14940 static int pvt_hash_cb(const void *obj, const int flags)
14941 {
14942 const struct chan_iax2_pvt *pvt = obj;
14943
14944 return pvt->peercallno;
14945 }
14946
14947 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14948 {
14949 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14950
14951 /* The frames_received field is used to hold whether we're matching
14952 * against a full frame or not ... */
14953
14954 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14955 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14956 }
14957
14958 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14959 {
14960 const struct chan_iax2_pvt *pvt = obj;
14961
14962 return pvt->transfercallno;
14963 }
14964
14965 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14966 {
14967 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14968
14969 /* The frames_received field is used to hold whether we're matching
14970 * against a full frame or not ... */
14971
14972 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14973 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14974 }
14975
14976 static int load_objects(void)
14977 {
14978 peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14979 peercnts = callno_limits = calltoken_ignores = NULL;
14980
14981 peers = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAX_PEER_BUCKETS,
14982 peer_hash_cb, NULL, peer_cmp_cb);
14983 if (!peers) {
14984 goto container_fail;
14985 }
14986
14987 users = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAX_USER_BUCKETS,
14988 user_hash_cb, NULL, user_cmp_cb);
14989 if (!users) {
14990 goto container_fail;
14991 }
14992
14993 iax_peercallno_pvts = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
14994 IAX_MAX_CALLS, pvt_hash_cb, NULL, pvt_cmp_cb);
14995 if (!iax_peercallno_pvts) {
14996 goto container_fail;
14997 }
14998
14999 iax_transfercallno_pvts = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
15000 IAX_MAX_CALLS, transfercallno_pvt_hash_cb, NULL, transfercallno_pvt_cmp_cb);
15001 if (!iax_transfercallno_pvts) {
15002 goto container_fail;
15003 }
15004
15005 peercnts = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, MAX_PEER_BUCKETS,
15006 peercnt_hash_cb, NULL, peercnt_cmp_cb);
15007 if (!peercnts) {
15008 goto container_fail;
15009 }
15010
15011 callno_limits = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
15012 MAX_PEER_BUCKETS, addr_range_hash_cb, NULL, addr_range_cmp_cb);
15013 if (!callno_limits) {
15014 goto container_fail;
15015 }
15016
15017 calltoken_ignores = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
15018 MAX_PEER_BUCKETS, addr_range_hash_cb, NULL, addr_range_cmp_cb);
15019 if (!calltoken_ignores) {
15020 goto container_fail;
15021 }
15022
15023 if (create_callno_pools()) {
15024 goto container_fail;
15025 }
15026
15027 transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT);
15028 if (!transmit_processor) {
15029 goto container_fail;
15030 }
15031
15032 return 0;
15033
15034 container_fail:
15035 if (peers) {
15036 ao2_ref(peers, -1);
15037 }
15038 if (users) {
15039 ao2_ref(users, -1);
15040 }
15041 if (iax_peercallno_pvts) {
15042 ao2_ref(iax_peercallno_pvts, -1);
15043 }
15044 if (iax_transfercallno_pvts) {
15045 ao2_ref(iax_transfercallno_pvts, -1);
15046 }
15047 if (peercnts) {
15048 ao2_ref(peercnts, -1);
15049 }
15050 if (callno_limits) {
15051 ao2_ref(callno_limits, -1);
15052 }
15053 if (calltoken_ignores) {
15054 ao2_ref(calltoken_ignores, -1);
15055 }
15056 return -1;
15057 }
15058
15059 /*!
15060 * \brief Load the module
15061 *
15062 * Module loading including tests for configuration or dependencies.
15063 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
15064 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
15065 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
15066 * configuration file or other non-critical problem return
15067 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
15068 */
15069 static int load_module(void)
15070 {
15071 static const char config[] = "iax.conf";
15072 int x = 0;
15073 struct iax2_registry *reg = NULL;
15074
15075 if (!(iax2_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
15076 return AST_MODULE_LOAD_DECLINE;
15077 }
15078 ast_format_cap_append_by_type(iax2_tech.capabilities, AST_MEDIA_TYPE_UNKNOWN);
15079
15080 if (load_objects()) {
15081 ao2_ref(iax2_tech.capabilities, -1);
15082 iax2_tech.capabilities = NULL;
15083 return AST_MODULE_LOAD_DECLINE;
15084 }
15085
15086 memset(iaxs, 0, sizeof(iaxs));
15087
15088 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
15089 ast_mutex_init(&iaxsl[x]);
15090 }
15091
15092 if (!(sched = ast_sched_context_create())) {
15093 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
15094 ao2_ref(iax2_tech.capabilities, -1);
15095 iax2_tech.capabilities = NULL;
15096 return AST_MODULE_LOAD_DECLINE;
15097 }
15098
15099 if (ast_sched_start_thread(sched)) {
15100 ast_sched_context_destroy(sched);
15101 ao2_ref(iax2_tech.capabilities, -1);
15102 iax2_tech.capabilities = NULL;
15103 sched = NULL;
15104 return AST_MODULE_LOAD_DECLINE;
15105 }
15106
15107 if (!(io = io_context_create())) {
15108 ast_log(LOG_ERROR, "Failed to create I/O context\n");
15109 ast_sched_context_destroy(sched);
15110 ao2_ref(iax2_tech.capabilities, -1);
15111 iax2_tech.capabilities = NULL;
15112 sched = NULL;
15113 return AST_MODULE_LOAD_DECLINE;
15114 }
15115
15116 if (!(netsock = ast_netsock_list_alloc())) {
15117 ast_log(LOG_ERROR, "Failed to create netsock list\n");
15118 io_context_destroy(io);
15119 ast_sched_context_destroy(sched);
15120 ao2_ref(iax2_tech.capabilities, -1);
15121 iax2_tech.capabilities = NULL;
15122 sched = NULL;
15123 return AST_MODULE_LOAD_DECLINE;
15124 }
15125 ast_netsock_init(netsock);
15126
15127 outsock = ast_netsock_list_alloc();
15128 if (!outsock) {
15129 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
15130 io_context_destroy(io);
15131 ast_sched_context_destroy(sched);
15132 ao2_ref(iax2_tech.capabilities, -1);
15133 iax2_tech.capabilities = NULL;
15134 sched = NULL;
15135 return AST_MODULE_LOAD_DECLINE;
15136 }
15137 ast_netsock_init(outsock);
15138
15139 randomcalltokendata = ast_random();
15140
15141 iax_set_output(iax_debug_output);
15142 iax_set_error(iax_error_output);
15143 jb_setoutput(jb_error_output, jb_warning_output, NULL);
15144
15145 if ((timer = ast_timer_open())) {
15146 ast_timer_set_rate(timer, 1000 / trunkfreq);
15147 }
15148
15149 if (set_config(config, 0, 0) == -1) {
15150 if (timer) {
15151 ast_timer_close(timer);
15152 timer = NULL;
15153 }
15154 __unload_module();
15155 return AST_MODULE_LOAD_DECLINE;
15156 }
15157
15158 ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
15159
15160 ast_register_application_xml(papp, iax2_prov_app);
15161
15162 ast_custom_function_register(&iaxpeer_function);
15163 ast_custom_function_register(&iaxvar_function);
15164
15165 ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
15166 ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
15167 ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
15168 ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
15169
15170 if (ast_channel_register(&iax2_tech)) {
15171 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
15172 __unload_module();
15173 return AST_MODULE_LOAD_DECLINE;
15174 }
15175
15176 if (ast_register_switch(&iax2_switch)) {
15177 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
15178 }
15179
15180 if (start_network_thread()) {
15181 ast_log(LOG_ERROR, "Unable to start network thread\n");
15182 __unload_module();
15183 return AST_MODULE_LOAD_DECLINE;
15184 } else {
15185 ast_verb(2, "IAX Ready and Listening\n");
15186 }
15187
15188 AST_LIST_LOCK(&registrations);
15189 AST_LIST_TRAVERSE(&registrations, reg, entry)
15190 iax2_do_register(reg);
15191 AST_LIST_UNLOCK(&registrations);
15192
15193 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
15194 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
15195
15196
15197 iax_firmware_reload();
15198 iax_provision_reload(0);
15199
15200 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
15201
15202 network_change_stasis_subscribe();
15203
15204 return AST_MODULE_LOAD_SUCCESS;
15205 }
15206
15207 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
15208 .support_level = AST_MODULE_SUPPORT_CORE,
15209 .load = load_module,
15210 .unload = unload_module,
15211 .reload = reload,
15212 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
15213 .requires = "dnsmgr",
15214 .optional_modules = "res_crypto",
15215 );