Asterisk - The Open Source Telephony Project  18.5.0
chan_iax2.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <[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  * \par See also
27  * \arg \ref Config_iax
28  *
29  * \ingroup channel_drivers
30  *
31  * \todo Implement musicclass settings for IAX2 devices
32  */
33 
34 /*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35  * \addtogroup configuration_file
36  */
37 
38 /*! \page iax.conf iax.conf
39  * \verbinclude iax.conf.sample
40  */
41 
42 /*!
43  * \todo XXX The IAX2 channel driver needs its native bridge
44  * code converted to the new bridge technology scheme.
45  *
46  * \note The chan_dahdi native bridge code can be used as an
47  * example. It also appears that chan_iax2 also has a native
48  * transfer check like chan_dahdi to eliminate tromboned calls.
49  *
50  * \note The existing native bridge code is marked with the
51  * IAX2_NATIVE_BRIDGING conditional.
52  */
53 
54 /*** MODULEINFO
55  <use type="module">res_crypto</use>
56  <use type="external">crypto</use>
57  <support_level>core</support_level>
58  ***/
59 
60 #include "asterisk.h"
61 
62 #include <sys/mman.h>
63 #include <dirent.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <arpa/inet.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <sys/time.h>
70 #include <signal.h>
71 #include <netdb.h>
72 #include <fcntl.h>
73 #include <sys/stat.h>
74 #include <regex.h>
75 
76 #include "asterisk/paths.h"
77 
78 #include "asterisk/lock.h"
79 #include "asterisk/frame.h"
80 #include "asterisk/channel.h"
81 #include "asterisk/module.h"
82 #include "asterisk/pbx.h"
83 #include "asterisk/sched.h"
84 #include "asterisk/io.h"
85 #include "asterisk/config.h"
86 #include "asterisk/cli.h"
87 #include "asterisk/translate.h"
88 #include "asterisk/md5.h"
89 #include "asterisk/crypto.h"
90 #include "asterisk/acl.h"
91 #include "asterisk/manager.h"
92 #include "asterisk/callerid.h"
93 #include "asterisk/app.h"
94 #include "asterisk/mwi.h"
95 #include "asterisk/astdb.h"
96 #include "asterisk/musiconhold.h"
97 #include "asterisk/features.h"
98 #include "asterisk/utils.h"
99 #include "asterisk/causes.h"
100 #include "asterisk/localtime.h"
101 #include "asterisk/dnsmgr.h"
102 #include "asterisk/devicestate.h"
103 #include "asterisk/stringfields.h"
104 #include "asterisk/linkedlists.h"
105 #include "asterisk/astobj2.h"
106 #include "asterisk/timing.h"
107 #include "asterisk/taskprocessor.h"
108 #include "asterisk/test.h"
111 #include "asterisk/bridge.h"
112 #include "asterisk/stasis.h"
113 #include "asterisk/stasis_system.h"
115 #include "asterisk/format_cache.h"
117 #include "asterisk/format_cap.h"
118 
119 #include "iax2/include/iax2.h"
120 #include "iax2/include/firmware.h"
121 #include "iax2/include/parser.h"
122 #include "iax2/include/provision.h"
123 #include "iax2/include/codec_pref.h"
125 #include "iax2/include/netsock.h"
126 
127 #include "jitterbuf.h"
128 
129 /*** DOCUMENTATION
130  <application name="IAX2Provision" language="en_US">
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  <synopsis>
147  Gets IAX peer information.
148  </synopsis>
149  <syntax>
150  <parameter name="peername" required="true">
151  <enumlist>
152  <enum name="CURRENTCHANNEL">
153  <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
154  endpoint of the current channel</para>
155  </enum>
156  </enumlist>
157  </parameter>
158  <parameter name="item">
159  <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
160  <enumlist>
161  <enum name="ip">
162  <para>(default) The IP address.</para>
163  </enum>
164  <enum name="status">
165  <para>The peer's status (if <literal>qualify=yes</literal>)</para>
166  </enum>
167  <enum name="mailbox">
168  <para>The configured mailbox.</para>
169  </enum>
170  <enum name="context">
171  <para>The configured context.</para>
172  </enum>
173  <enum name="expire">
174  <para>The epoch time of the next expire.</para>
175  </enum>
176  <enum name="dynamic">
177  <para>Is it dynamic? (yes/no).</para>
178  </enum>
179  <enum name="callerid_name">
180  <para>The configured Caller ID name.</para>
181  </enum>
182  <enum name="callerid_num">
183  <para>The configured Caller ID number.</para>
184  </enum>
185  <enum name="codecs">
186  <para>The configured codecs.</para>
187  </enum>
188  <enum name="codec[x]">
189  <para>Preferred codec index number <replaceable>x</replaceable> (beginning
190  with <literal>0</literal>)</para>
191  </enum>
192  </enumlist>
193  </parameter>
194  </syntax>
195  <description>
196  <para>Gets information associated with the specified IAX2 peer.</para>
197  </description>
198  <see-also>
199  <ref type="function">SIPPEER</ref>
200  </see-also>
201  </function>
202  <function name="IAXVAR" language="en_US">
203  <synopsis>
204  Sets or retrieves a remote variable.
205  </synopsis>
206  <syntax>
207  <parameter name="varname" required="true" />
208  </syntax>
209  <description>
210  <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
211  </description>
212  </function>
213  <info name="CHANNEL" language="en_US" tech="IAX">
214  <enumlist>
215  <enum name="osptoken">
216  <para>R/O Get the peer's osptoken.</para>
217  </enum>
218  <enum name="peerip">
219  <para>R/O Get the peer's ip address.</para>
220  </enum>
221  <enum name="peername">
222  <para>R/O Get the peer's username.</para>
223  </enum>
224  <enum name="secure_signaling">
225  <para>R/O Get the if the IAX channel is secured.</para>
226  </enum>
227  <enum name="secure_media">
228  <para>R/O Get the if the IAX channel is secured.</para>
229  </enum>
230  </enumlist>
231  </info>
232  <manager name="IAXpeers" language="en_US">
233  <synopsis>
234  List IAX peers.
235  </synopsis>
236  <syntax>
237  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
238  </syntax>
239  <description>
240  </description>
241  </manager>
242  <manager name="IAXpeerlist" language="en_US">
243  <synopsis>
244  List IAX Peers.
245  </synopsis>
246  <syntax>
247  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
248  </syntax>
249  <description>
250  <para>List all the IAX peers.</para>
251  </description>
252  </manager>
253  <manager name="IAXnetstats" language="en_US">
254  <synopsis>
255  Show IAX Netstats.
256  </synopsis>
257  <syntax />
258  <description>
259  <para>Show IAX channels network statistics.</para>
260  </description>
261  </manager>
262  <manager name="IAXregistry" language="en_US">
263  <synopsis>
264  Show IAX registrations.
265  </synopsis>
266  <syntax>
267  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
268  </syntax>
269  <description>
270  <para>Show IAX registrations.</para>
271  </description>
272  </manager>
273  ***/
274 
275 /* Define SCHED_MULTITHREADED to run the scheduler in a special
276  multithreaded mode. */
277 #define SCHED_MULTITHREADED
278 
279 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
280  thread is actually doing. */
281 #define DEBUG_SCHED_MULTITHREAD
282 
283 
284 #ifdef SO_NO_CHECK
285 static int nochecksums = 0;
286 #endif
287 
288 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
289 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
290 
291 #define DEFAULT_THREAD_COUNT 10
292 #define DEFAULT_MAX_THREAD_COUNT 100
293 #define DEFAULT_RETRY_TIME 1000
294 #define MEMORY_SIZE 100
295 #define DEFAULT_DROP 3
296 
297 #define DEBUG_SUPPORT
298 
299 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
300 
301 /* Sample over last 100 units to determine historic jitter */
302 #define GAMMA (0.01)
303 
305 
306 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
307 
308 
309 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
310  fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
311 #define MAX_TRUNK_MTU 1240
312 
313 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
314 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
315 
316 #define DEFAULT_CONTEXT "default"
317 
319 
320 static char language[MAX_LANGUAGE] = "";
321 static char regcontext[AST_MAX_CONTEXT] = "";
322 
323 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
324 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
325 static int network_change_sched_id = -1;
326 
327 static int maxauthreq = 3;
328 static int max_retries = 4;
329 static int ping_time = 21;
330 static int lagrq_time = 10;
331 static int maxjitterbuffer=1000;
332 static int resyncthreshold=1000;
333 static int maxjitterinterps=10;
334 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
335 
336 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
337 
338 static int trunkfreq = 20;
340 
341 static int authdebug = 0;
342 static int autokill = 0;
343 static int iaxcompat = 0;
344 static int last_authmethod = 0;
345 
346 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
347 
348 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
349 
350 static struct {
351  unsigned int tos;
352  unsigned int cos;
353 } qos = { 0, 0 };
354 
355 static int min_reg_expire;
356 static int max_reg_expire;
357 
358 static int srvlookup = 0;
359 
360 static struct ast_timer *timer; /* Timer for trunking */
361 
362 static struct ast_netsock_list *netsock;
363 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
364 static int defaultsockfd = -1;
365 
366 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
367 
368 /* Ethernet, etc */
369 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
370 /* T1, maybe ISDN */
371 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
372  ~AST_FORMAT_SLIN & \
373  ~AST_FORMAT_SLIN16 & \
374  ~AST_FORMAT_SIREN7 & \
375  ~AST_FORMAT_SIREN14 & \
376  ~AST_FORMAT_G719 & \
377  ~AST_FORMAT_ULAW & \
378  ~AST_FORMAT_ALAW & \
379  ~AST_FORMAT_G722)
380 /* A modem */
381 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
382  ~AST_FORMAT_G726 & \
383  ~AST_FORMAT_G726_AAL2 & \
384  ~AST_FORMAT_ADPCM)
385 
386 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
387  ~AST_FORMAT_G723)
388 
389 
390 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
391 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
392 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
393 
394 /* if a pvt has encryption setup done and is running on the call */
395 #define IAX_CALLENCRYPTED(pvt) \
396  (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
397 
398 #define IAX_DEBUGDIGEST(msg, key) do { \
399  int idx; \
400  char digest[33] = ""; \
401  \
402  if (!iaxdebug) \
403  break; \
404  \
405  for (idx = 0; idx < 16; idx++) \
406  sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
407  \
408  ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
409  } while(0)
410 
411 static struct io_context *io;
412 static struct ast_sched_context *sched;
413 
415 
416 static int iaxdebug = 0;
417 
418 static int iaxtrunkdebug = 0;
419 
420 static int test_losspct = 0;
421 #ifdef IAXTESTS
422 static int test_late = 0;
423 static int test_resync = 0;
424 static int test_jit = 0;
425 static int test_jitpct = 0;
426 #endif /* IAXTESTS */
427 
431 static int amaflags = 0;
432 static int adsi = 0;
433 static int delayreject = 0;
434 static int iax2_encryption = 0;
435 static int iax2_authmethods = 0;
436 
437 static struct ast_flags64 globalflags = { 0 };
438 
439 static pthread_t netthreadid = AST_PTHREADT_NULL;
440 
442  IAX_STATE_STARTED = (1 << 0),
444  IAX_STATE_TBD = (1 << 2),
445 };
446 
447 struct iax2_context {
450 };
451 
452 
453 #define IAX_HASCALLERID (uint64_t)(1LLU << 0) /*!< CallerID has been specified */
454 #define IAX_DELME (uint64_t)(1LLU << 1) /*!< Needs to be deleted */
455 #define IAX_TEMPONLY (uint64_t)(1LLU << 2) /*!< Temporary (realtime) */
456 #define IAX_TRUNK (uint64_t)(1LLU << 3) /*!< Treat as a trunk */
457 #define IAX_NOTRANSFER (uint64_t)(1LLU << 4) /*!< Don't native bridge */
458 #define IAX_USEJITTERBUF (uint64_t)(1LLU << 5) /*!< Use jitter buffer */
459 #define IAX_DYNAMIC (uint64_t)(1LLU << 6) /*!< dynamic peer */
460 #define IAX_SENDANI (uint64_t)(1LLU << 7) /*!< Send ANI along with CallerID */
461 #define IAX_RTSAVE_SYSNAME (uint64_t)(1LLU << 8) /*!< Save Systname on Realtime Updates */
462 #define IAX_ALREADYGONE (uint64_t)(1LLU << 9) /*!< Already disconnected */
463 #define IAX_PROVISION (uint64_t)(1LLU << 10) /*!< This is a provisioning request */
464 #define IAX_QUELCH (uint64_t)(1LLU << 11) /*!< Whether or not we quelch audio */
465 #define IAX_ENCRYPTED (uint64_t)(1LLU << 12) /*!< Whether we should assume encrypted tx/rx */
466 #define IAX_KEYPOPULATED (uint64_t)(1LLU << 13) /*!< Whether we have a key populated */
467 #define IAX_CODEC_USER_FIRST (uint64_t)(1LLU << 14) /*!< are we willing to let the other guy choose the codec? */
468 #define IAX_CODEC_NOPREFS (uint64_t)(1LLU << 15) /*!< Force old behaviour by turning off prefs */
469 #define IAX_CODEC_NOCAP (uint64_t)(1LLU << 16) /*!< only consider requested format and ignore capabilities*/
470 #define IAX_RTCACHEFRIENDS (uint64_t)(1LLU << 17) /*!< let realtime stay till your reload */
471 #define IAX_RTUPDATE (uint64_t)(1LLU << 18) /*!< Send a realtime update */
472 #define IAX_RTAUTOCLEAR (uint64_t)(1LLU << 19) /*!< erase me on expire */
473 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1LLU << 21) /*!< When using realtime, ignore registration expiration */
474 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1LLU << 22) /*!< Send trunk timestamps */
475 #define IAX_TRANSFERMEDIA (uint64_t)(1LLU << 23) /*!< When doing IAX2 transfers, transfer media only */
476 #define IAX_MAXAUTHREQ (uint64_t)(1LLU << 24) /*!< Maximum outstanding AUTHREQ restriction is in place */
477 #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 */
478 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1LLU << 26) /*!< Allow the FWDOWNL command? */
479 #define IAX_IMMEDIATE (uint64_t)(1LLU << 27) /*!< Allow immediate off-hook to extension s */
480 #define IAX_SENDCONNECTEDLINE (uint64_t)(1LLU << 28) /*!< Allow sending of connected line updates */
481 #define IAX_RECVCONNECTEDLINE (uint64_t)(1LLU << 29) /*!< Allow receiving of connected line updates */
482 #define IAX_FORCE_ENCRYPT (uint64_t)(1LLU << 30) /*!< Forces call encryption, if encryption not possible hangup */
483 #define IAX_SHRINKCALLERID (uint64_t)(1LLU << 31) /*!< Turn on and off caller id shrinking */
484 static int global_rtautoclear = 120;
485 
486 static int reload_config(int forced_reload);
487 
488 /*!
489  * \brief Call token validation settings.
490  */
492  /*! \brief Default calltoken required unless the ip is in the ignorelist */
494  /*! \brief Require call token validation. */
496  /*! \brief Require call token validation after a successful registration
497  * using call token validation occurs. */
499  /*! \brief Do not require call token validation. */
501 };
502 
503 struct iax2_user {
506  AST_STRING_FIELD(secret);
507  AST_STRING_FIELD(dbsecret);
511  AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
515  AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
516  );
517 
520  int amaflags;
521  int adsi;
522  uint64_t flags;
524  int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
525  int curauthreq; /*!< Current number of outstanding AUTHREQs */
526  struct iax2_codec_pref prefs;
527  struct ast_acl_list *acl;
530  enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
531 };
532 
533 struct iax2_peer {
536  AST_STRING_FIELD(username);
537  AST_STRING_FIELD(description); /*!< Description of the peer */
538  AST_STRING_FIELD(secret);
539  AST_STRING_FIELD(dbsecret);
540  AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
541 
542  AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
543  AST_STRING_FIELD(context); /*!< For transfers only */
544  AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
545  AST_STRING_FIELD(mailbox); /*!< Mailbox */
548  AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
549  /* Suggested caller id if registering */
550  AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
551  AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
552  AST_STRING_FIELD(zonetag); /*!< Time Zone */
553  AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
554  );
555  struct iax2_codec_pref prefs;
556  struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
557  struct ast_sockaddr addr;
558  int formats;
559  int sockfd; /*!< Socket to use for transmission */
560  struct ast_sockaddr mask;
561  int adsi;
562  uint64_t flags;
563 
564  /* Dynamic Registration fields */
565  struct ast_sockaddr defaddr; /*!< Default address if there is one */
566  int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
567  int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
568 
569  int expire; /*!< Schedule entry for expiry */
570  int expiry; /*!< How soon to expire */
571  iax2_format capability; /*!< Capability */
572 
573  /* Qualification */
574  int callno; /*!< Call number of POKE request */
575  int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
576  int lastms; /*!< How long last response took (in ms), or -1 for no response */
577  int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
578 
579  int pokefreqok; /*!< How often to check if the host is up */
580  int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
581  int historicms; /*!< How long recent average responses took */
582  int smoothing; /*!< Sample over how many units to determine historic ms */
583  uint16_t maxcallno; /*!< Max call number limit for this peer. Set on registration */
584 
585  struct ast_mwi_subscriber *mwi_event_sub; /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
586 
587  struct ast_acl_list *acl;
588  enum calltoken_peer_enum calltoken_required; /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
589 
590  struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
591 };
592 
593 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
594 
597  int sockfd;
598  struct ast_sockaddr addr;
599  struct timeval txtrunktime; /*!< Transmit trunktime */
600  struct timeval rxtrunktime; /*!< Receive trunktime */
601  struct timeval lasttxtime; /*!< Last transmitted trunktime */
602  struct timeval trunkact; /*!< Last trunk activity */
603  unsigned int lastsent; /*!< Last sent time */
604  /* Trunk data and length */
605  unsigned char *trunkdata;
606  unsigned int trunkdatalen;
607  unsigned int trunkdataalloc;
610  int calls;
612 };
613 
615 
624 };
625 
638 };
639 
641  struct ast_sockaddr addr; /*!< Who we connect to for registration purposes */
642  char username[80];
643  char secret[80]; /*!< Password or key name in []'s */
644  int expire; /*!< Sched ID of expiration */
645  int refresh; /*!< How often to refresh */
646  enum iax_reg_state regstate;
647  int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
648  int callno; /*!< Associated call number if applicable */
649  struct ast_sockaddr us; /*!< Who the server thinks we are */
650  struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
652  int port;
653  char hostname[];
654 };
655 
657 
658 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
659 #define MIN_RETRY_TIME 100
660 #define MAX_RETRY_TIME 10000
661 
662 #define MAX_JITTER_BUFFER 50
663 #define MIN_JITTER_BUFFER 10
664 
665 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
666 
667 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
668 
669 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
670 #define TS_GAP_FOR_JB_RESYNC 5000
671 
672 /* used for first_iax_message and last_iax_message. If this bit is set it was TX, else RX */
673 #define MARK_IAX_SUBCLASS_TX 0x8000
674 
677 static int iaxdynamicthreadcount = 0;
678 static int iaxdynamicthreadnum = 0;
679 static int iaxactivethreadcount = 0;
680 
681 struct iax_rr {
682  int jitter;
683  int losspct;
684  int losscnt;
685  int packets;
686  int delay;
687  int dropped;
688  int ooo;
689 };
690 
691 struct iax2_pvt_ref;
692 
693 /* We use the high order bit as the validated flag, and the lower 15 as the
694  * actual call number */
695 typedef uint16_t callno_entry;
696 
698  /*! Socket to send/receive on for this call */
699  int sockfd;
700  /*! ast_callid bound to dialog */
702  /*! Last received voice format */
704  /*! Last received video format */
706  /*! Last sent voice format */
708  /*! Last sent video format */
710  /*! What we are capable of sending */
712  /*! Last received timestamp */
713  unsigned int last;
714  /*! Last sent timestamp - never send the same timestamp twice in a single call */
715  unsigned int lastsent;
716  /*! Timestamp of the last video frame sent */
717  unsigned int lastvsent;
718  /*! Next outgoing timestamp if everything is good */
719  unsigned int nextpred;
720  /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
722  /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
724  /*! True if the last voice we transmitted was not silence/CNG */
725  unsigned int notsilenttx:1;
726  /*! Ping time */
727  unsigned int pingtime;
728  /*! Max time for initial response */
729  int maxtime;
730  /*! Peer Address */
731  struct ast_sockaddr addr;
732  /*! Actual used codec preferences */
733  struct iax2_codec_pref prefs;
734  /*! Requested codec preferences */
735  struct iax2_codec_pref rprefs;
736  /*! Our call number */
737  unsigned short callno;
738  /*! Our callno_entry entry */
739  callno_entry callno_entry;
740  /*! Peer callno */
741  unsigned short peercallno;
742  /*! Negotiated format, this is only used to remember what format was
743  chosen for an unauthenticated call so that the channel can get
744  created later using the right format */
746  /*! Peer selected format */
748  /*! Peer capability */
750  /*! timeval that we base our transmission on */
751  struct timeval offset;
752  /*! timeval that we base our delivery on */
753  struct timeval rxcore;
754  /*! The jitterbuffer */
756  /*! active jb read scheduler id */
757  int jbid;
758  /*! LAG */
759  int lag;
760  /*! Error, as discovered by the manager */
761  int error;
762  /*! Owner if we have one */
764  /*! What's our state? */
765  struct ast_flags state;
766  /*! Expiry (optional) */
767  int expiry;
768  /*! Next outgoing sequence number */
769  unsigned char oseqno;
770  /*! Next sequence number they have not yet acknowledged */
771  unsigned char rseqno;
772  /*! Next incoming sequence number */
773  unsigned char iseqno;
774  /*! Last incoming sequence number we have acknowledged */
775  unsigned char aseqno;
776 
778  /*! Peer name */
779  AST_STRING_FIELD(peer);
780  /*! Default Context */
782  /*! Caller ID if available */
785  /*! Hidden Caller ID (i.e. ANI) if appropriate */
786  AST_STRING_FIELD(ani);
787  /*! DNID */
788  AST_STRING_FIELD(dnid);
789  /*! RDNIS */
790  AST_STRING_FIELD(rdnis);
791  /*! Requested Extension */
793  /*! Expected Username */
794  AST_STRING_FIELD(username);
795  /*! Expected Secret */
796  AST_STRING_FIELD(secret);
797  /*! MD5 challenge */
799  /*! Public keys permitted keys for incoming authentication */
800  AST_STRING_FIELD(inkeys);
801  /*! Private key for outgoing authentication */
802  AST_STRING_FIELD(outkey);
803  /*! Preferred language */
805  /*! Hostname/peername for naming purposes */
807 
808  AST_STRING_FIELD(dproot);
812  /*! received OSP token */
813  AST_STRING_FIELD(osptoken);
814  /*! Default parkinglot */
816  );
817  /*! AUTHREJ all AUTHREP frames */
818  int authrej;
819  /*! permitted authentication methods */
821  /*! permitted encryption methods */
823  /*! Encryption AES-128 Key */
825  /*! Decryption AES-128 Key corresponding to ecx */
827  /*! Decryption AES-128 Key used to decrypt peer frames */
829  /*! scheduler id associated with iax_key_rotate
830  * for encrypted calls*/
832  /*! 32 bytes of semi-random data */
833  unsigned char semirand[32];
834  /*! Associated registry */
836  /*! Associated peer for poking */
838  /*! IAX_ flags */
839  uint64_t flags;
840  int adsi;
841 
842  /*! Transferring status */
843  enum iax_transfer_state transferring;
844  /*! Transfer identifier */
846  /*! Who we are IAX transferring to */
848  /*! What's the new call number for the transfer */
849  unsigned short transfercallno;
850  /*! Transfer encrypt AES-128 Key */
852 
853  /*! Status of knowledge of peer ADSI capability */
855 
856  /*! Callno of native bridge peer. (Valid if nonzero) */
857  unsigned short bridgecallno;
858 
859  int pingid; /*!< Transmit PING request */
860  int lagid; /*!< Retransmit lag request */
861  int autoid; /*!< Auto hangup for Dialplan requestor */
862  int authid; /*!< Authentication rejection ID */
863  int authfail; /*!< Reason to report failure */
864  int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
868  int amaflags;
870  /*! variables inherited from the user definition */
872  /*! variables transmitted in a NEW packet */
874  /*! last received remote rr */
875  struct iax_rr remote_rr;
876  /*! Current base time: (just for stats) */
877  int min;
878  /*! Dropped frame count: (just for stats) */
880  /*! received frame count: (just for stats) */
882  /*! Destroying this call initiated. */
884  /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
885  unsigned char calltoken_ie_len;
886  /*! hold all signaling frames from the pbx thread until we have a destination callno */
888  /*! frame queue for signaling frames from pbx thread waiting for destination callno */
890 };
891 
893  struct ast_frame f;
895 };
896 
900 };
901 
902 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
903 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
904 
905 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
906 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
907 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
908 
910  size_t capacity;
911  size_t available;
912  callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
913 };
914 
916 
917 /*! table of available call numbers */
919 
920 /*! table of available trunk call numbers */
922 
923 /*!
924  * \brief a list of frames that may need to be retransmitted
925  *
926  * \note The contents of this list do not need to be explicitly destroyed
927  * on module unload. This is because all active calls are destroyed, and
928  * all frames in this queue will get destroyed as a part of that process.
929  *
930  * \note Contents protected by the iaxsl[] locks
931  */
933 
935 
937 
938 static time_t max_calltoken_delay = 10;
939 
940 /*!
941  * This module will get much higher performance when doing a lot of
942  * user and peer lookups if the number of buckets is increased from 1.
943  * However, to maintain old behavior for Asterisk 1.4, these are set to
944  * 1 by default. When using multiple buckets, search order through these
945  * containers is considered random, so you will not be able to depend on
946  * the order the entires are specified in iax.conf for matching order. */
947 #ifdef LOW_MEMORY
948 #define MAX_PEER_BUCKETS 17
949 #else
950 #define MAX_PEER_BUCKETS 563
951 #endif
952 static struct ao2_container *peers;
953 
954 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
955 static struct ao2_container *users;
956 
957 /*! Table containing peercnt objects for every ip address consuming a callno */
958 static struct ao2_container *peercnts;
959 
960 /*! Table containing custom callno limit rules for a range of ip addresses. */
962 
963 /*! Table containing ip addresses not requiring calltoken validation */
965 
966 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
967 
968 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
969 
970 static uint16_t global_maxcallno;
971 
972 /*! Total num of call numbers allowed to be allocated without calltoken validation */
973 static uint16_t global_maxcallno_nonval;
974 
975 static uint16_t total_nonval_callno_used = 0;
976 
977 /*! peer connection private, keeps track of all the call numbers
978  * consumed by a single ip address */
979 struct peercnt {
980  /*! ip address consuming call numbers */
981  struct ast_sockaddr addr;
982  /*! Number of call numbers currently used by this ip address */
983  uint16_t cur;
984  /*! Max call numbers allowed for this ip address */
985  uint16_t limit;
986  /*! Specifies whether limit is set by a registration or not, if so normal
987  * limit setting rules do not apply to this address. */
988  unsigned char reg;
989 };
990 
991 /*! used by both callno_limits and calltoken_ignores containers */
992 struct addr_range {
993  /*! ip address range for custom callno limit rule */
994  struct ast_ha ha;
995  /*! callno limit for this ip address range, only used in callno_limits container */
996  uint16_t limit;
997  /*! delete me marker for reloads */
998  unsigned char delme;
999 };
1000 
1001 enum {
1002  /*! Extension exists */
1003  CACHE_FLAG_EXISTS = (1 << 0),
1004  /*! Extension is nonexistent */
1006  /*! Extension can exist */
1008  /*! Waiting to hear back response */
1010  /*! Timed out */
1012  /*! Request transmitted */
1014  /*! Timeout */
1016  /*! Matchmore */
1018 };
1019 
1021  char peercontext[AST_MAX_CONTEXT];
1023  struct timeval orig;
1024  struct timeval expiry;
1025  int flags;
1026  unsigned short callno;
1027  int waiters[256];
1029  AST_LIST_ENTRY(iax2_dpcache) peer_list;
1030 };
1031 
1033 
1034 static void reg_source_db(struct iax2_peer *p);
1035 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1036 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1037 
1038 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1039 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1040 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1041 
1047 };
1048 
1052 };
1053 
1056  size_t len;
1057  unsigned char buf[1];
1058 };
1059 
1060 struct iax2_thread {
1063  enum iax2_thread_iostate iostate;
1064 #ifdef SCHED_MULTITHREADED
1065  void (*schedfunc)(const void *);
1066  const void *scheddata;
1067 #endif
1068 #ifdef DEBUG_SCHED_MULTITHREAD
1069  char curfunc[80];
1070 #endif
1071  int actions;
1072  pthread_t threadid;
1074  struct ast_sockaddr ioaddr;
1075  unsigned char readbuf[4096];
1076  unsigned char *buf;
1077  ssize_t buf_len;
1078  size_t buf_size;
1079  int iofd;
1080  time_t checktime;
1085  /*! if this thread is processing a full frame,
1086  some information about that frame will be stored
1087  here, so we can avoid dispatching any more full
1088  frames for that callno to other threads */
1089  struct {
1090  unsigned short callno;
1091  struct ast_sockaddr addr;
1092  unsigned char type;
1093  unsigned char csub;
1094  } ffinfo;
1095  /*! Queued up full frames for processing. If more full frames arrive for
1096  * a call which this thread is already processing a full frame for, they
1097  * are queued up here. */
1099  unsigned char stop;
1100 };
1101 
1102 /* Thread lists */
1106 
1107 static void *iax2_process_thread(void *data);
1108 static void iax2_destroy(int callno);
1109 
1111 {
1112  ast_mutex_lock(lock);
1113  ast_cond_signal(cond);
1114  ast_mutex_unlock(lock);
1115 }
1116 
1117 /*!
1118  * \brief an array of iax2 pvt structures
1119  *
1120  * The container for active chan_iax2_pvt structures is implemented as an
1121  * array for extremely quick direct access to the correct pvt structure
1122  * based on the local call number. The local call number is used as the
1123  * index into the array where the associated pvt structure is stored.
1124  */
1126 
1127 static ast_callid iax_pvt_callid_get(int callno)
1128 {
1129  return iaxs[callno]->callid;
1130 }
1131 
1132 static void iax_pvt_callid_set(int callno, ast_callid callid)
1133 {
1134  iaxs[callno]->callid = callid;
1135 }
1136 
1137 static void iax_pvt_callid_new(int callno)
1138 {
1139  ast_callid callid = ast_create_callid();
1140  char buffer[AST_CALLID_BUFFER_LENGTH];
1141  ast_callid_strnprint(buffer, sizeof(buffer), callid);
1142  iax_pvt_callid_set(callno, callid);
1143 }
1144 
1145 /*!
1146  * \brief Another container of iax2_pvt structures
1147  *
1148  * Active IAX2 pvt structs are also stored in this container, if they are a part
1149  * of an active call where we know the remote side's call number. The reason
1150  * for this is that incoming media frames do not contain our call number. So,
1151  * instead of having to iterate the entire iaxs array, we use this container to
1152  * look up calls where the remote side is using a given call number.
1153  */
1155 
1156 /*!
1157  * \brief chan_iax2_pvt structure locks
1158  *
1159  * These locks are used when accessing a pvt structure in the iaxs array.
1160  * The index used here is the same as used in the iaxs array. It is the
1161  * local call number for the associated pvt struct.
1162  */
1164 
1165 /*!
1166  * * \brief Another container of iax2_pvt structures
1167  *
1168  * Active IAX2 pvt stucts used during transfering a call are stored here.
1169  */
1171 
1172 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1173  but keeps the division between trunked and non-trunked better. */
1174 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1175 
1176 /* Debug routines... */
1177 static struct ast_sockaddr debugaddr;
1178 
1179 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1180 {
1181  if (iaxdebug ||
1182  (addr && !ast_sockaddr_isnull(&debugaddr) &&
1185  !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1186 
1187  if (iaxdebug) {
1188  iax_showframe(f, fhi, rx, addr, datalen);
1189  } else {
1190  iaxdebug = 1;
1191  iax_showframe(f, fhi, rx, addr, datalen);
1192  iaxdebug = 0;
1193  }
1194  }
1195 }
1196 
1197 static void iax_debug_output(const char *data)
1198 {
1199  if (iaxdebug)
1200  ast_verbose("%s", data);
1201 }
1202 
1203 static void iax_error_output(const char *data)
1204 {
1205  ast_log(LOG_WARNING, "%s", data);
1206 }
1207 
1208 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1209 {
1210  va_list args;
1211  char buf[1024];
1212 
1213  va_start(args, fmt);
1214  vsnprintf(buf, sizeof(buf), fmt, args);
1215  va_end(args);
1216 
1217  ast_log(LOG_ERROR, "%s", buf);
1218 }
1219 
1220 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1221 {
1222  va_list args;
1223  char buf[1024];
1224 
1225  va_start(args, fmt);
1226  vsnprintf(buf, sizeof(buf), fmt, args);
1227  va_end(args);
1228 
1229  ast_log(LOG_WARNING, "%s", buf);
1230 }
1231 
1232 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1233 {
1234  va_list args;
1235  char buf[1024];
1236 
1237  va_start(args, fmt);
1238  vsnprintf(buf, sizeof(buf), fmt, args);
1239  va_end(args);
1240 
1241  ast_verbose("%s", buf);
1242 }
1243 
1244 static int expire_registry(const void *data);
1245 static int iax2_answer(struct ast_channel *c);
1246 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1247 static int iax2_devicestate(const char *data);
1248 static int iax2_digit_begin(struct ast_channel *c, char digit);
1249 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1250 static int iax2_do_register(struct iax2_registry *reg);
1251 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1252 static int iax2_hangup(struct ast_channel *c);
1253 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1254 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1255 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1256 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1257 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1258 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1259 static int iax2_sendtext(struct ast_channel *c, const char *text);
1260 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1261 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1262 static int iax2_transfer(struct ast_channel *c, const char *dest);
1263 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1264 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1265 
1266 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1267 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1268 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1269 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1270 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1271 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1272 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);
1273 static struct ast_frame *iax2_read(struct ast_channel *c);
1274 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1275 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1276 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1277 static void *iax2_dup_variable_datastore(void *);
1278 static void prune_peers(void);
1279 static void prune_users(void);
1280 static void iax2_free_variable_datastore(void *);
1281 
1282 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1283 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1284 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1285 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1286 static void build_rand_pad(unsigned char *buf, ssize_t len);
1287 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1288 static int replace_callno(const void *obj);
1289 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1290 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1291 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1292 
1293 static struct ast_channel_tech iax2_tech = {
1294  .type = "IAX2",
1295  .description = tdesc,
1296  .properties = AST_CHAN_TP_WANTSJITTER,
1297  .requester = iax2_request,
1298  .devicestate = iax2_devicestate,
1299  .send_digit_begin = iax2_digit_begin,
1300  .send_digit_end = iax2_digit_end,
1301  .send_text = iax2_sendtext,
1302  .send_image = iax2_sendimage,
1303  .send_html = iax2_sendhtml,
1304  .call = iax2_call,
1305  .hangup = iax2_hangup,
1306  .answer = iax2_answer,
1307  .read = iax2_read,
1308  .write = iax2_write,
1309  .write_video = iax2_write,
1310  .indicate = iax2_indicate,
1311  .setoption = iax2_setoption,
1312  .queryoption = iax2_queryoption,
1313  .transfer = iax2_transfer,
1314  .fixup = iax2_fixup,
1315  .func_channel_read = acf_channel_read,
1316 };
1317 
1318 /*!
1319  * \internal
1320  * \brief Obtain the owner channel lock if the owner exists.
1321  *
1322  * \param callno IAX2 call id.
1323  *
1324  * \note Assumes the iaxsl[callno] lock is already obtained.
1325  *
1326  * \note
1327  * IMPORTANT NOTE!!! Any time this function is used, even if
1328  * iaxs[callno] was valid before calling it, it may no longer be
1329  * valid after calling it. This function may unlock and lock
1330  * the mutex associated with this callno, meaning that another
1331  * thread may grab it and destroy the call.
1332  *
1333  * \return Nothing
1334  */
1335 static void iax2_lock_owner(int callno)
1336 {
1337  for (;;) {
1338  if (!iaxs[callno] || !iaxs[callno]->owner) {
1339  /* There is no owner lock to get. */
1340  break;
1341  }
1342  if (!ast_channel_trylock(iaxs[callno]->owner)) {
1343  /* We got the lock */
1344  break;
1345  }
1346  /* Avoid deadlock by pausing and trying again */
1347  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1348  }
1349 }
1350 
1351 /*!
1352  * \internal
1353  * \brief Check if a control subtype is allowed on the wire.
1354  *
1355  * \param subtype Control frame subtype to check if allowed to/from the wire.
1356  *
1357  * \retval non-zero if allowed.
1358  */
1359 static int iax2_is_control_frame_allowed(int subtype)
1360 {
1361  enum ast_control_frame_type control = subtype;
1362  int is_allowed;
1363 
1364  /*
1365  * Note: If we compare the enumeration type, which does not have any
1366  * negative constants, the compiler may optimize this code away.
1367  * Therefore, we must perform an integer comparison here.
1368  */
1369  if (subtype == -1) {
1370  return -1;
1371  }
1372 
1373  /* Default to not allowing control frames to pass. */
1374  is_allowed = 0;
1375 
1376  /*
1377  * The switch default is not present in order to take advantage
1378  * of the compiler complaining of a missing enum case.
1379  */
1380  switch (control) {
1381  /*
1382  * These control frames make sense to send/receive across the link.
1383  */
1384  case AST_CONTROL_HANGUP:
1385  case AST_CONTROL_RING:
1386  case AST_CONTROL_RINGING:
1387  case AST_CONTROL_ANSWER:
1388  case AST_CONTROL_BUSY:
1390  case AST_CONTROL_OFFHOOK:
1392  case AST_CONTROL_FLASH:
1393  case AST_CONTROL_WINK:
1394  case AST_CONTROL_OPTION:
1395  case AST_CONTROL_RADIO_KEY:
1397  case AST_CONTROL_PROGRESS:
1399  case AST_CONTROL_HOLD:
1400  case AST_CONTROL_UNHOLD:
1401  case AST_CONTROL_VIDUPDATE:
1405  case AST_CONTROL_AOC:
1407  case AST_CONTROL_MCID:
1408  is_allowed = -1;
1409  break;
1410 
1411  /*
1412  * These control frames do not make sense to send/receive across the link.
1413  */
1414  case _XXX_AST_CONTROL_T38:
1415  /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1416  case AST_CONTROL_SRCUPDATE:
1417  /* Across an IAX link the source is still the same. */
1418  case AST_CONTROL_TRANSFER:
1419  /* A success/fail status report from calling ast_transfer() on this machine. */
1420  case AST_CONTROL_CC:
1421  /* The payload contains pointers that are valid for the sending machine only. */
1422  case AST_CONTROL_SRCCHANGE:
1423  /* Across an IAX link the source is still the same. */
1425  /* The action can only be done by the sending machine. */
1426  case AST_CONTROL_END_OF_Q:
1427  /* This frame would cause the call to unexpectedly hangup. */
1429  /* Only meaningful across a bridge on this machine for direct-media exchange. */
1431  /* Intended only for the sending machine's local channel structure. */
1433  /* Intended only for masquerades when calling ast_indicate_data(). */
1435  /* Intended only for internal stream topology manipulation. */
1437  /* Intended only for internal stream topology change notification. */
1444  /* None of these playback stream control frames should go across the link. */
1449  /* None of these media recording control frames should go across the link. */
1450  break;
1451  }
1452  return is_allowed;
1453 }
1454 
1456 {
1457  if (!network_change_sub) {
1458  network_change_sub = stasis_subscribe(ast_system_topic(),
1459  network_change_stasis_cb, NULL);
1462  }
1463 }
1464 
1466 {
1467  network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1468 }
1469 
1471 {
1472  if (!acl_change_sub) {
1473  acl_change_sub = stasis_subscribe(ast_security_topic(),
1474  acl_change_stasis_cb, NULL);
1477  }
1478 }
1479 
1481 {
1482  acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1483 }
1484 
1485 static int network_change_sched_cb(const void *data)
1486 {
1487  struct iax2_registry *reg;
1490  AST_LIST_TRAVERSE(&registrations, reg, entry) {
1491  iax2_do_register(reg);
1492  }
1494 
1495  return 0;
1496 }
1497 
1498 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1499  struct stasis_message *message)
1500 {
1501  /* This callback is only concerned with network change messages from the system topic. */
1502  if (stasis_message_type(message) != ast_network_change_type()) {
1503  return;
1504  }
1505 
1506  ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1507  if (network_change_sched_id == -1) {
1509  }
1510 }
1511 
1512 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1513  struct stasis_message *message)
1514 {
1515  if (stasis_message_type(message) != ast_named_acl_change_type()) {
1516  return;
1517  }
1518 
1519  ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1520  reload_config(1);
1521 }
1522 
1524  .type = "IAX2_VARIABLE",
1525  .duplicate = iax2_dup_variable_datastore,
1526  .destroy = iax2_free_variable_datastore,
1527 };
1528 
1529 static void *iax2_dup_variable_datastore(void *old)
1530 {
1531  AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1532  struct ast_var_t *oldvar, *newvar;
1533 
1534  newlist = ast_calloc(sizeof(*newlist), 1);
1535  if (!newlist) {
1536  ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1537  return NULL;
1538  }
1539 
1540  AST_LIST_HEAD_INIT(newlist);
1541  AST_LIST_LOCK(oldlist);
1542  AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1543  newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1544  if (newvar)
1545  AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1546  else
1547  ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1548  }
1549  AST_LIST_UNLOCK(oldlist);
1550  return newlist;
1551 }
1552 
1553 static void iax2_free_variable_datastore(void *old)
1554 {
1555  AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1556  struct ast_var_t *oldvar;
1557 
1558  AST_LIST_LOCK(oldlist);
1559  while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1560  ast_free(oldvar);
1561  }
1562  AST_LIST_UNLOCK(oldlist);
1563  AST_LIST_HEAD_DESTROY(oldlist);
1564  ast_free(oldlist);
1565 }
1566 
1567 
1568 /* WARNING: insert_idle_thread should only ever be called within the
1569  * context of an iax2_process_thread() thread.
1570  */
1572 {
1573  if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1575  AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1577  } else {
1579  AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1581  }
1582 
1583  return;
1584 }
1585 
1586 static struct iax2_thread *find_idle_thread(void)
1587 {
1588  struct iax2_thread *thread = NULL;
1589 
1590  /* Pop the head of the idle list off */
1592  thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1594 
1595  /* If we popped a thread off the idle list, just return it */
1596  if (thread) {
1597  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1598  return thread;
1599  }
1600 
1601  /* Pop the head of the dynamic list off */
1605 
1606  /* If we popped a thread off the dynamic list, just return it */
1607  if (thread) {
1608  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1609  return thread;
1610  }
1611 
1612  /* If we can't create a new dynamic thread for any reason, return no thread at all */
1613  if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1614  return NULL;
1615 
1616  /* Set default values */
1617  ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1618  thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1619  thread->type = IAX_THREAD_TYPE_DYNAMIC;
1620 
1621  /* Initialize lock and condition */
1622  ast_mutex_init(&thread->lock);
1623  ast_cond_init(&thread->cond, NULL);
1624  ast_mutex_init(&thread->init_lock);
1625  ast_cond_init(&thread->init_cond, NULL);
1626  ast_mutex_lock(&thread->init_lock);
1627 
1628  /* Create thread and send it on it's way */
1630  ast_cond_destroy(&thread->cond);
1631  ast_mutex_destroy(&thread->lock);
1632  ast_mutex_unlock(&thread->init_lock);
1633  ast_cond_destroy(&thread->init_cond);
1634  ast_mutex_destroy(&thread->init_lock);
1635  ast_free(thread);
1636  return NULL;
1637  }
1638 
1639  /* this thread is not processing a full frame (since it is idle),
1640  so ensure that the field for the full frame call number is empty */
1641  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1642 
1643  /* Wait for the thread to be ready before returning it to the caller */
1644  ast_cond_wait(&thread->init_cond, &thread->init_lock);
1645 
1646  /* Done with init_lock */
1647  ast_mutex_unlock(&thread->init_lock);
1648 
1649  return thread;
1650 }
1651 
1652 #ifdef SCHED_MULTITHREADED
1653 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1654 {
1655  struct iax2_thread *thread;
1656  static time_t lasterror;
1657  time_t t;
1658 
1659  thread = find_idle_thread();
1660  if (thread != NULL) {
1661  thread->schedfunc = func;
1662  thread->scheddata = data;
1663  thread->iostate = IAX_IOSTATE_SCHEDREADY;
1664 #ifdef DEBUG_SCHED_MULTITHREAD
1665  ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1666 #endif
1667  signal_condition(&thread->lock, &thread->cond);
1668  return 0;
1669  }
1670  time(&t);
1671  if (t != lasterror) {
1672  lasterror = t;
1673  ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1674  }
1675 
1676  return -1;
1677 }
1678 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1679 #endif
1680 
1681 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1682  ast_sched_cb callback, const void *data)
1683 {
1684  return ast_sched_replace(id, con, when, callback, data);
1685 }
1686 
1687 static int iax2_sched_add(struct ast_sched_context *con, int when,
1688  ast_sched_cb callback, const void *data)
1689 {
1690  return ast_sched_add(con, when, callback, data);
1691 }
1692 
1693 /*
1694  * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1695  * \param callno Call number to lock.
1696  * \return 0 If call disappeared or has ongoing hangup procedure. 1 If call found and mutex is locked.
1697  */
1699 {
1700  ast_mutex_lock(&iaxsl[callno]);
1701 
1702  /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1703  * or destroy initiated (in middle of hang up procedure. */
1704  if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1705  ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1706  ast_mutex_unlock(&iaxsl[callno]);
1707  return 0;
1708  }
1709 
1710  /* Lock acquired, and callno is alive and kicking. */
1711  return 1;
1712 }
1713 
1714 static int send_ping(const void *data);
1715 
1716 static void __send_ping(const void *data)
1717 {
1718  int callno = PTR_TO_CALLNO(data);
1719 
1720  if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1721  ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1722  return;
1723  }
1724 
1725  /* Mark pingid as invalid scheduler id. */
1726  iaxs[callno]->pingid = -1;
1727 
1728  /* callno is now locked. */
1729  if (iaxs[callno]->peercallno) {
1730  /* Send PING packet. */
1731  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1732 
1733  /* Schedule sending next ping. */
1734  iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1735  }
1736 
1737  ast_mutex_unlock(&iaxsl[callno]);
1738 }
1739 
1740 static int send_ping(const void *data)
1741 {
1742 #ifdef SCHED_MULTITHREADED
1743  if (schedule_action(__send_ping, data))
1744 #endif
1745  __send_ping(data);
1746 
1747  return 0;
1748 }
1749 
1750 static void encmethods_to_str(int e, struct ast_str **buf)
1751 {
1752  ast_str_set(buf, 0, "(");
1753  if (e & IAX_ENCRYPT_AES128) {
1754  ast_str_append(buf, 0, "aes128");
1755  }
1756  if (e & IAX_ENCRYPT_KEYROTATE) {
1757  ast_str_append(buf, 0, ",keyrotate");
1758  }
1759  if (ast_str_strlen(*buf) > 1) {
1760  ast_str_append(buf, 0, ")");
1761  } else {
1762  ast_str_set(buf, 0, "No");
1763  }
1764 }
1765 
1766 static int get_encrypt_methods(const char *s)
1767 {
1768  int e;
1769  if (!strcasecmp(s, "aes128"))
1771  else if (ast_true(s))
1773  else
1774  e = 0;
1775  return e;
1776 }
1777 
1778 static int send_lagrq(const void *data);
1779 
1780 static void __send_lagrq(const void *data)
1781 {
1782  int callno = PTR_TO_CALLNO(data);
1783 
1784  if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1785  ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1786  return;
1787  }
1788 
1789  /* Mark lagid as invalid scheduler id. */
1790  iaxs[callno]->lagid = -1;
1791 
1792  /* callno is now locked. */
1793  if (iaxs[callno]->peercallno) {
1794  /* Send LAGRQ packet. */
1795  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1796 
1797  /* Schedule sending next lagrq. */
1798  iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1799  }
1800 
1801  ast_mutex_unlock(&iaxsl[callno]);
1802 }
1803 
1804 static int send_lagrq(const void *data)
1805 {
1806 #ifdef SCHED_MULTITHREADED
1807  if (schedule_action(__send_lagrq, data))
1808 #endif
1809  __send_lagrq(data);
1810  return 0;
1811 }
1812 
1813 static unsigned char compress_subclass(iax2_format subclass)
1814 {
1815  int x;
1816  int power=-1;
1817  /* If it's 64 or smaller, just return it */
1818  if (subclass < IAX_FLAG_SC_LOG)
1819  return subclass;
1820  /* Otherwise find its power */
1821  for (x = 0; x < IAX_MAX_SHIFT; x++) {
1822  if (subclass & (1LL << x)) {
1823  if (power > -1) {
1824  ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1825  return 0;
1826  } else
1827  power = x;
1828  }
1829  }
1830  return power | IAX_FLAG_SC_LOG;
1831 }
1832 
1833 static iax2_format uncompress_subclass(unsigned char csub)
1834 {
1835  /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1836  if (csub & IAX_FLAG_SC_LOG) {
1837  /* special case for 'compressed' -1 */
1838  if (csub == 0xff)
1839  return -1;
1840  else
1841  return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1842  }
1843  else
1844  return csub;
1845 }
1846 
1847 static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1848 {
1849  int x;
1850  struct ast_format *found_format = NULL;
1851 
1852  for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1853  struct ast_format *pref_format;
1854  uint64_t pref_bitfield;
1855 
1856  pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1857  if (!pref_bitfield) {
1858  break;
1859  }
1860 
1861  pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1862  if (!pref_format) {
1863  /* The bitfield is not associated with any format. */
1864  continue;
1865  }
1866  found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1867  if (found_format) {
1868  break;
1869  }
1870  }
1871 
1872  if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1873  return found_format;
1874  }
1875 
1876  ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1877  ao2_cleanup(found_format);
1878  return NULL;
1879 }
1880 
1882 {
1883  struct ast_format_cap *cap;
1884  struct ast_format *tmpfmt;
1885  iax2_format format = 0;
1886 
1889  tmpfmt = codec_choose_from_prefs(pref, cap);
1890  if (!tmpfmt) {
1891  ao2_ref(cap, -1);
1892  return 0;
1893  }
1894 
1896  ao2_ref(tmpfmt, -1);
1897  ao2_ref(cap, -1);
1898  }
1899 
1900  return format;
1901 }
1902 
1904 {
1905  struct ast_format *tmpfmt;
1906 
1908  if (!tmpfmt) {
1909  return "Unknown";
1910  }
1911 
1912  return ast_format_get_name(tmpfmt);
1913 }
1914 
1915 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1916 {
1918 
1919  if (!cap) {
1920  return "(Nothing)";
1921  }
1923  ast_format_cap_get_names(cap, codec_buf);
1924  ao2_ref(cap, -1);
1925 
1926  return ast_str_buffer(*codec_buf);
1927 }
1928 
1929 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1930 {
1931  int res, i;
1932  struct ast_format_cap *cap;
1933 
1934  /* We want to add the formats to the cap in the preferred order */
1936  if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1937  ao2_cleanup(cap);
1938  return 1;
1939  }
1940 
1941  res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1942 
1943  /* Adjust formats bitfield and pref list to match. */
1945  iax2_codec_pref_remove_missing(pref, *formats);
1946 
1947  for (i = 0; i < ast_format_cap_count(cap); i++) {
1948  struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1949 
1951  ao2_ref(fmt, -1);
1952  }
1953 
1954  ao2_ref(cap, -1);
1955 
1956  return res;
1957 }
1958 
1959 /*!
1960  * \note The only member of the peer passed here guaranteed to be set is the name field
1961  */
1962 static int peer_hash_cb(const void *obj, const int flags)
1963 {
1964  const struct iax2_peer *peer = obj;
1965  const char *name = obj;
1966 
1967  return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1968 }
1969 
1970 /*!
1971  * \note The only member of the peer passed here guaranteed to be set is the name field
1972  */
1973 static int peer_cmp_cb(void *obj, void *arg, int flags)
1974 {
1975  struct iax2_peer *peer = obj, *peer2 = arg;
1976  const char *name = arg;
1977 
1978  return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1979  CMP_MATCH | CMP_STOP : 0;
1980 }
1981 
1982 /*!
1983  * \note The only member of the user passed here guaranteed to be set is the name field
1984  */
1985 static int user_hash_cb(const void *obj, const int flags)
1986 {
1987  const struct iax2_user *user = obj;
1988  const char *name = obj;
1989 
1990  return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1991 }
1992 
1993 /*!
1994  * \note The only member of the user passed here guaranteed to be set is the name field
1995  */
1996 static int user_cmp_cb(void *obj, void *arg, int flags)
1997 {
1998  struct iax2_user *user = obj, *user2 = arg;
1999  const char *name = arg;
2000 
2001  return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2002  CMP_MATCH | CMP_STOP : 0;
2003 }
2004 
2005 /*!
2006  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2007  * so do not call it with a pvt lock held.
2008  */
2009 static struct iax2_peer *find_peer(const char *name, int realtime)
2010 {
2011  struct iax2_peer *peer = NULL;
2012 
2013  peer = ao2_find(peers, name, OBJ_KEY);
2014 
2015  /* Now go for realtime if applicable */
2016  if (!peer && realtime) {
2017  peer = realtime_peer(name, NULL);
2018  }
2019  return peer;
2020 }
2021 
2022 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2023 {
2024  ao2_ref(peer, +1);
2025  return peer;
2026 }
2027 
2028 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2029 {
2030  ao2_ref(peer, -1);
2031  return NULL;
2032 }
2033 
2034 static struct iax2_user *find_user(const char *name)
2035 {
2036  return ao2_find(users, name, OBJ_KEY);
2037 }
2038 
2039 static inline struct iax2_user *user_unref(struct iax2_user *user)
2040 {
2041  ao2_ref(user, -1);
2042  return NULL;
2043 }
2044 
2045 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2046 {
2047  struct iax2_peer *peer = NULL;
2048  int res = 0;
2049  struct ao2_iterator i;
2050 
2051  i = ao2_iterator_init(peers, 0);
2052  while ((peer = ao2_iterator_next(&i))) {
2053 
2054  if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2055  ast_copy_string(host, peer->name, len);
2056  peer_unref(peer);
2057  res = 1;
2058  break;
2059  }
2060  peer_unref(peer);
2061  }
2063 
2064  if (!peer) {
2065  peer = realtime_peer(NULL, &addr);
2066  if (peer) {
2067  ast_copy_string(host, peer->name, len);
2068  peer_unref(peer);
2069  res = 1;
2070  }
2071  }
2072 
2073  return res;
2074 }
2075 
2076 /* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2077 static int iax2_delete_from_sched(const void* data)
2078 {
2079  int sched_id = (int)(long)data;
2080 
2081  AST_SCHED_DEL(sched, sched_id);
2082 
2083  return 0;
2084 }
2085 
2086 /*!\note Assumes the lock on the pvt is already held, when
2087  * iax2_destroy_helper() is called. */
2088 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2089 {
2090  /* Decrement AUTHREQ count if needed */
2091  if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2092  struct iax2_user *user;
2093 
2094  user = ao2_find(users, pvt->username, OBJ_KEY);
2095  if (user) {
2096  ast_atomic_fetchadd_int(&user->curauthreq, -1);
2097  user_unref(user);
2098  }
2099 
2101  }
2102 
2103 
2104  /* Mark call destroy initiated flag. */
2105  pvt->destroy_initiated = 1;
2106 
2107  /*
2108  * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2109  * Already running tasks will be terminated because of destroy_initiated.
2110  *
2111  * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2112  * it leads to a deadlock between the scheduler thread callback locking
2113  * the callno mutex and this thread which holds the callno mutex one or
2114  * more times. It is better to have another thread delete the scheduled
2115  * callbacks which doesn't lock the callno mutex.
2116  */
2117  iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2118  iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2119 
2120  pvt->pingid = -1;
2121  pvt->lagid = -1;
2122 
2123  AST_SCHED_DEL(sched, pvt->autoid);
2124  AST_SCHED_DEL(sched, pvt->authid);
2125  AST_SCHED_DEL(sched, pvt->initid);
2126  AST_SCHED_DEL(sched, pvt->jbid);
2127  AST_SCHED_DEL(sched, pvt->keyrotateid);
2128 }
2129 
2130 static void iax2_frame_free(struct iax_frame *fr)
2131 {
2132  AST_SCHED_DEL(sched, fr->retrans);
2133  iax_frame_free(fr);
2134 }
2135 
2136 static int scheduled_destroy(const void *vid)
2137 {
2138  unsigned short callno = PTR_TO_CALLNO(vid);
2139  ast_mutex_lock(&iaxsl[callno]);
2140  if (iaxs[callno]) {
2141  ast_debug(1, "Really destroying %d now...\n", callno);
2142  iax2_destroy(callno);
2143  }
2144  ast_mutex_unlock(&iaxsl[callno]);
2145  return 0;
2146 }
2147 
2149 {
2150  if (s->f.datalen) {
2151  ast_free(s->f.data.ptr);
2152  }
2153  ast_free(s);
2154 }
2155 
2156 /*! \brief This function must be called once we are sure the other side has
2157  * given us a call number. All signaling is held here until that point. */
2158 static void send_signaling(struct chan_iax2_pvt *pvt)
2159 {
2160  struct signaling_queue_entry *s = NULL;
2161 
2162  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2163  iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2165  }
2166  pvt->hold_signaling = 0;
2167 }
2168 
2169 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2170  * we have received a destination call number. */
2171 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2172 {
2173  struct signaling_queue_entry *qe;
2174 
2175  if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2176  return 1; /* do not queue this frame */
2177  } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2178  return -1; /* out of memory */
2179  }
2180 
2181  /* copy ast_frame into our queue entry */
2182  qe->f = *f;
2183  if (qe->f.datalen) {
2184  /* if there is data in this frame copy it over as well */
2185  if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2187  return -1;
2188  }
2189  memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2190  }
2192 
2193  return 0;
2194 }
2195 
2196 static void pvt_destructor(void *obj)
2197 {
2198  struct chan_iax2_pvt *pvt = obj;
2199  struct iax_frame *cur = NULL;
2200  struct signaling_queue_entry *s = NULL;
2201 
2202  ast_mutex_lock(&iaxsl[pvt->callno]);
2203 
2204  iax2_destroy_helper(pvt);
2205 
2206  sched_delay_remove(&pvt->addr, pvt->callno_entry);
2207  pvt->callno_entry = 0;
2208 
2209  /* Already gone */
2211 
2212  AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2213  /* Cancel any pending transmissions */
2214  cur->retries = -1;
2215  }
2216 
2217  ast_mutex_unlock(&iaxsl[pvt->callno]);
2218 
2219  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2221  }
2222 
2223  if (pvt->reg) {
2224  pvt->reg->callno = 0;
2225  }
2226 
2227  if (!pvt->owner) {
2228  jb_frame frame;
2229  if (pvt->vars) {
2231  pvt->vars = NULL;
2232  }
2233 
2234  while (jb_getall(pvt->jb, &frame) == JB_OK) {
2235  iax2_frame_free(frame.data);
2236  }
2237 
2238  jb_destroy(pvt->jb);
2240  }
2241 }
2242 
2243 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2244 {
2245  struct chan_iax2_pvt *tmp;
2246  jb_conf jbconf;
2247 
2248  if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2249  return NULL;
2250  }
2251 
2252  tmp->pingid = -1;
2253  tmp->lagid = -1;
2254  tmp->autoid = -1;
2255  tmp->authid = -1;
2256  tmp->initid = -1;
2257  tmp->keyrotateid = -1;
2258  tmp->jbid = -1;
2259 
2260  if (ast_string_field_init(tmp, 32)) {
2261  ao2_ref(tmp, -1);
2262  tmp = NULL;
2263  return NULL;
2264  }
2265 
2266  tmp->prefs = prefs_global;
2267 
2268  ast_string_field_set(tmp,exten, "s");
2269  ast_string_field_set(tmp,host, host);
2270 
2271  tmp->jb = jb_new();
2272  jbconf.max_jitterbuf = maxjitterbuffer;
2276  jb_setconf(tmp->jb,&jbconf);
2277 
2279 
2280  tmp->hold_signaling = 1;
2282 
2283  return tmp;
2284 }
2285 
2286 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2287 {
2288  struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2289  if (new) {
2290  size_t afdatalen = new->afdatalen;
2291  memcpy(new, fr, sizeof(*new));
2292  iax_frame_wrap(new, &fr->af);
2293  new->afdatalen = afdatalen;
2294  new->data = NULL;
2295  new->datalen = 0;
2296  new->direction = DIRECTION_INGRESS;
2297  new->retrans = -1;
2298  }
2299  return new;
2300 }
2301 /* keep these defined in this order. They are used in find_callno to
2302  * determine whether or not a new call number should be allowed. */
2303 enum {
2304  /* do not allow a new call number, only search ones in use for match */
2306  /* search for match first, then allow a new one to be allocated */
2308  /* do not search for match, force a new call number */
2310  /* do not search for match, force a new call number. Signifies call number
2311  * has been calltoken validated */
2313 };
2314 
2315 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2316 {
2317  if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2318  /* This is the main host */
2319  if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2320  (check_dcallno ? dcallno == cur->callno : 1) ) {
2321  /* That's us. Be sure we keep track of the peer call number */
2322  return 1;
2323  }
2324  }
2325  if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2326  /* We're transferring */
2327  if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2328  return 1;
2329  }
2330  return 0;
2331 }
2332 
2333 static int make_trunk(unsigned short callno, int locked)
2334 {
2335  int x;
2336  int res= 0;
2337  callno_entry entry;
2338  if (iaxs[callno]->oseqno) {
2339  ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2340  return -1;
2341  }
2342  if (callno >= TRUNK_CALL_START) {
2343  ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2344  return -1;
2345  }
2346 
2347  if (get_unused_callno(
2349  CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2350  &entry)) {
2351  ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2352  return -1;
2353  }
2354 
2355  x = CALLNO_ENTRY_GET_CALLNO(entry);
2356  ast_mutex_lock(&iaxsl[x]);
2357 
2358  /*!
2359  * \note We delete these before switching the slot, because if
2360  * they fire in the meantime, they will generate a warning.
2361  */
2362  AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2363  AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2364  iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2365  iaxs[x] = iaxs[callno];
2366  iaxs[x]->callno = x;
2367 
2368  /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2369  * before assigning the new one */
2370  if (iaxs[x]->callno_entry) {
2372  sched,
2373  MIN_REUSE_TIME * 1000,
2374  replace_callno,
2375  CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2376 
2377  }
2378  iaxs[x]->callno_entry = entry;
2379 
2380  iaxs[callno] = NULL;
2381  /* Update the two timers that should have been started */
2382  iaxs[x]->pingid = iax2_sched_add(sched,
2383  ping_time * 1000, send_ping, (void *)(long)x);
2384  iaxs[x]->lagid = iax2_sched_add(sched,
2385  lagrq_time * 1000, send_lagrq, (void *)(long)x);
2386 
2387  if (locked)
2388  ast_mutex_unlock(&iaxsl[callno]);
2389  res = x;
2390  if (!locked)
2391  ast_mutex_unlock(&iaxsl[x]);
2392 
2393  /* We moved this call from a non-trunked to a trunked call */
2394  ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2395 
2396  return res;
2397 }
2398 
2399 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2400 {
2401  if (!pvt->transfercallno) {
2402  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2403  return;
2404  }
2405 
2406  ao2_link(iax_transfercallno_pvts, pvt);
2407 }
2408 
2409 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2410 {
2411  if (!pvt->transfercallno) {
2412  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2413  return;
2414  }
2415 
2416  ao2_unlink(iax_transfercallno_pvts, pvt);
2417 }
2418 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2419 {
2420  if (!pvt->peercallno) {
2421  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2422  return;
2423  }
2424 
2425  ao2_link(iax_peercallno_pvts, pvt);
2426 }
2427 
2428 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2429 {
2430  if (!pvt->peercallno) {
2431  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2432  return;
2433  }
2434 
2435  ao2_unlink(iax_peercallno_pvts, pvt);
2436 }
2437 
2438 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2439 {
2440  struct addr_range *lim = obj;
2441  lim->delme = 1;
2442  return 0;
2443 }
2444 
2445 static int addr_range_hash_cb(const void *obj, const int flags)
2446 {
2447  const struct addr_range *lim = obj;
2448  return abs(ast_sockaddr_hash(&lim->ha.addr));
2449 }
2450 
2451 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2452 {
2453  struct addr_range *lim1 = obj, *lim2 = arg;
2454  return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2455  !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2456  CMP_MATCH | CMP_STOP : 0;
2457 }
2458 
2459 static int peercnt_hash_cb(const void *obj, const int flags)
2460 {
2461  const struct peercnt *peercnt = obj;
2462 
2463  if (ast_sockaddr_isnull(&peercnt->addr)) {
2464  return 0;
2465  }
2466  return ast_sockaddr_hash(&peercnt->addr);
2467 }
2468 
2469 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2470 {
2471  struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2472  return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2473 }
2474 
2475 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2476 {
2477  struct addr_range *addr_range = obj;
2478  struct ast_sockaddr *addr = arg;
2479  struct ast_sockaddr tmp_addr;
2480 
2481  ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2482 
2483  if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2484  return CMP_MATCH | CMP_STOP;
2485  }
2486  return 0;
2487 }
2488 
2489 /*!
2490  * \internal
2491  *
2492  * \brief compares addr to calltoken_ignores table to determine if validation is required.
2493  */
2494 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2495 {
2496  struct addr_range *addr_range;
2497  struct iax2_peer *peer = NULL;
2498  struct iax2_user *user = NULL;
2499  /* if no username is given, check for guest accounts */
2500  const char *find = S_OR(name, "guest");
2501  int res = 1; /* required by default */
2502  int optional = 0;
2504  /* There are only two cases in which calltoken validation is not required.
2505  * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2506  * the peer definition has not set the requirecalltoken option.
2507  * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2508  */
2509 
2510  /* ----- Case 1 ----- */
2511  if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2512  ao2_ref(addr_range, -1);
2513  optional = 1;
2514  }
2515 
2516  /* ----- Case 2 ----- */
2517  if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2518  calltoken_required = user->calltoken_required;
2519  } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2520  calltoken_required = user->calltoken_required;
2521  } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2522  calltoken_required = peer->calltoken_required;
2523  } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2524  calltoken_required = peer->calltoken_required;
2525  }
2526 
2527  if (peer) {
2528  peer_unref(peer);
2529  }
2530  if (user) {
2531  user_unref(user);
2532  }
2533 
2534  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);
2535  if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2536  (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2537  res = 0;
2538  }
2539 
2540  return res;
2541 }
2542 
2543 /*!
2544  * \internal
2545  *
2546  * \brief set peercnt callno limit.
2547  *
2548  * \details
2549  * First looks in custom definitions. If not found, global limit
2550  * is used. Entries marked as reg already have
2551  * a custom limit set by a registration and are not modified.
2552  */
2553 static void set_peercnt_limit(struct peercnt *peercnt)
2554 {
2555  uint16_t limit = global_maxcallno;
2556  struct addr_range *addr_range;
2557  struct ast_sockaddr addr;
2558 
2559  ast_sockaddr_copy(&addr, &peercnt->addr);
2560 
2561  if (peercnt->reg && peercnt->limit) {
2562  return; /* this peercnt has a custom limit set by a registration */
2563  }
2564 
2565  if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2566  limit = addr_range->limit;
2567  ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2568  ao2_ref(addr_range, -1);
2569  }
2570 
2571  peercnt->limit = limit;
2572 }
2573 
2574 /*!
2575  * \internal
2576  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2577  */
2578 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2579 {
2580  struct peercnt *peercnt = obj;
2581 
2582  set_peercnt_limit(peercnt);
2583  ast_debug(1, "Reset limits for peercnts table\n");
2584 
2585  return 0;
2586 }
2587 
2588 /*!
2589  * \internal
2590  * \brief returns match if delme is set.
2591  */
2592 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2593 {
2594  struct addr_range *addr_range = obj;
2595 
2596  return addr_range->delme ? CMP_MATCH : 0;
2597 }
2598 
2599 /*!
2600  * \internal
2601  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2602  */
2603 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2604 {
2605  /* this function turns off and on custom callno limits set by peer registration */
2606  struct peercnt *peercnt;
2607  struct peercnt tmp;
2608 
2609  ast_sockaddr_copy(&tmp.addr, sockaddr);
2610 
2611  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2612  peercnt->reg = reg;
2613  if (limit) {
2614  peercnt->limit = limit;
2615  } else {
2616  set_peercnt_limit(peercnt);
2617  }
2618  ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2619  ao2_ref(peercnt, -1); /* decrement ref from find */
2620  }
2621 }
2622 
2623 /*!
2624  * \internal
2625  * \brief adds an ip to the peercnts table, increments connection count if it already exists
2626  *
2627  * \details First searches for the address in the peercnts table. If found
2628  * the current count is incremented. If not found a new peercnt is allocated
2629  * and linked into the peercnts table with a call number count of 1.
2630  */
2631 static int peercnt_add(struct ast_sockaddr *addr)
2632 {
2633  struct peercnt *peercnt;
2634  int res = 0;
2635  struct peercnt tmp;
2636 
2637  ast_sockaddr_copy(&tmp.addr, addr);
2638 
2639  /* Reasoning for peercnts container lock: Two identical ip addresses
2640  * could be added by different threads at the "same time". Without the container
2641  * lock, both threads could alloc space for the same object and attempt
2642  * to link to table. With the lock, one would create the object and link
2643  * to table while the other would find the already created peercnt object
2644  * rather than creating a new one. */
2645  ao2_lock(peercnts);
2646  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2647  ao2_lock(peercnt);
2648  } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2649  ao2_lock(peercnt);
2650  /* create and set defaults */
2651  ast_sockaddr_copy(&peercnt->addr, addr);
2652  set_peercnt_limit(peercnt);
2653  /* guarantees it does not go away after unlocking table
2654  * ao2_find automatically adds this */
2655  ao2_link(peercnts, peercnt);
2656  } else {
2657  ao2_unlock(peercnts);
2658  return -1;
2659  }
2660 
2661  /* check to see if the address has hit its callno limit. If not increment cur. */
2662  if (peercnt->limit > peercnt->cur) {
2663  peercnt->cur++;
2664  ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2665  } else { /* max num call numbers for this peer has been reached! */
2666  ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2667  res = -1;
2668  }
2669 
2670  /* clean up locks and ref count */
2671  ao2_unlock(peercnt);
2672  ao2_unlock(peercnts);
2673  ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2674 
2675  return res;
2676 }
2677 
2678 /*!
2679  * \internal
2680  * \brief decrements a peercnts table entry
2681  */
2682 static void peercnt_remove(struct peercnt *peercnt)
2683 {
2684  struct ast_sockaddr addr;
2685 
2686  ast_sockaddr_copy(&addr, &peercnt->addr);
2687 
2688  /*
2689  * Container locked here since peercnt may be unlinked from
2690  * list. If left unlocked, peercnt_add could try and grab this
2691  * entry from the table and modify it at the "same time" this
2692  * thread attemps to unlink it.
2693  */
2694  ao2_lock(peercnts);
2695  peercnt->cur--;
2696  ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2697  /* if this was the last connection from the peer remove it from table */
2698  if (peercnt->cur == 0) {
2699  ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2700  }
2701  ao2_unlock(peercnts);
2702 }
2703 
2704 /*!
2705  * \internal
2706  * \brief called by scheduler to decrement object
2707  */
2708 static int peercnt_remove_cb(const void *obj)
2709 {
2710  struct peercnt *peercnt = (struct peercnt *) obj;
2711 
2712  peercnt_remove(peercnt);
2713  ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2714 
2715  return 0;
2716 }
2717 
2718 /*!
2719  * \internal
2720  * \brief decrements peercnts connection count, finds by addr
2721  */
2722 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2723 {
2724  struct peercnt *peercnt;
2725  struct peercnt tmp;
2726 
2727  ast_sockaddr_copy(&tmp.addr, addr);
2728 
2729  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2730  peercnt_remove(peercnt);
2731  ao2_ref(peercnt, -1); /* decrement ref from find */
2732  }
2733  return 0;
2734 }
2735 
2736 /*!
2737  * \internal
2738  * \brief Create callno_limit entry based on configuration
2739  */
2740 static void build_callno_limits(struct ast_variable *v)
2741 {
2742  struct addr_range *addr_range = NULL;
2743  struct addr_range tmp;
2744  struct ast_ha *ha;
2745  int limit;
2746  int error;
2747  int found;
2748 
2749  for (; v; v = v->next) {
2750  limit = -1;
2751  error = 0;
2752  found = 0;
2753  ha = ast_append_ha("permit", v->name, NULL, &error);
2754 
2755  /* check for valid config information */
2756  if (error) {
2757  ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2758  continue;
2759  } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2760  ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2761  ast_free_ha(ha);
2762  continue;
2763  }
2764 
2765  ast_copy_ha(ha, &tmp.ha);
2766  /* find or create the addr_range */
2767  if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2768  ao2_lock(addr_range);
2769  found = 1;
2770  } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2771  ast_free_ha(ha);
2772  return; /* out of memory */
2773  }
2774 
2775  /* copy over config data into addr_range object */
2776  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2777  ast_free_ha(ha); /* cleanup the tmp ha */
2778  addr_range->limit = limit;
2779  addr_range->delme = 0;
2780 
2781  /* cleanup */
2782  if (found) {
2783  ao2_unlock(addr_range);
2784  } else {
2785  ao2_link(callno_limits, addr_range);
2786  }
2787  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2788  }
2789 }
2790 
2791 /*!
2792  * \internal
2793  * \brief Create calltoken_ignores entry based on configuration
2794  */
2795 static int add_calltoken_ignore(const char *addr)
2796 {
2797  struct addr_range tmp;
2798  struct addr_range *addr_range = NULL;
2799  struct ast_ha *ha = NULL;
2800  int error = 0;
2801 
2802  if (ast_strlen_zero(addr)) {
2803  ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2804  return -1;
2805  }
2806 
2807  ha = ast_append_ha("permit", addr, NULL, &error);
2808 
2809  /* check for valid config information */
2810  if (error) {
2811  ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2812  return -1;
2813  }
2814 
2815  ast_copy_ha(ha, &tmp.ha);
2816  /* find or create the addr_range */
2817  if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2818  ao2_lock(addr_range);
2819  addr_range->delme = 0;
2820  ao2_unlock(addr_range);
2821  } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2822  /* copy over config data into addr_range object */
2823  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2824  ao2_link(calltoken_ignores, addr_range);
2825  } else {
2826  ast_free_ha(ha);
2827  return -1;
2828  }
2829 
2830  ast_free_ha(ha);
2831  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2832 
2833  return 0;
2834 }
2835 
2836 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2837 {
2838  struct ao2_iterator i;
2839  struct peercnt *peercnt;
2840  struct ast_sockaddr addr;
2841  int found = 0;
2842 
2843  switch (cmd) {
2844  case CLI_INIT:
2845  e->command = "iax2 show callnumber usage";
2846  e->usage =
2847  "Usage: iax2 show callnumber usage [IP address]\n"
2848  " Shows current IP addresses which are consuming iax2 call numbers\n";
2849  return NULL;
2850  case CLI_GENERATE:
2851  return NULL;
2852  case CLI_HANDLER:
2853  if (a->argc < 4 || a->argc > 5)
2854  return CLI_SHOWUSAGE;
2855 
2856  if (a->argc == 4) {
2857  ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2858  }
2859 
2860  i = ao2_iterator_init(peercnts, 0);
2861  while ((peercnt = ao2_iterator_next(&i))) {
2862  ast_sockaddr_copy(&addr, &peercnt->addr);
2863 
2864  if (a->argc == 5) {
2865  if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2866  ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2867  ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2868  ao2_ref(peercnt, -1);
2869  found = 1;
2870  break;
2871  }
2872  } else {
2873  ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2874  }
2875  ao2_ref(peercnt, -1);
2876  }
2878 
2879  if (a->argc == 4) {
2880  size_t pool_avail = callno_pool.available;
2881  size_t trunk_pool_avail = callno_pool_trunk.available;
2882 
2883  ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2884  "Non-CallToken Validated Callno Used: %d\n",
2885  global_maxcallno_nonval,
2886  total_nonval_callno_used);
2887 
2888  ast_cli(a->fd, "Total Available Callno: %zu\n"
2889  "Regular Callno Available: %zu\n"
2890  "Trunk Callno Available: %zu\n",
2891  pool_avail + trunk_pool_avail,
2892  pool_avail,
2893  trunk_pool_avail);
2894  } else if (a->argc == 5 && !found) {
2895  ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2896  }
2897 
2898 
2899  return CLI_SUCCESS;
2900  default:
2901  return NULL;
2902  }
2903 }
2904 
2905 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2906 {
2907  struct call_number_pool *pool = NULL;
2908  callno_entry swap;
2909  size_t choice;
2910 
2911  switch (type) {
2912  case CALLNO_TYPE_NORMAL:
2913  pool = &callno_pool;
2914  break;
2915  case CALLNO_TYPE_TRUNK:
2916  pool = &callno_pool_trunk;
2917  break;
2918  default:
2919  ast_assert(0);
2920  break;
2921  }
2922 
2923  /* If we fail, make sure this has a defined value */
2924  *entry = 0;
2925 
2926  /* We lock here primarily to ensure thread safety of the
2927  * total_nonval_callno_used check and increment */
2929 
2930  /* Bail out if we don't have any available call numbers */
2931  if (!pool->available) {
2932  ast_log(LOG_WARNING, "Out of call numbers\n");
2934  return 1;
2935  }
2936 
2937  /* Only a certain number of non-validated call numbers should be allocated.
2938  * If there ever is an attack, this separates the calltoken validating users
2939  * from the non-calltoken validating users. */
2940  if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2942  "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2943  total_nonval_callno_used,
2944  global_maxcallno_nonval);
2946  return 1;
2947  }
2948 
2949  /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2950  * available call numbers. The array of call numbers begins as an ordered
2951  * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2952  * - let's call that x. When a call number is needed we pick a random index
2953  * into the array between 0 and x and use that as our call number. In a
2954  * typical FYD shuffle, we would swap the value that we are extracting with
2955  * the number at x, but in our case we swap and don't touch the value at x
2956  * because it is effectively invisible. We rely on the rest of the IAX2 core
2957  * to return the number to us at some point. Finally, we decrement x by 1
2958  * which establishes our new unused range.
2959  *
2960  * When numbers are returned to the pool, we put them just past x and bump x
2961  * by 1 so that this number is now available for re-use. */
2962 
2963  choice = ast_random() % pool->available;
2964 
2965  *entry = pool->numbers[choice];
2966  swap = pool->numbers[pool->available - 1];
2967 
2968  pool->numbers[choice] = swap;
2969  pool->available--;
2970 
2971  if (validated) {
2973  } else {
2974  total_nonval_callno_used++;
2975  }
2976 
2978 
2979  return 0;
2980 }
2981 
2982 static int replace_callno(const void *obj)
2983 {
2984  callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2985  struct call_number_pool *pool;
2986 
2987  /* We lock here primarily to ensure thread safety of the
2988  * total_nonval_callno_used check and decrement */
2990 
2991  if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2992  if (total_nonval_callno_used) {
2993  total_nonval_callno_used--;
2994  } else {
2996  "Attempted to decrement total non calltoken validated "
2997  "callnumbers below zero. Callno is: %d\n",
2998  CALLNO_ENTRY_GET_CALLNO(entry));
2999  }
3000  }
3001 
3003  pool = &callno_pool;
3004  } else {
3005  pool = &callno_pool_trunk;
3006  }
3007 
3008  ast_assert(pool->capacity > pool->available);
3009 
3010  /* This clears the validated flag */
3011  entry = CALLNO_ENTRY_GET_CALLNO(entry);
3012 
3013  pool->numbers[pool->available] = entry;
3014  pool->available++;
3015 
3017 
3018  return 0;
3019 }
3020 
3021 static int create_callno_pools(void)
3022 {
3023  uint16_t i;
3024 
3026 
3027  /* We start at 2. 0 and 1 are reserved. */
3028  for (i = 2; i < TRUNK_CALL_START; i++) {
3031  }
3032 
3033  for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3036  }
3037 
3040 
3042 
3043  return 0;
3044 }
3045 
3046 /*!
3047  * \internal
3048  * \brief Schedules delayed removal of iax2_pvt call number data
3049  *
3050  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3051  * available again, and the address from the previous connection must be decremented
3052  * from the peercnts table. This function schedules these operations to take place.
3053  */
3054 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3055 {
3056  int i;
3057  struct peercnt *peercnt;
3058  struct peercnt tmp;
3059 
3060  ast_sockaddr_copy(&tmp.addr, addr);
3061 
3062  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3063  /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3064  ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3065  i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3066  if (i == -1) {
3067  ao2_ref(peercnt, -1);
3068  }
3069  }
3070 
3072  sched,
3073  MIN_REUSE_TIME * 1000,
3074  replace_callno,
3075  CALLNO_ENTRY_TO_PTR(entry));
3076 }
3077 
3078 /*!
3079  * \internal
3080  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3081  *
3082  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3083  * a new callno.
3084  */
3085 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3086 {
3087  if (frametype != AST_FRAME_IAX) {
3088  return 0;
3089  }
3090  switch (subclass) {
3091  case IAX_COMMAND_NEW:
3092  case IAX_COMMAND_REGREQ:
3093  case IAX_COMMAND_FWDOWNL:
3094  case IAX_COMMAND_REGREL:
3095  return 1;
3096  case IAX_COMMAND_POKE:
3097  if (!inbound) {
3098  return 1;
3099  }
3100  break;
3101  }
3102  return 0;
3103 }
3104 
3105 /*
3106  * \note Calling this function while holding another pvt lock can cause a deadlock.
3107  */
3108 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3109 {
3110  int res = 0;
3111  int x;
3112  /* this call is calltoken validated as long as it is either NEW_FORCE
3113  * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3114  int validated = (new > NEW_ALLOW) ? 1 : 0;
3115  char host[80];
3116 
3117  if (new <= NEW_ALLOW) {
3118  if (callno) {
3119  struct chan_iax2_pvt *pvt;
3120  struct chan_iax2_pvt tmp_pvt = {
3121  .callno = dcallno,
3122  .peercallno = callno,
3123  .transfercallno = callno,
3124  /* hack!! */
3125  .frames_received = check_dcallno,
3126  };
3127 
3128  ast_sockaddr_copy(&tmp_pvt.addr, addr);
3129  /* this works for finding normal call numbers not involving transfering */
3130  if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3131  if (return_locked) {
3132  ast_mutex_lock(&iaxsl[pvt->callno]);
3133  }
3134  res = pvt->callno;
3135  ao2_ref(pvt, -1);
3136  pvt = NULL;
3137  return res;
3138  }
3139  /* this searches for transfer call numbers that might not get caught otherwise */
3140  memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3141  ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3142  if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3143  if (return_locked) {
3144  ast_mutex_lock(&iaxsl[pvt->callno]);
3145  }
3146  res = pvt->callno;
3147  ao2_ref(pvt, -1);
3148  pvt = NULL;
3149  return res;
3150  }
3151  }
3152  /* This will occur on the first response to a message that we initiated,
3153  * such as a PING. */
3154  if (dcallno) {
3155  ast_mutex_lock(&iaxsl[dcallno]);
3156  }
3157  if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3158  iaxs[dcallno]->peercallno = callno;
3159  res = dcallno;
3160  store_by_peercallno(iaxs[dcallno]);
3161  if (!res || !return_locked) {
3162  ast_mutex_unlock(&iaxsl[dcallno]);
3163  }
3164  return res;
3165  }
3166  if (dcallno) {
3167  ast_mutex_unlock(&iaxsl[dcallno]);
3168  }
3169  }
3170  if (!res && (new >= NEW_ALLOW)) {
3171  callno_entry entry;
3172 
3173  /* It may seem odd that we look through the peer list for a name for
3174  * this *incoming* call. Well, it is weird. However, users don't
3175  * have an IP address/port number that we can match against. So,
3176  * this is just checking for a peer that has that IP/port and
3177  * assuming that we have a user of the same name. This isn't always
3178  * correct, but it will be changed if needed after authentication. */
3179  if (!iax2_getpeername(*addr, host, sizeof(host)))
3180  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3181 
3182  if (peercnt_add(addr)) {
3183  /* This address has hit its callnumber limit. When the limit
3184  * is reached, the connection is not added to the peercnts table.*/
3185  return 0;
3186  }
3187 
3188  if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3189  /* since we ran out of space, remove the peercnt
3190  * entry we added earlier */
3191  peercnt_remove_by_addr(addr);
3192  ast_log(LOG_WARNING, "No more space\n");
3193  return 0;
3194  }
3195  x = CALLNO_ENTRY_GET_CALLNO(entry);
3196  ast_mutex_lock(&iaxsl[x]);
3197 
3198  iaxs[x] = new_iax(addr, host);
3199  if (iaxs[x]) {
3200  if (iaxdebug)
3201  ast_debug(1, "Creating new call structure %d\n", x);
3202  iaxs[x]->callno_entry = entry;
3203  iaxs[x]->sockfd = sockfd;
3204  ast_sockaddr_copy(&iaxs[x]->addr, addr);
3205  iaxs[x]->peercallno = callno;
3206  iaxs[x]->callno = x;
3207  iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3208  iaxs[x]->expiry = min_reg_expire;
3209  iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3210  iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3211  iaxs[x]->amaflags = amaflags;
3217 
3218  if (iaxs[x]->peercallno) {
3219  store_by_peercallno(iaxs[x]);
3220  }
3221  } else {
3222  ast_log(LOG_WARNING, "Out of resources\n");
3223  ast_mutex_unlock(&iaxsl[x]);
3225  return 0;
3226  }
3227  if (!return_locked)
3228  ast_mutex_unlock(&iaxsl[x]);
3229  res = x;
3230  }
3231  return res;
3232 }
3233 
3234 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3235  return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3236 }
3237 
3238 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3239 
3240  return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3241 }
3242 
3243 /*!
3244  * \brief Queue a frame to a call's owning asterisk channel
3245  *
3246  * \pre This function assumes that iaxsl[callno] is locked when called.
3247  *
3248  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3249  * was valid before calling it, it may no longer be valid after calling it.
3250  * This function may unlock and lock the mutex associated with this callno,
3251  * meaning that another thread may grab it and destroy the call.
3252  */
3253 static int iax2_queue_frame(int callno, struct ast_frame *f)
3254 {
3255  iax2_lock_owner(callno);
3256  if (iaxs[callno] && iaxs[callno]->owner) {
3257  ast_queue_frame(iaxs[callno]->owner, f);
3258  ast_channel_unlock(iaxs[callno]->owner);
3259  }
3260  return 0;
3261 }
3262 
3263 /*!
3264  * \brief Queue a hold frame on the ast_channel owner
3265  *
3266  * This function queues a hold frame on the owner of the IAX2 pvt struct that
3267  * is active for the given call number.
3268  *
3269  * \pre Assumes lock for callno is already held.
3270  *
3271  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3272  * was valid before calling it, it may no longer be valid after calling it.
3273  * This function may unlock and lock the mutex associated with this callno,
3274  * meaning that another thread may grab it and destroy the call.
3275  */
3276 static int iax2_queue_hold(int callno, const char *musicclass)
3277 {
3278  iax2_lock_owner(callno);
3279  if (iaxs[callno] && iaxs[callno]->owner) {
3280  ast_queue_hold(iaxs[callno]->owner, musicclass);
3281  ast_channel_unlock(iaxs[callno]->owner);
3282  }
3283  return 0;
3284 }
3285 
3286 /*!
3287  * \brief Queue an unhold frame on the ast_channel owner
3288  *
3289  * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3290  * is active for the given call number.
3291  *
3292  * \pre Assumes lock for callno is already held.
3293  *
3294  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3295  * was valid before calling it, it may no longer be valid after calling it.
3296  * This function may unlock and lock the mutex associated with this callno,
3297  * meaning that another thread may grab it and destroy the call.
3298  */
3299 static int iax2_queue_unhold(int callno)
3300 {
3301  iax2_lock_owner(callno);
3302  if (iaxs[callno] && iaxs[callno]->owner) {
3303  ast_queue_unhold(iaxs[callno]->owner);
3304  ast_channel_unlock(iaxs[callno]->owner);
3305  }
3306  return 0;
3307 }
3308 
3309 /*!
3310  * \brief Queue a hangup frame on the ast_channel owner
3311  *
3312  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3313  * is active for the given call number.
3314  *
3315  * \pre Assumes lock for callno is already held.
3316  *
3317  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3318  * was valid before calling it, it may no longer be valid after calling it.
3319  * This function may unlock and lock the mutex associated with this callno,
3320  * meaning that another thread may grab it and destroy the call.
3321  */
3322 static int iax2_queue_hangup(int callno)
3323 {
3324  iax2_lock_owner(callno);
3325  if (iaxs[callno] && iaxs[callno]->owner) {
3326  ast_queue_hangup(iaxs[callno]->owner);
3327  ast_channel_unlock(iaxs[callno]->owner);
3328  }
3329  return 0;
3330 }
3331 
3332 /*!
3333  * \note This function assumes that iaxsl[callno] is locked when called.
3334  *
3335  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3336  * was valid before calling it, it may no longer be valid after calling it.
3337  * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3338  * associated with this callno, meaning that another thread may grab it and destroy the call.
3339  */
3340 static int __do_deliver(void *data)
3341 {
3342  /* Just deliver the packet by using queueing. This is called by
3343  the IAX thread with the iaxsl lock held. */
3344  struct iax_frame *fr = data;
3345  fr->retrans = -1;
3347  if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3348  iax2_queue_frame(fr->callno, &fr->af);
3349  /* Free our iax frame */
3350  iax2_frame_free(fr);
3351  /* And don't run again */
3352  return 0;
3353 }
3354 
3355 static int handle_error(void)
3356 {
3357  /* XXX Ideally we should figure out why an error occurred and then abort those
3358  rather than continuing to try. Unfortunately, the published interface does
3359  not seem to work XXX */
3360 #if 0
3361  struct sockaddr_in *sin;
3362  int res;
3363  struct msghdr m;
3364  struct sock_extended_err e;
3365  m.msg_name = NULL;
3366  m.msg_namelen = 0;
3367  m.msg_iov = NULL;
3368  m.msg_control = &e;
3369  m.msg_controllen = sizeof(e);
3370  m.msg_flags = 0;
3371  res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3372  if (res < 0)
3373  ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3374  else {
3375  if (m.msg_controllen) {
3376  sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3377  if (sin)
3378  ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3379  else
3380  ast_log(LOG_WARNING, "No address detected??\n");
3381  } else {
3382  ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3383  }
3384  }
3385 #endif
3386  return 0;
3387 }
3388 
3389 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3390 {
3391  int res;
3392  res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3393 
3394  if (res < 0) {
3395  ast_debug(1, "Received error: %s\n", strerror(errno));
3396  handle_error();
3397  } else
3398  res = 0;
3399  return res;
3400 }
3401 
3402 static int send_packet(struct iax_frame *f)
3403 {
3404  int res;
3405  int callno = f->callno;
3406 
3407  /* Don't send if there was an error, but return error instead */
3408  if (!callno || !iaxs[callno] || iaxs[callno]->error)
3409  return -1;
3410 
3411  /* Called with iaxsl held */
3412  if (iaxdebug) {
3413  ast_debug(3, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3414  }
3415  if (f->transfer) {
3416  iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3417  res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3418  } else {
3419  iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3420  res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3421  }
3422  if (res < 0) {
3423  if (iaxdebug)
3424  ast_debug(1, "Received error: %s\n", strerror(errno));
3425  handle_error();
3426  } else
3427  res = 0;
3428 
3429  return res;
3430 }
3431 
3432 /*!
3433  * \note Since this function calls iax2_queue_hangup(), the pvt struct
3434  * for the given call number may disappear during its execution.
3435  */
3436 static int iax2_predestroy(int callno)
3437 {
3438  struct ast_channel *c = NULL;
3439  struct chan_iax2_pvt *pvt = iaxs[callno];
3440 
3441  if (!pvt)
3442  return -1;
3443 
3444  if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3445  iax2_destroy_helper(pvt);
3447  }
3448 
3449  if ((c = pvt->owner)) {
3451  iax2_queue_hangup(callno);
3452  pvt->owner = NULL;
3454  }
3455 
3456  return 0;
3457 }
3458 
3459 static void iax2_destroy(int callno)
3460 {
3461  struct chan_iax2_pvt *pvt = NULL;
3462  struct ast_channel *owner = NULL;
3463 
3464 retry:
3465  if ((pvt = iaxs[callno])) {
3466 #if 0
3467  /* iax2_destroy_helper gets called from this function later on. When
3468  * called twice, we get the (previously) familiar FRACK! errors in
3469  * devmode, from the scheduler. An alternative to this approach is to
3470  * reset the scheduler entries to -1 when they're deleted in
3471  * iax2_destroy_helper(). That approach was previously decided to be
3472  * "wrong" because "the memory is going to be deallocated anyway. Why
3473  * should we be resetting those values?" */
3474  iax2_destroy_helper(pvt);
3475 #endif
3476  }
3477 
3478  owner = pvt ? pvt->owner : NULL;
3479 
3480  if (owner) {
3481  if (ast_channel_trylock(owner)) {
3482  ast_debug(3, "Avoiding IAX destroy deadlock\n");
3483  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3484  goto retry;
3485  }
3486  }
3487 
3488  if (!owner) {
3489  iaxs[callno] = NULL;
3490  }
3491 
3492  if (pvt) {
3493  if (!owner) {
3494  pvt->owner = NULL;
3495  } else {
3496  /* If there's an owner, prod it to give up */
3497  /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3498  * because we already hold the owner channel lock. */
3499  ast_queue_hangup(owner);
3500  }
3501 
3502  if (pvt->peercallno) {
3503  remove_by_peercallno(pvt);
3504  }
3505 
3506  if (pvt->transfercallno) {
3508  }
3509 
3510  if (!owner) {
3511  ao2_ref(pvt, -1);
3512  pvt = NULL;
3513  }
3514  }
3515 
3516  if (owner) {
3517  ast_channel_unlock(owner);
3518  }
3519 }
3520 
3521 static int update_packet(struct iax_frame *f)
3522 {
3523  /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3524  struct ast_iax2_full_hdr *fh = f->data;
3525  struct ast_frame af;
3526 
3527  /* if frame is encrypted. decrypt before updating it. */
3528  if (f->encmethods) {
3529  decode_frame(&f->mydcx, fh, &af, &f->datalen);
3530  }
3531  /* Mark this as a retransmission */
3532  fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3533  /* Update iseqno */
3534  f->iseqno = iaxs[f->callno]->iseqno;
3535  fh->iseqno = f->iseqno;
3536 
3537  /* Now re-encrypt the frame */
3538  if (f->encmethods) {
3539  /* since this is a retransmit frame, create a new random padding
3540  * before re-encrypting. */
3541  build_rand_pad(f->semirand, sizeof(f->semirand));
3542  encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3543  }
3544  return 0;
3545 }
3546 
3547 static int attempt_transmit(const void *data);
3548 static void __attempt_transmit(const void *data)
3549 {
3550  /* Attempt to transmit the frame to the remote peer...
3551  Called without iaxsl held. */
3552  struct iax_frame *f = (struct iax_frame *)data;
3553  int freeme = 0;
3554  int callno = f->callno;
3555 
3556  /* Make sure this call is still active */
3557  if (callno)
3558  ast_mutex_lock(&iaxsl[callno]);
3559  if (callno && iaxs[callno]) {
3560  if (f->retries < 0) {
3561  /* Already ACK'd */
3562  freeme = 1;
3563  } else if (f->retries >= max_retries) {
3564  /* Too many attempts. Record an error. */
3565  if (f->transfer) {
3566  /* Transfer timeout */
3567  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3568  } else if (f->final) {
3569  iax2_destroy(callno);
3570  } else {
3571  if (iaxs[callno]->owner) {
3572  ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3574  ast_channel_name(iaxs[f->callno]->owner),
3575  f->af.frametype,
3576  f->af.subclass.integer,
3577  f->ts,
3578  f->oseqno);
3579  }
3580  iaxs[callno]->error = ETIMEDOUT;
3581  if (iaxs[callno]->owner) {
3583  /* Hangup the fd */
3584  iax2_queue_frame(callno, &fr); /* XXX */
3585  /* Remember, owner could disappear */
3586  if (iaxs[callno] && iaxs[callno]->owner)
3588  } else {
3589  if (iaxs[callno]->reg) {
3590  memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3591  iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3592  iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3593  }
3594  iax2_destroy(callno);
3595  }
3596  }
3597  freeme = 1;
3598  } else {
3599  /* Update it if it needs it */
3600  update_packet(f);
3601  /* Attempt transmission */
3602  send_packet(f);
3603  f->retries++;
3604  /* Try again later after 10 times as long */
3605  f->retrytime *= 10;
3606  if (f->retrytime > MAX_RETRY_TIME)
3608  /* Transfer messages max out at one second */
3609  if (f->transfer && (f->retrytime > 1000))
3610  f->retrytime = 1000;
3611  f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3612  }
3613  } else {
3614  /* Make sure it gets freed */
3615  f->retries = -1;
3616  freeme = 1;
3617  }
3618 
3619  if (freeme) {
3620  /* Don't attempt delivery, just remove it from the queue */
3621  AST_LIST_REMOVE(&frame_queue[callno], f, list);
3622  ast_mutex_unlock(&iaxsl[callno]);
3623  f->retrans = -1; /* this is safe because this is the scheduled function */
3624  /* Free the IAX frame */
3625  iax2_frame_free(f);
3626  } else if (callno) {
3627  ast_mutex_unlock(&iaxsl[callno]);
3628  }
3629 }
3630 
3631 static int attempt_transmit(const void *data)
3632 {
3633 #ifdef SCHED_MULTITHREADED
3635 #endif
3636  __attempt_transmit(data);
3637  return 0;
3638 }
3639 
3640 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3641 {
3642  struct iax2_peer *peer = NULL;
3643  struct iax2_user *user = NULL;
3644  static const char * const choices[] = { "all", NULL };
3645  char *cmplt;
3646 
3647  switch (cmd) {
3648  case CLI_INIT:
3649  e->command = "iax2 prune realtime";
3650  e->usage =
3651  "Usage: iax2 prune realtime [<peername>|all]\n"
3652  " Prunes object(s) from the cache\n";
3653  return NULL;
3654  case CLI_GENERATE:
3655  if (a->pos == 3) {
3656  cmplt = ast_cli_complete(a->word, choices, a->n);
3657  if (!cmplt)
3658  cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3659  return cmplt;
3660  }
3661  return NULL;
3662  }
3663  if (a->argc != 4)
3664  return CLI_SHOWUSAGE;
3665  if (!strcmp(a->argv[3], "all")) {
3666  prune_users();
3667  prune_peers();
3668  ast_cli(a->fd, "Cache flushed successfully.\n");
3669  return CLI_SUCCESS;
3670  }
3671  peer = find_peer(a->argv[3], 0);
3672  user = find_user(a->argv[3]);
3673  if (peer || user) {
3674  if (peer) {
3675  if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3677  expire_registry(peer_ref(peer));
3678  ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3679  } else {
3680  ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3681  }
3682  peer_unref(peer);
3683  }
3684  if (user) {
3685  if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3687  ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3688  } else {
3689  ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3690  }
3691  ao2_unlink(users,user);
3692  user_unref(user);
3693  }
3694  } else {
3695  ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3696  }
3697 
3698  return CLI_SUCCESS;
3699 }
3700 
3701 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3702 {
3703  switch (cmd) {
3704  case CLI_INIT:
3705  e->command = "iax2 test losspct";
3706  e->usage =
3707  "Usage: iax2 test losspct <percentage>\n"
3708  " For testing, throws away <percentage> percent of incoming packets\n";
3709  return NULL;
3710  case CLI_GENERATE:
3711  return NULL;
3712  }
3713  if (a->argc != 4)
3714  return CLI_SHOWUSAGE;
3715 
3716  test_losspct = atoi(a->argv[3]);
3717 
3718  return CLI_SUCCESS;
3719 }
3720 
3721 #ifdef IAXTESTS
3722 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3723 {
3724  switch (cmd) {
3725  case CLI_INIT:
3726  e->command = "iax2 test late";
3727  e->usage =
3728  "Usage: iax2 test late <ms>\n"
3729  " For testing, count the next frame as <ms> ms late\n";
3730  return NULL;
3731  case CLI_GENERATE:
3732  return NULL;
3733  }
3734 
3735  if (a->argc != 4)
3736  return CLI_SHOWUSAGE;
3737 
3738  test_late = atoi(a->argv[3]);
3739 
3740  return CLI_SUCCESS;
3741 }
3742 
3743 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3744 {
3745  switch (cmd) {
3746  case CLI_INIT:
3747  e->command = "iax2 test resync";
3748  e->usage =
3749  "Usage: iax2 test resync <ms>\n"
3750  " For testing, adjust all future frames by <ms> ms\n";
3751  return NULL;
3752  case CLI_GENERATE:
3753  return NULL;
3754  }
3755 
3756  if (a->argc != 4)
3757  return CLI_SHOWUSAGE;
3758 
3759  test_resync = atoi(a->argv[3]);
3760 
3761  return CLI_SUCCESS;
3762 }
3763 
3764 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3765 {
3766  switch (cmd) {
3767  case CLI_INIT:
3768  e->command = "iax2 test jitter";
3769  e->usage =
3770  "Usage: iax2 test jitter <ms> <pct>\n"
3771  " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3772  " percentage of packets. If <pct> is not specified, adds\n"
3773  " jitter to all packets.\n";
3774  return NULL;
3775  case CLI_GENERATE:
3776  return NULL;
3777  }
3778 
3779  if (a->argc < 4 || a->argc > 5)
3780  return CLI_SHOWUSAGE;
3781 
3782  test_jit = atoi(a->argv[3]);
3783  if (a->argc == 5)
3784  test_jitpct = atoi(a->argv[4]);
3785 
3786  return CLI_SUCCESS;
3787 }
3788 #endif /* IAXTESTS */
3789 
3790 /*! \brief peer_status: Report Peer status in character string */
3791 /* returns 1 if peer is online, -1 if unmonitored */
3792 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3793 {
3794  int res = 0;
3795  if (peer->maxms) {
3796  if (peer->lastms < 0) {
3797  ast_copy_string(status, "UNREACHABLE", statuslen);
3798  } else if (peer->lastms > peer->maxms) {
3799  snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3800  res = 1;
3801  } else if (peer->lastms) {
3802  snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3803  res = 1;
3804  } else {
3805  ast_copy_string(status, "UNKNOWN", statuslen);
3806  }
3807  } else {
3808  ast_copy_string(status, "Unmonitored", statuslen);
3809  res = -1;
3810  }
3811  return res;
3812 }
3813 
3814 /*! \brief Show one peer in detail */
3815 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3816 {
3817  char status[64];
3818  char cbuf[256];
3819  struct iax2_peer *peer;
3820  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3821  struct ast_str *encmethods = ast_str_alloca(256);
3822  int load_realtime = 0;
3823 
3824  switch (cmd) {
3825  case CLI_INIT:
3826  e->command = "iax2 show peer";
3827  e->usage =
3828  "Usage: iax2 show peer <name>\n"
3829  " Display details on specific IAX peer\n";
3830  return NULL;
3831  case CLI_GENERATE:
3832  if (a->pos == 3)
3833  return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3834  return NULL;
3835  }
3836 
3837  if (a->argc < 4)
3838  return CLI_SHOWUSAGE;
3839 
3840  load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3841 
3842  peer = find_peer(a->argv[3], load_realtime);
3843  if (peer) {
3844  char *str_addr, *str_defaddr;
3845  char *str_port, *str_defport;
3846 
3847  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3848  str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3849  str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3850  str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3851 
3852  encmethods_to_str(peer->encmethods, &encmethods);
3853  ast_cli(a->fd, "\n\n");
3854  ast_cli(a->fd, " * Name : %s\n", peer->name);
3855  ast_cli(a->fd, " Description : %s\n", peer->description);
3856  ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3857  ast_cli(a->fd, " Context : %s\n", peer->context);
3858  ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3859  ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3860  ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3861  ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3862  ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3863  ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3864  ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3865  ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3866  ast_cli(a->fd, " Expire : %d\n", peer->expire);
3867  ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3868  ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3869  ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3870  ast_cli(a->fd, " Username : %s\n", peer->username);
3871  ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3872 
3873  if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3874  strcpy(cbuf, "Error"); /* Safe */
3875  }
3876  ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3877 
3878  peer_status(peer, status, sizeof(status));
3879  ast_cli(a->fd, " Status : %s\n", status);
3880  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");
3881  ast_cli(a->fd, "\n");
3882  peer_unref(peer);
3883  } else {
3884  ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3885  ast_cli(a->fd, "\n");
3886  }
3887 
3888  return CLI_SUCCESS;
3889 }
3890 
3891 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3892 {
3893  int which = 0;
3894  struct iax2_peer *peer;
3895  char *res = NULL;
3896  int wordlen = strlen(word);
3897  struct ao2_iterator i;
3898 
3899  i = ao2_iterator_init(peers, 0);
3900  while ((peer = ao2_iterator_next(&i))) {
3901  if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3902  && (!flags || ast_test_flag64(peer, flags))) {
3903  res = ast_strdup(peer->name);
3904  peer_unref(peer);
3905  break;
3906  }
3907  peer_unref(peer);
3908  }
3910 
3911  return res;
3912 }
3913 
3914 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3915 {
3916  struct iax_frame *cur;
3917  int cnt = 0, dead = 0, final = 0, i = 0;
3918 
3919  switch (cmd) {
3920  case CLI_INIT:
3921  e->command = "iax2 show stats";
3922  e->usage =
3923  "Usage: iax2 show stats\n"
3924  " Display statistics on IAX channel driver.\n";
3925  return NULL;
3926  case CLI_GENERATE:
3927  return NULL;
3928  }
3929 
3930  if (a->argc != 3)
3931  return CLI_SHOWUSAGE;
3932 
3933  for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3934  ast_mutex_lock(&iaxsl[i]);
3935  AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3936  if (cur->retries < 0)
3937  dead++;
3938  if (cur->final)
3939  final++;
3940  cnt++;
3941  }
3942  ast_mutex_unlock(&iaxsl[i]);
3943  }
3944 
3945  ast_cli(a->fd, " IAX Statistics\n");
3946  ast_cli(a->fd, "---------------------\n");
3947  ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3948  ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3950  ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3951 
3952  trunk_timed = trunk_untimed = 0;
3955 
3956  return CLI_SUCCESS;
3957 }
3958 
3959 /*! \brief Set trunk MTU from CLI */
3960 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3961 {
3962  int mtuv;
3963 
3964  switch (cmd) {
3965  case CLI_INIT:
3966  e->command = "iax2 set mtu";
3967  e->usage =
3968  "Usage: iax2 set mtu <value>\n"
3969  " Set the system-wide IAX IP mtu to <value> bytes net or\n"
3970  " zero to disable. Disabling means that the operating system\n"
3971  " must handle fragmentation of UDP packets when the IAX2 trunk\n"
3972  " packet exceeds the UDP payload size. This is substantially\n"
3973  " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3974  " greater for G.711 samples.\n";
3975  return NULL;
3976  case CLI_GENERATE:
3977  return NULL;
3978  }
3979 
3980  if (a->argc != 4)
3981  return CLI_SHOWUSAGE;
3982  if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3983  mtuv = MAX_TRUNK_MTU;
3984  else
3985  mtuv = atoi(a->argv[3]);
3986 
3987  if (mtuv == 0) {
3988  ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
3990  return CLI_SUCCESS;
3991  }
3992  if (mtuv < 172 || mtuv > 4000) {
3993  ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
3994  return CLI_SHOWUSAGE;
3995  }
3996  ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
3997  global_max_trunk_mtu = mtuv;
3998  return CLI_SUCCESS;
3999 }
4000 
4001 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4002 {
4003  struct iax2_dpcache *dp = NULL;
4004  char tmp[1024], *pc = NULL;
4005  int s, x, y;
4006  struct timeval now = ast_tvnow();
4007 
4008  switch (cmd) {
4009  case CLI_INIT:
4010  e->command = "iax2 show cache";
4011  e->usage =
4012  "Usage: iax2 show cache\n"
4013  " Display currently cached IAX Dialplan results.\n";
4014  return NULL;
4015  case CLI_GENERATE:
4016  return NULL;
4017  }
4018 
4020 
4021  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4022 
4023  AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4024  s = dp->expiry.tv_sec - now.tv_sec;
4025  tmp[0] = '\0';
4026  if (dp->flags & CACHE_FLAG_EXISTS)
4027  strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4028  if (dp->flags & CACHE_FLAG_NONEXISTENT)
4029  strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4030  if (dp->flags & CACHE_FLAG_CANEXIST)
4031  strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4032  if (dp->flags & CACHE_FLAG_PENDING)
4033  strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4034  if (dp->flags & CACHE_FLAG_TIMEOUT)
4035  strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4036  if (dp->flags & CACHE_FLAG_TRANSMITTED)
4037  strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4038  if (dp->flags & CACHE_FLAG_MATCHMORE)
4039  strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4040  if (dp->flags & CACHE_FLAG_UNKNOWN)
4041  strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4042  /* Trim trailing pipe */
4043  if (!ast_strlen_zero(tmp)) {
4044  tmp[strlen(tmp) - 1] = '\0';
4045  } else {
4046  ast_copy_string(tmp, "(none)", sizeof(tmp));
4047  }
4048  y = 0;
4049  pc = strchr(dp->peercontext, '@');
4050  if (!pc) {
4051  pc = dp->peercontext;
4052  } else {
4053  pc++;
4054  }
4055  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4056  if (dp->waiters[x] > -1)
4057  y++;
4058  }
4059  if (s > 0) {
4060  ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4061  } else {
4062  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4063  }
4064  }
4065 
4067 
4068  return CLI_SUCCESS;
4069 }
4070 
4071 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4072 
4073 static void unwrap_timestamp(struct iax_frame *fr)
4074 {
4075  /* Video mini frames only encode the lower 15 bits of the session
4076  * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4077  const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4078  const int lower_mask = (1 << ts_shift) - 1;
4079  const int upper_mask = ~lower_mask;
4080  const int last_upper = iaxs[fr->callno]->last & upper_mask;
4081 
4082  if ( (fr->ts & upper_mask) == last_upper ) {
4083  const int x = fr->ts - iaxs[fr->callno]->last;
4084  const int threshold = (ts_shift == 15) ? 25000 : 50000;
4085 
4086  if (x < -threshold) {
4087  /* Sudden big jump backwards in timestamp:
4088  What likely happened here is that miniframe timestamp has circled but we haven't
4089  gotten the update from the main packet. We'll just pretend that we did, and
4090  update the timestamp appropriately. */
4091  fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4092  if (iaxdebug)
4093  ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4094  } else if (x > threshold) {
4095  /* Sudden apparent big jump forwards in timestamp:
4096  What's likely happened is this is an old miniframe belonging to the previous
4097  top 15 or 16-bit timestamp that has turned up out of order.
4098  Adjust the timestamp appropriately. */
4099  fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4100  if (iaxdebug)
4101  ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4102  }
4103  }
4104 }
4105 
4106 static int get_from_jb(const void *p);
4107 
4108 static void update_jbsched(struct chan_iax2_pvt *pvt)
4109 {
4110  int when;
4111 
4112  when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4113 
4114  when = jb_next(pvt->jb) - when;
4115 
4116  if (when <= 0) {
4117  /* XXX should really just empty until when > 0.. */
4118  when = 1;
4119  }
4120 
4121  pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4122  CALLNO_TO_PTR(pvt->callno));
4123 }
4124 
4125 static void __get_from_jb(const void *p)
4126 {
4127  int callno = PTR_TO_CALLNO(p);
4128  struct chan_iax2_pvt *pvt = NULL;
4129  struct iax_frame *fr;
4130  jb_frame frame;
4131  int ret;
4132  long ms;
4133  long next;
4134  struct timeval now = ast_tvnow();
4135 
4136  /* Make sure we have a valid private structure before going on */
4137  ast_mutex_lock(&iaxsl[callno]);
4138  pvt = iaxs[callno];
4139  if (!pvt) {
4140  /* No go! */
4141  ast_mutex_unlock(&iaxsl[callno]);
4142  return;
4143  }
4144 
4145  pvt->jbid = -1;
4146 
4147  /* round up a millisecond since ast_sched_runq does; */
4148  /* prevents us from spinning while waiting for our now */
4149  /* to catch up with runq's now */
4150  now.tv_usec += 1000;
4151 
4152  ms = ast_tvdiff_ms(now, pvt->rxcore);
4153 
4154  if(ms >= (next = jb_next(pvt->jb))) {
4155  struct ast_format *voicefmt;
4157  ret = jb_get(pvt->jb, &frame, ms, voicefmt ? ast_format_get_default_ms(voicefmt) : 20);
4158  switch(ret) {
4159  case JB_OK:
4160  fr = frame.data;
4161  __do_deliver(fr);
4162  /* __do_deliver() can cause the call to disappear */
4163  pvt = iaxs[callno];
4164  break;
4165  case JB_INTERP:
4166  {
4167  struct ast_frame af = { 0, };
4168 
4169  /* create an interpolation frame */
4171  af.subclass.format = voicefmt;
4172  af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4173  af.src = "IAX2 JB interpolation";
4174  af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4176 
4177  /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4178  * which we'd need to malloc, and then it would free it. That seems like a drag */
4179  if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4180  iax2_queue_frame(callno, &af);
4181  /* iax2_queue_frame() could cause the call to disappear */
4182  pvt = iaxs[callno];
4183  }
4184  }
4185  break;
4186  case JB_DROP:
4187  iax2_frame_free(frame.data);
4188  break;
4189  case JB_NOFRAME:
4190  case JB_EMPTY:
4191  /* do nothing */
4192  break;
4193  default:
4194  /* shouldn't happen */
4195  break;
4196  }
4197  }
4198  if (pvt)
4199  update_jbsched(pvt);
4200  ast_mutex_unlock(&iaxsl[callno]);
4201 }
4202 
4203 static int get_from_jb(const void *data)
4204 {
4205 #ifdef SCHED_MULTITHREADED
4206  if (schedule_action(__get_from_jb, data))
4207 #endif
4208  __get_from_jb(data);
4209  return 0;
4210 }
4211 
4212 /*!
4213  * \note This function assumes fr->callno is locked
4214  *
4215  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4216  * was valid before calling it, it may no longer be valid after calling it.
4217  */
4218 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4219 {
4220  int type, len;
4221  int ret;
4222  int needfree = 0;
4223 
4224  /*
4225  * Clear fr->af.data if there is no data in the buffer. Things
4226  * like AST_CONTROL_HOLD without a suggested music class must
4227  * have a NULL pointer.
4228  */
4229  if (!fr->af.datalen) {
4230  memset(&fr->af.data, 0, sizeof(fr->af.data));
4231  }
4232 
4233  /* Attempt to recover wrapped timestamps */
4234  unwrap_timestamp(fr);
4235 
4236  /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4237  if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4238  fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4239  else {
4240 #if 0
4241  ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4242 #endif
4243  fr->af.delivery = ast_tv(0,0);
4244  }
4245 
4246  type = JB_TYPE_CONTROL;
4247  len = 0;
4248 
4249  if(fr->af.frametype == AST_FRAME_VOICE) {
4250  type = JB_TYPE_VOICE;
4252  } else if(fr->af.frametype == AST_FRAME_CNG) {
4253  type = JB_TYPE_SILENCE;
4254  }
4255 
4256  if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4257  if (tsout)
4258  *tsout = fr->ts;
4259  __do_deliver(fr);
4260  return -1;
4261  }
4262 
4263  /* insert into jitterbuffer */
4264  /* TODO: Perhaps we could act immediately if it's not droppable and late */
4265  ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4266  calc_rxstamp(iaxs[fr->callno],fr->ts));
4267  if (ret == JB_DROP) {
4268  needfree++;
4269  } else if (ret == JB_SCHED) {
4270  update_jbsched(iaxs[fr->callno]);
4271  }
4272  if (tsout)
4273  *tsout = fr->ts;
4274  if (needfree) {
4275  /* Free our iax frame */
4276  iax2_frame_free(fr);
4277  return -1;
4278  }
4279  return 0;
4280 }
4281 
4282 static int transmit_frame(void *data)
4283 {
4284  struct iax_frame *fr = data;
4285 
4286  ast_mutex_lock(&iaxsl[fr->callno]);
4287 
4288  fr->sentyet = 1;
4289 
4290  if (iaxs[fr->callno]) {
4291  send_packet(fr);
4292  }
4293 
4294  if (fr->retries < 0) {
4295  ast_mutex_unlock(&iaxsl[fr->callno]);
4296  /* No retransmit requested */
4297  iax_frame_free(fr);
4298  } else {
4299  /* We need reliable delivery. Schedule a retransmission */
4301  fr->retries++;
4302  fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
4303  ast_mutex_unlock(&iaxsl[fr->callno]);
4304  }
4305 
4306  return 0;
4307 }
4308 
4309 static int iax2_transmit(struct iax_frame *fr)
4310 {
4311  fr->sentyet = 0;
4312 
4313  return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
4314 }
4315 
4316 static int iax2_digit_begin(struct ast_channel *c, char digit)
4317 {
4319 }
4320 
4321 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4322 {
4324 }
4325 
4326 static int iax2_sendtext(struct ast_channel *c, const char *text)
4327 {
4328 
4330  0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4331 }
4332 
4333 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4334 {
4336 }
4337 
4338 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4339 {
4340  return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4341 }
4342 
4343 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4344 {
4345  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4346  ast_mutex_lock(&iaxsl[callno]);
4347  if (iaxs[callno])
4348  iaxs[callno]->owner = newchan;
4349  else
4350  ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4351  ast_mutex_unlock(&iaxsl[callno]);
4352  return 0;
4353 }
4354 
4355 /*!
4356  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4357  * so do not call this with a pvt lock held.
4358  */
4359 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4360 {
4361  struct ast_variable *var = NULL;
4362  struct ast_variable *tmp;
4363  struct iax2_peer *peer=NULL;
4364  time_t regseconds = 0, nowtime;
4365  int dynamic=0;
4366  char *str_addr, *str_port;
4367 
4368  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4369  str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4370 
4371  if (peername) {
4372  var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4373  if (!var && !ast_sockaddr_isnull(addr)) {
4374  var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4375  }
4376  } else if (!ast_sockaddr_isnull(addr)) {
4377  var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4378  if (var) {
4379  /* We'll need the peer name in order to build the structure! */
4380  for (tmp = var; tmp; tmp = tmp->next) {
4381  if (!strcasecmp(tmp->name, "name"))
4382  peername = tmp->value;
4383  }
4384  }
4385  }
4386  if (!var && peername) { /* Last ditch effort */
4387  var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4388  /*!\note
4389  * If this one loaded something, then we need to ensure that the host
4390  * field matched. The only reason why we can't have this as a criteria
4391  * is because we only have the IP address and the host field might be
4392  * set as a name (and the reverse PTR might not match).
4393  */
4394  if (var && !ast_sockaddr_isnull(addr)) {
4395  for (tmp = var; tmp; tmp = tmp->next) {
4396  if (!strcasecmp(tmp->name, "host")) {
4397  struct ast_sockaddr *hostaddr = NULL;
4398 
4400  || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4401  /* No match */
4402  ast_variables_destroy(var);
4403  var = NULL;
4404  }
4405  ast_free(hostaddr);
4406  break;
4407  }
4408  }
4409  }
4410  }
4411  if (!var)
4412  return NULL;
4413 
4414  peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4415 
4416  if (!peer) {
4417  ast_variables_destroy(var);
4418  return NULL;
4419  }
4420 
4421  for (tmp = var; tmp; tmp = tmp->next) {
4422  /* Make sure it's not a user only... */
4423  if (!strcasecmp(tmp->name, "type")) {
4424  if (strcasecmp(tmp->value, "friend") &&
4425  strcasecmp(tmp->value, "peer")) {
4426  /* Whoops, we weren't supposed to exist! */
4427  peer = peer_unref(peer);
4428  break;
4429  }
4430  } else if (!strcasecmp(tmp->name, "regseconds")) {
4431  ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4432  } else if (!strcasecmp(tmp->name, "ipaddr")) {
4433  int setport = ast_sockaddr_port(&peer->addr);
4435  ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4436  } else {
4437  ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4438  }
4439  ast_sockaddr_set_port(&peer->addr, setport);
4440  } else if (!strcasecmp(tmp->name, "port")) {
4441  int bindport;
4442  if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4443  bindport = IAX_DEFAULT_PORTNO;
4444  }
4445  ast_sockaddr_set_port(&peer->addr, bindport);
4446  } else if (!strcasecmp(tmp->name, "host")) {
4447  if (!strcasecmp(tmp->value, "dynamic"))
4448  dynamic = 1;
4449  }
4450  }
4451 
4452  ast_variables_destroy(var);
4453 
4454  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4456  if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4457  if (peer->expire > -1) {
4458  if (!AST_SCHED_DEL(sched, peer->expire)) {
4459  peer->expire = -1;
4460  peer_unref(peer);
4461  }
4462  }
4463  peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
4464  if (peer->expire == -1)
4465  peer_unref(peer);
4466  }
4467  ao2_link(peers, peer);
4468  if (ast_test_flag64(peer, IAX_DYNAMIC))
4469  reg_source_db(peer);
4470  } else {
4472  }
4473 
4474  if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
4475  time(&nowtime);
4476  if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4477  memset(&peer->addr, 0, sizeof(peer->addr));
4478  realtime_update_peer(peer->name, &peer->addr, 0);
4479  ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4480  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4481  }
4482  else {
4483  ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4484  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4485  }
4486  }
4487 
4488  return peer;
4489 }
4490 
4491 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4492 {
4493  struct ast_variable *var;
4494  struct ast_variable *tmp;
4495  struct iax2_user *user=NULL;
4496  char *str_addr, *str_port;
4497 
4498  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4499  str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4500 
4501  var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4502  if (!var)
4503  var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4504  if (!var && !ast_sockaddr_isnull(addr)) {
4505  var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4506  if (!var)
4507  var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4508  }
4509  if (!var) { /* Last ditch effort */
4510  var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4511  /*!\note
4512  * If this one loaded something, then we need to ensure that the host
4513  * field matched. The only reason why we can't have this as a criteria
4514  * is because we only have the IP address and the host field might be
4515  * set as a name (and the reverse PTR might not match).
4516  */
4517  if (var) {
4518  for (tmp = var; tmp; tmp = tmp->next) {
4519  if (!strcasecmp(tmp->name, "host")) {
4520  struct ast_sockaddr *hostaddr = NULL;
4521 
4523  || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4524  /* No match */
4525  ast_variables_destroy(var);
4526  var = NULL;
4527  }
4528  ast_free(hostaddr);
4529  break;
4530  }
4531  }
4532  }
4533  }
4534  if (!var)
4535  return NULL;
4536 
4537  tmp = var;
4538  while(tmp) {
4539  /* Make sure it's not a peer only... */
4540  if (!strcasecmp(tmp->name, "type")) {
4541  if (strcasecmp(tmp->value, "friend") &&
4542  strcasecmp(tmp->value, "user")) {
4543  return NULL;
4544  }
4545  }
4546  tmp = tmp->next;
4547  }
4548 
4549  user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
4550 
4551  ast_variables_destroy(var);
4552 
4553  if (!user)
4554  return NULL;
4555 
4556  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4558  ao2_link(users, user);
4559  } else {
4561  }
4562 
4563  return user;
4564 }
4565 
4566 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4567 {
4568  char regseconds[20];
4569  const char *sysname = ast_config_AST_SYSTEM_NAME;
4570  char *syslabel = NULL;
4571  char *port;
4572 
4573  if (ast_strlen_zero(sysname)) /* No system name, disable this */
4574  sysname = NULL;
4575  else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
4576  syslabel = "regserver";
4577 
4578  snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4579  port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4580  ast_update_realtime("iaxpeers", "name", peername,
4581  "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4582  "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4583  "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
4584 }
4585 
4588  uint64_t flags;
4589  struct iax2_codec_pref prefs;
4590  int maxtime;
4593  int found;
4594  int sockfd;
4595  int adsi;
4596  char username[80];
4597  char secret[80];
4598  char outkey[80];
4599  char timezone[80];
4600  char cid_num[80];
4601  char cid_name[80];
4603  char peercontext[AST_MAX_CONTEXT];
4606 };
4607 
4608 static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4609 {
4610  struct iax2_peer *peer;
4611  int res = -1;
4612 
4614  cai->sockfd = defaultsockfd;
4615  cai->maxtime = 0;
4616 
4617  if (!(peer = find_peer(peername, 1))) {
4618  struct ast_sockaddr peer_addr;
4619 
4620  peer_addr.ss.ss_family = AST_AF_UNSPEC;
4621  cai->found = 0;
4622  if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4623  ast_log(LOG_WARNING, "No such host: %s\n", peername);
4624  return -1;
4625  }
4626 
4627  if (!ast_sockaddr_port(&peer_addr)) {
4629  }
4630 
4631  ast_sockaddr_copy(addr, &peer_addr);
4632  /*
4633  * Use The global iax prefs for unknown peer/user.
4634  * However, move the calling channel's native codec to
4635  * the top of the preference list.
4636  */
4637  cai->prefs = prefs_global;
4638  if (c) {
4639  int i;
4640 
4641  for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4644  iax2_codec_pref_prepend(&cai->prefs, format,
4646  1);
4647  ao2_ref(format, -1);
4648  }
4649  }
4650  return 0;
4651  }
4652 
4653  cai->found = 1;
4654 
4655  /* if the peer has no address (current or default), return failure */
4656  if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4657  goto return_unref;
4658  }
4659 
4660  /* if the peer is being monitored and is currently unreachable, return failure */
4661  if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4662  goto return_unref;
4663 
4665  cai->maxtime = peer->maxms;
4666  cai->capability = peer->capability;
4667  cai->encmethods = peer->encmethods;
4668  cai->authmethods = peer->authmethods;
4669  cai->sockfd = peer->sockfd;
4670  cai->adsi = peer->adsi;
4671  cai->prefs = peer->prefs;
4672  /* Move the calling channel's native codec to the top of the preference list */
4673  if (c) {
4674  int i;
4675 
4676  for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4677  struct ast_format *tmpfmt = ast_format_cap_get_format(
4679  iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4681  1);
4682  ao2_ref(tmpfmt, -1);
4683  }
4684  }
4685  ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4686  ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4687  ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4688  ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4689  ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4690  ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4691  ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4692  ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4693  ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4694  if (ast_strlen_zero(peer->dbsecret)) {
4695  ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4696  } else {
4697  char *family;
4698  char *key = NULL;
4699 
4700  family = ast_strdupa(peer->dbsecret);
4701  key = strchr(family, '/');
4702  if (key)
4703  *key++ = '\0';
4704  if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4705  ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4706  goto return_unref;
4707  }
4708  }
4709 
4710  if (!ast_sockaddr_isnull(&peer->addr)) {
4711  ast_sockaddr_copy(addr, &peer->addr);
4712  } else {
4713  ast_sockaddr_copy(addr, &peer->defaddr);
4714  }
4715 
4716  res = 0;
4717 
4718 return_unref:
4719  peer_unref(peer);
4720 
4721  return res;
4722 }
4723 
4724 static void __auto_congest(const void *nothing)
4725 {
4726  int callno = PTR_TO_CALLNO(nothing);
4728  ast_mutex_lock(&iaxsl[callno]);
4729  if (iaxs[callno]) {
4730  iaxs[callno]->initid = -1;
4731  iax2_queue_frame(callno, &f);
4732  ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4733  }
4734  ast_mutex_unlock(&iaxsl[callno]);
4735 }
4736 
4737 static int auto_congest(const void *data)
4738 {
4739 #ifdef SCHED_MULTITHREADED
4740  if (schedule_action(__auto_congest, data))
4741 #endif
4742  __auto_congest(data);
4743  return 0;
4744 }
4745 
4746 static unsigned int iax2_datetime(const char *tz)
4747 {
4748  struct timeval t = ast_tvnow();
4749  struct ast_tm tm;
4750  unsigned int tmp;
4751  ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
4752  tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
4753  tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
4754  tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
4755  tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
4756  tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
4757  tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
4758  return tmp;
4759 }
4760 
4762  char *username;
4763  char *password;
4764  char *key;
4765  char *peer;
4766  char *port;
4767  char *exten;
4768  char *context;
4769  char *options;
4770 };
4771 
4772 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
4773  struct ast_sockaddr *addr, int command, int ts, unsigned char seqno,
4774  int sockfd, struct iax_ie_data *ied)
4775 {
4776  struct {
4777  struct ast_iax2_full_hdr f;
4778  struct iax_ie_data ied;
4779  } data;
4780  size_t size = sizeof(struct ast_iax2_full_hdr);
4781 
4782  if (ied) {
4783  size += ied->pos;
4784  memcpy(&data.ied, ied->buf, ied->pos);
4785  }
4786 
4787  data.f.scallno = htons(0x8000 | callno);
4788  data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
4789  data.f.ts = htonl(ts);
4790  data.f.iseqno = seqno;
4791  data.f.oseqno = 0;
4792  data.f.type = AST_FRAME_IAX;
4793  data.f.csub = compress_subclass(command);
4794 
4795  iax_outputframe(NULL, &data.f, 0, addr, size - sizeof(struct ast_iax2_full_hdr));
4796 
4797  return ast_sendto(sockfd, &data, size, 0, addr);
4798 }
4799 
4800 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
4801 {
4802  /* first make sure their are two empty bytes left in ied->buf */
4803  if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
4804  ied->buf[ied->pos++] = IAX_IE_CALLTOKEN; /* type */
4805  ied->buf[ied->pos++] = 0; /* data size, ZERO in this case */
4806  pvt->calltoken_ie_len = 2;
4807  }
4808 }
4809 
4810 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
4811 {
4812  struct chan_iax2_pvt *pvt = iaxs[callno];
4813  int frametype = f->af.frametype;
4814  int subclass = f->af.subclass.integer;
4815  struct {
4816  struct ast_iax2_full_hdr fh;
4817  struct iax_ie_data ied;
4818  } data = {
4819  .ied.buf = { 0 },
4820  .ied.pos = 0,
4821  };
4822  /* total len - header len gives us the frame's IE len */
4823  int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
4824 
4825  if (!pvt) {
4826  return; /* this should not be possible if called from socket_process() */
4827  }
4828 
4829  /*
4830  * Check to make sure last frame sent is valid for call token resend
4831  * 1. Frame should _NOT_ be encrypted since it starts the IAX dialog
4832  * 2. Frame should _NOT_ already have a destination callno
4833  * 3. Frame must be a valid iax_frame subclass capable of starting dialog
4834  * 4. Pvt must have a calltoken_ie_len which represents the number of
4835  * bytes at the end of the frame used for the previous calltoken ie.
4836  * 5. Pvt's calltoken_ie_len must be _LESS_ than the total IE length
4837  * 6. Total length of f->data must be _LESS_ than size of our data struct
4838  * because f->data must be able to fit within data.
4839  */
4840  if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
4841  || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
4842  (f->datalen > sizeof(data))) {
4843 
4844  return; /* ignore resend, token was not valid for the dialog */
4845  }
4846 
4847  /* token is valid
4848  * 1. Copy frame data over
4849  * 2. Redo calltoken IE, it will always be the last ie in the frame.
4850  * NOTE: Having the ie always be last is not protocol specified,
4851  * it is only an implementation choice. Since we only expect the ie to
4852  * be last for frames we have sent, this can no way be affected by
4853  * another end point.
4854  * 3. Remove frame from queue
4855  * 4. Free old frame
4856  * 5. Clear previous seqnos
4857  * 6. Resend with CALLTOKEN ie.
4858  */
4859 
4860  /* ---1.--- */
4861  memcpy(&data, f->data, f->datalen);
4862  data.ied.pos = ie_data_pos;
4863 
4864  /* ---2.--- */
4865  /* move to the beginning of the calltoken ie so we can write over it */
4866  data.ied.pos -= pvt->calltoken_ie_len;
4867  iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
4868 
4869  /* make sure to update token length incase it ever has to be stripped off again */
4870  pvt->calltoken_ie_len = data.ied.pos - ie_data_pos; /* new pos minus old pos tells how big token ie is */
4871 
4872  /* ---3.--- */
4873  AST_LIST_REMOVE(&frame_queue[callno], f, list);
4874 
4875  /* ---4.--- */
4876  iax2_frame_free(f);
4877 
4878  /* ---5.--- */
4879  pvt->oseqno = 0;
4880  pvt->rseqno = 0;
4881  pvt->iseqno = 0;
4882  pvt->aseqno = 0;
4883  if (pvt->peercallno) {
4884  remove_by_peercallno(pvt);
4885  pvt->peercallno = 0;
4886  }
4887 
4888  /* ---6.--- */
4889  send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
4890 }
4891 
4892 static void requirecalltoken_mark_auto(const char *name, int subclass)
4893 {
4894  struct iax2_user *user = NULL;
4895  struct iax2_peer *peer = NULL;
4896 
4897  if (ast_strlen_zero(name)) {
4898  return; /* no username given */
4899  }
4900 
4901  if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
4903  } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
4905  }
4906 
4907  if (peer) {
4908  peer_unref(peer);
4909  }
4910  if (user) {
4911  user_unref(user);
4912  }
4913 }
4914 
4915 /*!
4916  * \internal
4917  *
4918  * \brief handles calltoken logic for a received iax_frame.
4919  *
4920  * \note frametype must be AST_FRAME_IAX.
4921  *
4922  * \note
4923  * Three different cases are possible here.
4924  * Case 1. An empty calltoken is provided. This means the client supports
4925  * calltokens but has not yet received one from us. In this case
4926  * a full calltoken IE is created and sent in a calltoken fullframe.
4927  * Case 2. A full calltoken is received and must be checked for validity.
4928  * Case 3. No calltoken is received indicating that the client does not
4929  * support calltokens. In this case it is up to the configuration
4930  * to decide how this should be handled (reject or permit without calltoken)
4931  */
4932 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
4933  struct ast_sockaddr *addr, int fd)
4934 {
4935 #define CALLTOKEN_HASH_FORMAT "%s%u%d" /* address + port + ts + randomcalldata */
4936 #define CALLTOKEN_IE_FORMAT "%u?%s" /* time + ? + (40 char hash) */
4937  struct ast_str *buf = ast_str_alloca(256);
4938  time_t t = time(NULL);
4939  char hash[41]; /* 40 char sha1 hash */
4940  int subclass = uncompress_subclass(fh->csub);
4941 
4942  /* ----- Case 1 ----- */
4943  if (ies->calltoken && !ies->calltokendata) { /* empty calltoken is provided, client supports calltokens */
4944  struct iax_ie_data ied = {
4945  .buf = { 0 },
4946  .pos = 0,
4947  };
4948 
4949  /* create the hash with their address data and our timestamp */
4950  ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_sockaddr_stringify(addr), (unsigned int) t, randomcalltokendata);
4951  ast_sha1_hash(hash, ast_str_buffer(buf));
4952 
4953  ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
4955  send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
4956 
4957  return 1;
4958 
4959  /* ----- Case 2 ----- */
4960  } else if (ies->calltoken && ies->calltokendata) { /* calltoken received, check to see if it is valid */
4961  char *rec_hash = NULL; /* the received hash, make sure it matches with ours. */
4962  char *rec_ts = NULL; /* received timestamp */
4963  unsigned int rec_time; /* received time_t */
4964 
4965  /* split the timestamp from the hash data */
4966  rec_hash = strchr((char *) ies->calltokendata, '?');
4967  if (rec_hash) {
4968  *rec_hash++ = '\0';
4969  rec_ts = (char *) ies->calltokendata;
4970  }
4971 
4972  /* check that we have valid data before we do any comparisons */
4973  if (!rec_hash || !rec_ts) {
4974  goto reject;
4975  } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
4976  goto reject;
4977  }
4978 
4979  /* create a hash with their address and the _TOKEN'S_ timestamp */
4980  ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_sockaddr_stringify(addr), (unsigned int) rec_time, randomcalltokendata);
4981  ast_sha1_hash(hash, ast_str_buffer(buf));
4982 
4983  /* compare hashes and then check timestamp delay */
4984  if (strcmp(hash, rec_hash)) {
4985  ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_sockaddr_stringify(addr));
4986  goto reject; /* received hash does not match ours, reject */
4987  } else if ((t < rec_time) || ((t - rec_time) >= max_calltoken_delay)) {
4988  ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_sockaddr_stringify(addr));
4989  goto reject; /* too much delay, reject */
4990  }
4991 
4992  /* at this point the call token is valid, returning 0
4993  * will allow socket_process to continue as usual */
4994  requirecalltoken_mark_auto(ies->username, subclass);
4995  return 0;
4996 
4997  /* ----- Case 3 ----- */
4998  } else { /* calltokens are not supported for this client, how do we respond? */
4999  if (calltoken_required(addr, ies->username, subclass)) {
5000  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"));
5001  goto reject;
5002  }
5003  return 0; /* calltoken is not required for this addr, so permit it. */
5004  }
5005 
5006 reject:
5007  /* received frame has failed calltoken inspection, send apathetic reject messages */
5008  if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
5009  send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5010  } else {
5011  send_apathetic_reply(1, ntohs(fh->scallno), addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
5012  }
5013 
5014  return 1;
5015 }
5016 
5017 /*!
5018  * \brief Parses an IAX dial string into its component parts.
5019  * \param data the string to be parsed
5020  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
5021  * \return nothing
5022  *
5023  * This function parses the string and fills the structure
5024  * with pointers to its component parts. The input string
5025  * will be modified.
5026  *
5027  * \note This function supports both plaintext passwords and RSA
5028  * key names; if the password string is formatted as '[keyname]',
5029  * then the keyname will be placed into the key field, and the
5030  * password field will be set to NULL.
5031  *
5032  * \note The dial string format is:
5033  * [username[:password]@]peer[:port][/exten[@context]][/options]
5034  */
5035 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
5036 {
5037  if (ast_strlen_zero(data))
5038  return;
5039 
5040  pds->peer = strsep(&data, "/");
5041  pds->exten = strsep(&data, "/");
5042  pds->options = data;
5043 
5044  if (pds->exten) {
5045  data = pds->exten;
5046  pds->exten = strsep(&data, "@");
5047  pds->context = data;
5048  }
5049 
5050  if (strchr(pds->peer, '@')) {
5051  data = pds->peer;
5052  pds->username = strsep(&data, "@");
5053  pds->peer = data;
5054  }
5055 
5056  if (pds->username) {
5057  data = pds->username;
5058  pds->username = strsep(&data, ":");
5059  pds->password = data;
5060  }
5061 
5062  data = pds->peer;
5063  pds->peer = strsep(&data, ":");
5064  pds->port = data;
5065 
5066  /*
5067  * Check for a key name wrapped in [] in the password position.
5068  * If found, move it to the key field instead.
5069  */
5070  if (pds->password && (pds->password[0] == '[')) {
5071  pds->key = ast_strip_quoted(pds->password, "[", "]");
5072  pds->password = NULL;
5073  }
5074 }
5075 
5076 static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
5077 {
5078  struct ast_sockaddr addr;
5079  char *l=NULL, *n=NULL, *tmpstr;
5080  struct iax_ie_data ied;
5081  char *defaultrdest = "s";
5082  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5083  struct parsed_dial_string pds;
5084  struct create_addr_info cai;
5085  struct ast_var_t *var;
5086  struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
5087  const char* osp_token_ptr;
5088  unsigned int osp_token_length;
5089  unsigned char osp_block_index;
5090  unsigned int osp_block_length;
5091  unsigned char osp_buffer[256];
5092  char encoded_prefs[32];
5093  iax2_format iax2_tmpfmt;
5094 
5096  ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", ast_channel_name(c));
5097  return -1;
5098  }
5099 
5100  memset(&cai, 0, sizeof(cai));
5103 
5104  memset(&pds, 0, sizeof(pds));
5105  tmpstr = ast_strdupa(dest);
5106  parse_dial_string(tmpstr, &pds);
5107 
5108  if (ast_strlen_zero(pds.peer)) {
5109  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
5110  return -1;
5111  }
5112  if (!pds.exten) {
5113  pds.exten = defaultrdest;
5114  }
5115  if (create_addr(pds.peer, c, &addr, &cai)) {
5116  ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
5117  return -1;
5118  }
5119 
5120  if (ast_test_flag64(&cai, IAX_FORCE_ENCRYPT) ||
5121  ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
5122  if (!cai.encmethods) {
5123  ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
5125  return -1;
5126  }
5127  if (((cai.authmethods & IAX_AUTH_MD5) || (cai.authmethods & IAX_AUTH_PLAINTEXT)) &&
5129  ast_log(LOG_WARNING, "Call terminated. Encryption forced but no secret provided\n");
5130  return -1;
5131  }
5132  }
5133 
5134  if (!pds.username && !ast_strlen_zero(cai.username))
5135  pds.username = cai.username;
5136  if (!pds.password && !ast_strlen_zero(cai.secret))
5137  pds.password = cai.secret;
5138  if (!pds.key && !ast_strlen_zero(cai.outkey))
5139  pds.key = cai.outkey;
5140  if (!pds.context && !ast_strlen_zero(cai.peercontext))
5141  pds.context = cai.peercontext;
5142 
5143  /* Keep track of the context for outgoing calls too */
5145 
5146  if (pds.port) {
5147  int bindport;
5148  if (ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
5149  ast_sockaddr_set_port(&addr, bindport);
5150  }
5151  }
5152 
5155 
5156  /* Now build request */
5157  memset(&ied, 0, sizeof(ied));
5158 
5159  /* On new call, first IE MUST be IAX version of caller */
5162  if (pds.options && strchr(pds.options, 'a')) {
5163  /* Request auto answer */
5165  }
5166 
5167  /* WARNING: this breaks down at 190 bits! */
5168  iax2_codec_pref_convert(&cai.prefs, encoded_prefs, sizeof(encoded_prefs), 1);
5169  iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, encoded_prefs);
5170 
5171  if (l) {
5175  } else if (n) {
5178  } else {
5180  }
5181 
5183  iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, ast_channel_dialed(c)->transit_network_select);
5184 
5185  if (n)
5187  if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
5188  && ast_channel_connected(c)->ani.number.valid
5189  && ast_channel_connected(c)->ani.number.str) {
5190  iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, ast_channel_connected(c)->ani.number.str);
5191  }
5192 
5195  if (!ast_strlen_zero(ast_channel_dialed(c)->number.str)) {
5197  }
5198  if (ast_channel_redirecting(c)->from.number.valid
5199  && !ast_strlen_zero(ast_channel_redirecting(c)->from.number.str)) {
5200  iax_ie_append_str(&ied, IAX_IE_RDNIS, ast_channel_redirecting(c)->from.number.str);
5201  }
5202 
5203  if (pds.context)
5205 
5206  if (pds.username)
5208 
5209  if (cai.encmethods)
5211 
5212  ast_mutex_lock(&iaxsl[callno]);
5213 
5216 
5217  if (pds.username)
5218  ast_string_field_set(iaxs[callno], username, pds.username);
5219 
5220  iaxs[callno]->encmethods = cai.encmethods;
5221 
5222  iaxs[callno]->adsi = cai.adsi;
5223 
5224  ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
5225  ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
5226 
5227  if (pds.key)
5228  ast_string_field_set(iaxs[callno], outkey, pds.key);
5229  if (pds.password)
5230  ast_string_field_set(iaxs[callno], secret, pds.password);
5231 
5233  iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) iax2_tmpfmt);
5234  iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, iax2_tmpfmt);
5235 
5236  iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
5237  iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
5240 
5241  if (iaxs[callno]->maxtime) {
5242  /* Initialize pingtime and auto-congest time */
5243  iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
5244  iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
5245  } else if (autokill) {
5246  iaxs[callno]->pingtime = autokill / 2;
5247  iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
5248  }
5249 
5250  /* Check if there is an OSP token */
5251  osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
5252  if (!ast_strlen_zero(osp_token_ptr)) {
5253  if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
5254  osp_block_index = 0;
5255  while (osp_token_length > 0) {
5256  osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
5257  osp_buffer[0] = osp_block_index;
5258  memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
5259  iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
5260  osp_block_index++;
5261  osp_token_ptr += osp_block_length;
5262  osp_token_length -= osp_block_length;
5263  }
5264  } else
5265  ast_log(LOG_WARNING, "OSP token is too long\n");
5266  } else if (iaxdebug)
5267  ast_debug(1, "OSP token is undefined\n");
5268 
5269  /* send the command using the appropriate socket for this peer */
5270  iaxs[callno]->sockfd = cai.sockfd;
5271 
5272  /* Add remote vars */
5273  if (variablestore) {
5274  AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
5275  ast_debug(1, "Found an IAX variable store on this channel\n");
5276  AST_LIST_LOCK(variablelist);
5277  AST_LIST_TRAVERSE(variablelist, var, entries) {
5278  char tmp[256];
5279  int i;
5280  ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
5281  /* Automatically divide the value up into sized chunks */
5282  for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
5283  snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
5284  iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
5285  }
5286  }
5287  AST_LIST_UNLOCK(variablelist);
5288  }
5289 
5290  /* Transmit the string in a "NEW" request */
5291  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
5292  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
5293 
5294  ast_mutex_unlock(&iaxsl[callno]);
5296 
5297  return 0;
5298 }
5299 
5300 static int iax2_hangup(struct ast_channel *c)
5301 {
5302  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5303  struct iax_ie_data ied;
5304  int alreadygone;
5305  memset(&ied, 0, sizeof(ied));
5306  ast_mutex_lock(&iaxsl[callno]);
5307  if (callno && iaxs[callno]) {
5308  ast_debug(1, "We're hanging up %s now...\n", ast_channel_name(c));
5309  alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
5310  /* Send the hangup unless we have had a transmission error or are already gone */
5312  if (!iaxs[callno]->error && !alreadygone) {
5313  if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
5314  ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
5315  }
5316  if (!iaxs[callno]) {
5317  ast_mutex_unlock(&iaxsl[callno]);
5318  return 0;
5319  }
5320  }
5321  /* Explicitly predestroy it */
5322  iax2_predestroy(callno);
5323  /* If we were already gone to begin with, destroy us now */
5324  if (iaxs[callno] && alreadygone) {
5325  ast_debug(1, "Really destroying %s now...\n", ast_channel_name(c));
5326  iax2_destroy(callno);
5327  } else if (iaxs[callno]) {
5328  if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
5329  ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
5330  iax2_destroy(callno);
5331  }
5332  }
5333  } else if (ast_channel_tech_pvt(c)) {
5334  /* If this call no longer exists, but the channel still
5335  * references it we need to set the channel's tech_pvt to null
5336  * to avoid ast_channel_free() trying to free it.
5337  */
5339  }
5340  ast_mutex_unlock(&iaxsl[callno]);
5341  ast_verb(3, "Hungup '%s'\n", ast_channel_name(c));
5342  return 0;
5343 }
5344 
5345 /*!
5346  * \note expects the pvt to be locked
5347  */
5348 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
5349 {
5350  unsigned short callno = pvt->callno;
5351 
5352  if (!pvt->peercallno) {
5353  /* We don't know the remote side's call number, yet. :( */
5354  int count = 10;
5355  while (count-- && pvt && !pvt->peercallno) {
5356  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
5357  pvt = iaxs[callno];
5358  }
5359  if (!pvt || !pvt->peercallno) {
5360  return -1;
5361  }
5362  }
5363 
5364  return 0;
5365 }
5366 
5367 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
5368 {
5369  struct ast_option_header *h;
5370  int res;
5371 
5372  switch (option) {
5373  case AST_OPTION_TXGAIN:
5374  case AST_OPTION_RXGAIN:
5375  /* these two cannot be sent, because they require a result */
5376  errno = ENOSYS;
5377  return -1;
5378  case AST_OPTION_OPRMODE:
5379  errno = EINVAL;
5380  return -1;
5383  {
5384  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5385  ast_mutex_lock(&iaxsl[callno]);
5386  if ((*(int *) data)) {
5387  ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5388  } else {
5389  ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
5390  }
5391  ast_mutex_unlock(&iaxsl[callno]);
5392  return 0;
5393  }
5394  /* These options are sent to the other side across the network where
5395  * they will be passed to whatever channel is bridged there. Don't
5396  * do anything silly like pass an option that transmits pointers to
5397  * memory on this machine to a remote machine to use */
5399  case AST_OPTION_TDD:
5400  case AST_OPTION_RELAXDTMF:
5401  case AST_OPTION_AUDIO_MODE:
5403  case AST_OPTION_FAX_DETECT:
5404  {
5405  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5406  struct chan_iax2_pvt *pvt;
5407 
5408  ast_mutex_lock(&iaxsl[callno]);
5409  pvt = iaxs[callno];
5410 
5411  if (wait_for_peercallno(pvt)) {
5412  ast_mutex_unlock(&iaxsl[callno]);
5413  return -1;
5414  }
5415 
5416  ast_mutex_unlock(&iaxsl[callno]);
5417 
5418  if (!(h = ast_malloc(datalen + sizeof(*h)))) {
5419  return -1;
5420  }
5421 
5422  h->flag = AST_OPTION_FLAG_REQUEST;
5423  h->option = htons(option);
5424  memcpy(h->data, data, datalen);
5426  AST_CONTROL_OPTION, 0, (unsigned char *) h,
5427  datalen + sizeof(*h), -1);
5428  ast_free(h);
5429  return res;
5430  }
5431  default:
5432  return -1;
5433  }
5434 
5435  /* Just in case someone does a break instead of a return */
5436  return -1;
5437 }
5438 
5439 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
5440 {
5441  switch (option) {
5444  {
5445  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5446  ast_mutex_lock(&iaxsl[callno]);
5447  *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
5448  ast_mutex_unlock(&iaxsl[callno]);
5449  return 0;
5450  }
5451  default:
5452  return -1;
5453  }
5454 }
5455 
5456 static struct ast_frame *iax2_read(struct ast_channel *c)
5457 {
5458  ast_debug(1, "I should never be called!\n");
5459  return &ast_null_frame;
5460 }
5461 
5462 static int iax2_key_rotate(const void *vpvt)
5463 {
5464  int res = 0;
5465  struct chan_iax2_pvt *pvt = (void *) vpvt;
5466  struct MD5Context md5;
5467  char key[17] = "";
5468  struct iax_ie_data ied = {
5469  .pos = 0,
5470  };
5471 
5472  ast_mutex_lock(&iaxsl[pvt->callno]);
5473  pvt->keyrotateid = ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
5474 
5475  snprintf(key, sizeof(key), "%lX", (unsigned long)ast_random());
5476 
5477  MD5Init(&md5);
5478  MD5Update(&md5, (unsigned char *) key, strlen(key));
5479  MD5Final((unsigned char *) key, &md5);
5480 
5481  IAX_DEBUGDIGEST("Sending", key);
5482 
5483  iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
5484 
5485  res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
5486 
5487  build_ecx_key((unsigned char *) key, pvt);
5488 
5489  ast_mutex_unlock(&iaxsl[pvt->callno]);
5490 
5491  return res;
5492 }
5493 
5494 #if defined(IAX2_NATIVE_BRIDGING)
5495 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
5496 {
5497  int res;
5498  struct iax_ie_data ied0;
5499  struct iax_ie_data ied1;
5500  unsigned int transferid = (unsigned int)ast_random();
5501 
5502  if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
5503  ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
5504  ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
5505  ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
5506  return 0;
5507  }
5508 
5509  memset(&ied0, 0, sizeof(ied0));
5510  iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
5511  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
5512  iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
5513 
5514  memset(&ied1, 0, sizeof(ied1));
5515  iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
5516  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
5517  iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
5518 
5519  res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
5520  if (res)
5521  return -1;
5522  res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
5523  if (res)
5524  return -1;
5525  iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5526  iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
5527  return 0;
5528 }
5529 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5530 
5531 #if defined(IAX2_NATIVE_BRIDGING)
5532 static void lock_both(unsigned short callno0, unsigned short callno1)
5533 {
5534  ast_mutex_lock(&iaxsl[callno0]);
5535  while (ast_mutex_trylock(&iaxsl[callno1])) {
5536  DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
5537  }
5538 }
5539 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5540 
5541 #if defined(IAX2_NATIVE_BRIDGING)
5542 static void unlock_both(unsigned short callno0, unsigned short callno1)
5543 {
5544  ast_mutex_unlock(&iaxsl[callno1]);
5545  ast_mutex_unlock(&iaxsl[callno0]);
5546 }
5547 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5548 
5549 #if defined(IAX2_NATIVE_BRIDGING)
5550 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)
5551 {
5552  struct ast_channel *cs[3];
5553  struct ast_channel *who, *other;
5554  int to = -1;
5555  int res = -1;
5556  int transferstarted=0;
5557  struct ast_frame *f;
5558  unsigned short callno0 = PTR_TO_CALLNO(ast_channel_tech_pvt(c0));
5559  unsigned short callno1 = PTR_TO_CALLNO(ast_channel_tech_pvt(c1));
5560  struct timeval waittimer = {0, 0};
5561 
5562  /* We currently do not support native bridging if a timeoutms value has been provided */
5563  if (timeoutms > 0) {
5564  return AST_BRIDGE_FAILED;
5565  }
5566 
5567  timeoutms = -1;
5568 
5569  lock_both(callno0, callno1);
5570  if (!iaxs[callno0] || !iaxs[callno1]) {
5571  unlock_both(callno0, callno1);
5572  return AST_BRIDGE_FAILED;
5573  }
5574  /* Put them in native bridge mode */
5576  iaxs[callno0]->bridgecallno = callno1;
5577  iaxs[callno1]->bridgecallno = callno0;
5578  }
5579  unlock_both(callno0, callno1);
5580 
5581  /* If not, try to bridge until we can execute a transfer, if we can */
5582  cs[0] = c0;
5583  cs[1] = c1;
5584  for (/* ever */;;) {
5585  /* Check in case we got masqueraded into */
5586  if ((ast_channel_tech(c0) != &iax2_tech) || (ast_channel_tech(c1) != &iax2_tech)) {
5587  ast_verb(3, "Can't masquerade, we're different...\n");
5588  /* Remove from native mode */
5589  if (ast_channel_tech(c0) == &iax2_tech) {
5590  ast_mutex_lock(&iaxsl[callno0]);
5591  iaxs[callno0]->bridgecallno = 0;
5592  ast_mutex_unlock(&iaxsl[callno0]);
5593  }
5594  if (ast_channel_tech(c1) == &iax2_tech) {
5595  ast_mutex_lock(&iaxsl[callno1]);
5596  iaxs[callno1]->bridgecallno = 0;
5597  ast_mutex_unlock(&iaxsl[callno1]);
5598  }
5599  return AST_BRIDGE_FAILED_NOWARN;
5600  }
5604 
5605  ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n",
5608 
5609  /* Remove from native mode */
5610  lock_both(callno0, callno1);
5611  if (iaxs[callno0])
5612  iaxs[callno0]->bridgecallno = 0;
5613  if (iaxs[callno1])
5614  iaxs[callno1]->bridgecallno = 0;
5615  unlock_both(callno0, callno1);
5616  return AST_BRIDGE_FAILED_NOWARN;
5617  }
5618  /* check if transferred and if we really want native bridging */
5619  if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
5620  /* Try the transfer */
5621  if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
5622  ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
5623  ast_log(LOG_WARNING, "Unable to start the transfer\n");
5624  transferstarted = 1;
5625  }
5626  if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
5627  /* Call has been transferred. We're no longer involved */
5628  struct timeval now = ast_tvnow();
5629  if (ast_tvzero(waittimer)) {
5630  waittimer = now;
5631  } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
5634  *fo = NULL;
5635  *rc = c0;
5636  res = AST_BRIDGE_COMPLETE;
5637  break;
5638  }
5639  }
5640  to = 1000;
5641  who = ast_waitfor_n(cs, 2, &to);
5642  /* XXX This will need to be updated to calculate
5643  * timeout correctly once timeoutms is allowed to be
5644  * > 0. Right now, this can go badly if the waitfor
5645  * times out in less than a millisecond
5646  */
5647  if (timeoutms > -1) {
5648  timeoutms -= (1000 - to);
5649  if (timeoutms < 0)
5650  timeoutms = 0;
5651  }
5652  if (!who) {
5653  if (!timeoutms) {
5654  res = AST_BRIDGE_RETRY;
5655  break;
5656  }
5657  if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
5658  res = AST_BRIDGE_FAILED;
5659  break;
5660  }
5661  continue;
5662  }
5663  f = ast_read(who);
5664  if (!f) {
5665  *fo = NULL;
5666  *rc = who;
5667  res = AST_BRIDGE_COMPLETE;
5668  break;
5669  }
5670  other = (who == c0) ? c1 : c0; /* the 'other' channel */
5671  if (f->frametype == AST_FRAME_CONTROL) {
5672  switch (f->subclass.integer) {
5673  case AST_CONTROL_VIDUPDATE:
5674  case AST_CONTROL_SRCUPDATE:
5675  case AST_CONTROL_SRCCHANGE:
5677  ast_write(other, f);
5678  break;
5681  break;
5682  default:
5683  *fo = f;
5684  *rc = who;
5685  res = AST_BRIDGE_COMPLETE;
5686  break;
5687  }
5688  if (res == AST_BRIDGE_COMPLETE) {
5689  break;
5690  }
5691  } else if (f->frametype == AST_FRAME_VOICE
5692  || f->frametype == AST_FRAME_TEXT
5693  || f->frametype == AST_FRAME_VIDEO
5694  || f->frametype == AST_FRAME_IMAGE) {
5695  ast_write(other, f);
5696  } else if (f->frametype == AST_FRAME_DTMF) {
5697  /* monitored dtmf take out of the bridge.
5698  * check if we monitor the specific source.
5699  */
5700  int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
5701 
5702  if (flags & monitored_source) {
5703  *rc = who;
5704  *fo = f;
5705  res = AST_BRIDGE_COMPLETE;
5706  /* Remove from native mode */
5707  break;
5708  }
5709  ast_write(other, f);
5710  }
5711  ast_frfree(f);
5712  /* Swap who gets priority */
5713  cs[2] = cs[0];
5714  cs[0] = cs[1];
5715  cs[1] = cs[2];
5716  }
5717  lock_both(callno0, callno1);
5718  if(iaxs[callno0])
5719  iaxs[callno0]->bridgecallno = 0;
5720  if(iaxs[callno1])
5721  iaxs[callno1]->bridgecallno = 0;
5722  unlock_both(callno0, callno1);
5723  return res;
5724 }
5725 #endif /* defined(IAX2_NATIVE_BRIDGING) */
5726 
5727 static int iax2_answer(struct ast_channel *c)
5728 {
5729  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5730  ast_debug(1, "Answering IAX2 call\n");
5731  return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
5732 }
5733 
5734 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
5735 {
5736  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5737  struct chan_iax2_pvt *pvt;
5738  int res = 0;
5739 
5740  if (iaxdebug)
5741  ast_debug(1, "Indicating condition %d\n", condition);
5742 
5743  ast_mutex_lock(&iaxsl[callno]);
5744  pvt = iaxs[callno];
5745 
5746  if (wait_for_peercallno(pvt)) {
5747  res = -1;
5748  goto done;
5749  }
5750 
5751  switch (condition) {
5752  case AST_CONTROL_HOLD:
5753  if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5754  ast_moh_start(c, data, pvt->mohinterpret);
5755  goto done;
5756  }
5757  break;
5758  case AST_CONTROL_UNHOLD:
5759  if (strcasecmp(pvt->mohinterpret, "passthrough")) {
5760  ast_moh_stop(c);
5761  goto done;
5762  }
5763  break;
5767  /* We are not configured to allow sending these updates. */
5768  ast_debug(2, "Callno %d: Config blocked sending control frame %d.\n",
5769  callno, condition);
5770  goto done;
5771  }
5772  break;
5775  res = -1;
5776  goto done;
5777  }
5778 
5779  res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
5780 
5781 done:
5782  ast_mutex_unlock(&iaxsl[callno]);
5783 
5784  return res;
5785 }
5786 
5787 static int iax2_transfer(struct ast_channel *c, const char *dest)
5788 {
5789  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
5790  struct iax_ie_data ied = { "", };
5791  char tmp[256], *context;
5793  ast_copy_string(tmp, dest, sizeof(tmp));
5794  context = strchr(tmp, '@');
5795  if (context) {
5796  *context = '\0';
5797  context++;
5798  }
5800  if (context)
5801  iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
5802  ast_debug(1, "Transferring '%s' to '%s'\n", ast_channel_name(c), dest);
5803  ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
5804  return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
5805 }
5806 
5807 static int iax2_getpeertrunk(struct ast_sockaddr addr)
5808 {
5809  struct iax2_peer *peer;
5810  int res = 0;
5811  struct ao2_iterator i;
5812 
5813  i = ao2_iterator_init(peers, 0);
5814  while ((peer = ao2_iterator_next(&i))) {
5815 
5816  if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
5817  res = ast_test_flag64(peer, IAX_TRUNK);
5818  peer_unref(peer);
5819  break;
5820  }
5821  peer_unref(peer);
5822  }
5824 
5825  return res;
5826 }
5827 
5828 /*! \brief Create new call, interface with the PBX core */
5829 static struct ast_channel *ast_iax2_new(int callno, int state, iax2_format capability,
5830  struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids,
5831  const struct ast_channel *requestor, unsigned int cachable)
5832 {
5833  struct ast_channel *tmp = NULL;
5834  struct chan_iax2_pvt *i;
5835  struct iax2_peer *peer;
5836  struct ast_variable *v = NULL;
5837  struct ast_format_cap *native;
5838  struct ast_format *tmpfmt;
5839  ast_callid callid;
5840  char *peer_name = NULL;
5841 
5842  if (!(i = iaxs[callno])) {
5843  ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
5844  return NULL;
5845  }
5846 
5847  if (!capability) {
5848  ast_log(LOG_WARNING, "No formats specified for call to: IAX2/%s-%d\n",
5849  i->host, i->callno);
5850  return NULL;
5851  }
5853  if (!native) {
5854  return NULL;
5855  }
5856  if (iax2_codec_pref_best_bitfield2cap(capability, prefs, native)
5857  || !ast_format_cap_count(native)) {
5858  ast_log(LOG_WARNING, "No requested formats available for call to: IAX2/%s-%d\n",
5859  i->host, i->callno);
5860  ao2_ref(native, -1);
5861  return NULL;
5862  }
5863 
5864  if (!ast_strlen_zero(i->peer)) {
5865  peer_name = ast_strdupa(i->peer);
5866  } else if (!ast_strlen_zero(i->host)) {
5867  peer_name = ast_strdupa(i->host);
5868  }
5869 
5870  /* Don't hold call lock while making a channel or looking up a peer */
5871  ast_mutex_unlock(&iaxsl[callno]);
5872 
5873  if (!ast_strlen_zero(peer_name)) {
5874  peer = find_peer(peer_name, 1);
5875  if (peer && peer->endpoint) {
5876  tmp = ast_channel_alloc_with_endpoint(1, state, i->cid_num, i->cid_name,
5877  i->accountcode, i->exten, i->context, assignedids, requestor,
5878  i->amaflags, peer->endpoint, "IAX2/%s-%d", i->host, i->callno);
5879  }
5880  ao2_cleanup(peer);
5881  }
5882 
5883  if (!tmp) {
5884  tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode,
5885  i->exten, i->context, assignedids, requestor, i->amaflags, "IAX2/%s-%d",
5886  i->host, i->callno);
5887  }
5888 
5889  ast_mutex_lock(&iaxsl[callno]);
5890  if (i != iaxs[callno]) {
5891  if (tmp) {
5892  /* unlock and relock iaxsl[callno] to preserve locking order */
5893  ast_mutex_unlock(&iaxsl[callno]);
5894  ast_channel_unlock(tmp);
5895  tmp = ast_channel_release(tmp);
5896  ast_mutex_lock(&iaxsl[callno]);
5897  }
5898  ao2_ref(native, -1);
5899  return NULL;
5900  }
5901  if (!tmp) {
5902  ao2_ref(native, -1);
5903  return NULL;
5904  }
5905 
5907 
5908  if ((callid = iaxs[callno]->callid)) {
5909  ast_channel_callid_set(tmp, callid);
5910  }
5911 
5912  ast_channel_tech_set(tmp, &iax2_tech);
5913 
5914  /* We can support any format by default, until we get restricted */
5915  ast_channel_nativeformats_set(tmp, native);
5916  tmpfmt = ast_format_cap_get_format(native, 0);
5917 
5918  ast_channel_set_readformat(tmp, tmpfmt);
5919  ast_channel_set_rawreadformat(tmp, tmpfmt);
5920  ast_channel_set_writeformat(tmp, tmpfmt);
5921  ast_channel_set_rawwriteformat(tmp, tmpfmt);
5922 
5923  ao2_ref(tmpfmt, -1);
5924  ao2_ref(native, -1);
5925 
5927 
5928  if (!ast_strlen_zero(i->parkinglot))
5929  ast_channel_parkinglot_set(tmp, i->parkinglot);
5930  /* Don't use ast_set_callerid() here because it will
5931  * generate a NewCallerID event before the NewChannel event */
5932  if (!ast_strlen_zero(i->ani)) {
5933  ast_channel_caller(tmp)->ani.number.valid = 1;
5935  } else if (!ast_strlen_zero(i->cid_num)) {
5936  ast_channel_caller(tmp)->ani.number.valid = 1;
5938  }
5940  if (!ast_strlen_zero(i->rdnis)) {
5943  }
5948  if (!ast_strlen_zero(i->language))
5949  ast_channel_language_set(tmp, i->language);
5950  if (!ast_strlen_zero(i->accountcode))
5951  ast_channel_accountcode_set(tmp, i->accountcode);
5952  if (i->amaflags)
5955  ast_channel_exten_set(tmp, i->exten);
5956  if (i->adsi)
5958  else
5960  i->owner = tmp;
5961  i->capability = capability;
5962 
5963  if (!cachable) {
5965  }
5966 
5967  /* Set inherited variables */
5968  if (i->vars) {
5969  for (v = i->vars ; v ; v = v->next)
5970  pbx_builtin_setvar_helper(tmp, v->name, v->value);
5971  }
5972  if (i->iaxvars) {
5973  struct ast_datastore *variablestore;
5974  struct ast_variable *var, *prev = NULL;
5975  AST_LIST_HEAD(, ast_var_t) *varlist;
5976  ast_debug(1, "Loading up the channel with IAXVARs\n");
5977  varlist = ast_calloc(1, sizeof(*varlist));
5978  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
5979  if (variablestore && varlist) {
5980  variablestore->data = varlist;
5981  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
5982  AST_LIST_HEAD_INIT(varlist);
5983  for (var = i->iaxvars; var; var = var->next) {
5984  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
5985  if (prev)
5986  ast_free(prev);
5987  prev = var;
5988  if (!newvar) {
5989  /* Don't abort list traversal, as this would leave i->iaxvars in an inconsistent state. */
5990  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
5991  } else {
5992  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
5993  }
5994  }
5995  if (prev)
5996  ast_free(prev);
5997  i->iaxvars = NULL;
5998  ast_channel_datastore_add(i->owner, variablestore);
5999  } else {
6000  if (variablestore) {
6001  ast_datastore_free(variablestore);
6002  }
6003  if (varlist) {
6004  ast_free(varlist);
6005  }
6006  }
6007  }
6008 
6010  ast_channel_unlock(tmp);
6011 
6012  if (state != AST_STATE_DOWN) {
6013  if (ast_pbx_start(tmp)) {
6014  ast_log(LOG_WARNING, "Unable to start PBX on %s\n", ast_channel_name(tmp));
6015  /* unlock and relock iaxsl[callno] to preserve locking order */
6016  ast_mutex_unlock(&iaxsl[callno]);
6017  ast_hangup(tmp);
6018  ast_mutex_lock(&iaxsl[callno]);
6019  return NULL;
6020  }
6021  }
6022 
6024  return tmp;
6025 }
6026 
6027 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
6028 {
6029  unsigned long int mssincetx; /* unsigned to handle overflows */
6030  long int ms, pred;
6031 
6032  tpeer->trunkact = *now;
6033  mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
6034  if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
6035  /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
6036  tpeer->txtrunktime = *now;
6037  tpeer->lastsent = 999999;
6038  }
6039  /* Update last transmit time now */
6040  tpeer->lasttxtime = *now;
6041 
6042  /* Calculate ms offset */
6043  ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
6044  /* Predict from last value */
6045  pred = tpeer->lastsent + sampms;
6046  if (labs(ms - pred) < MAX_TIMESTAMP_SKEW)
6047  ms = pred;
6048 
6049  /* We never send the same timestamp twice, so fudge a little if we must */
6050  if (ms == tpeer->lastsent)
6051  ms = tpeer->lastsent + 1;
6052  tpeer->lastsent = ms;
6053  return ms;
6054 }
6055 
6056 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
6057 {
6058  long ms; /* NOT unsigned */
6059  if (ast_tvzero(iaxs[callno]->rxcore)) {
6060  /* Initialize rxcore time if appropriate */
6061  iaxs[callno]->rxcore = ast_tvnow();
6062  /* Round to nearest 20ms so traces look pretty */
6063  iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
6064  }
6065  /* Calculate difference between trunk and channel */
6066  ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
6067  /* Return as the sum of trunk time and the difference between trunk and real time */
6068  return ms + ts;
6069 }
6070 
6071 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
6072 {
6073  int ms;
6074  int voice = 0;
6075  int genuine = 0;
6076  int adjust;
6077  int rate = 0;
6078  struct timeval *delivery = NULL;
6079 
6080 
6081  /* What sort of frame do we have?: voice is self-explanatory
6082  "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
6083  non-genuine frames are CONTROL frames [ringing etc], DTMF
6084  The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
6085  the others need a timestamp slaved to the voice frames so that they go in sequence
6086  */
6087  if (f->frametype == AST_FRAME_VOICE) {
6088  voice = 1;
6089  rate = ast_format_get_sample_rate(f->subclass.format) / 1000;
6090  delivery = &f->delivery;
6091  } else if (f->frametype == AST_FRAME_IAX) {
6092  genuine = 1;
6093  } else if (f->frametype == AST_FRAME_CNG) {
6094  p->notsilenttx = 0;
6095  }
6096 
6097  if (ast_tvzero(p->offset)) {
6098  p->offset = ast_tvnow();
6099  /* Round to nearest 20ms for nice looking traces */
6100  p->offset.tv_usec -= p->offset.tv_usec % 20000;
6101  }
6102  /* If the timestamp is specified, just send it as is */
6103  if (ts)
6104  return ts;
6105  /* If we have a time that the frame arrived, always use it to make our timestamp */
6106  if (delivery && !ast_tvzero(*delivery)) {
6107  ms = ast_tvdiff_ms(*delivery, p->offset);
6108  if (ms < 0) {
6109  ms = 0;
6110  }
6111  if (iaxdebug)
6112  ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
6113  } else {
6114  ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
6115  if (ms < 0)
6116  ms = 0;
6117  if (voice) {
6118  /* On a voice frame, use predicted values if appropriate */
6119  adjust = (ms - p->nextpred);
6120  if (p->notsilenttx && abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6121  /* Adjust our txcore, keeping voice and non-voice synchronized */
6122  /* AN EXPLANATION:
6123  When we send voice, we usually send "calculated" timestamps worked out
6124  on the basis of the number of samples sent. When we send other frames,
6125  we usually send timestamps worked out from the real clock.
6126  The problem is that they can tend to drift out of step because the
6127  source channel's clock and our clock may not be exactly at the same rate.
6128  We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
6129  for this call. Moving it adjusts timestamps for non-voice frames.
6130  We make the adjustment in the style of a moving average. Each time we
6131  adjust p->offset by 10% of the difference between our clock-derived
6132  timestamp and the predicted timestamp. That's why you see "10000"
6133  below even though IAX2 timestamps are in milliseconds.
6134  The use of a moving average avoids offset moving too radically.
6135  Generally, "adjust" roams back and forth around 0, with offset hardly
6136  changing at all. But if a consistent different starts to develop it
6137  will be eliminated over the course of 10 frames (200-300msecs)
6138  */
6139  if (adjust < 0)
6140  p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
6141  else if (adjust > 0)
6142  p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
6143 
6144  if (!p->nextpred) {
6145  p->nextpred = ms; /*f->samples / rate;*/
6146  if (p->nextpred <= p->lastsent)
6147  p->nextpred = p->lastsent + 3;
6148  }
6149  ms = p->nextpred;
6150  } else {
6151  /* in this case, just use the actual
6152  * time, since we're either way off
6153  * (shouldn't happen), or we're ending a
6154  * silent period -- and seed the next
6155  * predicted time. Also, round ms to the
6156  * next multiple of frame size (so our
6157  * silent periods are multiples of
6158  * frame size too) */
6159 
6160  if (iaxdebug && abs(adjust) > MAX_TIMESTAMP_SKEW )
6161  ast_debug(1, "predicted timestamp skew (%d) > max (%d), using real ts instead.\n",
6162  abs(adjust), MAX_TIMESTAMP_SKEW);
6163 
6164  if (f->samples >= rate) /* check to make sure we don't core dump */
6165  {
6166  int diff = ms % (f->samples / rate);
6167  if (diff)
6168  ms += f->samples/rate - diff;
6169  }
6170 
6171  p->nextpred = ms;
6172  p->notsilenttx = 1;
6173  }
6174  } else if ( f->frametype == AST_FRAME_VIDEO ) {
6175  /*
6176  * IAX2 draft 03 says that timestamps MUST be in order.
6177  * It does not say anything about several frames having the same timestamp
6178  * When transporting video, we can have a frame that spans multiple iax packets
6179  * (so called slices), so it would make sense to use the same timestamp for all of
6180  * them
6181  * We do want to make sure that frames don't go backwards though
6182  */
6183  if ( (unsigned int)ms < p->lastsent )
6184  ms = p->lastsent;
6185  } else {
6186  /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
6187  it's a genuine frame */
6188  adjust = (ms - p->lastsent);
6189  if (genuine) {
6190  /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
6191  if (ms <= p->lastsent)
6192  ms = p->lastsent + 3;
6193  } else if (abs(adjust) <= MAX_TIMESTAMP_SKEW) {
6194  /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
6195  ms = p->lastsent + 3;
6196  }
6197  }
6198  }
6199  p->lastsent = ms;
6200  if (voice) {
6201  p->nextpred = p->nextpred + f->samples / rate;
6202  }
6203  return ms;
6204 }
6205 
6206 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
6207 {
6208  /* Returns where in "receive time" we are. That is, how many ms
6209  since we received (or would have received) the frame with timestamp 0 */
6210  int ms;
6211 #ifdef IAXTESTS
6212  int jit;
6213 #endif /* IAXTESTS */
6214  /* Setup rxcore if necessary */
6215  if (ast_tvzero(p->rxcore)) {
6216  p->rxcore = ast_tvnow();
6217  if (iaxdebug)
6218  ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %ums\n",
6219  p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
6220  p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
6221 #if 1
6222  if (iaxdebug)
6223  ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
6224  p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
6225 #endif
6226  }
6227 
6228  ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
6229 #ifdef IAXTESTS
6230  if (test_jit) {
6231  if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
6232  jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
6233  if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
6234  jit = -jit;
6235  ms += jit;
6236  }
6237  }
6238  if (test_late) {
6239  ms += test_late;
6240  test_late = 0;
6241  }
6242 #endif /* IAXTESTS */
6243  return ms;
6244 }
6245 
6246 static struct iax2_trunk_peer *find_tpeer(struct ast_sockaddr *addr, int fd)
6247 {
6248  struct iax2_trunk_peer *tpeer = NULL;
6249 
6250  /* Finds and locks trunk peer */
6252 
6253  AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
6254  if (!ast_sockaddr_cmp(&tpeer->addr, addr)) {
6255  ast_mutex_lock(&tpeer->lock);
6256  break;
6257  }
6258  }
6259 
6260  if (!tpeer) {
6261  if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
6262  ast_mutex_init(&tpeer->lock);
6263  tpeer->lastsent = 9999;
6264  ast_sockaddr_copy(&tpeer->addr, addr);
6265  tpeer->trunkact = ast_tvnow();
6266  ast_mutex_lock(&tpeer->lock);
6267  tpeer->sockfd = fd;
6268 
6269 #ifdef SO_NO_CHECK
6270  setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
6271 #endif
6272  ast_debug(1, "Created trunk peer for '%s'\n", ast_sockaddr_stringify(&tpeer->addr));
6273  AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
6274  }
6275  }
6276 
6278 
6279  return tpeer;
6280 }
6281 
6282 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
6283 {
6284  struct ast_frame *f;
6285  struct iax2_trunk_peer *tpeer;
6286  void *tmp, *ptr;
6287  struct timeval now;
6288  struct ast_iax2_meta_trunk_entry *met;
6289  struct ast_iax2_meta_trunk_mini *mtm;
6290 
6291  f = &fr->af;
6292  tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
6293  if (tpeer) {
6294 
6295  if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
6296  /* Need to reallocate space */
6297  if (tpeer->trunkdataalloc < trunkmaxsize) {
6298  if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
6299  ast_mutex_unlock(&tpeer->lock);
6300  return -1;
6301  }
6302 
6304  tpeer->trunkdata = tmp;
6305  ast_debug(1, "Expanded trunk '%s' to %u bytes\n", ast_sockaddr_stringify(&tpeer->addr), tpeer->trunkdataalloc);
6306  } else {
6307  ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s\n", ast_sockaddr_stringify(&tpeer->addr));
6308  ast_mutex_unlock(&tpeer->lock);
6309  return -1;
6310  }
6311  }
6312 
6313  /* Append to meta frame */
6314  ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
6315  if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
6316  mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6317  mtm->len = htons(f->datalen);
6318  mtm->mini.callno = htons(pvt->callno);
6319  mtm->mini.ts = htons(0xffff & fr->ts);
6320  ptr += sizeof(struct ast_iax2_meta_trunk_mini);
6321  tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
6322  } else {
6323  met = (struct ast_iax2_meta_trunk_entry *)ptr;
6324  /* Store call number and length in meta header */
6325  met->callno = htons(pvt->callno);
6326  met->len = htons(f->datalen);
6327  /* Advance pointers/decrease length past trunk entry header */
6328  ptr += sizeof(struct ast_iax2_meta_trunk_entry);
6329  tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
6330  }
6331  /* Copy actual trunk data */
6332  memcpy(ptr, f->data.ptr, f->datalen);
6333  tpeer->trunkdatalen += f->datalen;
6334 
6335  tpeer->calls++;
6336 
6337  /* track the largest mtu we actually have sent */
6338  if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
6339  trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
6340 
6341  /* if we have enough for a full MTU, ship it now without waiting */
6342  if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
6343  now = ast_tvnow();
6344  send_trunk(tpeer, &now);
6345  trunk_untimed ++;
6346  }
6347 
6348  ast_mutex_unlock(&tpeer->lock);
6349  }
6350  return 0;
6351 }
6352 
6353 /* IAX2 encryption requires 16 to 32 bytes of random padding to be present
6354  * before the encryption data. This function randomizes that data. */
6355 static void build_rand_pad(unsigned char *buf, ssize_t len)
6356 {
6357  long tmp;
6358  for (tmp = ast_random(); len > 0; tmp = ast_random()) {
6359  memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
6360  buf += sizeof(tmp);
6361  len -= sizeof(tmp);
6362  }
6363 }
6364 
6365 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6366 {
6367  build_ecx_key(digest, pvt);
6368  ast_aes_set_decrypt_key(digest, &pvt->dcx);
6369 }
6370 
6371 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
6372 {
6373  /* it is required to hold the corresponding decrypt key to our encrypt key
6374  * in the pvt struct because queued frames occasionally need to be decrypted and
6375  * re-encrypted when updated for a retransmission */
6376  build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
6377  ast_aes_set_encrypt_key(digest, &pvt->ecx);
6378  ast_aes_set_decrypt_key(digest, &pvt->mydcx);
6379 }
6380 
6381 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
6382 {
6383 #if 0
6384  /* Debug with "fake encryption" */
6385  int x;
6386  if (len % 16)
6387  ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6388  for (x=0;x<len;x++)
6389  dst[x] = src[x] ^ 0xff;
6390 #else
6391  unsigned char lastblock[16] = { 0 };
6392  int x;
6393  while(len > 0) {
6394  ast_aes_decrypt(src, dst, dcx);
6395  for (x=0;x<16;x++)
6396  dst[x] ^= lastblock[x];
6397  memcpy(lastblock, src, sizeof(lastblock));
6398  dst += 16;
6399  src += 16;
6400  len -= 16;
6401  }
6402 #endif
6403 }
6404 
6405 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
6406 {
6407 #if 0
6408  /* Debug with "fake encryption" */
6409  int x;
6410  if (len % 16)
6411  ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
6412  for (x=0;x<len;x++)
6413  dst[x] = src[x] ^ 0xff;
6414 #else
6415  unsigned char curblock[16] = { 0 };
6416  int x;
6417  while(len > 0) {
6418  for (x=0;x<16;x++)
6419  curblock[x] ^= src[x];
6420  ast_aes_encrypt(curblock, dst, ecx);
6421  memcpy(curblock, dst, sizeof(curblock));
6422  dst += 16;
6423  src += 16;
6424  len -= 16;
6425  }
6426 #endif
6427 }
6428 
6429 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6430 {
6431  int padding;
6432  unsigned char *workspace;
6433 
6434  workspace = ast_alloca(*datalen);
6435  memset(f, 0, sizeof(*f));
6436  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6437  struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6438  if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
6439  return -1;
6440  /* Decrypt */
6441  memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
6442 
6443  padding = 16 + (workspace[15] & 0x0f);
6444  if (iaxdebug)
6445  ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02hhx)\n", *datalen, padding, workspace[15]);
6446  if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
6447  return -1;
6448 
6449  *datalen -= padding;
6450  memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6451  f->frametype = fh->type;
6452  if (f->frametype == AST_FRAME_VIDEO) {
6453  f->subclass.format = ast_format_compatibility_bitfield2format(uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1));
6454  } else if (f->frametype == AST_FRAME_VOICE) {
6456  } else {
6458  }
6459  } else {
6460  struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6461  if (iaxdebug)
6462  ast_debug(1, "Decoding mini with length %d\n", *datalen);
6463  if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
6464  return -1;
6465  /* Decrypt */
6466  memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
6467  padding = 16 + (workspace[15] & 0x0f);
6468  if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
6469  return -1;
6470  *datalen -= padding;
6471  memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6472  }
6473  return 0;
6474 }
6475 
6476 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
6477 {
6478  int padding;
6479  unsigned char *workspace;
6480  workspace = ast_alloca(*datalen + 32);
6481  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6482  struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
6483  if (iaxdebug)
6484  ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
6485  padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
6486  padding = 16 + (padding & 0xf);
6487  memcpy(workspace, poo, padding);
6488  memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
6489  workspace[15] &= 0xf0;
6490  workspace[15] |= (padding & 0xf);
6491  if (iaxdebug)
6492  ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02hhx)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
6493  *datalen += padding;
6494  memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
6495  if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
6496  memcpy(poo, workspace + *datalen - 32, 32);
6497  } else {
6498  struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
6499  if (iaxdebug)
6500  ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
6501  padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
6502  padding = 16 + (padding & 0xf);
6503  memcpy(workspace, poo, padding);
6504  memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
6505  workspace[15] &= 0xf0;
6506  workspace[15] |= (padding & 0x0f);
6507  *datalen += padding;
6508  memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
6509  if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
6510  memcpy(poo, workspace + *datalen - 32, 32);
6511  }
6512  return 0;
6513 }
6514 
6515 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
6516 {
6517  int res=-1;
6518  if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
6519  /* Search for possible keys, given secrets */
6520  struct MD5Context md5;
6521  unsigned char digest[16];
6522  char *tmppw, *stringp;
6523 
6524  tmppw = ast_strdupa(iaxs[callno]->secret);
6525  stringp = tmppw;
6526  while ((tmppw = strsep(&stringp, ";"))) {
6527  MD5Init(&md5);
6528  MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6529  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6530  MD5Final(digest, &md5);
6531  build_encryption_keys(digest, iaxs[callno]);
6532  res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6533  if (!res) {
6534  ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
6535  break;
6536  }
6537  }
6538  } else
6539  res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
6540  return res;
6541 }
6542 
6543 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
6544 {
6545  /* Queue a packet for delivery on a given private structure. Use "ts" for
6546  timestamp, or calculate if ts is 0. Send immediately without retransmission
6547  or delayed, with retransmission */
6548  struct ast_iax2_full_hdr *fh;
6549  struct ast_iax2_mini_hdr *mh;
6550  struct ast_iax2_video_hdr *vh;
6551  struct {
6552  struct iax_frame fr2;
6553  unsigned char buffer[4096];
6554  } frb;
6555  struct iax_frame *fr;
6556  int res;
6557  int sendmini=0;
6558  unsigned int lastsent;
6559  unsigned int fts;
6560 
6561  frb.fr2.afdatalen = sizeof(frb.buffer);
6562 
6563  if (!pvt) {
6564  ast_log(LOG_WARNING, "No private structure for packet?\n");
6565  return -1;
6566  }
6567 
6568  lastsent = pvt->lastsent;
6569 
6570  /* Calculate actual timestamp */
6571  fts = calc_timestamp(pvt, ts, f);
6572 
6573  /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
6574  * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
6575  * increment the "predicted timestamps" for voice, if we're predicting */
6576  if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
6577  return 0;
6578 #if 0
6580  "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
6581  *("=!" + (f->frametype == AST_FRAME_VOICE)),
6582  IAX_CALLENCRYPTED(pvt) ? "" : "not ",
6583  pvt->keyrotateid != -1 ? "" : "no "
6584  );
6585 #endif
6586  if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
6587  iax2_key_rotate(pvt);
6588  }
6589 
6590  if ((ast_test_flag64(pvt, IAX_TRUNK) ||
6591  (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
6592  ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
6593  /* High two bytes are the same on timestamp, or sending on a trunk */ &&
6594  (f->frametype == AST_FRAME_VOICE)
6595  /* is a voice frame */ &&
6598  /* is the same type */ ) {
6599  /* Force immediate rather than delayed transmission */
6600  now = 1;
6601  /* Mark that mini-style frame is appropriate */
6602  sendmini = 1;
6603  }
6604  if ( f->frametype == AST_FRAME_VIDEO ) {
6605  /*
6606  * If the lower 15 bits of the timestamp roll over, or if
6607  * the video format changed then send a full frame.
6608  * Otherwise send a mini video frame
6609  */
6610  if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
6613  ) {
6614  now = 1;
6615  sendmini = 1;
6616  } else {
6617  now = 0;
6618  sendmini = 0;
6619  }
6620  pvt->lastvsent = fts;
6621  }
6622  if (f->frametype == AST_FRAME_IAX) {
6623  /* 0x8000 marks this message as TX:, this bit will be stripped later */
6625  if (!pvt->first_iax_message) {
6626  pvt->first_iax_message = pvt->last_iax_message;
6627  }
6628  }
6629  /* Allocate an iax_frame */
6630  if (now) {
6631  fr = &frb.fr2;
6632  } else
6634  if (!fr) {
6635  ast_log(LOG_WARNING, "Out of memory\n");
6636  return -1;
6637  }
6638  /* Copy our prospective frame into our immediate or retransmitted wrapper */
6639  iax_frame_wrap(fr, f);
6640 
6641  fr->ts = fts;
6642  fr->callno = pvt->callno;
6643  fr->transfer = transfer;
6644  fr->final = final;
6645  fr->encmethods = 0;
6646  if (!sendmini) {
6647  /* We need a full frame */
6648  if (seqno > -1)
6649  fr->oseqno = seqno;
6650  else
6651  fr->oseqno = pvt->oseqno++;
6652  fr->iseqno = pvt->iseqno;
6653  fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
6654  fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
6655  fh->ts = htonl(fr->ts);
6656  fh->oseqno = fr->oseqno;
6657  if (transfer) {
6658  fh->iseqno = 0;
6659  } else
6660  fh->iseqno = fr->iseqno;
6661  /* Keep track of the last thing we've acknowledged */
6662  if (!transfer)
6663  pvt->aseqno = fr->iseqno;
6664  fh->type = fr->af.frametype & 0xFF;
6665 
6666  if (fr->af.frametype == AST_FRAME_VIDEO) {
6668  tmpfmt |= fr->af.subclass.frame_ending ? 0x1LL : 0;
6669  fh->csub = compress_subclass(tmpfmt | ((tmpfmt & 0x1LL) << 6));
6670  } else if (fr->af.frametype == AST_FRAME_VOICE) {
6672  } else {
6674  }
6675 
6676  if (transfer) {
6677  fr->dcallno = pvt->transfercallno;
6678  } else
6679  fr->dcallno = pvt->peercallno;
6680  fh->dcallno = htons(fr->dcallno);
6681  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
6682  fr->data = fh;
6683  fr->retries = 0;
6684  /* Retry after 2x the ping time has passed */
6685  fr->retrytime = pvt->pingtime * 2;
6686  if (fr->retrytime < MIN_RETRY_TIME)
6687  fr->retrytime = MIN_RETRY_TIME;
6688  if (fr->retrytime > MAX_RETRY_TIME)
6689  fr->retrytime = MAX_RETRY_TIME;
6690  /* Acks' don't get retried */
6691  if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
6692  fr->retries = -1;
6693  else if (f->frametype == AST_FRAME_VOICE)
6695  else if (f->frametype == AST_FRAME_VIDEO)
6697  if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6698  if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6699  if (fr->transfer)
6700  iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6701  else
6702  iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
6703  encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
6704  fr->encmethods = pvt->encmethods;
6705  fr->ecx = pvt->ecx;
6706  fr->mydcx = pvt->mydcx;
6707  memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
6708  } else
6709  ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6710  }
6711 
6712  if (now) {
6713  res = send_packet(fr);
6714  } else
6715  res = iax2_transmit(fr);
6716  } else {
6717  if (ast_test_flag64(pvt, IAX_TRUNK)) {
6718  iax2_trunk_queue(pvt, fr);
6719  res = 0;
6720  } else if (fr->af.frametype == AST_FRAME_VIDEO) {
6721  /* Video frame have no sequence number */
6722  fr->oseqno = -1;
6723  fr->iseqno = -1;
6724  vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
6725  vh->zeros = 0;
6726  vh->callno = htons(0x8000 | fr->callno);
6727  vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.frame_ending ? 0x8000 : 0));
6728  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
6729  fr->data = vh;
6730  fr->retries = -1;
6731  res = send_packet(fr);
6732  } else {
6733  /* Mini-frames have no sequence number */
6734  fr->oseqno = -1;
6735  fr->iseqno = -1;
6736  /* Mini frame will do */
6737  mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
6738  mh->callno = htons(fr->callno);
6739  mh->ts = htons(fr->ts & 0xFFFF);
6740  fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
6741  fr->data = mh;
6742  fr->retries = -1;
6743  if (pvt->transferring == TRANSFER_MEDIAPASS)
6744  fr->transfer = 1;
6745  if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
6746  if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
6747  encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
6748  } else
6749  ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
6750  }
6751  res = send_packet(fr);
6752  }
6753  }
6754  return res;
6755 }
6756 
6757 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
6758 {
6759  regex_t regexbuf;
6760  int havepattern = 0;
6761 
6762 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
6763 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
6764 
6765  struct iax2_user *user = NULL;
6766  char auth[90];
6767  char *pstr = "";
6768  struct ao2_iterator i;
6769 
6770  switch (cmd) {
6771  case CLI_INIT:
6772  e->command = "iax2 show users [like]";
6773  e->usage =
6774  "Usage: iax2 show users [like <pattern>]\n"
6775  " Lists all known IAX2 users.\n"
6776  " Optional regular expression pattern is used to filter the user list.\n";
6777  return NULL;
6778  case CLI_GENERATE:
6779  return NULL;
6780  }
6781 
6782  switch (a->argc) {
6783  case 5:
6784  if (!strcasecmp(a->argv[3], "like")) {
6785  if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
6786  return CLI_SHOWUSAGE;
6787  havepattern = 1;
6788  } else
6789  return CLI_SHOWUSAGE;
6790  case 3:
6791  break;
6792  default:
6793  return CLI_SHOWUSAGE;
6794  }
6795 
6796  ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
6797  i = ao2_iterator_init(users, 0);
6798  for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
6799  if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
6800  continue;
6801 
6802  if (!ast_strlen_zero(user->secret)) {
6803  ast_copy_string(auth,user->secret, sizeof(auth));
6804  } else if (!ast_strlen_zero(user->inkeys)) {
6805  snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
6806  } else
6807  ast_copy_string(auth, "-no secret-", sizeof(auth));
6808 
6809  if(ast_test_flag64(user, IAX_CODEC_NOCAP))
6810  pstr = "REQ Only";
6811  else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
6812  pstr = "Disabled";
6813  else
6814  pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
6815 
6816  ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
6817  user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
6818  ast_acl_list_is_empty(user->acl) ? "No" : "Yes", pstr);
6819  }
6821 
6822  if (havepattern)
6823  regfree(&regexbuf);
6824 
6825  return CLI_SUCCESS;
6826 #undef FORMAT
6827 #undef FORMAT2
6828 }
6829 
6831  regex_t regexbuf;
6833  char idtext[256];
6840 };
6841 
6842 #define PEERS_FORMAT2 "%-15.15s %-40.40s %s %-40.40s %-9s %s %-11s %-32.32s\n"
6843 #define PEERS_FORMAT "%-15.15s %-40.40s %s %-40.40s %-6s%s %s %-11s %-32.32s\n"
6844 
6845 static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
6846 {
6847  char name[256] = "";
6848  char status[64];
6849  int retstatus;
6850  struct ast_str *encmethods = ast_str_alloca(256);
6851 
6852  char *tmp_host, *tmp_mask, *tmp_port;
6853 
6854  tmp_host = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
6855  tmp_mask = ast_strdupa(ast_sockaddr_stringify_addr(&peer->mask));
6856  tmp_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
6857 
6858  if (!ast_strlen_zero(peer->username)) {
6859  snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
6860  } else {
6861  ast_copy_string(name, peer->name, sizeof(name));
6862  }
6863 
6864  encmethods_to_str(peer->encmethods, &encmethods);
6865  retstatus = peer_status(peer, status, sizeof(status));
6866  if (retstatus > 0) {
6867  cont->online_peers++;
6868  } else if (!retstatus) {
6869  cont->offline_peers++;
6870  } else {
6871  cont->unmonitored_peers++;
6872  }
6873 
6874  if (s) {
6875  if (cont->peerlist) { /* IAXpeerlist */
6876  astman_append(s,
6877  "Event: PeerEntry\r\n%s"
6878  "Channeltype: IAX\r\n",
6879  cont->idtext);
6880  if (!ast_strlen_zero(peer->username)) {
6881  astman_append(s,
6882  "ObjectName: %s\r\n"
6883  "ObjectUsername: %s\r\n",
6884  peer->name,
6885  peer->username);
6886  } else {
6887  astman_append(s,
6888  "ObjectName: %s\r\n",
6889  name);
6890  }
6891  } else { /* IAXpeers */
6892  astman_append(s,
6893  "Event: PeerEntry\r\n%s"
6894  "Channeltype: IAX2\r\n"
6895  "ObjectName: %s\r\n",
6896  cont->idtext,
6897  name);
6898  }
6899  astman_append(s,
6900  "ChanObjectType: peer\r\n"
6901  "IPaddress: %s\r\n",
6902  tmp_host);
6903  if (cont->peerlist) { /* IAXpeerlist */
6904  astman_append(s,
6905  "Mask: %s\r\n"
6906  "Port: %s\r\n",
6907  tmp_mask,
6908  tmp_port);
6909  } else { /* IAXpeers */
6910  astman_append(s,
6911  "IPport: %s\r\n",
6912  tmp_port);
6913  }
6914  astman_append(s,
6915  "Dynamic: %s\r\n"
6916  "Trunk: %s\r\n"
6917  "Encryption: %s\r\n"
6918  "Status: %s\r\n",
6919  ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
6920  ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
6921  peer->encmethods ? ast_str_buffer(encmethods) : "no",
6922  status);
6923  if (cont->peerlist) { /* IAXpeerlist */
6924  astman_append(s, "\r\n");
6925  } else { /* IAXpeers */
6926  astman_append(s,
6927  "Description: %s\r\n\r\n",
6928  peer->description);
6929  }
6930  } else {
6931  ast_cli(fd, PEERS_FORMAT,
6932  name,
6933  tmp_host,
6934  ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
6935  tmp_mask,
6936  tmp_port,
6937  ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
6938  peer->encmethods ? "(E)" : " ",
6939  status,
6940  peer->description);
6941  }
6942 
6943  cont->total_peers++;
6944 }
6945 
6946 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
6947 {
6948  struct show_peers_context cont = {
6949  .havepattern = 0,
6950  .idtext = "",
6951  .registeredonly = 0,
6952 
6953  .peerlist = 0,
6954 
6955  .total_peers = 0,
6956  .online_peers = 0,
6957  .offline_peers = 0,
6958  .unmonitored_peers = 0,
6959  };
6960 
6961  struct ao2_iterator i;
6962 
6963  struct iax2_peer *peer = NULL;
6964 
6965  switch (argc) {
6966  case 6:
6967  if (!strcasecmp(argv[3], "registered"))
6968  cont.registeredonly = 1;
6969  else
6970  return RESULT_SHOWUSAGE;
6971  if (!strcasecmp(argv[4], "like")) {
6972  if (regcomp(&cont.regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
6973  return RESULT_SHOWUSAGE;
6974  cont.havepattern = 1;
6975  } else
6976  return RESULT_SHOWUSAGE;
6977  break;
6978  case 5:
6979  if (!strcasecmp(argv[3], "like")) {
6980  if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
6981  return RESULT_SHOWUSAGE;
6982  cont.havepattern = 1;
6983  } else
6984  return RESULT_SHOWUSAGE;
6985  break;
6986  case 4:
6987  if (!strcasecmp(argv[3], "registered")) {
6988  cont.registeredonly = 1;
6989  } else {
6990  return RESULT_SHOWUSAGE;
6991  }
6992  break;
6993  case 3:
6994  break;
6995  default:
6996  return RESULT_SHOWUSAGE;
6997  }
6998 
6999 
7000  if (!s) {
7001  ast_cli(fd, PEERS_FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", "Description");
7002  }
7003 
7004  i = ao2_iterator_init(peers, 0);
7005  for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7006 
7007  if (cont.registeredonly && ast_sockaddr_isnull(&peer->addr)) {
7008  continue;
7009  }
7010  if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
7011  continue;
7012  }
7013 
7014  _iax2_show_peers_one(fd, s, &cont, peer);
7015 
7016  }
7018 
7019  if (!s) {
7020  ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
7021  cont.total_peers, cont.online_peers, cont.offline_peers, cont.unmonitored_peers);
7022  }
7023 
7024  if (cont.havepattern) {
7025  regfree(&cont.regexbuf);
7026  }
7027 
7028  if (total) {
7029  *total = cont.total_peers;
7030  }
7031 
7032  return RESULT_SUCCESS;
7033 
7034 }
7035 #undef PEERS_FORMAT2
7036 #undef PEERS_FORMAT
7037 
7038 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7039 {
7040  struct iax2_thread *thread = NULL;
7041  time_t t;
7042  int threadcount = 0, dynamiccount = 0;
7043  char type;
7044 
7045  switch (cmd) {
7046  case CLI_INIT:
7047  e->command = "iax2 show threads";
7048  e->usage =
7049  "Usage: iax2 show threads\n"
7050  " Lists status of IAX helper threads\n";
7051  return NULL;
7052  case CLI_GENERATE:
7053  return NULL;
7054  }
7055  if (a->argc != 3)
7056  return CLI_SHOWUSAGE;
7057 
7058  ast_cli(a->fd, "IAX2 Thread Information\n");
7059  time(&t);
7060  ast_cli(a->fd, "Idle Threads:\n");
7062  AST_LIST_TRAVERSE(&idle_list, thread, list) {
7063 #ifdef DEBUG_SCHED_MULTITHREAD
7064  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7065  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7066 #else
7067  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7068  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7069 #endif
7070  threadcount++;
7071  }
7073  ast_cli(a->fd, "Active Threads:\n");
7075  AST_LIST_TRAVERSE(&active_list, thread, list) {
7076  if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
7077  type = 'D';
7078  else
7079  type = 'P';
7080 #ifdef DEBUG_SCHED_MULTITHREAD
7081  ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d, func='%s'\n",
7082  type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7083 #else
7084  ast_cli(a->fd, "Thread %c%d: state=%u, update=%d, actions=%d\n",
7085  type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7086 #endif
7087  threadcount++;
7088  }
7090  ast_cli(a->fd, "Dynamic Threads:\n");
7092  AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
7093 #ifdef DEBUG_SCHED_MULTITHREAD
7094  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d, func='%s'\n",
7095  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
7096 #else
7097  ast_cli(a->fd, "Thread %d: state=%u, update=%d, actions=%d\n",
7098  thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
7099 #endif
7100  dynamiccount++;
7101  }
7103  ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
7104  return CLI_SUCCESS;
7105 }
7106 
7107 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7108 {
7109  struct iax2_peer *p;
7110 
7111  switch (cmd) {
7112  case CLI_INIT:
7113  e->command = "iax2 unregister";
7114  e->usage =
7115  "Usage: iax2 unregister <peername>\n"
7116  " Unregister (force expiration) an IAX2 peer from the registry.\n";
7117  return NULL;
7118  case CLI_GENERATE:
7119  return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
7120  }
7121 
7122  if (a->argc != 3)
7123  return CLI_SHOWUSAGE;
7124 
7125  p = find_peer(a->argv[2], 1);
7126  if (p) {
7127  if (p->expire > -1) {
7128  struct iax2_peer *peer;
7129 
7130  peer = ao2_find(peers, a->argv[2], OBJ_KEY);
7131  if (peer) {
7132  expire_registry(peer_ref(peer)); /* will release its own reference when done */
7133  peer_unref(peer); /* ref from ao2_find() */
7134  ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
7135  } else {
7136  ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
7137  }
7138  } else {
7139  ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
7140  }
7141  peer_unref(p);
7142  } else {
7143  ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
7144  }
7145  return CLI_SUCCESS;
7146 }
7147 
7148 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
7149 {
7150  int which = 0;
7151  struct iax2_peer *p = NULL;
7152  char *res = NULL;
7153  int wordlen = strlen(word);
7154 
7155  /* 0 - iax2; 1 - unregister; 2 - <peername> */
7156  if (pos == 2) {
7157  struct ao2_iterator i = ao2_iterator_init(peers, 0);
7158  while ((p = ao2_iterator_next(&i))) {
7159  if (!strncasecmp(p->name, word, wordlen) &&
7160  ++which > state && p->expire > -1) {
7161  res = ast_strdup(p->name);
7162  peer_unref(p);
7163  break;
7164  }
7165  peer_unref(p);
7166  }
7168  }
7169 
7170  return res;
7171 }
7172 
7173 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7174 {
7175  switch (cmd) {
7176  case CLI_INIT:
7177  e->command = "iax2 show peers";
7178  e->usage =
7179  "Usage: iax2 show peers [registered] [like <pattern>]\n"
7180  " Lists all known IAX2 peers.\n"
7181  " Optional 'registered' argument lists only peers with known addresses.\n"
7182  " Optional regular expression pattern is used to filter the peer list.\n";
7183  return NULL;
7184  case CLI_GENERATE:
7185  return NULL;
7186  }
7187 
7188  switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
7189  case RESULT_SHOWUSAGE:
7190  return CLI_SHOWUSAGE;
7191  case RESULT_FAILURE:
7192  return CLI_FAILURE;
7193  default:
7194  return CLI_SUCCESS;
7195  }
7196 }
7197 
7198 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
7199 {
7200  ast_cli_netstats(s, -1, 0);
7201  astman_append(s, "\r\n");
7202  return RESULT_SUCCESS;
7203 }
7204 
7206  void *user_data)
7207 {
7208  int *fd = user_data;
7209 
7210  ast_cli(*fd, "%-15.15s %-15d %-15d\n",
7211  header->devname,
7212  ntohs(header->version),
7213  (int) ntohl(header->datalen));
7214 
7215  return 0;
7216 }
7217 
7218 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7219 {
7220  switch (cmd) {
7221  case CLI_INIT:
7222  e->command = "iax2 show firmware";
7223  e->usage =
7224  "Usage: iax2 show firmware\n"
7225  " Lists all known IAX firmware images.\n";
7226  return NULL;
7227  case CLI_GENERATE:
7228  return NULL;
7229  }
7230 
7231  if (a->argc != 3 && a->argc != 4)
7232  return CLI_SHOWUSAGE;
7233 
7234  ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
7235 
7237  a->argc == 3 ? NULL : a->argv[3],
7239  (void *) &a->fd);
7240 
7241  return CLI_SUCCESS;
7242 }
7243 
7244 /*! \brief callback to display iax peers in manager */
7245 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
7246 {
7247  static const char * const a[] = { "iax2", "show", "peers" };
7248  const char *id = astman_get_header(m,"ActionID");
7249  char idtext[256] = "";
7250  int total = 0;
7251 
7252  if (!ast_strlen_zero(id))
7253  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7254 
7255  astman_send_listack(s, m, "Peer status list will follow", "start");
7256 
7257  /* List the peers in separate manager events */
7258  __iax2_show_peers(-1, &total, s, 3, a);
7259 
7260  /* Send final confirmation */
7261  astman_send_list_complete_start(s, m, "PeerlistComplete", total);
7263  return 0;
7264 }
7265 
7266 /*! \brief callback to display iax peers in manager format */
7267 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
7268 {
7269  struct show_peers_context cont = {
7270  .havepattern = 0,
7271  .idtext = "",
7272  .registeredonly = 0,
7273 
7274  .peerlist = 1,
7275 
7276  .total_peers = 0,
7277  .online_peers = 0,
7278  .offline_peers = 0,
7279  .unmonitored_peers = 0,
7280  };
7281 
7282  struct iax2_peer *peer = NULL;
7283  struct ao2_iterator i;
7284 
7285  const char *id = astman_get_header(m,"ActionID");
7286 
7287  if (!ast_strlen_zero(id)) {
7288  snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
7289  }
7290 
7291  astman_send_listack(s, m, "IAX Peer status list will follow", "start");
7292 
7293  i = ao2_iterator_init(peers, 0);
7294  for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
7295  _iax2_show_peers_one(-1, s, &cont, peer);
7296  }
7298 
7299  astman_send_list_complete_start(s, m, "PeerlistComplete", cont.total_peers);
7301 
7302  return RESULT_SUCCESS;
7303 }
7304 
7305 
7306 static char *regstate2str(int regstate)
7307 {
7308  switch(regstate) {
7310  return "Unregistered";
7311  case REG_STATE_REGSENT:
7312  return "Request Sent";
7313  case REG_STATE_AUTHSENT:
7314  return "Auth. Sent";
7315  case REG_STATE_REGISTERED:
7316  return "Registered";
7317  case REG_STATE_REJECTED:
7318  return "Rejected";
7319  case REG_STATE_TIMEOUT:
7320  return "Timeout";
7321  case REG_STATE_NOAUTH:
7322  return "No Authentication";
7323  default:
7324  return "Unknown";
7325  }
7326 }
7327 
7328 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7329 {
7330 #define FORMAT2 "%-45.45s %-6.6s %-10.10s %-45.45s %8.8s %s\n"
7331 #define FORMAT "%-45.45s %-6.6s %-10.10s %-45.45s %8d %s\n"
7332 
7333  struct iax2_registry *reg = NULL;
7334  char host[80];
7335  char perceived[80];
7336  int counter = 0;
7337 
7338  switch (cmd) {
7339  case CLI_INIT:
7340  e->command = "iax2 show registry";
7341  e->usage =
7342  "Usage: iax2 show registry\n"
7343  " Lists all registration requests and status.\n";
7344  return NULL;
7345  case CLI_GENERATE:
7346  return NULL;
7347  }
7348  if (a->argc != 3)
7349  return CLI_SHOWUSAGE;
7350  ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
7352  AST_LIST_TRAVERSE(&registrations, reg, entry) {
7353  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7354 
7355  snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->addr) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->addr));
7356 
7357  ast_cli(a->fd, FORMAT, host,
7358  (reg->dnsmgr) ? "Y" : "N",
7359  reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
7360  counter++;
7361  }
7363  ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
7364  return CLI_SUCCESS;
7365 #undef FORMAT
7366 #undef FORMAT2
7367 }
7368 
7369 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
7370 {
7371  const char *id = astman_get_header(m, "ActionID");
7372  struct iax2_registry *reg = NULL;
7373  char idtext[256] = "";
7374  char host[80] = "";
7375  char perceived[80] = "";
7376  int total = 0;
7377 
7378  if (!ast_strlen_zero(id))
7379  snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
7380 
7381  astman_send_listack(s, m, "Registrations will follow", "start");
7382 
7384  AST_LIST_TRAVERSE(&registrations, reg, entry) {
7385  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(&reg->addr));
7386 
7387  snprintf(perceived, sizeof(perceived), "%s", ast_sockaddr_isnull(&reg->addr) ? "<Unregistered>" : ast_sockaddr_stringify(&reg->addr));
7388 
7389  astman_append(s,
7390  "Event: RegistryEntry\r\n"
7391  "%s"
7392  "Host: %s\r\n"
7393  "DNSmanager: %s\r\n"
7394  "Username: %s\r\n"
7395  "Perceived: %s\r\n"
7396  "Refresh: %d\r\n"
7397  "State: %s\r\n"
7398  "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
7399  reg->refresh, regstate2str(reg->regstate));
7400 
7401  total++;
7402  }
7404 
7405  astman_send_list_complete_start(s, m, "RegistrationsComplete", total);
7407 
7408  return 0;
7409 }
7410 
7411 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7412 {
7413 #define FORMAT2 "%-20.20s %-40.40s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
7414 #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"
7415 #define FORMATB "%-20.20s %-40.40s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
7416  int x;
7417  int numchans = 0;
7418  char first_message[10] = { 0, };
7419  char last_message[10] = { 0, };
7420 
7421  switch (cmd) {
7422  case CLI_INIT:
7423  e->command = "iax2 show channels";
7424  e->usage =
7425  "Usage: iax2 show channels\n"
7426  " Lists all currently active IAX channels.\n";
7427  return NULL;
7428  case CLI_GENERATE:
7429  return NULL;
7430  }
7431 
7432  if (a->argc != 3)
7433  return CLI_SHOWUSAGE;
7434  ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
7435  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7436  ast_mutex_lock(&iaxsl[x]);
7437  if (iaxs[x]) {
7438  int lag, jitter, localdelay;
7439  jb_info jbinfo;
7440  if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7441  jb_getinfo(iaxs[x]->jb, &jbinfo);
7442  jitter = jbinfo.jitter;
7443  localdelay = jbinfo.current - jbinfo.min;
7444  } else {
7445  jitter = -1;
7446  localdelay = 0;
7447  }
7448 
7449  iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7450  iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7451  lag = iaxs[x]->remote_rr.delay;
7452  ast_cli(a->fd, FORMAT,
7453  iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7454  ast_sockaddr_stringify_addr(&iaxs[x]->addr),
7455  S_OR(iaxs[x]->username, "(None)"),
7456  iaxs[x]->callno, iaxs[x]->peercallno,
7457  iaxs[x]->oseqno, iaxs[x]->iseqno,
7458  lag,
7459  jitter,
7460  localdelay,
7461  iax2_getformatname(iaxs[x]->voiceformat),
7462  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7463  first_message,
7464  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7465  last_message);
7466  numchans++;
7467  }
7468  ast_mutex_unlock(&iaxsl[x]);
7469  }
7470  ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7471  return CLI_SUCCESS;
7472 #undef FORMAT
7473 #undef FORMAT2
7474 #undef FORMATB
7475 }
7476 
7477 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
7478 {
7479  int x;
7480  int numchans = 0;
7481  char first_message[10] = { 0, };
7482  char last_message[10] = { 0, };
7483 #define ACN_FORMAT1 "%-20.25s %4u %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
7484 #define ACN_FORMAT2 "%s %u %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
7485  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
7486  ast_mutex_lock(&iaxsl[x]);
7487  if (iaxs[x]) {
7488  int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
7489  jb_info jbinfo;
7490  iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
7491  iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
7492 
7493  if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
7494  jb_getinfo(iaxs[x]->jb, &jbinfo);
7495  localjitter = jbinfo.jitter;
7496  localdelay = jbinfo.current - jbinfo.min;
7497  locallost = jbinfo.frames_lost;
7498  locallosspct = jbinfo.losspct/1000;
7499  localdropped = jbinfo.frames_dropped;
7500  localooo = jbinfo.frames_ooo;
7501  } else {
7502  localjitter = -1;
7503  localdelay = 0;
7504  locallost = -1;
7505  locallosspct = -1;
7506  localdropped = 0;
7507  localooo = -1;
7508  }
7509  if (s)
7510  astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7511  iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7512  iaxs[x]->pingtime,
7513  localjitter,
7514  localdelay,
7515  locallost,
7516  locallosspct,
7517  localdropped,
7518  localooo,
7519  iaxs[x]->frames_received/1000,
7520  iaxs[x]->remote_rr.jitter,
7521  iaxs[x]->remote_rr.delay,
7522  iaxs[x]->remote_rr.losscnt,
7523  iaxs[x]->remote_rr.losspct,
7524  iaxs[x]->remote_rr.dropped,
7525  iaxs[x]->remote_rr.ooo,
7526  iaxs[x]->remote_rr.packets/1000,
7527  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7528  first_message,
7529  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7530  last_message);
7531  else
7532  ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
7533  iaxs[x]->owner ? ast_channel_name(iaxs[x]->owner) : "(None)",
7534  iaxs[x]->pingtime,
7535  localjitter,
7536  localdelay,
7537  locallost,
7538  locallosspct,
7539  localdropped,
7540  localooo,
7541  iaxs[x]->frames_received/1000,
7542  iaxs[x]->remote_rr.jitter,
7543  iaxs[x]->remote_rr.delay,
7544  iaxs[x]->remote_rr.losscnt,
7545  iaxs[x]->remote_rr.losspct,
7546  iaxs[x]->remote_rr.dropped,
7547  iaxs[x]->remote_rr.ooo,
7548  iaxs[x]->remote_rr.packets/1000,
7549  (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7550  first_message,
7551  (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
7552  last_message);
7553  numchans++;
7554  }
7555  ast_mutex_unlock(&iaxsl[x]);
7556  }
7557 
7558  return numchans;
7559 }
7560 
7561 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7562 {
7563  int numchans = 0;
7564 
7565  switch (cmd) {
7566  case CLI_INIT:
7567  e->command = "iax2 show netstats";
7568  e->usage =
7569  "Usage: iax2 show netstats\n"
7570  " Lists network status for all currently active IAX channels.\n";
7571  return NULL;
7572  case CLI_GENERATE:
7573  return NULL;
7574  }
7575  if (a->argc != 3)
7576  return CLI_SHOWUSAGE;
7577  ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
7578  ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
7579  numchans = ast_cli_netstats(NULL, a->fd, 1);
7580  ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
7581  return CLI_SUCCESS;
7582 }
7583 
7584 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7585 {
7586  switch (cmd) {
7587  case CLI_INIT:
7588  e->command = "iax2 set debug {on|off|peer}";
7589  e->usage =
7590  "Usage: iax2 set debug {on|off|peer peername}\n"
7591  " Enables/Disables dumping of IAX packets for debugging purposes.\n";
7592  return NULL;
7593  case CLI_GENERATE:
7594  if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
7595  return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
7596  return NULL;
7597  }
7598 
7599  if (a->argc < e->args || a->argc > e->args + 1)
7600  return CLI_SHOWUSAGE;
7601 
7602  if (!strcasecmp(a->argv[3], "peer")) {
7603  struct iax2_peer *peer;
7604 
7605  if (a->argc != e->args + 1)
7606  return CLI_SHOWUSAGE;
7607 
7608  peer = find_peer(a->argv[4], 1);
7609 
7610  if (!peer) {
7611  ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
7612  return CLI_FAILURE;
7613  }
7614 
7615  ast_sockaddr_copy(&debugaddr, &peer->addr);
7616 
7617  ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_port(&debugaddr));
7618 
7619  ao2_ref(peer, -1);
7620  } else if (!strncasecmp(a->argv[3], "on", 2)) {
7621  iaxdebug = 1;
7622  ast_cli(a->fd, "IAX2 Debugging Enabled\n");
7623  } else {
7624  iaxdebug = 0;
7625  memset(&debugaddr, 0, sizeof(debugaddr));
7626  ast_cli(a->fd, "IAX2 Debugging Disabled\n");
7627  }
7628  return CLI_SUCCESS;
7629 }
7630 
7631 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7632 {
7633  switch (cmd) {
7634  case CLI_INIT:
7635  e->command = "iax2 set debug trunk {on|off}";
7636  e->usage =
7637  "Usage: iax2 set debug trunk {on|off}\n"
7638  " Enables/Disables debugging of IAX trunking\n";
7639  return NULL;
7640  case CLI_GENERATE:
7641  return NULL;
7642  }
7643 
7644  if (a->argc != e->args)
7645  return CLI_SHOWUSAGE;
7646 
7647  if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
7648  iaxtrunkdebug = 1;
7649  ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
7650  } else {
7651  iaxtrunkdebug = 0;
7652  ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
7653  }
7654  return CLI_SUCCESS;
7655 }
7656 
7657 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
7658 {
7659  switch (cmd) {
7660  case CLI_INIT:
7661  e->command = "iax2 set debug jb {on|off}";
7662  e->usage =
7663  "Usage: iax2 set debug jb {on|off}\n"
7664  " Enables/Disables jitterbuffer debugging information\n";
7665  return NULL;
7666  case CLI_GENERATE:
7667  return NULL;
7668  }
7669 
7670  if (a->argc != e->args)
7671  return CLI_SHOWUSAGE;
7672 
7673  if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
7675  ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
7676  } else {
7678  ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
7679  }
7680  return CLI_SUCCESS;
7681 }
7682 
7683 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
7684 {
7685  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(c));
7686  int res = -1;
7687  ast_mutex_lock(&iaxsl[callno]);
7688  if (iaxs[callno]) {
7689  /* If there's an outstanding error, return failure now */
7690  if (!iaxs[callno]->error) {
7691  if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
7692  res = 0;
7693  /* Don't waste bandwidth sending null frames */
7694  else if (f->frametype == AST_FRAME_NULL)
7695  res = 0;
7696  else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
7697  res = 0;
7698  else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
7699  res = 0;
7700  else
7701  /* Simple, just queue for transmission */
7702  res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
7703  } else {
7704  ast_debug(1, "Write error: %s\n", strerror(errno));
7705  }
7706  }
7707  /* If it's already gone, just return */
7708  ast_mutex_unlock(&iaxsl[callno]);
7709  return res;
7710 }
7711 
7712 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
7713  int now, int transfer, int final)
7714 {
7715  struct ast_frame f = { 0, };
7716  int res = 0;
7717 
7718  f.frametype = type;
7719  f.subclass.integer = command;
7720  f.datalen = datalen;
7721  f.src = __FUNCTION__;
7722  f.data.ptr = (void *) data;
7723 
7724  if ((res = queue_signalling(i, &f)) <= 0) {
7725  return res;
7726  }
7727 
7728  return iax2_send(i, &f, ts, seqno, now, transfer, final);
7729 }
7730 
7731 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7732 {
7733  if (type == AST_FRAME_CONTROL && !iax2_is_control_frame_allowed(command)) {
7734  /* Control frame should not go out on the wire. */
7735  ast_debug(2, "Callno %d: Blocked sending control frame %d.\n",
7736  i->callno, command);
7737  return 0;
7738  }
7739  return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
7740 }
7741 
7742 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
7743 {
7744  int res;
7745  ast_mutex_lock(&iaxsl[callno]);
7746  res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
7747  ast_mutex_unlock(&iaxsl[callno]);
7748  return res;
7749 }
7750 
7751 /*!
7752  * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
7753  * the pvt struct for the given call number may disappear during its
7754  * execution.
7755  */
7756 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)
7757 {
7758  int call_num = i->callno;
7759  /* It is assumed that the callno has already been locked */
7760  iax2_predestroy(i->callno);
7761  if (!iaxs[call_num])
7762  return -1;
7763  return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
7764 }
7765 
7766 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)
7767 {
7768  return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
7769 }
7770 
7771 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
7772 {
7773  return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
7774 }
7775 
7776 static int apply_context(struct iax2_context *con, const char *context)
7777 {
7778  while(con) {
7779  if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
7780  return -1;
7781  con = con->next;
7782  }
7783  return 0;
7784 }
7785 
7786 
7787 static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
7788 {
7789  /* Start pessimistic */
7790  int res = -1;
7791  int version = 2;
7792  struct iax2_user *user = NULL, *best = NULL;
7793  int bestscore = 0;
7794  int gotcapability = 0;
7795  struct ast_variable *v = NULL, *tmpvar = NULL;
7796  struct ao2_iterator i;
7797 
7798  if (!iaxs[callno])
7799  return res;
7800  if (ies->called_number)
7801  ast_string_field_set(iaxs[callno], exten, ies->called_number);
7802  if (ies->calling_number) {
7803  if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
7805  }
7806  ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
7807  }
7808  if (ies->calling_name)
7809  ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
7810  if (ies->calling_ani)
7811  ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
7812  if (ies->dnid)
7813  ast_string_field_set(iaxs[callno], dnid, ies->dnid);
7814  if (ies->rdnis)
7815  ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
7816  if (ies->called_context)
7817  ast_string_field_set(iaxs[callno], context, ies->called_context);
7818  if (ies->language)
7819  ast_string_field_set(iaxs[callno], language, ies->language);
7820  if (ies->username)
7821  ast_string_field_set(iaxs[callno], username, ies->username);
7822  if (ies->calling_ton > -1)
7823  iaxs[callno]->calling_ton = ies->calling_ton;
7824  if (ies->calling_tns > -1)
7825  iaxs[callno]->calling_tns = ies->calling_tns;
7826  if (ies->calling_pres > -1)
7827  iaxs[callno]->calling_pres = ies->calling_pres;
7828  if (ies->format)
7829  iaxs[callno]->peerformat = ies->format;
7830  if (ies->adsicpe)
7831  iaxs[callno]->peeradsicpe = ies->adsicpe;
7832  if (ies->capability) {
7833  gotcapability = 1;
7834  iaxs[callno]->peercapability = ies->capability;
7835  }
7836  if (ies->version)
7837  version = ies->version;
7838 
7839  /* Use provided preferences until told otherwise for actual preferences */
7840  if (ies->codec_prefs) {
7841  iax2_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
7842  } else {
7843  memset(&iaxs[callno]->rprefs, 0, sizeof(iaxs[callno]->rprefs));
7844  }
7845  iaxs[callno]->prefs = iaxs[callno]->rprefs;
7846 
7847  if (!gotcapability) {
7848  iaxs[callno]->peercapability = iaxs[callno]->peerformat;
7849  }
7850  if (version > IAX_PROTO_VERSION) {
7851  ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
7852  ast_sockaddr_stringify_addr(addr), version);
7853  return res;
7854  }
7855  /* Search the userlist for a compatible entry, and fill in the rest */
7856  i = ao2_iterator_init(users, 0);
7857  while ((user = ao2_iterator_next(&i))) {
7858  if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
7859  !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
7860  && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_ALLOW) /* Access is permitted from this IP */
7861  && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
7862  apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
7863  if (!ast_strlen_zero(iaxs[callno]->username)) {
7864  /* Exact match, stop right now. */
7865  if (best)
7866  user_unref(best);
7867  best = user;
7868  break;
7869  } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
7870  /* No required authentication */
7871  if (user->acl) {
7872  /* There was host authentication and we passed, bonus! */
7873  if (bestscore < 4) {
7874  bestscore = 4;
7875  if (best)
7876  user_unref(best);
7877  best = user;
7878  continue;
7879  }
7880  } else {
7881  /* No host access, but no secret, either, not bad */
7882  if (bestscore < 3) {
7883  bestscore = 3;
7884  if (best)
7885  user_unref(best);
7886  best = user;
7887  continue;
7888  }
7889  }
7890  } else {
7891  if (user->acl) {
7892  /* Authentication, but host access too, eh, it's something.. */
7893  if (bestscore < 2) {
7894  bestscore = 2;
7895  if (best)
7896  user_unref(best);
7897  best = user;
7898  continue;
7899  }
7900  } else {
7901  /* Authentication and no host access... This is our baseline */
7902  if (bestscore < 1) {
7903  bestscore = 1;
7904  if (best)
7905  user_unref(best);
7906  best = user;
7907  continue;
7908  }
7909  }
7910  }
7911  }
7912  user_unref(user);
7913  }
7915  user = best;
7916  if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
7917  user = realtime_user(iaxs[callno]->username, addr);
7918  if (user && (ast_apply_acl(user->acl, addr, "IAX2 user ACL: ") == AST_SENSE_DENY /* Access is denied from this IP */
7919  || (!ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
7920  !apply_context(user->contexts, iaxs[callno]->context)))) { /* Context is permitted */
7921  user = user_unref(user);
7922  }
7923  }
7924  if (user) {
7925  /* We found our match (use the first) */
7926  /* copy vars */
7927  for (v = user->vars ; v ; v = v->next) {
7928  if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
7929  if (ast_variable_list_replace(&iaxs[callno]->vars, tmpvar)) {
7930  tmpvar->next = iaxs[callno]->vars;
7931  iaxs[callno]->vars = tmpvar;
7932  }
7933  }
7934  }
7935  /* If a max AUTHREQ restriction is in place, activate it */
7936  if (user->maxauthreq > 0)
7937  ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
7938  iaxs[callno]->prefs = user->prefs;
7940  iaxs[callno]->encmethods = user->encmethods;
7941  /* Store the requested username if not specified */
7942  if (ast_strlen_zero(iaxs[callno]->username))
7943  ast_string_field_set(iaxs[callno], username, user->name);
7944  /* Store whether this is a trunked call, too, of course, and move if appropriate */
7945  ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
7946  iaxs[callno]->capability = user->capability;
7947  /* And use the default context */
7948  if (ast_strlen_zero(iaxs[callno]->context)) {
7949  if (user->contexts)
7950  ast_string_field_set(iaxs[callno], context, user->contexts->context);
7951  else
7953  }
7954  /* And any input keys */
7955  ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
7956  /* And the permitted authentication methods */
7957  iaxs[callno]->authmethods = user->authmethods;
7958  iaxs[callno]->adsi = user->adsi;
7959  /* If the user has callerid, override the remote caller id. */
7960  if (ast_test_flag64(user, IAX_HASCALLERID)) {
7961  iaxs[callno]->calling_tns = 0;
7962  iaxs[callno]->calling_ton = 0;
7963  ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
7964  ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
7965  ast_string_field_set(iaxs[callno], ani, user->cid_num);
7967  } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
7969  } /* else user is allowed to set their own CID settings */
7970  if (!ast_strlen_zero(user->accountcode))
7971  ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
7972  if (!ast_strlen_zero(user->mohinterpret))
7973  ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
7974  if (!ast_strlen_zero(user->mohsuggest))
7975  ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
7976  if (!ast_strlen_zero(user->parkinglot))
7977  ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
7978  if (user->amaflags)
7979  iaxs[callno]->amaflags = user->amaflags;
7980  if (!ast_strlen_zero(user->language))
7981  ast_string_field_set(iaxs[callno], language, user->language);
7983  /* Keep this check last */
7984  if (!ast_strlen_zero(user->dbsecret)) {
7985  char *family, *key=NULL;
7986  char buf[80];
7987  family = ast_strdupa(user->dbsecret);
7988  key = strchr(family, '/');
7989  if (key) {
7990  *key = '\0';
7991  key++;
7992  }
7993  if (!key || ast_db_get(family, key, buf, sizeof(buf)))
7994  ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
7995  else
7996  ast_string_field_set(iaxs[callno], secret, buf);
7997  } else
7998  ast_string_field_set(iaxs[callno], secret, user->secret);
7999  res = 0;
8000  user = user_unref(user);
8001  } else {
8002  /* user was not found, but we should still fake an AUTHREQ.
8003  * Set authmethods to the last known authmethod used by the system
8004  * Set a fake secret, it's not looked at, just required to attempt authentication.
8005  * Set authrej so the AUTHREP is rejected without even looking at its contents */
8007  ast_string_field_set(iaxs[callno], secret, "badsecret");
8008  iaxs[callno]->authrej = 1;
8009  if (!ast_strlen_zero(iaxs[callno]->username)) {
8010  /* only send the AUTHREQ if a username was specified. */
8011  res = 0;
8012  }
8013  }
8014  ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*addr), IAX_TRUNK);
8015  return res;
8016 }
8017 
8018 static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
8019 {
8020  struct ast_iax2_full_hdr fh;
8021  fh.scallno = htons(src | IAX_FLAG_FULL);
8022  fh.dcallno = htons(dst);
8023  fh.ts = 0;
8024  fh.oseqno = 0;
8025  fh.iseqno = 0;
8026  fh.type = AST_FRAME_IAX;
8028  iax_outputframe(NULL, &fh, 0, addr, 0);
8029 
8030  ast_debug(1, "Raw Hangup %s, src=%d, dst=%d\n", ast_sockaddr_stringify(addr), src, dst);
8031  return ast_sendto(sockfd, &fh, sizeof(fh), 0, addr);
8032 }
8033 
8034 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
8035 {
8036  /* Select exactly one common encryption if there are any */
8037  p->encmethods &= enc;
8038  if (p->encmethods) {
8039  if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){ /* if key rotation is not supported, turn off keyrotation. */
8040  p->keyrotateid = -2;
8041  }
8042  if (p->encmethods & IAX_ENCRYPT_AES128)
8044  else
8045  p->encmethods = 0;
8046  }
8047 }
8048 
8049 /*!
8050  * \pre iaxsl[call_num] is locked
8051  *
8052  * \note Since this function calls send_command_final(), the pvt struct for the given
8053  * call number may disappear while executing this function.
8054  */
8055 static int authenticate_request(int call_num)
8056 {
8057  struct iax_ie_data ied;
8058  int res = -1, authreq_restrict = 0;
8059  char challenge[10];
8060  struct chan_iax2_pvt *p = iaxs[call_num];
8061 
8062  memset(&ied, 0, sizeof(ied));
8063 
8064  /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
8065  if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
8066  struct iax2_user *user;
8067 
8068  user = ao2_find(users, p->username, OBJ_KEY);
8069  if (user) {
8070  if (user->curauthreq == user->maxauthreq)
8071  authreq_restrict = 1;
8072  else
8073  user->curauthreq++;
8074  user = user_unref(user);
8075  }
8076  }
8077 
8078  /* If the AUTHREQ limit test failed, send back an error */
8079  if (authreq_restrict) {
8080  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
8083  return 0;
8084  }
8085 
8087  if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
8088  snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
8089  ast_string_field_set(p, challenge, challenge);
8090  /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
8092  }
8093  if (p->encmethods)
8095 
8097 
8098  res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
8099 
8100  if (p->encmethods)
8102 
8103  return res;
8104 }
8105 
8106 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
8107 {
8108  char requeststr[256];
8109  char md5secret[256] = "";
8110  char secret[256] = "";
8111  char rsasecret[256] = "";
8112  int res = -1;
8113  int x;
8114  struct iax2_user *user;
8115 
8116  if (p->authrej) {
8117  return res;
8118  }
8119 
8120  user = ao2_find(users, p->username, OBJ_KEY);
8121  if (user) {
8122  if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
8123  ast_atomic_fetchadd_int(&user->curauthreq, -1);
8125  }
8126  ast_string_field_set(p, host, user->name);
8127  user = user_unref(user);
8128  }
8129  if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
8130  ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
8131  return res;
8132  }
8134  return res;
8135  if (ies->password)
8136  ast_copy_string(secret, ies->password, sizeof(secret));
8137  if (ies->md5_result)
8138  ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8139  if (ies->rsa_result)
8140  ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8141  if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
8142  struct ast_key *key;
8143  char *keyn;
8144  char *tmpkey;
8145  char *stringp=NULL;
8146  if (!(tmpkey = ast_strdup(p->inkeys))) {
8147  ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8148  return res;
8149  }
8150  stringp = tmpkey;
8151  keyn = strsep(&stringp, ":");
8152  while(keyn) {
8153  key = ast_key_get(keyn, AST_KEY_PUBLIC);
8154  if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
8155  res = 0;
8156  break;
8157  } else if (!key)
8158  ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
8159  keyn = strsep(&stringp, ":");
8160  }
8161  ast_free(tmpkey);
8162  } else if (p->authmethods & IAX_AUTH_MD5) {
8163  struct MD5Context md5;
8164  unsigned char digest[16];
8165  char *tmppw, *stringp;
8166  tmppw = ast_strdupa(p->secret);
8167  stringp = tmppw;
8168  while((tmppw = strsep(&stringp, ";"))) {
8169  MD5Init(&md5);
8170  MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
8171  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8172  MD5Final(digest, &md5);
8173  /* If they support md5, authenticate with it. */
8174  for (x=0;x<16;x++)
8175  sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8176  if (!strcasecmp(requeststr, md5secret)) {
8177  res = 0;
8178  break;
8179  }
8180  }
8181  } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
8182  if (!strcmp(secret, p->secret))
8183  res = 0;
8184  }
8185  return res;
8186 }
8187 
8188 /*! \brief Verify inbound registration */
8189 static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
8190 {
8191  char requeststr[256] = "";
8192  char peer[256] = "";
8193  char md5secret[256] = "";
8194  char rsasecret[256] = "";
8195  char secret[256] = "";
8196  struct iax2_peer *p = NULL;
8197  struct ast_key *key;
8198  char *keyn;
8199  int x;
8200  int expire = 0;
8201  int res = -1;
8202 
8203  ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8204  /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
8205  if (ies->username)
8206  ast_copy_string(peer, ies->username, sizeof(peer));
8207  if (ies->password)
8208  ast_copy_string(secret, ies->password, sizeof(secret));
8209  if (ies->md5_result)
8210  ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
8211  if (ies->rsa_result)
8212  ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
8213  if (ies->refresh)
8214  expire = ies->refresh;
8215 
8216  if (ast_strlen_zero(peer)) {
8217  ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_sockaddr_stringify_addr(addr));
8218  return -1;
8219  }
8220 
8221  /* SLD: first call to lookup peer during registration */
8222  ast_mutex_unlock(&iaxsl[callno]);
8223  p = find_peer(peer, 1);
8224  ast_mutex_lock(&iaxsl[callno]);
8225  if (!p || !iaxs[callno]) {
8226  if (iaxs[callno]) {
8227  int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
8228  /* Anything, as long as it's non-blank */
8229  ast_string_field_set(iaxs[callno], secret, "badsecret");
8230  /* An AUTHREQ must be sent in response to a REGREQ of an invalid peer unless
8231  * 1. A challenge already exists indicating a AUTHREQ was already sent out.
8232  * 2. A plaintext secret is present in ie as result of a previous AUTHREQ requesting it.
8233  * 3. A plaintext secret is present in the ie and the last_authmethod used by a peer happened
8234  * to be plaintext, indicating it is an authmethod used by other peers on the system.
8235  *
8236  * If none of these cases exist, res will be returned as 0 without authentication indicating
8237  * an AUTHREQ needs to be sent out. */
8238 
8239  if (ast_strlen_zero(iaxs[callno]->challenge) &&
8240  !(!ast_strlen_zero(secret) && plaintext)) {
8241  /* by setting res to 0, an REGAUTH will be sent */
8242  res = 0;
8243  }
8244  }
8245  if (authdebug && !p)
8246  ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8247  goto return_unref;
8248  }
8249 
8250  if (!ast_test_flag64(p, IAX_DYNAMIC)) {
8251  if (authdebug)
8252  ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_sockaddr_stringify_addr(addr));
8253  goto return_unref;
8254  }
8255 
8256  if (!ast_apply_acl(p->acl, addr, "IAX2 Peer ACL: ")) {
8257  if (authdebug)
8258  ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8259  goto return_unref;
8260  }
8261  ast_string_field_set(iaxs[callno], secret, p->secret);
8262  ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
8263  /* Check secret against what we have on file */
8264  if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8265  if (!ast_strlen_zero(p->inkeys)) {
8266  char *tmpkey;
8267  char *stringp=NULL;
8268  if (!(tmpkey = ast_strdup(p->inkeys))) {
8269  ast_log(LOG_ERROR, "Unable to create a temporary string for parsing stored 'inkeys'\n");
8270  goto return_unref;
8271  }
8272  stringp = tmpkey;
8273  keyn = strsep(&stringp, ":");
8274  while(keyn) {
8275  key = ast_key_get(keyn, AST_KEY_PUBLIC);
8276  if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
8277  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8278  break;
8279  } else if (!key)
8280  ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
8281  keyn = strsep(&stringp, ":");
8282  }
8283  ast_free(tmpkey);
8284  if (!keyn) {
8285  if (authdebug)
8286  ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
8287  goto return_unref;
8288  }
8289  } else {
8290  if (authdebug)
8291  ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
8292  goto return_unref;
8293  }
8294  } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
8295  struct MD5Context md5;
8296  unsigned char digest[16];
8297  char *tmppw, *stringp;
8298 
8299  tmppw = ast_strdupa(p->secret);
8300  stringp = tmppw;
8301  while((tmppw = strsep(&stringp, ";"))) {
8302  MD5Init(&md5);
8303  MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
8304  MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
8305  MD5Final(digest, &md5);
8306  for (x=0;x<16;x++)
8307  sprintf(requeststr + (x << 1), "%02hhx", digest[x]); /* safe */
8308  if (!strcasecmp(requeststr, md5secret))
8309  break;
8310  }
8311  if (tmppw) {
8312  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8313  } else {
8314  if (authdebug)
8315  ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_sockaddr_stringify_addr(addr), p->name, requeststr, md5secret);
8316  goto return_unref;
8317  }
8318  } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
8319  /* They've provided a plain text password and we support that */
8320  if (strcmp(secret, p->secret)) {
8321  if (authdebug)
8322  ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_sockaddr_stringify_addr(addr), p->name);
8323  goto return_unref;
8324  } else
8325  ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
8326  } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
8327  /* if challenge has been sent, but no challenge response if given, reject. */
8328  goto return_unref;
8329  }
8330  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8331 
8332  /* either Authentication has taken place, or a REGAUTH must be sent before verifying registration */
8333  res = 0;
8334 
8335 return_unref:
8336  if (iaxs[callno]) {
8337  ast_string_field_set(iaxs[callno], peer, peer);
8338 
8339  /* Choose lowest expiry number */
8340  if (expire && (expire < iaxs[callno]->expiry)) {
8341  iaxs[callno]->expiry = expire;
8342  }
8343  }
8344 
8345  if (p) {
8346  peer_unref(p);
8347  }
8348  return res;
8349 }
8350 
8351 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)
8352 {
8353  int res = -1;
8354  int x;
8355  if (!ast_strlen_zero(keyn)) {
8356  if (!(authmethods & IAX_AUTH_RSA)) {
8357  if (ast_strlen_zero(secret)) {
8358  ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_sockaddr_stringify_addr(addr));
8359  }
8360  } else if (ast_strlen_zero(challenge)) {
8361  ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_sockaddr_stringify_addr(addr));
8362  } else {
8363  char sig[256];
8364  struct ast_key *key;
8365  key = ast_key_get(keyn, AST_KEY_PRIVATE);
8366  if (!key) {
8367  ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
8368  } else {
8369  if (ast_sign(key, (char*)challenge, sig)) {
8370  ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
8371  res = -1;
8372  } else {
8374  res = 0;
8375  }
8376  }
8377 
8378  }
8379  }
8380  /* Fall back */
8381  if (res && !ast_strlen_zero(secret)) {
8382  if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
8383  struct MD5Context md5;
8384  unsigned char digest[16];
8385  char digres[128];
8386  MD5Init(&md5);
8387  MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
8388  MD5Update(&md5, (unsigned char *)secret, strlen(secret));
8389  MD5Final(digest, &md5);
8390  /* If they support md5, authenticate with it. */
8391  for (x=0;x<16;x++)
8392  sprintf(digres + (x << 1), "%02hhx", digest[x]); /* safe */
8393  if (pvt) {
8394  build_encryption_keys(digest, pvt);
8395  }
8396  iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
8397  res = 0;
8398  } else if (authmethods & IAX_AUTH_PLAINTEXT) {
8399  iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
8400  res = 0;
8401  } else
8402  ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_sockaddr_stringify_addr(addr), authmethods);
8403  }
8404  return res;
8405 }
8406 
8407 /*!
8408  * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
8409  * so do not call this function with a pvt lock held.
8410  */
8411 static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
8412 {
8413  struct iax2_peer *peer = NULL;
8414  /* Start pessimistic */
8415  int res = -1;
8416  int authmethods = 0;
8417  struct iax_ie_data ied;
8418  uint16_t callno = p->callno;
8419 
8420  memset(&ied, 0, sizeof(ied));
8421 
8422  if (ies->username)
8423  ast_string_field_set(p, username, ies->username);
8424  if (ies->challenge)
8426  if (ies->authmethods)
8427  authmethods = ies->authmethods;
8428  if (authmethods & IAX_AUTH_MD5)
8429  merge_encryption(p, ies->encmethods);
8430  else
8431  p->encmethods = 0;
8432 
8433  /* Check for override RSA authentication first */
8434  if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
8435  /* Normal password authentication */
8436  res = authenticate(p->challenge, override, okey, authmethods, &ied, addr, p);
8437  } else {
8438  struct ao2_iterator i = ao2_iterator_init(peers, 0);
8439  while ((peer = ao2_iterator_next(&i))) {
8440  struct ast_sockaddr peer_addr;
8441  struct ast_sockaddr tmp_sockaddr1;
8442  struct ast_sockaddr tmp_sockaddr2;
8443 
8444  ast_sockaddr_copy(&peer_addr, &peer->addr);
8445 
8446  ast_sockaddr_apply_netmask(addr, &peer->mask, &tmp_sockaddr1);
8447  ast_sockaddr_apply_netmask(&peer_addr, &peer->mask, &tmp_sockaddr2);
8448 
8449  if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
8450  /* No peer specified at our end, or this is the peer */
8451  && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
8452  /* No username specified in peer rule, or this is the right username */
8453  && (ast_sockaddr_isnull(&peer_addr) || !(ast_sockaddr_cmp_addr(&tmp_sockaddr1, &tmp_sockaddr2)))
8454  /* No specified host, or this is our host */
8455  ) {
8456  res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, addr, p);
8457  if (!res) {
8458  peer_unref(peer);
8459  break;
8460  }
8461  }
8462  peer_unref(peer);
8463  }
8465  if (!peer) {
8466  /* We checked our list and didn't find one. It's unlikely, but possible,
8467  that we're trying to authenticate *to* a realtime peer */
8468  const char *peer_name = ast_strdupa(p->peer);
8469  ast_mutex_unlock(&iaxsl[callno]);
8470  if ((peer = realtime_peer(peer_name, NULL))) {
8471  ast_mutex_lock(&iaxsl[callno]);
8472  if (!(p = iaxs[callno])) {
8473  peer_unref(peer);
8474  return -1;
8475  }
8476  res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, addr, p);
8477  peer_unref(peer);
8478  }
8479  if (!peer) {
8480  ast_mutex_lock(&iaxsl[callno]);
8481  if (!(p = iaxs[callno]))
8482  return -1;
8483  }
8484  }
8485  }
8486 
8487  if (ies->encmethods) {
8488  if (ast_strlen_zero(p->secret) &&
8489  ((ies->authmethods & IAX_AUTH_MD5) || (ies->authmethods & IAX_AUTH_PLAINTEXT))) {
8490  ast_log(LOG_WARNING, "Call terminated. Encryption requested by peer but no secret available locally\n");
8491  return -1;
8492  }
8494  } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
8495  ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
8496  return -1; /* if force encryption is yes, and no encryption methods, then return -1 to hangup */
8497  }
8498  if (!res) {
8499  struct ast_datastore *variablestore;
8500  struct ast_variable *var, *prev = NULL;
8501  AST_LIST_HEAD(, ast_var_t) *varlist;
8502  varlist = ast_calloc(1, sizeof(*varlist));
8503  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
8504  if (variablestore && varlist && p->owner) {
8505  variablestore->data = varlist;
8506  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8507  AST_LIST_HEAD_INIT(varlist);
8508  for (var = ies->vars; var; var = var->next) {
8509  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8510  if (prev)
8511  ast_free(prev);
8512  prev = var;
8513  if (!newvar) {
8514  /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
8515  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8516  } else {
8517  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8518  }
8519  }
8520  if (prev)
8521  ast_free(prev);
8522  ies->vars = NULL;
8523  ast_channel_datastore_add(p->owner, variablestore);
8524  } else {
8525  if (p->owner)
8526  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8527  if (variablestore)
8528  ast_datastore_free(variablestore);
8529  if (varlist)
8530  ast_free(varlist);
8531  }
8532  }
8533 
8534  if (!res)
8535  res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
8536  return res;
8537 }
8538 
8539 static int iax2_do_register(struct iax2_registry *reg);
8540 
8541 static void __iax2_do_register_s(const void *data)
8542 {
8543  struct iax2_registry *reg = (struct iax2_registry *)data;
8544 
8545  if (ast_sockaddr_isnull(&reg->addr)) {
8546  reg->addr.ss.ss_family = AST_AF_UNSPEC;
8547  ast_dnsmgr_lookup(reg->hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL);
8548  if (!ast_sockaddr_port(&reg->addr)) {
8549  ast_sockaddr_set_port(&reg->addr, reg->port);
8550  } else {
8551  reg->port = ast_sockaddr_port(&reg->addr);
8552  }
8553  }
8554 
8555  reg->expire = -1;
8556  iax2_do_register(reg);
8557 }
8558 
8559 static int iax2_do_register_s(const void *data)
8560 {
8561 #ifdef SCHED_MULTITHREADED
8563 #endif
8564  __iax2_do_register_s(data);
8565  return 0;
8566 }
8567 
8568 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8569 {
8570  int newcall = 0;
8571  struct iax_ie_data ied;
8572  struct ast_sockaddr new = { {0,} };
8573 
8574  memset(&ied, 0, sizeof(ied));
8575  if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8576  ast_sockaddr_copy(&new, &ies->apparent_addr);
8577  }
8578  if (ies->callno) {
8579  newcall = ies->callno;
8580  }
8581  if (!newcall || ast_sockaddr_isnull(&new)) {
8582  ast_log(LOG_WARNING, "Invalid transfer request\n");
8583  return -1;
8584  }
8585  pvt->transfercallno = newcall;
8586  ast_sockaddr_copy(&pvt->transfer, &new);
8587  pvt->transferid = ies->transferid;
8588  /* only store by transfercallno if this is a new transfer,
8589  * just in case we get a duplicate TXREQ */
8590  if (pvt->transferring == TRANSFER_NONE) {
8592  }
8594 
8595  if (ies->transferid) {
8597  }
8599  return 0;
8600 }
8601 
8602 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
8603 {
8604  char exten[256] = "";
8605  int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
8606  struct iax2_dpcache *dp = NULL;
8607 
8608  if (ies->called_number)
8609  ast_copy_string(exten, ies->called_number, sizeof(exten));
8610 
8611  if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
8612  status = CACHE_FLAG_EXISTS;
8613  else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
8614  status = CACHE_FLAG_CANEXIST;
8615  else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
8616  status = CACHE_FLAG_NONEXISTENT;
8617 
8618  if (ies->refresh)
8619  expiry = ies->refresh;
8620  if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
8621  matchmore = CACHE_FLAG_MATCHMORE;
8622 
8625  if (strcmp(dp->exten, exten))
8626  continue;
8628  dp->callno = 0;
8629  dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
8630  if (dp->flags & CACHE_FLAG_PENDING) {
8631  dp->flags &= ~CACHE_FLAG_PENDING;
8632  dp->flags |= status;
8633  dp->flags |= matchmore;
8634  }
8635  /* Wake up waiters */
8636  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
8637  if (dp->waiters[x] > -1) {
8638  if (write(dp->waiters[x], "asdf", 4) < 0) {
8639  }
8640  }
8641  }
8642  }
8645 
8646  return 0;
8647 }
8648 
8649 static int complete_transfer(int callno, struct iax_ies *ies)
8650 {
8651  int peercallno = 0;
8652  struct chan_iax2_pvt *pvt = iaxs[callno];
8653  struct iax_frame *cur;
8654  jb_frame frame;
8655 
8656  if (ies->callno)
8657  peercallno = ies->callno;
8658 
8659  if (peercallno < 1) {
8660  ast_log(LOG_WARNING, "Invalid transfer request\n");
8661  return -1;
8662  }
8664  /* since a transfer has taken place, the address will change.
8665  * This must be accounted for in the peercnts table. Remove
8666  * the old address and add the new one */
8668  peercnt_add(&pvt->transfer);
8669  /* now copy over the new address */
8670  memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
8671  memset(&pvt->transfer, 0, sizeof(pvt->transfer));
8672  /* Reset sequence numbers */
8673  pvt->oseqno = 0;
8674  pvt->rseqno = 0;
8675  pvt->iseqno = 0;
8676  pvt->aseqno = 0;
8677 
8678  if (pvt->peercallno) {
8679  remove_by_peercallno(pvt);
8680  }
8681  pvt->peercallno = peercallno;
8682  /*this is where the transfering call swiches hash tables */
8683  store_by_peercallno(pvt);
8684  pvt->transferring = TRANSFER_NONE;
8685  pvt->svoiceformat = -1;
8686  pvt->voiceformat = 0;
8687  pvt->svideoformat = -1;
8688  pvt->videoformat = 0;
8689  pvt->transfercallno = 0;
8690  memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
8691  memset(&pvt->offset, 0, sizeof(pvt->offset));
8692  /* reset jitterbuffer */
8693  while(jb_getall(pvt->jb,&frame) == JB_OK)
8694  iax2_frame_free(frame.data);
8695  jb_reset(pvt->jb);
8696  pvt->lag = 0;
8697  pvt->last = 0;
8698  pvt->lastsent = 0;
8699  pvt->nextpred = 0;
8701  AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
8702  /* We must cancel any packets that would have been transmitted
8703  because now we're talking to someone new. It's okay, they
8704  were transmitted to someone that didn't care anyway. */
8705  cur->retries = -1;
8706  }
8707  return 0;
8708 }
8709 
8710 static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
8711 {
8712  ast_system_publish_registry("IAX2", username, domain, status, cause);
8713 }
8714 
8715 /*! \brief Acknowledgment received for OUR registration */
8716 static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
8717 {
8718  struct iax2_registry *reg;
8719  /* Start pessimistic */
8720  char peer[256] = "";
8721  char msgstatus[60];
8722  int refresh = 60;
8723  char ourip[256] = "<Unspecified>";
8724  struct ast_sockaddr oldus;
8725  struct ast_sockaddr us;
8726  int oldmsgs;
8727 
8728  if (!ast_sockaddr_isnull(&ies->apparent_addr)) {
8729  ast_sockaddr_copy(&us, &ies->apparent_addr);
8730  }
8731  if (ies->username) {
8732  ast_copy_string(peer, ies->username, sizeof(peer));
8733  }
8734  if (ies->refresh) {
8735  refresh = ies->refresh;
8736  }
8737  if (ies->calling_number) {
8738  /* We don't do anything with it really, but maybe we should */
8739  }
8740  reg = iaxs[callno]->reg;
8741  if (!reg) {
8742  ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
8743  return -1;
8744  }
8745  ast_sockaddr_copy(&oldus, &reg->us);
8746  oldmsgs = reg->messages;
8747  if (ast_sockaddr_cmp(&reg->addr, addr)) {
8748  ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_sockaddr_stringify(addr));
8749  return -1;
8750  }
8751  ast_sockaddr_copy(&reg->us, &us);
8752  if (ies->msgcount >= 0) {
8753  reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
8754  }
8755  /* always refresh the registration at the interval requested by the server
8756  we are registering to
8757  */
8758  reg->refresh = refresh;
8759  reg->expire = iax2_sched_replace(reg->expire, sched,
8760  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8761  if (ast_sockaddr_cmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
8762 
8763  if (reg->messages > 255) {
8764  snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
8765  } else if (reg->messages > 1) {
8766  snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
8767  } else if (reg->messages > 0) {
8768  ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
8769  } else {
8770  ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
8771  }
8772 
8773  snprintf(ourip, sizeof(ourip), "%s", ast_sockaddr_stringify(&reg->us));
8774 
8775  ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_sockaddr_stringify(addr), ourip, msgstatus);
8776  iax2_publish_registry(reg->username, ast_sockaddr_stringify(addr), "Registered", NULL);
8777  }
8779  return 0;
8780 }
8781 
8782 static int iax2_append_register(const char *hostname, const char *username,
8783  const char *secret, const char *porta)
8784 {
8785  struct iax2_registry *reg;
8786 
8787  if (!(reg = ast_calloc(1, sizeof(*reg) + strlen(hostname) + 1))) {
8788  return -1;
8789  }
8790 
8791  reg->addr.ss.ss_family = AST_AF_UNSPEC;
8792  if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
8793  ast_free(reg);
8794  return -1;
8795  }
8796 
8797  ast_copy_string(reg->username, username, sizeof(reg->username));
8798  strcpy(reg->hostname, hostname); /* Note: This is safe */
8799 
8800  if (secret) {
8801  ast_copy_string(reg->secret, secret, sizeof(reg->secret));
8802  }
8803 
8804  reg->expire = -1;
8806 
8807  reg->port = ast_sockaddr_port(&reg->addr);
8808 
8809  if (!porta && !reg->port) {
8810  reg->port = IAX_DEFAULT_PORTNO;
8811  } else if (porta) {
8812  sscanf(porta, "%5d", &reg->port);
8813  }
8814 
8815  ast_sockaddr_set_port(&reg->addr, reg->port);
8816 
8818  AST_LIST_INSERT_HEAD(&registrations, reg, entry);
8820 
8821  return 0;
8822 }
8823 
8824 static int iax2_register(const char *value, int lineno)
8825 {
8826  char copy[256];
8827  char *username, *hostname, *secret;
8828  char *porta;
8829  char *stringp=NULL;
8830 
8831  if (!value)
8832  return -1;
8833 
8834  ast_copy_string(copy, value, sizeof(copy));
8835  stringp = copy;
8836  username = strsep(&stringp, "@");
8837  hostname = strsep(&stringp, "@");
8838 
8839  if (!hostname) {
8840  ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
8841  return -1;
8842  }
8843 
8844  stringp = username;
8845  username = strsep(&stringp, ":");
8846  secret = strsep(&stringp, ":");
8847  stringp = hostname;
8848  hostname = strsep(&stringp, ":");
8849  porta = strsep(&stringp, ":");
8850 
8851  if (porta && !atoi(porta)) {
8852  ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
8853  return -1;
8854  }
8855 
8856  return iax2_append_register(hostname, username, secret, porta);
8857 }
8858 
8859 
8860 static void register_peer_exten(struct iax2_peer *peer, int onoff)
8861 {
8862  char multi[256];
8863  char *stringp, *ext;
8864  if (!ast_strlen_zero(regcontext)) {
8865  ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
8866  stringp = multi;
8867  while((ext = strsep(&stringp, "&"))) {
8868  if (onoff) {
8869  if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
8870  ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
8871  "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
8872  } else
8874  }
8875  }
8876 }
8877 static void prune_peers(void);
8878 
8879 static void unlink_peer(struct iax2_peer *peer)
8880 {
8881  if (peer->expire > -1) {
8882  if (!AST_SCHED_DEL(sched, peer->expire)) {
8883  peer->expire = -1;
8884  peer_unref(peer);
8885  }
8886  }
8887 
8888  if (peer->pokeexpire > -1) {
8889  if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
8890  peer->pokeexpire = -1;
8891  peer_unref(peer);
8892  }
8893  }
8894 
8895  ao2_unlink(peers, peer);
8896 }
8897 
8898 static void __expire_registry(const void *data)
8899 {
8900  struct iax2_peer *peer = (struct iax2_peer *) data;
8901  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
8902 
8903  if (!peer)
8904  return;
8905  if (peer->expire == -1) {
8906  /* Removed already (possibly through CLI), ignore */
8907  return;
8908  }
8909 
8910  peer->expire = -1;
8911 
8912  ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
8914  realtime_update_peer(peer->name, &peer->addr, 0);
8916  blob = ast_json_pack("{s: s, s: s}",
8917  "peer_status", "Unregistered",
8918  "cause", "Expired");
8920  /* modify entry in peercnts table as _not_ registered */
8921  peercnt_modify((unsigned char) 0, 0, &peer->addr);
8922  /* Reset the address */
8923  ast_sockaddr_setnull(&peer->addr);
8924  /* Reset expiry value */
8925  peer->expiry = min_reg_expire;
8926  if (!ast_test_flag64(peer, IAX_TEMPONLY))
8927  ast_db_del("IAX/Registry", peer->name);
8928  register_peer_exten(peer, 0);
8929  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
8930  if (iax2_regfunk)
8931  iax2_regfunk(peer->name, 0);
8932 
8933  if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
8934  unlink_peer(peer);
8935 
8936  peer_unref(peer);
8937 }
8938 
8939 static int expire_registry(const void *data)
8940 {
8941 #ifdef SCHED_MULTITHREADED
8943 #endif
8944  __expire_registry(data);
8945  return 0;
8946 }
8947 
8948 static void reg_source_db(struct iax2_peer *p)
8949 {
8950  char data[80];
8951  char *expiry;
8952 
8953  if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
8954  return;
8955  }
8956 
8957  expiry = strrchr(data, ':');
8958  if (!expiry) {
8959  ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
8960  return;
8961  }
8962  *expiry++ = '\0';
8963 
8964  if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
8965  ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
8966  return;
8967  }
8968 
8969  p->expiry = atoi(expiry);
8970 
8971  ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
8973 
8974  iax2_poke_peer(p, 0);
8975  if (p->expire > -1) {
8976  if (!AST_SCHED_DEL(sched, p->expire)) {
8977  p->expire = -1;
8978  peer_unref(p);
8979  }
8980  }
8981 
8982  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
8983 
8984  p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
8985  if (p->expire == -1) {
8986  peer_unref(p);
8987  }
8988 
8989  if (iax2_regfunk) {
8990  iax2_regfunk(p->name, 1);
8991  }
8992 
8993  register_peer_exten(p, 1);
8994 }
8995 
8996 /*!
8997  * \pre iaxsl[callno] is locked
8998  *
8999  * \note Since this function calls send_command_final(), the pvt struct for
9000  * the given call number may disappear while executing this function.
9001  */
9002 static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
9003 {
9004 
9005  /* Called from IAX thread only, with proper iaxsl lock */
9006  struct iax_ie_data ied = {
9007  .pos = 0,
9008  };
9009  struct iax2_peer *p;
9010  int msgcount;
9011  char data[80];
9012  uint16_t version;
9013  const char *peer_name;
9014  int res = -1;
9015  char *str_addr;
9016 
9017  peer_name = ast_strdupa(iaxs[callno]->peer);
9018 
9019  /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
9020  ast_mutex_unlock(&iaxsl[callno]);
9021  if (!(p = find_peer(peer_name, 1))) {
9022  ast_mutex_lock(&iaxsl[callno]);
9023  ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
9024  return -1;
9025  }
9026  ast_mutex_lock(&iaxsl[callno]);
9027  if (!iaxs[callno])
9028  goto return_unref;
9029 
9031  if (!ast_sockaddr_isnull(addr)) {
9032  time_t nowtime;
9033  time(&nowtime);
9034  realtime_update_peer(peer_name, addr, nowtime);
9035  } else {
9036  realtime_update_peer(peer_name, addr, 0);
9037  }
9038  }
9039 
9040  /* treat an unspecified refresh interval as the minimum */
9041  if (!refresh) {
9042  refresh = min_reg_expire;
9043  }
9044  if (refresh > max_reg_expire) {
9045  ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9046  p->name, max_reg_expire, refresh);
9047  p->expiry = max_reg_expire;
9048  } else if (refresh < min_reg_expire) {
9049  ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
9050  p->name, min_reg_expire, refresh);
9051  p->expiry = min_reg_expire;
9052  } else {
9053  p->expiry = refresh;
9054  }
9055 
9056  if (ast_sockaddr_cmp(&p->addr, addr)) {
9057  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
9058 
9059  if (iax2_regfunk) {
9060  iax2_regfunk(p->name, 1);
9061  }
9062 
9063  /* modify entry in peercnts table as _not_ registered */
9064  peercnt_modify((unsigned char) 0, 0, &p->addr);
9065 
9066  /* Stash the IP address from which they registered */
9067  ast_sockaddr_copy(&p->addr, addr);
9068 
9069  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
9070 
9071  snprintf(data, sizeof(data), "%s:%d", ast_sockaddr_stringify(addr), p->expiry);
9072 
9073  if (!ast_test_flag64(p, IAX_TEMPONLY) && !ast_sockaddr_isnull(addr)) {
9074  ast_db_put("IAX/Registry", p->name, data);
9075  ast_verb(3, "Registered IAX2 '%s' (%s) at %s\n",
9076  p->name,
9077  ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED",
9078  ast_sockaddr_stringify(addr));
9080  blob = ast_json_pack("{s: s, s: s, s: i}",
9081  "peer_status", "Registered",
9082  "address", str_addr,
9083  "port", ast_sockaddr_port(addr));
9084  register_peer_exten(p, 1);
9085  ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9086  } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
9087  ast_verb(3, "Unregistered IAX2 '%s' (%s)\n",
9088  p->name,
9089  ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
9091  blob = ast_json_pack("{s: s}",
9092  "peer_status", "Unregistered");
9093  register_peer_exten(p, 0);
9094  ast_db_del("IAX/Registry", p->name);
9095  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", p->name); /* Activate notification */
9096  }
9097 
9099 
9100  /* Update the host */
9101  /* Verify that the host is really there */
9102  iax2_poke_peer(p, callno);
9103  }
9104 
9105  /* modify entry in peercnts table as registered */
9106  if (p->maxcallno) {
9107  peercnt_modify((unsigned char) 1, p->maxcallno, &p->addr);
9108  }
9109 
9110  /* Make sure our call still exists, an INVAL at the right point may make it go away */
9111  if (!iaxs[callno]) {
9112  res = -1;
9113  goto return_unref;
9114  }
9115 
9116  /* Store socket fd */
9117  p->sockfd = fd;
9118  /* Setup the expiry */
9119  if (p->expire > -1) {
9120  if (!AST_SCHED_DEL(sched, p->expire)) {
9121  p->expire = -1;
9122  peer_unref(p);
9123  }
9124  }
9125 
9126  if (p->expiry && !ast_sockaddr_isnull(addr)) {
9127  p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
9128  if (p->expire == -1)
9129  peer_unref(p);
9130  }
9133  if (!ast_sockaddr_isnull(addr)) {
9134  struct ast_sockaddr peer_addr;
9135 
9136  ast_sockaddr_copy(&peer_addr, &p->addr);
9137 
9139  iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
9140  if (!ast_strlen_zero(p->mailbox)) {
9141  int new, old;
9142  RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
9143 
9145  if (msg) {
9146  struct ast_mwi_state *mwi_state = stasis_message_data(msg);
9147  new = mwi_state->new_msgs;
9148  old = mwi_state->old_msgs;
9149  } else { /* Fall back on checking the mailbox directly */
9150  ast_app_inboxcount(p->mailbox, &new, &old);
9151  }
9152 
9153  if (new > 255) {
9154  new = 255;
9155  }
9156  if (old > 255) {
9157  old = 255;
9158  }
9159  msgcount = (old << 8) | new;
9160 
9161  iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
9162  }
9163  if (ast_test_flag64(p, IAX_HASCALLERID)) {
9166  }
9167  }
9168  if (iax_firmware_get_version(devtype, &version)) {
9169  iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
9170  }
9171 
9172  res = 0;
9173 
9174 return_unref:
9175  peer_unref(p);
9176 
9177  return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
9178 }
9179 
9180 static int registry_authrequest(int callno)
9181 {
9182  struct iax_ie_data ied;
9183  struct iax2_peer *p;
9184  char challenge[10];
9185  const char *peer_name;
9186  int sentauthmethod;
9187 
9188  peer_name = ast_strdupa(iaxs[callno]->peer);
9189 
9190  /* SLD: third call to find_peer in registration */
9191  ast_mutex_unlock(&iaxsl[callno]);
9192  if ((p = find_peer(peer_name, 1))) {
9194  }
9195 
9196  ast_mutex_lock(&iaxsl[callno]);
9197  if (!iaxs[callno])
9198  goto return_unref;
9199 
9200  memset(&ied, 0, sizeof(ied));
9201  /* The selection of which delayed reject is sent may leak information,
9202  * if it sets a static response. For example, if a host is known to only
9203  * use MD5 authentication, then an RSA response would indicate that the
9204  * peer does not exist, and vice-versa.
9205  * Therefore, we use whatever the last peer used (which may vary over the
9206  * course of a server, which should leak minimal information). */
9207  sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : IAX_AUTH_MD5;
9208  if (!p) {
9209  iaxs[callno]->authmethods = sentauthmethod;
9210  }
9211  iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
9212  if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
9213  /* Build the challenge */
9214  snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
9215  ast_string_field_set(iaxs[callno], challenge, challenge);
9216  iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
9217  }
9218  iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
9219 
9220 return_unref:
9221  if (p) {
9222  peer_unref(p);
9223  }
9224 
9225  return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
9226 }
9227 
9228 static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
9229 {
9230  struct iax2_registry *reg;
9231  /* Start pessimistic */
9232  struct iax_ie_data ied;
9233  char peer[256] = "";
9234  char challenge[256] = "";
9235  int res;
9236  int authmethods = 0;
9237  if (ies->authmethods)
9238  authmethods = ies->authmethods;
9239  if (ies->username)
9240  ast_copy_string(peer, ies->username, sizeof(peer));
9241  if (ies->challenge)
9242  ast_copy_string(challenge, ies->challenge, sizeof(challenge));
9243  memset(&ied, 0, sizeof(ied));
9244  reg = iaxs[callno]->reg;
9245  if (reg) {
9246 
9247  if (ast_sockaddr_cmp(&reg->addr, addr)) {
9248  ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_sockaddr_stringify(addr));
9249  return -1;
9250  }
9251  if (ast_strlen_zero(reg->secret)) {
9252  ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
9253  reg->regstate = REG_STATE_NOAUTH;
9254  return -1;
9255  }
9258  if (reg->secret[0] == '[') {
9259  char tmpkey[256];
9260  ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
9261  tmpkey[strlen(tmpkey) - 1] = '\0';
9262  res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, addr, NULL);
9263  } else
9264  res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, addr, NULL);
9265  if (!res) {
9267  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
9268  return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9269  } else
9270  return -1;
9271  ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
9272  } else
9273  ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
9274  return -1;
9275 }
9276 
9277 static void stop_stuff(int callno)
9278 {
9279  iax2_destroy_helper(iaxs[callno]);
9280 }
9281 
9282 static void __auth_reject(const void *nothing)
9283 {
9284  /* Called from IAX thread only, without iaxs lock */
9285  int callno = (int)(long)(nothing);
9286  struct iax_ie_data ied;
9287  ast_mutex_lock(&iaxsl[callno]);
9288  if (iaxs[callno]) {
9289  memset(&ied, 0, sizeof(ied));
9290  if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
9291  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
9293  } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
9294  iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
9296  }
9297  send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
9298  }
9299  ast_mutex_unlock(&iaxsl[callno]);
9300 }
9301 
9302 static int auth_reject(const void *data)
9303 {
9304  int callno = (int)(long)(data);
9305  ast_mutex_lock(&iaxsl[callno]);
9306  if (iaxs[callno])
9307  iaxs[callno]->authid = -1;
9308  ast_mutex_unlock(&iaxsl[callno]);
9309 #ifdef SCHED_MULTITHREADED
9310  if (schedule_action(__auth_reject, data))
9311 #endif
9312  __auth_reject(data);
9313  return 0;
9314 }
9315 
9316 static int auth_fail(int callno, int failcode)
9317 {
9318  /* Schedule sending the authentication failure in one second, to prevent
9319  guessing */
9320  if (iaxs[callno]) {
9321  iaxs[callno]->authfail = failcode;
9322  if (delayreject) {
9323  iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
9324  sched, 1000, auth_reject, (void *)(long)callno);
9325  } else
9326  auth_reject((void *)(long)callno);
9327  }
9328  return 0;
9329 }
9330 
9331 static void __auto_hangup(const void *nothing)
9332 {
9333  /* Called from IAX thread only, without iaxs lock */
9334  int callno = (int)(long)(nothing);
9335  struct iax_ie_data ied;
9336  ast_mutex_lock(&iaxsl[callno]);
9337  if (iaxs[callno]) {
9338  memset(&ied, 0, sizeof(ied));
9339  iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
9341  send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
9342  }
9343  ast_mutex_unlock(&iaxsl[callno]);
9344 }
9345 
9346 static int auto_hangup(const void *data)
9347 {
9348  int callno = (int)(long)(data);
9349  ast_mutex_lock(&iaxsl[callno]);
9350  if (iaxs[callno]) {
9351  iaxs[callno]->autoid = -1;
9352  }
9353  ast_mutex_unlock(&iaxsl[callno]);
9354 #ifdef SCHED_MULTITHREADED
9355  if (schedule_action(__auto_hangup, data))
9356 #endif
9357  __auto_hangup(data);
9358  return 0;
9359 }
9360 
9361 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
9362 {
9363  struct iax_ie_data ied;
9364  /* Auto-hangup with 30 seconds of inactivity */
9365  iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9366  sched, 30000, auto_hangup, (void *)(long)callno);
9367  memset(&ied, 0, sizeof(ied));
9369  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
9371 }
9372 
9373 static int iax2_vnak(int callno)
9374 {
9375  return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
9376 }
9377 
9378 static void vnak_retransmit(int callno, int last)
9379 {
9380  struct iax_frame *f;
9381 
9382  AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
9383  /* Send a copy immediately */
9384  if (((unsigned char) (f->oseqno - last) < 128) &&
9385  (f->retries >= 0)) {
9386  send_packet(f);
9387  }
9388  }
9389 }
9390 
9391 static void __iax2_poke_peer_s(const void *data)
9392 {
9393  struct iax2_peer *peer = (struct iax2_peer *)data;
9394  iax2_poke_peer(peer, 0);
9395  peer_unref(peer);
9396 }
9397 
9398 static int iax2_poke_peer_s(const void *data)
9399 {
9400  struct iax2_peer *peer = (struct iax2_peer *)data;
9401  peer->pokeexpire = -1;
9402 #ifdef SCHED_MULTITHREADED
9404 #endif
9405  __iax2_poke_peer_s(data);
9406  return 0;
9407 }
9408 
9409 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
9410 {
9411  int res = 0;
9412  struct iax_frame *fr;
9413  struct ast_iax2_meta_hdr *meta;
9414  struct ast_iax2_meta_trunk_hdr *mth;
9415  int calls = 0;
9416 
9417  /* Point to frame */
9418  fr = (struct iax_frame *)tpeer->trunkdata;
9419  /* Point to meta data */
9420  meta = (struct ast_iax2_meta_hdr *)fr->afdata;
9421  mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
9422  if (tpeer->trunkdatalen) {
9423  /* We're actually sending a frame, so fill the meta trunk header and meta header */
9424  meta->zeros = 0;
9425  meta->metacmd = IAX_META_TRUNK;
9426  if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
9427  meta->cmddata = IAX_META_TRUNK_MINI;
9428  else
9430  mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
9431  /* And the rest of the ast_iax2 header */
9433  fr->retrans = -1;
9434  fr->transfer = 0;
9435  /* Any appropriate call will do */
9436  fr->data = fr->afdata;
9437  fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
9438  res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
9439  calls = tpeer->calls;
9440 #if 0
9441  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));
9442 #endif
9443  /* Reset transmit trunk side data */
9444  tpeer->trunkdatalen = 0;
9445  tpeer->calls = 0;
9446  }
9447  if (res < 0)
9448  return res;
9449  return calls;
9450 }
9451 
9452 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
9453 {
9454  /* Drop when trunk is about 5 seconds idle */
9455  if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
9456  return 1;
9457  return 0;
9458 }
9459 
9460 static int timing_read(int *id, int fd, short events, void *cbdata)
9461 {
9462  int res, processed = 0, totalcalls = 0;
9463  struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
9464  struct timeval now = ast_tvnow();
9465 
9466  if (iaxtrunkdebug) {
9467  ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
9468  }
9469 
9470  if (timer) {
9471  if (ast_timer_ack(timer, 1) < 0) {
9472  ast_log(LOG_ERROR, "Timer failed acknowledge\n");
9473  return 0;
9474  }
9475  }
9476 
9477  /* For each peer that supports trunking... */
9479  AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
9480  processed++;
9481  res = 0;
9482  ast_mutex_lock(&tpeer->lock);
9483  /* We can drop a single tpeer per pass. That makes all this logic
9484  substantially easier */
9485  if (!drop && iax2_trunk_expired(tpeer, &now)) {
9486  /* Take it out of the list, but don't free it yet, because it
9487  could be in use */
9489  drop = tpeer;
9490  } else {
9491  res = send_trunk(tpeer, &now);
9492  trunk_timed++;
9493  if (iaxtrunkdebug) {
9494  ast_verbose(" - Trunk peer (%s) has %d call chunk%s in transit, %u bytes backloged and has hit a high water mark of %u bytes\n",
9495  ast_sockaddr_stringify(&tpeer->addr),
9496  res,
9497  (res != 1) ? "s" : "",
9498  tpeer->trunkdatalen,
9499  tpeer->trunkdataalloc);
9500  }
9501  }
9502  totalcalls += res;
9503  res = 0;
9504  ast_mutex_unlock(&tpeer->lock);
9505  }
9508 
9509  if (drop) {
9510  ast_mutex_lock(&drop->lock);
9511  /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
9512  because by the time they could get tpeerlock, we've already grabbed it */
9513  ast_debug(1, "Dropping unused iax2 trunk peer '%s'\n", ast_sockaddr_stringify(&drop->addr));
9514  if (drop->trunkdata) {
9515  ast_free(drop->trunkdata);
9516  drop->trunkdata = NULL;
9517  }
9518  ast_mutex_unlock(&drop->lock);
9519  ast_mutex_destroy(&drop->lock);
9520  ast_free(drop);
9521  }
9522 
9523  if (iaxtrunkdebug) {
9524  ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
9525  }
9526  iaxtrunkdebug = 0;
9527 
9528  return 1;
9529 }
9530 
9531 struct dpreq_data {
9532  int callno;
9534  char callednum[AST_MAX_EXTENSION];
9535  char *callerid;
9536 };
9537 
9538 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
9539 {
9540  unsigned short dpstatus = 0;
9541  struct iax_ie_data ied1;
9542  int mm;
9543 
9544  memset(&ied1, 0, sizeof(ied1));
9545  mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
9546  /* Must be started */
9547  if (ast_exists_extension(NULL, context, callednum, 1, callerid)) {
9548  dpstatus = IAX_DPSTATUS_EXISTS;
9549  } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
9550  dpstatus = IAX_DPSTATUS_CANEXIST;
9551  } else {
9552  dpstatus = IAX_DPSTATUS_NONEXISTENT;
9553  }
9554  if (ast_ignore_pattern(context, callednum))
9555  dpstatus |= IAX_DPSTATUS_IGNOREPAT;
9556  if (mm)
9557  dpstatus |= IAX_DPSTATUS_MATCHMORE;
9558  if (!skiplock)
9559  ast_mutex_lock(&iaxsl[callno]);
9560  if (iaxs[callno]) {
9561  iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
9562  iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
9564  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
9565  }
9566  if (!skiplock)
9567  ast_mutex_unlock(&iaxsl[callno]);
9568 }
9569 
9570 static void *dp_lookup_thread(void *data)
9571 {
9572  /* Look up for dpreq */
9573  struct dpreq_data *dpr = data;
9574  dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
9575  if (dpr->callerid)
9576  ast_free(dpr->callerid);
9577  ast_free(dpr);
9578  return NULL;
9579 }
9580 
9581 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
9582 {
9583  pthread_t newthread;
9584  struct dpreq_data *dpr;
9585 
9586  if (!(dpr = ast_calloc(1, sizeof(*dpr))))
9587  return;
9588 
9589  dpr->callno = callno;
9590  ast_copy_string(dpr->context, context, sizeof(dpr->context));
9591  ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
9592  if (callerid)
9593  dpr->callerid = ast_strdup(callerid);
9594  if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
9595  ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
9596  }
9597 }
9598 
9599 static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
9600 {
9601  unsigned int ourver;
9602  char rsi[80];
9603  snprintf(rsi, sizeof(rsi), "si-%s", si);
9604  if (iax_provision_version(&ourver, rsi, 1))
9605  return 0;
9606  ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
9607  if (ourver != ver)
9608  iax2_provision(addr, sockfd, NULL, rsi, 1);
9609  return 0;
9610 }
9611 
9612 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
9613 {
9614  jb_info stats;
9615  jb_getinfo(pvt->jb, &stats);
9616 
9617  memset(iep, 0, sizeof(*iep));
9618 
9620  if(stats.frames_in == 0) stats.frames_in = 1;
9621  iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
9623  iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
9626 }
9627 
9628 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
9629 {
9630  iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
9631  iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
9632  iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
9633  iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
9634  iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
9635  iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
9636  iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
9637 }
9638 
9639 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
9640 {
9641  int i;
9642  unsigned int length, offset = 0;
9643  char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
9644 
9645  for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
9646  length = ies->ospblocklength[i];
9647  if (length != 0) {
9648  if (length > IAX_MAX_OSPBLOCK_SIZE) {
9649  /* OSP token block length wrong, clear buffer */
9650  offset = 0;
9651  break;
9652  } else {
9653  memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
9654  offset += length;
9655  }
9656  } else {
9657  break;
9658  }
9659  }
9660  *(full_osptoken + offset) = '\0';
9661  if (strlen(full_osptoken) != offset) {
9662  /* OSP token length wrong, clear buffer */
9663  *full_osptoken = '\0';
9664  }
9665 
9666  ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
9667 }
9668 
9669 static void log_jitterstats(unsigned short callno)
9670 {
9671  int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
9672  jb_info jbinfo;
9673 
9674  ast_mutex_lock(&iaxsl[callno]);
9675  if (iaxs[callno] && iaxs[callno]->owner && ast_channel_name(iaxs[callno]->owner)) {
9676  if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
9677  jb_getinfo(iaxs[callno]->jb, &jbinfo);
9678  localjitter = jbinfo.jitter;
9679  localdelay = jbinfo.current - jbinfo.min;
9680  locallost = jbinfo.frames_lost;
9681  locallosspct = jbinfo.losspct/1000;
9682  localdropped = jbinfo.frames_dropped;
9683  localooo = jbinfo.frames_ooo;
9684  localpackets = jbinfo.frames_in;
9685  }
9686  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",
9687  ast_channel_name(iaxs[callno]->owner),
9688  iaxs[callno]->pingtime,
9689  localjitter,
9690  localdelay,
9691  locallost,
9692  locallosspct,
9693  localdropped,
9694  localooo,
9695  localpackets,
9696  iaxs[callno]->remote_rr.jitter,
9697  iaxs[callno]->remote_rr.delay,
9698  iaxs[callno]->remote_rr.losscnt,
9699  iaxs[callno]->remote_rr.losspct/1000,
9700  iaxs[callno]->remote_rr.dropped,
9701  iaxs[callno]->remote_rr.ooo,
9702  iaxs[callno]->remote_rr.packets);
9703  }
9704  ast_mutex_unlock(&iaxsl[callno]);
9705 }
9706 
9707 static int socket_process(struct iax2_thread *thread);
9708 
9709 /*!
9710  * \brief Handle any deferred full frames for this thread
9711  */
9712 static void handle_deferred_full_frames(struct iax2_thread *thread)
9713 {
9714  struct iax2_pkt_buf *pkt_buf;
9715 
9716  ast_mutex_lock(&thread->lock);
9717 
9718  while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
9719  ast_mutex_unlock(&thread->lock);
9720 
9721  thread->buf = pkt_buf->buf;
9722  thread->buf_len = pkt_buf->len;
9723  thread->buf_size = pkt_buf->len + 1;
9724 
9725  socket_process(thread);
9726 
9727  thread->buf = NULL;
9728  ast_free(pkt_buf);
9729 
9730  ast_mutex_lock(&thread->lock);
9731  }
9732 
9733  ast_mutex_unlock(&thread->lock);
9734 }
9735 
9736 /*!
9737  * \brief Queue the last read full frame for processing by a certain thread
9738  *
9739  * If there are already any full frames queued, they are sorted
9740  * by sequence number.
9741  */
9742 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
9743 {
9744  struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
9745  struct ast_iax2_full_hdr *fh, *cur_fh;
9746 
9747  if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
9748  return;
9749 
9750  pkt_buf->len = from_here->buf_len;
9751  memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
9752 
9753  fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
9754  ast_mutex_lock(&to_here->lock);
9755  AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
9756  cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
9757  if (fh->oseqno < cur_fh->oseqno) {
9758  AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
9759  break;
9760  }
9761  }
9763 
9764  if (!cur_pkt_buf)
9765  AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
9766 
9767  to_here->iostate = IAX_IOSTATE_READY;
9768  ast_cond_signal(&to_here->cond);
9769 
9770  ast_mutex_unlock(&to_here->lock);
9771 }
9772 
9773 static int socket_read(int *id, int fd, short events, void *cbdata)
9774 {
9775  struct iax2_thread *thread;
9776  time_t t;
9777  static time_t last_errtime = 0;
9778  struct ast_iax2_full_hdr *fh;
9779 
9780  if (!(thread = find_idle_thread())) {
9781  time(&t);
9782  if (t != last_errtime) {
9783  last_errtime = t;
9784  ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
9785  }
9786  usleep(1);
9787  return 1;
9788  }
9789 
9790  thread->iofd = fd;
9791  thread->buf_len = ast_recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, &thread->ioaddr);
9792  thread->buf_size = sizeof(thread->readbuf);
9793  thread->buf = thread->readbuf;
9794  if (thread->buf_len < 0) {
9795  if (errno != ECONNREFUSED && errno != EAGAIN)
9796  ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
9797  handle_error();
9798  thread->iostate = IAX_IOSTATE_IDLE;
9799  signal_condition(&thread->lock, &thread->cond);
9800  return 1;
9801  }
9802  if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
9803  thread->iostate = IAX_IOSTATE_IDLE;
9804  signal_condition(&thread->lock, &thread->cond);
9805  return 1;
9806  }
9807 
9808  /* Determine if this frame is a full frame; if so, and any thread is currently
9809  processing a full frame for the same callno from this peer, then drop this
9810  frame (and the peer will retransmit it) */
9811  fh = (struct ast_iax2_full_hdr *) thread->buf;
9812  if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
9813  struct iax2_thread *cur = NULL;
9814  uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
9815 
9818  if ((cur->ffinfo.callno == callno) &&
9819  !ast_sockaddr_cmp_addr(&cur->ffinfo.addr, &thread->ioaddr))
9820  break;
9821  }
9822  if (cur) {
9823  /* we found another thread processing a full frame for this call,
9824  so queue it up for processing later. */
9825  defer_full_frame(thread, cur);
9827  thread->iostate = IAX_IOSTATE_IDLE;
9828  signal_condition(&thread->lock, &thread->cond);
9829  return 1;
9830  } else {
9831  /* this thread is going to process this frame, so mark it */
9832  thread->ffinfo.callno = callno;
9833  ast_sockaddr_copy(&thread->ffinfo.addr, &thread->ioaddr);
9834  thread->ffinfo.type = fh->type;
9835  thread->ffinfo.csub = fh->csub;
9837  }
9839  }
9840 
9841  /* Mark as ready and send on its way */
9842  thread->iostate = IAX_IOSTATE_READY;
9843 #ifdef DEBUG_SCHED_MULTITHREAD
9844  ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
9845 #endif
9846  signal_condition(&thread->lock, &thread->cond);
9847 
9848  return 1;
9849 }
9850 
9851 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd,
9852  struct iax_frame *fr)
9853 {
9854  unsigned char metatype;
9855  struct ast_iax2_meta_trunk_mini *mtm;
9856  struct ast_iax2_meta_trunk_hdr *mth;
9857  struct ast_iax2_meta_trunk_entry *mte;
9858  struct iax2_trunk_peer *tpeer;
9859  unsigned int ts;
9860  void *ptr;
9861  struct timeval rxtrunktime;
9862  struct ast_frame f = { 0, };
9863 
9864  if (packet_len < sizeof(*meta)) {
9865  ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a meta frame but is too short\n",
9866  ast_sockaddr_stringify(addr));
9867  return 1;
9868  }
9869 
9870  if (meta->metacmd != IAX_META_TRUNK)
9871  return 1;
9872 
9873  if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
9874  ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
9875  (int) (sizeof(*meta) + sizeof(*mth)));
9876  return 1;
9877  }
9878  mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
9879  ts = ntohl(mth->ts);
9880  metatype = meta->cmddata;
9881  packet_len -= (sizeof(*meta) + sizeof(*mth));
9882  ptr = mth->data;
9883  tpeer = find_tpeer(addr, sockfd);
9884  if (!tpeer) {
9885  ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s': No matching peer\n",
9886  ast_sockaddr_stringify(addr));
9887  return 1;
9888  }
9889  tpeer->trunkact = ast_tvnow();
9890  if (!ts || ast_tvzero(tpeer->rxtrunktime))
9891  tpeer->rxtrunktime = tpeer->trunkact;
9892  rxtrunktime = tpeer->rxtrunktime;
9893  ast_mutex_unlock(&tpeer->lock);
9894  while (packet_len >= sizeof(*mte)) {
9895  /* Process channels */
9896  unsigned short callno, trunked_ts, len;
9897 
9898  if (metatype == IAX_META_TRUNK_MINI) {
9899  mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
9900  ptr += sizeof(*mtm);
9901  packet_len -= sizeof(*mtm);
9902  len = ntohs(mtm->len);
9903  callno = ntohs(mtm->mini.callno);
9904  trunked_ts = ntohs(mtm->mini.ts);
9905  } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
9906  mte = (struct ast_iax2_meta_trunk_entry *)ptr;
9907  ptr += sizeof(*mte);
9908  packet_len -= sizeof(*mte);
9909  len = ntohs(mte->len);
9910  callno = ntohs(mte->callno);
9911  trunked_ts = 0;
9912  } else {
9913  ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s': dropping\n", ast_sockaddr_stringify(addr));
9914  break;
9915  }
9916  /* Stop if we don't have enough data */
9917  if (len > packet_len)
9918  break;
9919  fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, addr, NEW_PREVENT, sockfd, 0);
9920  if (!fr->callno)
9921  continue;
9922 
9923  /* If it's a valid call, deliver the contents. If not, we
9924  drop it, since we don't have a scallno to use for an INVAL */
9925  /* Process as a mini frame */
9926  memset(&f, 0, sizeof(f));
9928  if (!iaxs[fr->callno]) {
9929  /* drop it */
9930  } else if (iaxs[fr->callno]->voiceformat == 0) {
9931  ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
9932  iax2_vnak(fr->callno);
9933  } else {
9935  f.datalen = len;
9936  if (f.datalen >= 0) {
9937  if (f.datalen)
9938  f.data.ptr = ptr;
9939  else
9940  f.data.ptr = NULL;
9941  if (trunked_ts)
9942  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
9943  else
9944  fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
9945  /* Don't pass any packets until we're started */
9946  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
9947  struct iax_frame *duped_fr;
9948 
9949  /* Common things */
9950  f.src = "IAX2";
9951  f.mallocd = 0;
9952  f.offset = 0;
9953  if (f.datalen && (f.frametype == AST_FRAME_VOICE))
9955  else
9956  f.samples = 0;
9957  fr->outoforder = 0;
9958  iax_frame_wrap(fr, &f);
9959  duped_fr = iaxfrdup2(fr);
9960  if (duped_fr)
9961  schedule_delivery(duped_fr, 1, 1, &fr->ts);
9962  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
9963  iaxs[fr->callno]->last = fr->ts;
9964  }
9965  } else {
9966  ast_log(LOG_WARNING, "Datalen < 0?\n");
9967  }
9968  }
9969  ast_mutex_unlock(&iaxsl[fr->callno]);
9970  ptr += len;
9971  packet_len -= len;
9972  }
9973 
9974  return 1;
9975 }
9976 
9977 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9978 {
9979  struct ast_datastore *variablestore;
9980  AST_LIST_HEAD(, ast_var_t) *varlist;
9981  struct ast_var_t *var;
9982 
9983  if (!chan) {
9984  ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
9985  return -1;
9986  }
9987 
9988  variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
9989  if (!variablestore) {
9990  *buf = '\0';
9991  return 0;
9992  }
9993  varlist = variablestore->data;
9994 
9995  AST_LIST_LOCK(varlist);
9996  AST_LIST_TRAVERSE(varlist, var, entries) {
9997  if (strcmp(var->name, data) == 0) {
9998  ast_copy_string(buf, var->value, len);
9999  break;
10000  }
10001  }
10002  AST_LIST_UNLOCK(varlist);
10003  return 0;
10004 }
10005 
10006 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
10007 {
10008  struct ast_datastore *variablestore;
10009  AST_LIST_HEAD(, ast_var_t) *varlist;
10010  struct ast_var_t *var;
10011 
10012  if (!chan) {
10013  ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
10014  return -1;
10015  }
10016 
10017  variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
10018  if (!variablestore) {
10019  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10020  if (!variablestore) {
10021  ast_log(LOG_ERROR, "Memory allocation error\n");
10022  return -1;
10023  }
10024  varlist = ast_calloc(1, sizeof(*varlist));
10025  if (!varlist) {
10026  ast_datastore_free(variablestore);
10027  ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10028  return -1;
10029  }
10030 
10031  AST_LIST_HEAD_INIT(varlist);
10032  variablestore->data = varlist;
10033  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10034  ast_channel_datastore_add(chan, variablestore);
10035  } else
10036  varlist = variablestore->data;
10037 
10038  AST_LIST_LOCK(varlist);
10039  AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
10040  if (strcmp(var->name, data) == 0) {
10042  ast_var_delete(var);
10043  break;
10044  }
10045  }
10047  var = ast_var_assign(data, value);
10048  if (var)
10049  AST_LIST_INSERT_TAIL(varlist, var, entries);
10050  else
10051  ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
10052  AST_LIST_UNLOCK(varlist);
10053  return 0;
10054 }
10055 
10057  .name = "IAXVAR",
10058  .read = acf_iaxvar_read,
10059  .write = acf_iaxvar_write,
10060 };
10061 
10062 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
10063 {
10064  iax2_lock_owner(callno);
10065  if (iaxs[callno] && iaxs[callno]->owner) {
10066  struct ast_channel *owner;
10067  const char *name;
10068 
10069  owner = iaxs[callno]->owner;
10070  if (causecode) {
10071  ast_channel_hangupcause_set(owner, causecode);
10072  }
10073  name = ast_strdupa(ast_channel_name(owner));
10074  ast_channel_ref(owner);
10075  ast_channel_unlock(owner);
10076  ast_mutex_unlock(&iaxsl[callno]);
10077  ast_set_hangupsource(owner, name, 0);
10078  ast_channel_unref(owner);
10079  ast_mutex_lock(&iaxsl[callno]);
10080  }
10081 }
10082 
10083 static int socket_process_helper(struct iax2_thread *thread)
10084 {
10085  struct ast_sockaddr addr;
10086  int res;
10087  int updatehistory=1;
10088  int new = NEW_PREVENT;
10089  int dcallno = 0;
10090  char decrypted = 0;
10091  struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
10092  struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
10093  struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
10094  struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
10095  struct iax_frame *fr;
10096  struct iax_frame *cur;
10097  struct ast_frame f = { 0, };
10098  struct ast_channel *c = NULL;
10099  struct iax2_dpcache *dp;
10100  struct iax2_peer *peer;
10101  struct iax_ies ies;
10102  struct iax_ie_data ied0, ied1;
10104  int fd;
10105  int exists;
10106  int minivid = 0;
10107  char empty[32]=""; /* Safety measure */
10108  struct iax_frame *duped_fr;
10109  char host_pref_buf[128];
10110  char caller_pref_buf[128];
10111  struct iax2_codec_pref pref;
10112  char *using_prefs = "mine";
10113 
10114  /* allocate an iax_frame with 4096 bytes of data buffer */
10115  fr = ast_alloca(sizeof(*fr) + 4096);
10116  memset(fr, 0, sizeof(*fr));
10117  fr->afdatalen = 4096; /* From ast_alloca() above */
10118 
10119  /* Copy frequently used parameters to the stack */
10120  res = thread->buf_len;
10121  fd = thread->iofd;
10122  ast_sockaddr_copy(&addr, &thread->ioaddr);
10123 
10124  if (res < sizeof(*mh)) {
10125  ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
10126  return 1;
10127  }
10128  if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
10129  if (res < sizeof(*vh)) {
10130  ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a video frame but is too short\n",
10131  ast_sockaddr_stringify(&addr));
10132  return 1;
10133  }
10134 
10135  /* This is a video frame, get call number */
10136  fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &addr, new, fd, 0);
10137  minivid = 1;
10138  } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
10139  return socket_process_meta(res, meta, &addr, fd, fr);
10140 
10141 #ifdef DEBUG_SUPPORT
10142  if (res >= sizeof(*fh))
10143  iax_outputframe(NULL, fh, 1, &addr, res - sizeof(*fh));
10144 #endif
10145  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10146  if (res < sizeof(*fh)) {
10147  ast_log(LOG_WARNING, "Rejecting packet from '%s' that is flagged as a full frame but is too short\n",
10148  ast_sockaddr_stringify(&addr));
10149  return 1;
10150  }
10151 
10152  /* Get the destination call number */
10153  dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
10154 
10155 
10156  /* check to make sure this full frame isn't encrypted before we attempt
10157  * to look inside of it. If it is encrypted, decrypt it first. Its ok if the
10158  * callno is not found here, that just means one hasn't been allocated for
10159  * this connection yet. */
10160  if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, NEW_PREVENT, fd, 1))) {
10161  ast_mutex_lock(&iaxsl[fr->callno]);
10162  if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
10163  if (decrypt_frame(fr->callno, fh, &f, &res)) {
10164  ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10165  ast_mutex_unlock(&iaxsl[fr->callno]);
10166  return 1;
10167  }
10168  decrypted = 1;
10169  }
10170  ast_mutex_unlock(&iaxsl[fr->callno]);
10171  }
10172 
10173  /* Retrieve the type and subclass */
10174  f.frametype = fh->type;
10175  if (f.frametype == AST_FRAME_VIDEO) {
10177  if ((fh->csub >> 6) & 0x1) {
10178  f.subclass.frame_ending = 1;
10179  }
10180  } else if (f.frametype == AST_FRAME_VOICE) {
10182  } else {
10184  }
10185 
10186  /* Deal with POKE/PONG without allocating a callno */
10188  /* Reply back with a PONG, but don't care about the result. */
10189  send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10190  return 1;
10191  } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10192  /* Ignore */
10193  return 1;
10194  }
10195 
10196  f.datalen = res - sizeof(*fh);
10197  if (f.datalen) {
10198  if (f.frametype == AST_FRAME_IAX) {
10199  if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10200  ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_sockaddr_stringify(&addr));
10202  return 1;
10203  }
10204  f.data.ptr = NULL;
10205  f.datalen = 0;
10206  } else {
10207  f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10208  memset(&ies, 0, sizeof(ies));
10209  }
10210  } else {
10211  if (f.frametype == AST_FRAME_IAX)
10212  f.data.ptr = NULL;
10213  else
10214  f.data.ptr = empty;
10215  memset(&ies, 0, sizeof(ies));
10216  }
10217 
10218  if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10219  /* only set NEW_ALLOW if calltoken checks out */
10220  if (handle_call_token(fh, &ies, &addr, fd)) {
10222  return 1;
10223  }
10224 
10225  if (ies.calltoken && ies.calltokendata) {
10226  /* if we've gotten this far, and the calltoken ie data exists,
10227  * then calltoken validation _MUST_ have taken place. If calltoken
10228  * data is provided, it is always validated reguardless of any
10229  * calltokenoptional or requirecalltoken options */
10231  } else {
10232  new = NEW_ALLOW;
10233  }
10234  }
10235  } else {
10236  /* Don't know anything about it yet */
10238  f.subclass.integer = 0;
10239  memset(&ies, 0, sizeof(ies));
10240  }
10241 
10242  if (!fr->callno) {
10243  int check_dcallno = 0;
10244 
10245  /*
10246  * We enforce accurate destination call numbers for ACKs. This forces the other
10247  * end to know the destination call number before call setup can complete.
10248  *
10249  * Discussed in the following thread:
10250  * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
10251  */
10252 
10253  if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10254  check_dcallno = 1;
10255  }
10256 
10257  if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &addr, new, fd, check_dcallno))) {
10259  send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10261  send_apathetic_reply(1, ntohs(fh->scallno), &addr, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10262  }
10264  return 1;
10265  }
10266  }
10267 
10268  if (fr->callno > 0) {
10269  ast_callid mount_callid;
10270  ast_mutex_lock(&iaxsl[fr->callno]);
10271  if (iaxs[fr->callno] && ((mount_callid = iax_pvt_callid_get(fr->callno)))) {
10272  /* Bind to thread */
10273  ast_callid_threadassoc_add(mount_callid);
10274  }
10275  }
10276 
10277  if (!fr->callno || !iaxs[fr->callno]) {
10278  /* A call arrived for a nonexistent destination. Unless it's an "inval"
10279  frame, reply with an inval */
10280  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10281  /* We can only raw hangup control frames */
10282  if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10286  (f.frametype != AST_FRAME_IAX))
10287  raw_hangup(&addr, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10288  fd);
10289  }
10290  if (fr->callno > 0){
10291  ast_mutex_unlock(&iaxsl[fr->callno]);
10292  }
10294  return 1;
10295  }
10296  if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10297  if (decrypt_frame(fr->callno, fh, &f, &res)) {
10298  ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10300  ast_mutex_unlock(&iaxsl[fr->callno]);
10301  return 1;
10302  }
10303  decrypted = 1;
10304  }
10305 
10306 #ifdef DEBUG_SUPPORT
10307  if (decrypted) {
10308  iax_outputframe(NULL, fh, 3, &addr, res - sizeof(*fh));
10309  }
10310 #endif
10311 
10312  if (iaxs[fr->callno]->owner && fh->type == AST_FRAME_IAX &&
10313  (fh->csub == IAX_COMMAND_HANGUP
10314  || fh->csub == IAX_COMMAND_REJECT
10315  || fh->csub == IAX_COMMAND_REGREJ
10316  || fh->csub == IAX_COMMAND_TXREJ)) {
10317  struct ast_control_pvt_cause_code *cause_code;
10318  int data_size = sizeof(*cause_code);
10319  char subclass[40] = "";
10320 
10321  /* get subclass text */
10322  iax_frame_subclass2str(fh->csub, subclass, sizeof(subclass));
10323 
10324  /* add length of "IAX2 " */
10325  data_size += 5;
10326  /* for IAX hangup frames, add length of () and number */
10327  data_size += 3;
10328  if (ies.causecode > 9) {
10329  data_size++;
10330  }
10331  if (ies.causecode > 99) {
10332  data_size++;
10333  }
10334  /* add length of subclass */
10335  data_size += strlen(subclass);
10336 
10337  cause_code = ast_alloca(data_size);
10338  memset(cause_code, 0, data_size);
10340 
10341  cause_code->ast_cause = ies.causecode;
10342  snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "IAX2 %s(%d)", subclass, ies.causecode);
10343 
10344  iax2_lock_owner(fr->callno);
10345  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10346  ast_queue_control_data(iaxs[fr->callno]->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
10347  ast_channel_hangupcause_hash_set(iaxs[fr->callno]->owner, cause_code, data_size);
10348  ast_channel_unlock(iaxs[fr->callno]->owner);
10349  }
10350  if (!iaxs[fr->callno]) {
10352  ast_mutex_unlock(&iaxsl[fr->callno]);
10353  return 1;
10354  }
10355  }
10356 
10357  /* count this frame */
10358  iaxs[fr->callno]->frames_received++;
10359 
10360  if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) && !minivid &&
10361  f.subclass.integer != IAX_COMMAND_TXCNT && /* for attended transfer */
10362  f.subclass.integer != IAX_COMMAND_TXACC) { /* for attended transfer */
10363  unsigned short new_peercallno;
10364 
10365  new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10366  if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10367  if (iaxs[fr->callno]->peercallno) {
10368  remove_by_peercallno(iaxs[fr->callno]);
10369  }
10370  iaxs[fr->callno]->peercallno = new_peercallno;
10371  store_by_peercallno(iaxs[fr->callno]);
10372  }
10373  }
10374  if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10375  if (iaxdebug)
10376  ast_debug(1, "Received packet %d, (%u, %d)\n", fh->oseqno, f.frametype, f.subclass.integer);
10377  /* Check if it's out of order (and not an ACK or INVAL) */
10378  fr->oseqno = fh->oseqno;
10379  fr->iseqno = fh->iseqno;
10380  fr->ts = ntohl(fh->ts);
10381 #ifdef IAXTESTS
10382  if (test_resync) {
10383  ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10384  fr->ts += test_resync;
10385  }
10386 #endif /* IAXTESTS */
10387 #if 0
10388  if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10389  ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10390  (f.subclass == IAX_COMMAND_NEW ||
10393  f.subclass == IAX_COMMAND_REJECT)) ) )
10394 #endif
10395  if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10396  updatehistory = 0;
10397  if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10398  (iaxs[fr->callno]->iseqno ||
10400  (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10401  (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10402  (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10404  (f.frametype != AST_FRAME_IAX))) {
10405  if (
10406  ((f.subclass.integer != IAX_COMMAND_ACK) &&
10409  (f.subclass.integer != IAX_COMMAND_TXREADY) && /* for attended transfer */
10410  (f.subclass.integer != IAX_COMMAND_TXREL) && /* for attended transfer */
10411  (f.subclass.integer != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
10413  (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10414  (f.frametype != AST_FRAME_IAX)) {
10415  /* If it's not an ACK packet, it's out of order. */
10416  ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %u, subclass = %d)\n",
10417  iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10418  /* Check to see if we need to request retransmission,
10419  * and take sequence number wraparound into account */
10420  if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10421  /* If we've already seen it, ack it XXX There's a border condition here XXX */
10422  if ((f.frametype != AST_FRAME_IAX) ||
10424  ast_debug(1, "Acking anyway\n");
10425  /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
10426  we have anything to send, we'll retransmit and get an ACK back anyway XXX */
10428  }
10429  } else {
10430  /* Send a VNAK requesting retransmission */
10431  iax2_vnak(fr->callno);
10432  }
10434  ast_mutex_unlock(&iaxsl[fr->callno]);
10435  return 1;
10436  }
10437  } else {
10438  /* Increment unless it's an ACK or VNAK */
10439  if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10443  (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10444  (f.frametype != AST_FRAME_IAX))
10445  iaxs[fr->callno]->iseqno++;
10446  }
10447  /* Ensure text frames are NULL-terminated */
10448  if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10449  if (res < thread->buf_size)
10450  thread->buf[res++] = '\0';
10451  else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
10452  thread->buf[res - 1] = '\0';
10453  }
10454 
10455  /* Handle implicit ACKing unless this is an INVAL, and only if this is
10456  from the real peer, not the transfer peer */
10457  if (!ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10459  (f.frametype != AST_FRAME_IAX))) {
10460  unsigned char x;
10461  int call_to_destroy;
10462  /* First we have to qualify that the ACKed value is within our window */
10463  if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10464  x = fr->iseqno;
10465  else
10466  x = iaxs[fr->callno]->oseqno;
10467  if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10468  /* The acknowledgement is within our window. Time to acknowledge everything
10469  that it says to */
10470  for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10471  /* Ack the packet with the given timestamp */
10472  if (iaxdebug)
10473  ast_debug(1, "Cancelling transmission of packet %d\n", x);
10474  call_to_destroy = 0;
10475  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10476  /* If it's our call, and our timestamp, mark -1 retries */
10477  if (x == cur->oseqno) {
10478  cur->retries = -1;
10479  /* Destroy call if this is the end */
10480  if (cur->final)
10481  call_to_destroy = fr->callno;
10482  }
10483  }
10484  if (call_to_destroy) {
10485  if (iaxdebug)
10486  ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10487  ast_mutex_lock(&iaxsl[call_to_destroy]);
10488  iax2_destroy(call_to_destroy);
10489  ast_mutex_unlock(&iaxsl[call_to_destroy]);
10490  }
10491  }
10492  /* Note how much we've received acknowledgement for */
10493  if (iaxs[fr->callno])
10494  iaxs[fr->callno]->rseqno = fr->iseqno;
10495  else {
10496  /* Stop processing now */
10498  ast_mutex_unlock(&iaxsl[fr->callno]);
10499  return 1;
10500  }
10501  } else {
10502  ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10503  }
10504  }
10505  if (ast_sockaddr_cmp(&addr, &iaxs[fr->callno]->addr) &&
10506  ((f.frametype != AST_FRAME_IAX) ||
10508  (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10509  /* Only messages we accept from a transfer host are TXACC and TXCNT */
10511  ast_mutex_unlock(&iaxsl[fr->callno]);
10512  return 1;
10513  }
10514 
10515  /* when we receive the first full frame for a new incoming channel,
10516  it is safe to start the PBX on the channel because we have now
10517  completed a 3-way handshake with the peer */
10518  if ((f.frametype == AST_FRAME_VOICE) ||
10519  (f.frametype == AST_FRAME_VIDEO) ||
10520  (f.frametype == AST_FRAME_IAX)) {
10521  if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10524  iaxs[fr->callno]->chosenformat, &iaxs[fr->callno]->rprefs, NULL, NULL,
10527  ast_mutex_unlock(&iaxsl[fr->callno]);
10528  return 1;
10529  }
10530  }
10531 
10532  if (ies.vars) {
10533  struct ast_datastore *variablestore = NULL;
10534  struct ast_variable *var, *prev = NULL;
10535  AST_LIST_HEAD(, ast_var_t) *varlist;
10536 
10537  iax2_lock_owner(fr->callno);
10538  if (!iaxs[fr->callno]) {
10540  ast_mutex_unlock(&iaxsl[fr->callno]);
10541  return 1;
10542  }
10543  if ((c = iaxs[fr->callno]->owner)) {
10544  varlist = ast_calloc(1, sizeof(*varlist));
10545  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10546 
10547  if (variablestore && varlist) {
10548  variablestore->data = varlist;
10549  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10550  AST_LIST_HEAD_INIT(varlist);
10551  ast_debug(1, "I can haz IAX vars?\n");
10552  for (var = ies.vars; var; var = var->next) {
10553  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10554  if (prev) {
10555  ast_free(prev);
10556  }
10557  prev = var;
10558  if (!newvar) {
10559  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
10560  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10561  } else {
10562  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10563  }
10564  }
10565  if (prev) {
10566  ast_free(prev);
10567  }
10568  ies.vars = NULL;
10569  ast_channel_datastore_add(c, variablestore);
10570  } else {
10571  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10572  if (variablestore) {
10573  ast_datastore_free(variablestore);
10574  }
10575  if (varlist) {
10576  ast_free(varlist);
10577  }
10578  }
10579  ast_channel_unlock(c);
10580  } else {
10581  /* No channel yet, so transfer the variables directly over to the pvt,
10582  * for later inheritance. */
10583  ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10584  for (var = ies.vars; var && var->next; var = var->next);
10585  if (var) {
10586  var->next = iaxs[fr->callno]->iaxvars;
10587  iaxs[fr->callno]->iaxvars = ies.vars;
10588  ies.vars = NULL;
10589  }
10590  }
10591  }
10592 
10593  if (ies.vars) {
10594  ast_debug(1, "I have IAX variables, but they were not processed\n");
10595  }
10596  }
10597 
10598  /* once we receive our first IAX Full Frame that is not CallToken related, send all
10599  * queued signaling frames that were being held. */
10600  if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10601  send_signaling(iaxs[fr->callno]);
10602  }
10603 
10604  if (f.frametype == AST_FRAME_VOICE) {
10607  ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_format_get_name(f.subclass.format));
10608  if (iaxs[fr->callno]->owner) {
10609  iax2_lock_owner(fr->callno);
10610  if (iaxs[fr->callno]) {
10611  if (iaxs[fr->callno]->owner) {
10613  if (native) {
10614  ast_format_cap_append(native, f.subclass.format, 0);
10615  ast_channel_nativeformats_set(iaxs[fr->callno]->owner, native);
10616  if (ast_channel_readformat(iaxs[fr->callno]->owner)) {
10618  }
10619  ao2_ref(native, -1);
10620  }
10621  ast_channel_unlock(iaxs[fr->callno]->owner);
10622  }
10623  } else {
10624  ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10625  /* Free remote variables (if any) */
10626  if (ies.vars) {
10628  ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10629  ies.vars = NULL;
10630  }
10631  ast_mutex_unlock(&iaxsl[fr->callno]);
10632  return 1;
10633  }
10634  }
10635  }
10636  }
10637  if (f.frametype == AST_FRAME_VIDEO) {
10639  ast_debug(1, "Ooh, video format changed to %s\n", ast_format_get_name(f.subclass.format));
10641  }
10642  }
10643  if (f.frametype == AST_FRAME_IAX) {
10644  AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
10645  /* Handle the IAX pseudo frame itself */
10646  if (iaxdebug)
10647  ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10648 
10649  /* Update last ts unless the frame's timestamp originated with us. */
10650  if (iaxs[fr->callno]->last < fr->ts &&
10654  iaxs[fr->callno]->last = fr->ts;
10655  if (iaxdebug)
10656  ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
10657  }
10658  iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10659  if (!iaxs[fr->callno]->first_iax_message) {
10660  iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10661  }
10662  switch(f.subclass.integer) {
10663  case IAX_COMMAND_ACK:
10664  /* Do nothing */
10665  break;
10666  case IAX_COMMAND_QUELCH:
10667  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10668  ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10669  if (ies.musiconhold) {
10670  const char *moh_suggest;
10671 
10672  iax2_lock_owner(fr->callno);
10673  if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10674  break;
10675  }
10676 
10677  /*
10678  * We already hold the owner lock so we do not
10679  * need to check iaxs[fr->callno] after it returns.
10680  */
10681  moh_suggest = iaxs[fr->callno]->mohsuggest;
10682  iax2_queue_hold(fr->callno, moh_suggest);
10683  ast_channel_unlock(iaxs[fr->callno]->owner);
10684  }
10685  }
10686  break;
10687  case IAX_COMMAND_UNQUELCH:
10688  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10689  iax2_lock_owner(fr->callno);
10690  if (!iaxs[fr->callno]) {
10691  break;
10692  }
10693 
10694  ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10695  if (!iaxs[fr->callno]->owner) {
10696  break;
10697  }
10698 
10699  /*
10700  * We already hold the owner lock so we do not
10701  * need to check iaxs[fr->callno] after it returns.
10702  */
10704  ast_channel_unlock(iaxs[fr->callno]->owner);
10705  }
10706  break;
10707  case IAX_COMMAND_TXACC:
10708  if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10709  /* Ack the packet with the given timestamp */
10710  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10711  /* Cancel any outstanding txcnt's */
10712  if (cur->transfer) {
10713  cur->retries = -1;
10714  }
10715  }
10716  memset(&ied1, 0, sizeof(ied1));
10717  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10718  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10719  iaxs[fr->callno]->transferring = TRANSFER_READY;
10720  }
10721  break;
10722  case IAX_COMMAND_NEW:
10723  /* Ignore if it's already up */
10725  break;
10726  if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
10727  ast_mutex_unlock(&iaxsl[fr->callno]);
10728  check_provisioning(&addr, fd, ies.serviceident, ies.provver);
10729  ast_mutex_lock(&iaxsl[fr->callno]);
10730  if (!iaxs[fr->callno]) {
10731  break;
10732  }
10733  }
10734  /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
10735  if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10736  int new_callno;
10737  if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10738  fr->callno = new_callno;
10739  }
10740  /* For security, always ack immediately */
10741  if (delayreject)
10743  if (check_access(fr->callno, &addr, &ies)) {
10744  /* They're not allowed on */
10746  if (authdebug) {
10747  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n",
10748  ast_sockaddr_stringify(&addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10749  }
10750  break;
10751  }
10752  if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10754  ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10755  break;
10756  }
10757  if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10758  const char *context, *exten, *cid_num;
10759 
10760  context = ast_strdupa(iaxs[fr->callno]->context);
10761  exten = ast_strdupa(iaxs[fr->callno]->exten);
10762  cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10763 
10764  /* This might re-enter the IAX code and need the lock */
10765  ast_mutex_unlock(&iaxsl[fr->callno]);
10766  exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10767  ast_mutex_lock(&iaxsl[fr->callno]);
10768 
10769  if (!iaxs[fr->callno]) {
10770  break;
10771  }
10772  } else
10773  exists = 0;
10774  /* Get OSP token if it does exist */
10775  save_osptoken(fr, &ies);
10776  if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10777  if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10778  memset(&ied0, 0, sizeof(ied0));
10779  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10781  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10782  if (!iaxs[fr->callno]) {
10783  break;
10784  }
10785  if (authdebug) {
10786  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
10787  ast_sockaddr_stringify(&addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
10788  }
10789  } else {
10790  /* Select an appropriate format */
10791 
10792  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10793  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10794  using_prefs = "reqonly";
10795  } else {
10796  using_prefs = "disabled";
10797  }
10798  format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10799  memset(&pref, 0, sizeof(pref));
10800  strcpy(caller_pref_buf, "disabled");
10801  strcpy(host_pref_buf, "disabled");
10802  } else {
10803  struct ast_format *tmpfmt;
10804  using_prefs = "mine";
10805  /* If the information elements are in here... use them */
10806  if (ies.codec_prefs)
10807  iax2_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10808  if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
10809  /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
10810  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10811  pref = iaxs[fr->callno]->rprefs;
10812  using_prefs = "caller";
10813  } else {
10814  pref = iaxs[fr->callno]->prefs;
10815  }
10816  } else
10817  pref = iaxs[fr->callno]->prefs;
10818 
10819  format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
10820  iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10821  iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10822  }
10823  if (!format) {
10824  if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10825  format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10826  if (!format) {
10827  memset(&ied0, 0, sizeof(ied0));
10828  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10830  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10831  if (!iaxs[fr->callno]) {
10832  break;
10833  }
10834  if (authdebug) {
10835  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10836  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10837  struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10838 
10839  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10840  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10841  ast_sockaddr_stringify(&addr),
10842  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
10843  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
10844  } else {
10845  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10846  ast_sockaddr_stringify(&addr),
10847  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
10848  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
10849  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
10850  }
10851  }
10852  } else {
10853  /* Pick one... */
10854  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10855  if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10856  format = 0;
10857  } else {
10858  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10859  using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10860  memset(&pref, 0, sizeof(pref));
10861  format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10862  strcpy(caller_pref_buf,"disabled");
10863  strcpy(host_pref_buf,"disabled");
10864  } else {
10865  struct ast_format *tmpfmt;
10866  using_prefs = "mine";
10867  if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
10868  /* Do the opposite of what we tried above. */
10869  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10870  pref = iaxs[fr->callno]->prefs;
10871  } else {
10872  pref = iaxs[fr->callno]->rprefs;
10873  using_prefs = "caller";
10874  }
10875  format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10876  } else /* if no codec_prefs IE do it the old way */
10877  format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10878  }
10879  }
10880 
10881  if (!format) {
10882  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10883  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10884  struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
10885 
10886  memset(&ied0, 0, sizeof(ied0));
10887  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10889  ast_log(LOG_ERROR, "No best format in '%s'???\n", iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
10890  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10891  if (!iaxs[fr->callno]) {
10892  break;
10893  }
10894  if (authdebug) {
10895  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10896  ast_sockaddr_stringify(&addr),
10897  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
10898  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
10899  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
10900  }
10902  break;
10903  }
10904  }
10905  }
10906  if (format) {
10907  /* No authentication required, let them in */
10908  memset(&ied1, 0, sizeof(ied1));
10909  iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10911  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10912  if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10914  ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10915  "%srequested format = %s,\n"
10916  "%srequested prefs = %s,\n"
10917  "%sactual format = %s,\n"
10918  "%shost prefs = %s,\n"
10919  "%spriority = %s\n",
10920  ast_sockaddr_stringify(&addr),
10922  iax2_getformatname(iaxs[fr->callno]->peerformat),
10924  caller_pref_buf,
10926  iax2_getformatname(format),
10928  host_pref_buf,
10930  using_prefs);
10931 
10932  iaxs[fr->callno]->chosenformat = format;
10933 
10934  /* Since this is a new call, we should go ahead and set the callid for it. */
10937  } else {
10938  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10939  /* If this is a TBD call, we're ready but now what... */
10940  ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_sockaddr_stringify(&addr));
10941  }
10942  }
10943  }
10944  break;
10945  }
10946  if (iaxs[fr->callno]->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA))
10947  merge_encryption(iaxs[fr->callno], ies.encmethods);
10948  else
10949  iaxs[fr->callno]->encmethods = 0;
10950  if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10952  break;
10953  case IAX_COMMAND_DPREQ:
10954  /* Request status in the dialplan */
10955  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10956  !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10957  if (iaxcompat) {
10958  /* Spawn a thread for the lookup */
10959  spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10960  } else {
10961  /* Just look it up */
10962  dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10963  }
10964  }
10965  break;
10966  case IAX_COMMAND_HANGUP:
10968  ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10969  /* Set hangup cause according to remote and hangupsource */
10970  if (iaxs[fr->callno]->owner) {
10972  if (!iaxs[fr->callno]) {
10973  break;
10974  }
10975  }
10976 
10977  /* Send ack immediately, before we destroy */
10979  iax2_destroy(fr->callno);
10980  break;
10981  case IAX_COMMAND_REJECT:
10982  /* Set hangup cause according to remote and hangup source */
10983  if (iaxs[fr->callno]->owner) {
10985  if (!iaxs[fr->callno]) {
10986  break;
10987  }
10988  }
10989 
10990  if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10991  if (iaxs[fr->callno]->owner && authdebug)
10992  ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10993  ast_sockaddr_stringify(&addr),
10994  ies.cause ? ies.cause : "<Unknown>");
10995  ast_debug(1, "Immediately destroying %d, having received reject\n",
10996  fr->callno);
10997  }
10998  /* Send ack immediately, before we destroy */
11000  fr->ts, NULL, 0, fr->iseqno);
11001  if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
11002  iaxs[fr->callno]->error = EPERM;
11003  iax2_destroy(fr->callno);
11004  break;
11005  case IAX_COMMAND_TRANSFER:
11006  {
11007  iax2_lock_owner(fr->callno);
11008  if (!iaxs[fr->callno]) {
11009  /* Initiating call went away before we could transfer. */
11010  break;
11011  }
11012  if (iaxs[fr->callno]->owner) {
11013  struct ast_channel *owner = iaxs[fr->callno]->owner;
11014  char *context = ast_strdupa(iaxs[fr->callno]->context);
11015 
11016  ast_channel_ref(owner);
11017  ast_channel_unlock(owner);
11018  ast_mutex_unlock(&iaxsl[fr->callno]);
11019 
11020  if (ast_bridge_transfer_blind(1, owner, ies.called_number,
11021  context, NULL, NULL) != AST_BRIDGE_TRANSFER_SUCCESS) {
11022  ast_log(LOG_WARNING, "Blind transfer of '%s' to '%s@%s' failed\n",
11023  ast_channel_name(owner), ies.called_number,
11024  context);
11025  }
11026 
11027  ast_channel_unref(owner);
11028  ast_mutex_lock(&iaxsl[fr->callno]);
11029  }
11030 
11031  break;
11032  }
11033  case IAX_COMMAND_ACCEPT:
11034  /* Ignore if call is already up or needs authentication or is a TBD */
11036  break;
11037  if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
11038  /* Send ack immediately, before we destroy */
11040  iax2_destroy(fr->callno);
11041  break;
11042  }
11043  if (ies.format) {
11044  iaxs[fr->callno]->peerformat = ies.format;
11045  } else {
11046  if (iaxs[fr->callno]->owner)
11048  else
11049  iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
11050  }
11051  ast_verb(3, "Call accepted by %s (format %s)\n", ast_sockaddr_stringify(&addr),
11052  iax2_getformatname(iaxs[fr->callno]->peerformat));
11053  if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
11054  memset(&ied0, 0, sizeof(ied0));
11055  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11057  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11058  if (!iaxs[fr->callno]) {
11059  break;
11060  }
11061  if (authdebug) {
11062  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11063  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11064 
11065  ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
11066  ast_sockaddr_stringify(&addr),
11067  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_buf),
11068  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11069  }
11070  } else {
11072 
11073  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11074  iax2_lock_owner(fr->callno);
11075  if (iaxs[fr->callno] && iaxs[fr->callno]->owner && native) {
11076  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11077 
11078  /* Switch us to use a compatible format */
11080  iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11081  native);
11082  ast_channel_nativeformats_set(iaxs[fr->callno]->owner, native);
11083  ast_verb(3, "Format for call is %s\n", ast_format_cap_get_names(ast_channel_nativeformats(iaxs[fr->callno]->owner), &cap_buf));
11084 
11085  /* Setup read/write formats properly. */
11086  if (ast_channel_writeformat(iaxs[fr->callno]->owner))
11087  ast_set_write_format(iaxs[fr->callno]->owner, ast_channel_writeformat(iaxs[fr->callno]->owner));
11088  if (ast_channel_readformat(iaxs[fr->callno]->owner))
11089  ast_set_read_format(iaxs[fr->callno]->owner, ast_channel_readformat(iaxs[fr->callno]->owner));
11090  ast_channel_unlock(iaxs[fr->callno]->owner);
11091  }
11092 
11093  ao2_cleanup(native);
11094  }
11095  if (iaxs[fr->callno]) {
11097  AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
11098  if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
11099  iax2_dprequest(dp, fr->callno);
11101  }
11102  break;
11103  case IAX_COMMAND_POKE:
11104  /* Send back a pong packet with the original timestamp */
11105  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
11106  break;
11107  case IAX_COMMAND_PING:
11108  {
11109  struct iax_ie_data pingied;
11110  construct_rr(iaxs[fr->callno], &pingied);
11111  /* Send back a pong packet with the original timestamp */
11112  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
11113  }
11114  break;
11115  case IAX_COMMAND_PONG:
11116  /* Calculate ping time */
11117  iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
11118  /* save RR info */
11119  save_rr(fr, &ies);
11120 
11121  /* Good time to write jb stats for this call */
11122  log_jitterstats(fr->callno);
11123 
11124  if (iaxs[fr->callno]->peerpoke) {
11125  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
11126  peer = iaxs[fr->callno]->peerpoke;
11127  if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
11128  if (iaxs[fr->callno]->pingtime <= peer->maxms) {
11129  ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %u\n", peer->name, iaxs[fr->callno]->pingtime);
11131  blob = ast_json_pack("{s: s, s: I}",
11132  "peer_status", "Reachable",
11133  "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11134  ast_devstate_changed(AST_DEVICE_NOT_INUSE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11135  }
11136  } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
11137  if (iaxs[fr->callno]->pingtime > peer->maxms) {
11138  ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%u ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
11140  blob = ast_json_pack("{s: s, s: I}",
11141  "peer_status", "Lagged",
11142  "time", (ast_json_int_t)iaxs[fr->callno]->pingtime);
11143  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
11144  }
11145  }
11147  peer->lastms = iaxs[fr->callno]->pingtime;
11148  if (peer->smoothing && (peer->lastms > -1))
11149  peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
11150  else if (peer->smoothing && peer->lastms < 0)
11151  peer->historicms = (0 + peer->historicms) / 2;
11152  else
11153  peer->historicms = iaxs[fr->callno]->pingtime;
11154 
11155  /* Remove scheduled iax2_poke_noanswer */
11156  if (peer->pokeexpire > -1) {
11157  if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
11158  peer_unref(peer);
11159  peer->pokeexpire = -1;
11160  }
11161  }
11162  /* Schedule the next cycle */
11163  if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
11164  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11165  else
11166  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
11167  if (peer->pokeexpire == -1)
11168  peer_unref(peer);
11169  /* and finally send the ack */
11171  /* And wrap up the qualify call */
11172  iax2_destroy(fr->callno);
11173  peer->callno = 0;
11174  ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
11175  }
11176  break;
11177  case IAX_COMMAND_LAGRQ:
11178  case IAX_COMMAND_LAGRP:
11179  f.src = "LAGRQ";
11180  f.mallocd = 0;
11181  f.offset = 0;
11182  f.samples = 0;
11183  iax_frame_wrap(fr, &f);
11184  if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
11185  /* Received a LAGRQ - echo back a LAGRP */
11187  iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
11188  } else {
11189  /* Received LAGRP in response to our LAGRQ */
11190  unsigned int ts;
11191  /* This is a reply we've been given, actually measure the difference */
11192  ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
11193  iaxs[fr->callno]->lag = ts - fr->ts;
11194  if (iaxdebug)
11195  ast_debug(1, "Peer %s lag measured as %dms\n",
11196  ast_sockaddr_stringify(&addr), iaxs[fr->callno]->lag);
11197  }
11198  break;
11199  case IAX_COMMAND_AUTHREQ:
11200  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11201  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>");
11202  break;
11203  }
11204  if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
11205  struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
11206  .subclass.integer = AST_CONTROL_HANGUP,
11207  };
11209  "I don't know how to authenticate %s to %s\n",
11210  ies.username ? ies.username : "<unknown>", ast_sockaddr_stringify(&addr));
11211  iax2_queue_frame(fr->callno, &hangup_fr);
11212  }
11213  break;
11214  case IAX_COMMAND_AUTHREP:
11215  /* For security, always ack immediately */
11216  if (delayreject)
11218  /* Ignore once we've started */
11219  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11220  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>");
11221  break;
11222  }
11223  if (authenticate_verify(iaxs[fr->callno], &ies)) {
11224  if (authdebug)
11225  ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_sockaddr_stringify(&addr),
11226  iaxs[fr->callno]->username);
11227  memset(&ied0, 0, sizeof(ied0));
11229  break;
11230  }
11231  if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11232  /* This might re-enter the IAX code and need the lock */
11233  exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11234  } else
11235  exists = 0;
11236  if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11237  if (authdebug)
11238  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n",
11239  ast_sockaddr_stringify(&addr),
11240  iaxs[fr->callno]->exten,
11241  iaxs[fr->callno]->context);
11242  memset(&ied0, 0, sizeof(ied0));
11243  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11245  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11246  if (!iaxs[fr->callno]) {
11247  break;
11248  }
11249  } else {
11250  /* Select an appropriate format */
11251  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11252  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11253  using_prefs = "reqonly";
11254  } else {
11255  using_prefs = "disabled";
11256  }
11257  format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11258  memset(&pref, 0, sizeof(pref));
11259  strcpy(caller_pref_buf, "disabled");
11260  strcpy(host_pref_buf, "disabled");
11261  } else {
11262  struct ast_format *tmpfmt;
11263  using_prefs = "mine";
11264  if (ies.codec_prefs)
11265  iax2_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11266  if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11267  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11268  pref = iaxs[fr->callno]->rprefs;
11269  using_prefs = "caller";
11270  } else {
11271  pref = iaxs[fr->callno]->prefs;
11272  }
11273  } else /* if no codec_prefs IE do it the old way */
11274  pref = iaxs[fr->callno]->prefs;
11275  format = iax2_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability);
11276  iax2_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11277  iax2_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11278  }
11279  if (!format) {
11280  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11281  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11282  struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11283 
11284  if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11285  ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11286  iax2_getformatname(iaxs[fr->callno]->peerformat),
11287  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf));
11288  format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11289  }
11290  if (!format) {
11291  if (authdebug) {
11292  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11293  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11294  ast_sockaddr_stringify(&addr),
11295  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11296  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11297  } else {
11298  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11299  ast_sockaddr_stringify(&addr),
11300  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11301  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11302  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11303  }
11304  }
11305  memset(&ied0, 0, sizeof(ied0));
11306  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11308  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11309  if (!iaxs[fr->callno]) {
11310  break;
11311  }
11312  } else {
11313  /* Pick one... */
11314  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11315  if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11316  format = 0;
11317  } else {
11318  if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11319  using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11320  memset(&pref, 0, sizeof(pref));
11321  format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)
11322  ? iaxs[fr->callno]->peerformat
11323  : iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11324  strcpy(caller_pref_buf,"disabled");
11325  strcpy(host_pref_buf,"disabled");
11326  } else {
11327  struct ast_format *tmpfmt;
11328  using_prefs = "mine";
11329  if (iax2_codec_pref_index(&iaxs[fr->callno]->rprefs, 0, &tmpfmt)) {
11330  /* Do the opposite of what we tried above. */
11331  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11332  pref = iaxs[fr->callno]->prefs;
11333  } else {
11334  pref = iaxs[fr->callno]->rprefs;
11335  using_prefs = "caller";
11336  }
11337  format = iax2_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11338  } else /* if no codec_prefs IE do it the old way */
11339  format = iax2_format_compatibility_best(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11340  }
11341  }
11342  if (!format) {
11343  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11344  struct ast_str *peer_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11345  struct ast_str *peer_form_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11346 
11347  ast_log(LOG_ERROR, "No best format in %s???\n",
11348  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, &cap_buf));
11349  if (authdebug) {
11350  if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11351  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11352  ast_sockaddr_stringify(&addr),
11353  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11354  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11355  } else {
11356  ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11357  ast_sockaddr_stringify(&addr),
11358  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &peer_form_buf),
11359  iax2_getformatname_multiple(iaxs[fr->callno]->peercapability, &peer_buf),
11360  iax2_getformatname_multiple(iaxs[fr->callno]->capability, &cap_buf));
11361  }
11362  }
11363  memset(&ied0, 0, sizeof(ied0));
11364  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11366  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11367  if (!iaxs[fr->callno]) {
11368  break;
11369  }
11370  }
11371  }
11372  }
11373  if (format) {
11374  /* Authentication received */
11375  memset(&ied1, 0, sizeof(ied1));
11376  iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11378  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11379  if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11380  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11381  ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11382  "%srequested format = %s,\n"
11383  "%srequested prefs = %s,\n"
11384  "%sactual format = %s,\n"
11385  "%shost prefs = %s,\n"
11386  "%spriority = %s\n",
11387  ast_sockaddr_stringify(&addr),
11389  iax2_getformatname(iaxs[fr->callno]->peerformat),
11391  caller_pref_buf,
11393  iax2_getformatname(format),
11395  host_pref_buf,
11397  using_prefs);
11398 
11399  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11400  c = ast_iax2_new(fr->callno, AST_STATE_RING, format,
11401  &iaxs[fr->callno]->rprefs, NULL, NULL, 1);
11402  if (!c) {
11403  iax2_destroy(fr->callno);
11404  } else if (ies.vars) {
11405  struct ast_datastore *variablestore;
11406  struct ast_variable *var, *prev = NULL;
11407  AST_LIST_HEAD(, ast_var_t) *varlist;
11408  varlist = ast_calloc(1, sizeof(*varlist));
11409  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11410  if (variablestore && varlist) {
11411  variablestore->data = varlist;
11412  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11413  AST_LIST_HEAD_INIT(varlist);
11414  ast_debug(1, "I can haz IAX vars? w00t\n");
11415  for (var = ies.vars; var; var = var->next) {
11416  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11417  if (prev)
11418  ast_free(prev);
11419  prev = var;
11420  if (!newvar) {
11421  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11422  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11423  } else {
11424  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11425  }
11426  }
11427  if (prev)
11428  ast_free(prev);
11429  ies.vars = NULL;
11430  ast_channel_datastore_add(c, variablestore);
11431  } else {
11432  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11433  if (variablestore)
11434  ast_datastore_free(variablestore);
11435  if (varlist)
11436  ast_free(varlist);
11437  }
11438  }
11439  } else {
11440  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11441  /* If this is a TBD call, we're ready but now what... */
11442  ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_sockaddr_stringify(&addr));
11443  if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11444  goto immediatedial;
11445  }
11446  }
11447  }
11448  }
11449  break;
11450  case IAX_COMMAND_DIAL:
11451 immediatedial:
11452  if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11453  ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11454  ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11455  if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11456  if (authdebug)
11457  ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n",
11458  ast_sockaddr_stringify(&addr),
11459  iaxs[fr->callno]->exten,
11460  iaxs[fr->callno]->context);
11461  memset(&ied0, 0, sizeof(ied0));
11462  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11464  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11465  if (!iaxs[fr->callno]) {
11466  break;
11467  }
11468  } else {
11469  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
11470  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11471  ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11472  ast_sockaddr_stringify(&addr),
11473  iax2_getformatname_multiple(iaxs[fr->callno]->peerformat, &cap_buf));
11474  ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11477  iaxs[fr->callno]->peerformat, &iaxs[fr->callno]->rprefs,
11478  NULL, NULL, 1);
11479  if (!c) {
11480  iax2_destroy(fr->callno);
11481  } else if (ies.vars) {
11482  struct ast_datastore *variablestore;
11483  struct ast_variable *var, *prev = NULL;
11484  AST_LIST_HEAD(, ast_var_t) *varlist;
11485  varlist = ast_calloc(1, sizeof(*varlist));
11486  variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11487  ast_debug(1, "I can haz IAX vars? w00t\n");
11488  if (variablestore && varlist) {
11489  variablestore->data = varlist;
11490  variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11491  AST_LIST_HEAD_INIT(varlist);
11492  for (var = ies.vars; var; var = var->next) {
11493  struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11494  if (prev)
11495  ast_free(prev);
11496  prev = var;
11497  if (!newvar) {
11498  /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
11499  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11500  } else {
11501  AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11502  }
11503  }
11504  if (prev)
11505  ast_free(prev);
11506  ies.vars = NULL;
11507  ast_channel_datastore_add(c, variablestore);
11508  } else {
11509  ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11510  if (variablestore)
11511  ast_datastore_free(variablestore);
11512  if (varlist)
11513  ast_free(varlist);
11514  }
11515  }
11516  }
11517  }
11518  break;
11519  case IAX_COMMAND_INVAL:
11520  iaxs[fr->callno]->error = ENOTCONN;
11521  ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11522  iax2_destroy(fr->callno);
11523  ast_debug(1, "Destroying call %d\n", fr->callno);
11524  break;
11525  case IAX_COMMAND_VNAK:
11526  ast_debug(1, "Received VNAK: resending outstanding frames\n");
11527  /* Force retransmission */
11528  vnak_retransmit(fr->callno, fr->iseqno);
11529  break;
11530  case IAX_COMMAND_REGREQ:
11531  case IAX_COMMAND_REGREL:
11532  /* For security, always ack immediately */
11533  if (delayreject)
11535  if (register_verify(fr->callno, &addr, &ies)) {
11536  if (!iaxs[fr->callno]) {
11537  break;
11538  }
11539  /* Send delayed failure */
11541  break;
11542  }
11543  if (!iaxs[fr->callno]) {
11544  break;
11545  }
11546  if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11547  ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11548 
11549  if (f.subclass.integer == IAX_COMMAND_REGREL) {
11550  ast_sockaddr_setnull(&addr);
11551  }
11552  if (update_registry(&addr, fr->callno, ies.devicetype, fd, ies.refresh)) {
11553  ast_log(LOG_WARNING, "Registry error\n");
11554  }
11555  if (!iaxs[fr->callno]) {
11556  break;
11557  }
11558  if (ies.provverpres && ies.serviceident && !(ast_sockaddr_isnull(&addr))) {
11559  ast_mutex_unlock(&iaxsl[fr->callno]);
11560  check_provisioning(&addr, fd, ies.serviceident, ies.provver);
11561  ast_mutex_lock(&iaxsl[fr->callno]);
11562  }
11563  break;
11564  }
11566  break;
11567  case IAX_COMMAND_REGACK:
11568  if (iax2_ack_registry(&ies, &addr, fr->callno)) {
11569  ast_log(LOG_WARNING, "Registration failure\n");
11570  }
11571  /* Send ack immediately, before we destroy */
11573  iax2_destroy(fr->callno);
11574  break;
11575  case IAX_COMMAND_REGREJ:
11576  if (iaxs[fr->callno]->reg) {
11577  if (authdebug) {
11578  ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n",
11579  iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>",
11580  ast_sockaddr_stringify(&addr));
11581  }
11582  iax2_publish_registry(iaxs[fr->callno]->reg->username, ast_sockaddr_stringify(&addr), "Rejected", S_OR(ies.cause, "<unknown>"));
11583  iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11584  }
11585  /* Send ack immediately, before we destroy */
11587  iax2_destroy(fr->callno);
11588  break;
11589  case IAX_COMMAND_REGAUTH:
11590  /* Authentication request */
11591  if (registry_rerequest(&ies, fr->callno, &addr)) {
11592  memset(&ied0, 0, sizeof(ied0));
11593  iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11595  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11596  }
11597  break;
11598  case IAX_COMMAND_TXREJ:
11599  while (iaxs[fr->callno]
11600  && iaxs[fr->callno]->bridgecallno
11601  && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11602  DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11603  }
11604  if (!iaxs[fr->callno]) {
11605  break;
11606  }
11607 
11608  iaxs[fr->callno]->transferring = TRANSFER_NONE;
11609  ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11610  memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11611 
11612  if (!iaxs[fr->callno]->bridgecallno) {
11613  break;
11614  }
11615 
11616  if (iaxs[iaxs[fr->callno]->bridgecallno]
11617  && iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11618  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
11619  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11620  }
11621  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11622  break;
11623  case IAX_COMMAND_TXREADY:
11624  while (iaxs[fr->callno]
11625  && iaxs[fr->callno]->bridgecallno
11626  && ast_mutex_trylock(&iaxsl[iaxs[fr->callno]->bridgecallno])) {
11627  DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
11628  }
11629  if (!iaxs[fr->callno]) {
11630  break;
11631  }
11632 
11633  if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
11634  iaxs[fr->callno]->transferring = TRANSFER_READY;
11635  } else if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN) {
11636  iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11637  } else {
11638  if (iaxs[fr->callno]->bridgecallno) {
11639  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11640  }
11641  break;
11642  }
11643  ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>");
11644 
11645  if (!iaxs[fr->callno]->bridgecallno) {
11646  break;
11647  }
11648 
11649  if (!iaxs[iaxs[fr->callno]->bridgecallno]
11650  || (iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_READY
11651  && iaxs[iaxs[fr->callno]->bridgecallno]->transferring != TRANSFER_MREADY)) {
11652  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11653  break;
11654  }
11655 
11656  /* Both sides are ready */
11657 
11658  /* XXX what isn't checked here is that both sides match transfer types. */
11659 
11660  if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11661  ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11662  iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11663 
11664  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11665  iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11666 
11667  memset(&ied0, 0, sizeof(ied0));
11668  memset(&ied1, 0, sizeof(ied1));
11669  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11670  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11671  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11672  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11673  } else {
11674  ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? ast_channel_name(iaxs[fr->callno]->owner) : "<Unknown>",
11675  iaxs[iaxs[fr->callno]->bridgecallno]->owner ? ast_channel_name(iaxs[iaxs[fr->callno]->bridgecallno]->owner) : "<Unknown>");
11676 
11677  iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11678  iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11679  ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11681 
11682  /* Stop doing lag & ping requests */
11683  stop_stuff(fr->callno);
11684  stop_stuff(iaxs[fr->callno]->bridgecallno);
11685 
11686  memset(&ied0, 0, sizeof(ied0));
11687  memset(&ied1, 0, sizeof(ied1));
11688  iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11689  iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11690  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11691  send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11692  }
11693  ast_mutex_unlock(&iaxsl[iaxs[fr->callno]->bridgecallno]);
11694  break;
11695  case IAX_COMMAND_TXREQ:
11696  try_transfer(iaxs[fr->callno], &ies);
11697  break;
11698  case IAX_COMMAND_TXCNT:
11699  if (iaxs[fr->callno]->transferring)
11701  break;
11702  case IAX_COMMAND_TXREL:
11703  /* Send ack immediately, rather than waiting until we've changed addresses */
11705  complete_transfer(fr->callno, &ies);
11706  stop_stuff(fr->callno); /* for attended transfer to work with libiax */
11707  break;
11708  case IAX_COMMAND_TXMEDIA:
11709  if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11710  AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11711  /* Cancel any outstanding frames and start anew */
11712  if (cur->transfer) {
11713  cur->retries = -1;
11714  }
11715  }
11716  /* Start sending our media to the transfer address, but otherwise leave the call as-is */
11717  iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11718  }
11719  break;
11720  case IAX_COMMAND_RTKEY:
11721  if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11723  "we've been told to rotate our encryption key, "
11724  "but this isn't an encrypted call. bad things will happen.\n"
11725  );
11726  break;
11727  }
11728 
11729  IAX_DEBUGDIGEST("Receiving", ies.challenge);
11730 
11731  ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11732  break;
11733  case IAX_COMMAND_DPREP:
11734  complete_dpreply(iaxs[fr->callno], &ies);
11735  break;
11736  case IAX_COMMAND_UNSUPPORT:
11737  ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11738  break;
11739  case IAX_COMMAND_FWDOWNL:
11740  /* Firmware download */
11741  if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11743  break;
11744  }
11745  memset(&ied0, 0, sizeof(ied0));
11746  res = iax_firmware_append(&ied0, ies.devicetype, ies.fwdesc);
11747  if (res < 0)
11748  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11749  else if (res > 0)
11750  send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11751  else
11752  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11753  break;
11754  case IAX_COMMAND_CALLTOKEN:
11755  {
11756  struct iax_frame *cur;
11757  /* find last sent frame */
11758  if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11759  resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11760  }
11761  break;
11762  }
11763  default:
11764  ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11765  memset(&ied0, 0, sizeof(ied0));
11767  send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11768  }
11769  /* Free remote variables (if any) */
11770  if (ies.vars) {
11772  ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11773  ies.vars = NULL;
11774  }
11775 
11776  /* Don't actually pass these frames along */
11777  if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11782  if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno) {
11784  }
11785  }
11786  ast_mutex_unlock(&iaxsl[fr->callno]);
11787  return 1;
11788  }
11789  /* Unless this is an ACK or INVAL frame, ack it */
11790  if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11792  } else if (minivid) {
11794  if (iaxs[fr->callno]->videoformat > 0) {
11795  if (ntohs(vh->ts) & 0x8000LL) {
11796  f.subclass.frame_ending = 1;
11797  }
11799  } else {
11800  ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11801  iax2_vnak(fr->callno);
11803  ast_mutex_unlock(&iaxsl[fr->callno]);
11804  return 1;
11805  }
11806  f.datalen = res - sizeof(*vh);
11807  if (f.datalen)
11808  f.data.ptr = thread->buf + sizeof(*vh);
11809  else
11810  f.data.ptr = NULL;
11811 #ifdef IAXTESTS
11812  if (test_resync) {
11813  fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11814  } else
11815 #endif /* IAXTESTS */
11816  fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11817  } else {
11818  /* A mini frame */
11820  if (iaxs[fr->callno]->voiceformat > 0)
11822  else {
11823  ast_debug(1, "Received mini frame before first full voice frame\n");
11824  iax2_vnak(fr->callno);
11826  ast_mutex_unlock(&iaxsl[fr->callno]);
11827  return 1;
11828  }
11829  f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11830  if (f.datalen < 0) {
11831  ast_log(LOG_WARNING, "Datalen < 0?\n");
11833  ast_mutex_unlock(&iaxsl[fr->callno]);
11834  return 1;
11835  }
11836  if (f.datalen)
11837  f.data.ptr = thread->buf + sizeof(*mh);
11838  else
11839  f.data.ptr = NULL;
11840 #ifdef IAXTESTS
11841  if (test_resync) {
11842  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11843  } else
11844 #endif /* IAXTESTS */
11845  fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11846  /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
11847  }
11848 
11849  /* Don't pass any packets until we're started */
11850  if (!iaxs[fr->callno]
11851  || !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11853  ast_mutex_unlock(&iaxsl[fr->callno]);
11854  return 1;
11855  }
11856 
11857  if (f.frametype == AST_FRAME_CONTROL) {
11859  /* Control frame not allowed to come from the wire. */
11860  ast_debug(2, "Callno %d: Blocked receiving control frame %d.\n",
11861  fr->callno, f.subclass.integer);
11863  ast_mutex_unlock(&iaxsl[fr->callno]);
11864  return 1;
11865  }
11868  if (iaxs[fr->callno]
11869  && !ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11870  /* We are not configured to allow receiving these updates. */
11871  ast_debug(2, "Callno %d: Config blocked receiving control frame %d.\n",
11872  fr->callno, f.subclass.integer);
11874  ast_mutex_unlock(&iaxsl[fr->callno]);
11875  return 1;
11876  }
11877  }
11878 
11879  iax2_lock_owner(fr->callno);
11880  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11881  if (f.subclass.integer == AST_CONTROL_BUSY) {
11883  } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
11885  }
11886  ast_channel_unlock(iaxs[fr->callno]->owner);
11887  }
11888  }
11889 
11890  if (f.frametype == AST_FRAME_CONTROL
11892  && iaxs[fr->callno]) {
11893  struct ast_party_connected_line connected;
11894 
11895  /*
11896  * Process a received connected line update.
11897  *
11898  * Initialize defaults.
11899  */
11900  ast_party_connected_line_init(&connected);
11901  connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11902  connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11903 
11904  if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11905  ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11906  ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11907  iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11908 
11909  iax2_lock_owner(fr->callno);
11910  if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
11911  ast_set_callerid(iaxs[fr->callno]->owner,
11912  S_COR(connected.id.number.valid, connected.id.number.str, ""),
11913  S_COR(connected.id.name.valid, connected.id.name.str, ""),
11914  NULL);
11917  ast_channel_unlock(iaxs[fr->callno]->owner);
11918  }
11919  }
11920  ast_party_connected_line_free(&connected);
11921  }
11922 
11923  /* Common things */
11924  f.src = "IAX2";
11925  f.mallocd = 0;
11926  f.offset = 0;
11927  f.len = 0;
11928  if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11930  /* We need to byteswap incoming slinear samples from network byte order */
11933  } else
11934  f.samples = 0;
11935  iax_frame_wrap(fr, &f);
11936 
11937  /* If this is our most recent packet, use it as our basis for timestamping */
11938  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11939  /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
11940  fr->outoforder = 0;
11941  } else {
11942  if (iaxdebug && iaxs[fr->callno]) {
11943  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);
11944  }
11945  fr->outoforder = 1;
11946  }
11947  fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11948  if (iaxs[fr->callno]) {
11949  duped_fr = iaxfrdup2(fr);
11950  if (duped_fr) {
11951  schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11952  }
11953  }
11954  if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11955  iaxs[fr->callno]->last = fr->ts;
11956 #if 1
11957  if (iaxdebug)
11958  ast_debug(1, "For call=%d, set last=%u\n", fr->callno, fr->ts);
11959 #endif
11960  }
11961 
11962  /* Always run again */
11964  ast_mutex_unlock(&iaxsl[fr->callno]);
11965  return 1;
11966 }
11967 
11968 static int socket_process(struct iax2_thread *thread)
11969 {
11970  int res = socket_process_helper(thread);
11973  }
11974  return res;
11975 }
11976 
11977 /* Function to clean up process thread if it is cancelled */
11978 static void iax2_process_thread_cleanup(void *data)
11979 {
11980  struct iax2_thread *thread = data;
11981  ast_mutex_destroy(&thread->lock);
11982  ast_cond_destroy(&thread->cond);
11983  ast_mutex_destroy(&thread->init_lock);
11984  ast_cond_destroy(&thread->init_cond);
11985  ast_free(thread);
11986  /* Ignore check_return warning from Coverity for ast_atomic_dec_and_test below */
11987  ast_atomic_dec_and_test(&iaxactivethreadcount);
11988 }
11989 
11990 static void *iax2_process_thread(void *data)
11991 {
11992  struct iax2_thread *thread = data;
11993  struct timeval wait;
11994  struct timespec ts;
11995  int put_into_idle = 0;
11996  int first_time = 1;
11997  int old_state;
11998 
11999  ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
12000 
12001  pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
12002  pthread_cleanup_push(iax2_process_thread_cleanup, data);
12003 
12004  for (;;) {
12005  /* Wait for something to signal us to be awake */
12006  ast_mutex_lock(&thread->lock);
12007 
12008  if (thread->stop) {
12009  ast_mutex_unlock(&thread->lock);
12010  break;
12011  }
12012 
12013  /* Flag that we're ready to accept signals */
12014  if (first_time) {
12015  signal_condition(&thread->init_lock, &thread->init_cond);
12016  first_time = 0;
12017  }
12018 
12019  /* Put into idle list if applicable */
12020  if (put_into_idle) {
12021  insert_idle_thread(thread);
12022  }
12023 
12024  if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
12025  struct iax2_thread *t = NULL;
12026  /* Wait to be signalled or time out */
12027  wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12028  ts.tv_sec = wait.tv_sec;
12029  ts.tv_nsec = wait.tv_usec * 1000;
12030  if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12031  /* This thread was never put back into the available dynamic
12032  * thread list, so just go away. */
12033  if (!put_into_idle || thread->stop) {
12034  ast_mutex_unlock(&thread->lock);
12035  break;
12036  }
12038  /* Account for the case where this thread is acquired *right* after a timeout */
12039  if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
12040  ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
12042  if (t) {
12043  /* This dynamic thread timed out waiting for a task and was
12044  * not acquired immediately after the timeout,
12045  * so it's time to go away. */
12046  ast_mutex_unlock(&thread->lock);
12047  break;
12048  }
12049  /* Someone grabbed our thread *right* after we timed out.
12050  * Wait for them to set us up with something to do and signal
12051  * us to continue. */
12052  wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
12053  ts.tv_sec = wait.tv_sec;
12054  ts.tv_nsec = wait.tv_usec * 1000;
12055  if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
12056  ast_mutex_unlock(&thread->lock);
12057  break;
12058  }
12059  }
12060  } else {
12061  ast_cond_wait(&thread->cond, &thread->lock);
12062  }
12063 
12064  /* Go back into our respective list */
12065  put_into_idle = 1;
12066 
12067  ast_mutex_unlock(&thread->lock);
12068 
12069  if (thread->stop) {
12070  break;
12071  }
12072 
12073  /* See what we need to do */
12074  switch (thread->iostate) {
12075  case IAX_IOSTATE_IDLE:
12076  continue;
12077  case IAX_IOSTATE_READY:
12078  thread->actions++;
12079  thread->iostate = IAX_IOSTATE_PROCESSING;
12080  socket_process(thread);
12082  break;
12084  thread->actions++;
12085  thread->iostate = IAX_IOSTATE_PROCESSING;
12086 #ifdef SCHED_MULTITHREADED
12087  thread->schedfunc(thread->scheddata);
12088 #endif
12089  break;
12090  default:
12091  break;
12092  }
12093 
12094  /* The network thread added us to the active_thread list when we were given
12095  * frames to process, Now that we are done, we must remove ourselves from
12096  * the active list, and return to the idle list */
12098  AST_LIST_REMOVE(&active_list, thread, list);
12100 
12101  /* Make sure another frame didn't sneak in there after we thought we were done. */
12103 
12104  time(&thread->checktime);
12105  thread->iostate = IAX_IOSTATE_IDLE;
12106 #ifdef DEBUG_SCHED_MULTITHREAD
12107  thread->curfunc[0]='\0';
12108 #endif
12109  }
12110 
12111  /*!
12112  * \note For some reason, idle threads are exiting without being
12113  * removed from an idle list, which is causing memory
12114  * corruption. Forcibly remove it from the list, if it's there.
12115  */
12117  AST_LIST_REMOVE(&idle_list, thread, list);
12119 
12121  AST_LIST_REMOVE(&dynamic_list, thread, list);
12123 
12124  if (!thread->stop) {
12125  /* Nobody asked me to stop so nobody is waiting to join me. */
12126  pthread_detach(pthread_self());
12127  }
12128 
12129  /* I am exiting here on my own volition, I need to clean up my own data structures
12130  * Assume that I am no longer in any of the lists (idle, active, or dynamic)
12131  */
12132  pthread_cleanup_pop(1);
12133  return NULL;
12134 }
12135 
12136 static int iax2_do_register(struct iax2_registry *reg)
12137 {
12138  struct iax_ie_data ied;
12139  if (iaxdebug)
12140  ast_debug(1, "Sending registration request for '%s'\n", reg->username);
12141 
12142  if (reg->dnsmgr &&
12143  ((reg->regstate == REG_STATE_TIMEOUT) || ast_sockaddr_isnull(&reg->addr))) {
12144  /* Maybe the IP has changed, force DNS refresh */
12145  ast_dnsmgr_refresh(reg->dnsmgr);
12146  }
12147 
12148  /*
12149  * if IP has Changed, free allocated call to create a new one with new IP
12150  * call has the pointer to IP and must be updated to the new one
12151  */
12152  if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
12153  int callno = reg->callno;
12154  ast_mutex_lock(&iaxsl[callno]);
12155  iax2_destroy(callno);
12156  ast_mutex_unlock(&iaxsl[callno]);
12157  reg->callno = 0;
12158  }
12159  if (ast_sockaddr_isnull(&reg->addr)) {
12160  if (iaxdebug)
12161  ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
12162  /* Setup the next registration attempt */
12163  reg->expire = iax2_sched_replace(reg->expire, sched,
12164  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12165  return -1;
12166  }
12167  if (!ast_sockaddr_port(&reg->addr) && reg->port) {
12168  ast_sockaddr_set_port(&reg->addr, reg->port);
12169  }
12170 
12171  if (!reg->callno) {
12172 
12173  ast_debug(3, "Allocate call number\n");
12174 
12175  reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
12176  if (reg->callno < 1) {
12177  ast_log(LOG_WARNING, "Unable to create call for registration\n");
12178  return -1;
12179  } else
12180  ast_debug(3, "Registration created on call %d\n", reg->callno);
12181  iaxs[reg->callno]->reg = reg;
12182  ast_mutex_unlock(&iaxsl[reg->callno]);
12183  }
12184  /* Setup the next registration a little early */
12185  reg->expire = iax2_sched_replace(reg->expire, sched,
12186  (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
12187  /* Send the request */
12188  memset(&ied, 0, sizeof(ied));
12191  add_empty_calltoken_ie(iaxs[reg->callno], &ied); /* this _MUST_ be the last ie added */
12192  send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
12193  reg->regstate = REG_STATE_REGSENT;
12194  return 0;
12195 }
12196 
12197 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
12198 {
12199  /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
12200  is found for template */
12201  struct iax_ie_data provdata;
12202  struct iax_ie_data ied;
12203  unsigned int sig;
12204  struct ast_sockaddr addr;
12205  int callno;
12206  struct create_addr_info cai;
12207 
12208  memset(&cai, 0, sizeof(cai));
12209 
12210  ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
12211 
12212  if (iax_provision_build(&provdata, &sig, template, force)) {
12213  ast_debug(1, "No provisioning found for template '%s'\n", template);
12214  return 0;
12215  }
12216 
12217  if (end) {
12218  ast_sockaddr_copy(&addr, end);
12219  cai.sockfd = sockfd;
12220  } else if (create_addr(dest, NULL, &addr, &cai))
12221  return -1;
12222 
12223  /* Build the rest of the message */
12224  memset(&ied, 0, sizeof(ied));
12225  iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
12226 
12227  callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12228  if (!callno)
12229  return -1;
12230 
12231  if (iaxs[callno]) {
12232  /* Schedule autodestruct in case they don't ever give us anything back */
12233  iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
12234  sched, 15000, auto_hangup, (void *)(long)callno);
12235  ast_set_flag64(iaxs[callno], IAX_PROVISION);
12236  /* Got a call number now, so go ahead and send the provisioning information */
12237  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
12238  }
12239  ast_mutex_unlock(&iaxsl[callno]);
12240 
12241  return 1;
12242 }
12243 
12244 static char *papp = "IAX2Provision";
12245 
12246 /*! iax2provision
12247 \ingroup applications
12248 */
12249 static int iax2_prov_app(struct ast_channel *chan, const char *data)
12250 {
12251  int res;
12252  char *sdata;
12253  char *opts;
12254  int force =0;
12255  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
12256  if (ast_strlen_zero(data))
12257  data = "default";
12258  sdata = ast_strdupa(data);
12259  opts = strchr(sdata, '|');
12260  if (opts)
12261  *opts='\0';
12262 
12263  if (ast_channel_tech(chan) != &iax2_tech) {
12264  ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
12265  return -1;
12266  }
12267  if (!callno || !iaxs[callno] || ast_sockaddr_isnull(&iaxs[callno]->addr)) {
12268  ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
12269  return -1;
12270  }
12271  res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
12272  ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
12273  ast_sockaddr_stringify(&iaxs[callno]->addr),
12274  sdata, res);
12275  return res;
12276 }
12277 
12278 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
12279 {
12280  int force = 0;
12281  int res;
12282 
12283  switch (cmd) {
12284  case CLI_INIT:
12285  e->command = "iax2 provision";
12286  e->usage =
12287  "Usage: iax2 provision <host> <template> [forced]\n"
12288  " Provisions the given peer or IP address using a template\n"
12289  " matching either 'template' or '*' if the template is not\n"
12290  " found. If 'forced' is specified, even empty provisioning\n"
12291  " fields will be provisioned as empty fields.\n";
12292  return NULL;
12293  case CLI_GENERATE:
12294  if (a->pos == 3)
12295  return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
12296  return NULL;
12297  }
12298 
12299  if (a->argc < 4)
12300  return CLI_SHOWUSAGE;
12301  if (a->argc > 4) {
12302  if (!strcasecmp(a->argv[4], "forced"))
12303  force = 1;
12304  else
12305  return CLI_SHOWUSAGE;
12306  }
12307  res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
12308  if (res < 0)
12309  ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
12310  else if (res < 1)
12311  ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
12312  else
12313  ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
12314  return CLI_SUCCESS;
12315 }
12316 
12317 static void __iax2_poke_noanswer(const void *data)
12318 {
12319  struct iax2_peer *peer = (struct iax2_peer *)data;
12320  int callno;
12321 
12322  if (peer->lastms > -1) {
12323  RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
12324 
12325  ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
12327  blob = ast_json_pack("{s: s, s: i}",
12328  "peer_status", "Unreachable",
12329  "time", peer->lastms);
12331  ast_devstate_changed(AST_DEVICE_UNAVAILABLE, AST_DEVSTATE_CACHABLE, "IAX2/%s", peer->name); /* Activate notification */
12332  }
12333  if ((callno = peer->callno) > 0) {
12334  ast_mutex_lock(&iaxsl[callno]);
12335  iax2_destroy(callno);
12336  ast_mutex_unlock(&iaxsl[callno]);
12337  }
12338  peer->callno = 0;
12339  peer->lastms = -1;
12340  /* Try again quickly */
12341  peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12342  if (peer->pokeexpire == -1)
12343  peer_unref(peer);
12344 }
12345 
12346 static int iax2_poke_noanswer(const void *data)
12347 {
12348  struct iax2_peer *peer = (struct iax2_peer *)data;
12349  peer->pokeexpire = -1;
12350 #ifdef SCHED_MULTITHREADED
12352 #endif
12353  __iax2_poke_noanswer(data);
12354  peer_unref(peer);
12355  return 0;
12356 }
12357 
12358 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12359 {
12360  struct iax2_peer *peer = obj;
12361 
12362  iax2_poke_peer(peer, 0);
12363 
12364  return 0;
12365 }
12366 
12367 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12368 {
12369  int callno;
12370  int poke_timeout;
12371 
12372  if (!peer->maxms || (ast_sockaddr_isnull(&peer->addr) && !peer->dnsmgr)) {
12373  /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
12374  immediately after clearing things out */
12375  peer->lastms = 0;
12376  peer->historicms = 0;
12377  peer->pokeexpire = -1;
12378  peer->callno = 0;
12379  return 0;
12380  }
12381 
12382  /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
12383  if ((callno = peer->callno) > 0) {
12384  ast_log(LOG_NOTICE, "Still have a callno...\n");
12385  ast_mutex_lock(&iaxsl[callno]);
12386  iax2_destroy(callno);
12387  ast_mutex_unlock(&iaxsl[callno]);
12388  }
12389  if (heldcall)
12390  ast_mutex_unlock(&iaxsl[heldcall]);
12391  callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
12392  if (heldcall)
12393  ast_mutex_lock(&iaxsl[heldcall]);
12394  if (callno < 1) {
12395  ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12396  return -1;
12397  }
12398 
12399  if (peer->pokeexpire > -1) {
12400  if (!AST_SCHED_DEL(sched, peer->pokeexpire)) {
12401  peer->pokeexpire = -1;
12402  peer_unref(peer);
12403  }
12404  }
12405 
12406  if (peer->lastms < 0){
12407  /* If the host is already unreachable then use time less than the unreachable
12408  * interval. 5/6 is arbitrary multiplier to get value less than
12409  * peer->pokefreqnotok. Value less than peer->pokefreqnotok is used to expire
12410  * current POKE before starting new POKE (which is scheduled after
12411  * peer->pokefreqnotok). */
12412  poke_timeout = peer->pokefreqnotok * 5 / 6;
12413  } else {
12414  /* If the host is reachable, use timeout large enough to allow for multiple
12415  * POKE retries. Limit this value to less than peer->pokefreqok. 5/6 is arbitrary
12416  * multiplier to get value less than peer->pokefreqok. Value less than
12417  * peer->pokefreqok is used to expire current POKE before starting new POKE
12418  * (which is scheduled after peer->pokefreqok). */
12419  poke_timeout = MIN(MAX_RETRY_TIME * 2 + peer->maxms, peer->pokefreqok * 5 / 6);
12420  }
12421 
12422  /* Queue up a new task to handle no reply */
12423  peer->pokeexpire = iax2_sched_add(sched, poke_timeout, iax2_poke_noanswer, peer_ref(peer));
12424 
12425  if (peer->pokeexpire == -1)
12426  peer_unref(peer);
12427 
12428  /* And send the poke */
12429  ast_mutex_lock(&iaxsl[callno]);
12430  if (iaxs[callno]) {
12431  struct iax_ie_data ied = {
12432  .buf = { 0 },
12433  .pos = 0,
12434  };
12435 
12436  /* Speed up retransmission times for this qualify call */
12437  iaxs[callno]->pingtime = peer->maxms / 8;
12438  iaxs[callno]->peerpoke = peer;
12439 
12440  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
12441  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12442  }
12443  ast_mutex_unlock(&iaxsl[callno]);
12444 
12445  return 0;
12446 }
12447 
12448 static void free_context(struct iax2_context *con)
12449 {
12450  struct iax2_context *conl;
12451  while(con) {
12452  conl = con;
12453  con = con->next;
12454  ast_free(conl);
12455  }
12456 }
12457 
12458 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)
12459 {
12460  int callno;
12461  int res;
12462  struct ast_sockaddr addr;
12463  struct ast_channel *c;
12464  struct parsed_dial_string pds;
12465  struct create_addr_info cai;
12466  char *tmpstr;
12467  ast_callid callid;
12468 
12469  memset(&pds, 0, sizeof(pds));
12470  tmpstr = ast_strdupa(data);
12471  parse_dial_string(tmpstr, &pds);
12472 
12473  callid = ast_read_threadstorage_callid();
12474 
12475  if (ast_strlen_zero(pds.peer)) {
12476  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
12477  return NULL;
12478  }
12479  memset(&cai, 0, sizeof(cai));
12481 
12483 
12484  /* Populate our address from the given */
12485  if (create_addr(pds.peer, NULL, &addr, &cai)) {
12486  *cause = AST_CAUSE_UNREGISTERED;
12487  return NULL;
12488  }
12489 
12490  if (pds.port) {
12491  int bindport;
12492  ast_parse_arg(pds.port, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535);
12493  ast_sockaddr_set_port(&addr, bindport);
12494  }
12495 
12496  callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
12497  if (callno < 1) {
12498  ast_log(LOG_WARNING, "Unable to create call\n");
12499  *cause = AST_CAUSE_CONGESTION;
12500  return NULL;
12501  }
12502 
12503  /* If this is a trunk, update it now */
12505  if (ast_test_flag64(&cai, IAX_TRUNK)) {
12506  int new_callno;
12507  if ((new_callno = make_trunk(callno, 1)) != -1)
12508  callno = new_callno;
12509  }
12510  iaxs[callno]->maxtime = cai.maxtime;
12511  if (callid) {
12512  iax_pvt_callid_set(callno, callid);
12513  }
12514 
12515  if (cai.found) {
12516  ast_string_field_set(iaxs[callno], host, pds.peer);
12517  }
12518 
12519  c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, &cai.prefs, assignedids,
12520  requestor, cai.found);
12521 
12522  ast_mutex_unlock(&iaxsl[callno]);
12523 
12524  if (c) {
12525  struct ast_format_cap *joint;
12526  struct ast_format *format;
12527  if (callid) {
12528  ast_channel_lock(c);
12529  ast_channel_callid_set(c, callid);
12530  ast_channel_unlock(c);
12531  }
12532 
12534  if (!joint) {
12535  ast_hangup(c);
12536  return NULL;
12537  }
12538 
12540 
12541  /* If there is no joint format find one through translation */
12542  if (!ast_format_cap_count(joint)) {
12543  struct ast_format *best_fmt_cap = NULL;
12544  struct ast_format *best_fmt_native = NULL;
12545 
12546  res = ast_translator_best_choice(cap, ast_channel_nativeformats(c), &best_fmt_cap, &best_fmt_native);
12547  if (res < 0) {
12548  struct ast_str *native_cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12549  struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
12550 
12551  ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12553  ast_format_cap_get_names(cap, &cap_buf),
12554  ast_channel_name(c));
12555  ast_hangup(c);
12556  ao2_ref(joint, -1);
12557  return NULL;
12558  }
12559  ast_format_cap_append(joint, best_fmt_native, 0);
12560  ao2_ref(best_fmt_cap, -1);
12561  ao2_ref(best_fmt_native, -1);
12562  }
12565  ast_channel_set_readformat(c, format);
12566  ast_channel_set_writeformat(c, format);
12567 
12568  ao2_ref(joint, -1);
12569  ao2_ref(format, -1);
12570  }
12571 
12572  return c;
12573 }
12574 
12575 static void *network_thread(void *ignore)
12576 {
12577  int res;
12578 
12579  if (timer) {
12581  }
12582 
12583  for (;;) {
12584  pthread_testcancel();
12585  /* Wake up once a second just in case SIGURG was sent while
12586  * we weren't in poll(), to make sure we don't hang when trying
12587  * to unload. */
12588  res = ast_io_wait(io, 1000);
12589  /* Timeout(=0), and EINTR is not a thread exit condition. We do
12590  * not want to exit the thread loop on these conditions. */
12591  if (res < 0 && errno != -EINTR) {
12592  ast_log(LOG_ERROR, "IAX2 network thread unexpected exit: %s\n", strerror(errno));
12593  break;
12594  }
12595  }
12596 
12597  return NULL;
12598 }
12599 
12600 static int start_network_thread(void)
12601 {
12602  struct iax2_thread *thread;
12603  int threadcount = 0;
12604  int x;
12605  for (x = 0; x < iaxthreadcount; x++) {
12606  thread = ast_calloc(1, sizeof(*thread));
12607  if (thread) {
12608  thread->type = IAX_THREAD_TYPE_POOL;
12609  thread->threadnum = ++threadcount;
12610  ast_mutex_init(&thread->lock);
12611  ast_cond_init(&thread->cond, NULL);
12612  ast_mutex_init(&thread->init_lock);
12613  ast_cond_init(&thread->init_cond, NULL);
12614 
12615  ast_mutex_lock(&thread->init_lock);
12616 
12618  ast_log(LOG_WARNING, "Failed to create new thread!\n");
12619  ast_mutex_destroy(&thread->lock);
12620  ast_cond_destroy(&thread->cond);
12621  ast_mutex_unlock(&thread->init_lock);
12622  ast_mutex_destroy(&thread->init_lock);
12623  ast_cond_destroy(&thread->init_cond);
12624  ast_free(thread);
12625  thread = NULL;
12626  continue;
12627  }
12628  /* Wait for the thread to be ready */
12629  ast_cond_wait(&thread->init_cond, &thread->init_lock);
12630 
12631  /* Done with init_lock */
12632  ast_mutex_unlock(&thread->init_lock);
12633 
12635  AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12637  }
12638  }
12640  ast_log(LOG_ERROR, "Failed to create new thread!\n");
12641  return -1;
12642  }
12643  ast_verb(2, "%d helper threads started\n", threadcount);
12644  return 0;
12645 }
12646 
12647 static struct iax2_context *build_context(const char *context)
12648 {
12649  struct iax2_context *con;
12650 
12651  if ((con = ast_calloc(1, sizeof(*con))))
12652  ast_copy_string(con->context, context, sizeof(con->context));
12653 
12654  return con;
12655 }
12656 
12657 static int get_auth_methods(const char *value)
12658 {
12659  int methods = 0;
12660  if (strstr(value, "rsa"))
12661  methods |= IAX_AUTH_RSA;
12662  if (strstr(value, "md5"))
12663  methods |= IAX_AUTH_MD5;
12664  if (strstr(value, "plaintext"))
12665  methods |= IAX_AUTH_PLAINTEXT;
12666  return methods;
12667 }
12668 
12669 
12670 /*! \brief Check if address can be used as packet source.
12671  \return 0 address available, 1 address unavailable, -1 error
12672 */
12673 static int check_srcaddr(struct ast_sockaddr *addr)
12674 {
12675  int sd;
12676 
12677  sd = socket(addr->ss.ss_family, SOCK_DGRAM, 0);
12678  if (sd < 0) {
12679  ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12680  return -1;
12681  }
12682 
12683  if (ast_bind(sd, addr) < 0) {
12684  ast_debug(1, "Can't bind: %s\n", strerror(errno));
12685  close(sd);
12686  return 1;
12687  }
12688 
12689  close(sd);
12690  return 0;
12691 }
12692 
12693 /*! \brief Parse the "sourceaddress" value,
12694  lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
12695  not found. */
12696 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12697 {
12698  struct ast_sockaddr addr;
12699  int nonlocal = 1;
12700  int port = IAX_DEFAULT_PORTNO;
12701  int sockfd = defaultsockfd;
12702  char *tmp;
12703  char *host;
12704  char *portstr;
12705 
12706  tmp = ast_strdupa(srcaddr);
12707  ast_sockaddr_split_hostport(tmp, &host, &portstr, 0);
12708 
12709  if (portstr) {
12710  port = atoi(portstr);
12711  if (port < 1)
12712  port = IAX_DEFAULT_PORTNO;
12713  }
12714 
12715  addr.ss.ss_family = AST_AF_UNSPEC;
12716  if (!ast_get_ip(&addr, host)) {
12717  struct ast_netsock *sock;
12718 
12719  if (check_srcaddr(&addr) == 0) {
12720  /* ip address valid. */
12721  ast_sockaddr_set_port(&addr, port);
12722 
12723  if (!(sock = ast_netsock_find(netsock, &addr)))
12724  sock = ast_netsock_find(outsock, &addr);
12725  if (sock) {
12726  sockfd = ast_netsock_sockfd(sock);
12727  nonlocal = 0;
12728  } else {
12729  /* INADDR_ANY matches anyway! */
12730  ast_sockaddr_parse(&addr, "0.0.0.0", 0);
12731  ast_sockaddr_set_port(&addr, port);
12732  if (ast_netsock_find(netsock, &addr)) {
12733  sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12734  if (sock) {
12735  sockfd = ast_netsock_sockfd(sock);
12736  ast_netsock_unref(sock);
12737  nonlocal = 0;
12738  } else {
12739  nonlocal = 2;
12740  }
12741  }
12742  }
12743  }
12744  }
12745 
12746  peer->sockfd = sockfd;
12747 
12748  if (nonlocal == 1) {
12750  "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12751  srcaddr,
12752  peer->name);
12753  return -1;
12754  } else if (nonlocal == 2) {
12756  "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12757  srcaddr,
12758  peer->name);
12759  return -1;
12760  } else {
12761  ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12762  return 0;
12763  }
12764 }
12765 
12766 static void peer_destructor(void *obj)
12767 {
12768  struct iax2_peer *peer = obj;
12769  int callno = peer->callno;
12770 
12771  ast_free_acl_list(peer->acl);
12772 
12773  if (callno > 0) {
12774  ast_mutex_lock(&iaxsl[callno]);
12775  iax2_destroy(callno);
12776  ast_mutex_unlock(&iaxsl[callno]);
12777  }
12778 
12779  register_peer_exten(peer, 0);
12780 
12781  if (peer->dnsmgr)
12782  ast_dnsmgr_release(peer->dnsmgr);
12783 
12784  if (peer->mwi_event_sub) {
12786  }
12787 
12789 
12791 }
12792 
12793 /*! \brief Create peer structure based on configuration */
12794 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12795 {
12796  struct iax2_peer *peer = NULL;
12797  struct ast_acl_list *oldacl = NULL;
12798  int maskfound = 0;
12799  int found = 0;
12800  int firstpass = 1;
12801  int subscribe_acl_change = 0;
12802 
12803  if (!temponly) {
12804  peer = ao2_find(peers, name, OBJ_KEY);
12805  if (peer && !ast_test_flag64(peer, IAX_DELME))
12806  firstpass = 0;
12807  }
12808 
12809  if (peer) {
12810  found++;
12811  if (firstpass) {
12812  oldacl = peer->acl;
12813  peer->acl = NULL;
12814  }
12815  unlink_peer(peer);
12816  } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12817  peer->expire = -1;
12818  peer->pokeexpire = -1;
12819  peer->sockfd = defaultsockfd;
12820  if (ast_string_field_init(peer, 32))
12821  peer = peer_unref(peer);
12822  if (!(peer->endpoint = ast_endpoint_create("IAX2", name))) {
12823  peer = peer_unref(peer);
12824  }
12825  }
12826 
12827  if (peer) {
12828  if (firstpass) {
12830  peer->encmethods = iax2_encryption;
12831  peer->authmethods = iax2_authmethods;
12832  peer->adsi = adsi;
12833  ast_string_field_set(peer, secret, "");
12834  if (!found) {
12835  ast_string_field_set(peer, name, name);
12836  ast_sockaddr_parse(&peer->addr, "0.0.0.0", 0);
12838  peer->expiry = min_reg_expire;
12839  }
12840  peer->prefs = prefs_global;
12841  peer->capability = iax2_capability;
12842  peer->smoothing = 0;
12843  peer->pokefreqok = DEFAULT_FREQ_OK;
12845  peer->maxcallno = 0;
12846  peercnt_modify((unsigned char) 0, 0, &peer->addr);
12848  ast_string_field_set(peer,context,"");
12849  ast_string_field_set(peer,peercontext,"");
12851  ast_string_field_set(peer, cid_name, "");
12852  ast_string_field_set(peer, cid_num, "");
12855  }
12856 
12857  if (!v) {
12858  v = alt;
12859  alt = NULL;
12860  }
12861  while(v) {
12862  if (!strcasecmp(v->name, "secret")) {
12863  ast_string_field_set(peer, secret, v->value);
12864  } else if (!strcasecmp(v->name, "mailbox")) {
12865  ast_string_field_set(peer, mailbox, v->value);
12866  } else if (!strcasecmp(v->name, "hasvoicemail")) {
12867  if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12868  /*
12869  * hasvoicemail is a users.conf legacy voicemail enable method.
12870  * hasvoicemail is only going to work for app_voicemail mailboxes.
12871  */
12872  if (strchr(name, '@')) {
12873  ast_string_field_set(peer, mailbox, name);
12874  } else {
12875  ast_string_field_build(peer, mailbox, "%s@default", name);
12876  }
12877  }
12878  } else if (!strcasecmp(v->name, "mohinterpret")) {
12880  } else if (!strcasecmp(v->name, "mohsuggest")) {
12882  } else if (!strcasecmp(v->name, "dbsecret")) {
12883  ast_string_field_set(peer, dbsecret, v->value);
12884  } else if (!strcasecmp(v->name, "description")) {
12885  ast_string_field_set(peer, description, v->value);
12886  } else if (!strcasecmp(v->name, "trunk")) {
12888  if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12889  ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12890  ast_clear_flag64(peer, IAX_TRUNK);
12891  }
12892  } else if (!strcasecmp(v->name, "auth")) {
12893  peer->authmethods = get_auth_methods(v->value);
12894  if (peer->authmethods & IAX_AUTH_PLAINTEXT) {
12895  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);
12896  }
12897  } else if (!strcasecmp(v->name, "encryption")) {
12898  peer->encmethods |= get_encrypt_methods(v->value);
12899  if (!peer->encmethods) {
12901  }
12902  } else if (!strcasecmp(v->name, "forceencryption")) {
12903  if (ast_false(v->value)) {
12905  } else {
12906  peer->encmethods |= get_encrypt_methods(v->value);
12907  if (peer->encmethods) {
12909  }
12910  }
12911  } else if (!strcasecmp(v->name, "transfer")) {
12912  if (!strcasecmp(v->value, "mediaonly")) {
12914  } else if (ast_true(v->value)) {
12916  } else
12918  } else if (!strcasecmp(v->name, "jitterbuffer")) {
12920  } else if (!strcasecmp(v->name, "host")) {
12921  if (!strcasecmp(v->value, "dynamic")) {
12922  /* They'll register with us */
12923  ast_set_flag64(peer, IAX_DYNAMIC);
12924  if (!found) {
12925  int peer_port = ast_sockaddr_port(&peer->addr);
12926  if (peer_port) {
12927  ast_sockaddr_set_port(&peer->defaddr, peer_port);
12928  }
12929  ast_sockaddr_setnull(&peer->addr);
12930  }
12931  } else {
12932  /* Non-dynamic. Make sure we become that way if we're not */
12933  AST_SCHED_DEL(sched, peer->expire);
12935  if (peer->dnsmgr) {
12936  // Make sure we refresh dnsmgr if we're using it
12937  ast_dnsmgr_refresh(peer->dnsmgr);
12938  } else {
12939  // Or just invalidate the address
12940  peer->addr.ss.ss_family = AST_AF_UNSPEC;
12941  }
12942  if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL)) {
12943  return peer_unref(peer);
12944  }
12945  if (!ast_sockaddr_port(&peer->addr)) {
12947  }
12948  }
12949  } else if (!strcasecmp(v->name, "defaultip")) {
12950  struct ast_sockaddr peer_defaddr_tmp;
12951  peer_defaddr_tmp.ss.ss_family = AF_UNSPEC;
12952  if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12953  return peer_unref(peer);
12954  }
12955  ast_sockaddr_set_port(&peer_defaddr_tmp, ast_sockaddr_port(&peer->defaddr));
12956  ast_sockaddr_copy(&peer->defaddr, &peer_defaddr_tmp);
12957  } else if (!strcasecmp(v->name, "sourceaddress")) {
12958  peer_set_srcaddr(peer, v->value);
12959  } else if (!strcasecmp(v->name, "permit") ||
12960  !strcasecmp(v->name, "deny") ||
12961  !strcasecmp(v->name, "acl")) {
12962  ast_append_acl(v->name, v->value, &peer->acl, NULL, &subscribe_acl_change);
12963  } else if (!strcasecmp(v->name, "mask")) {
12964  maskfound++;
12965  ast_sockaddr_parse(&peer->mask, v->value, 0);
12966  } else if (!strcasecmp(v->name, "context")) {
12967  ast_string_field_set(peer, context, v->value);
12968  } else if (!strcasecmp(v->name, "regexten")) {
12969  ast_string_field_set(peer, regexten, v->value);
12970  } else if (!strcasecmp(v->name, "peercontext")) {
12971  ast_string_field_set(peer, peercontext, v->value);
12972  } else if (!strcasecmp(v->name, "port")) {
12973  int bindport;
12974  if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
12975  bindport = IAX_DEFAULT_PORTNO;
12976  }
12977  if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12978  ast_sockaddr_set_port(&peer->defaddr, bindport);
12979  } else {
12980  ast_sockaddr_set_port(&peer->addr, bindport);
12981  }
12982  } else if (!strcasecmp(v->name, "username")) {
12983  ast_string_field_set(peer, username, v->value);
12984  } else if (!strcasecmp(v->name, "allow")) {
12985  iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12986  } else if (!strcasecmp(v->name, "disallow")) {
12987  iax2_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12988  } else if (!strcasecmp(v->name, "callerid")) {
12989  if (!ast_strlen_zero(v->value)) {
12990  char name2[80];
12991  char num2[80];
12992  ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12993  ast_string_field_set(peer, cid_name, name2);
12994  ast_string_field_set(peer, cid_num, num2);
12995  } else {
12996  ast_string_field_set(peer, cid_name, "");
12997  ast_string_field_set(peer, cid_num, "");
12998  }
13000  } else if (!strcasecmp(v->name, "fullname")) {
13001  ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
13003  } else if (!strcasecmp(v->name, "cid_number")) {
13004  ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
13006  } else if (!strcasecmp(v->name, "sendani")) {
13008  } else if (!strcasecmp(v->name, "inkeys")) {
13009  ast_string_field_set(peer, inkeys, v->value);
13010  } else if (!strcasecmp(v->name, "outkey")) {
13011  ast_string_field_set(peer, outkey, v->value);
13012  } else if (!strcasecmp(v->name, "qualify")) {
13013  if (!strcasecmp(v->value, "no")) {
13014  peer->maxms = 0;
13015  } else if (!strcasecmp(v->value, "yes")) {
13016  peer->maxms = DEFAULT_MAXMS;
13017  } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
13018  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);
13019  peer->maxms = 0;
13020  }
13021  } else if (!strcasecmp(v->name, "qualifysmoothing")) {
13022  peer->smoothing = ast_true(v->value);
13023  } else if (!strcasecmp(v->name, "qualifyfreqok")) {
13024  if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
13025  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);
13026  }
13027  } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
13028  if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
13029  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);
13030  }
13031  } else if (!strcasecmp(v->name, "timezone")) {
13032  ast_string_field_set(peer, zonetag, v->value);
13033  } else if (!strcasecmp(v->name, "adsi")) {
13034  peer->adsi = ast_true(v->value);
13035  } else if (!strcasecmp(v->name, "connectedline")) {
13036  if (ast_true(v->value)) {
13038  } else if (!strcasecmp(v->value, "send")) {
13041  } else if (!strcasecmp(v->value, "receive")) {
13044  } else {
13046  }
13047  } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13048  if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
13049  ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13050  } else {
13051  peercnt_modify((unsigned char) 1, peer->maxcallno, &peer->addr);
13052  }
13053  } else if (!strcasecmp(v->name, "requirecalltoken")) {
13054  /* default is required unless in optional ip list */
13055  if (ast_false(v->value)) {
13057  } else if (!strcasecmp(v->value, "auto")) {
13059  } else if (ast_true(v->value)) {
13061  } else {
13062  ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13063  }
13064  } /* else if (strcasecmp(v->name,"type")) */
13065  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13066  v = v->next;
13067  if (!v) {
13068  v = alt;
13069  alt = NULL;
13070  }
13071  }
13072  if (!peer->authmethods)
13073  peer->authmethods = IAX_AUTH_MD5;
13074  ast_clear_flag64(peer, IAX_DELME);
13075  }
13076 
13077  if (!maskfound && !ast_sockaddr_isnull(&peer->addr)) {
13078  if (ast_sockaddr_is_ipv4_mapped(&peer->addr)) {
13079  ast_sockaddr_parse(&peer->mask, "::ffff:ffff:ffff", 0);
13080  } else if (ast_sockaddr_is_ipv6(&peer->addr)) {
13081  ast_sockaddr_parse(&peer->mask, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0);
13082  } else {
13083  ast_sockaddr_parse(&peer->mask, "255.255.255.255", 0);
13084  }
13085  }
13086 
13087  if (oldacl) {
13088  ast_free_acl_list(oldacl);
13089  }
13090 
13091  if (!ast_strlen_zero(peer->mailbox) && !peer->mwi_event_sub) {
13092  /* The MWI subscriptions exist just so the core knows we care about those
13093  * mailboxes. However, we just grab the events out of the cache when it
13094  * is time to send MWI, since it is only sent with a REGACK. */
13096  }
13097 
13098  if (subscribe_acl_change) {
13100  }
13101 
13102  return peer;
13103 }
13104 
13105 static void user_destructor(void *obj)
13106 {
13107  struct iax2_user *user = obj;
13108 
13109  ast_free_acl_list(user->acl);
13110  free_context(user->contexts);
13111  if(user->vars) {
13112  ast_variables_destroy(user->vars);
13113  user->vars = NULL;
13114  }
13116 }
13117 
13118 /*! \brief Create in-memory user structure from configuration */
13119 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
13120 {
13121  struct iax2_user *user = NULL;
13122  struct iax2_context *con, *conl = NULL;
13123  struct ast_acl_list *oldacl = NULL;
13124  struct iax2_context *oldcon = NULL;
13125  int format;
13126  int firstpass=1;
13127  int oldcurauthreq = 0;
13128  int subscribe_acl_change = 0;
13129  char *varname = NULL, *varval = NULL;
13130  struct ast_variable *tmpvar = NULL;
13131 
13132  if (!temponly) {
13133  user = ao2_find(users, name, OBJ_KEY);
13134  if (user && !ast_test_flag64(user, IAX_DELME))
13135  firstpass = 0;
13136  }
13137 
13138  if (user) {
13139  if (firstpass) {
13140  oldcurauthreq = user->curauthreq;
13141  oldacl = user->acl;
13142  oldcon = user->contexts;
13143  user->acl = NULL;
13144  user->contexts = NULL;
13145  }
13146  /* Already in the list, remove it and it will be added back (or FREE'd) */
13147  ao2_unlink(users, user);
13148  } else {
13149  user = ao2_alloc(sizeof(*user), user_destructor);
13150  }
13151 
13152  if (user) {
13153  if (firstpass) {
13155  memset(user, 0, sizeof(struct iax2_user));
13156  if (ast_string_field_init(user, 32)) {
13157  user = user_unref(user);
13158  goto cleanup;
13159  }
13160  user->maxauthreq = maxauthreq;
13161  user->curauthreq = oldcurauthreq;
13162  user->prefs = prefs_global;
13163  user->capability = iax2_capability;
13164  user->encmethods = iax2_encryption;
13165  user->authmethods = iax2_authmethods;
13166  user->adsi = adsi;
13168  ast_string_field_set(user, name, name);
13172  ast_string_field_set(user, cid_name, "");
13173  ast_string_field_set(user, cid_num, "");
13177  }
13178  if (!v) {
13179  v = alt;
13180  alt = NULL;
13181  }
13182  while(v) {
13183  if (!strcasecmp(v->name, "context")) {
13184  con = build_context(v->value);
13185  if (con) {
13186  if (conl)
13187  conl->next = con;
13188  else
13189  user->contexts = con;
13190  conl = con;
13191  }
13192  } else if (!strcasecmp(v->name, "permit") ||
13193  !strcasecmp(v->name, "deny") ||
13194  !strcasecmp(v->name, "acl")) {
13195  ast_append_acl(v->name, v->value, &user->acl, NULL, &subscribe_acl_change);
13196  } else if (!strcasecmp(v->name, "setvar")) {
13197  varname = ast_strdupa(v->value);
13198  if ((varval = strchr(varname, '='))) {
13199  *varval = '\0';
13200  varval++;
13201  if ((tmpvar = ast_variable_new(varname, varval, ""))) {
13202  if (ast_variable_list_replace(&user->vars, tmpvar)) {
13203  tmpvar->next = user->vars;
13204  user->vars = tmpvar;
13205  }
13206  }
13207  }
13208  } else if (!strcasecmp(v->name, "allow")) {
13209  iax2_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
13210  } else if (!strcasecmp(v->name, "disallow")) {
13211  iax2_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
13212  } else if (!strcasecmp(v->name, "trunk")) {
13214  if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
13215  ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
13216  ast_clear_flag64(user, IAX_TRUNK);
13217  }
13218  } else if (!strcasecmp(v->name, "auth")) {
13219  user->authmethods = get_auth_methods(v->value);
13220  if (user->authmethods & IAX_AUTH_PLAINTEXT) {
13221  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);
13222  }
13223  } else if (!strcasecmp(v->name, "encryption")) {
13224  user->encmethods |= get_encrypt_methods(v->value);
13225  if (!user->encmethods) {
13227  }
13228  } else if (!strcasecmp(v->name, "forceencryption")) {
13229  if (ast_false(v->value)) {
13231  } else {
13232  user->encmethods |= get_encrypt_methods(v->value);
13233  if (user->encmethods) {
13235  }
13236  }
13237  } else if (!strcasecmp(v->name, "transfer")) {
13238  if (!strcasecmp(v->value, "mediaonly")) {
13240  } else if (ast_true(v->value)) {
13242  } else
13244  } else if (!strcasecmp(v->name, "codecpriority")) {
13245  if(!strcasecmp(v->value, "caller"))
13247  else if(!strcasecmp(v->value, "disabled"))
13249  else if(!strcasecmp(v->value, "reqonly")) {
13252  }
13253  } else if (!strcasecmp(v->name, "immediate")) {
13255  } else if (!strcasecmp(v->name, "jitterbuffer")) {
13257  } else if (!strcasecmp(v->name, "dbsecret")) {
13258  ast_string_field_set(user, dbsecret, v->value);
13259  } else if (!strcasecmp(v->name, "secret")) {
13260  if (!ast_strlen_zero(user->secret)) {
13261  char *old = ast_strdupa(user->secret);
13262 
13263  ast_string_field_build(user, secret, "%s;%s", old, v->value);
13264  } else
13265  ast_string_field_set(user, secret, v->value);
13266  } else if (!strcasecmp(v->name, "callerid")) {
13267  if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
13268  char name2[80];
13269  char num2[80];
13270  ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
13271  ast_string_field_set(user, cid_name, name2);
13272  ast_string_field_set(user, cid_num, num2);
13274  } else {
13276  ast_string_field_set(user, cid_name, "");
13277  ast_string_field_set(user, cid_num, "");
13278  }
13279  } else if (!strcasecmp(v->name, "fullname")) {
13280  if (!ast_strlen_zero(v->value)) {
13281  ast_string_field_set(user, cid_name, v->value);
13283  } else {
13284  ast_string_field_set(user, cid_name, "");
13285  if (ast_strlen_zero(user->cid_num))
13287  }
13288  } else if (!strcasecmp(v->name, "cid_number")) {
13289  if (!ast_strlen_zero(v->value)) {
13290  ast_string_field_set(user, cid_num, v->value);
13292  } else {
13293  ast_string_field_set(user, cid_num, "");
13294  if (ast_strlen_zero(user->cid_name))
13296  }
13297  } else if (!strcasecmp(v->name, "accountcode")) {
13299  } else if (!strcasecmp(v->name, "mohinterpret")) {
13301  } else if (!strcasecmp(v->name, "mohsuggest")) {
13303  } else if (!strcasecmp(v->name, "parkinglot")) {
13305  } else if (!strcasecmp(v->name, "language")) {
13306  ast_string_field_set(user, language, v->value);
13307  } else if (!strcasecmp(v->name, "amaflags")) {
13308  format = ast_channel_string2amaflag(v->value);
13309  if (format < 0) {
13310  ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13311  } else {
13312  user->amaflags = format;
13313  }
13314  } else if (!strcasecmp(v->name, "inkeys")) {
13315  ast_string_field_set(user, inkeys, v->value);
13316  } else if (!strcasecmp(v->name, "maxauthreq")) {
13317  user->maxauthreq = atoi(v->value);
13318  if (user->maxauthreq < 0)
13319  user->maxauthreq = 0;
13320  } else if (!strcasecmp(v->name, "adsi")) {
13321  user->adsi = ast_true(v->value);
13322  } else if (!strcasecmp(v->name, "connectedline")) {
13323  if (ast_true(v->value)) {
13325  } else if (!strcasecmp(v->value, "send")) {
13328  } else if (!strcasecmp(v->value, "receive")) {
13331  } else {
13333  }
13334  } else if (!strcasecmp(v->name, "requirecalltoken")) {
13335  /* default is required unless in optional ip list */
13336  if (ast_false(v->value)) {
13338  } else if (!strcasecmp(v->value, "auto")) {
13340  } else if (ast_true(v->value)) {
13342  } else {
13343  ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
13344  }
13345  } /* else if (strcasecmp(v->name,"type")) */
13346  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13347  v = v->next;
13348  if (!v) {
13349  v = alt;
13350  alt = NULL;
13351  }
13352  }
13353  if (!user->authmethods) {
13354  if (!ast_strlen_zero(user->secret)) {
13355  user->authmethods = IAX_AUTH_MD5;
13356  if (!ast_strlen_zero(user->inkeys))
13357  user->authmethods |= IAX_AUTH_RSA;
13358  } else if (!ast_strlen_zero(user->inkeys)) {
13359  user->authmethods = IAX_AUTH_RSA;
13360  } else {
13361  user->authmethods = IAX_AUTH_MD5;
13362  }
13363  }
13364  ast_clear_flag64(user, IAX_DELME);
13365  }
13366 cleanup:
13367  if (oldacl) {
13368  ast_free_acl_list(oldacl);
13369  }
13370  if (oldcon) {
13371  free_context(oldcon);
13372  }
13373 
13374  if (subscribe_acl_change) {
13376  }
13377 
13378  return user;
13379 }
13380 
13381 static int peer_delme_cb(void *obj, void *arg, int flags)
13382 {
13383  struct iax2_peer *peer = obj;
13384 
13385  ast_set_flag64(peer, IAX_DELME);
13386 
13387  return 0;
13388 }
13389 
13390 static int user_delme_cb(void *obj, void *arg, int flags)
13391 {
13392  struct iax2_user *user = obj;
13393 
13394  ast_set_flag64(user, IAX_DELME);
13395 
13396  return 0;
13397 }
13398 
13399 static void delete_users(void)
13400 {
13401  struct iax2_registry *reg;
13402 
13404 
13406  while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
13407  if (sched) {
13408  AST_SCHED_DEL(sched, reg->expire);
13409  }
13410  if (reg->callno) {
13411  int callno = reg->callno;
13412  ast_mutex_lock(&iaxsl[callno]);
13413  if (iaxs[callno]) {
13414  iaxs[callno]->reg = NULL;
13415  iax2_destroy(callno);
13416  }
13417  ast_mutex_unlock(&iaxsl[callno]);
13418  }
13419  if (reg->dnsmgr)
13420  ast_dnsmgr_release(reg->dnsmgr);
13421  ast_free(reg);
13422  }
13424 
13426 }
13427 
13428 static void prune_users(void)
13429 {
13430  struct iax2_user *user;
13431  struct ao2_iterator i;
13432 
13433  i = ao2_iterator_init(users, 0);
13434  while ((user = ao2_iterator_next(&i))) {
13436  ao2_unlink(users, user);
13437  }
13438  user_unref(user);
13439  }
13441 }
13442 
13443 /* Prune peers who still are supposed to be deleted */
13444 static void prune_peers(void)
13445 {
13446  struct iax2_peer *peer;
13447  struct ao2_iterator i;
13448 
13449  i = ao2_iterator_init(peers, 0);
13450  while ((peer = ao2_iterator_next(&i))) {
13452  unlink_peer(peer);
13453  }
13454  peer_unref(peer);
13455  }
13457 }
13458 
13459 static void set_config_destroy(void)
13460 {
13461  strcpy(accountcode, "");
13462  strcpy(language, "");
13463  strcpy(mohinterpret, "");
13464  strcpy(mohsuggest, "");
13466  amaflags = 0;
13467  delayreject = 0;
13470  delete_users();
13471  ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13472  ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13473 }
13474 
13475 /*! \brief Load configuration */
13476 static int set_config(const char *config_file, int reload, int forced)
13477 {
13478  struct ast_config *cfg, *ucfg;
13479  iax2_format capability;
13480  struct ast_variable *v;
13481  char *cat;
13482  const char *utype;
13483  const char *tosval;
13484  int format;
13485  int portno = IAX_DEFAULT_PORTNO;
13486  int x;
13487  int mtuv;
13488  int subscribe_network_change = 1;
13489  struct iax2_user *user;
13490  struct iax2_peer *peer;
13491  struct ast_netsock *ns;
13492  struct ast_flags config_flags = { (reload && !forced) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13493  struct ast_sockaddr bindaddr;
13494  struct iax2_codec_pref prefs_new;
13495 
13496  cfg = ast_config_load(config_file, config_flags);
13497 
13498  if (!cfg) {
13499  ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13500  return -1;
13501  } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13502  ucfg = ast_config_load("users.conf", config_flags);
13503  if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13504  return 0;
13505  /* Otherwise we need to reread both files */
13506  ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13507  if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13508  ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13509  ast_config_destroy(ucfg);
13510  return 0;
13511  }
13512  if (!cfg) {
13513  /* should have been able to load the config here */
13514  ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13515  return -1;
13516  }
13517  } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13518  ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13519  return 0;
13520  } else { /* iax.conf changed, gotta reread users.conf, too */
13521  ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13522  if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13523  ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13524  ast_config_destroy(cfg);
13525  return 0;
13526  }
13527  }
13528 
13529  if (reload) {
13531  }
13532 
13533  ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
13534 
13535  /* Setup new codec prefs */
13537 
13538  /* Reset Global Flags */
13539  memset(&globalflags, 0, sizeof(globalflags));
13540  ast_set_flag64(&globalflags, IAX_RTUPDATE);
13541  ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13542 
13543 #ifdef SO_NO_CHECK
13544  nochecksums = 0;
13545 #endif
13546  /* Reset default parking lot */
13547  default_parkinglot[0] = '\0';
13548 
13552  global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13553  global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13554 
13555  maxauthreq = 3;
13556 
13557  srvlookup = 0;
13558  iax2_authmethods = 0;
13559 
13560  v = ast_variable_browse(cfg, "general");
13561 
13562  /* Seed initial tos value */
13563  tosval = ast_variable_retrieve(cfg, "general", "tos");
13564  if (tosval) {
13565  if (ast_str2tos(tosval, &qos.tos))
13566  ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13567  }
13568  /* Seed initial cos value */
13569  tosval = ast_variable_retrieve(cfg, "general", "cos");
13570  if (tosval) {
13571  if (ast_str2cos(tosval, &qos.cos))
13572  ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13573  }
13574  while(v) {
13575  if (!strcasecmp(v->name, "bindport")) {
13576  if (reload) {
13577  ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13578  }
13579  else if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE, &portno, 1024, 65535)) {
13580  portno = IAX_DEFAULT_PORTNO;
13581  }
13582  } else if (!strcasecmp(v->name, "pingtime")){
13583  ping_time = atoi(v->value);
13584  }
13585  else if (!strcasecmp(v->name, "iaxthreadcount")) {
13586  if (reload) {
13587  if (atoi(v->value) != iaxthreadcount)
13588  ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13589  } else {
13590  iaxthreadcount = atoi(v->value);
13591  if (iaxthreadcount < 1) {
13592  ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13593  iaxthreadcount = 1;
13594  } else if (iaxthreadcount > 256) {
13595  ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13596  iaxthreadcount = 256;
13597  }
13598  }
13599  } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13600  if (reload) {
13602  iaxmaxthreadcount = atoi(v->value);
13604  } else {
13605  iaxmaxthreadcount = atoi(v->value);
13606  if (iaxmaxthreadcount < 0) {
13607  ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13608  iaxmaxthreadcount = 0;
13609  } else if (iaxmaxthreadcount > 256) {
13610  ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13611  iaxmaxthreadcount = 256;
13612  }
13613  }
13614  } else if (!strcasecmp(v->name, "nochecksums")) {
13615 #ifdef SO_NO_CHECK
13616  if (ast_true(v->value))
13617  nochecksums = 1;
13618  else
13619  nochecksums = 0;
13620 #else
13621  if (ast_true(v->value))
13622  ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13623 #endif
13624  }
13625  else if (!strcasecmp(v->name, "maxjitterbuffer"))
13626  maxjitterbuffer = atoi(v->value);
13627  else if (!strcasecmp(v->name, "resyncthreshold"))
13628  resyncthreshold = atoi(v->value);
13629  else if (!strcasecmp(v->name, "maxjitterinterps"))
13630  maxjitterinterps = atoi(v->value);
13631  else if (!strcasecmp(v->name, "jittertargetextra"))
13632  jittertargetextra = atoi(v->value);
13633  else if (!strcasecmp(v->name, "lagrqtime"))
13634  lagrq_time = atoi(v->value);
13635  else if (!strcasecmp(v->name, "maxregexpire"))
13636  max_reg_expire = atoi(v->value);
13637  else if (!strcasecmp(v->name, "minregexpire"))
13638  min_reg_expire = atoi(v->value);
13639  else if (!strcasecmp(v->name, "bindaddr")) {
13640  if (reload) {
13641  ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13642  } else {
13643 
13644  if (!ast_parse_arg(v->value, PARSE_ADDR, NULL)) {
13645 
13646  ast_sockaddr_parse(&bindaddr, v->value, 0);
13647 
13648  if (!ast_sockaddr_port(&bindaddr)) {
13649  ast_sockaddr_set_port(&bindaddr, portno);
13650  }
13651 
13652  if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13653  ast_log(LOG_WARNING, "Unable to apply binding to '%s' at line %d\n", v->value, v->lineno);
13654  } else {
13655  ast_verb(2, "Binding IAX2 to address %s\n", ast_sockaddr_stringify(&bindaddr));
13656 
13657  if (defaultsockfd < 0) {
13659  }
13660  ast_netsock_unref(ns);
13661  }
13662 
13663  } else {
13664  ast_log(LOG_WARNING, "Invalid address '%s' specified, at line %d\n", v->value, v->lineno);
13665  }
13666  }
13667  } else if (!strcasecmp(v->name, "auth")) {
13670  ast_log(LOG_WARNING, "Default auth method is set to deprecated 'plaintext' at line %d of iax.conf\n", v->lineno);
13671  }
13672  } else if (!strcasecmp(v->name, "authdebug")) {
13673  authdebug = ast_true(v->value);
13674  } else if (!strcasecmp(v->name, "encryption")) {
13676  if (!iax2_encryption) {
13677  ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13678  }
13679  } else if (!strcasecmp(v->name, "forceencryption")) {
13680  if (ast_false(v->value)) {
13681  ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13682  } else {
13684  if (iax2_encryption) {
13685  ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13686  }
13687  }
13688  } else if (!strcasecmp(v->name, "transfer")) {
13689  if (!strcasecmp(v->value, "mediaonly")) {
13691  } else if (ast_true(v->value)) {
13693  } else
13695  } else if (!strcasecmp(v->name, "codecpriority")) {
13696  if(!strcasecmp(v->value, "caller"))
13697  ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13698  else if(!strcasecmp(v->value, "disabled"))
13699  ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13700  else if(!strcasecmp(v->value, "reqonly")) {
13701  ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13702  ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13703  }
13704  } else if (!strcasecmp(v->name, "jitterbuffer"))
13705  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13706  else if (!strcasecmp(v->name, "delayreject"))
13707  delayreject = ast_true(v->value);
13708  else if (!strcasecmp(v->name, "allowfwdownload"))
13709  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13710  else if (!strcasecmp(v->name, "rtcachefriends"))
13711  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13712  else if (!strcasecmp(v->name, "rtignoreregexpire"))
13713  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13714  else if (!strcasecmp(v->name, "rtupdate"))
13715  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13716  else if (!strcasecmp(v->name, "rtsavesysname"))
13717  ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13718  else if (!strcasecmp(v->name, "trunktimestamps"))
13719  ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13720  else if (!strcasecmp(v->name, "rtautoclear")) {
13721  int i = atoi(v->value);
13722  if(i > 0)
13723  global_rtautoclear = i;
13724  else
13725  i = 0;
13726  ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13727  } else if (!strcasecmp(v->name, "trunkfreq")) {
13728  trunkfreq = atoi(v->value);
13729  if (trunkfreq < 10) {
13730  ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13731  trunkfreq = 10;
13732  } else if (trunkfreq > 1000) {
13733  ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13734  trunkfreq = 1000;
13735  }
13736  if (timer) {
13737  ast_timer_set_rate(timer, 1000 / trunkfreq);
13738  }
13739  } else if (!strcasecmp(v->name, "trunkmtu")) {
13740  mtuv = atoi(v->value);
13741  if (mtuv == 0 )
13743  else if (mtuv >= 172 && mtuv < 4000)
13744  global_max_trunk_mtu = mtuv;
13745  else
13746  ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13747  mtuv, v->lineno);
13748  } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13749  trunkmaxsize = atoi(v->value);
13750  if (trunkmaxsize == 0)
13752  } else if (!strcasecmp(v->name, "autokill")) {
13753  if (sscanf(v->value, "%30d", &x) == 1) {
13754  if (x >= 0)
13755  autokill = x;
13756  else
13757  ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13758  } else if (ast_true(v->value)) {
13760  } else {
13761  autokill = 0;
13762  }
13763  } else if (!strcasecmp(v->name, "bandwidth")) {
13764  if (!strcasecmp(v->value, "low")) {
13765  capability = iax2_codec_pref_from_bitfield(&prefs_new,
13767  } else if (!strcasecmp(v->value, "medium")) {
13768  capability = iax2_codec_pref_from_bitfield(&prefs_new,
13770  } else if (!strcasecmp(v->value, "high")) {
13771  capability = iax2_codec_pref_from_bitfield(&prefs_new,
13773  } else {
13774  ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13775  }
13776  } else if (!strcasecmp(v->name, "allow")) {
13777  iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 1);
13778  } else if (!strcasecmp(v->name, "disallow")) {
13779  iax2_parse_allow_disallow(&prefs_new, &capability, v->value, 0);
13780  } else if (!strcasecmp(v->name, "register")) {
13781  iax2_register(v->value, v->lineno);
13782  } else if (!strcasecmp(v->name, "iaxcompat")) {
13783  iaxcompat = ast_true(v->value);
13784  } else if (!strcasecmp(v->name, "regcontext")) {
13786  /* Create context if it doesn't exist already */
13788  } else if (!strcasecmp(v->name, "tos")) {
13789  if (ast_str2tos(v->value, &qos.tos))
13790  ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13791  } else if (!strcasecmp(v->name, "cos")) {
13792  if (ast_str2cos(v->value, &qos.cos))
13793  ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13794  } else if (!strcasecmp(v->name, "parkinglot")) {
13796  } else if (!strcasecmp(v->name, "accountcode")) {
13798  } else if (!strcasecmp(v->name, "mohinterpret")) {
13800  } else if (!strcasecmp(v->name, "mohsuggest")) {
13802  } else if (!strcasecmp(v->name, "amaflags")) {
13803  format = ast_channel_string2amaflag(v->value);
13804  if (format < 0) {
13805  ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13806  } else {
13807  amaflags = format;
13808  }
13809  } else if (!strcasecmp(v->name, "language")) {
13810  ast_copy_string(language, v->value, sizeof(language));
13811  } else if (!strcasecmp(v->name, "maxauthreq")) {
13812  maxauthreq = atoi(v->value);
13813  if (maxauthreq < 0)
13814  maxauthreq = 0;
13815  } else if (!strcasecmp(v->name, "adsi")) {
13816  adsi = ast_true(v->value);
13817  } else if (!strcasecmp(v->name, "srvlookup")) {
13818  srvlookup = ast_true(v->value);
13819  } else if (!strcasecmp(v->name, "connectedline")) {
13820  if (ast_true(v->value)) {
13822  } else if (!strcasecmp(v->value, "send")) {
13823  ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13824  ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13825  } else if (!strcasecmp(v->value, "receive")) {
13826  ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13827  ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13828  } else {
13830  }
13831  } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13832  if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13833  ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
13834  }
13835  } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13836  if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13837  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);
13838  }
13839  } else if (!strcasecmp(v->name, "calltokenoptional")) {
13840  if (add_calltoken_ignore(v->value)) {
13841  ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13842  return -1;
13843  }
13844  } else if (!strcasecmp(v->name, "calltokenexpiration")) {
13845  int temp = -1;
13846  sscanf(v->value, "%u", &temp);
13847  if( temp <= 0 ){
13848  ast_log(LOG_WARNING, "Invalid calltokenexpiration value %s. Should be integer greater than 0.\n", v->value);
13849  } else {
13850  max_calltoken_delay = temp;
13851  }
13852  } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13853  if (ast_true(v->value)) {
13854  subscribe_network_change = 1;
13855  } else if (ast_false(v->value)) {
13856  subscribe_network_change = 0;
13857  } else {
13858  ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13859  }
13860  } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13861  if (ast_true(v->value)) {
13862  ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13863  } else if (ast_false(v->value)) {
13864  ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13865  } else {
13866  ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13867  }
13868  }/*else if (strcasecmp(v->name,"type")) */
13869  /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
13870  v = v->next;
13871  }
13872 
13873  if (subscribe_network_change) {
13875  } else {
13877  }
13878 
13879  if (defaultsockfd < 0) {
13880 
13881  ast_sockaddr_set_port(&bindaddr, portno);
13882 
13883  if (!(ns = ast_netsock_bindaddr(netsock, io, &bindaddr, qos.tos, qos.cos, socket_read, NULL))) {
13884  ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13885  } else {
13886  ast_verb(2, "Binding IAX2 to default address %s\n", ast_sockaddr_stringify(&bindaddr));
13888  ast_netsock_unref(ns);
13889  }
13890  }
13891  if (reload) {
13892  ast_netsock_release(outsock);
13893  outsock = ast_netsock_list_alloc();
13894  if (!outsock) {
13895  ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13896  return -1;
13897  }
13898  ast_netsock_init(outsock);
13899  }
13900 
13902  ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13905  }
13906  prefs_global = prefs_new;
13907  iax2_capability = capability;
13908 
13909  if (ucfg) {
13910  struct ast_variable *gen;
13911  int genhasiax;
13912  int genregisteriax;
13913  const char *hasiax, *registeriax;
13914 
13915  genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13916  genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13917  gen = ast_variable_browse(ucfg, "general");
13918  cat = ast_category_browse(ucfg, NULL);
13919  while (cat) {
13920  if (strcasecmp(cat, "general")) {
13921  hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13922  registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13923  if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13924  /* Start with general parameters, then specific parameters, user and peer */
13925  user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13926  if (user) {
13927  ao2_link(users, user);
13928  user = user_unref(user);
13929  }
13930  peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13931  if (peer) {
13932  if (ast_test_flag64(peer, IAX_DYNAMIC)) {
13933  reg_source_db(peer);
13934  }
13935  ao2_link(peers, peer);
13936  peer = peer_unref(peer);
13937  }
13938  }
13939  if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13940  char tmp[256];
13941  const char *host = ast_variable_retrieve(ucfg, cat, "host");
13942  const char *username = ast_variable_retrieve(ucfg, cat, "username");
13943  const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13944  if (!host)
13945  host = ast_variable_retrieve(ucfg, "general", "host");
13946  if (!username)
13947  username = ast_variable_retrieve(ucfg, "general", "username");
13948  if (!secret)
13949  secret = ast_variable_retrieve(ucfg, "general", "secret");
13950  if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13951  if (!ast_strlen_zero(secret))
13952  snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13953  else
13954  snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13955  iax2_register(tmp, 0);
13956  }
13957  }
13958  }
13959  cat = ast_category_browse(ucfg, cat);
13960  }
13961  ast_config_destroy(ucfg);
13962  }
13963 
13964  cat = ast_category_browse(cfg, NULL);
13965  while(cat) {
13966  if (strcasecmp(cat, "general")) {
13967  utype = ast_variable_retrieve(cfg, cat, "type");
13968  if (!strcasecmp(cat, "callnumberlimits")) {
13970  } else if (utype) {
13971  if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13972  user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13973  if (user) {
13974  ao2_link(users, user);
13975  user = user_unref(user);
13976  }
13977  }
13978  if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13979  peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13980  if (peer) {
13981  if (ast_test_flag64(peer, IAX_DYNAMIC))
13982  reg_source_db(peer);
13983  ao2_link(peers, peer);
13984  peer = peer_unref(peer);
13985  }
13986  } else if (strcasecmp(utype, "user")) {
13987  ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13988  }
13989  } else
13990  ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13991  }
13992  cat = ast_category_browse(cfg, cat);
13993  }
13994  ast_config_destroy(cfg);
13995  return 1;
13996 }
13997 
13998 static void poke_all_peers(void)
13999 {
14000  struct ao2_iterator i;
14001  struct iax2_peer *peer;
14002 
14003  i = ao2_iterator_init(peers, 0);
14004  while ((peer = ao2_iterator_next(&i))) {
14005  iax2_poke_peer(peer, 0);
14006  peer_unref(peer);
14007  }
14009 }
14010 static int reload_config(int forced_reload)
14011 {
14012  static const char config[] = "iax.conf";
14013  struct iax2_registry *reg;
14014 
14015  if (set_config(config, 1, forced_reload) > 0) {
14016  prune_peers();
14017  prune_users();
14021  trunk_timed = trunk_untimed = 0;
14023  memset(&debugaddr, '\0', sizeof(debugaddr));
14024 
14026  AST_LIST_TRAVERSE(&registrations, reg, entry)
14027  iax2_do_register(reg);
14029 
14030  /* Qualify hosts, too */
14031  poke_all_peers();
14032  }
14033 
14036  ast_unload_realtime("iaxpeers");
14037 
14038  return 0;
14039 }
14040 
14041 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14042 {
14043  switch (cmd) {
14044  case CLI_INIT:
14045  e->command = "iax2 reload";
14046  e->usage =
14047  "Usage: iax2 reload\n"
14048  " Reloads IAX configuration from iax.conf\n";
14049  return NULL;
14050  case CLI_GENERATE:
14051  return NULL;
14052  }
14053 
14054  reload_config(0);
14055 
14056  return CLI_SUCCESS;
14057 }
14058 
14059 static int reload(void)
14060 {
14061  return reload_config(0);
14062 }
14063 
14064 static int cache_get_callno_locked(const char *data)
14065 {
14066  struct ast_sockaddr addr;
14067  int x;
14068  int callno;
14069  struct iax_ie_data ied;
14070  struct create_addr_info cai;
14071  struct parsed_dial_string pds;
14072  char *tmpstr;
14073 
14074  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14075  /* Look for an *exact match* call. Once a call is negotiated, it can only
14076  look up entries for a single context */
14077  if (!ast_mutex_trylock(&iaxsl[x])) {
14078  if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
14079  return x;
14080  ast_mutex_unlock(&iaxsl[x]);
14081  }
14082  }
14083 
14084  /* No match found, we need to create a new one */
14085 
14086  memset(&cai, 0, sizeof(cai));
14087  memset(&ied, 0, sizeof(ied));
14088  memset(&pds, 0, sizeof(pds));
14089 
14090  tmpstr = ast_strdupa(data);
14091  parse_dial_string(tmpstr, &pds);
14092 
14093  if (ast_strlen_zero(pds.peer)) {
14094  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14095  return -1;
14096  }
14097 
14098  /* Populate our address from the given */
14099  if (create_addr(pds.peer, NULL, &addr, &cai))
14100  return -1;
14101 
14102  ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
14103  pds.peer, pds.username, pds.password, pds.context);
14104 
14105  callno = find_callno_locked(0, 0, &addr, NEW_FORCE, cai.sockfd, 0);
14106  if (callno < 1) {
14107  ast_log(LOG_WARNING, "Unable to create call\n");
14108  return -1;
14109  }
14110 
14111  ast_string_field_set(iaxs[callno], dproot, data);
14112  iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
14113 
14116  /* the string format is slightly different from a standard dial string,
14117  because the context appears in the 'exten' position
14118  */
14119  if (pds.exten)
14121  if (pds.username)
14125  /* Keep password handy */
14126  if (pds.password)
14127  ast_string_field_set(iaxs[callno], secret, pds.password);
14128  if (pds.key)
14129  ast_string_field_set(iaxs[callno], outkey, pds.key);
14130  /* Start the call going */
14131  add_empty_calltoken_ie(iaxs[callno], &ied); /* this _MUST_ be the last ie added */
14132  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
14133 
14134  return callno;
14135 }
14136 
14137 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
14138 {
14139  struct iax2_dpcache *dp = NULL;
14140  struct timeval now = ast_tvnow();
14141  int x, com[2], timeout, old = 0, outfd, doabort, callno;
14142  struct ast_channel *c = NULL;
14143  struct ast_frame *f = NULL;
14144 
14145  AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
14146  if (ast_tvcmp(now, dp->expiry) > 0) {
14147  AST_LIST_REMOVE_CURRENT(cache_list);
14148  if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
14149  ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
14150  else
14151  ast_free(dp);
14152  continue;
14153  }
14154  if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
14155  break;
14156  }
14158 
14159  if (!dp) {
14160  /* No matching entry. Create a new one. */
14161  /* First, can we make a callno? */
14162  if ((callno = cache_get_callno_locked(data)) < 0) {
14163  ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
14164  return NULL;
14165  }
14166  if (!(dp = ast_calloc(1, sizeof(*dp)))) {
14167  ast_mutex_unlock(&iaxsl[callno]);
14168  return NULL;
14169  }
14170  ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
14171  ast_copy_string(dp->exten, exten, sizeof(dp->exten));
14172  dp->expiry = ast_tvnow();
14173  dp->orig = dp->expiry;
14174  /* Expires in 30 mins by default */
14175  dp->expiry.tv_sec += iaxdefaultdpcache;
14176  dp->flags = CACHE_FLAG_PENDING;
14177  for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
14178  dp->waiters[x] = -1;
14179  /* Insert into the lists */
14180  AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
14181  AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
14182  /* Send the request if we're already up */
14183  if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
14184  iax2_dprequest(dp, callno);
14185  ast_mutex_unlock(&iaxsl[callno]);
14186  }
14187 
14188  /* By here we must have a dp */
14189  if (dp->flags & CACHE_FLAG_PENDING) {
14190  struct timeval start;
14191  int ms;
14192  /* Okay, here it starts to get nasty. We need a pipe now to wait
14193  for a reply to come back so long as it's pending */
14194  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14195  /* Find an empty slot */
14196  if (dp->waiters[x] < 0)
14197  break;
14198  }
14199  if (x >= ARRAY_LEN(dp->waiters)) {
14200  ast_log(LOG_WARNING, "No more waiter positions available\n");
14201  return NULL;
14202  }
14203  if (pipe(com)) {
14204  ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
14205  return NULL;
14206  }
14207  dp->waiters[x] = com[1];
14208  /* Okay, now we wait */
14209  timeout = iaxdefaulttimeout * 1000;
14210  /* Temporarily unlock */
14212  /* Defer any dtmf */
14213  if (chan)
14214  old = ast_channel_defer_dtmf(chan);
14215  doabort = 0;
14216  start = ast_tvnow();
14217  while ((ms = ast_remaining_ms(start, timeout))) {
14218  c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &ms);
14219  if (outfd > -1)
14220  break;
14221  if (!c)
14222  continue;
14223  if (!(f = ast_read(c))) {
14224  doabort = 1;
14225  break;
14226  }
14227  ast_frfree(f);
14228  }
14229  if (!ms) {
14230  ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
14231  }
14233  dp->waiters[x] = -1;
14234  close(com[1]);
14235  close(com[0]);
14236  if (doabort) {
14237  /* Don't interpret anything, just abort. Not sure what th epoint
14238  of undeferring dtmf on a hung up channel is but hey whatever */
14239  if (!old && chan)
14241  return NULL;
14242  }
14243  if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
14244  /* Now to do non-independent analysis the results of our wait */
14245  if (dp->flags & CACHE_FLAG_PENDING) {
14246  /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
14247  pending. Don't let it take as long to timeout. */
14248  dp->flags &= ~CACHE_FLAG_PENDING;
14249  dp->flags |= CACHE_FLAG_TIMEOUT;
14250  /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
14251  systems without leaving it unavailable once the server comes back online */
14252  dp->expiry.tv_sec = dp->orig.tv_sec + 60;
14253  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
14254  if (dp->waiters[x] > -1) {
14255  if (write(dp->waiters[x], "asdf", 4) < 0) {
14256  ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14257  }
14258  }
14259  }
14260  }
14261  }
14262  /* Our caller will obtain the rest */
14263  if (!old && chan)
14265  }
14266  return dp;
14267 }
14268 
14269 /*! \brief Part of the IAX2 switch interface */
14270 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14271 {
14272  int res = 0;
14273  struct iax2_dpcache *dp = NULL;
14274 #if 0
14275  ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14276 #endif
14277  if ((priority != 1) && (priority != 2))
14278  return 0;
14279 
14281  if ((dp = find_cache(chan, data, context, exten, priority))) {
14282  if (dp->flags & CACHE_FLAG_EXISTS)
14283  res = 1;
14284  } else {
14285  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14286  }
14288 
14289  return res;
14290 }
14291 
14292 /*! \brief part of the IAX2 dial plan switch interface */
14293 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14294 {
14295  int res = 0;
14296  struct iax2_dpcache *dp = NULL;
14297 #if 0
14298  ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14299 #endif
14300  if ((priority != 1) && (priority != 2))
14301  return 0;
14302 
14304  if ((dp = find_cache(chan, data, context, exten, priority))) {
14305  if (dp->flags & CACHE_FLAG_CANEXIST)
14306  res = 1;
14307  } else {
14308  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14309  }
14311 
14312  return res;
14313 }
14314 
14315 /*! \brief Part of the IAX2 Switch interface */
14316 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14317 {
14318  int res = 0;
14319  struct iax2_dpcache *dp = NULL;
14320 #if 0
14321  ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
14322 #endif
14323  if ((priority != 1) && (priority != 2))
14324  return 0;
14325 
14327  if ((dp = find_cache(chan, data, context, exten, priority))) {
14328  if (dp->flags & CACHE_FLAG_MATCHMORE)
14329  res = 1;
14330  } else {
14331  ast_log(LOG_WARNING, "Unable to make DP cache\n");
14332  }
14334 
14335  return res;
14336 }
14337 
14338 /*! \brief Execute IAX2 dialplan switch */
14339 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
14340 {
14341  char odata[256];
14342  char req[sizeof(odata) + AST_MAX_CONTEXT + AST_MAX_EXTENSION + sizeof("IAX2//@")];
14343  char *ncontext;
14344  struct iax2_dpcache *dp = NULL;
14345  struct ast_app *dial = NULL;
14346 #if 0
14347  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);
14348 #endif
14349  if (priority == 2) {
14350  /* Indicate status, can be overridden in dialplan */
14351  const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
14352  if (dialstatus) {
14353  dial = pbx_findapp(dialstatus);
14354  if (dial)
14355  pbx_exec(chan, dial, "");
14356  }
14357  return -1;
14358  } else if (priority != 1)
14359  return -1;
14360 
14362  if ((dp = find_cache(chan, data, context, exten, priority))) {
14363  if (dp->flags & CACHE_FLAG_EXISTS) {
14364  ast_copy_string(odata, data, sizeof(odata));
14365  ncontext = strchr(odata, '/');
14366  if (ncontext) {
14367  *ncontext = '\0';
14368  ncontext++;
14369  snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
14370  } else {
14371  snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
14372  }
14373  ast_verb(3, "Executing Dial('%s')\n", req);
14374  } else {
14376  ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
14377  return -1;
14378  }
14379  }
14381 
14382  if ((dial = pbx_findapp("Dial")))
14383  return pbx_exec(chan, dial, req);
14384  else
14385  ast_log(LOG_WARNING, "No dial application registered\n");
14386 
14387  return -1;
14388 }
14389 
14390 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
14391 {
14392  struct iax2_peer *peer;
14393  char *peername, *colname;
14394 
14395  peername = ast_strdupa(data);
14396 
14397  /* if our channel, return the IP address of the endpoint of current channel */
14398  if (!strcmp(peername,"CURRENTCHANNEL")) {
14399  unsigned short callno;
14400  if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14401  return -1;
14402  }
14403  callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
14404  ast_copy_string(buf, !ast_sockaddr_isnull(&iaxs[callno]->addr) ? ast_sockaddr_stringify_addr(&iaxs[callno]->addr) : "", len);
14405  return 0;
14406  }
14407 
14408  if ((colname = strchr(peername, ',')))
14409  *colname++ = '\0';
14410  else
14411  colname = "ip";
14412 
14413  if (!(peer = find_peer(peername, 1)))
14414  return -1;
14415 
14416  if (!strcasecmp(colname, "ip")) {
14418  } else if (!strcasecmp(colname, "status")) {
14419  peer_status(peer, buf, len);
14420  } else if (!strcasecmp(colname, "mailbox")) {
14421  ast_copy_string(buf, peer->mailbox, len);
14422  } else if (!strcasecmp(colname, "context")) {
14423  ast_copy_string(buf, peer->context, len);
14424  } else if (!strcasecmp(colname, "expire")) {
14425  snprintf(buf, len, "%d", peer->expire);
14426  } else if (!strcasecmp(colname, "dynamic")) {
14427  ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
14428  } else if (!strcasecmp(colname, "callerid_name")) {
14429  ast_copy_string(buf, peer->cid_name, len);
14430  } else if (!strcasecmp(colname, "callerid_num")) {
14431  ast_copy_string(buf, peer->cid_num, len);
14432  } else if (!strcasecmp(colname, "codecs")) {
14433  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
14434 
14435  iax2_getformatname_multiple(peer->capability, &codec_buf);
14436  ast_copy_string(buf, ast_str_buffer(codec_buf), len);
14437  } else if (!strncasecmp(colname, "codec[", 6)) {
14438  char *codecnum, *ptr;
14439  struct ast_format *tmpfmt;
14440 
14441  /* skip over "codec" to the '[' */
14442  codecnum = colname + 5;
14443  *codecnum = '\0';
14444  codecnum++;
14445  if ((ptr = strchr(codecnum, ']'))) {
14446  *ptr = '\0';
14447  }
14448  if((iax2_codec_pref_index(&peer->prefs, atoi(codecnum), &tmpfmt))) {
14449  ast_copy_string(buf, ast_format_get_name(tmpfmt), len);
14450  } else {
14451  buf[0] = '\0';
14452  }
14453  } else {
14454  buf[0] = '\0';
14455  }
14456 
14457  peer_unref(peer);
14458 
14459  return 0;
14460 }
14461 
14463  .name = "IAXPEER",
14464  .read = function_iaxpeer,
14465 };
14466 
14467 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
14468 {
14469  struct chan_iax2_pvt *pvt;
14470  unsigned int callno;
14471  int res = 0;
14472 
14473  if (!chan || ast_channel_tech(chan) != &iax2_tech) {
14474  ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
14475  return -1;
14476  }
14477 
14478  callno = PTR_TO_CALLNO(ast_channel_tech_pvt(chan));
14479  ast_mutex_lock(&iaxsl[callno]);
14480  if (!(pvt = iaxs[callno])) {
14481  ast_mutex_unlock(&iaxsl[callno]);
14482  return -1;
14483  }
14484 
14485  if (!strcasecmp(args, "osptoken")) {
14486  ast_copy_string(buf, pvt->osptoken, buflen);
14487  } else if (!strcasecmp(args, "peerip")) {
14488  ast_copy_string(buf, !ast_sockaddr_isnull(&pvt->addr) ? ast_sockaddr_stringify_addr(&pvt->addr) : "", buflen);
14489  } else if (!strcasecmp(args, "peername")) {
14490  ast_copy_string(buf, pvt->username, buflen);
14491  } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14492  snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14493  } else {
14494  res = -1;
14495  }
14496 
14497  ast_mutex_unlock(&iaxsl[callno]);
14498 
14499  return res;
14500 }
14501 
14502 /*! \brief Part of the device state notification system ---*/
14503 static int iax2_devicestate(const char *data)
14504 {
14505  struct parsed_dial_string pds;
14506  char *tmp = ast_strdupa(data);
14507  struct iax2_peer *p;
14508  int res = AST_DEVICE_INVALID;
14509 
14510  memset(&pds, 0, sizeof(pds));
14511  parse_dial_string(tmp, &pds);
14512 
14513  if (ast_strlen_zero(pds.peer)) {
14514  ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
14515  return res;
14516  }
14517 
14518  ast_debug(3, "Checking device state for device %s\n", pds.peer);
14519 
14520  /* SLD: FIXME: second call to find_peer during registration */
14521  if (!(p = find_peer(pds.peer, 1)))
14522  return res;
14523 
14524  res = AST_DEVICE_UNAVAILABLE;
14525 
14526  ast_debug(3, "Found peer. What's device state of %s? addr=%s, defaddr=%s maxms=%d, lastms=%d\n",
14528 
14529  if (((!ast_sockaddr_isnull(&p->addr)) || (!ast_sockaddr_isnull(&p->defaddr))) &&
14530  (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14531  /* Peer is registered, or have default IP address
14532  and a valid registration */
14533  if (p->historicms == 0 || p->historicms <= p->maxms)
14534  /* let the core figure out whether it is in use or not */
14535  res = AST_DEVICE_UNKNOWN;
14536  }
14537 
14538  peer_unref(p);
14539 
14540  return res;
14541 }
14542 
14543 static struct ast_switch iax2_switch =
14544 {
14545  .name = "IAX2",
14546  .description = "IAX Remote Dialplan Switch",
14547  .exists = iax2_exists,
14548  .canmatch = iax2_canmatch,
14549  .exec = iax2_exec,
14550  .matchmore = iax2_matchmore,
14551 };
14552 
14553 static struct ast_cli_entry cli_iax2[] = {
14554  AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14555  AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14556  AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14557  AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14558  AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14559  AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14560  AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14561  AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14562  AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14563  AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14564  AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14565  AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14566  AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14567  AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14568  AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14569  AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14570  AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14571  AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14572  AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14573  AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14574 #ifdef IAXTESTS
14575  AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14576  AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14577  AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14578 #endif /* IAXTESTS */
14579 };
14580 
14581 static void cleanup_thread_list(void *head)
14582 {
14583  AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14584  struct iax2_thread_list *list_head = head;
14585  struct iax2_thread *thread;
14586 
14587  AST_LIST_LOCK(list_head);
14588  while ((thread = AST_LIST_REMOVE_HEAD(list_head, list))) {
14589  pthread_t thread_id = thread->threadid;
14590 
14591  thread->stop = 1;
14592  signal_condition(&thread->lock, &thread->cond);
14593 
14594  AST_LIST_UNLOCK(list_head);
14595  pthread_join(thread_id, NULL);
14596  AST_LIST_LOCK(list_head);
14597  }
14598  AST_LIST_UNLOCK(list_head);
14599 }
14600 
14601 static int __unload_module(void)
14602 {
14603  int x;
14604 
14607 
14608  ast_manager_unregister("IAXpeers");
14609  ast_manager_unregister("IAXpeerlist");
14610  ast_manager_unregister("IAXnetstats");
14611  ast_manager_unregister("IAXregistry");
14613  ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14614  ast_unregister_switch(&iax2_switch);
14615  ast_channel_unregister(&iax2_tech);
14616 
14617  if (netthreadid != AST_PTHREADT_NULL) {
14618  pthread_cancel(netthreadid);
14619  pthread_kill(netthreadid, SIGURG);
14620  pthread_join(netthreadid, NULL);
14621  }
14622 
14623  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14624  if (iaxs[x]) {
14625  iax2_destroy(x);
14626  }
14627  }
14628 
14629  /* Call for all threads to halt */
14633 
14634  ast_netsock_release(netsock);
14635  ast_netsock_release(outsock);
14636  for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14637  if (iaxs[x]) {
14638  iax2_destroy(x);
14639  }
14640  }
14641  ast_manager_unregister( "IAXpeers" );
14642  ast_manager_unregister( "IAXpeerlist" );
14643  ast_manager_unregister( "IAXnetstats" );
14644  ast_manager_unregister( "IAXregistry" );
14646  ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14647  ast_unregister_switch(&iax2_switch);
14648  ast_channel_unregister(&iax2_tech);
14649  delete_users();
14652 
14653  for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14654  ast_mutex_destroy(&iaxsl[x]);
14655  }
14656 
14657  ao2_ref(peers, -1);
14658  ao2_ref(users, -1);
14659  ao2_ref(iax_peercallno_pvts, -1);
14660  ao2_ref(iax_transfercallno_pvts, -1);
14661  ao2_ref(callno_limits, -1);
14662  ao2_ref(calltoken_ignores, -1);
14663  if (timer) {
14664  ast_timer_close(timer);
14665  timer = NULL;
14666  }
14667  transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14668 
14671  sched = NULL;
14672  ao2_ref(peercnts, -1);
14673 
14675  ast_unload_realtime("iaxpeers");
14676 
14677  ao2_ref(iax2_tech.capabilities, -1);
14678  iax2_tech.capabilities = NULL;
14679  return 0;
14680 }
14681 
14682 static int unload_module(void)
14683 {
14684  ast_custom_function_unregister(&iaxpeer_function);
14685  ast_custom_function_unregister(&iaxvar_function);
14686  return __unload_module();
14687 }
14688 
14689 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14690 {
14691  struct iax2_peer *peer = obj;
14692 
14693  if (peer->sockfd < 0)
14694  peer->sockfd = defaultsockfd;
14695 
14696  return 0;
14697 }
14698 
14699 static int pvt_hash_cb(const void *obj, const int flags)
14700 {
14701  const struct chan_iax2_pvt *pvt = obj;
14702 
14703  return pvt->peercallno;
14704 }
14705 
14706 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14707 {
14708  struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14709 
14710  /* The frames_received field is used to hold whether we're matching
14711  * against a full frame or not ... */
14712 
14713  return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14714  pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14715 }
14716 
14717 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14718 {
14719  const struct chan_iax2_pvt *pvt = obj;
14720 
14721  return pvt->transfercallno;
14722 }
14723 
14724 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14725 {
14726  struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14727 
14728  /* The frames_received field is used to hold whether we're matching
14729  * against a full frame or not ... */
14730 
14731  return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14732  pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14733 }
14734 
14735 static int load_objects(void)
14736 {
14737  peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14738  peercnts = callno_limits = calltoken_ignores = NULL;
14739 
14742  if (!peers) {
14743  goto container_fail;
14744  }
14745 
14748  if (!users) {
14749  goto container_fail;
14750  }
14751 
14752  iax_peercallno_pvts = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
14754  if (!iax_peercallno_pvts) {
14755  goto container_fail;
14756  }
14757 
14758  iax_transfercallno_pvts = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
14760  if (!iax_transfercallno_pvts) {
14761  goto container_fail;
14762  }
14763 
14766  if (!peercnts) {
14767  goto container_fail;
14768  }
14769 
14772  if (!callno_limits) {
14773  goto container_fail;
14774  }
14775 
14776  calltoken_ignores = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
14778  if (!calltoken_ignores) {
14779  goto container_fail;
14780  }
14781 
14782  if (create_callno_pools()) {
14783  goto container_fail;
14784  }
14785 
14786  transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT);
14787  if (!transmit_processor) {
14788  goto container_fail;
14789  }
14790 
14791  return 0;
14792 
14793 container_fail:
14794  if (peers) {
14795  ao2_ref(peers, -1);
14796  }
14797  if (users) {
14798  ao2_ref(users, -1);
14799  }
14800  if (iax_peercallno_pvts) {
14801  ao2_ref(iax_peercallno_pvts, -1);
14802  }
14803  if (iax_transfercallno_pvts) {
14804  ao2_ref(iax_transfercallno_pvts, -1);
14805  }
14806  if (peercnts) {
14807  ao2_ref(peercnts, -1);
14808  }
14809  if (callno_limits) {
14810  ao2_ref(callno_limits, -1);
14811  }
14812  if (calltoken_ignores) {
14813  ao2_ref(calltoken_ignores, -1);
14814  }
14815  return -1;
14816 }
14817 
14818 /*!
14819  * \brief Load the module
14820  *
14821  * Module loading including tests for configuration or dependencies.
14822  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
14823  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
14824  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
14825  * configuration file or other non-critical problem return
14826  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
14827  */
14828 static int load_module(void)
14829 {
14830  static const char config[] = "iax.conf";
14831  int x = 0;
14832  struct iax2_registry *reg = NULL;
14833 
14835  return AST_MODULE_LOAD_DECLINE;
14836  }
14838 
14839  if (load_objects()) {
14840  ao2_ref(iax2_tech.capabilities, -1);
14841  iax2_tech.capabilities = NULL;
14842  return AST_MODULE_LOAD_DECLINE;
14843  }
14844 
14845  memset(iaxs, 0, sizeof(iaxs));
14846 
14847  for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14848  ast_mutex_init(&iaxsl[x]);
14849  }
14850 
14851  if (!(sched = ast_sched_context_create())) {
14852  ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14853  ao2_ref(iax2_tech.capabilities, -1);
14854  iax2_tech.capabilities = NULL;
14855  return AST_MODULE_LOAD_DECLINE;
14856  }
14857 
14858  if (ast_sched_start_thread(sched)) {
14860  ao2_ref(iax2_tech.capabilities, -1);
14861  iax2_tech.capabilities = NULL;
14862  sched = NULL;
14863  return AST_MODULE_LOAD_DECLINE;
14864  }
14865 
14866  if (!(io = io_context_create())) {
14867  ast_log(LOG_ERROR, "Failed to create I/O context\n");
14869  ao2_ref(iax2_tech.capabilities, -1);
14870  iax2_tech.capabilities = NULL;
14871  sched = NULL;
14872  return AST_MODULE_LOAD_DECLINE;
14873  }
14874 
14875  if (!(netsock = ast_netsock_list_alloc())) {
14876  ast_log(LOG_ERROR, "Failed to create netsock list\n");
14877  io_context_destroy(io);
14879  ao2_ref(iax2_tech.capabilities, -1);
14880  iax2_tech.capabilities = NULL;
14881  sched = NULL;
14882  return AST_MODULE_LOAD_DECLINE;
14883  }
14884  ast_netsock_init(netsock);
14885 
14886  outsock = ast_netsock_list_alloc();
14887  if (!outsock) {
14888  ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14889  io_context_destroy(io);
14891  ao2_ref(iax2_tech.capabilities, -1);
14892  iax2_tech.capabilities = NULL;
14893  sched = NULL;
14894  return AST_MODULE_LOAD_DECLINE;
14895  }
14896  ast_netsock_init(outsock);
14897 
14898  randomcalltokendata = ast_random();
14899 
14903 
14904  if ((timer = ast_timer_open())) {
14905  ast_timer_set_rate(timer, 1000 / trunkfreq);
14906  }
14907 
14908  if (set_config(config, 0, 0) == -1) {
14909  if (timer) {
14910  ast_timer_close(timer);
14911  timer = NULL;
14912  }
14913  __unload_module();
14914  return AST_MODULE_LOAD_DECLINE;
14915  }
14916 
14917  ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14918 
14920 
14921  ast_custom_function_register(&iaxpeer_function);
14922  ast_custom_function_register(&iaxvar_function);
14923 
14928 
14929  if (ast_channel_register(&iax2_tech)) {
14930  ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
14931  __unload_module();
14932  return AST_MODULE_LOAD_DECLINE;
14933  }
14934 
14935  if (ast_register_switch(&iax2_switch)) {
14936  ast_log(LOG_ERROR, "Unable to register IAX switch\n");
14937  }
14938 
14939  if (start_network_thread()) {
14940  ast_log(LOG_ERROR, "Unable to start network thread\n");
14941  __unload_module();
14942  return AST_MODULE_LOAD_DECLINE;
14943  } else {
14944  ast_verb(2, "IAX Ready and Listening\n");
14945  }
14946 
14948  AST_LIST_TRAVERSE(&registrations, reg, entry)
14949  iax2_do_register(reg);
14951 
14952  ao2_callback(peers, 0, peer_set_sock_cb, NULL);
14953  ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
14954 
14955 
14958 
14959  ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
14960 
14962 
14963  return AST_MODULE_LOAD_SUCCESS;
14964 }
14965 
14966 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
14967  .support_level = AST_MODULE_SUPPORT_CORE,
14968  .load = load_module,
14969  .unload = unload_module,
14970  .reload = reload,
14971  .load_pri = AST_MODPRI_CHANNEL_DRIVER,
14972  .requires = "dnsmgr",
14973  .optional_modules = "res_crypto",
14974 );
int iax_ie_append_short(struct iax_ie_data *ied, unsigned char ie, unsigned short value)
Definition: parser.c:762
static char * ast_sockaddr_stringify_addr(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only.
Definition: netsock2.h:290
static char user[512]
int ast_io_wait(struct io_context *ioc, int howlong)
Waits for IO.
Definition: io.c:278
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)]
chan_iax2_pvt structure locks
Definition: chan_iax2.c:1163
static int iaxdefaultdpcache
Definition: chan_iax2.c:346
static int iax2_delete_from_sched(const void *data)
Definition: chan_iax2.c:2077
static void requirecalltoken_mark_auto(const char *name, int subclass)
Definition: chan_iax2.c:4892
static struct iax_frame * iaxfrdup2(struct iax_frame *fr)
Definition: chan_iax2.c:2286
static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:9977
char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:4605
const char * name
Definition: pbx.h:119
struct iax_frame * next
Definition: parser.h:139
struct ast_party_caller * ast_channel_caller(struct ast_channel *chan)
const char * type
Definition: datastore.h:32
int ast_sched_start_thread(struct ast_sched_context *con)
Start a thread for processing scheduler entries.
Definition: sched.c:195
unsigned int notsilenttx
Definition: chan_iax2.c:725
static int iax2_call(struct ast_channel *c, const char *dest, int timeout)
Definition: chan_iax2.c:5076
struct ast_variable * ast_load_realtime(const char *family,...) attribute_sentinel
Definition: main/config.c:3339
static char musicclass[MAX_MUSICCLASS]
Definition: chan_mgcp.c:162
int calling_pres
Definition: chan_iax2.c:867
struct ast_variable * next
unsigned char buf[1]
Definition: chan_iax2.c:1057
long max_jitterbuf
Definition: jitterbuf.h:67
struct ast_channel * ast_waitfor_n(struct ast_channel **chan, int n, int *ms)
Waits for input on a group of channels Wait for input on an array of channels for a given # of millis...
Definition: channel.c:3166
Require call token validation after a successful registration using call token validation occurs...
Definition: chan_iax2.c:498
int ast_queue_hangup(struct ast_channel *chan)
Queue a hangup frame.
Definition: channel.c:1150
void iax_set_error(void(*output)(const char *data))
struct ast_frame af
Definition: parser.h:141
static const char type[]
Definition: chan_ooh323.c:109
static char * handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7584
struct sockaddr_storage ss
Definition: netsock2.h:98
static int load_module(void)
Load the module.
Definition: chan_iax2.c:14828
static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7369
static uint16_t global_maxcallno_nonval
Definition: chan_iax2.c:973
static void jb_error_output(const char *fmt,...)
Definition: chan_iax2.c:1208
void ast_party_connected_line_init(struct ast_party_connected_line *init)
Initialize the given connected line structure.
Definition: channel.c:2022
unsigned int datalen
Definition: iax2.h:297
static char accountcode[AST_MAX_ACCOUNT_CODE]
Definition: chan_iax2.c:428
int presentation
Q.931 encoded presentation-indicator encoded field.
Definition: channel.h:278
unsigned int fwdesc
Definition: parser.h:66
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
Definition: chan_iax2.c:4338
unsigned int trunkdatalen
Definition: chan_iax2.c:606
static int socket_process(struct iax2_thread *thread)
Definition: chan_iax2.c:11968
pthread_t thread
Definition: app_meetme.c:1089
static char * complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
Definition: chan_iax2.c:3891
char digit
void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
Set caller ID number, name and ANI and generate AMI event.
Definition: channel.c:7434
static int handle_error(void)
Definition: chan_iax2.c:3355
#define IAX_IE_IAX_UNKNOWN
Definition: iax2.h:153
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition: chan_iax2.c:1179
static int test_losspct
Definition: chan_iax2.c:420
#define ast_channel_lock(chan)
Definition: channel.h:2945
int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks to see if adding anything to this extension might match something. (exists ^ canmatch) ...
Definition: pbx.c:4199
static char * handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7038
#define attribute_pure
Definition: compiler.h:35
const ast_string_field secret
Definition: chan_iax2.c:816
const ast_string_field rdnis
Definition: chan_iax2.c:816
static char exten[AST_MAX_EXTENSION]
Definition: chan_alsa.c:118
uint16_t callno_entry
Definition: chan_iax2.c:691
Main Channel structure associated with a channel.
struct ast_party_dialed::@246 number
Dialed/Called number.
struct timeval lasttxtime
Definition: chan_iax2.c:601
static int iax2_ack_registry(struct iax_ies *ies, struct ast_sockaddr *addr, int callno)
Acknowledgment received for OUR registration.
Definition: chan_iax2.c:8716
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL
Definition: chan_iax2.c:968
static void build_rand_pad(unsigned char *buf, ssize_t len)
Definition: chan_iax2.c:6355
Music on hold handling.
void ast_sched_clean_by_callback(struct ast_sched_context *con, ast_sched_cb match, ast_sched_cb cleanup_cb)
Clean all scheduled events with matching callback.
Definition: sched.c:407
#define AST_CLI_DEFINE(fn, txt,...)
Definition: cli.h:197
void iax_firmware_reload(void)
Definition: firmware.c:206
#define IAX_RTSAVE_SYSNAME
Definition: chan_iax2.c:461
static struct ast_format * codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Definition: chan_iax2.c:1847
unsigned int cos
Definition: chan_iax2.c:352
char * str
Subscriber phone number (Malloced)
Definition: channel.h:292
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
Definition: chan_iax2.c:4343
#define MAX_PEER_BUCKETS
Definition: chan_iax2.c:950
#define IAX_TRUNKTIMESTAMPS
Definition: chan_iax2.c:474
ssize_t ast_sendto(int sockfd, const void *buf, size_t len, int flags, const struct ast_sockaddr *dest_addr)
Wrapper around sendto(2) that uses ast_sockaddr.
Definition: netsock2.c:614
uint16_t limit
Definition: chan_iax2.c:985
uint64_t iax2_format_compatibility_cap2bitfield(const struct ast_format_cap *cap)
Convert a format capabilities structure to a bitfield.
static int srvlookup
Definition: chan_iax2.c:358
#define IAX_IE_CAPABILITY2
Definition: iax2.h:187
int iax_ie_append_int(struct iax_ie_data *ied, unsigned char ie, unsigned int value)
Definition: parser.c:755
#define IAX_CALLENCRYPTED(pvt)
Definition: chan_iax2.c:395
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:39
unsigned char csub
Definition: iax2.h:235
unsigned char data[0]
Definition: iax2.h:265
struct timeval rxcore
Definition: chan_iax2.c:753
enum ast_media_type ast_format_get_type(const struct ast_format *format)
Get the media type of a format.
Definition: format.c:354
const char *const type
Definition: channel.h:630
static void free_context(struct iax2_context *con)
Definition: chan_iax2.c:12448
unsigned short callno
Definition: chan_iax2.c:1090
int encmethods
Definition: chan_iax2.c:519
int calling_tns
Definition: parser.h:33
Asterisk locking-related definitions:
void astman_append(struct mansession *s, const char *fmt,...)
Definition: manager.c:3080
static int make_trunk(unsigned short callno, int locked)
Definition: chan_iax2.c:2333
#define IAX_IE_CALLINGTNS
Definition: iax2.h:170
const ast_string_field osptoken
Definition: chan_iax2.c:816
Asterisk main include file. File version handling, generic pbx functions.
struct ast_format * ast_format_compatibility_bitfield2format(uint64_t bitfield)
Convert a bitfield to its respective format structure.
static const char config_file[]
Definition: cdr_odbc.c:57
int encmethods
Definition: chan_iax2.c:567
unsigned char iseqno
Definition: chan_iax2.c:773
static char language[MAX_LANGUAGE]
Definition: chan_iax2.c:320
void * ast_mwi_unsubscribe(struct ast_mwi_subscriber *sub)
Unsubscribe from the stasis topic and MWI.
Definition: mwi.c:249
#define ast_realloc(p, len)
A wrapper for realloc()
Definition: astmm.h:228
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
Definition: chan_iax2.c:2148
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
Definition: linkedlists.h:172
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
const ast_string_field cid_num
Definition: chan_iax2.c:816
char * str
Subscriber phone number (Malloced)
Definition: channel.h:387
char chan_name[AST_CHANNEL_NAME]
char * serviceident
Definition: parser.h:64
static int jittertargetextra
Definition: chan_iax2.c:334
#define ast_copy_flags64(dest, src, flagz)
Definition: utils.h:141
static struct iax2_peer * find_peer(const char *name, int realtime)
Definition: chan_iax2.c:2009
static char parkinglot[AST_MAX_CONTEXT]
Definition: chan_mgcp.c:163
void iax_frame_subclass2str(enum iax_frame_subclass subclass, char *str, size_t len)
Definition: parser.c:462
static int prune_addr_range_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2592
static char * handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7657
const ast_string_field exten
Definition: chan_iax2.c:816
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
Definition: json.c:591
int expire
Definition: chan_iax2.c:569
Security Event Reporting API.
char * rsa_result
Definition: parser.h:50
static int amaflags
Definition: chan_iax2.c:431
uint64_t ast_format_compatibility_format2bitfield(const struct ast_format *format)
Convert a format structure to its respective bitfield.
static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
Definition: chan_iax2.c:6282
static int iax2_predestroy(int callno)
Definition: chan_iax2.c:3436
#define AST_OPTION_TXGAIN
unsigned char calltoken_ie_len
Definition: chan_iax2.c:885
iax2_format capability
Definition: chan_iax2.c:4587
static char * complete_iax2_unregister(const char *line, const char *word, int pos, int state)
Definition: chan_iax2.c:7148
static uint16_t DEFAULT_MAXCALLNO_LIMIT
Definition: chan_iax2.c:966
int ast_callerid_split(const char *src, char *name, int namelen, char *num, int numlen)
Definition: callerid.c:1092
#define ast_channel_alloc_with_endpoint(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag, endpoint,...)
Definition: channel.h:1263
void iax_set_output(void(*output)(const char *data))
static void __auth_reject(const void *nothing)
Definition: chan_iax2.c:9282
static pthread_t netthreadid
Definition: chan_iax2.c:439
ast_aes_decrypt_key dcx
Definition: chan_iax2.c:828
int pbx_exec(struct ast_channel *c, struct ast_app *app, const char *data)
Execute an application.
Definition: pbx_app.c:471
#define IAX_FLAG_SC_LOG
Definition: iax2.h:44
char * md5_result
Definition: parser.h:49
#define FORMAT2
unsigned char aseqno
Definition: chan_iax2.c:775
const ast_string_field dnid
Definition: chan_iax2.c:816
int presentation
Q.931 presentation-indicator and screening-indicator encoded fields.
Definition: channel.h:296
static void network_change_stasis_subscribe(void)
Definition: chan_iax2.c:1455
static void handle_deferred_full_frames(struct iax2_thread *thread)
Handle any deferred full frames for this thread.
Definition: chan_iax2.c:9712
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
Definition: chan_iax2.c:4566
Channels have this property if they can accept input with jitter; i.e. most VoIP channels.
Definition: channel.h:961
CallerID (and other GR30) management and generation Includes code and algorithms from the Zapata libr...
void ast_channel_set_writeformat(struct ast_channel *chan, struct ast_format *format)
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition: extconf.c:1263
char idtext[256]
Definition: chan_iax2.c:6833
unsigned char encdata[0]
Definition: iax2.h:243
static struct iax2_peer * realtime_peer(const char *peername, struct ast_sockaddr *addr)
Definition: chan_iax2.c:4359
static struct iax2_peer * peer_unref(struct iax2_peer *peer)
Definition: chan_iax2.c:2028
struct ast_sockaddr addr
Definition: chan_iax2.c:598
char * config
Definition: conf2ael.c:66
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int command, int ts, unsigned char seqno, int sockfd, struct iax_ie_data *ied)
Definition: chan_iax2.c:4772
#define CALLTOKEN_HASH_FORMAT
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition: chan_iax2.c:1498
#define ast_pthread_create_detached(a, b, c, d)
Definition: utils.h:563
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
Definition: netsock2.c:230
iax2_format svoiceformat
Definition: chan_iax2.c:707
iax2_format videoformat
Definition: chan_iax2.c:705
Definition: iax2.h:280
static int network_change_sched_cb(const void *data)
Definition: chan_iax2.c:1485
struct ast_party_id id
Connected party ID.
Definition: channel.h:459
static struct ao2_container * iax_peercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1154
static int iax2_write(struct ast_channel *c, struct ast_frame *f)
Definition: chan_iax2.c:7683
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Definition: clicompat.c:30
void * ast_channel_tech_pvt(const struct ast_channel *chan)
static void __attempt_transmit(const void *data)
Definition: chan_iax2.c:3548
#define ast_channel_unref(c)
Decrease channel reference count.
Definition: channel.h:2981
unsigned short scallno
Definition: iax2.h:229
static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14717
struct iax2_registry * reg
Definition: chan_iax2.c:835
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7742
struct ast_endpoint * ast_endpoint_create(const char *tech, const char *resource)
Create an endpoint struct.
size_t afdatalen
Definition: parser.h:143
static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
part of the IAX2 dial plan switch interface
Definition: chan_iax2.c:14293
static int send_lagrq(const void *data)
Definition: chan_iax2.c:1804
#define ast_test_flag(p, flag)
Definition: utils.h:63
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition: extconf.c:1216
#define IAX_USEJITTERBUF
Definition: chan_iax2.c:458
static int addr_range_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2438
static int exists(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_logic.c:124
int ast_netsock_sockfd(const struct ast_netsock *ns)
Definition: netsock.c:183
struct ast_sockaddr addr
Definition: acl.h:53
Device state management.
const ast_string_field description
Definition: chan_iax2.c:554
struct stasis_topic * ast_security_topic(void)
A stasis_topic which publishes messages for security related issues.
Support for translation of data formats. translate.c.
static struct @111 qos
#define IAX_SHRINKCALLERID
Definition: chan_iax2.c:483
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
Definition: netsock2.h:171
#define MAX_MUSICCLASS
Definition: channel.h:174
const char * ast_var_value(const struct ast_var_t *var)
Definition: chanvars.c:80
static void iax_pvt_callid_new(int callno)
Definition: chan_iax2.c:1137
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6371
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
Definition: json.c:73
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition: chan_iax2.c:1512
struct ast_party_name name
Subscriber name.
Definition: channel.h:341
int sockfd
Definition: netsock.c:54
#define OBJ_KEY
Definition: astobj2.h:1155
#define RESULT_SHOWUSAGE
Definition: cli.h:41
void ast_channel_unregister(const struct ast_channel_tech *tech)
Unregister a channel technology.
Definition: channel.c:570
struct ast_party_id from
Who is redirecting the call (Sent to the party the call is redirected toward)
Definition: channel.h:528
int iax_firmware_get_version(const char *dev, uint16_t *version)
Definition: firmware.c:263
const ast_string_field name
Definition: chan_iax2.c:516
ast_aes_encrypt_key ecx
Definition: chan_iax2.c:824
struct iax2_thread::@124 full_frames
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
unsigned int transferid
Definition: parser.h:61
void ast_channel_hangupcause_set(struct ast_channel *chan, int value)
static void __iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8541
struct ast_ha ha
Definition: chan_iax2.c:994
#define IAX_META_TRUNK_MINI
Definition: iax2.h:206
struct stasis_cache * ast_mwi_state_cache(void)
Backend cache for ast_mwi_topic_cached().
Definition: mwi.c:90
#define schedule_action(func, data)
Definition: chan_iax2.c:1678
static char * handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:14041
unsigned short version
Definition: iax2.h:295
struct ast_variable * vars
Definition: chan_iax2.c:871
static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 Switch interface.
Definition: chan_iax2.c:14316
static void unlink_peer(struct iax2_peer *peer)
Definition: chan_iax2.c:8879
static const char * iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
Definition: chan_iax2.c:1915
int ast_queue_unhold(struct ast_channel *chan)
Queue an unhold frame.
Definition: channel.c:1216
unsigned char oseqno
Definition: chan_iax2.c:769
#define IAX_IE_VARIABLE
Definition: iax2.h:183
#define IAX_IE_RR_LOSS
Definition: iax2.h:178
#define OBJ_POINTER
Definition: astobj2.h:1154
iax2_thread_iostate
Definition: chan_iax2.c:1042
iax2_format peercapability
Definition: chan_iax2.c:749
static time_t max_calltoken_delay
Definition: chan_iax2.c:938
struct ast_channel * ast_channel_release(struct ast_channel *chan)
Unlink and release reference to a channel.
Definition: channel.c:1584
const char * ast_var_name(const struct ast_var_t *var)
Definition: chanvars.c:60
void ast_channel_set_rawwriteformat(struct ast_channel *chan, struct ast_format *format)
int sockfd
Definition: chan_iax2.c:559
int ast_netsock_release(struct ast_netsock_list *list)
Definition: netsock.c:85
#define ast_set_flag(p, flag)
Definition: utils.h:70
const char * iax2_getformatname(iax2_format format)
iax2 wrapper function for ast_getformatname
Definition: chan_iax2.c:1903
static int send_ping(const void *data)
Definition: chan_iax2.c:1740
void jb_setoutput(jb_output_function_t err, jb_output_function_t warn, jb_output_function_t dbg)
Definition: jitterbuf.c:55
struct iax2_context * next
Definition: chan_iax2.c:449
static int peercnt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2459
static int max_reg_expire
Definition: chan_iax2.c:356
void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
Start the list complete event.
Definition: manager.c:3237
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
Definition: chan_iax2.c:12367
#define DEADLOCK_AVOIDANCE(lock)
Definition: lock.h:374
Stasis Message Bus API. See Stasis Message Bus API for detailed documentation.
static struct ast_netsock_list * netsock
Definition: chan_iax2.c:362
descriptor for a cli entry.
Definition: cli.h:171
const int argc
Definition: cli.h:160
#define AST_OPTION_OPRMODE
static int update_packet(struct iax_frame *f)
Definition: chan_iax2.c:3521
#define LOG_WARNING
Definition: logger.h:274
#define IAX_IE_DATETIME
Definition: iax2.h:161
enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
Create a new thread and start the PBX.
Definition: pbx.c:4712
const ast_string_field dbsecret
Definition: chan_iax2.c:516
static int iax2_queue_frame(int callno, struct ast_frame *f)
Queue a frame to a call&#39;s owning asterisk channel.
Definition: chan_iax2.c:3253
long losspct
Definition: jitterbuf.h:88
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:139
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
Definition: chan_iax2.c:2045
static char * handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:6757
#define AST_FORMAT_CAP_NAMES_LEN
Definition: format_cap.h:326
char * ast_str_buffer(const struct ast_str *buf)
Returns the string buffer within the ast_str buf.
Definition: strings.h:714
char * username
Definition: parser.h:36
unsigned char oseqno
Definition: iax2.h:232
AST_JSON_INT_T ast_json_int_t
Primarily used to cast when packing to an "I" type.
Definition: json.h:87
#define MARK_IAX_SUBCLASS_TX
Definition: chan_iax2.c:673
enum iax_transfer_state transferring
Definition: chan_iax2.c:843
int historicms
Definition: chan_iax2.c:581
int ast_party_id_presentation(const struct ast_party_id *id)
Determine the overall presentation value for the given party.
Definition: channel.c:1821
char * iax_prov_complete_template(const char *line, const char *word, int pos, int state)
Definition: provision.c:179
#define ao2_callback(c, flags, cb_fn, arg)
Definition: astobj2.h:1716
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
Definition: chan_iax2.c:5439
Media Format Bitfield Compatibility API.
unsigned int rr_dropped
Definition: parser.h:78
struct ast_taskprocessor * ast_taskprocessor_get(const char *name, enum ast_tps_options create)
Get a reference to a taskprocessor with the specified name and create the taskprocessor if necessary...
Provide cryptographic signature routines.
static void __get_from_jb(const void *p)
Definition: chan_iax2.c:4125
static struct chan_iax2_pvt * new_iax(struct ast_sockaddr *addr, const char *host)
Definition: chan_iax2.c:2243
int ast_unload_realtime(const char *family)
Release any resources cached for a realtime family.
Definition: main/config.c:3406
#define CONFIG_STATUS_FILEINVALID
struct ast_netsock * ast_netsock_bindaddr(struct ast_netsock_list *list, struct io_context *ioc, struct ast_sockaddr *bindaddr, int tos, int cos, ast_io_cb callback, void *data)
Definition: netsock.c:109
unsigned char semirand[32]
Definition: chan_iax2.c:833
int ooo
Definition: chan_iax2.c:688
#define IAX_ENCRYPT_KEYROTATE
Definition: iax2.h:200
#define IAX_META_TRUNK
Definition: iax2.h:202
int calling_ton
Definition: parser.h:32
enum iax_reg_state regstate
Definition: chan_iax2.c:646
static int iax2_transmit(struct iax_frame *fr)
Definition: chan_iax2.c:4309
static int iax2_authmethods
Definition: chan_iax2.c:435
struct stasis_message_type * ast_network_change_type(void)
A stasis_message_type for network changes.
static int iaxmaxthreadcount
Definition: chan_iax2.c:676
const ast_string_field language
Definition: chan_iax2.c:516
static int auto_congest(const void *data)
Definition: chan_iax2.c:4737
struct iax2_codec_pref rprefs
Definition: chan_iax2.c:735
#define IAX_FORCE_ENCRYPT
Definition: chan_iax2.c:482
static int timeout
Definition: cdr_mysql.c:86
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
Definition: chan_iax2.c:14467
static unsigned int iax2_datetime(const char *tz)
Definition: chan_iax2.c:4746
static int tmp()
Definition: bt_open.c:389
const ast_string_field inkeys
Definition: chan_iax2.c:516
static void register_peer_exten(struct iax2_peer *peer, int onoff)
Definition: chan_iax2.c:8860
unsigned char type
Definition: chan_iax2.c:1092
struct ast_tm * ast_localtime(const struct timeval *timep, struct ast_tm *p_tm, const char *zone)
Timezone-independent version of localtime_r(3).
Definition: localtime.c:1739
#define IAX_DEFAULT_REG_EXPIRE
Definition: iax2.h:123
#define IAX_QUELCH
Definition: chan_iax2.c:464
#define IAX_DELAYPBXSTART
Definition: chan_iax2.c:477
#define IAX_LINGER_TIMEOUT
Definition: iax2.h:126
#define IAX_IE_CALLNO
Definition: iax2.h:151
#define AST_CAUSE_FACILITY_REJECTED
Definition: causes.h:116
static int delayreject
Definition: chan_iax2.c:433
#define IAX_DELME
Definition: chan_iax2.c:454
static int network_change_sched_id
Definition: chan_iax2.c:325
#define DEFAULT_MAX_THREAD_COUNT
Definition: chan_iax2.c:292
static int load_objects(void)
Definition: chan_iax2.c:14735
static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Execute IAX2 dialplan switch.
Definition: chan_iax2.c:14339
static int trunk_untimed
Definition: chan_iax2.c:314
static int ping_time
Definition: chan_iax2.c:329
Structure for variables, used for configurations and for channel variables.
iax2_format format
Definition: parser.h:39
static pj_pool_t * pool
Global memory pool for configuration and timers.
static void unwrap_timestamp(struct iax_frame *fr)
Definition: chan_iax2.c:4073
static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
Definition: chan_iax2.c:6071
#define IAX_IE_MD5_RESULT
Definition: iax2.h:146
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
Definition: chan_iax2.c:1929
const ast_string_field challenge
Definition: chan_iax2.c:816
ast_control_transfer
static void iax_debug_output(const char *data)
Definition: chan_iax2.c:1197
#define var
Definition: ast_expr2f.c:614
void MD5Final(unsigned char digest[16], struct MD5Context *context)
Definition: md5.c:120
#define MAX_TIMESTAMP_SKEW
Definition: chan_iax2.c:667
unsigned short bridgecallno
Definition: chan_iax2.c:857
struct ast_variable * iaxvars
Definition: chan_iax2.c:873
#define IAX_DPSTATUS_MATCHMORE
Definition: iax2.h:219
#define IAX_DEFAULT_PORTNO
Definition: iax2.h:128
#define IAX_IE_FIRMWAREVER
Definition: iax2.h:164
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9409
#define MIN_RETRY_TIME
Definition: chan_iax2.c:659
enum jb_return_code jb_put(jitterbuf *jb, void *data, const enum jb_frame_type type, long ms, long ts, long now)
queue a frame
Definition: jitterbuf.c:525
long frames_lost
Definition: jitterbuf.h:80
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
Definition: time.h:108
time_t checktime
Definition: chan_iax2.c:1080
return a reference to a taskprocessor, create one if it does not exist
Definition: taskprocessor.h:75
#define IAX_ENCRYPTED
Definition: chan_iax2.c:465
Test Framework API.
struct ast_frame * ast_read(struct ast_channel *chan)
Reads a frame.
Definition: channel.c:4302
int iax_get_oframes(void)
Definition: parser.c:1341
#define AST_IO_IN
Definition: io.h:34
unsigned char delme
Definition: chan_iax2.c:998
static struct stasis_subscription * network_change_sub
Definition: chan_iax2.c:323
const ast_string_field name
Definition: chan_iax2.c:554
const ast_string_field language
Definition: chan_iax2.c:816
Definition: cli.h:152
static struct iax2_thread * find_idle_thread(void)
Definition: chan_iax2.c:1586
void ast_timer_close(struct ast_timer *handle)
Close an opened timing handle.
Definition: timing.c:154
static char * handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:12278
if(!yyg->yy_init)
Definition: ast_expr2f.c:868
struct stasis_message_type * stasis_message_type(const struct stasis_message *msg)
Get the message type for a stasis_message.
Structure to pass both assignedid values to channel drivers.
Definition: channel.h:605
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
Definition: stasis.c:1079
static void jb_debug_output(const char *fmt,...)
Definition: chan_iax2.c:1232
unsigned char afdata[0]
Definition: parser.h:145
int ast_ignore_pattern(const char *context, const char *pattern)
Checks to see if a number should be ignored.
Definition: pbx.c:6921
#define IAX_IE_RR_DELAY
Definition: iax2.h:180
struct stasis_message_type * ast_named_acl_change_type(void)
a stasis_message_type for changes against a named ACL or the set of all named ACLs ...
int iax_provision_unload(void)
Definition: provision.c:520
Structure for a data store type.
Definition: datastore.h:31
ast_channel_state
ast_channel states
Definition: channelstate.h:35
#define DEFAULT_FREQ_OK
Definition: chan_iax2.c:391
unsigned int lastvsent
Definition: chan_iax2.c:717
static char * handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7561
struct ast_timer * ast_timer_open(void)
Open a timer.
Definition: timing.c:122
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:5348
int frames_dropped
Definition: chan_iax2.c:879
unsigned char semirand[32]
Definition: parser.h:137
uint64_t iax2_codec_pref_from_bitfield(struct iax2_codec_pref *pref, uint64_t bitfield)
Create codec preference list from the given bitfield formats.
Definition: codec_pref.c:483
char * str
Subscriber name (Malloced)
Definition: channel.h:265
int * ast_io_add(struct io_context *ioc, int fd, ast_io_cb callback, short events, void *data)
Adds an IO context.
Definition: io.c:162
static int registry_authrequest(int callno)
Definition: chan_iax2.c:9180
void ast_unregister_switch(struct ast_switch *sw)
Unregister an alternative switch.
Definition: pbx_switch.c:76
static const struct adsi_event events[]
Definition: app_adsiprog.c:85
static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:6365
int packets
Definition: chan_iax2.c:685
Scheduler ID holder.
Definition: sched.c:70
Used in the sip_show_peers functions to pass parameters.
Definition: chan_iax2.c:6830
ast_callid callid
Definition: chan_iax2.c:701
Definition of a media format.
Definition: format.c:43
#define ast_cond_wait(cond, mutex)
Definition: lock.h:203
void iax2_codec_pref_remove_missing(struct iax2_codec_pref *pref, uint64_t bitfield)
Removes format from the pref list that aren&#39;t in the bitfield.
Definition: codec_pref.c:288
#define IAX_CODEC_NOPREFS
Definition: chan_iax2.c:468
Background DNS update manager.
int ast_str_append(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Append to a thread local dynamic string.
Definition: strings.h:1091
#define ast_cond_init(cond, attr)
Definition: lock.h:199
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition: cli.h:265
static char * handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3701
struct ast_netsock_list * ast_netsock_list_alloc(void)
Definition: netsock.c:72
#define IAX_CAPABILITY_FULLBANDWIDTH
Definition: chan_iax2.c:369
int ast_format_cap_append_by_type(struct ast_format_cap *cap, enum ast_media_type type)
Add all codecs Asterisk knows about for a specific type to the capabilities structure.
Definition: format_cap.c:216
static int matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Definition: pbx_lua.c:1381
int iax_provision_build(struct iax_ie_data *provdata, unsigned int *signature, const char *template, int force)
Definition: provision.c:209
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
unsigned short transfercallno
Definition: chan_iax2.c:849
int callno
Definition: chan_iax2.c:574
static int auto_hangup(const void *data)
Definition: chan_iax2.c:9346
void iax2_codec_pref_prepend(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing, int only_if_existing)
Prepend an audio codec to a preference list, removing it first if it was already there.
Definition: codec_pref.c:434
ast_control_frame_type
Internal control frame subtype field values.
static int copy(char *infile, char *outfile)
Utility function to copy a file.
int dropped
Definition: chan_iax2.c:687
#define IAX_IE_AUTOANSWER
Definition: iax2.h:155
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:150
#define AST_DECLARE_STRING_FIELDS(field_list)
Declare the fields needed in a structure.
Definition: stringfields.h:337
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:650
#define IAX_SENDANI
Definition: chan_iax2.c:460
size_t ast_format_cap_count(const struct ast_format_cap *cap)
Get the number of formats present within the capabilities structure.
Definition: format_cap.c:395
void ast_endpoint_set_state(struct ast_endpoint *endpoint, enum ast_endpoint_state state)
Updates the state of the given endpoint.
struct ast_flags state
Definition: chan_iax2.c:765
unsigned int ast_callid
Definition: logger.h:87
static struct @481 methods[]
#define ast_set_flag64(p, flag)
Definition: utils.h:127
Wrapper for an ast_acl linked list.
Definition: acl.h:76
#define ast_assert(a)
Definition: utils.h:695
#define IAX_CODEC_USER_FIRST
Definition: chan_iax2.c:467
#define ast_mutex_lock(a)
Definition: lock.h:187
#define CALLNO_ENTRY_IS_VALIDATED(a)
Definition: chan_iax2.c:906
static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
Definition: chan_iax2.c:4800
unsigned char stop
Definition: chan_iax2.c:1099
#define IAX_MAX_OSPTOKEN_SIZE
Definition: iax2.h:192
#define IAX_DPSTATUS_IGNOREPAT
Definition: iax2.h:218
#define AST_OPTION_SECURE_MEDIA
#define ao2_unlock(a)
Definition: astobj2.h:730
static void user_destructor(void *obj)
Definition: chan_iax2.c:13105
static struct test_val c
static void set_hangup_source_and_cause(int callno, unsigned char causecode)
Definition: chan_iax2.c:10062
int ast_channel_register(const struct ast_channel_tech *tech)
Register a channel technology (a new channel driver) Called by a channel module to register the kind ...
Definition: channel.c:539
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
Definition: chan_iax2.c:2315
char * text
Definition: app_queue.c:1508
unsigned int last
Definition: chan_iax2.c:713
#define ast_str_alloca(init_len)
Definition: strings.h:800
const char * ast_format_get_name(const struct ast_format *format)
Get the name associated with a format.
Definition: format.c:334
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition: time.h:98
void ast_verbose(const char *fmt,...)
Definition: extconf.c:2207
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:243
Structure for a data store object.
Definition: datastore.h:68
static char * handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7328
static int socket_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9773
void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
Destroy the connected line information contents.
Definition: channel.c:2072
#define AST_OPTION_TDD
unsigned int rr_loss
Definition: parser.h:75
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition: channel.c:2404
Definition: parser.h:27
Definition: dnsmgr.c:66
int smoothing
Definition: chan_iax2.c:582
#define IAX_DEBUGDIGEST(msg, key)
Definition: chan_iax2.c:398
int ast_str2tos(const char *value, unsigned int *tos)
Convert a string to the appropriate TOS value.
Definition: acl.c:967
jitterbuf * jb
Definition: chan_iax2.c:755
static int iax2_devicestate(const char *data)
Part of the device state notification system —.
Definition: chan_iax2.c:14503
struct iax_frame * iax_frame_new(int direction, int datalen, unsigned int cacheable)
Definition: parser.c:1218
char * ast_category_browse(struct ast_config *config, const char *prev_name)
Browse categories.
Definition: extconf.c:3328
static void log_jitterstats(unsigned short callno)
Definition: chan_iax2.c:9669
#define FORMAT
static int peercnt_add(struct ast_sockaddr *addr)
Definition: chan_iax2.c:2631
const char * args
#define MAX_TRUNKDATA
Definition: chan_iax2.c:336
#define NULL
Definition: resample.c:96
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
Definition: netsock2.c:388
calltoken_peer_enum
Call token validation settings.
Definition: chan_iax2.c:491
Domain data structure.
Definition: sip.h:888
#define IAX_IE_CHALLENGE
Definition: iax2.h:145
unsigned int provver
Definition: parser.h:71
#define AST_CAUSE_NO_USER_RESPONSE
Definition: causes.h:107
enum jb_return_code jb_get(jitterbuf *jb, jb_frame *frame, long now, long interpl)
get a frame for time now (receiver&#39;s time) return value is one of JB_OK: You&#39;ve got frame! JB_DROP: H...
Definition: jitterbuf.c:785
int iax2_format_compatibility_bitfield2cap(uint64_t bitfield, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure.
I/O Management (derived from Cheops-NG)
unsigned short dpstatus
Definition: parser.h:53
static void send_signaling(struct chan_iax2_pvt *pvt)
This function must be called once we are sure the other side has given us a call number. All signaling is held here until that point.
Definition: chan_iax2.c:2158
char * end
Definition: eagi_proxy.c:73
static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
Definition: chan_iax2.c:10006
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
Definition: chan_iax2.c:4218
#define CALLNO_ENTRY_GET_CALLNO(a)
Definition: chan_iax2.c:907
callno_entry callno_entry
Definition: chan_iax2.c:739
char username[80]
Definition: chan_iax2.c:4596
ast_mutex_t lock
Definition: chan_iax2.c:596
int value
Definition: syslog.c:37
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
Force a refresh of a dnsmgr entry.
Definition: dnsmgr.c:239
static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
Definition: chan_iax2.c:7198
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies, struct ast_sockaddr *addr, int fd)
Definition: chan_iax2.c:4932
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
Definition: linkedlists.h:855
static char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:429
static char * handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7631
#define AST_FRAME_DTMF
static struct iax2_user * build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create in-memory user structure from configuration.
Definition: chan_iax2.c:13119
#define IAX_IE_DPSTATUS
Definition: iax2.h:150
char * devicetype
Definition: parser.h:63
#define PTR_TO_CALLNO_ENTRY(a)
Definition: chan_iax2.c:902
#define IAX_IE_LANGUAGE
Definition: iax2.h:140
Structure used to handle a large number of boolean flags == used only in app_dial?
Definition: utils.h:204
char * calling_number
Definition: parser.h:29
static int priority
const char * ext
Definition: http.c:147
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
Definition: chan_iax2.c:4321
int ast_unregister_application(const char *app)
Unregister an application.
Definition: pbx_app.c:392
static char default_parkinglot[AST_MAX_CONTEXT]
Definition: chan_iax2.c:318
static int update_registry(struct ast_sockaddr *addr, int callno, char *devtype, int fd, unsigned short refresh)
Definition: chan_iax2.c:9002
static void set_config_destroy(void)
Definition: chan_iax2.c:13459
#define AST_LIST_TRAVERSE_SAFE_END
Closes a safe loop traversal block.
Definition: linkedlists.h:614
void ast_moh_stop(struct ast_channel *chan)
Turn off music on hold on a given channel.
Definition: channel.c:7876
void ast_free_ptr(void *ptr)
free() wrapper
Definition: astmm.c:1771
Socket address structure.
Definition: netsock2.h:97
int iax2_codec_pref_best_bitfield2cap(uint64_t bitfield, struct iax2_codec_pref *prefs, struct ast_format_cap *cap)
Convert a bitfield to a format capabilities structure in the "best" order.
Definition: codec_pref.c:112
static char cid_num[AST_MAX_EXTENSION]
Definition: chan_mgcp.c:164
#define ast_cond_signal(cond)
Definition: lock.h:201
#define IAX_PROVISION
Definition: chan_iax2.c:463
struct ast_channel * ast_waitfor_nandfds(struct ast_channel **chan, int n, int *fds, int nfds, int *exception, int *outfd, int *ms)
Waits for activity on a group of channels.
Definition: channel.c:2997
int tm_year
Definition: localtime.h:41
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
Definition: netsock2.c:590
static int iaxactivethreadcount
Definition: chan_iax2.c:679
int ast_update_realtime(const char *family, const char *keyfield, const char *lookup,...) attribute_sentinel
Update realtime configuration.
Definition: main/config.c:3489
#define ast_verb(level,...)
Definition: logger.h:463
static int transfer
Definition: chan_mgcp.c:194
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
Definition: netsock2.c:413
static int lagrq_time
Definition: chan_iax2.c:330
struct ast_netsock * ast_netsock_bind(struct ast_netsock_list *list, struct io_context *ioc, const char *bindinfo, int defaultport, int tos, int cos, ast_io_cb callback, void *data)
Definition: netsock.c:167
static void pvt_destructor(void *obj)
Definition: chan_iax2.c:2196
static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
callback to display iax peers in manager format
Definition: chan_iax2.c:7267
#define IAX_IE_RR_JITTER
Definition: iax2.h:177
void MD5Init(struct MD5Context *context)
Definition: md5.c:57
#define MAX_RETRY_TIME
Definition: chan_iax2.c:660
struct iax_frame::@156 list
int ast_atomic_fetchadd_int(volatile int *p, int v)
Atomically add v to *p and return the previous value of *p.
Definition: lock.h:755
const ast_string_field inkeys
Definition: chan_iax2.c:554
const char * line
Definition: cli.h:162
static struct iax2_trunk_peer * find_tpeer(struct ast_sockaddr *addr, int fd)
Definition: chan_iax2.c:6246
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition: datastore.c:68
#define IAX_IE_CALLING_NUMBER
Definition: iax2.h:132
int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Looks for a valid matching extension.
Definition: pbx.c:4194
ast_aes_decrypt_key mydcx
Definition: parser.h:135
#define PEERS_FORMAT2
Definition: chan_iax2.c:6842
unsigned int nextpred
Definition: chan_iax2.c:719
int ast_translator_best_choice(struct ast_format_cap *dst_cap, struct ast_format_cap *src_cap, struct ast_format **dst_fmt_out, struct ast_format **src_fmt_out)
Chooses the best translation path.
Definition: translate.c:1385
unsigned short callno
Definition: iax2.h:270
static char * handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7107
Implementation of the IAX2 protocol.
int ast_callid_threadassoc_remove(void)
Removes callid from thread storage of the calling thread.
Definition: logger.c:2003
const char * pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
Return a pointer to the value of the corresponding channel variable.
static struct ast_custom_function iaxpeer_function
Definition: chan_iax2.c:14462
struct ast_frame_subclass subclass
const ast_string_field parkinglot
Definition: chan_iax2.c:816
static struct iax2_context * build_context(const char *context)
Definition: chan_iax2.c:12647
static struct ao2_container * iax_transfercallno_pvts
Another container of iax2_pvt structures.
Definition: chan_iax2.c:1170
ast_callid ast_read_threadstorage_callid(void)
extracts the callerid from the thread
Definition: logger.c:1962
int iax_ie_append_raw(struct iax_ie_data *ied, unsigned char ie, const void *data, int datalen)
Definition: parser.c:725
#define IAX_IE_CALLING_ANI
Definition: iax2.h:133
#define MAX_LANGUAGE
Definition: channel.h:173
int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
Simply remove extension from context.
Definition: pbx.c:4952
void iax_showframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
Definition: parser.c:594
uint16_t maxcallno
Definition: chan_iax2.c:583
Utility functions.
static iax2_format uncompress_subclass(unsigned char csub)
Definition: chan_iax2.c:1833
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Definition: netsock2.h:140
#define IAX_META_TRUNK_SUPERMINI
Definition: iax2.h:205
int authmethods
Definition: chan_iax2.c:566
int args
This gets set in ast_cli_register()
Definition: cli.h:185
threshold
Definition: dsp.h:71
int AST_OPTIONAL_API_NAME() ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
base64 decode then sent to __ast_check_signature_bin
Definition: res_crypto.c:445
int ast_context_destroy_by_name(const char *context, const char *registrar)
Destroy a context by name.
Definition: pbx.c:8244
const char * astman_get_header(const struct message *m, char *var)
Get header from mananger transaction.
Definition: manager.c:2820
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int)
Definition: chan_iax2.c:7771
unsigned short callno
Definition: iax2.h:248
#define IAX_CAPABILITY_LOWBANDWIDTH
Definition: chan_iax2.c:381
#define CALLNO_ENTRY_SET_VALIDATED(a)
Definition: chan_iax2.c:905
static char * handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:4001
unsigned int tos
Definition: chan_iax2.c:351
unsigned int pingtime
Definition: chan_iax2.c:727
#define ast_module_unref(mod)
Release a reference to the module.
Definition: module.h:469
pthread_cond_t ast_cond_t
Definition: lock.h:176
#define ast_strlen_zero(foo)
Definition: strings.h:52
struct chan_iax2_pvt::signaling_queue signaling_queue
static int resyncthreshold
Definition: chan_iax2.c:332
static int check_provisioning(struct ast_sockaddr *addr, int sockfd, char *si, unsigned int ver)
Definition: chan_iax2.c:9599
const char * name
Definition: pbx.h:162
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
Definition: linkedlists.h:652
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data)
Definition: chan_iax2.c:1681
int expiry
Definition: chan_iax2.c:570
struct ast_format * ast_channel_readformat(struct ast_channel *chan)
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2088
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
Definition: main/cli.c:1811
int ast_channel_defer_dtmf(struct ast_channel *chan)
Defers DTMF so that you only read things like hangups and audio.
Definition: channel.c:1257
unsigned char type
Definition: iax2.h:234
#define ast_pthread_create_background(a, b, c, d)
Definition: utils.h:567
int ast_format_cap_update_by_allow_disallow(struct ast_format_cap *cap, const char *list, int allowing)
Parse an "allow" or "deny" list and modify a format capabilities structure accordingly.
Definition: format_cap.c:320
const char * ast_config_AST_SYSTEM_NAME
Definition: options.c:170
void ast_channel_tech_set(struct ast_channel *chan, const struct ast_channel_tech *value)
static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
Queue the last read full frame for processing by a certain thread.
Definition: chan_iax2.c:9742
int done
Definition: test_amihooks.c:48
#define IAX_IE_ENCRYPTION
Definition: iax2.h:173
Number structure.
Definition: app_followme.c:154
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized, or having a 0 length.
Definition: netsock2.h:127
#define AST_MAX_ACCOUNT_CODE
Definition: channel.h:171
static int register_verify(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Verify inbound registration.
Definition: chan_iax2.c:8189
jitterbuf * jb_new(void)
new jitterbuf
Definition: jitterbuf.c:86
enum ama_flags ast_channel_string2amaflag(const char *flag)
Convert a string to a detail record AMA flag.
Definition: channel.c:4405
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
Definition: netsock2.h:521
int msgcount
Definition: parser.h:58
Custom localtime functions for multiple timezones.
uint64_t iax2_codec_pref_order_value_to_format_bitfield(int order_value)
Convert an iax2_codec_pref order value into a format bitfield.
Definition: codec_pref.c:367
internal representation of ACL entries In principle user applications would have no need for this...
Definition: acl.h:51
int ast_callid_threadassoc_add(ast_callid callid)
Adds a known callid to thread storage of the calling thread.
Definition: logger.c:1984
meta
below block is needed for mssql
Definition: env.py:22
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
Definition: chan_iax2.c:6543
#define MIN(a, b)
Definition: utils.h:226
int ast_str_set(struct ast_str **buf, ssize_t max_len, const char *fmt,...)
Set a dynamic string using variable arguments.
Definition: strings.h:1065
unsigned short dcallno
Definition: iax2.h:230
struct ast_party_id id
Caller party ID.
Definition: channel.h:421
static int __unload_module(void)
Definition: chan_iax2.c:14601
static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
Definition: chan_iax2.c:9361
static int netsocket
Definition: pbx_dundi.c:186
static struct ast_sockaddr debugaddr
Definition: chan_iax2.c:1177
static char * ast_sockaddr_stringify_port(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return a port only.
Definition: netsock2.h:362
static int autokill
Definition: chan_iax2.c:342
Configuration File Parser.
#define IAX_DYNAMIC
Definition: chan_iax2.c:459
char * called_context
Definition: parser.h:35
AES_KEY ast_aes_encrypt_key
Definition: crypto.h:35
iax2_state
Definition: chan_iax2.c:441
unsigned int ts
Definition: iax2.h:276
struct iax2_context * contexts
Definition: chan_iax2.c:528
char * codec_prefs
Definition: parser.h:40
int ast_get_time_t(const char *src, time_t *dst, time_t _default, int *consumed)
get values from config variables.
Definition: main/utils.c:2198
char * ast_strip_quoted(char *s, const char *beg_quotes, const char *end_quotes)
Strip leading/trailing whitespace and quotes from a string.
Definition: main/utils.c:1639
static int global_max_trunk_mtu
Definition: chan_iax2.c:313
char * challenge
Definition: parser.h:48
struct ast_iax2_mini_hdr mini
Definition: iax2.h:288
#define EVENT_FLAG_SYSTEM
Definition: manager.h:71
static struct iax2_peer * build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
Create peer structure based on configuration.
Definition: chan_iax2.c:12794
static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct ast_sockaddr *addr, int sockfd, struct iax_frame *fr)
Definition: chan_iax2.c:9851
unsigned int sentyet
Definition: parser.h:115
long frames_in
Definition: jitterbuf.h:77
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:452
iax2_thread_type
Definition: chan_iax2.c:1049
#define ast_log
Definition: astobj2.c:42
long jb_next(jitterbuf *jb)
when is the next frame due out, in receiver&#39;s time (0=EMPTY) This value may change as frames are adde...
Definition: jitterbuf.c:767
#define MAX_TRUNK_MTU
Maximum transmission unit for the UDP packet in the trunk not to be fragmented. This is based on 1516...
Definition: chan_iax2.c:311
void ast_channel_set_rawreadformat(struct ast_channel *chan, struct ast_format *format)
long resync_threshold
Definition: jitterbuf.h:68
static int defaultsockfd
Definition: chan_iax2.c:364
static void * iax2_process_thread(void *data)
Definition: chan_iax2.c:11990
#define SENTINEL
Definition: compiler.h:87
#define IAX_MAX_OSPBLOCK_NUM
Definition: iax2.h:191
#define ast_config_load(filename, flags)
Load a config file.
unsigned int encmethods
Definition: parser.h:47
void ast_netsock_unref(struct ast_netsock *ns)
Definition: netsock.c:198
#define MAX_USER_BUCKETS
Definition: chan_iax2.c:954
unsigned short callno
Definition: parser.h:54
enum ast_format_cmp_res ast_format_cmp(const struct ast_format *format1, const struct ast_format *format2)
Compare two formats.
Definition: format.c:201
int provverpres
Definition: parser.h:73
int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt,...)
Tells Asterisk the State for Device is changed.
Definition: devicestate.c:510
static char host[256]
Definition: muted.c:77
struct ast_module * self
Definition: module.h:342
int ast_sockaddr_split_hostport(char *str, char **host, char **port, int flags)
Splits a string into its host and port components.
Definition: netsock2.c:164
enum ast_transfer_result ast_bridge_transfer_blind(int is_external, struct ast_channel *transferer, const char *exten, const char *context, transfer_channel_cb new_channel_cb, void *user_data)
Blind transfer target to the extension and context provided.
Definition: bridge.c:4477
char * ast_callerid_merge(char *buf, int bufsiz, const char *name, const char *num, const char *unknown)
Definition: callerid.c:1073
static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
Definition: chan_iax2.c:8106
unsigned short len
Definition: iax2.h:287
static int scheduled_destroy(const void *vid)
Definition: chan_iax2.c:2136
struct ast_party_id ani
Automatic Number Identification (ANI)
Definition: channel.h:428
static void __send_lagrq(const void *data)
Definition: chan_iax2.c:1780
unsigned char * calltokendata
Definition: parser.h:84
#define VERBOSE_PREFIX_4
Definition: logger.h:44
#define IAX_IE_FORMAT2
Definition: iax2.h:188
General Asterisk PBX channel definitions.
static void * iax2_dup_variable_datastore(void *)
Definition: chan_iax2.c:1529
static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
Definition: chan_iax2.c:6381
static int iax2_transfer(struct ast_channel *c, const char *dest)
Definition: chan_iax2.c:5787
static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
Definition: chan_iax2.c:4810
int ast_realtime_require_field(const char *family,...) attribute_sentinel
Inform realtime what fields that may be stored.
Definition: main/config.c:3382
static void iax2_destroy(int callno)
Definition: chan_iax2.c:3459
struct timeval txtrunktime
Definition: chan_iax2.c:599
static struct ao2_container * users
Definition: chan_iax2.c:955
static void * dp_lookup_thread(void *data)
Definition: chan_iax2.c:9570
#define DEFAULT_RETRY_TIME
Definition: chan_iax2.c:293
#define DEFAULT_THREAD_COUNT
Definition: chan_iax2.c:291
unsigned char causecode
Definition: parser.h:56
#define AST_SCHED_DEL(sched, id)
Remove a scheduler entry.
Definition: sched.h:46
void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
Set the source of the hangup in this channel and it&#39;s bridge.
Definition: channel.c:2504
Asterisk file paths, configured in asterisk.conf.
#define AST_FRIENDLY_OFFSET
Offset into a frame&#39;s data buffer.
void io_context_destroy(struct io_context *ioc)
Destroys a context.
Definition: io.c:107
static struct ao2_container * peers
Definition: chan_iax2.c:952
const char * src
void astman_send_list_complete_end(struct mansession *s)
End the list complete event.
Definition: manager.c:3245
#define DIRECTION_OUTGRESS
Definition: parser.h:88
void ast_channel_undefer_dtmf(struct ast_channel *chan)
Unset defer DTMF flag on channel.
Definition: channel.c:1271
#define ast_mutex_trylock(a)
Definition: lock.h:189
unsigned int cacheable
Definition: parser.h:123
struct ast_sockaddr netmask
Definition: acl.h:54
#define AST_IO_PRI
Definition: io.h:38
long frames_ooo
Definition: jitterbuf.h:82
#define DIRECTION_INGRESS
Definition: parser.h:87
char exten[AST_MAX_EXTENSION]
Definition: chan_iax2.c:1022
#define IAX_IE_CAUSECODE
Definition: iax2.h:172
int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
Sets read format on channel chan.
Definition: channel.c:5849
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition: utils.h:911
Network socket handling.
static int iax2_lock_callno_unless_destroyed(int callno)
Definition: chan_iax2.c:1698
#define AST_OPTION_RELAXDTMF
unsigned int rr_jitter
Definition: parser.h:74
int ast_variable_list_replace(struct ast_variable **head, struct ast_variable *replacement)
Replace a variable in the given list with a new value.
Definition: main/config.c:668
struct timeval offset
Definition: chan_iax2.c:751
iax2_format peerformat
Definition: chan_iax2.c:747
static struct ast_generator gen
const int fd
Definition: cli.h:159
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
Free a DNS manager entry.
Definition: dnsmgr.c:136
void ast_channel_nativeformats_set(struct ast_channel *chan, struct ast_format_cap *value)
#define IAX_IE_VERSION
Definition: iax2.h:141
static int peer_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:1962
#define ast_string_field_init(x, size)
Initialize a field pool and fields.
Definition: stringfields.h:353
void ast_channel_stage_snapshot_done(struct ast_channel *chan)
Clear flag to indicate channel snapshot is being staged, and publish snapshot.
#define PTR_TO_CALLNO(a)
Definition: chan_iax2.c:288
struct ast_party_connected_line * ast_channel_connected(struct ast_channel *chan)
int losspct
Definition: chan_iax2.c:683
static void acl_change_stasis_subscribe(void)
Definition: chan_iax2.c:1470
#define AST_PTHREADT_NULL
Definition: lock.h:66
int iax2_codec_pref_to_cap(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
Convert a preference structure to a capabilities structure.
Definition: codec_pref.c:91
static struct call_number_pool callno_pool_trunk
Definition: chan_iax2.c:921
#define IAX_HASCALLERID
Definition: chan_iax2.c:453
char username[80]
Definition: chan_iax2.c:642
const int n
Definition: cli.h:165
enum iax2_thread_type type
Definition: chan_iax2.c:1062
unsigned char iax_unknown
Definition: parser.h:57
size_t buf_size
Definition: chan_iax2.c:1078
Data structure associated with a custom dialplan function.
Definition: pbx.h:118
Access Control of various sorts.
IAX Firmware Support header file.
static void iax2_publish_registry(const char *username, const char *domain, const char *status, const char *cause)
Definition: chan_iax2.c:8710
ast_mutex_t lock
Definition: app_meetme.c:1091
Global IO variables are now in a struct in order to be made threadsafe.
Definition: io.c:71
#define IAX_RTCACHEFRIENDS
Definition: chan_iax2.c:470
ast_cond_t cond
Definition: app_meetme.c:1090
static char mohsuggest[MAX_MUSICCLASS]
Definition: chan_iax2.c:430
#define AST_MAX_EXTENSION
Definition: channel.h:135
static int iaxtrunkdebug
Definition: chan_iax2.c:418
unsigned short peercallno
Definition: chan_iax2.c:741
Scheduler Routines (derived from cheops)
enum iax2_thread_iostate iostate
Definition: chan_iax2.c:1063
const ast_string_field zonetag
Definition: chan_iax2.c:554
const ast_string_field mohinterpret
Definition: chan_iax2.c:816
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
Definition: chan_iax2.c:1881
#define AST_STRING_FIELD(name)
Declare a string field.
Definition: stringfields.h:299
char * osptokenblock[IAX_MAX_OSPBLOCK_NUM]
Definition: parser.h:81
static char * handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7173
unsigned short len
Definition: iax2.h:282
int iax_ie_append(struct iax_ie_data *ied, unsigned char ie)
Definition: parser.c:779
int tm_mon
Definition: localtime.h:40
#define IAX_DPSTATUS_NONEXISTENT
Definition: iax2.h:217
#define AST_LIST_REMOVE_CURRENT(field)
Removes the current entry from a list during a traversal.
Definition: linkedlists.h:556
unsigned short zeros
Definition: iax2.h:262
static int complete_transfer(int callno, struct iax_ies *ies)
Definition: chan_iax2.c:8649
Asterisk internal frame definitions.
static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition: chan_iax2.c:3234
#define ao2_ref(o, delta)
Definition: astobj2.h:464
void ast_channel_set_readformat(struct ast_channel *chan, struct ast_format *format)
static struct @112 frame_queue[IAX_MAX_CALLS]
a list of frames that may need to be retransmitted
#define S_COR(a, b, c)
returns the equivalent of logic or for strings, with an additional boolean check: second one if not e...
Definition: strings.h:85
static char * papp
Definition: chan_iax2.c:12244
#define IAX_IE_CALLING_NAME
Definition: iax2.h:134
void ast_config_destroy(struct ast_config *config)
Destroys a config.
Definition: extconf.c:1290
In case you didn&#39;t read that giant block of text above the mansession_session struct, the struct mansession is named this solely to keep the API the same in Asterisk. This structure really represents data that is different from Manager action to Manager action. The mansession_session pointer contained within points to session-specific data.
Definition: manager.c:1625
struct ast_format * ast_format_cap_get_compatible_format(const struct ast_format_cap *cap, const struct ast_format *format)
Find if input ast_format is within the capabilities of the ast_format_cap object then return the comp...
Definition: format_cap.c:548
unsigned char data[0]
Definition: iax2.h:277
const ast_string_field regexten
Definition: chan_iax2.c:554
long int ast_random(void)
Definition: main/utils.c:2064
const ast_string_field username
Definition: chan_iax2.c:816
unsigned int lastsent
Definition: chan_iax2.c:603
#define ao2_lock(a)
Definition: astobj2.h:718
int old_msgs
Definition: mwi.h:462
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition: time.h:238
static uint16_t total_nonval_callno_used
Definition: chan_iax2.c:975
#define IAX_IE_PROVISIONING
Definition: iax2.h:159
static void __auto_hangup(const void *nothing)
Definition: chan_iax2.c:9331
static void iax_pvt_callid_set(int callno, ast_callid callid)
Definition: chan_iax2.c:1132
Require call token validation.
Definition: chan_iax2.c:495
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno, int now, int transfer, int final)
Definition: chan_iax2.c:7712
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
Definition: chan_iax2.c:3054
#define AST_BRIDGE_DTMF_CHANNEL_1
Report DTMF on channel 1.
Definition: channel.h:2384
static struct ao2_container * calltoken_ignores
Definition: chan_iax2.c:964
static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: chan_iax2.c:14390
int ast_atomic_dec_and_test(volatile int *p)
decrement *p by 1 and return true if the variable has reached 0.
Definition: lock.h:765
void AST_OPTIONAL_API_NAME() ast_aes_encrypt(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *ctx)
Definition: res_crypto.c:476
int AST_OPTIONAL_API_NAME() ast_sign(struct ast_key *key, char *msg, char *sig)
wrapper for __ast_sign_bin then base64 encode it
Definition: res_crypto.c:399
unsigned int ast_codec_samples_count(struct ast_frame *frame)
Get the number of samples contained within a frame.
Definition: codec.c:378
#define ast_format_cap_append(cap, format, framing)
Definition: format_cap.h:103
void ast_channel_amaflags_set(struct ast_channel *chan, enum ama_flags value)
Default calltoken required unless the ip is in the ignorelist.
Definition: chan_iax2.c:493
static void challenge(const char *realm, pjsip_tx_data *tdata, const pjsip_rx_data *rdata, int is_stale)
astobj2 callback for adding digest challenges to responses
int last_iax_message
Definition: chan_iax2.c:723
A set of macros to manage forward-linked lists.
unsigned char * buf
Definition: chan_iax2.c:1076
#define ast_malloc(len)
A wrapper for malloc()
Definition: astmm.h:193
long frames_dropped
Definition: jitterbuf.h:81
int iax_get_frames(void)
Definition: parser.c:1339
int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
Sets write format on channel chan.
Definition: channel.c:5890
#define AST_KEY_PRIVATE
Definition: crypto.h:43
static char zonetag[80]
unsigned short adsicpe
Definition: parser.h:43
#define IAX_AUTH_RSA
Definition: iax2.h:197
static void __send_ping(const void *data)
Definition: chan_iax2.c:1716
#define ast_variable_new(name, value, filename)
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:832
static void delete_users(void)
Definition: chan_iax2.c:13399
int tm_mday
Definition: localtime.h:39
static int trunkfreq
Definition: chan_iax2.c:338
static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
Definition: chan_iax2.c:9538
AST_LIST_HEAD_NOLOCK(contactliststruct, contact)
callno_entry numbers[IAX_MAX_CALLS/2+1]
Definition: chan_iax2.c:912
static int iaxdebug
Definition: chan_iax2.c:416
int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
Determine whether an extension exists.
Definition: pbx.c:4179
static int iax2_queue_unhold(int callno)
Queue an unhold frame on the ast_channel owner.
Definition: chan_iax2.c:3299
struct ast_frame f
Definition: chan_iax2.c:893
static int authenticate_reply(struct chan_iax2_pvt *p, struct ast_sockaddr *addr, struct iax_ies *ies, const char *override, const char *okey)
Definition: chan_iax2.c:8411
#define ast_format_cap_alloc(flags)
Definition: format_cap.h:52
static int unload_module(void)
Definition: chan_iax2.c:14682
iax_reg_state
Definition: chan_iax2.c:616
int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
Queue a hold frame.
Definition: channel.c:1191
#define IAX2_TRUNK_PREFACE
Definition: chan_iax2.c:593
#define IAX_IE_DNID
Definition: iax2.h:143
static void iax2_free_variable_datastore(void *)
Definition: chan_iax2.c:1553
static int timing_read(int *id, int fd, short events, void *cbdata)
Definition: chan_iax2.c:9460
const ast_string_field accountcode
Definition: chan_iax2.c:516
unsigned short callno
Definition: iax2.h:281
enum ast_acl_sense ast_apply_acl(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr, const char *purpose)
Apply a set of rules to a given IP address.
Definition: acl.c:800
ast_cond_t cond
Definition: chan_iax2.c:1082
Structure to describe a channel "technology", ie a channel driver See for examples: ...
Definition: channel.h:629
int ast_sockaddr_hash(const struct ast_sockaddr *addr)
Computes a hash value from the address. The port is ignored.
Definition: netsock2.c:548
void ast_channel_adsicpe_set(struct ast_channel *chan, enum ast_channel_adsicpe value)
static int peercnt_remove_cb(const void *obj)
Definition: chan_iax2.c:2708
Core PBX routines and definitions.
static int trunk_timed
Definition: chan_iax2.c:314
int ast_sockaddr_apply_netmask(const struct ast_sockaddr *addr, const struct ast_sockaddr *netmask, struct ast_sockaddr *result)
Apply a netmask to an address and store the result in a separate structure.
Definition: netsock2.c:357
static int user_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13390
static void acl_change_stasis_unsubscribe(void)
Definition: chan_iax2.c:1480
iax2_format capability
Definition: chan_iax2.c:711
uint16_t limit
Definition: chan_iax2.c:996
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f)
Queue one or more frames to a channel&#39;s frame queue.
Definition: channel.c:1139
int lastms
Definition: chan_iax2.c:576
static ast_callid iax_pvt_callid_get(int callno)
Definition: chan_iax2.c:1127
int ast_check_hangup(struct ast_channel *chan)
Check to see if a channel is needing hang up.
Definition: channel.c:445
static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8602
static int firmware_show_callback(struct ast_iax2_firmware_header *header, void *user_data)
Definition: chan_iax2.c:7205
static int __do_deliver(void *data)
Definition: chan_iax2.c:3340
static void poke_all_peers(void)
Definition: chan_iax2.c:13998
#define IAX_RECVCONNECTEDLINE
Definition: chan_iax2.c:481
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:530
int version
Definition: parser.h:42
#define AST_CAUSE_DESTINATION_OUT_OF_ORDER
Definition: causes.h:114
int ast_acl_list_is_empty(struct ast_acl_list *acl_list)
Determines if an ACL is empty or if it contains entries.
Definition: acl.c:541
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2418
unsigned int direction
Definition: parser.h:121
#define CONFIG_STATUS_FILEUNCHANGED
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
peer_status: Report Peer status in character string
Definition: chan_iax2.c:3792
#define stasis_subscribe(topic, callback, data)
Definition: stasis.h:652
int formats
Definition: chan_iax2.c:558
int pokefreqok
Definition: chan_iax2.c:579
Format Capabilities API.
long target_extra
Definition: jitterbuf.h:70
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4603
int first_iax_message
Definition: chan_iax2.c:721
struct iax2_codec_pref prefs
Definition: chan_iax2.c:4589
int destroy_initiated
Definition: chan_iax2.c:883
uint64_t flags
Definition: chan_iax2.c:562
void ast_sha1_hash(char *output, const char *input)
Produces SHA1 hash based on input string.
Definition: main/utils.c:264
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:290
struct ast_sched_context * ast_sched_context_create(void)
Create a scheduler context.
Definition: sched.c:236
struct timeval expiry
Definition: chan_iax2.c:1024
static int maxjitterbuffer
Definition: chan_iax2.c:331
jitterbuf: an application-independent jitterbuffer jitterbuf.c
static int iax2_answer(struct ast_channel *c)
Definition: chan_iax2.c:5727
int delay
Definition: chan_iax2.c:686
#define IAX_IE_CALLTOKEN
Definition: iax2.h:185
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:290
const char *const * argv
Definition: cli.h:161
unsigned int rr_ooo
Definition: parser.h:79
unsigned char reg
Definition: chan_iax2.c:988
static int(* iax2_regfunk)(const char *username, int onoff)
Definition: chan_iax2.c:366
static struct iax2_codec_pref prefs_global
Definition: chan_iax2.c:304
static int iax2_queue_hangup(int callno)
Queue a hangup frame on the ast_channel owner.
Definition: chan_iax2.c:3322
static int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
Definition: chan_iax2.c:3085
static int iax2_register(const char *value, int lineno)
Definition: chan_iax2.c:8824
static int replace_callno(const void *obj)
Definition: chan_iax2.c:2982
int ast_manager_unregister(const char *action)
Unregister a registered manager command.
Definition: manager.c:7258
iax2_format voiceformat
Definition: chan_iax2.c:703
static struct ast_taskprocessor * transmit_processor
Definition: chan_iax2.c:934
void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len)
Definition: md5.c:72
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
char secret[80]
Definition: chan_iax2.c:4597
ast_aes_decrypt_key mydcx
Definition: chan_iax2.c:826
#define IAX_IE_CALLED_NUMBER
Definition: iax2.h:131
void ast_channel_stage_snapshot(struct ast_channel *chan)
Set flag to indicate channel snapshot is being staged.
int pos
Definition: parser.h:150
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
Definition: chan_iax2.c:5367
int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
Parse connected line indication frame data.
Definition: channel.c:8881
const ast_string_field outkey
Definition: chan_iax2.c:554
static int iaxdynamicthreadcount
Definition: chan_iax2.c:677
IAX2 Provisioning protocol.
#define AST_OPTION_DIGIT_DETECT
int curauthreq
Definition: chan_iax2.c:525
static int iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9398
#define AST_CAUSE_FACILITY_NOT_SUBSCRIBED
Definition: causes.h:125
static void iax2_frame_free(struct iax_frame *fr)
Definition: chan_iax2.c:2130
unsigned short ts
Definition: iax2.h:271
int ast_timer_ack(const struct ast_timer *handle, unsigned int quantity)
Acknowledge a timer event.
Definition: timing.c:171
#define IAX_IE_ADSICPE
Definition: iax2.h:142
static void set_peercnt_limit(struct peercnt *peercnt)
Definition: chan_iax2.c:2553
char name[0]
Definition: chanvars.h:31
#define IAX_MAX_OSPBLOCK_SIZE
Definition: iax2.h:190
#define LOG_ERROR
Definition: logger.h:285
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compres two struct timeval instances returning -1, 0, 1 if the first arg is smaller, equal or greater to the second.
Definition: time.h:128
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
Definition: chan_iax2.c:5734
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:730
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Definition: astobj2.h:1310
unsigned int final
Definition: parser.h:119
const void * scheddata
Definition: chan_iax2.c:1066
uint16_t cur
Definition: chan_iax2.c:983
#define IAX_CODEC_NOCAP
Definition: chan_iax2.c:469
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
Definition: main/utils.c:1951
const ast_string_field accountcode
Definition: chan_iax2.c:816
static int iaxcompat
Definition: chan_iax2.c:343
#define IAX_TRUNK
Definition: chan_iax2.c:456
int pokeexpire
Definition: chan_iax2.c:575
Implementation of Inter-Asterisk eXchange, version 2 iax2-parser::c iax2-parser.h chan_iax2...
The descriptor of a dynamic string XXX storage will be optimized later if needed We use the ts field ...
Definition: strings.h:584
Format capabilities structure, holds formats + preference order + etc.
Definition: format_cap.c:54
ast_callid ast_create_callid(void)
factory function to create a new uniquely identifying callid.
Definition: logger.c:1957
static int iax2_vnak(int callno)
Definition: chan_iax2.c:9373
unsigned int transfer
Definition: parser.h:117
static int maxauthreq
Definition: chan_iax2.c:327
struct ast_taskprocessor * mailbox
Definition: stasis.c:687
const ast_string_field mohinterpret
Definition: chan_iax2.c:554
#define AST_OPTION_RXGAIN
uint64_t flags
Definition: chan_iax2.c:522
void * data
Definition: jitterbuf.h:100
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
Definition: chan_iax2.c:2494
const ast_string_field parkinglot
Definition: chan_iax2.c:516
Media Format Bitfield Compatibility API.
void * data
Definition: parser.h:103
#define ao2_unlink(container, obj)
Definition: astobj2.h:1598
const ast_string_field peer
Definition: chan_iax2.c:816
int iax2_codec_pref_string(struct iax2_codec_pref *pref, char *buf, size_t size)
Dump audio codec preference list into a string.
Definition: codec_pref.c:178
void iax_firmware_unload(void)
Definition: firmware.c:250
#define CLI_SHOWUSAGE
Definition: cli.h:45
unsigned char csub
Definition: chan_iax2.c:1093
static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
Definition: chan_iax2.c:6056
static int peer_set_sock_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14689
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
Definition: netsock2.h:537
struct iax2_codec_pref prefs
Definition: chan_iax2.c:526
static int reload_config(int forced_reload)
Definition: chan_iax2.c:14010
static struct chan_iax2_pvt * iaxs[IAX_MAX_CALLS]
an array of iax2 pvt structures
Definition: chan_iax2.c:1125
unsigned short ts
Definition: iax2.h:249
int plan
Q.931 Type-Of-Number and Numbering-Plan encoded fields.
Definition: channel.h:294
void * stasis_message_data(const struct stasis_message *msg)
Get the data contained in a message.
int calling_pres
Definition: parser.h:34
static void iax2_process_thread_cleanup(void *data)
Definition: chan_iax2.c:11978
int ast_remaining_ms(struct timeval start, int max_ms)
Calculate remaining milliseconds given a starting timestamp and upper bound.
Definition: main/utils.c:2033
static void iax_error_output(const char *data)
Definition: chan_iax2.c:1203
static char * handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Show one peer in detail.
Definition: chan_iax2.c:3815
unsigned short callno
Definition: parser.h:99
enum jb_return_code jb_setconf(jitterbuf *jb, jb_conf *conf)
set jitterbuf conf
Definition: jitterbuf.c:825
static struct ast_frame * iax2_read(struct ast_channel *c)
Definition: chan_iax2.c:5456
const ast_string_field mohsuggest
Definition: chan_iax2.c:816
static struct ast_netsock_list * outsock
Definition: chan_iax2.c:363
struct ast_acl_list * ast_free_acl_list(struct ast_acl_list *acl)
Free a list of ACLs.
Definition: acl.c:233
#define IAX_IE_AUTHMETHODS
Definition: iax2.h:144
static char * tz
Definition: cdr_pgsql.c:75
unsigned char cmddata
Definition: iax2.h:264
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force)
Definition: chan_iax2.c:12197
static void __iax2_poke_peer_s(const void *data)
Definition: chan_iax2.c:9391
struct iax2_peer * peerpoke
Definition: chan_iax2.c:837
void ast_callid_strnprint(char *buffer, size_t buffer_size, ast_callid callid)
copy a string representation of the callid into a target string
Definition: logger.c:1952
void ast_var_delete(struct ast_var_t *var)
Definition: extconf.c:2473
struct ast_mwi_subscriber * mwi_event_sub
Definition: chan_iax2.c:585
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
char * value
Definition: chanvars.h:30
struct stasis_message_type * ast_endpoint_state_type(void)
Message type for endpoint state changes.
static struct iax2_user * user_unref(struct iax2_user *user)
Definition: chan_iax2.c:2039
ast_channel_adsicpe
Definition: channel.h:869
int errno
char cid_name[80]
Definition: chan_iax2.c:4601
char * language
Definition: parser.h:41
int iax_ie_append_versioned_uint64(struct iax_ie_data *ied, unsigned char ie, unsigned char version, uint64_t value)
Definition: parser.c:745
char mohinterpret[MAX_MUSICCLASS]
Definition: chan_iax2.c:4604
const ast_string_field inkeys
Definition: chan_iax2.c:816
static int max_retries
Definition: chan_iax2.c:328
const ast_string_field mohinterpret
Definition: chan_iax2.c:516
Definition: file.c:69
static int iax2_sendtext(struct ast_channel *c, const char *text)
Definition: chan_iax2.c:4326
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition: extconf.c:2283
Definition: chan_iax2.c:892
Connected Line/Party information.
Definition: channel.h:457
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
Definition: chan_iax2.c:2603
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2578
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition: netsock2.h:260
ast_aes_encrypt_key ecx
Definition: parser.h:133
pthread_t threadid
Definition: chan_iax2.c:1072
static int min_reg_expire
Definition: chan_iax2.c:355
int iax_get_iframes(void)
Definition: parser.c:1340
struct ast_party_dialed * ast_channel_dialed(struct ast_channel *chan)
def ignore(key=None, val=None, section=None, pjsip=None, nmapped=None, type='endpoint')
Definition: sip_to_pjsip.py:48
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
Definition: chan_iax2.c:4333
static struct ast_channel_tech iax2_tech
Definition: chan_iax2.c:1293
int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
Turn on music on hold on a given channel.
Definition: channel.c:7866
ssize_t ast_recvfrom(int sockfd, void *buf, size_t len, int flags, struct ast_sockaddr *src_addr)
Wrapper around recvfrom(2) that uses struct ast_sockaddr.
Definition: netsock2.c:606
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7766
static int transmit_frame(void *data)
Definition: chan_iax2.c:4282
const ast_string_field mohsuggest
Definition: chan_iax2.c:554
static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9639
long ms
Definition: jitterbuf.h:102
Do not require call token validation.
Definition: chan_iax2.c:500
static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:12358
unsigned int ts
Definition: parser.h:109
#define ao2_iterator_next(iter)
Definition: astobj2.h:1933
#define ast_cond_destroy(cond)
Definition: lock.h:200
unsigned short callno
Definition: chan_iax2.c:1026
static int iaxdynamicthreadnum
Definition: chan_iax2.c:678
#define ao2_alloc(data_size, destructor_fn)
Definition: astobj2.h:411
#define AST_PRES_NUMBER_NOT_AVAILABLE
Definition: callerid.h:353
int ast_get_ip(struct ast_sockaddr *addr, const char *hostname)
Get the IP address given a hostname.
Definition: acl.c:1000
#define DEFAULT_CONTEXT
Definition: chan_iax2.c:316
void iax2_codec_pref_append(struct iax2_codec_pref *pref, struct ast_format *format, unsigned int framing)
Append a audio codec to a preference list, removing it first if it was already there.
Definition: codec_pref.c:422
unsigned int ast_format_cap_get_format_framing(const struct ast_format_cap *cap, const struct ast_format *format)
Get the framing for a format.
Definition: format_cap.c:443
static const struct ast_datastore_info iax2_variable_datastore_info
Definition: chan_iax2.c:1523
#define AST_LIST_LAST(head)
Returns the last entry contained in a list.
Definition: linkedlists.h:428
#define IAX_IE_PASSWORD
Definition: iax2.h:137
#define LOG_NOTICE
Definition: logger.h:263
const ast_string_field username
Definition: chan_iax2.c:554
char * rdnis
Definition: parser.h:45
#define CALLNO_ENTRY_TO_PTR(a)
Definition: chan_iax2.c:903
const char * ast_format_cap_get_names(const struct ast_format_cap *cap, struct ast_str **buf)
Get the names of codecs of a set of formats.
Definition: format_cap.c:736
static int trunk_maxmtu
Definition: chan_iax2.c:314
#define IAX_ALLOWFWDOWNLOAD
Definition: chan_iax2.c:478
static int registry_rerequest(struct iax_ies *ies, int callno, struct ast_sockaddr *addr)
Definition: chan_iax2.c:9228
struct stasis_topic * ast_system_topic(void)
A Stasis Message Bus API topic which publishes messages regarding system changes. ...
static int pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14706
struct ast_format_cap * capabilities
Definition: channel.h:633
#define IAX_IE_MSGCOUNT
Definition: iax2.h:154
const ast_string_field ani
Definition: chan_iax2.c:816
unsigned char devname[16]
Definition: iax2.h:296
static int maxjitterinterps
Definition: chan_iax2.c:333
static struct ast_sched_context * sched
Definition: chan_iax2.c:412
static int totalcalls
Definition: pbx.c:774
static int trunkmaxsize
Definition: chan_iax2.c:339
struct timeval orig
Definition: chan_iax2.c:1023
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:490
static struct ast_flags64 globalflags
Definition: chan_iax2.c:437
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:409
static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
Definition: chan_iax2.c:4608
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
Definition: linkedlists.h:710
static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
Parse the "sourceaddress" value, lookup in netsock list and set peer&#39;s sockfd. Defaults to defaultsoc...
Definition: chan_iax2.c:12696
static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition: chan_iax2.c:6515
const ast_string_field host
Definition: chan_iax2.c:816
static int iax2_encryption
Definition: chan_iax2.c:434
char outkey[80]
Definition: chan_iax2.c:4598
static const char tdesc[]
Definition: chan_iax2.c:306
uint64_t flags
Definition: chan_iax2.c:839
static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
callback to display iax peers in manager
Definition: chan_iax2.c:7245
static void vnak_retransmit(int callno, int last)
Definition: chan_iax2.c:9378
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame)
Definition: chan_iax2.c:3238
#define ast_channel_unlock(chan)
Definition: channel.h:2946
int iax_provision_reload(int reload)
Definition: provision.c:529
#define IAX_TRANSFERMEDIA
Definition: chan_iax2.c:475
static char version[AST_MAX_EXTENSION]
Definition: chan_ooh323.c:391
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:448
#define CLI_FAILURE
Definition: cli.h:46
static int addr_range_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:2445
void stasis_subscription_cb_noop(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Stasis subscription callback function that does nothing.
Definition: stasis.c:811
char * calling_name
Definition: parser.h:31
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
Parses an IAX dial string into its component parts.
Definition: chan_iax2.c:5035
#define DEFAULT_MAXMS
Definition: chan_iax2.c:390
static void __iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12317
#define AST_MAX_CONTEXT
Definition: channel.h:136
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
Definition: main/utils.c:782
int retries
Definition: parser.h:107
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data)
Definition: chan_iax2.c:1687
#define AST_CAUSE_UNREGISTERED
Definition: causes.h:153
static const char name[]
Definition: cdr_mysql.c:74
struct iax2_trunk_peer::@115 list
#define IAX_IE_RR_OOO
Definition: iax2.h:182
unsigned int authmethods
Definition: parser.h:46
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
Definition: linkedlists.h:625
#define ast_free(a)
Definition: astmm.h:182
char * command
Definition: cli.h:186
int datalen
Definition: parser.h:105
unsigned char calltoken
Definition: parser.h:83
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
static unsigned char compress_subclass(iax2_format subclass)
Definition: chan_iax2.c:1813
int iax_firmware_append(struct iax_ie_data *ied, const char *dev, unsigned int desc)
Definition: firmware.c:283
AES_KEY ast_aes_decrypt_key
Definition: crypto.h:36
#define AST_OPTION_SECURE_SIGNALING
static int user_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:1985
struct ast_var_t::@249 entries
#define AST_CHANNEL_NAME
Definition: channel.h:172
static void cleanup_thread_list(void *head)
Definition: chan_iax2.c:14581
struct ast_endpoint * endpoint
Definition: chan_iax2.c:590
unsigned int ast_format_get_default_ms(const struct ast_format *format)
Get the default framing size (in milliseconds) for a format.
Definition: format.c:359
unsigned char iseqno
Definition: iax2.h:233
#define AST_OPTION_AUDIO_MODE
#define ast_var_assign(name, value)
Definition: chanvars.h:40
int ast_str2cos(const char *value, unsigned int *cos)
Convert a string to the appropriate COS value.
Definition: acl.c:953
#define IAX_IE_CODEC_PREFS
Definition: iax2.h:175
int ast_format_cap_identical(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2)
Determine if two capabilities structures are identical.
Definition: format_cap.c:689
int ast_register_switch(struct ast_switch *sw)
Register an alternative dialplan switch.
Definition: pbx_switch.c:58
static int set_config(const char *config_file, int reload, int forced)
Load configuration.
Definition: chan_iax2.c:13476
int retrytime
Definition: parser.h:111
void ast_hangup(struct ast_channel *chan)
Hang up a channel.
Definition: channel.c:2548
static int randomcalltokendata
Definition: chan_iax2.c:936
struct ast_sockaddr addr
Definition: chan_iax2.c:1091
unsigned char * trunkdata
Definition: chan_iax2.c:605
#define CALLNO_TO_PTR(a)
Definition: chan_iax2.c:289
static struct ast_channel * iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
Definition: chan_iax2.c:12458
static int socket_process_helper(struct iax2_thread *thread)
Definition: chan_iax2.c:10083
static void insert_idle_thread(struct iax2_thread *thread)
Definition: chan_iax2.c:1571
#define IAX_RTIGNOREREGEXPIRE
Definition: chan_iax2.c:473
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *result,...)
The argument parsing routine.
Definition: main/config.c:3657
int ast_write(struct ast_channel *chan, struct ast_frame *frame)
Write a frame to a channel This function writes the given frame to the indicated channel.
Definition: channel.c:5189
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
Definition: chan_iax2.c:6429
int maxms
Definition: chan_iax2.c:577
const char * word
Definition: cli.h:163
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7756
char hostname[]
Definition: chan_iax2.c:653
struct stasis_message_type * ast_mwi_state_type(void)
Get the Stasis Message Bus API message type for MWI messages.
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
Definition: stasis.c:1136
char * called_number
Definition: parser.h:28
iax2_format chosenformat
Definition: chan_iax2.c:745
#define PEERS_FORMAT
Definition: chan_iax2.c:6843
Module has failed to load, may be in an inconsistent state.
Definition: module.h:78
char callednum[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9534
static int cache_get_callno_locked(const char *data)
Definition: chan_iax2.c:14064
int ast_sockaddr_is_ipv4_mapped(const struct ast_sockaddr *addr)
Determine if this is an IPv4-mapped IPv6 address.
Definition: netsock2.c:507
static int get_auth_methods(const char *value)
Definition: chan_iax2.c:12657
struct ast_variable * vars
Definition: chan_iax2.c:529
#define DATASTORE_INHERIT_FOREVER
Definition: channel.h:193
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
Definition: chan_iax2.c:2905
#define IAX_IMMEDIATE
Definition: chan_iax2.c:479
#define IAX_NOTRANSFER
Definition: chan_iax2.c:457
char context[AST_MAX_EXTENSION]
Definition: chan_iax2.c:9533
#define ao2_find(container, arg, flags)
Definition: astobj2.h:1756
struct timeval trunkact
Definition: chan_iax2.c:602
ssize_t buf_len
Definition: chan_iax2.c:1077
const ast_string_field cid_num
Definition: chan_iax2.c:554
An API for managing task processing threads that can be shared across modules.
unsigned int inheritance
Definition: datastore.h:73
void(* schedfunc)(const void *)
Definition: chan_iax2.c:1065
int ast_db_get(const char *family, const char *key, char *value, int valuelen)
Get key value specified by family/key.
Definition: main/db.c:412
static int iaxthreadcount
Definition: chan_iax2.c:675
int tm_hour
Definition: localtime.h:38
int retrans
Definition: parser.h:129
int ast_timer_fd(const struct ast_timer *handle)
Get a poll()-able file descriptor for a timer.
Definition: timing.c:161
int ast_timer_set_rate(const struct ast_timer *handle, unsigned int rate)
Set the timing tick rate.
Definition: timing.c:166
int losscnt
Definition: chan_iax2.c:684
static int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
Definition: chan_iax2.c:9452
static int iax2_getpeertrunk(struct ast_sockaddr addr)
Definition: chan_iax2.c:5807
static struct iax2_dpcache * find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
Definition: chan_iax2.c:14137
int(* ast_sched_cb)(const void *data)
scheduler callback
Definition: sched.h:175
#define IAX_MAX_CALLS
Definition: iax2.h:37
static void __auto_congest(const void *nothing)
Definition: chan_iax2.c:4724
unsigned char buf[1024]
Definition: parser.h:149
#define IAX_IE_OSPTOKEN
Definition: iax2.h:184
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
Definition: sched.c:565
#define ast_set2_flag64(p, value, flag)
Definition: utils.h:151
int encmethods
Definition: parser.h:131
structure to hold users read from users.conf
#define ast_string_field_build(x, field, fmt, args...)
Set a field to a complex (built) value.
Definition: stringfields.h:550
static void * cleanup(void *unused)
Definition: pbx_realtime.c:124
static void reg_source_db(struct iax2_peer *p)
Definition: chan_iax2.c:8948
Structure used to handle boolean flags.
Definition: utils.h:199
static void * network_thread(void *ignore)
Definition: chan_iax2.c:12575
static int iax2_poke_noanswer(const void *data)
Definition: chan_iax2.c:12346
static int create_callno_pools(void)
Definition: chan_iax2.c:3021
static char * handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3914
struct iax_rr remote_rr
Definition: chan_iax2.c:875
ast_mutex_t init_lock
Definition: chan_iax2.c:1083
#define ast_clear_flag64(p, flag)
Definition: utils.h:134
struct chan_iax2_pvt::@117 dpentries
#define IAX_DPSTATUS_CANEXIST
Definition: iax2.h:216
#define ast_clear_flag(p, flag)
Definition: utils.h:77
#define IAX_CAPABILITY_MEDBANDWIDTH
Definition: chan_iax2.c:371
struct ast_party_redirecting * ast_channel_redirecting(struct ast_channel *chan)
Definition: md5.h:26
static char cid_name[AST_MAX_EXTENSION]
Definition: chan_mgcp.c:165
AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS|AST_MODFLAG_LOAD_ORDER, "HTTP Phone Provisioning",.support_level=AST_MODULE_SUPPORT_EXTENDED,.load=load_module,.unload=unload_module,.reload=reload,.load_pri=AST_MODPRI_CHANNEL_DEPEND,.requires="http",)
struct timeval delivery
static char * regstate2str(int regstate)
Definition: chan_iax2.c:7306
static int check_access(int callno, struct ast_sockaddr *addr, struct iax_ies *ies)
Definition: chan_iax2.c:7787
static struct ast_cli_entry cli_iax2[]
Definition: chan_iax2.c:14553
void ast_channel_callid_set(struct ast_channel *chan, ast_callid value)
char peercontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:1021
static void iax2_lock_owner(int callno)
Definition: chan_iax2.c:1335
struct ast_sockaddr addr
Definition: chan_iax2.c:981
unsigned short rr_delay
Definition: parser.h:77
static int user_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:1996
static int expire_registry(const void *data)
Definition: chan_iax2.c:8939
const ast_string_field context
Definition: chan_iax2.c:554
int pokefreqnotok
Definition: chan_iax2.c:580
int iax_ie_append_byte(struct iax_ie_data *ied, unsigned char ie, unsigned char dat)
Definition: parser.c:774
const char * usage
Definition: cli.h:177
static int send_packet(struct iax_frame *f)
Definition: chan_iax2.c:3402
static void network_change_stasis_unsubscribe(void)
Definition: chan_iax2.c:1465
void ast_channel_exten_set(struct ast_channel *chan, const char *value)
struct ast_format_cap * ast_channel_nativeformats(const struct ast_channel *chan)
size_t available
Definition: chan_iax2.c:911
static struct iax2_user * find_user(const char *name)
Definition: chan_iax2.c:2034
stasis_subscription_cb callback
Definition: stasis.c:689
int ast_get_ip_or_srv(struct ast_sockaddr *addr, const char *hostname, const char *service)
Get the IP address given a hostname and optional service.
Definition: acl.c:897
static int start_network_thread(void)
Definition: chan_iax2.c:12600
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name...
void ast_endpoint_blob_publish(struct ast_endpoint *endpoint, struct stasis_message_type *type, struct ast_json *blob)
Creates and publishes a ast_endpoint_blob message.
ast_cond_t init_cond
Definition: chan_iax2.c:1084
unsigned char encdata[0]
Definition: iax2.h:258
struct ast_sockaddr addr
Definition: chan_iax2.c:557
struct ast_frame ast_null_frame
Definition: main/frame.c:79
static char * handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Set trunk MTU from CLI.
Definition: chan_iax2.c:3960
ast_mutex_t lock
Definition: chan_iax2.c:1081
int iax_ie_append_str(struct iax_ie_data *ied, unsigned char ie, const char *str)
Definition: parser.c:769
#define IAX_IE_CALLINGTON
Definition: iax2.h:169
int tm_sec
Definition: localtime.h:36
int amaflags
Definition: chan_iax2.c:520
void ast_free_ha(struct ast_ha *ha)
Free a list of HAs.
Definition: acl.c:222
iax2_format capability
Definition: chan_iax2.c:571
#define IAX_IE_REFRESH
Definition: iax2.h:149
#define AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
Definition: callerid.h:332
unsigned char readbuf[4096]
Definition: chan_iax2.c:1075
#define EVENT_FLAG_REPORTING
Definition: manager.h:80
#define CLI_SUCCESS
Definition: cli.h:44
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
Definition: main/config.c:694
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2409
const ast_string_field secret
Definition: chan_iax2.c:554
char curfunc[80]
Definition: chan_iax2.c:1069
size_t ast_str_strlen(const struct ast_str *buf)
Returns the current length of the string stored within buf.
Definition: strings.h:688
static int get_from_jb(const void *p)
Definition: chan_iax2.c:4203
#define IAX_RTAUTOCLEAR
Definition: chan_iax2.c:472
struct ast_sockaddr addr
Definition: chan_iax2.c:731
char order[IAX2_CODEC_PREF_SIZE]
Definition: codec_pref.h:36
void * data
Definition: datastore.h:70
static ast_mutex_t callno_pool_lock
Definition: chan_iax2.c:915
static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
Definition: chan_iax2.c:9628
int transit_network_select
Transit Network Select.
Definition: channel.h:398
struct ast_netsock * ast_netsock_find(struct ast_netsock_list *list, struct ast_sockaddr *addr)
Definition: netsock.c:94
void iax_frame_wrap(struct iax_frame *fr, struct ast_frame *f)
Definition: parser.c:1185
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
Definition: linkedlists.h:680
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
Definition: chan_iax2.c:6476
struct iax2_thread::@123 ffinfo
const ast_string_field mohsuggest
Definition: chan_iax2.c:516
char hold_signaling
Definition: chan_iax2.c:887
int maxauthreq
Definition: chan_iax2.c:524
static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
Definition: chan_iax2.c:8568
char * strsep(char **str, const char *delims)
struct ast_variable * vars
Definition: parser.h:80
A ast_taskprocessor structure is a singleton by name.
Definition: taskprocessor.c:69
#define AST_CAUSE_NO_ROUTE_DESTINATION
Definition: causes.h:99
#define IAX_IE_CALLINGPRES
Definition: iax2.h:168
int ast_taskprocessor_push(struct ast_taskprocessor *tps, int(*task_exe)(void *datap), void *datap) attribute_warn_unused_result
Push a task into the specified taskprocessor queue and signal the taskprocessor thread.
#define AST_OPTION_FAX_DETECT
static struct stasis_subscription * acl_change_sub
Definition: chan_iax2.c:324
#define IAX_ALREADYGONE
Definition: chan_iax2.c:462
struct iax2_dpcache::@120 peer_list
#define ast_channel_ref(c)
Increase channel reference count.
Definition: channel.h:2970
void iax_firmware_traverse(const char *filter, int(*callback)(struct ast_iax2_firmware_header *header, void *data), void *data)
Definition: firmware.c:321
#define abs(x)
Definition: f2c.h:195
int ast_add_extension(const char *context, int replace, const char *extension, int priority, const char *label, const char *callerid, const char *application, void *data, void(*datad)(void *), const char *registrar)
Add and extension to an extension context.
Definition: pbx.c:6970
#define IAX_PROTO_VERSION
Definition: iax2.h:27
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition: astobj2.h:1841
static struct io_context * io
Definition: chan_iax2.c:411
static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
Definition: chan_iax2.c:8034
#define IAX_IE_RDNIS
Definition: iax2.h:158
#define ao2_cleanup(obj)
Definition: astobj2.h:1958
int ast_netsock_init(struct ast_netsock_list *list)
Definition: netsock.c:77
static int adsi
Definition: chan_iax2.c:432
Standard Command Line Interface.
iax2_format capability
Definition: chan_iax2.c:523
struct ast_acl_list * acl
Definition: chan_iax2.c:527
static void update_jbsched(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:4108
callno_type
Definition: chan_iax2.c:897
struct ast_sockaddr us
Definition: chan_iax2.c:649
int ast_channel_hangupcause(const struct ast_channel *chan)
int ast_sched_replace(int old_id, struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
replace a scheduler entry
Definition: sched.c:557
int musiconhold
Definition: parser.h:60
int ast_db_del(const char *family, const char *key)
Delete entry in astdb.
Definition: main/db.c:429
void ast_channel_context_set(struct ast_channel *chan, const char *value)
struct signaling_queue_entry * next
Definition: chan_iax2.c:894
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
static int iaxdefaulttimeout
Definition: chan_iax2.c:348
struct ast_sockaddr mask
Definition: chan_iax2.c:560
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
Add a rule to an ACL struct.
Definition: acl.c:430
static int authdebug
Definition: chan_iax2.c:341
int ast_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service)
Allocate and initialize a DNS manager entry.
Definition: dnsmgr.c:191
#define IAX_IE_USERNAME
Definition: iax2.h:136
int adsi
Definition: chan_iax2.c:561
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one...
Definition: strings.h:79
void * ast_taskprocessor_unreference(struct ast_taskprocessor *tps)
Unreference the specified taskprocessor and its reference count will decrement.
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
Definition: time.h:226
ast_app: A registered application
Definition: pbx_app.c:45
static void prune_peers(void)
Definition: chan_iax2.c:13444
const char * ast_channel_name(const struct ast_channel *chan)
unsigned char rseqno
Definition: chan_iax2.c:771
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
Definition: chan_iax2.c:3389
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is "false"...
Definition: main/utils.c:1968
#define IAX_IE_RR_DROPPED
Definition: iax2.h:181
const int pos
Definition: cli.h:164
int new_msgs
Definition: mwi.h:461
static char * handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:3640
int iax_provision_version(unsigned int *signature, const char *template, int force)
Definition: provision.c:258
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2399
char secret[80]
Definition: chan_iax2.c:643
char timezone[80]
Definition: chan_iax2.c:4599
int AST_OPTIONAL_API_NAME() ast_aes_set_encrypt_key(const unsigned char *key, ast_aes_encrypt_key *ctx)
Definition: res_crypto.c:466
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:2428
#define IAX_KEYPOPULATED
Definition: chan_iax2.c:466
enum jb_return_code jb_getinfo(jitterbuf *jb, jb_info *stats)
get jitterbuf info: only "statistics" may be valid
Definition: jitterbuf.c:815
int ast_setstate(struct ast_channel *chan, enum ast_channel_state)
Change the state of a channel.
Definition: channel.c:7486
Asterisk MWI API.
struct ast_channel * owner
Definition: chan_iax2.c:763
#define ast_frfree(fr)
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition: format.c:379
static struct iax2_peer * peer_ref(struct iax2_peer *peer)
Definition: chan_iax2.c:2022
#define AST_CALLID_BUFFER_LENGTH
Definition: logger.h:46
const ast_string_field mailbox
Definition: chan_iax2.c:554
struct ast_sockaddr apparent_addr
Definition: parser.h:51
unsigned int rr_pkts
Definition: parser.h:76
struct ast_sockaddr addr
Definition: chan_iax2.c:641
static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char *const argv[])
Definition: chan_iax2.c:6946
char cid_num[80]
Definition: chan_iax2.c:4600
const ast_string_field cid_name
Definition: chan_iax2.c:816
static int check_srcaddr(struct ast_sockaddr *addr)
Check if address can be used as packet source.
Definition: chan_iax2.c:12673
int iax_ie_append_addr(struct iax_ie_data *ied, unsigned char ie, const struct ast_sockaddr *addr)
Definition: parser.c:740
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int)
Definition: chan_iax2.c:7731
int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control, const void *data, size_t datalen)
Queue a control frame with payload.
Definition: channel.c:1238
static int apply_context(struct iax2_context *con, const char *context)
Definition: chan_iax2.c:7776
static void prune_users(void)
Definition: chan_iax2.c:13428
#define AST_CAUSE_BUSY
Definition: causes.h:148
#define DEFAULT_TRUNKDATA
Definition: chan_iax2.c:665
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
Definition: stasis.c:1025
struct ast_dnsmgr_entry * dnsmgr
Definition: chan_iax2.c:556
long min
Definition: jitterbuf.h:85
#define AST_OPTION_FLAG_REQUEST
struct stasis_forward * sub
Definition: res_corosync.c:240
#define IAX_IE_RR_PKTS
Definition: iax2.h:179
uint64_t iax2_format_compatibility_best(uint64_t formats)
Pick the best format from the given bitfield formats.
static char * handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:2836
Data structure associated with a single frame of data.
static void jb_warning_output(const char *fmt,...)
Definition: chan_iax2.c:1220
#define IAX_FLAG_FULL
Definition: iax2.h:40
struct iax2_codec_pref prefs
Definition: chan_iax2.c:733
#define IAX_IE_CAUSE
Definition: iax2.h:152
Internal Asterisk hangup causes.
static char regcontext[AST_MAX_CONTEXT]
Definition: chan_iax2.c:321
static int authenticate_request(int call_num)
Definition: chan_iax2.c:8055
static int auth_reject(const void *data)
Definition: chan_iax2.c:9302
#define IAX_MAXAUTHREQ
Definition: chan_iax2.c:476
static int total
Definition: res_adsi.c:968
static struct ast_str * hostname
Definition: cdr_mysql.c:77
void ast_channel_softhangup_internal_flag_add(struct ast_channel *chan, int value)
const char * ast_channel_language(const struct ast_channel *chan)
struct stasis_message * stasis_cache_get(struct stasis_cache *cache, struct stasis_message_type *type, const char *id)
Retrieve an item from the cache for the ast_eid_default entity.
Definition: stasis_cache.c:686
#define IAX_IE_RSA_RESULT
Definition: iax2.h:147
Abstract JSON element (object, array, string, int, ...).
unsigned int ospblocklength[IAX_MAX_OSPBLOCK_NUM]
Definition: parser.h:82
static void encmethods_to_str(int e, struct ast_str **buf)
Definition: chan_iax2.c:1750
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2451
static uint16_t global_maxcallno
Definition: chan_iax2.c:970
struct ast_key *AST_OPTIONAL_API_NAME() ast_key_get(const char *kname, int ktype)
return the ast_key structure for name
Definition: res_crypto.c:141
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
All frames other than that of type AST_FRAME_IAX must be held until we have received a destination ca...
Definition: chan_iax2.c:2171
char * password
Definition: parser.h:37
static int iax2_do_register_s(const void *data)
Definition: chan_iax2.c:8559
static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct ast_sockaddr *addr, struct chan_iax2_pvt *pvt)
Definition: chan_iax2.c:8351
#define AST_OPTION_TONE_VERIFY
int oseqno
Definition: parser.h:125
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
Check is see if a dnsmgr entry has changed.
Definition: dnsmgr.c:247
const ast_string_field cid_name
Definition: chan_iax2.c:554
static void stop_stuff(int callno)
Definition: chan_iax2.c:9277
char * calling_ani
Definition: parser.h:30
static int iax2_digit_begin(struct ast_channel *c, char digit)
Definition: chan_iax2.c:4316
struct ast_ha * ast_append_ha(const char *sense, const char *stuff, struct ast_ha *path, int *error)
Add a new rule to a list of HAs.
Definition: acl.c:713
Definition: search.h:40
const char * ast_channel_context(const struct ast_channel *chan)
int ast_db_put(const char *family, const char *key, const char *value)
Store value addressed by family/key.
Definition: main/db.c:327
int error(const char *format,...)
Definition: utils/frame.c:999
#define ast_frame_byteswap_be(fr)
#define IAX_IE_CALLED_CONTEXT
Definition: iax2.h:135
static int iax2_append_register(const char *hostname, const char *username, const char *secret, const char *porta)
Definition: chan_iax2.c:8782
#define IAX_AUTH_PLAINTEXT
Definition: iax2.h:195
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition: extconf.c:2298
#define ast_datastore_alloc(info, uid)
Definition: datastore.h:89
#define ast_set_flags_to64(p, flag, value)
Definition: utils.h:161
unsigned short zeros
Definition: iax2.h:269
union ast_frame::@263 data
static int pvt_hash_cb(const void *obj, const int flags)
Definition: chan_iax2.c:14699
#define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field)
Loops safely over (traverses) the entries in a list.
Definition: linkedlists.h:528
enum ast_frame_type frametype
#define IAX_ENCRYPT_AES128
Definition: iax2.h:199
static int __schedule_action(void(*func)(const void *data), const void *data, const char *funcname)
Definition: chan_iax2.c:1653
void ast_system_publish_registry(const char *channeltype, const char *username, const char *domain, const char *status, const char *cause)
Publish a channel driver outgoing registration message.
#define IAX_IE_APPARENT_ADDR
Definition: iax2.h:148
static struct ast_channel * ast_iax2_new(int callno, int state, iax2_format capability, struct iax2_codec_pref *prefs, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, unsigned int cachable)
Create new call, interface with the PBX core.
Definition: chan_iax2.c:5829
char context[AST_MAX_CONTEXT]
Definition: chan_iax2.c:4602
void iax_frame_free(struct iax_frame *fr)
Definition: parser.c:1285
static int iax2_hangup(struct ast_channel *c)
Definition: chan_iax2.c:5300
#define ast_mutex_init(pmutex)
Definition: lock.h:184
long jitter
Definition: jitterbuf.h:84
const ast_string_field parkinglot
Definition: chan_iax2.c:554
ast_aes_encrypt_key tdcx
Definition: chan_iax2.c:851
Generic container type.
#define ast_channel_trylock(chan)
Definition: channel.h:2947
static struct call_number_pool callno_pool
Definition: chan_iax2.c:918
static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
Definition: chan_iax2.c:3108
iax2_format svideoformat
Definition: chan_iax2.c:709
static int get_encrypt_methods(const char *s)
Definition: chan_iax2.c:1766
iax2_format capability
Definition: parser.h:38
unsigned char valid
TRUE if the name information is valid/present.
Definition: channel.h:280
static int attempt_transmit(const void *data)
Definition: chan_iax2.c:3631
int authmethods
Definition: chan_iax2.c:518
#define IAX_AUTH_MD5
Definition: iax2.h:196
void jb_destroy(jitterbuf *jb)
destroy jitterbuf
Definition: jitterbuf.c:99
static char context[AST_MAX_CONTEXT]
Definition: chan_alsa.c:116
Call Parking and Pickup API Includes code and algorithms from the Zapata library. ...
struct ast_flags * ast_channel_flags(struct ast_channel *chan)
Media Format Bitfield Compatibility API.
const ast_string_field dbsecret
Definition: chan_iax2.c:554
struct ast_format * ast_format_cap_get_format(const struct ast_format_cap *cap, int position)
Get the format at a specific index.
Definition: format_cap.c:400
int jitter
Definition: chan_iax2.c:682
#define ast_mutex_destroy(a)
Definition: lock.h:186
static int last_authmethod
Definition: chan_iax2.c:344
unsigned short callno
Definition: chan_iax2.c:737
#define IAX_SENDCONNECTEDLINE
Definition: chan_iax2.c:480
struct ast_context * ast_context_find_or_create(struct ast_context **extcontexts, struct ast_hashtab *exttable, const char *name, const char *registrar)
Register a new context or find an existing one.
Definition: pbx.c:6198
const ast_string_field cid_name
Definition: chan_iax2.c:516
#define AST_LIST_INSERT_BEFORE_CURRENT(elm, field)
Inserts a list entry before the current entry during a traversal.
Definition: linkedlists.h:598
struct ast_format * format
static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
Part of the IAX2 switch interface.
Definition: chan_iax2.c:14270
static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
Definition: chan_iax2.c:6027
unsigned short refresh
Definition: parser.h:52
int adsi
Definition: chan_iax2.c:521
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
Definition: chan_iax2.c:7477
static int iax2_prov_app(struct ast_channel *chan, const char *data)
Definition: chan_iax2.c:12249
static void _iax2_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct iax2_peer *peer)
Definition: chan_iax2.c:6845
const ast_string_field context
Definition: chan_iax2.c:816
static int peer_delme_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:13381
unsigned int lastsent
Definition: chan_iax2.c:715
#define IAX_MAX_SHIFT
Definition: iax2.h:46
#define IAX_IE_TRANSFERID
Definition: iax2.h:157
void ast_shrink_phone_number(char *n)
Shrink a phone number in place to just digits (more accurately it just removes ()&#39;s, .&#39;s, and -&#39;s...
Definition: callerid.c:947
char * cause
Definition: parser.h:55
struct timeval rxtrunktime
Definition: chan_iax2.c:600
The structure that contains MWI state.
Definition: mwi.h:457
static int iax2_key_rotate(const void *vpvt)
Definition: chan_iax2.c:5462
struct ast_app * pbx_findapp(const char *app)
Look up an application.
Definition: ael_main.c:165
#define MIN_REUSE_TIME
Definition: chan_iax2.c:299
#define ast_manager_register_xml(action, authority, func)
Register a manager callback using XML documentation to describe the manager.
Definition: manager.h:186
#define TRUNK_CALL_START
Definition: chan_iax2.c:1174
void ast_endpoint_shutdown(struct ast_endpoint *endpoint)
Shutsdown an ast_endpoint.
#define IAX_IE_FORMAT
Definition: iax2.h:139
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
#define AST_CAUSE_CALL_REJECTED
Definition: causes.h:110
static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
Definition: chan_iax2.c:9581
unsigned short dcallno
Definition: parser.h:101
const ast_string_field secret
Definition: chan_iax2.c:516
void iax2_codec_pref_convert(struct iax2_codec_pref *pref, char *buf, size_t size, int right)
Shift an audio codec preference list up or down 65 bytes so that it becomes an ASCII string...
Definition: codec_pref.c:44
Bridging API.
static struct ast_timer * timer
Definition: chan_iax2.c:360
#define RESULT_SUCCESS
Definition: cli.h:40
#define ast_channel_alloc(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag,...)
Create a channel structure.
Definition: channel.h:1259
static struct iax2_user * realtime_user(const char *username, struct ast_sockaddr *addr)
Definition: chan_iax2.c:4491
struct ast_format * ast_format_slin
Built-in cached signed linear 8kHz format.
Definition: format_cache.c:41
#define AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
Definition: causes.h:129
Asterisk module definitions.
const ast_string_field cid_num
Definition: chan_iax2.c:516
struct ast_format * ast_channel_writeformat(struct ast_channel *chan)
#define IAX_FLAG_RETRANS
Definition: iax2.h:42
struct ast_format * iax2_codec_pref_index(struct iax2_codec_pref *pref, int idx, struct ast_format **result)
Codec located at a particular place in the preference index.
Definition: codec_pref.c:77
static int iax2_queue_hold(int callno, const char *musicclass)
Queue a hold frame on the ast_channel owner.
Definition: chan_iax2.c:3276
static void peercnt_remove(struct peercnt *peercnt)
Definition: chan_iax2.c:2682
int AST_OPTIONAL_API_NAME() ast_aes_set_decrypt_key(const unsigned char *key, ast_aes_decrypt_key *ctx)
Definition: res_crypto.c:471
MD5 digest functions.
enum jb_return_code jb_getall(jitterbuf *jb, jb_frame *frameout)
unconditionally get frames from jitterbuf until empty
Definition: jitterbuf.c:801
struct ast_mwi_subscriber * ast_mwi_subscribe_pool(const char *mailbox, stasis_subscription_cb callback, void *data)
Add an MWI state subscriber, and stasis subscription to the mailbox.
Definition: mwi.c:230
int ast_format_cap_get_compatible(const struct ast_format_cap *cap1, const struct ast_format_cap *cap2, struct ast_format_cap *result)
Find the compatible formats between two capabilities structures.
Definition: format_cap.c:630
static snd_pcm_format_t format
Definition: chan_alsa.c:102
static int trunk_nmaxmtu
Definition: chan_iax2.c:314
static int global_rtautoclear
Definition: chan_iax2.c:484
enum calltoken_peer_enum calltoken_required
Definition: chan_iax2.c:588
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition: channel.c:2390
Persistant data storage (akin to *doze registry)
static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
Definition: chan_iax2.c:9612
void ast_channel_tech_pvt_set(struct ast_channel *chan, void *value)
int frames_received
Definition: chan_iax2.c:881
#define ast_string_field_free_memory(x)
free all memory - to be called before destroying the object
Definition: stringfields.h:368
iax_transfer_state
Definition: chan_iax2.c:626
Application convenience functions, designed to give consistent look and feel to Asterisk apps...
static struct ao2_container * callno_limits
Definition: chan_iax2.c:961
long current
Definition: jitterbuf.h:86
static char * handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7411
#define IAX_MAX_OSPBUFF_SIZE
Definition: iax2.h:193
static struct ast_switch iax2_switch
Definition: chan_iax2.c:14543
unsigned char valid
TRUE if the number information is valid/present.
Definition: channel.h:298
Endpoint abstractions.
unsigned char metacmd
Definition: iax2.h:263
static int peer_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:1973
const struct ast_channel_tech * ast_channel_tech(const struct ast_channel *chan)
void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
Sets the HANGUPCAUSE hash and optionally the SIP_CAUSE hash on the given channel. ...
Definition: channel.c:4391
struct ast_sockaddr transfer
Definition: chan_iax2.c:847
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
#define ast_cond_timedwait(cond, mutex, time)
Definition: lock.h:204
static struct ast_custom_function iaxvar_function
Definition: chan_iax2.c:10056
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
Definition: chan_iax2.c:6206
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2469
void ast_sched_context_destroy(struct ast_sched_context *c)
destroys a schedule context
Definition: sched.c:269
#define ast_custom_function_register(acf)
Register a custom function.
Definition: pbx.h:1508
#define ACN_FORMAT2
#define IAX_RTUPDATE
Definition: chan_iax2.c:471
static int iax2_do_register(struct iax2_registry *reg)
Definition: chan_iax2.c:12136
#define AST_CAUSE_CONGESTION
Definition: causes.h:152
void AST_OPTIONAL_API_NAME() ast_aes_decrypt(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *ctx)
Definition: res_crypto.c:481
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
Definition: netsock2.c:524
static void build_callno_limits(struct ast_variable *v)
Definition: chan_iax2.c:2740
#define IAX_IE_CAPABILITY
Definition: iax2.h:138
long max_contig_interp
Definition: jitterbuf.h:69
#define AST_KEY_PUBLIC
Definition: crypto.h:42
#define AST_BRIDGE_DTMF_CHANNEL_0
Report DTMF on channel 0.
Definition: channel.h:2382
struct iax2_thread::@122 list
Timing source management.
#define AST_MUTEX_DEFINE_STATIC(mutex)
Definition: lock.h:518
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
Definition: chan_iax2.c:1110
struct ast_sockaddr ioaddr
Definition: chan_iax2.c:1074
#define ast_register_application_xml(app, execute)
Register an application using XML documentation.
Definition: module.h:626
int waiters[256]
Definition: chan_iax2.c:1027
const ast_string_field peercontext
Definition: chan_iax2.c:554
int tm_min
Definition: localtime.h:37
Structure for mutex and tracking information.
Definition: lock.h:135
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
Definition: chan_iax2.c:2722
static int iax2_is_control_frame_allowed(int subtype)
Definition: chan_iax2.c:1359
#define RESULT_FAILURE
Definition: cli.h:42
static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
Definition: chan_iax2.c:6405
char * dnid
Definition: parser.h:44
int64_t iax2_format
Definition: iax2.h:222
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:2475
#define CALLTOKEN_IE_FORMAT
jack_status_t status
Definition: app_jack.c:146
unsigned int trunkdataalloc
Definition: chan_iax2.c:607
static iax2_format iax2_capability
Definition: chan_iax2.c:414
static int add_calltoken_ignore(const char *addr)
Definition: chan_iax2.c:2795
static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
Definition: chan_iax2.c:14724
uint64_t flags
Definition: chan_iax2.c:4588
int iseqno
Definition: parser.h:127
char * callerid
Definition: chan_iax2.c:9535
Media Format Cache API.
int iax_parse_ies(struct iax_ies *ies, unsigned char *data, int datalen)
Definition: parser.c:794
short word
int ast_app_inboxcount(const char *mailboxes, int *newmsgs, int *oldmsgs)
Determine number of new/old messages in a mailbox.
Definition: main/app.c:677
#define ast_mutex_unlock(a)
Definition: lock.h:188
struct iax2_codec_pref prefs
Definition: chan_iax2.c:555
struct ast_acl_list * acl
Definition: chan_iax2.c:587
int ast_sockaddr_resolve(struct ast_sockaddr **addrs, const char *str, int flags, int family)
Parses a string with an IPv4 or IPv6 address and place results into an array.
Definition: netsock2.c:280
struct ast_sockaddr defaddr
Definition: chan_iax2.c:565
unsigned int refresh
void ast_copy_ha(const struct ast_ha *from, struct ast_ha *to)
Copy the contents of one HA to another.
Definition: acl.c:255
unsigned int ts
Definition: iax2.h:231
static void peer_destructor(void *obj)
Definition: chan_iax2.c:12766
ast_bridge_result
Definition: channel.h:207
static force_inline int attribute_pure ast_str_hash(const char *str)
Compute a hash value on a string.
Definition: strings.h:1206
static void __expire_registry(const void *data)
Definition: chan_iax2.c:8898
#define IAX_DPSTATUS_EXISTS
Definition: iax2.h:215
void jb_reset(jitterbuf *jb)
reset jitterbuf
Definition: jitterbuf.c:72
unsigned int outoforder
Definition: parser.h:113
#define ACN_FORMAT1
#define ast_string_field_set(x, field, data)
Set a field to a simple string value.
Definition: stringfields.h:514
#define IAX_TEMPONLY
Definition: chan_iax2.c:455
static struct ao2_container * peercnts
Definition: chan_iax2.c:958
static int reload(void)
Definition: chan_iax2.c:14059
#define DEFAULT_FREQ_NOTOK
Definition: chan_iax2.c:392
size_t len
Definition: chan_iax2.c:1056
static int raw_hangup(struct ast_sockaddr *addr, unsigned short src, unsigned short dst, int sockfd)
Definition: chan_iax2.c:8018
void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
Send ack in manager transaction to begin a list.
Definition: manager.c:3201
static char * handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: chan_iax2.c:7218
static struct test_val a
struct ast_party_number number
Subscriber phone number.
Definition: channel.h:343
static int auth_fail(int callno, int failcode)
Definition: chan_iax2.c:9316
#define ast_test_flag64(p, flag)
Definition: utils.h:120
#define ast_module_ref(mod)
Hold a reference to the module.
Definition: module.h:443
#define ao2_link(container, obj)
Definition: astobj2.h:1549
struct io_context * io_context_create(void)
Creates a context Create a context for I/O operations Basically mallocs an IO structure and sets up s...
Definition: io.c:81