Asterisk - The Open Source Telephony Project  GIT-master-a1fa8df
chan_iax2.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*! \file
20  *
21  * \brief Implementation of Inter-Asterisk eXchange Version 2
22  * as specified in RFC 5456
23  *
24  * \author Mark Spencer <markster@digium.com>
25  *
26  * \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 */
806  AST_STRING_FIELD(host);
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) */
869  int amaflags;
871  /*! variables inherited from the user definition */
873  /*! variables transmitted in a NEW packet */
875  /*! last received remote rr */
876  struct iax_rr remote_rr;
877  /*! Current base time: (just for stats) */
878  int min;
879  /*! Dropped frame count: (just for stats) */
881  /*! received frame count: (just for stats) */
883  /*! Destroying this call initiated. */
885  /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
886  unsigned char calltoken_ie_len;
887  /*! hold all signaling frames from the pbx thread until we have a destination callno */
889  /*! frame queue for signaling frames from pbx thread waiting for destination callno */
891 };
892 
894  struct ast_frame f;
896 };
897 
901 };
902 
903 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
904 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
905 
906 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
907 #define CALLNO_ENTRY_IS_VALIDATED(a) ((a) & 0x8000)
908 #define CALLNO_ENTRY_GET_CALLNO(a) ((a) & 0x7FFF)
909 
911  size_t capacity;
912  size_t available;
913  callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
914 };
915 
917 
918 /*! table of available call numbers */
920 
921 /*! table of available trunk call numbers */
923 
924 /*!
925  * \brief a list of frames that may need to be retransmitted
926  *
927  * \note The contents of this list do not need to be explicitly destroyed
928  * on module unload. This is because all active calls are destroyed, and
929  * all frames in this queue will get destroyed as a part of that process.
930  *
931  * \note Contents protected by the iaxsl[] locks
932  */
934 
936 
938 
939 static time_t max_calltoken_delay = 10;
940 
941 /*!
942  * This module will get much higher performance when doing a lot of
943  * user and peer lookups if the number of buckets is increased from 1.
944  * However, to maintain old behavior for Asterisk 1.4, these are set to
945  * 1 by default. When using multiple buckets, search order through these
946  * containers is considered random, so you will not be able to depend on
947  * the order the entires are specified in iax.conf for matching order. */
948 #ifdef LOW_MEMORY
949 #define MAX_PEER_BUCKETS 17
950 #else
951 #define MAX_PEER_BUCKETS 563
952 #endif
953 static struct ao2_container *peers;
954 
955 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
956 static struct ao2_container *users;
957 
958 /*! Table containing peercnt objects for every ip address consuming a callno */
959 static struct ao2_container *peercnts;
960 
961 /*! Table containing custom callno limit rules for a range of ip addresses. */
963 
964 /*! Table containing ip addresses not requiring calltoken validation */
966 
967 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
968 
969 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
970 
971 static uint16_t global_maxcallno;
972 
973 /*! Total num of call numbers allowed to be allocated without calltoken validation */
974 static uint16_t global_maxcallno_nonval;
975 
976 static uint16_t total_nonval_callno_used = 0;
977 
978 /*! peer connection private, keeps track of all the call numbers
979  * consumed by a single ip address */
980 struct peercnt {
981  /*! ip address consuming call numbers */
982  struct ast_sockaddr addr;
983  /*! Number of call numbers currently used by this ip address */
984  uint16_t cur;
985  /*! Max call numbers allowed for this ip address */
986  uint16_t limit;
987  /*! Specifies whether limit is set by a registration or not, if so normal
988  * limit setting rules do not apply to this address. */
989  unsigned char reg;
990 };
991 
992 /*! used by both callno_limits and calltoken_ignores containers */
993 struct addr_range {
994  /*! ip address range for custom callno limit rule */
995  struct ast_ha ha;
996  /*! callno limit for this ip address range, only used in callno_limits container */
997  uint16_t limit;
998  /*! delete me marker for reloads */
999  unsigned char delme;
1000 };
1001 
1002 enum {
1003  /*! Extension exists */
1004  CACHE_FLAG_EXISTS = (1 << 0),
1005  /*! Extension is nonexistent */
1007  /*! Extension can exist */
1009  /*! Waiting to hear back response */
1011  /*! Timed out */
1013  /*! Request transmitted */
1015  /*! Timeout */
1017  /*! Matchmore */
1019 };
1020 
1022  char peercontext[AST_MAX_CONTEXT];
1024  struct timeval orig;
1025  struct timeval expiry;
1026  int flags;
1027  unsigned short callno;
1028  int waiters[256];
1030  AST_LIST_ENTRY(iax2_dpcache) peer_list;
1031 };
1032 
1034 
1035 static void reg_source_db(struct iax2_peer *p);
1036 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1037 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1038 
1039 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1040 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1041 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1042 
1048 };
1049 
1053 };
1054 
1057  size_t len;
1058  unsigned char buf[1];
1059 };
1060 
1061 struct iax2_thread {
1064  enum iax2_thread_iostate iostate;
1065 #ifdef SCHED_MULTITHREADED
1066  void (*schedfunc)(const void *);
1067  const void *scheddata;
1068 #endif
1069 #ifdef DEBUG_SCHED_MULTITHREAD
1070  char curfunc[80];
1071 #endif
1072  int actions;
1073  pthread_t threadid;
1075  struct ast_sockaddr ioaddr;
1076  unsigned char readbuf[4096];
1077  unsigned char *buf;
1078  ssize_t buf_len;
1079  size_t buf_size;
1080  int iofd;
1081  time_t checktime;
1086  /*! if this thread is processing a full frame,
1087  some information about that frame will be stored
1088  here, so we can avoid dispatching any more full
1089  frames for that callno to other threads */
1090  struct {
1091  unsigned short callno;
1092  struct ast_sockaddr addr;
1093  unsigned char type;
1094  unsigned char csub;
1095  } ffinfo;
1096  /*! Queued up full frames for processing. If more full frames arrive for
1097  * a call which this thread is already processing a full frame for, they
1098  * are queued up here. */
1100  unsigned char stop;
1101 };
1102 
1103 /* Thread lists */
1107 
1108 static void *iax2_process_thread(void *data);
1109 static void iax2_destroy(int callno);
1110 
1112 {
1113  ast_mutex_lock(lock);
1114  ast_cond_signal(cond);
1115  ast_mutex_unlock(lock);
1116 }
1117 
1118 /*!
1119  * \brief an array of iax2 pvt structures
1120  *
1121  * The container for active chan_iax2_pvt structures is implemented as an
1122  * array for extremely quick direct access to the correct pvt structure
1123  * based on the local call number. The local call number is used as the
1124  * index into the array where the associated pvt structure is stored.
1125  */
1127 
1128 static ast_callid iax_pvt_callid_get(int callno)
1129 {
1130  return iaxs[callno]->callid;
1131 }
1132 
1133 static void iax_pvt_callid_set(int callno, ast_callid callid)
1134 {
1135  iaxs[callno]->callid = callid;
1136 }
1137 
1138 static void iax_pvt_callid_new(int callno)
1139 {
1140  ast_callid callid = ast_create_callid();
1141  char buffer[AST_CALLID_BUFFER_LENGTH];
1142  ast_callid_strnprint(buffer, sizeof(buffer), callid);
1143  iax_pvt_callid_set(callno, callid);
1144 }
1145 
1146 /*!
1147  * \brief Another container of iax2_pvt structures
1148  *
1149  * Active IAX2 pvt structs are also stored in this container, if they are a part
1150  * of an active call where we know the remote side's call number. The reason
1151  * for this is that incoming media frames do not contain our call number. So,
1152  * instead of having to iterate the entire iaxs array, we use this container to
1153  * look up calls where the remote side is using a given call number.
1154  */
1156 
1157 /*!
1158  * \brief chan_iax2_pvt structure locks
1159  *
1160  * These locks are used when accessing a pvt structure in the iaxs array.
1161  * The index used here is the same as used in the iaxs array. It is the
1162  * local call number for the associated pvt struct.
1163  */
1165 
1166 /*!
1167  * * \brief Another container of iax2_pvt structures
1168  *
1169  * Active IAX2 pvt stucts used during transfering a call are stored here.
1170  */
1172 
1173 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
1174  but keeps the division between trunked and non-trunked better. */
1175 #define TRUNK_CALL_START (IAX_MAX_CALLS / 2)
1176 
1177 /* Debug routines... */
1178 static struct ast_sockaddr debugaddr;
1179 
1180 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1181 {
1182  if (iaxdebug ||
1183  (addr && !ast_sockaddr_isnull(&debugaddr) &&
1186  !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1187 
1188  if (iaxdebug) {
1189  iax_showframe(f, fhi, rx, addr, datalen);
1190  } else {
1191  iaxdebug = 1;
1192  iax_showframe(f, fhi, rx, addr, datalen);
1193  iaxdebug = 0;
1194  }
1195  }
1196 }
1197 
1198 static void iax_debug_output(const char *data)
1199 {
1200  if (iaxdebug)
1201  ast_verbose("%s", data);
1202 }
1203 
1204 static void iax_error_output(const char *data)
1205 {
1206  ast_log(LOG_WARNING, "%s", data);
1207 }
1208 
1209 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1210 {
1211  va_list args;
1212  char buf[1024];
1213 
1214  va_start(args, fmt);
1215  vsnprintf(buf, sizeof(buf), fmt, args);
1216  va_end(args);
1217 
1218  ast_log(LOG_ERROR, "%s", buf);
1219 }
1220 
1221 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1222 {
1223  va_list args;
1224  char buf[1024];
1225 
1226  va_start(args, fmt);
1227  vsnprintf(buf, sizeof(buf), fmt, args);
1228  va_end(args);
1229 
1230  ast_log(LOG_WARNING, "%s", buf);
1231 }
1232 
1233 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1234 {
1235  va_list args;
1236  char buf[1024];
1237 
1238  va_start(args, fmt);
1239  vsnprintf(buf, sizeof(buf), fmt, args);
1240  va_end(args);
1241 
1242  ast_verbose("%s", buf);
1243 }
1244 
1245 static int expire_registry(const void *data);
1246 static int iax2_answer(struct ast_channel *c);
1247 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1248 static int iax2_devicestate(const char *data);
1249 static int iax2_digit_begin(struct ast_channel *c, char digit);
1250 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1251 static int iax2_do_register(struct iax2_registry *reg);
1252 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1253 static int iax2_hangup(struct ast_channel *c);
1254 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1255 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1256 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1257 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1258 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1259 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1260 static int iax2_sendtext(struct ast_channel *c, const char *text);
1261 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1262 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1263 static int iax2_transfer(struct ast_channel *c, const char *dest);
1264 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1265 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1266 
1267 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1268 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1269 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1270 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1271 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1272 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1273 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);
1274 static struct ast_frame *iax2_read(struct ast_channel *c);
1275 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1276 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1277 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1278 static void *iax2_dup_variable_datastore(void *);
1279 static void prune_peers(void);
1280 static void prune_users(void);
1281 static void iax2_free_variable_datastore(void *);
1282 
1283 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1284 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1285 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1286 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1287 static void build_rand_pad(unsigned char *buf, ssize_t len);
1288 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1289 static int replace_callno(const void *obj);
1290 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1291 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1292 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1293 
1294 static struct ast_channel_tech iax2_tech = {
1295  .type = "IAX2",
1296  .description = tdesc,
1297  .properties = AST_CHAN_TP_WANTSJITTER,
1298  .requester = iax2_request,
1299  .devicestate = iax2_devicestate,
1300  .send_digit_begin = iax2_digit_begin,
1301  .send_digit_end = iax2_digit_end,
1302  .send_text = iax2_sendtext,
1303  .send_image = iax2_sendimage,
1304  .send_html = iax2_sendhtml,
1305  .call = iax2_call,
1306  .hangup = iax2_hangup,
1307  .answer = iax2_answer,
1308  .read = iax2_read,
1309  .write = iax2_write,
1310  .write_video = iax2_write,
1311  .indicate = iax2_indicate,
1312  .setoption = iax2_setoption,
1313  .queryoption = iax2_queryoption,
1314  .transfer = iax2_transfer,
1315  .fixup = iax2_fixup,
1316  .func_channel_read = acf_channel_read,
1317 };
1318 
1319 /*!
1320  * \internal
1321  * \brief Obtain the owner channel lock if the owner exists.
1322  *
1323  * \param callno IAX2 call id.
1324  *
1325  * \note Assumes the iaxsl[callno] lock is already obtained.
1326  *
1327  * \note
1328  * IMPORTANT NOTE!!! Any time this function is used, even if
1329  * iaxs[callno] was valid before calling it, it may no longer be
1330  * valid after calling it. This function may unlock and lock
1331  * the mutex associated with this callno, meaning that another
1332  * thread may grab it and destroy the call.
1333  *
1334  * \return Nothing
1335  */
1336 static void iax2_lock_owner(int callno)
1337 {
1338  for (;;) {
1339  if (!iaxs[callno] || !iaxs[callno]->owner) {
1340  /* There is no owner lock to get. */
1341  break;
1342  }
1343  if (!ast_channel_trylock(iaxs[callno]->owner)) {
1344  /* We got the lock */
1345  break;
1346  }
1347  /* Avoid deadlock by pausing and trying again */
1348  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1349  }
1350 }
1351 
1352 /*!
1353  * \internal
1354  * \brief Check if a control subtype is allowed on the wire.
1355  *
1356  * \param subtype Control frame subtype to check if allowed to/from the wire.
1357  *
1358  * \retval non-zero if allowed.
1359  */
1360 static int iax2_is_control_frame_allowed(int subtype)
1361 {
1362  enum ast_control_frame_type control = subtype;
1363  int is_allowed;
1364 
1365  /*
1366  * Note: If we compare the enumeration type, which does not have any
1367  * negative constants, the compiler may optimize this code away.
1368  * Therefore, we must perform an integer comparison here.
1369  */
1370  if (subtype == -1) {
1371  return -1;
1372  }
1373 
1374  /* Default to not allowing control frames to pass. */
1375  is_allowed = 0;
1376 
1377  /*
1378  * The switch default is not present in order to take advantage
1379  * of the compiler complaining of a missing enum case.
1380  */
1381  switch (control) {
1382  /*
1383  * These control frames make sense to send/receive across the link.
1384  */
1385  case AST_CONTROL_HANGUP:
1386  case AST_CONTROL_RING:
1387  case AST_CONTROL_RINGING:
1388  case AST_CONTROL_ANSWER:
1389  case AST_CONTROL_BUSY:
1391  case AST_CONTROL_OFFHOOK:
1393  case AST_CONTROL_FLASH:
1394  case AST_CONTROL_WINK:
1395  case AST_CONTROL_OPTION:
1396  case AST_CONTROL_RADIO_KEY:
1398  case AST_CONTROL_PROGRESS:
1400  case AST_CONTROL_HOLD:
1401  case AST_CONTROL_UNHOLD:
1402  case AST_CONTROL_VIDUPDATE:
1406  case AST_CONTROL_AOC:
1408  case AST_CONTROL_MCID:
1409  is_allowed = -1;
1410  break;
1411 
1412  /*
1413  * These control frames do not make sense to send/receive across the link.
1414  */
1415  case _XXX_AST_CONTROL_T38:
1416  /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1417  case AST_CONTROL_SRCUPDATE:
1418  /* Across an IAX link the source is still the same. */
1419  case AST_CONTROL_TRANSFER:
1420  /* A success/fail status report from calling ast_transfer() on this machine. */
1421  case AST_CONTROL_CC:
1422  /* The payload contains pointers that are valid for the sending machine only. */
1423  case AST_CONTROL_SRCCHANGE:
1424  /* Across an IAX link the source is still the same. */
1426  /* The action can only be done by the sending machine. */
1427  case AST_CONTROL_END_OF_Q:
1428  /* This frame would cause the call to unexpectedly hangup. */
1430  /* Only meaningful across a bridge on this machine for direct-media exchange. */
1432  /* Intended only for the sending machine's local channel structure. */
1434  /* Intended only for masquerades when calling ast_indicate_data(). */
1436  /* Intended only for internal stream topology manipulation. */
1438  /* Intended only for internal stream topology change notification. */
1445  /* None of these playback stream control frames should go across the link. */
1450  /* None of these media recording control frames should go across the link. */
1451  break;
1452  }
1453  return is_allowed;
1454 }
1455 
1457 {
1458  if (!network_change_sub) {
1459  network_change_sub = stasis_subscribe(ast_system_topic(),
1460  network_change_stasis_cb, NULL);
1463  }
1464 }
1465 
1467 {
1468  network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1469 }
1470 
1472 {
1473  if (!acl_change_sub) {
1474  acl_change_sub = stasis_subscribe(ast_security_topic(),
1475  acl_change_stasis_cb, NULL);
1478  }
1479 }
1480 
1482 {
1483  acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1484 }
1485 
1486 static int network_change_sched_cb(const void *data)
1487 {
1488  struct iax2_registry *reg;
1491  AST_LIST_TRAVERSE(&registrations, reg, entry) {
1492  iax2_do_register(reg);
1493  }
1495 
1496  return 0;
1497 }
1498 
1499 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1500  struct stasis_message *message)
1501 {
1502  /* This callback is only concerned with network change messages from the system topic. */
1503  if (stasis_message_type(message) != ast_network_change_type()) {
1504  return;
1505  }
1506 
1507  ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1508  if (network_change_sched_id == -1) {
1510  }
1511 }
1512 
1513 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1514  struct stasis_message *message)
1515 {
1516  if (stasis_message_type(message) != ast_named_acl_change_type()) {
1517  return;
1518  }
1519 
1520  ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1521  reload_config(1);
1522 }
1523 
1525  .type = "IAX2_VARIABLE",
1526  .duplicate = iax2_dup_variable_datastore,
1527  .destroy = iax2_free_variable_datastore,
1528 };
1529 
1530 static void *iax2_dup_variable_datastore(void *old)
1531 {
1532  AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1533  struct ast_var_t *oldvar, *newvar;
1534 
1535  newlist = ast_calloc(sizeof(*newlist), 1);
1536  if (!newlist) {
1537  ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1538  return NULL;
1539  }
1540 
1541  AST_LIST_HEAD_INIT(newlist);
1542  AST_LIST_LOCK(oldlist);
1543  AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1544  newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1545  if (newvar)
1546  AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1547  else
1548  ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1549  }
1550  AST_LIST_UNLOCK(oldlist);
1551  return newlist;
1552 }
1553 
1554 static void iax2_free_variable_datastore(void *old)
1555 {
1556  AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1557  struct ast_var_t *oldvar;
1558 
1559  AST_LIST_LOCK(oldlist);
1560  while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1561  ast_free(oldvar);
1562  }
1563  AST_LIST_UNLOCK(oldlist);
1564  AST_LIST_HEAD_DESTROY(oldlist);
1565  ast_free(oldlist);
1566 }
1567 
1568 
1569 /* WARNING: insert_idle_thread should only ever be called within the
1570  * context of an iax2_process_thread() thread.
1571  */
1573 {
1574  if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1576  AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1578  } else {
1580  AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1582  }
1583 
1584  return;
1585 }
1586 
1587 static struct iax2_thread *find_idle_thread(void)
1588 {
1589  struct iax2_thread *thread = NULL;
1590 
1591  /* Pop the head of the idle list off */
1593  thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1595 
1596  /* If we popped a thread off the idle list, just return it */
1597  if (thread) {
1598  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1599  return thread;
1600  }
1601 
1602  /* Pop the head of the dynamic list off */
1606 
1607  /* If we popped a thread off the dynamic list, just return it */
1608  if (thread) {
1609  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1610  return thread;
1611  }
1612 
1613  /* If we can't create a new dynamic thread for any reason, return no thread at all */
1614  if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1615  return NULL;
1616 
1617  /* Set default values */
1618  ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1619  thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1620  thread->type = IAX_THREAD_TYPE_DYNAMIC;
1621 
1622  /* Initialize lock and condition */
1623  ast_mutex_init(&thread->lock);
1624  ast_cond_init(&thread->cond, NULL);
1625  ast_mutex_init(&thread->init_lock);
1626  ast_cond_init(&thread->init_cond, NULL);
1627  ast_mutex_lock(&thread->init_lock);
1628 
1629  /* Create thread and send it on it's way */
1631  ast_cond_destroy(&thread->cond);
1632  ast_mutex_destroy(&thread->lock);
1633  ast_mutex_unlock(&thread->init_lock);
1634  ast_cond_destroy(&thread->init_cond);
1635  ast_mutex_destroy(&thread->init_lock);
1636  ast_free(thread);
1637  return NULL;
1638  }
1639 
1640  /* this thread is not processing a full frame (since it is idle),
1641  so ensure that the field for the full frame call number is empty */
1642  memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1643 
1644  /* Wait for the thread to be ready before returning it to the caller */
1645  ast_cond_wait(&thread->init_cond, &thread->init_lock);
1646 
1647  /* Done with init_lock */
1648  ast_mutex_unlock(&thread->init_lock);
1649 
1650  return thread;
1651 }
1652 
1653 #ifdef SCHED_MULTITHREADED
1654 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1655 {
1656  struct iax2_thread *thread;
1657  static time_t lasterror;
1658  time_t t;
1659 
1660  thread = find_idle_thread();
1661  if (thread != NULL) {
1662  thread->schedfunc = func;
1663  thread->scheddata = data;
1664  thread->iostate = IAX_IOSTATE_SCHEDREADY;
1665 #ifdef DEBUG_SCHED_MULTITHREAD
1666  ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1667 #endif
1668  signal_condition(&thread->lock, &thread->cond);
1669  return 0;
1670  }
1671  time(&t);
1672  if (t != lasterror) {
1673  lasterror = t;
1674  ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1675  }
1676 
1677  return -1;
1678 }
1679 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1680 #endif
1681 
1682 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1683  ast_sched_cb callback, const void *data)
1684 {
1685  return ast_sched_replace(id, con, when, callback, data);
1686 }
1687 
1688 static int iax2_sched_add(struct ast_sched_context *con, int when,
1689  ast_sched_cb callback, const void *data)
1690 {
1691  return ast_sched_add(con, when, callback, data);
1692 }
1693 
1694 /*
1695  * \brief Acquire the iaxsl[callno] if call exists and not having ongoing hangup.
1696  * \param callno Call number to lock.
1697  * \return 0 If call disappeared or has ongoing hangup procedure. 1 If call found and mutex is locked.
1698  */
1700 {
1701  ast_mutex_lock(&iaxsl[callno]);
1702 
1703  /* We acquired the lock; but the call was already destroyed (we came after full hang up procedures)
1704  * or destroy initiated (in middle of hang up procedure. */
1705  if (!iaxs[callno] || iaxs[callno]->destroy_initiated) {
1706  ast_debug(3, "I wanted to lock callno %d, but it is dead or going to die.\n", callno);
1707  ast_mutex_unlock(&iaxsl[callno]);
1708  return 0;
1709  }
1710 
1711  /* Lock acquired, and callno is alive and kicking. */
1712  return 1;
1713 }
1714 
1715 static int send_ping(const void *data);
1716 
1717 static void __send_ping(const void *data)
1718 {
1719  int callno = PTR_TO_CALLNO(data);
1720 
1721  if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1722  ast_debug(3, "Hangup initiated on call %d, aborting __send_ping\n", callno);
1723  return;
1724  }
1725 
1726  /* Mark pingid as invalid scheduler id. */
1727  iaxs[callno]->pingid = -1;
1728 
1729  /* callno is now locked. */
1730  if (iaxs[callno]->peercallno) {
1731  /* Send PING packet. */
1732  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1733 
1734  /* Schedule sending next ping. */
1735  iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1736  }
1737 
1738  ast_mutex_unlock(&iaxsl[callno]);
1739 }
1740 
1741 static int send_ping(const void *data)
1742 {
1743 #ifdef SCHED_MULTITHREADED
1744  if (schedule_action(__send_ping, data))
1745 #endif
1746  __send_ping(data);
1747 
1748  return 0;
1749 }
1750 
1751 static void encmethods_to_str(int e, struct ast_str **buf)
1752 {
1753  ast_str_set(buf, 0, "(");
1754  if (e & IAX_ENCRYPT_AES128) {
1755  ast_str_append(buf, 0, "aes128");
1756  }
1757  if (e & IAX_ENCRYPT_KEYROTATE) {
1758  ast_str_append(buf, 0, ",keyrotate");
1759  }
1760  if (ast_str_strlen(*buf) > 1) {
1761  ast_str_append(buf, 0, ")");
1762  } else {
1763  ast_str_set(buf, 0, "No");
1764  }
1765 }
1766 
1767 static int get_encrypt_methods(const char *s)
1768 {
1769  int e;
1770  if (!strcasecmp(s, "aes128"))
1772  else if (ast_true(s))
1774  else
1775  e = 0;
1776  return e;
1777 }
1778 
1779 static int send_lagrq(const void *data);
1780 
1781 static void __send_lagrq(const void *data)
1782 {
1783  int callno = PTR_TO_CALLNO(data);
1784 
1785  if (iax2_lock_callno_unless_destroyed(callno) == 0) {
1786  ast_debug(3, "Hangup initiated on call %d, aborting __send_lagrq\n", callno);
1787  return;
1788  }
1789 
1790  /* Mark lagid as invalid scheduler id. */
1791  iaxs[callno]->lagid = -1;
1792 
1793  /* callno is now locked. */
1794  if (iaxs[callno]->peercallno) {
1795  /* Send LAGRQ packet. */
1796  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1797 
1798  /* Schedule sending next lagrq. */
1799  iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1800  }
1801 
1802  ast_mutex_unlock(&iaxsl[callno]);
1803 }
1804 
1805 static int send_lagrq(const void *data)
1806 {
1807 #ifdef SCHED_MULTITHREADED
1808  if (schedule_action(__send_lagrq, data))
1809 #endif
1810  __send_lagrq(data);
1811  return 0;
1812 }
1813 
1814 static unsigned char compress_subclass(iax2_format subclass)
1815 {
1816  int x;
1817  int power=-1;
1818  /* If it's 64 or smaller, just return it */
1819  if (subclass < IAX_FLAG_SC_LOG)
1820  return subclass;
1821  /* Otherwise find its power */
1822  for (x = 0; x < IAX_MAX_SHIFT; x++) {
1823  if (subclass & (1LL << x)) {
1824  if (power > -1) {
1825  ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1826  return 0;
1827  } else
1828  power = x;
1829  }
1830  }
1831  return power | IAX_FLAG_SC_LOG;
1832 }
1833 
1834 static iax2_format uncompress_subclass(unsigned char csub)
1835 {
1836  /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1837  if (csub & IAX_FLAG_SC_LOG) {
1838  /* special case for 'compressed' -1 */
1839  if (csub == 0xff)
1840  return -1;
1841  else
1842  return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1843  }
1844  else
1845  return csub;
1846 }
1847 
1848 static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1849 {
1850  int x;
1851  struct ast_format *found_format = NULL;
1852 
1853  for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1854  struct ast_format *pref_format;
1855  uint64_t pref_bitfield;
1856 
1857  pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1858  if (!pref_bitfield) {
1859  break;
1860  }
1861 
1862  pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1863  if (!pref_format) {
1864  /* The bitfield is not associated with any format. */
1865  continue;
1866  }
1867  found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1868  if (found_format) {
1869  break;
1870  }
1871  }
1872 
1873  if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1874  return found_format;
1875  }
1876 
1877  ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1878  ao2_cleanup(found_format);
1879  return NULL;
1880 }
1881 
1883 {
1884  struct ast_format_cap *cap;
1885  struct ast_format *tmpfmt;
1886  iax2_format format = 0;
1887 
1890  tmpfmt = codec_choose_from_prefs(pref, cap);
1891  if (!tmpfmt) {
1892  ao2_ref(cap, -1);
1893  return 0;
1894  }
1895 
1897  ao2_ref(tmpfmt, -1);
1898  ao2_ref(cap, -1);
1899  }
1900 
1901  return format;
1902 }
1903 
1905 {
1906  struct ast_format *tmpfmt;
1907 
1909  if (!tmpfmt) {
1910  return "Unknown";
1911  }
1912 
1913  return ast_format_get_name(tmpfmt);
1914 }
1915 
1916 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1917 {
1919 
1920  if (!cap) {
1921  return "(Nothing)";
1922  }
1924  ast_format_cap_get_names(cap, codec_buf);
1925  ao2_ref(cap, -1);
1926 
1927  return ast_str_buffer(*codec_buf);
1928 }
1929 
1930 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1931 {
1932  int res, i;
1933  struct ast_format_cap *cap;
1934 
1935  /* We want to add the formats to the cap in the preferred order */
1937  if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1938  ao2_cleanup(cap);
1939  return 1;
1940  }
1941 
1942  res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1943 
1944  /* Adjust formats bitfield and pref list to match. */
1946  iax2_codec_pref_remove_missing(pref, *formats);
1947 
1948  for (i = 0; i < ast_format_cap_count(cap); i++) {
1949  struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1950 
1952  ao2_ref(fmt, -1);
1953  }
1954 
1955  ao2_ref(cap, -1);
1956 
1957  return res;
1958 }
1959 
1960 /*!
1961  * \note The only member of the peer passed here guaranteed to be set is the name field
1962  */
1963 static int peer_hash_cb(const void *obj, const int flags)
1964 {
1965  const struct iax2_peer *peer = obj;
1966  const char *name = obj;
1967 
1968  return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1969 }
1970 
1971 /*!
1972  * \note The only member of the peer passed here guaranteed to be set is the name field
1973  */
1974 static int peer_cmp_cb(void *obj, void *arg, int flags)
1975 {
1976  struct iax2_peer *peer = obj, *peer2 = arg;
1977  const char *name = arg;
1978 
1979  return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1980  CMP_MATCH | CMP_STOP : 0;
1981 }
1982 
1983 /*!
1984  * \note The only member of the user passed here guaranteed to be set is the name field
1985  */
1986 static int user_hash_cb(const void *obj, const int flags)
1987 {
1988  const struct iax2_user *user = obj;
1989  const char *name = obj;
1990 
1991  return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1992 }
1993 
1994 /*!
1995  * \note The only member of the user passed here guaranteed to be set is the name field
1996  */
1997 static int user_cmp_cb(void *obj, void *arg, int flags)
1998 {
1999  struct iax2_user *user = obj, *user2 = arg;
2000  const char *name = arg;
2001 
2002  return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
2003  CMP_MATCH | CMP_STOP : 0;
2004 }
2005 
2006 /*!
2007  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
2008  * so do not call it with a pvt lock held.
2009  */
2010 static struct iax2_peer *find_peer(const char *name, int realtime)
2011 {
2012  struct iax2_peer *peer = NULL;
2013 
2014  peer = ao2_find(peers, name, OBJ_KEY);
2015 
2016  /* Now go for realtime if applicable */
2017  if (!peer && realtime) {
2018  peer = realtime_peer(name, NULL);
2019  }
2020  return peer;
2021 }
2022 
2023 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2024 {
2025  ao2_ref(peer, +1);
2026  return peer;
2027 }
2028 
2029 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2030 {
2031  ao2_ref(peer, -1);
2032  return NULL;
2033 }
2034 
2035 static struct iax2_user *find_user(const char *name)
2036 {
2037  return ao2_find(users, name, OBJ_KEY);
2038 }
2039 
2040 static inline struct iax2_user *user_unref(struct iax2_user *user)
2041 {
2042  ao2_ref(user, -1);
2043  return NULL;
2044 }
2045 
2046 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2047 {
2048  struct iax2_peer *peer = NULL;
2049  int res = 0;
2050  struct ao2_iterator i;
2051 
2052  i = ao2_iterator_init(peers, 0);
2053  while ((peer = ao2_iterator_next(&i))) {
2054 
2055  if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2056  ast_copy_string(host, peer->name, len);
2057  peer_unref(peer);
2058  res = 1;
2059  break;
2060  }
2061  peer_unref(peer);
2062  }
2064 
2065  if (!peer) {
2066  peer = realtime_peer(NULL, &addr);
2067  if (peer) {
2068  ast_copy_string(host, peer->name, len);
2069  peer_unref(peer);
2070  res = 1;
2071  }
2072  }
2073 
2074  return res;
2075 }
2076 
2077 /* Call AST_SCHED_DEL on a scheduled task if it is found in scheduler. */
2078 static int iax2_delete_from_sched(const void* data)
2079 {
2080  int sched_id = (int)(long)data;
2081 
2082  AST_SCHED_DEL(sched, sched_id);
2083 
2084  return 0;
2085 }
2086 
2087 /*!\note Assumes the lock on the pvt is already held, when
2088  * iax2_destroy_helper() is called. */
2089 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2090 {
2091  /* Decrement AUTHREQ count if needed */
2092  if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2093  struct iax2_user *user;
2094 
2095  user = ao2_find(users, pvt->username, OBJ_KEY);
2096  if (user) {
2097  ast_atomic_fetchadd_int(&user->curauthreq, -1);
2098  user_unref(user);
2099  }
2100 
2102  }
2103 
2104 
2105  /* Mark call destroy initiated flag. */
2106  pvt->destroy_initiated = 1;
2107 
2108  /*
2109  * Schedule deleting the scheduled (but didn't run yet) PINGs or LAGRQs.
2110  * Already running tasks will be terminated because of destroy_initiated.
2111  *
2112  * Don't call AST_SCHED_DEL from this thread for pingid and lagid because
2113  * it leads to a deadlock between the scheduler thread callback locking
2114  * the callno mutex and this thread which holds the callno mutex one or
2115  * more times. It is better to have another thread delete the scheduled
2116  * callbacks which doesn't lock the callno mutex.
2117  */
2118  iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->pingid);
2119  iax2_sched_add(sched, 0, iax2_delete_from_sched, (void*)(long)pvt->lagid);
2120 
2121  pvt->pingid = -1;
2122  pvt->lagid = -1;
2123 
2124  AST_SCHED_DEL(sched, pvt->autoid);
2125  AST_SCHED_DEL(sched, pvt->authid);
2126  AST_SCHED_DEL(sched, pvt->initid);
2127  AST_SCHED_DEL(sched, pvt->jbid);
2128  AST_SCHED_DEL(sched, pvt->keyrotateid);
2129 }
2130 
2131 static void iax2_frame_free(struct iax_frame *fr)
2132 {
2133  AST_SCHED_DEL(sched, fr->retrans);
2134  iax_frame_free(fr);
2135 }
2136 
2137 static int scheduled_destroy(const void *vid)
2138 {
2139  unsigned short callno = PTR_TO_CALLNO(vid);
2140  ast_mutex_lock(&iaxsl[callno]);
2141  if (iaxs[callno]) {
2142  ast_debug(1, "Really destroying %d now...\n", callno);
2143  iax2_destroy(callno);
2144  }
2145  ast_mutex_unlock(&iaxsl[callno]);
2146  return 0;
2147 }
2148 
2150 {
2151  if (s->f.datalen) {
2152  ast_free(s->f.data.ptr);
2153  }
2154  ast_free(s);
2155 }
2156 
2157 /*! \brief This function must be called once we are sure the other side has
2158  * given us a call number. All signaling is held here until that point. */
2159 static void send_signaling(struct chan_iax2_pvt *pvt)
2160 {
2161  struct signaling_queue_entry *s = NULL;
2162 
2163  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2164  iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2166  }
2167  pvt->hold_signaling = 0;
2168 }
2169 
2170 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2171  * we have received a destination call number. */
2172 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2173 {
2174  struct signaling_queue_entry *qe;
2175 
2176  if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2177  return 1; /* do not queue this frame */
2178  } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2179  return -1; /* out of memory */
2180  }
2181 
2182  /* copy ast_frame into our queue entry */
2183  qe->f = *f;
2184  if (qe->f.datalen) {
2185  /* if there is data in this frame copy it over as well */
2186  if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2188  return -1;
2189  }
2190  memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2191  }
2193 
2194  return 0;
2195 }
2196 
2197 static void pvt_destructor(void *obj)
2198 {
2199  struct chan_iax2_pvt *pvt = obj;
2200  struct iax_frame *cur = NULL;
2201  struct signaling_queue_entry *s = NULL;
2202 
2203  ast_mutex_lock(&iaxsl[pvt->callno]);
2204 
2205  iax2_destroy_helper(pvt);
2206 
2207  sched_delay_remove(&pvt->addr, pvt->callno_entry);
2208  pvt->callno_entry = 0;
2209 
2210  /* Already gone */
2212 
2213  AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2214  /* Cancel any pending transmissions */
2215  cur->retries = -1;
2216  }
2217 
2218  ast_mutex_unlock(&iaxsl[pvt->callno]);
2219 
2220  while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2222  }
2223 
2224  if (pvt->reg) {
2225  pvt->reg->callno = 0;
2226  }
2227 
2228  if (!pvt->owner) {
2229  jb_frame frame;
2230  if (pvt->vars) {
2232  pvt->vars = NULL;
2233  }
2234 
2235  while (jb_getall(pvt->jb, &frame) == JB_OK) {
2236  iax2_frame_free(frame.data);
2237  }
2238 
2239  jb_destroy(pvt->jb);
2241  }
2242 }
2243 
2244 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2245 {
2246  struct chan_iax2_pvt *tmp;
2247  jb_conf jbconf;
2248 
2249  if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2250  return NULL;
2251  }
2252 
2253  tmp->pingid = -1;
2254  tmp->lagid = -1;
2255  tmp->autoid = -1;
2256  tmp->authid = -1;
2257  tmp->initid = -1;
2258  tmp->keyrotateid = -1;
2259  tmp->jbid = -1;
2260 
2261  if (ast_string_field_init(tmp, 32)) {
2262  ao2_ref(tmp, -1);
2263  tmp = NULL;
2264  return NULL;
2265  }
2266 
2267  tmp->prefs = prefs_global;
2268 
2269  ast_string_field_set(tmp,exten, "s");
2270  ast_string_field_set(tmp,host, host);
2271 
2272  tmp->jb = jb_new();
2273  jbconf.max_jitterbuf = maxjitterbuffer;
2277  jb_setconf(tmp->jb,&jbconf);
2278 
2280 
2281  tmp->hold_signaling = 1;
2283 
2284  return tmp;
2285 }
2286 
2287 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2288 {
2289  struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2290  if (new) {
2291  size_t afdatalen = new->afdatalen;
2292  memcpy(new, fr, sizeof(*new));
2293  iax_frame_wrap(new, &fr->af);
2294  new->afdatalen = afdatalen;
2295  new->data = NULL;
2296  new->datalen = 0;
2297  new->direction = DIRECTION_INGRESS;
2298  new->retrans = -1;
2299  }
2300  return new;
2301 }
2302 /* keep these defined in this order. They are used in find_callno to
2303  * determine whether or not a new call number should be allowed. */
2304 enum {
2305  /* do not allow a new call number, only search ones in use for match */
2307  /* search for match first, then allow a new one to be allocated */
2309  /* do not search for match, force a new call number */
2311  /* do not search for match, force a new call number. Signifies call number
2312  * has been calltoken validated */
2314 };
2315 
2316 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2317 {
2318  if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2319  /* This is the main host */
2320  if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2321  (check_dcallno ? dcallno == cur->callno : 1) ) {
2322  /* That's us. Be sure we keep track of the peer call number */
2323  return 1;
2324  }
2325  }
2326  if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2327  /* We're transferring */
2328  if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2329  return 1;
2330  }
2331  return 0;
2332 }
2333 
2334 static int make_trunk(unsigned short callno, int locked)
2335 {
2336  int x;
2337  int res= 0;
2338  callno_entry entry;
2339  if (iaxs[callno]->oseqno) {
2340  ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2341  return -1;
2342  }
2343  if (callno >= TRUNK_CALL_START) {
2344  ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2345  return -1;
2346  }
2347 
2348  if (get_unused_callno(
2350  CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2351  &entry)) {
2352  ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2353  return -1;
2354  }
2355 
2356  x = CALLNO_ENTRY_GET_CALLNO(entry);
2357  ast_mutex_lock(&iaxsl[x]);
2358 
2359  /*!
2360  * \note We delete these before switching the slot, because if
2361  * they fire in the meantime, they will generate a warning.
2362  */
2363  AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2364  AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2365  iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2366  iaxs[x] = iaxs[callno];
2367  iaxs[x]->callno = x;
2368 
2369  /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2370  * before assigning the new one */
2371  if (iaxs[x]->callno_entry) {
2373  sched,
2374  MIN_REUSE_TIME * 1000,
2375  replace_callno,
2376  CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2377 
2378  }
2379  iaxs[x]->callno_entry = entry;
2380 
2381  iaxs[callno] = NULL;
2382  /* Update the two timers that should have been started */
2383  iaxs[x]->pingid = iax2_sched_add(sched,
2384  ping_time * 1000, send_ping, (void *)(long)x);
2385  iaxs[x]->lagid = iax2_sched_add(sched,
2386  lagrq_time * 1000, send_lagrq, (void *)(long)x);
2387 
2388  if (locked)
2389  ast_mutex_unlock(&iaxsl[callno]);
2390  res = x;
2391  if (!locked)
2392  ast_mutex_unlock(&iaxsl[x]);
2393 
2394  /* We moved this call from a non-trunked to a trunked call */
2395  ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2396 
2397  return res;
2398 }
2399 
2400 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2401 {
2402  if (!pvt->transfercallno) {
2403  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2404  return;
2405  }
2406 
2407  ao2_link(iax_transfercallno_pvts, pvt);
2408 }
2409 
2410 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2411 {
2412  if (!pvt->transfercallno) {
2413  ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2414  return;
2415  }
2416 
2417  ao2_unlink(iax_transfercallno_pvts, pvt);
2418 }
2419 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2420 {
2421  if (!pvt->peercallno) {
2422  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2423  return;
2424  }
2425 
2426  ao2_link(iax_peercallno_pvts, pvt);
2427 }
2428 
2429 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2430 {
2431  if (!pvt->peercallno) {
2432  ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2433  return;
2434  }
2435 
2436  ao2_unlink(iax_peercallno_pvts, pvt);
2437 }
2438 
2439 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2440 {
2441  struct addr_range *lim = obj;
2442  lim->delme = 1;
2443  return 0;
2444 }
2445 
2446 static int addr_range_hash_cb(const void *obj, const int flags)
2447 {
2448  const struct addr_range *lim = obj;
2449  return abs(ast_sockaddr_hash(&lim->ha.addr));
2450 }
2451 
2452 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2453 {
2454  struct addr_range *lim1 = obj, *lim2 = arg;
2455  return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2456  !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2457  CMP_MATCH | CMP_STOP : 0;
2458 }
2459 
2460 static int peercnt_hash_cb(const void *obj, const int flags)
2461 {
2462  const struct peercnt *peercnt = obj;
2463 
2464  if (ast_sockaddr_isnull(&peercnt->addr)) {
2465  return 0;
2466  }
2467  return ast_sockaddr_hash(&peercnt->addr);
2468 }
2469 
2470 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2471 {
2472  struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2473  return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2474 }
2475 
2476 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2477 {
2478  struct addr_range *addr_range = obj;
2479  struct ast_sockaddr *addr = arg;
2480  struct ast_sockaddr tmp_addr;
2481 
2482  ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2483 
2484  if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2485  return CMP_MATCH | CMP_STOP;
2486  }
2487  return 0;
2488 }
2489 
2490 /*!
2491  * \internal
2492  *
2493  * \brief compares addr to calltoken_ignores table to determine if validation is required.
2494  */
2495 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2496 {
2497  struct addr_range *addr_range;
2498  struct iax2_peer *peer = NULL;
2499  struct iax2_user *user = NULL;
2500  /* if no username is given, check for guest accounts */
2501  const char *find = S_OR(name, "guest");
2502  int res = 1; /* required by default */
2503  int optional = 0;
2505  /* There are only two cases in which calltoken validation is not required.
2506  * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2507  * the peer definition has not set the requirecalltoken option.
2508  * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2509  */
2510 
2511  /* ----- Case 1 ----- */
2512  if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2513  ao2_ref(addr_range, -1);
2514  optional = 1;
2515  }
2516 
2517  /* ----- Case 2 ----- */
2518  if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2519  calltoken_required = user->calltoken_required;
2520  } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2521  calltoken_required = user->calltoken_required;
2522  } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2523  calltoken_required = peer->calltoken_required;
2524  } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2525  calltoken_required = peer->calltoken_required;
2526  }
2527 
2528  if (peer) {
2529  peer_unref(peer);
2530  }
2531  if (user) {
2532  user_unref(user);
2533  }
2534 
2535  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);
2536  if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2537  (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2538  res = 0;
2539  }
2540 
2541  return res;
2542 }
2543 
2544 /*!
2545  * \internal
2546  *
2547  * \brief set peercnt callno limit.
2548  *
2549  * \details
2550  * First looks in custom definitions. If not found, global limit
2551  * is used. Entries marked as reg already have
2552  * a custom limit set by a registration and are not modified.
2553  */
2554 static void set_peercnt_limit(struct peercnt *peercnt)
2555 {
2556  uint16_t limit = global_maxcallno;
2557  struct addr_range *addr_range;
2558  struct ast_sockaddr addr;
2559 
2560  ast_sockaddr_copy(&addr, &peercnt->addr);
2561 
2562  if (peercnt->reg && peercnt->limit) {
2563  return; /* this peercnt has a custom limit set by a registration */
2564  }
2565 
2566  if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2567  limit = addr_range->limit;
2568  ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2569  ao2_ref(addr_range, -1);
2570  }
2571 
2572  peercnt->limit = limit;
2573 }
2574 
2575 /*!
2576  * \internal
2577  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2578  */
2579 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2580 {
2581  struct peercnt *peercnt = obj;
2582 
2583  set_peercnt_limit(peercnt);
2584  ast_debug(1, "Reset limits for peercnts table\n");
2585 
2586  return 0;
2587 }
2588 
2589 /*!
2590  * \internal
2591  * \brief returns match if delme is set.
2592  */
2593 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2594 {
2595  struct addr_range *addr_range = obj;
2596 
2597  return addr_range->delme ? CMP_MATCH : 0;
2598 }
2599 
2600 /*!
2601  * \internal
2602  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2603  */
2604 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2605 {
2606  /* this function turns off and on custom callno limits set by peer registration */
2607  struct peercnt *peercnt;
2608  struct peercnt tmp;
2609 
2610  ast_sockaddr_copy(&tmp.addr, sockaddr);
2611 
2612  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2613  peercnt->reg = reg;
2614  if (limit) {
2615  peercnt->limit = limit;
2616  } else {
2617  set_peercnt_limit(peercnt);
2618  }
2619  ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2620  ao2_ref(peercnt, -1); /* decrement ref from find */
2621  }
2622 }
2623 
2624 /*!
2625  * \internal
2626  * \brief adds an ip to the peercnts table, increments connection count if it already exists
2627  *
2628  * \details First searches for the address in the peercnts table. If found
2629  * the current count is incremented. If not found a new peercnt is allocated
2630  * and linked into the peercnts table with a call number count of 1.
2631  */
2632 static int peercnt_add(struct ast_sockaddr *addr)
2633 {
2634  struct peercnt *peercnt;
2635  int res = 0;
2636  struct peercnt tmp;
2637 
2638  ast_sockaddr_copy(&tmp.addr, addr);
2639 
2640  /* Reasoning for peercnts container lock: Two identical ip addresses
2641  * could be added by different threads at the "same time". Without the container
2642  * lock, both threads could alloc space for the same object and attempt
2643  * to link to table. With the lock, one would create the object and link
2644  * to table while the other would find the already created peercnt object
2645  * rather than creating a new one. */
2646  ao2_lock(peercnts);
2647  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2648  ao2_lock(peercnt);
2649  } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2650  ao2_lock(peercnt);
2651  /* create and set defaults */
2652  ast_sockaddr_copy(&peercnt->addr, addr);
2653  set_peercnt_limit(peercnt);
2654  /* guarantees it does not go away after unlocking table
2655  * ao2_find automatically adds this */
2656  ao2_link(peercnts, peercnt);
2657  } else {
2658  ao2_unlock(peercnts);
2659  return -1;
2660  }
2661 
2662  /* check to see if the address has hit its callno limit. If not increment cur. */
2663  if (peercnt->limit > peercnt->cur) {
2664  peercnt->cur++;
2665  ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2666  } else { /* max num call numbers for this peer has been reached! */
2667  ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2668  res = -1;
2669  }
2670 
2671  /* clean up locks and ref count */
2672  ao2_unlock(peercnt);
2673  ao2_unlock(peercnts);
2674  ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2675 
2676  return res;
2677 }
2678 
2679 /*!
2680  * \internal
2681  * \brief decrements a peercnts table entry
2682  */
2683 static void peercnt_remove(struct peercnt *peercnt)
2684 {
2685  struct ast_sockaddr addr;
2686 
2687  ast_sockaddr_copy(&addr, &peercnt->addr);
2688 
2689  /*
2690  * Container locked here since peercnt may be unlinked from
2691  * list. If left unlocked, peercnt_add could try and grab this
2692  * entry from the table and modify it at the "same time" this
2693  * thread attemps to unlink it.
2694  */
2695  ao2_lock(peercnts);
2696  peercnt->cur--;
2697  ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2698  /* if this was the last connection from the peer remove it from table */
2699  if (peercnt->cur == 0) {
2700  ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2701  }
2702  ao2_unlock(peercnts);
2703 }
2704 
2705 /*!
2706  * \internal
2707  * \brief called by scheduler to decrement object
2708  */
2709 static int peercnt_remove_cb(const void *obj)
2710 {
2711  struct peercnt *peercnt = (struct peercnt *) obj;
2712 
2713  peercnt_remove(peercnt);
2714  ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2715 
2716  return 0;
2717 }
2718 
2719 /*!
2720  * \internal
2721  * \brief decrements peercnts connection count, finds by addr
2722  */
2723 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2724 {
2725  struct peercnt *peercnt;
2726  struct peercnt tmp;
2727 
2728  ast_sockaddr_copy(&tmp.addr, addr);
2729 
2730  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2731  peercnt_remove(peercnt);
2732  ao2_ref(peercnt, -1); /* decrement ref from find */
2733  }
2734  return 0;
2735 }
2736 
2737 /*!
2738  * \internal
2739  * \brief Create callno_limit entry based on configuration
2740  */
2741 static void build_callno_limits(struct ast_variable *v)
2742 {
2743  struct addr_range *addr_range = NULL;
2744  struct addr_range tmp;
2745  struct ast_ha *ha;
2746  int limit;
2747  int error;
2748  int found;
2749 
2750  for (; v; v = v->next) {
2751  limit = -1;
2752  error = 0;
2753  found = 0;
2754  ha = ast_append_ha("permit", v->name, NULL, &error);
2755 
2756  /* check for valid config information */
2757  if (error) {
2758  ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2759  continue;
2760  } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2761  ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2762  ast_free_ha(ha);
2763  continue;
2764  }
2765 
2766  ast_copy_ha(ha, &tmp.ha);
2767  /* find or create the addr_range */
2768  if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2769  ao2_lock(addr_range);
2770  found = 1;
2771  } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2772  ast_free_ha(ha);
2773  return; /* out of memory */
2774  }
2775 
2776  /* copy over config data into addr_range object */
2777  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2778  ast_free_ha(ha); /* cleanup the tmp ha */
2779  addr_range->limit = limit;
2780  addr_range->delme = 0;
2781 
2782  /* cleanup */
2783  if (found) {
2784  ao2_unlock(addr_range);
2785  } else {
2786  ao2_link(callno_limits, addr_range);
2787  }
2788  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2789  }
2790 }
2791 
2792 /*!
2793  * \internal
2794  * \brief Create calltoken_ignores entry based on configuration
2795  */
2796 static int add_calltoken_ignore(const char *addr)
2797 {
2798  struct addr_range tmp;
2799  struct addr_range *addr_range = NULL;
2800  struct ast_ha *ha = NULL;
2801  int error = 0;
2802 
2803  if (ast_strlen_zero(addr)) {
2804  ast_log(LOG_WARNING, "invalid calltokenoptional (null)\n");
2805  return -1;
2806  }
2807 
2808  ha = ast_append_ha("permit", addr, NULL, &error);
2809 
2810  /* check for valid config information */
2811  if (error) {
2812  ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2813  return -1;
2814  }
2815 
2816  ast_copy_ha(ha, &tmp.ha);
2817  /* find or create the addr_range */
2818  if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2819  ao2_lock(addr_range);
2820  addr_range->delme = 0;
2821  ao2_unlock(addr_range);
2822  } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2823  /* copy over config data into addr_range object */
2824  ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2825  ao2_link(calltoken_ignores, addr_range);
2826  } else {
2827  ast_free_ha(ha);
2828  return -1;
2829  }
2830 
2831  ast_free_ha(ha);
2832  ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2833 
2834  return 0;
2835 }
2836 
2837 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2838 {
2839  struct ao2_iterator i;
2840  struct peercnt *peercnt;
2841  struct ast_sockaddr addr;
2842  int found = 0;
2843 
2844  switch (cmd) {
2845  case CLI_INIT:
2846  e->command = "iax2 show callnumber usage";
2847  e->usage =
2848  "Usage: iax2 show callnumber usage [IP address]\n"
2849  " Shows current IP addresses which are consuming iax2 call numbers\n";
2850  return NULL;
2851  case CLI_GENERATE:
2852  return NULL;
2853  case CLI_HANDLER:
2854  if (a->argc < 4 || a->argc > 5)
2855  return CLI_SHOWUSAGE;
2856 
2857  if (a->argc == 4) {
2858  ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2859  }
2860 
2861  i = ao2_iterator_init(peercnts, 0);
2862  while ((peercnt = ao2_iterator_next(&i))) {
2863  ast_sockaddr_copy(&addr, &peercnt->addr);
2864 
2865  if (a->argc == 5) {
2866  if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2867  ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2868  ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2869  ao2_ref(peercnt, -1);
2870  found = 1;
2871  break;
2872  }
2873  } else {
2874  ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2875  }
2876  ao2_ref(peercnt, -1);
2877  }
2879 
2880  if (a->argc == 4) {
2881  size_t pool_avail = callno_pool.available;
2882  size_t trunk_pool_avail = callno_pool_trunk.available;
2883 
2884  ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2885  "Non-CallToken Validated Callno Used: %d\n",
2886  global_maxcallno_nonval,
2887  total_nonval_callno_used);
2888 
2889  ast_cli(a->fd, "Total Available Callno: %zu\n"
2890  "Regular Callno Available: %zu\n"
2891  "Trunk Callno Available: %zu\n",
2892  pool_avail + trunk_pool_avail,
2893  pool_avail,
2894  trunk_pool_avail);
2895  } else if (a->argc == 5 && !found) {
2896  ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2897  }
2898 
2899 
2900  return CLI_SUCCESS;
2901  default:
2902  return NULL;
2903  }
2904 }
2905 
2906 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2907 {
2908  struct call_number_pool *pool = NULL;
2909  callno_entry swap;
2910  size_t choice;
2911 
2912  switch (type) {
2913  case CALLNO_TYPE_NORMAL:
2914  pool = &callno_pool;
2915  break;
2916  case CALLNO_TYPE_TRUNK:
2917  pool = &callno_pool_trunk;
2918  break;
2919  default:
2920  ast_assert(0);
2921  break;
2922  }
2923 
2924  /* If we fail, make sure this has a defined value */
2925  *entry = 0;
2926 
2927  /* We lock here primarily to ensure thread safety of the
2928  * total_nonval_callno_used check and increment */
2930 
2931  /* Bail out if we don't have any available call numbers */
2932  if (!pool->available) {
2933  ast_log(LOG_WARNING, "Out of call numbers\n");
2935  return 1;
2936  }
2937 
2938  /* Only a certain number of non-validated call numbers should be allocated.
2939  * If there ever is an attack, this separates the calltoken validating users
2940  * from the non-calltoken validating users. */
2941  if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2943  "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2944  total_nonval_callno_used,
2945  global_maxcallno_nonval);
2947  return 1;
2948  }
2949 
2950  /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2951  * available call numbers. The array of call numbers begins as an ordered
2952  * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2953  * - let's call that x. When a call number is needed we pick a random index
2954  * into the array between 0 and x and use that as our call number. In a
2955  * typical FYD shuffle, we would swap the value that we are extracting with
2956  * the number at x, but in our case we swap and don't touch the value at x
2957  * because it is effectively invisible. We rely on the rest of the IAX2 core
2958  * to return the number to us at some point. Finally, we decrement x by 1
2959  * which establishes our new unused range.
2960  *
2961  * When numbers are returned to the pool, we put them just past x and bump x
2962  * by 1 so that this number is now available for re-use. */
2963 
2964  choice = ast_random() % pool->available;
2965 
2966  *entry = pool->numbers[choice];
2967  swap = pool->numbers[pool->available - 1];
2968 
2969  pool->numbers[choice] = swap;
2970  pool->available--;
2971 
2972  if (validated) {
2974  } else {
2975  total_nonval_callno_used++;
2976  }
2977 
2979 
2980  return 0;
2981 }
2982 
2983 static int replace_callno(const void *obj)
2984 {
2985  callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2986  struct call_number_pool *pool;
2987 
2988  /* We lock here primarily to ensure thread safety of the
2989  * total_nonval_callno_used check and decrement */
2991 
2992  if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2993  if (total_nonval_callno_used) {
2994  total_nonval_callno_used--;
2995  } else {
2997  "Attempted to decrement total non calltoken validated "
2998  "callnumbers below zero. Callno is: %d\n",
2999  CALLNO_ENTRY_GET_CALLNO(entry));
3000  }
3001  }
3002 
3004  pool = &callno_pool;
3005  } else {
3006  pool = &callno_pool_trunk;
3007  }
3008 
3009  ast_assert(pool->capacity > pool->available);
3010 
3011  /* This clears the validated flag */
3012  entry = CALLNO_ENTRY_GET_CALLNO(entry);
3013 
3014  pool->numbers[pool->available] = entry;
3015  pool->available++;
3016 
3018 
3019  return 0;
3020 }
3021 
3022 static int create_callno_pools(void)
3023 {
3024  uint16_t i;
3025 
3027 
3028  /* We start at 2. 0 and 1 are reserved. */
3029  for (i = 2; i < TRUNK_CALL_START; i++) {
3032  }
3033 
3034  for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
3037  }
3038 
3041 
3043 
3044  return 0;
3045 }
3046 
3047 /*!
3048  * \internal
3049  * \brief Schedules delayed removal of iax2_pvt call number data
3050  *
3051  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3052  * available again, and the address from the previous connection must be decremented
3053  * from the peercnts table. This function schedules these operations to take place.
3054  */
3055 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3056 {
3057  int i;
3058  struct peercnt *peercnt;
3059  struct peercnt tmp;
3060 
3061  ast_sockaddr_copy(&tmp.addr, addr);
3062 
3063  if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3064  /* refcount is incremented with ao2_find. keep that ref for the scheduler */
3065  ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3066  i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3067  if (i == -1) {
3068  ao2_ref(peercnt, -1);
3069  }
3070  }
3071 
3073  sched,
3074  MIN_REUSE_TIME * 1000,
3075  replace_callno,
3076  CALLNO_ENTRY_TO_PTR(entry));
3077 }
3078 
3079 /*!
3080  * \internal
3081  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3082  *
3083  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3084  * a new callno.
3085  */
3086 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3087 {
3088  if (frametype != AST_FRAME_IAX) {
3089  return 0;
3090  }
3091  switch (subclass) {
3092  case IAX_COMMAND_NEW:
3093  case IAX_COMMAND_REGREQ:
3094  case IAX_COMMAND_FWDOWNL:
3095  case IAX_COMMAND_REGREL:
3096  return 1;
3097  case IAX_COMMAND_POKE:
3098  if (!inbound) {
3099  return 1;
3100  }
3101  break;
3102  }
3103  return 0;
3104 }
3105 
3106 /*
3107  * \note Calling this function while holding another pvt lock can cause a deadlock.
3108  */
3109 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3110 {
3111  int res = 0;
3112  int x;
3113  /* this call is calltoken validated as long as it is either NEW_FORCE
3114  * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3115  int validated = (new > NEW_ALLOW) ? 1 : 0;
3116  char host[80];
3117 
3118  if (new <= NEW_ALLOW) {
3119  if (callno) {
3120  struct chan_iax2_pvt *pvt;
3121  struct chan_iax2_pvt tmp_pvt = {
3122  .callno = dcallno,
3123  .peercallno = callno,
3124  .transfercallno = callno,
3125  /* hack!! */
3126  .frames_received = check_dcallno,
3127  };
3128 
3129  ast_sockaddr_copy(&tmp_pvt.addr, addr);
3130  /* this works for finding normal call numbers not involving transfering */
3131  if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3132  if (return_locked) {
3133  ast_mutex_lock(&iaxsl[pvt->callno]);
3134  }
3135  res = pvt->callno;
3136  ao2_ref(pvt, -1);
3137  pvt = NULL;
3138  return res;
3139  }
3140  /* this searches for transfer call numbers that might not get caught otherwise */
3141  memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3142  ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3143  if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3144  if (return_locked) {
3145  ast_mutex_lock(&iaxsl[pvt->callno]);
3146  }
3147  res = pvt->callno;
3148  ao2_ref(pvt, -1);
3149  pvt = NULL;
3150  return res;
3151  }
3152  }
3153  /* This will occur on the first response to a message that we initiated,
3154  * such as a PING. */
3155  if (dcallno) {
3156  ast_mutex_lock(&iaxsl[dcallno]);
3157  }
3158  if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3159  iaxs[dcallno]->peercallno = callno;
3160  res = dcallno;
3161  store_by_peercallno(iaxs[dcallno]);
3162  if (!res || !return_locked) {
3163  ast_mutex_unlock(&iaxsl[dcallno]);
3164  }
3165  return res;
3166  }
3167  if (dcallno) {
3168  ast_mutex_unlock(&iaxsl[dcallno]);
3169  }
3170  }
3171  if (!res && (new >= NEW_ALLOW)) {
3172  callno_entry entry;
3173 
3174  /* It may seem odd that we look through the peer list for a name for
3175  * this *incoming* call. Well, it is weird. However, users don't
3176  * have an IP address/port number that we can match against. So,
3177  * this is just checking for a peer that has that IP/port and
3178  * assuming that we have a user of the same name. This isn't always
3179  * correct, but it will be changed if needed after authentication. */
3180  if (!iax2_getpeername(*addr, host, sizeof(host)))
3181  snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3182 
3183  if (peercnt_add(addr)) {
3184  /* This address has hit its callnumber limit. When the limit
3185  * is reached, the connection is not added to the peercnts table.*/
3186  return 0;
3187  }
3188 
3189  if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3190  /* since we ran out of space, remove the peercnt
3191  * entry we added earlier */
3192  peercnt_remove_by_addr(addr);
3193  ast_log(LOG_WARNING, "No more space\n");
3194  return 0;
3195  }
3196  x = CALLNO_ENTRY_GET_CALLNO(entry);
3197  ast_mutex_lock(&iaxsl[x]);
3198 
3199  iaxs[x] = new_iax(addr, host);
3200  if (iaxs[x]) {
3201  if (iaxdebug)
3202  ast_debug(1, "Creating new call structure %d\n", x);
3203  iaxs[x]->callno_entry = entry;
3204  iaxs[x]->sockfd = sockfd;
3205  ast_sockaddr_copy(&iaxs[x]->addr, addr);
3206  iaxs[x]->peercallno = callno;
3207  iaxs[x]->callno = x;
3208  iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3209  iaxs[x]->expiry = min_reg_expire;
3210  iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3211  iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3212  iaxs[x]->amaflags = amaflags;
3218 
3219  if (iaxs[x]->peercallno) {
3220  store_by_peercallno(iaxs[x]);
3221  }
3222  } else {
3223  ast_log(LOG_WARNING, "Out of resources\n");
3224  ast_mutex_unlock(&iaxsl[x]);
3226  return 0;
3227  }
3228  if (!return_locked)
3229  ast_mutex_unlock(&iaxsl[x]);
3230  res = x;
3231  }
3232  return res;
3233 }
3234 
3235 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3236  return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3237 }
3238 
3239 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3240 
3241  return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3242 }
3243 
3244 /*!
3245  * \brief Queue a frame to a call's owning asterisk channel
3246  *
3247  * \pre This function assumes that iaxsl[callno] is locked when called.
3248  *
3249  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3250  * was valid before calling it, it may no longer be valid after calling it.
3251  * This function may unlock and lock the mutex associated with this callno,
3252  * meaning that another thread may grab it and destroy the call.
3253  */
3254 static int iax2_queue_frame(int callno, struct ast_frame *f)
3255 {
3256  iax2_lock_owner(callno);
3257  if (iaxs[callno] && iaxs[callno]->owner) {
3258  ast_queue_frame(iaxs[callno]->owner, f);
3259  ast_channel_unlock(iaxs[callno]->owner);
3260  }
3261  return 0;
3262 }
3263 
3264 /*!
3265  * \brief Queue a hold frame on the ast_channel owner
3266  *
3267  * This function queues a hold frame on the owner of the IAX2 pvt struct that
3268  * is active for the given call number.
3269  *
3270  * \pre Assumes lock for callno is already held.
3271  *
3272  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3273  * was valid before calling it, it may no longer be valid after calling it.
3274  * This function may unlock and lock the mutex associated with this callno,
3275  * meaning that another thread may grab it and destroy the call.
3276  */
3277 static int iax2_queue_hold(int callno, const char *musicclass)
3278 {
3279  iax2_lock_owner(callno);
3280  if (iaxs[callno] && iaxs[callno]->owner) {
3281  ast_queue_hold(iaxs[callno]->owner, musicclass);
3282  ast_channel_unlock(iaxs[callno]->owner);
3283  }
3284  return 0;
3285 }
3286 
3287 /*!
3288  * \brief Queue an unhold frame on the ast_channel owner
3289  *
3290  * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3291  * is active for the given call number.
3292  *
3293  * \pre Assumes lock for callno is already held.
3294  *
3295  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3296  * was valid before calling it, it may no longer be valid after calling it.
3297  * This function may unlock and lock the mutex associated with this callno,
3298  * meaning that another thread may grab it and destroy the call.
3299  */
3300 static int iax2_queue_unhold(int callno)
3301 {
3302  iax2_lock_owner(callno);
3303  if (iaxs[callno] && iaxs[callno]->owner) {
3304  ast_queue_unhold(iaxs[callno]->owner);
3305  ast_channel_unlock(iaxs[callno]->owner);
3306  }
3307  return 0;
3308 }
3309 
3310 /*!
3311  * \brief Queue a hangup frame on the ast_channel owner
3312  *
3313  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3314  * is active for the given call number.
3315  *
3316  * \pre Assumes lock for callno is already held.
3317  *
3318  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3319  * was valid before calling it, it may no longer be valid after calling it.
3320  * This function may unlock and lock the mutex associated with this callno,
3321  * meaning that another thread may grab it and destroy the call.
3322  */
3323 static int iax2_queue_hangup(int callno)
3324 {
3325  iax2_lock_owner(callno);
3326  if (iaxs[callno] && iaxs[callno]->owner) {
3327  ast_queue_hangup(iaxs[callno]->owner);
3328  ast_channel_unlock(iaxs[callno]->owner);
3329  }
3330  return 0;
3331 }
3332 
3333 /*!
3334  * \note This function assumes that iaxsl[callno] is locked when called.
3335  *
3336  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3337  * was valid before calling it, it may no longer be valid after calling it.
3338  * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3339  * associated with this callno, meaning that another thread may grab it and destroy the call.
3340  */
3341 static int __do_deliver(void *data)
3342 {
3343  /* Just deliver the packet by using queueing. This is called by
3344  the IAX thread with the iaxsl lock held. */
3345  struct iax_frame *fr = data;
3346  fr->retrans = -1;
3348  if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3349  iax2_queue_frame(fr->callno, &fr->af);
3350  /* Free our iax frame */
3351  iax2_frame_free(fr);
3352  /* And don't run again */
3353  return 0;
3354 }
3355 
3356 static int handle_error(void)
3357 {
3358  /* XXX Ideally we should figure out why an error occurred and then abort those
3359  rather than continuing to try. Unfortunately, the published interface does
3360  not seem to work XXX */
3361 #if 0
3362  struct sockaddr_in *sin;
3363  int res;
3364  struct msghdr m;
3365  struct sock_extended_err e;
3366  m.msg_name = NULL;
3367  m.msg_namelen = 0;
3368  m.msg_iov = NULL;
3369  m.msg_control = &e;
3370  m.msg_controllen = sizeof(e);
3371  m.msg_flags = 0;
3372  res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3373  if (res < 0)
3374  ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3375  else {
3376  if (m.msg_controllen) {
3377  sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3378  if (sin)
3379  ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3380  else
3381  ast_log(LOG_WARNING, "No address detected??\n");
3382  } else {
3383  ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3384  }
3385  }
3386 #endif
3387  return 0;
3388 }
3389 
3390 static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3391 {
3392  int res;
3393  res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3394 
3395  if (res < 0) {
3396  ast_debug(1, "Received error: %s\n", strerror(errno));
3397  handle_error();
3398  } else
3399  res = 0;
3400  return res;
3401 }
3402 
3403 static int send_packet(struct iax_frame *f)
3404 {
3405  int res;
3406  int callno = f->callno;
3407 
3408  /* Don't send if there was an error, but return error instead */
3409  if (!callno || !iaxs[callno] || iaxs[callno]->error)
3410  return -1;
3411 
3412  /* Called with iaxsl held */
3413  if (iaxdebug) {
3414  ast_debug(3, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3415  }
3416  if (f->transfer) {
3417  iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3418  res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3419  } else {
3420  iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3421  res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3422  }
3423  if (res < 0) {
3424  if (iaxdebug)
3425  ast_debug(1, "Received error: %s\n", strerror(errno));
3426  handle_error();
3427  } else
3428  res = 0;
3429 
3430  return res;
3431 }
3432 
3433 /*!
3434  * \note Since this function calls iax2_queue_hangup(), the pvt struct
3435  * for the given call number may disappear during its execution.
3436  */
3437 static int iax2_predestroy(int callno)
3438 {
3439  struct ast_channel *c = NULL;
3440  struct chan_iax2_pvt *pvt = iaxs[callno];
3441 
3442  if (!pvt)
3443  return -1;
3444 
3445  if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3446  iax2_destroy_helper(pvt);
3448  }
3449 
3450  if ((c = pvt->owner)) {
3452  iax2_queue_hangup(callno);
3453  pvt->owner = NULL;
3455  }
3456 
3457  return 0;
3458 }
3459 
3460 static void iax2_destroy(int callno)
3461 {
3462  struct chan_iax2_pvt *pvt = NULL;
3463  struct ast_channel *owner = NULL;
3464 
3465 retry:
3466  if ((pvt = iaxs[callno])) {
3467 #if 0
3468  /* iax2_destroy_helper gets called from this function later on. When
3469  * called twice, we get the (previously) familiar FRACK! errors in
3470  * devmode, from the scheduler. An alternative to this approach is to
3471  * reset the scheduler entries to -1 when they're deleted in
3472  * iax2_destroy_helper(). That approach was previously decided to be
3473  * "wrong" because "the memory is going to be deallocated anyway. Why
3474  * should we be resetting those values?" */
3475  iax2_destroy_helper(pvt);
3476 #endif
3477  }
3478 
3479  owner = pvt ? pvt->owner : NULL;
3480 
3481  if (owner) {
3482  if (ast_channel_trylock(owner)) {
3483  ast_debug(3, "Avoiding IAX destroy deadlock\n");
3484  DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3485  goto retry;
3486  }
3487  }
3488 
3489  if (!owner) {
3490  iaxs[callno] = NULL;
3491  }
3492 
3493  if (pvt) {
3494  if (!owner) {
3495  pvt->owner = NULL;
3496  } else {
3497  /* If there's an owner, prod it to give up */
3498  /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3499  * because we already hold the owner channel lock. */
3500  ast_queue_hangup(owner);
3501  }
3502 
3503  if (pvt->peercallno) {
3504  remove_by_peercallno(pvt);
3505  }
3506 
3507  if (pvt->transfercallno) {
3509  }
3510 
3511  if (!owner) {
3512  ao2_ref(pvt, -1);
3513  pvt = NULL;
3514  }
3515  }
3516 
3517  if (owner) {
3518  ast_channel_unlock(owner);
3519  }
3520 }
3521 
3522 static int update_packet(struct iax_frame *f)
3523 {
3524  /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3525  struct ast_iax2_full_hdr *fh = f->data;
3526  struct ast_frame af;
3527 
3528  /* if frame is encrypted. decrypt before updating it. */
3529  if (f->encmethods) {
3530  decode_frame(&f->mydcx, fh, &af, &f->datalen);
3531  }
3532  /* Mark this as a retransmission */
3533  fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3534  /* Update iseqno */
3535  f->iseqno = iaxs[f->callno]->iseqno;
3536  fh->iseqno = f->iseqno;
3537 
3538  /* Now re-encrypt the frame */
3539  if (f->encmethods) {
3540  /* since this is a retransmit frame, create a new random padding
3541  * before re-encrypting. */
3542  build_rand_pad(f->semirand, sizeof(f->semirand));
3543  encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3544  }
3545  return 0;
3546 }
3547 
3548 static int attempt_transmit(const void *data);
3549 static void __attempt_transmit(const void *data)
3550 {
3551  /* Attempt to transmit the frame to the remote peer...
3552  Called without iaxsl held. */
3553  struct iax_frame *f = (struct iax_frame *)data;
3554  int freeme = 0;
3555  int callno = f->callno;
3556 
3557  /* Make sure this call is still active */
3558  if (callno)
3559  ast_mutex_lock(&iaxsl[callno]);
3560  if (callno && iaxs[callno]) {
3561  if (f->retries < 0) {
3562  /* Already ACK'd */
3563  freeme = 1;
3564  } else if (f->retries >= max_retries) {
3565  /* Too many attempts. Record an error. */
3566  if (f->transfer) {
3567  /* Transfer timeout */
3568  send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3569  } else if (f->final) {
3570  iax2_destroy(callno);
3571  } else {
3572  if (iaxs[callno]->owner) {
3573  ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3575  ast_channel_name(iaxs[f->callno]->owner),
3576  f->af.frametype,
3577  f->af.subclass.integer,
3578  f->ts,
3579  f->oseqno);
3580  }
3581  iaxs[callno]->error = ETIMEDOUT;
3582  if (iaxs[callno]->owner) {
3584  /* Hangup the fd */
3585  iax2_queue_frame(callno, &fr); /* XXX */
3586  /* Remember, owner could disappear */
3587  if (iaxs[callno] && iaxs[callno]->owner)
3589  } else {
3590  if (iaxs[callno]->reg) {
3591  memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3592  iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3593  iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3594  }
3595  iax2_destroy(callno);
3596  }
3597  }
3598  freeme = 1;
3599  } else {
3600  /* Update it if it needs it */
3601  update_packet(f);
3602  /* Attempt transmission */
3603  send_packet(f);
3604  f->retries++;
3605  /* Try again later after 10 times as long */
3606  f->retrytime *= 10;
3607  if (f->retrytime > MAX_RETRY_TIME)
3609  /* Transfer messages max out at one second */
3610  if (f->transfer && (f->retrytime > 1000))
3611  f->retrytime = 1000;
3612  f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3613  }
3614  } else {
3615  /* Make sure it gets freed */
3616  f->retries = -1;
3617  freeme = 1;
3618  }
3619 
3620  if (freeme) {
3621  /* Don't attempt delivery, just remove it from the queue */
3622  AST_LIST_REMOVE(&frame_queue[callno], f, list);
3623  ast_mutex_unlock(&iaxsl[callno]);
3624  f->retrans = -1; /* this is safe because this is the scheduled function */
3625  /* Free the IAX frame */
3626  iax2_frame_free(f);
3627  } else if (callno) {
3628  ast_mutex_unlock(&iaxsl[callno]);
3629  }
3630 }
3631 
3632 static int attempt_transmit(const void *data)
3633 {
3634 #ifdef SCHED_MULTITHREADED
3636 #endif
3637  __attempt_transmit(data);
3638  return 0;
3639 }
3640 
3641 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3642 {
3643  struct iax2_peer *peer = NULL;
3644  struct iax2_user *user = NULL;
3645  static const char * const choices[] = { "all", NULL };
3646  char *cmplt;
3647 
3648  switch (cmd) {
3649  case CLI_INIT:
3650  e->command = "iax2 prune realtime";
3651  e->usage =
3652  "Usage: iax2 prune realtime [<peername>|all]\n"
3653  " Prunes object(s) from the cache\n";
3654  return NULL;
3655  case CLI_GENERATE:
3656  if (a->pos == 3) {
3657  cmplt = ast_cli_complete(a->word, choices, a->n);
3658  if (!cmplt)
3659  cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3660  return cmplt;
3661  }
3662  return NULL;
3663  }
3664  if (a->argc != 4)
3665  return CLI_SHOWUSAGE;
3666  if (!strcmp(a->argv[3], "all")) {
3667  prune_users();
3668  prune_peers();
3669  ast_cli(a->fd, "Cache flushed successfully.\n");
3670  return CLI_SUCCESS;
3671  }
3672  peer = find_peer(a->argv[3], 0);
3673  user = find_user(a->argv[3]);
3674  if (peer || user) {
3675  if (peer) {
3676  if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3678  expire_registry(peer_ref(peer));
3679  ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3680  } else {
3681  ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3682  }
3683  peer_unref(peer);
3684  }
3685  if (user) {
3686  if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3688  ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3689  } else {
3690  ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3691  }
3692  ao2_unlink(users,user);
3693  user_unref(user);
3694  }
3695  } else {
3696  ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3697  }
3698 
3699  return CLI_SUCCESS;
3700 }
3701 
3702 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3703 {
3704  switch (cmd) {
3705  case CLI_INIT:
3706  e->command = "iax2 test losspct";
3707  e->usage =
3708  "Usage: iax2 test losspct <percentage>\n"
3709  " For testing, throws away <percentage> percent of incoming packets\n";
3710  return NULL;
3711  case CLI_GENERATE:
3712  return NULL;
3713  }
3714  if (a->argc != 4)
3715  return CLI_SHOWUSAGE;
3716 
3717  test_losspct = atoi(a->argv[3]);
3718 
3719  return CLI_SUCCESS;
3720 }
3721 
3722 #ifdef IAXTESTS
3723 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3724 {
3725  switch (cmd) {
3726  case CLI_INIT:
3727  e->command = "iax2 test late";
3728  e->usage =
3729  "Usage: iax2 test late <ms>\n"
3730  " For testing, count the next frame as <ms> ms late\n";
3731  return NULL;
3732  case CLI_GENERATE:
3733  return NULL;
3734  }
3735 
3736  if (a->argc != 4)
3737  return CLI_SHOWUSAGE;
3738 
3739  test_late = atoi(a->argv[3]);
3740 
3741  return CLI_SUCCESS;
3742 }
3743 
3744 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3745 {
3746  switch (cmd) {
3747  case CLI_INIT:
3748  e->command = "iax2 test resync";
3749  e->usage =
3750  "Usage: iax2 test resync <ms>\n"
3751  " For testing, adjust all future frames by <ms> ms\n";
3752  return NULL;
3753  case CLI_GENERATE:
3754  return NULL;
3755  }
3756 
3757  if (a->argc != 4)
3758  return CLI_SHOWUSAGE;
3759 
3760  test_resync = atoi(a->argv[3]);
3761 
3762  return CLI_SUCCESS;
3763 }
3764 
3765 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3766 {
3767  switch (cmd) {
3768  case CLI_INIT:
3769  e->command = "iax2 test jitter";
3770  e->usage =
3771  "Usage: iax2 test jitter <ms> <pct>\n"
3772  " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3773  " percentage of packets. If <pct> is not specified, adds\n"
3774  " jitter to all packets.\n";
3775  return NULL;
3776  case CLI_GENERATE:
3777  return NULL;
3778  }
3779 
3780  if (a->argc < 4 || a->argc > 5)
3781  return CLI_SHOWUSAGE;
3782 
3783  test_jit = atoi(a->argv[3]);
3784  if (a->argc == 5)
3785  test_jitpct = atoi(a->argv[4]);
3786 
3787  return CLI_SUCCESS;
3788 }
3789 #endif /* IAXTESTS */
3790 
3791 /*! \brief peer_status: Report Peer status in character string */
3792 /* returns 1 if peer is online, -1 if unmonitored */
3793 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3794 {
3795  int res = 0;
3796  if (peer->maxms) {
3797  if (peer->lastms < 0) {
3798  ast_copy_string(status, "UNREACHABLE", statuslen);
3799  } else if (peer->lastms > peer->maxms) {
3800  snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3801  res = 1;
3802  } else if (peer->lastms) {
3803  snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3804  res = 1;
3805  } else {
3806  ast_copy_string(status, "UNKNOWN", statuslen);
3807  }
3808  } else {
3809  ast_copy_string(status, "Unmonitored", statuslen);
3810  res = -1;
3811  }
3812  return res;
3813 }
3814 
3815 /*! \brief Show one peer in detail */
3816 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3817 {
3818  char status[64];
3819  char cbuf[256];
3820  struct iax2_peer *peer;
3821  struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3822  struct ast_str *encmethods = ast_str_alloca(256);
3823  int load_realtime = 0;
3824 
3825  switch (cmd) {
3826  case CLI_INIT:
3827  e->command = "iax2 show peer";
3828  e->usage =
3829  "Usage: iax2 show peer <name>\n"
3830  " Display details on specific IAX peer\n";
3831  return NULL;
3832  case CLI_GENERATE:
3833  if (a->pos == 3)
3834  return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3835  return NULL;
3836  }
3837 
3838  if (a->argc < 4)
3839  return CLI_SHOWUSAGE;
3840 
3841  load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3842 
3843  peer = find_peer(a->argv[3], load_realtime);
3844  if (peer) {
3845  char *str_addr, *str_defaddr;
3846  char *str_port, *str_defport;
3847 
3848  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3849  str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3850  str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3851  str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3852 
3853  encmethods_to_str(peer->encmethods, &encmethods);
3854  ast_cli(a->fd, "\n\n");
3855  ast_cli(a->fd, " * Name : %s\n", peer->name);
3856  ast_cli(a->fd, " Description : %s\n", peer->description);
3857  ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3858  ast_cli(a->fd, " Context : %s\n", peer->context);
3859  ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
3860  ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
3861  ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3862  ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
3863  ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3864  ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3865  ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3866  ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3867  ast_cli(a->fd, " Expire : %d\n", peer->expire);
3868  ast_cli(a->fd, " ACL : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3869  ast_cli(a->fd, " Addr->IP : %s Port %s\n", str_addr ? str_addr : "(Unspecified)", str_port);
3870  ast_cli(a->fd, " Defaddr->IP : %s Port %s\n", str_defaddr, str_defport);
3871  ast_cli(a->fd, " Username : %s\n", peer->username);
3872  ast_cli(a->fd, " Codecs : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3873 
3874  if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3875  strcpy(cbuf, "Error"); /* Safe */
3876  }
3877  ast_cli(a->fd, " Codec Order : %s\n", cbuf);
3878 
3879  peer_status(peer, status, sizeof(status));
3880  ast_cli(a->fd, " Status : %s\n", status);
3881  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");
3882  ast_cli(a->fd, "\n");
3883  peer_unref(peer);
3884  } else {
3885  ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3886  ast_cli(a->fd, "\n");
3887  }
3888 
3889  return CLI_SUCCESS;
3890 }
3891 
3892 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3893 {
3894  int which = 0;
3895  struct iax2_peer *peer;
3896  char *res = NULL;
3897  int wordlen = strlen(word);
3898  struct ao2_iterator i;
3899 
3900  i = ao2_iterator_init(peers, 0);
3901  while ((peer = ao2_iterator_next(&i))) {
3902  if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3903  && (!flags || ast_test_flag64(peer, flags))) {
3904  res = ast_strdup(peer->name);
3905  peer_unref(peer);
3906  break;
3907  }
3908  peer_unref(peer);
3909  }
3911 
3912  return res;
3913 }
3914 
3915 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3916 {
3917  struct iax_frame *cur;
3918  int cnt = 0, dead = 0, final = 0, i = 0;
3919 
3920  switch (cmd) {
3921  case CLI_INIT:
3922  e->command = "iax2 show stats";
3923  e->usage =
3924  "Usage: iax2 show stats\n"
3925  " Display statistics on IAX channel driver.\n";
3926  return NULL;
3927  case CLI_GENERATE:
3928  return NULL;
3929  }
3930 
3931  if (a->argc != 3)
3932  return CLI_SHOWUSAGE;
3933 
3934  for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3935  ast_mutex_lock(&iaxsl[i]);
3936  AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3937  if (cur->retries < 0)
3938  dead++;
3939  if (cur->final)
3940  final++;
3941  cnt++;
3942  }
3943  ast_mutex_unlock(&iaxsl[i]);
3944  }
3945 
3946  ast_cli(a->fd, " IAX Statistics\n");
3947  ast_cli(a->fd, "---------------------\n");
3948  ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3949  ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3951  ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3952 
3953  trunk_timed = trunk_untimed = 0;
3956 
3957  return CLI_SUCCESS;
3958 }
3959 
3960 /*! \brief Set trunk MTU from CLI */
3961 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3962 {
3963  int mtuv;
3964 
3965  switch (cmd) {
3966  case CLI_INIT:
3967  e->command = "iax2 set mtu";
3968  e->usage =
3969  "Usage: iax2 set mtu <value>\n"
3970  " Set the system-wide IAX IP mtu to <value> bytes net or\n"
3971  " zero to disable. Disabling means that the operating system\n"
3972  " must handle fragmentation of UDP packets when the IAX2 trunk\n"
3973  " packet exceeds the UDP payload size. This is substantially\n"
3974  " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3975  " greater for G.711 samples.\n";
3976  return NULL;
3977  case CLI_GENERATE:
3978  return NULL;
3979  }
3980 
3981  if (a->argc != 4)
3982  return CLI_SHOWUSAGE;
3983  if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3984  mtuv = MAX_TRUNK_MTU;
3985  else
3986  mtuv = atoi(a->argv[3]);
3987 
3988  if (mtuv == 0) {
3989  ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
3991  return CLI_SUCCESS;
3992  }
3993  if (mtuv < 172 || mtuv > 4000) {
3994  ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
3995  return CLI_SHOWUSAGE;
3996  }
3997  ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
3998  global_max_trunk_mtu = mtuv;
3999  return CLI_SUCCESS;
4000 }
4001 
4002 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4003 {
4004  struct iax2_dpcache *dp = NULL;
4005  char tmp[1024], *pc = NULL;
4006  int s, x, y;
4007  struct timeval now = ast_tvnow();
4008 
4009  switch (cmd) {
4010  case CLI_INIT:
4011  e->command = "iax2 show cache";
4012  e->usage =
4013  "Usage: iax2 show cache\n"
4014  " Display currently cached IAX Dialplan results.\n";
4015  return NULL;
4016  case CLI_GENERATE:
4017  return NULL;
4018  }
4019 
4021 
4022  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
4023 
4024  AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4025  s = dp->expiry.tv_sec - now.tv_sec;
4026  tmp[0] = '\0';
4027  if (dp->flags & CACHE_FLAG_EXISTS)
4028  strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4029  if (dp->flags & CACHE_FLAG_NONEXISTENT)
4030  strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4031  if (dp->flags & CACHE_FLAG_CANEXIST)
4032  strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4033  if (dp->flags & CACHE_FLAG_PENDING)
4034  strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4035  if (dp->flags & CACHE_FLAG_TIMEOUT)
4036  strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4037  if (dp->flags & CACHE_FLAG_TRANSMITTED)
4038  strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4039  if (dp->flags & CACHE_FLAG_MATCHMORE)
4040  strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4041  if (dp->flags & CACHE_FLAG_UNKNOWN)
4042  strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4043  /* Trim trailing pipe */
4044  if (!ast_strlen_zero(tmp)) {
4045  tmp[strlen(tmp) - 1] = '\0';
4046  } else {
4047  ast_copy_string(tmp, "(none)", sizeof(tmp));
4048  }
4049  y = 0;
4050  pc = strchr(dp->peercontext, '@');
4051  if (!pc) {
4052  pc = dp->peercontext;
4053  } else {
4054  pc++;
4055  }
4056  for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4057  if (dp->waiters[x] > -1)
4058  y++;
4059  }
4060  if (s > 0) {
4061  ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4062  } else {
4063  ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4064  }
4065  }
4066 
4068 
4069  return CLI_SUCCESS;
4070 }
4071 
4072 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4073 
4074 static void unwrap_timestamp(struct iax_frame *fr)
4075 {
4076  /* Video mini frames only encode the lower 15 bits of the session
4077  * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4078  const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4079  const int lower_mask = (1 << ts_shift) - 1;
4080  const int upper_mask = ~lower_mask;
4081  const int last_upper = iaxs[fr->callno]->last & upper_mask;
4082 
4083  if ( (fr->ts & upper_mask) == last_upper ) {
4084  const int x = fr->ts - iaxs[fr->callno]->last;
4085  const int threshold = (ts_shift == 15) ? 25000 : 50000;
4086 
4087  if (x < -threshold) {
4088  /* Sudden big jump backwards in timestamp:
4089  What likely happened here is that miniframe timestamp has circled but we haven't
4090  gotten the update from the main packet. We'll just pretend that we did, and
4091  update the timestamp appropriately. */
4092  fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4093  if (iaxdebug)
4094  ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4095  } else if (x > threshold) {
4096  /* Sudden apparent big jump forwards in timestamp:
4097  What's likely happened is this is an old miniframe belonging to the previous
4098  top 15 or 16-bit timestamp that has turned up out of order.
4099  Adjust the timestamp appropriately. */
4100  fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4101  if (iaxdebug)
4102  ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4103  }
4104  }
4105 }
4106 
4107 static int get_from_jb(const void *p);
4108 
4109 static void update_jbsched(struct chan_iax2_pvt *pvt)
4110 {
4111  int when;
4112 
4113  when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4114 
4115  when = jb_next(pvt->jb) - when;
4116 
4117  if (when <= 0) {
4118  /* XXX should really just empty until when > 0.. */
4119  when = 1;
4120  }
4121 
4122  pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4123  CALLNO_TO_PTR(pvt->callno));
4124 }
4125 
4126 static void __get_from_jb(const void *p)
4127 {
4128  int callno = PTR_TO_CALLNO(p);
4129  struct chan_iax2_pvt *pvt = NULL;
4130  struct iax_frame *fr;
4131  jb_frame frame;
4132  int ret;
4133  long ms;
4134  long next;
4135  struct timeval now = ast_tvnow();
4136  struct ast_format *voicefmt;
4137 
4138  /* Make sure we have a valid private structure before going on */
4139  ast_mutex_lock(&iaxsl[callno]);
4140  pvt = iaxs[callno];
4141  if (!pvt) {
4142  /* No go! */
4143  ast_mutex_unlock(&iaxsl[callno]);
4144  return;
4145  }
4146 
4147  pvt->jbid = -1;
4148 
4149  /* round up a millisecond since ast_sched_runq does; */
4150  /* prevents us from spinning while waiting for our now */
4151  /* to catch up with runq's now */
4152  now.tv_usec += 1000;
4153 
4154  ms = ast_tvdiff_ms(now, pvt->rxcore);
4155 
4157  if (voicefmt && ms >= (next = jb_next(pvt->jb))) {
4158  ret = jb_get(pvt->jb, &frame, ms, ast_format_get_default_ms(voicefmt));
4159  switch(ret) {
4160  case JB_OK:
4161  fr = frame.data;
4162  __do_deliver(fr);
4163  /* __do_deliver() can cause the call to disappear */
4164  pvt = iaxs[callno];
4165  break;
4166  case JB_INTERP:
4167  {
4168  struct ast_frame af = { 0, };
4169 
4170  /* create an interpolation frame */
4172  af.subclass.format = voicefmt;
4173  af.samples = frame.ms * (ast_format_get_sample_rate(voicefmt) / 1000);
4174  af.src = "IAX2 JB interpolation";
4175  af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
4177 
4178  /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
4179  * which we'd need to malloc, and then it would free it. That seems like a drag */
4180  if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
4181  iax2_queue_frame(callno, &af);
4182  /* iax2_queue_frame() could cause the call to disappear */
4183  pvt = iaxs[callno];
4184  }
4185  }
4186  break;
4187  case JB_DROP:
4188  iax2_frame_free(frame.data);
4189  break;
4190  case JB_NOFRAME:
4191  case JB_EMPTY:
4192  /* do nothing */
4193  break;
4194  default:
4195  /* shouldn't happen */
4196  break;
4197  }
4198  }
4199  if (pvt)
4200  update_jbsched(pvt);
4201  ast_mutex_unlock(&iaxsl[callno]);
4202 }
4203 
4204 static int get_from_jb(const void *data)
4205 {
4206 #ifdef SCHED_MULTITHREADED
4207  if (schedule_action(__get_from_jb, data))
4208 #endif
4209  __get_from_jb(data);
4210  return 0;
4211 }
4212 
4213 /*!
4214  * \note This function assumes fr->callno is locked
4215  *
4216  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
4217  * was valid before calling it, it may no longer be valid after calling it.
4218  */
4219 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
4220 {
4221  int type, len;
4222  int ret;
4223  int needfree = 0;
4224 
4225  /*
4226  * Clear fr->af.data if there is no data in the buffer. Things
4227  * like AST_CONTROL_HOLD without a suggested music class must
4228  * have a NULL pointer.
4229  */
4230  if (!fr->af.datalen) {
4231  memset(&fr->af.data, 0, sizeof(fr->af.data));
4232  }
4233 
4234  /* Attempt to recover wrapped timestamps */
4235  unwrap_timestamp(fr);
4236 
4237  /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
4238  if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
4239  fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
4240  else {
4241 #if 0
4242  ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
4243 #endif
4244  fr->af.delivery = ast_tv(0,0);
4245  }
4246 
4247  type = JB_TYPE_CONTROL;
4248  len = 0;
4249 
4250  if(fr->af.frametype == AST_FRAME_VOICE) {
4251  type = JB_TYPE_VOICE;
4253  } else if(fr->af.frametype == AST_FRAME_CNG) {
4254  type = JB_TYPE_SILENCE;
4255  }
4256 
4257  if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
4258  if (tsout)
4259  *tsout = fr->ts;
4260  __do_deliver(fr);
4261  return -1;
4262  }
4263 
4264  /* insert into jitterbuffer */
4265  /* TODO: Perhaps we could act immediately if it's not droppable and late */
4266  ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
4267  calc_rxstamp(iaxs[fr->callno],fr->ts));
4268  if (ret == JB_DROP) {
4269  needfree++;
4270  } else if (ret == JB_SCHED) {
4271  update_jbsched(iaxs[fr->callno]);
4272  }
4273  if (tsout)
4274  *tsout = fr->ts;
4275  if (needfree) {
4276  /* Free our iax frame */
4277  iax2_frame_free(fr);
4278  return -1;
4279  }
4280  return 0;
4281 }
4282 
4283 static int transmit_frame(void *data)
4284 {
4285  struct iax_frame *fr = data;
4286 
4287  ast_mutex_lock(&iaxsl[fr->callno]);
4288 
4289  fr->sentyet = 1;
4290 
4291  if (iaxs[fr->callno]) {
4292  send_packet(fr);
4293  }
4294 
4295  if (fr->retries < 0) {
4296  ast_mutex_unlock(&iaxsl[fr->callno]);
4297  /* No retransmit requested */
4298  iax_frame_free(fr);
4299  } else {
4300  /* We need reliable delivery. Schedule a retransmission */
4302  fr->retries++;
4303  fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
4304  ast_mutex_unlock(&iaxsl[fr->callno]);
4305  }
4306 
4307  return 0;
4308 }
4309 
4310 static int iax2_transmit(struct iax_frame *fr)
4311 {
4312  fr->sentyet = 0;
4313 
4314  return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
4315 }
4316 
4317 static int iax2_digit_begin(struct ast_channel *c, char digit)
4318 {
4320 }
4321 
4322 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
4323 {
4325 }
4326 
4327 static int iax2_sendtext(struct ast_channel *c, const char *text)
4328 {
4329 
4331  0, 0, (unsigned char *)text, strlen(text) + 1, -1);
4332 }
4333 
4334 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
4335 {
4337 }
4338 
4339 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
4340 {
4341  return send_command_locked(PTR_TO_CALLNO(ast_channel_tech_pvt(c)), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
4342 }
4343 
4344 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
4345 {
4346  unsigned short callno = PTR_TO_CALLNO(ast_channel_tech_pvt(newchan));
4347  ast_mutex_lock(&iaxsl[callno]);
4348  if (iaxs[callno])
4349  iaxs[callno]->owner = newchan;
4350  else
4351  ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
4352  ast_mutex_unlock(&iaxsl[callno]);
4353  return 0;
4354 }
4355 
4356 /*!
4357  * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
4358  * so do not call this with a pvt lock held.
4359  */
4360 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr)
4361 {
4362  struct ast_variable *var = NULL;
4363  struct ast_variable *tmp;
4364  struct iax2_peer *peer=NULL;
4365  time_t regseconds = 0, nowtime;
4366  int dynamic=0;
4367  char *str_addr, *str_port;
4368 
4369  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4370  str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4371 
4372  if (peername) {
4373  var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
4374  if (!var && !ast_sockaddr_isnull(addr)) {
4375  var = ast_load_realtime("iaxpeers", "name", peername, "host", str_addr, SENTINEL);
4376  }
4377  } else if (!ast_sockaddr_isnull(addr)) {
4378  var = ast_load_realtime("iaxpeers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4379  if (var) {
4380  /* We'll need the peer name in order to build the structure! */
4381  for (tmp = var; tmp; tmp = tmp->next) {
4382  if (!strcasecmp(tmp->name, "name"))
4383  peername = tmp->value;
4384  }
4385  }
4386  }
4387  if (!var && peername) { /* Last ditch effort */
4388  var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
4389  /*!\note
4390  * If this one loaded something, then we need to ensure that the host
4391  * field matched. The only reason why we can't have this as a criteria
4392  * is because we only have the IP address and the host field might be
4393  * set as a name (and the reverse PTR might not match).
4394  */
4395  if (var && !ast_sockaddr_isnull(addr)) {
4396  for (tmp = var; tmp; tmp = tmp->next) {
4397  if (!strcasecmp(tmp->name, "host")) {
4398  struct ast_sockaddr *hostaddr = NULL;
4399 
4401  || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4402  /* No match */
4403  ast_variables_destroy(var);
4404  var = NULL;
4405  }
4406  ast_free(hostaddr);
4407  break;
4408  }
4409  }
4410  }
4411  }
4412  if (!var)
4413  return NULL;
4414 
4415  peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
4416 
4417  if (!peer) {
4418  ast_variables_destroy(var);
4419  return NULL;
4420  }
4421 
4422  for (tmp = var; tmp; tmp = tmp->next) {
4423  /* Make sure it's not a user only... */
4424  if (!strcasecmp(tmp->name, "type")) {
4425  if (strcasecmp(tmp->value, "friend") &&
4426  strcasecmp(tmp->value, "peer")) {
4427  /* Whoops, we weren't supposed to exist! */
4428  peer = peer_unref(peer);
4429  break;
4430  }
4431  } else if (!strcasecmp(tmp->name, "regseconds")) {
4432  ast_get_time_t(tmp->value, &regseconds, 0, NULL);
4433  } else if (!strcasecmp(tmp->name, "ipaddr")) {
4434  int setport = ast_sockaddr_port(&peer->addr);
4436  ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
4437  } else {
4438  ast_sockaddr_parse(&peer->addr, tmp->value, 0);
4439  }
4440  ast_sockaddr_set_port(&peer->addr, setport);
4441  } else if (!strcasecmp(tmp->name, "port")) {
4442  int bindport;
4443  if (ast_parse_arg(tmp->value, PARSE_UINT32 | PARSE_IN_RANGE, &bindport, 0, 65535)) {
4444  bindport = IAX_DEFAULT_PORTNO;
4445  }
4446  ast_sockaddr_set_port(&peer->addr, bindport);
4447  } else if (!strcasecmp(tmp->name, "host")) {
4448  if (!strcasecmp(tmp->value, "dynamic"))
4449  dynamic = 1;
4450  }
4451  }
4452 
4453  ast_variables_destroy(var);
4454 
4455  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4457  if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
4458  if (peer->expire > -1) {
4459  if (!AST_SCHED_DEL(sched, peer->expire)) {
4460  peer->expire = -1;
4461  peer_unref(peer);
4462  }
4463  }
4464  peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
4465  if (peer->expire == -1)
4466  peer_unref(peer);
4467  }
4468  ao2_link(peers, peer);
4469  if (ast_test_flag64(peer, IAX_DYNAMIC))
4470  reg_source_db(peer);
4471  } else {
4473  }
4474 
4475  if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
4476  time(&nowtime);
4477  if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
4478  memset(&peer->addr, 0, sizeof(peer->addr));
4479  realtime_update_peer(peer->name, &peer->addr, 0);
4480  ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
4481  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4482  }
4483  else {
4484  ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
4485  peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
4486  }
4487  }
4488 
4489  return peer;
4490 }
4491 
4492 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr)
4493 {
4494  struct ast_variable *var;
4495  struct ast_variable *tmp;
4496  struct iax2_user *user=NULL;
4497  char *str_addr, *str_port;
4498 
4499  str_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
4500  str_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
4501 
4502  var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
4503  if (!var)
4504  var = ast_load_realtime("iaxusers", "name", username, "host", str_addr, SENTINEL);
4505  if (!var && !ast_sockaddr_isnull(addr)) {
4506  var = ast_load_realtime("iaxusers", "name", username, "ipaddr", str_addr, "port", str_port, SENTINEL);
4507  if (!var)
4508  var = ast_load_realtime("iaxusers", "ipaddr", str_addr, "port", str_port, SENTINEL);
4509  }
4510  if (!var) { /* Last ditch effort */
4511  var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
4512  /*!\note
4513  * If this one loaded something, then we need to ensure that the host
4514  * field matched. The only reason why we can't have this as a criteria
4515  * is because we only have the IP address and the host field might be
4516  * set as a name (and the reverse PTR might not match).
4517  */
4518  if (var) {
4519  for (tmp = var; tmp; tmp = tmp->next) {
4520  if (!strcasecmp(tmp->name, "host")) {
4521  struct ast_sockaddr *hostaddr = NULL;
4522 
4524  || ast_sockaddr_cmp_addr(hostaddr, addr)) {
4525  /* No match */
4526  ast_variables_destroy(var);
4527  var = NULL;
4528  }
4529  ast_free(hostaddr);
4530  break;
4531  }
4532  }
4533  }
4534  }
4535  if (!var)
4536  return NULL;
4537 
4538  tmp = var;
4539  while(tmp) {
4540  /* Make sure it's not a peer only... */
4541  if (!strcasecmp(tmp->name, "type")) {
4542  if (strcasecmp(tmp->value, "friend") &&
4543  strcasecmp(tmp->value, "user")) {
4544  return NULL;
4545  }
4546  }
4547  tmp = tmp->next;
4548  }
4549 
4550  user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
4551 
4552  ast_variables_destroy(var);
4553 
4554  if (!user)
4555  return NULL;
4556 
4557  if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
4559  ao2_link(users, user);
4560  } else {
4562  }
4563 
4564  return user;
4565 }
4566 
4567 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
4568 {
4569  char regseconds[20];
4570  const char *sysname = ast_config_AST_SYSTEM_NAME;
4571  char *syslabel = NULL;
4572  char *port;
4573 
4574  if (ast_strlen_zero(sysname)) /* No system name, disable this */
4575  sysname = NULL;
4576  else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
4577  syslabel = "regserver";
4578 
4579  snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
4580  port = ast_strdupa(ast_sockaddr_stringify_port(sockaddr));
4581  ast_update_realtime("iaxpeers", "name", peername,
4582  "ipaddr", ast_sockaddr_isnull(sockaddr) ? "" : ast_sockaddr_stringify_addr(sockaddr),
4583  "port", ast_sockaddr_isnull(sockaddr) ? "" : port,
4584  "regseconds", regseconds, syslabel, sysname, SENTINEL); /* note syslable can be NULL */
4585 }
4586 
4589  uint64_t flags;
4590  struct iax2_codec_pref prefs;
4591  int maxtime;
4594  int found;
4595  int sockfd;
4596  int adsi;
4597  char username[80];
4598  char secret[80];
4599  char outkey[80];
4600  char timezone[80];
4601  char cid_num[80];
4602  char cid_name[80];
4604  char peercontext[AST_MAX_CONTEXT];
4607 };
4608 
4609 static int create_addr(const char *peername, struct ast_channel *c, struct ast_sockaddr *addr, struct create_addr_info *cai)
4610 {
4611  struct iax2_peer *peer;
4612  int res = -1;
4613 
4615  cai->sockfd = defaultsockfd;
4616  cai->maxtime = 0;
4617 
4618  if (!(peer = find_peer(peername, 1))) {
4619  struct ast_sockaddr peer_addr;
4620 
4621  peer_addr.ss.ss_family = AST_AF_UNSPEC;
4622  cai->found = 0;
4623  if (ast_get_ip_or_srv(&peer_addr, peername, srvlookup ? "_iax._udp" : NULL)) {
4624  ast_log(LOG_WARNING, "No such host: %s\n", peername);
4625  return -1;
4626  }
4627 
4628  if (!ast_sockaddr_port(&peer_addr)) {
4630  }
4631 
4632  ast_sockaddr_copy(addr, &peer_addr);
4633  /*
4634  * Use The global iax prefs for unknown peer/user.
4635  * However, move the calling channel's native codec to
4636  * the top of the preference list.
4637  */
4638  cai->prefs = prefs_global;
4639  if (c) {
4640  int i;
4641 
4642  for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4645  iax2_codec_pref_prepend(&cai->prefs, format,
4647  1);
4648  ao2_ref(format, -1);
4649  }
4650  }
4651  return 0;
4652  }
4653 
4654  cai->found = 1;
4655 
4656  /* if the peer has no address (current or default), return failure */
4657  if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
4658  goto return_unref;
4659  }
4660 
4661  /* if the peer is being monitored and is currently unreachable, return failure */
4662  if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
4663  goto return_unref;
4664 
4666  cai->maxtime = peer->maxms;
4667  cai->capability = peer->capability;
4668  cai->encmethods = peer->encmethods;
4669  cai->authmethods = peer->authmethods;
4670  cai->sockfd = peer->sockfd;
4671  cai->adsi = peer->adsi;
4672  cai->prefs = peer->prefs;
4673  /* Move the calling channel's native codec to the top of the preference list */
4674  if (c) {
4675  int i;
4676 
4677  for (i = 0; i < ast_format_cap_count(ast_channel_nativeformats(c)); i++) {
4678  struct ast_format *tmpfmt = ast_format_cap_get_format(
4680  iax2_codec_pref_prepend(&cai->prefs, tmpfmt,
4682  1);
4683  ao2_ref(tmpfmt, -1);
4684  }
4685  }
4686  ast_copy_string(cai->context, peer->context, sizeof(cai->context));
4687  ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
4688  ast_copy_string(cai->username, peer->username, sizeof(cai->username));
4689  ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
4690  ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
4691  ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
4692  ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
4693  ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
4694  ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
4695  if (ast_strlen_zero(peer->dbsecret)) {
4696  ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
4697  } else {
4698  char *family;
4699  char *key = NULL;
4700 
4701  family = ast_strdupa(peer->dbsecret);
4702  key = strchr(family, '/');
4703  if (key)
4704  *key++ = '\0';
4705  if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
4706  ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
4707  goto return_unref;
4708  }
4709  }
4710 
4711  if (!ast_sockaddr_isnull(&peer->addr)) {
4712  ast_sockaddr_copy(addr, &peer->addr);
4713  } else {
4714  ast_sockaddr_copy(addr, &peer->defaddr);
4715  }
4716 
4717  res = 0;
4718 
4719 return_unref:
4720  peer_unref(peer);
4721 
4722  return res;
4723 }
4724 
4725 static void __auto_congest(const void *nothing)
4726 {
4727  int callno = PTR_TO_CALLNO(nothing);
4729  ast_mutex_lock(&iaxsl[callno]);
4730  if (iaxs[callno]) {
4731  iaxs[callno]->initid = -1;
4732  iax2_queue_frame(callno, &f);
4733  ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
4734  }
4735  ast_mutex_unlock(&iaxsl[callno]);
4736 }
4737 
4738 static int auto_congest(const void *data)
4739 {
4740 #ifdef SCHED_MULTITHREADED
4741  if (schedule_action(__auto_congest, data))
4742 #endif
4743  __auto_congest(data);
4744  return 0;
4745 }