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