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