chan_iax2: Only send mini frames if the underlying format has not changed, not if...
[asterisk/asterisk.git] / channels / chan_iax2.c
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="external">crypto</use>
56         <support_level>core</support_level>
57  ***/
58
59 #include "asterisk.h"
60
61 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
62
63 #include <sys/mman.h>
64 #include <dirent.h>
65 #include <sys/socket.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <sys/time.h>
71 #include <sys/signal.h>
72 #include <signal.h>
73 #include <strings.h>
74 #include <netdb.h>
75 #include <fcntl.h>
76 #include <sys/stat.h>
77 #include <regex.h>
78
79 #include "asterisk/paths.h"
80
81 #include "asterisk/lock.h"
82 #include "asterisk/frame.h"
83 #include "asterisk/channel.h"
84 #include "asterisk/module.h"
85 #include "asterisk/pbx.h"
86 #include "asterisk/sched.h"
87 #include "asterisk/io.h"
88 #include "asterisk/config.h"
89 #include "asterisk/cli.h"
90 #include "asterisk/translate.h"
91 #include "asterisk/md5.h"
92 #include "asterisk/crypto.h"
93 #include "asterisk/acl.h"
94 #include "asterisk/manager.h"
95 #include "asterisk/callerid.h"
96 #include "asterisk/app.h"
97 #include "asterisk/astdb.h"
98 #include "asterisk/musiconhold.h"
99 #include "asterisk/features.h"
100 #include "asterisk/utils.h"
101 #include "asterisk/causes.h"
102 #include "asterisk/localtime.h"
103 #include "asterisk/dnsmgr.h"
104 #include "asterisk/devicestate.h"
105 #include "asterisk/netsock.h"
106 #include "asterisk/stringfields.h"
107 #include "asterisk/linkedlists.h"
108 #include "asterisk/astobj2.h"
109 #include "asterisk/timing.h"
110 #include "asterisk/taskprocessor.h"
111 #include "asterisk/test.h"
112 #include "asterisk/data.h"
113 #include "asterisk/security_events.h"
114 #include "asterisk/stasis_endpoints.h"
115 #include "asterisk/bridge.h"
116 #include "asterisk/stasis.h"
117 #include "asterisk/stasis_system.h"
118 #include "asterisk/stasis_channels.h"
119 #include "asterisk/format_cache.h"
120 #include "asterisk/format_compatibility.h"
121 #include "asterisk/format_cap.h"
122
123 #include "iax2/include/iax2.h"
124 #include "iax2/include/firmware.h"
125 #include "iax2/include/parser.h"
126 #include "iax2/include/provision.h"
127 #include "iax2/include/codec_pref.h"
128 #include "iax2/include/format_compatibility.h"
129
130 #include "jitterbuf.h"
131
132 /*** DOCUMENTATION
133         <application name="IAX2Provision" language="en_US">
134                 <synopsis>
135                         Provision a calling IAXy with a given template.
136                 </synopsis>
137                 <syntax>
138                         <parameter name="template">
139                                 <para>If not specified, defaults to <literal>default</literal>.</para>
140                         </parameter>
141                 </syntax>
142                 <description>
143                         <para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
144                         given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
145                         or <literal>0</literal> on success.</para>
146                 </description>
147         </application>
148         <function name="IAXPEER" language="en_US">
149                 <synopsis>
150                         Gets IAX peer information.
151                 </synopsis>
152                 <syntax>
153                         <parameter name="peername" required="true">
154                                 <enumlist>
155                                         <enum name="CURRENTCHANNEL">
156                                                 <para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
157                                                 endpoint of the current channel</para>
158                                         </enum>
159                                 </enumlist>
160                         </parameter>
161                         <parameter name="item">
162                                 <para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
163                                 <enumlist>
164                                         <enum name="ip">
165                                                 <para>(default) The IP address.</para>
166                                         </enum>
167                                         <enum name="status">
168                                                 <para>The peer's status (if <literal>qualify=yes</literal>)</para>
169                                         </enum>
170                                         <enum name="mailbox">
171                                                 <para>The configured mailbox.</para>
172                                         </enum>
173                                         <enum name="context">
174                                                 <para>The configured context.</para>
175                                         </enum>
176                                         <enum name="expire">
177                                                 <para>The epoch time of the next expire.</para>
178                                         </enum>
179                                         <enum name="dynamic">
180                                                 <para>Is it dynamic? (yes/no).</para>
181                                         </enum>
182                                         <enum name="callerid_name">
183                                                 <para>The configured Caller ID name.</para>
184                                         </enum>
185                                         <enum name="callerid_num">
186                                                 <para>The configured Caller ID number.</para>
187                                         </enum>
188                                         <enum name="codecs">
189                                                 <para>The configured codecs.</para>
190                                         </enum>
191                                         <enum name="codec[x]">
192                                                 <para>Preferred codec index number <replaceable>x</replaceable> (beginning
193                                                 with <literal>0</literal>)</para>
194                                         </enum>
195                                 </enumlist>
196                         </parameter>
197                 </syntax>
198                 <description>
199                         <para>Gets information associated with the specified IAX2 peer.</para>
200                 </description>
201                 <see-also>
202                         <ref type="function">SIPPEER</ref>
203                 </see-also>
204         </function>
205         <function name="IAXVAR" language="en_US">
206                 <synopsis>
207                         Sets or retrieves a remote variable.
208                 </synopsis>
209                 <syntax>
210                         <parameter name="varname" required="true" />
211                 </syntax>
212                 <description>
213                         <para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
214                 </description>
215         </function>
216         <manager name="IAXpeers" language="en_US">
217                 <synopsis>
218                         List IAX peers.
219                 </synopsis>
220                 <syntax>
221                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
222                 </syntax>
223                 <description>
224                 </description>
225         </manager>
226         <manager name="IAXpeerlist" language="en_US">
227                 <synopsis>
228                         List IAX Peers.
229                 </synopsis>
230                 <syntax>
231                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
232                 </syntax>
233                 <description>
234                         <para>List all the IAX peers.</para>
235                 </description>
236         </manager>
237         <manager name="IAXnetstats" language="en_US">
238                 <synopsis>
239                         Show IAX Netstats.
240                 </synopsis>
241                 <syntax />
242                 <description>
243                         <para>Show IAX channels network statistics.</para>
244                 </description>
245         </manager>
246         <manager name="IAXregistry" language="en_US">
247                 <synopsis>
248                         Show IAX registrations.
249                 </synopsis>
250                 <syntax>
251                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
252                 </syntax>
253                 <description>
254                         <para>Show IAX registrations.</para>
255                 </description>
256         </manager>
257  ***/
258
259 /* Define SCHED_MULTITHREADED to run the scheduler in a special
260    multithreaded mode. */
261 #define SCHED_MULTITHREADED
262
263 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
264    thread is actually doing. */
265 #define DEBUG_SCHED_MULTITHREAD
266
267
268 #ifdef SO_NO_CHECK
269 static int nochecksums = 0;
270 #endif
271
272 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
273 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
274
275 #define DEFAULT_THREAD_COUNT 10
276 #define DEFAULT_MAX_THREAD_COUNT 100
277 #define DEFAULT_RETRY_TIME 1000
278 #define MEMORY_SIZE 100
279 #define DEFAULT_DROP 3
280
281 #define DEBUG_SUPPORT
282
283 #define MIN_REUSE_TIME          60      /* Don't reuse a call number within 60 seconds */
284
285 /* Sample over last 100 units to determine historic jitter */
286 #define GAMMA (0.01)
287
288 static struct iax2_codec_pref prefs;
289
290 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
291
292
293 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
294     fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
295 #define MAX_TRUNK_MTU 1240
296
297 static int global_max_trunk_mtu;        /*!< Maximum MTU, 0 if not used */
298 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;    /*!< Trunk MTU statistics */
299
300 #define DEFAULT_CONTEXT "default"
301
302 static char default_parkinglot[AST_MAX_CONTEXT];
303
304 static char language[MAX_LANGUAGE] = "";
305 static char regcontext[AST_MAX_CONTEXT] = "";
306
307 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
308 static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
309 static int network_change_sched_id = -1;
310
311 static int maxauthreq = 3;
312 static int max_retries = 4;
313 static int ping_time = 21;
314 static int lagrq_time = 10;
315 static int maxjitterbuffer=1000;
316 static int resyncthreshold=1000;
317 static int maxjitterinterps=10;
318 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
319
320 #define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
321
322 static int trunkfreq = 20;
323 static int trunkmaxsize = MAX_TRUNKDATA;
324
325 static int authdebug = 0;
326 static int autokill = 0;
327 static int iaxcompat = 0;
328 static int last_authmethod = 0;
329
330 static int iaxdefaultdpcache=10 * 60;   /* Cache dialplan entries for 10 minutes by default */
331
332 static int iaxdefaulttimeout = 5;               /* Default to wait no more than 5 seconds for a reply to come back */
333
334 static struct {
335         unsigned int tos;
336         unsigned int cos;
337 } qos = { 0, 0 };
338
339 static int min_reg_expire;
340 static int max_reg_expire;
341
342 static int srvlookup = 0;
343
344 static struct ast_timer *timer;                         /* Timer for trunking */
345
346 static struct ast_netsock_list *netsock;
347 static struct ast_netsock_list *outsock;                /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
348 static int defaultsockfd = -1;
349
350 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
351
352 /* Ethernet, etc */
353 #define IAX_CAPABILITY_FULLBANDWIDTH    0xFFFF
354 /* T1, maybe ISDN */
355 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
356                      ~ast_format_compatibility_format2bitfield(ast_format_slin) &      \
357                      ~ast_format_compatibility_format2bitfield(ast_format_slin16) &    \
358                      ~ast_format_compatibility_format2bitfield(ast_format_siren7) &       \
359                      ~ast_format_compatibility_format2bitfield(ast_format_siren14) &      \
360                      ~ast_format_compatibility_format2bitfield(ast_format_g719) &         \
361                      ~ast_format_compatibility_format2bitfield(ast_format_ulaw) &         \
362                      ~ast_format_compatibility_format2bitfield(ast_format_alaw) &         \
363                      ~ast_format_compatibility_format2bitfield(ast_format_g722))
364 /* A modem */
365 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
366                      ~ast_format_compatibility_format2bitfield(ast_format_g726) &         \
367                      ~ast_format_compatibility_format2bitfield(ast_format_g726_aal2) &    \
368                      ~ast_format_compatibility_format2bitfield(ast_format_adpcm))
369
370 #define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
371                      ~ast_format_compatibility_format2bitfield(ast_format_g723))
372
373
374 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
375 #define DEFAULT_FREQ_OK         60 * 1000       /* How often to check for the host to be up */
376 #define DEFAULT_FREQ_NOTOK      10 * 1000       /* How often to check, if the host is down... */
377
378 /* if a pvt has encryption setup done and is running on the call */
379 #define IAX_CALLENCRYPTED(pvt) \
380         (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
381
382 #define IAX_DEBUGDIGEST(msg, key) do { \
383                 int idx; \
384                 char digest[33] = ""; \
385                 \
386                 if (!iaxdebug) \
387                         break; \
388                 \
389                 for (idx = 0; idx < 16; idx++) \
390                         sprintf(digest + (idx << 1), "%2.2x", (unsigned) key[idx]); \
391                 \
392                 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
393         } while(0)
394
395 static struct io_context *io;
396 static struct ast_sched_context *sched;
397
398 #define DONT_RESCHEDULE -2
399
400 static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
401
402 static int iaxdebug = 0;
403
404 static int iaxtrunkdebug = 0;
405
406 static int test_losspct = 0;
407 #ifdef IAXTESTS
408 static int test_late = 0;
409 static int test_resync = 0;
410 static int test_jit = 0;
411 static int test_jitpct = 0;
412 #endif /* IAXTESTS */
413
414 static char accountcode[AST_MAX_ACCOUNT_CODE];
415 static char mohinterpret[MAX_MUSICCLASS];
416 static char mohsuggest[MAX_MUSICCLASS];
417 static int amaflags = 0;
418 static int adsi = 0;
419 static int delayreject = 0;
420 static int iax2_encryption = 0;
421
422 static struct ast_flags64 globalflags = { 0 };
423
424 static pthread_t netthreadid = AST_PTHREADT_NULL;
425
426 enum iax2_state {
427         IAX_STATE_STARTED =                     (1 << 0),
428         IAX_STATE_AUTHENTICATED =       (1 << 1),
429         IAX_STATE_TBD =                         (1 << 2),
430 };
431
432 struct iax2_context {
433         char context[AST_MAX_CONTEXT];
434         struct iax2_context *next;
435 };
436
437
438 #define IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
439 #define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
440 #define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
441 #define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
442 #define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
443 #define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
444 #define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
445 #define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
446 #define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
447 #define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
448 #define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
449 #define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
450 #define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
451 #define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
452 #define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
453 #define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
454 #define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
455 #define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
456 #define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
457 #define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
458 #define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
459 #define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
460 #define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
461 #define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
462 #define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
463 #define IAX_DELAYPBXSTART       (uint64_t)(1 << 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 */
464 #define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
465 #define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
466 #define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
467 #define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
468 #define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
469 #define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
470 static int global_rtautoclear = 120;
471
472 static int reload_config(int forced_reload);
473
474 /*!
475  * \brief Call token validation settings.
476  */
477 enum calltoken_peer_enum {
478         /*! \brief Default calltoken required unless the ip is in the ignorelist */
479         CALLTOKEN_DEFAULT = 0,
480         /*! \brief Require call token validation. */
481         CALLTOKEN_YES = 1,
482         /*! \brief Require call token validation after a successful registration
483          *         using call token validation occurs. */
484         CALLTOKEN_AUTO = 2,
485         /*! \brief Do not require call token validation. */
486         CALLTOKEN_NO = 3,
487 };
488
489 struct iax2_user {
490         AST_DECLARE_STRING_FIELDS(
491                 AST_STRING_FIELD(name);
492                 AST_STRING_FIELD(secret);
493                 AST_STRING_FIELD(dbsecret);
494                 AST_STRING_FIELD(accountcode);
495                 AST_STRING_FIELD(mohinterpret);
496                 AST_STRING_FIELD(mohsuggest);
497                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
498                 AST_STRING_FIELD(language);
499                 AST_STRING_FIELD(cid_num);
500                 AST_STRING_FIELD(cid_name);
501                 AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
502         );
503
504         int authmethods;
505         int encmethods;
506         int amaflags;
507         int adsi;
508         uint64_t flags;
509         iax2_format capability;
510         int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
511         int curauthreq; /*!< Current number of outstanding AUTHREQs */
512         struct iax2_codec_pref prefs;
513         struct ast_acl_list *acl;
514         struct iax2_context *contexts;
515         struct ast_variable *vars;
516         enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
517 };
518
519 struct iax2_peer {
520         AST_DECLARE_STRING_FIELDS(
521                 AST_STRING_FIELD(name);
522                 AST_STRING_FIELD(username);
523                 AST_STRING_FIELD(description);          /*!< Description of the peer */
524                 AST_STRING_FIELD(secret);
525                 AST_STRING_FIELD(dbsecret);
526                 AST_STRING_FIELD(outkey);           /*!< What key we use to talk to this peer */
527
528                 AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
529                 AST_STRING_FIELD(context);      /*!< For transfers only */
530                 AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
531                 AST_STRING_FIELD(mailbox);          /*!< Mailbox */
532                 AST_STRING_FIELD(mohinterpret);
533                 AST_STRING_FIELD(mohsuggest);
534                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this peer can use to authenticate to us */
535                 /* Suggested caller id if registering */
536                 AST_STRING_FIELD(cid_num);              /*!< Default context (for transfer really) */
537                 AST_STRING_FIELD(cid_name);             /*!< Default context (for transfer really) */
538                 AST_STRING_FIELD(zonetag);              /*!< Time Zone */
539                 AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
540         );
541         struct iax2_codec_pref prefs;
542         struct ast_dnsmgr_entry *dnsmgr;                /*!< DNS refresh manager */
543         struct ast_sockaddr addr;
544         int formats;
545         int sockfd;                                     /*!< Socket to use for transmission */
546         struct ast_sockaddr mask;
547         int adsi;
548         uint64_t flags;
549
550         /* Dynamic Registration fields */
551         struct ast_sockaddr defaddr;                    /*!< Default address if there is one */
552         int authmethods;                                /*!< Authentication methods (IAX_AUTH_*) */
553         int encmethods;                                 /*!< Encryption methods (IAX_ENCRYPT_*) */
554
555         int expire;                                     /*!< Schedule entry for expiry */
556         int expiry;                                     /*!< How soon to expire */
557         iax2_format capability;                         /*!< Capability */
558
559         /* Qualification */
560         int callno;                                     /*!< Call number of POKE request */
561         int pokeexpire;                                 /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
562         int lastms;                                     /*!< How long last response took (in ms), or -1 for no response */
563         int maxms;                                      /*!< Max ms we will accept for the host to be up, 0 to not monitor */
564
565         int pokefreqok;                                 /*!< How often to check if the host is up */
566         int pokefreqnotok;                              /*!< How often to check when the host has been determined to be down */
567         int historicms;                                 /*!< How long recent average responses took */
568         int smoothing;                                  /*!< Sample over how many units to determine historic ms */
569         uint16_t maxcallno;                             /*!< Max call number limit for this peer.  Set on registration */
570
571         struct stasis_subscription *mwi_event_sub;      /*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
572
573         struct ast_acl_list *acl;
574         enum calltoken_peer_enum calltoken_required;    /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
575
576         struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
577 };
578
579 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
580
581 struct iax2_trunk_peer {
582         ast_mutex_t lock;
583         int sockfd;
584         struct ast_sockaddr addr;
585         struct timeval txtrunktime;             /*!< Transmit trunktime */
586         struct timeval rxtrunktime;             /*!< Receive trunktime */
587         struct timeval lasttxtime;              /*!< Last transmitted trunktime */
588         struct timeval trunkact;                /*!< Last trunk activity */
589         unsigned int lastsent;                  /*!< Last sent time */
590         /* Trunk data and length */
591         unsigned char *trunkdata;
592         unsigned int trunkdatalen;
593         unsigned int trunkdataalloc;
594         int trunkmaxmtu;
595         int trunkerror;
596         int calls;
597         AST_LIST_ENTRY(iax2_trunk_peer) list;
598 };
599
600 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
601
602 enum iax_reg_state {
603         REG_STATE_UNREGISTERED = 0,
604         REG_STATE_REGSENT,
605         REG_STATE_AUTHSENT,
606         REG_STATE_REGISTERED,
607         REG_STATE_REJECTED,
608         REG_STATE_TIMEOUT,
609         REG_STATE_NOAUTH
610 };
611
612 enum iax_transfer_state {
613         TRANSFER_NONE = 0,
614         TRANSFER_BEGIN,
615         TRANSFER_READY,
616         TRANSFER_RELEASED,
617         TRANSFER_PASSTHROUGH,
618         TRANSFER_MBEGIN,
619         TRANSFER_MREADY,
620         TRANSFER_MRELEASED,
621         TRANSFER_MPASSTHROUGH,
622         TRANSFER_MEDIA,
623         TRANSFER_MEDIAPASS
624 };
625
626 struct iax2_registry {
627         struct ast_sockaddr addr;               /*!< Who we connect to for registration purposes */
628         char username[80];
629         char secret[80];                        /*!< Password or key name in []'s */
630         int expire;                             /*!< Sched ID of expiration */
631         int refresh;                            /*!< How often to refresh */
632         enum iax_reg_state regstate;
633         int messages;                           /*!< Message count, low 8 bits = new, high 8 bits = old */
634         int callno;                             /*!< Associated call number if applicable */
635         struct ast_sockaddr us;                 /*!< Who the server thinks we are */
636         struct ast_dnsmgr_entry *dnsmgr;        /*!< DNS refresh manager */
637         AST_LIST_ENTRY(iax2_registry) entry;
638 };
639
640 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
641
642 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
643 #define MIN_RETRY_TIME          100
644 #define MAX_RETRY_TIME          10000
645
646 #define MAX_JITTER_BUFFER       50
647 #define MIN_JITTER_BUFFER       10
648
649 #define DEFAULT_TRUNKDATA       640 * 10        /*!< 40ms, uncompressed linear * 10 channels */
650
651 #define MAX_TIMESTAMP_SKEW      160             /*!< maximum difference between actual and predicted ts for sending */
652
653 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
654 #define TS_GAP_FOR_JB_RESYNC    5000
655
656 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
657 #define MARK_IAX_SUBCLASS_TX    0x8000
658
659 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
660 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
661 static int iaxdynamicthreadcount = 0;
662 static int iaxdynamicthreadnum = 0;
663 static int iaxactivethreadcount = 0;
664
665 struct iax_rr {
666         int jitter;
667         int losspct;
668         int losscnt;
669         int packets;
670         int delay;
671         int dropped;
672         int ooo;
673 };
674
675 struct iax2_pvt_ref;
676
677 /* We use the high order bit as the validated flag, and the lower 15 as the
678  * actual call number */
679 typedef uint16_t callno_entry;
680
681 struct chan_iax2_pvt {
682         /*! Socket to send/receive on for this call */
683         int sockfd;
684         /*! ast_callid bound to dialog */
685         struct ast_callid *callid;
686         /*! Last received voice format */
687         iax2_format voiceformat;
688         /*! Last received video format */
689         iax2_format videoformat;
690         /*! Last sent voice format */
691         iax2_format svoiceformat;
692         /*! Last sent video format */
693         iax2_format svideoformat;
694         /*! What we are capable of sending */
695         iax2_format capability;
696         /*! Last received timestamp */
697         unsigned int last;
698         /*! Last sent timestamp - never send the same timestamp twice in a single call */
699         unsigned int lastsent;
700         /*! Timestamp of the last video frame sent */
701         unsigned int lastvsent;
702         /*! Next outgoing timestamp if everything is good */
703         unsigned int nextpred;
704         /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
705         int first_iax_message;
706         /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
707         int last_iax_message;
708         /*! True if the last voice we transmitted was not silence/CNG */
709         unsigned int notsilenttx:1;
710         /*! Ping time */
711         unsigned int pingtime;
712         /*! Max time for initial response */
713         int maxtime;
714         /*! Peer Address */
715         struct ast_sockaddr addr;
716         /*! Actual used codec preferences */
717         struct iax2_codec_pref prefs;
718         /*! Requested codec preferences */
719         struct iax2_codec_pref rprefs;
720         /*! Our call number */
721         unsigned short callno;
722         /*! Our callno_entry entry */
723         callno_entry callno_entry;
724         /*! Peer callno */
725         unsigned short peercallno;
726         /*! Negotiated format, this is only used to remember what format was
727             chosen for an unauthenticated call so that the channel can get
728             created later using the right format */
729         iax2_format chosenformat;
730         /*! Peer selected format */
731         iax2_format peerformat;
732         /*! Peer capability */
733         iax2_format peercapability;
734         /*! timeval that we base our transmission on */
735         struct timeval offset;
736         /*! timeval that we base our delivery on */
737         struct timeval rxcore;
738         /*! The jitterbuffer */
739         jitterbuf *jb;
740         /*! active jb read scheduler id */
741         int jbid;
742         /*! LAG */
743         int lag;
744         /*! Error, as discovered by the manager */
745         int error;
746         /*! Owner if we have one */
747         struct ast_channel *owner;
748         /*! What's our state? */
749         struct ast_flags state;
750         /*! Expiry (optional) */
751         int expiry;
752         /*! Next outgoing sequence number */
753         unsigned char oseqno;
754         /*! Next sequence number they have not yet acknowledged */
755         unsigned char rseqno;
756         /*! Next incoming sequence number */
757         unsigned char iseqno;
758         /*! Last incoming sequence number we have acknowledged */
759         unsigned char aseqno;
760
761         AST_DECLARE_STRING_FIELDS(
762                 /*! Peer name */
763                 AST_STRING_FIELD(peer);
764                 /*! Default Context */
765                 AST_STRING_FIELD(context);
766                 /*! Caller ID if available */
767                 AST_STRING_FIELD(cid_num);
768                 AST_STRING_FIELD(cid_name);
769                 /*! Hidden Caller ID (i.e. ANI) if appropriate */
770                 AST_STRING_FIELD(ani);
771                 /*! DNID */
772                 AST_STRING_FIELD(dnid);
773                 /*! RDNIS */
774                 AST_STRING_FIELD(rdnis);
775                 /*! Requested Extension */
776                 AST_STRING_FIELD(exten);
777                 /*! Expected Username */
778                 AST_STRING_FIELD(username);
779                 /*! Expected Secret */
780                 AST_STRING_FIELD(secret);
781                 /*! MD5 challenge */
782                 AST_STRING_FIELD(challenge);
783                 /*! Public keys permitted keys for incoming authentication */
784                 AST_STRING_FIELD(inkeys);
785                 /*! Private key for outgoing authentication */
786                 AST_STRING_FIELD(outkey);
787                 /*! Preferred language */
788                 AST_STRING_FIELD(language);
789                 /*! Hostname/peername for naming purposes */
790                 AST_STRING_FIELD(host);
791
792                 AST_STRING_FIELD(dproot);
793                 AST_STRING_FIELD(accountcode);
794                 AST_STRING_FIELD(mohinterpret);
795                 AST_STRING_FIELD(mohsuggest);
796                 /*! received OSP token */
797                 AST_STRING_FIELD(osptoken);
798                 /*! Default parkinglot */
799                 AST_STRING_FIELD(parkinglot);
800         );
801         /*! AUTHREJ all AUTHREP frames */
802         int authrej;
803         /*! permitted authentication methods */
804         int authmethods;
805         /*! permitted encryption methods */
806         int encmethods;
807         /*! Encryption AES-128 Key */
808         ast_aes_encrypt_key ecx;
809         /*! Decryption AES-128 Key corresponding to ecx */
810         ast_aes_decrypt_key mydcx;
811         /*! Decryption AES-128 Key used to decrypt peer frames */
812         ast_aes_decrypt_key dcx;
813         /*! scheduler id associated with iax_key_rotate
814          * for encrypted calls*/
815         int keyrotateid;
816         /*! 32 bytes of semi-random data */
817         unsigned char semirand[32];
818         /*! Associated registry */
819         struct iax2_registry *reg;
820         /*! Associated peer for poking */
821         struct iax2_peer *peerpoke;
822         /*! IAX_ flags */
823         uint64_t flags;
824         int adsi;
825
826         /*! Transferring status */
827         enum iax_transfer_state transferring;
828         /*! Transfer identifier */
829         int transferid;
830         /*! Who we are IAX transferring to */
831         struct ast_sockaddr transfer;
832         /*! What's the new call number for the transfer */
833         unsigned short transfercallno;
834         /*! Transfer encrypt AES-128 Key */
835         ast_aes_encrypt_key tdcx;
836
837         /*! Status of knowledge of peer ADSI capability */
838         int peeradsicpe;
839
840         /*! Callno of native bridge peer. (Valid if nonzero) */
841         unsigned short bridgecallno;
842
843         int pingid;                     /*!< Transmit PING request */
844         int lagid;                      /*!< Retransmit lag request */
845         int autoid;                     /*!< Auto hangup for Dialplan requestor */
846         int authid;                     /*!< Authentication rejection ID */
847         int authfail;                   /*!< Reason to report failure */
848         int initid;                     /*!< Initial peer auto-congest ID (based on qualified peers) */
849         int calling_ton;
850         int calling_tns;
851         int calling_pres;
852         int amaflags;
853         AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
854         /*! variables inherited from the user definition */
855         struct ast_variable *vars;
856         /*! variables transmitted in a NEW packet */
857         struct ast_variable *iaxvars;
858         /*! last received remote rr */
859         struct iax_rr remote_rr;
860         /*! Current base time: (just for stats) */
861         int min;
862         /*! Dropped frame count: (just for stats) */
863         int frames_dropped;
864         /*! received frame count: (just for stats) */
865         int frames_received;
866         /*! num bytes used for calltoken ie, even an empty ie should contain 2 */
867         unsigned char calltoken_ie_len;
868         /*! hold all signaling frames from the pbx thread until we have a destination callno */
869         char hold_signaling;
870         /*! frame queue for signaling frames from pbx thread waiting for destination callno */
871         AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
872 };
873
874 struct signaling_queue_entry {
875         struct ast_frame f;
876         AST_LIST_ENTRY(signaling_queue_entry) next;
877 };
878
879 enum callno_type {
880         CALLNO_TYPE_NORMAL,
881         CALLNO_TYPE_TRUNK,
882 };
883
884 #define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
885 #define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
886
887 #define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
888 #define CALLNO_ENTRY_IS_VALIDATED(a)  ((a) & 0x8000)
889 #define CALLNO_ENTRY_GET_CALLNO(a)    ((a) & 0x7FFF)
890
891 struct call_number_pool {
892         size_t capacity;
893         size_t available;
894         callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
895 };
896
897 AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
898
899 /*! table of available call numbers */
900 static struct call_number_pool callno_pool;
901
902 /*! table of available trunk call numbers */
903 static struct call_number_pool callno_pool_trunk;
904
905 /*!
906  * \brief a list of frames that may need to be retransmitted
907  *
908  * \note The contents of this list do not need to be explicitly destroyed
909  * on module unload.  This is because all active calls are destroyed, and
910  * all frames in this queue will get destroyed as a part of that process.
911  *
912  * \note Contents protected by the iaxsl[] locks
913  */
914 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
915
916 static struct ast_taskprocessor *transmit_processor;
917
918 static int randomcalltokendata;
919
920 static const time_t MAX_CALLTOKEN_DELAY = 10;
921
922 /*!
923  * This module will get much higher performance when doing a lot of
924  * user and peer lookups if the number of buckets is increased from 1.
925  * However, to maintain old behavior for Asterisk 1.4, these are set to
926  * 1 by default.  When using multiple buckets, search order through these
927  * containers is considered random, so you will not be able to depend on
928  * the order the entires are specified in iax.conf for matching order. */
929 #ifdef LOW_MEMORY
930 #define MAX_PEER_BUCKETS 17
931 #else
932 #define MAX_PEER_BUCKETS 563
933 #endif
934 static struct ao2_container *peers;
935
936 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
937 static struct ao2_container *users;
938
939 /*! Table containing peercnt objects for every ip address consuming a callno */
940 static struct ao2_container *peercnts;
941
942 /*! Table containing custom callno limit rules for a range of ip addresses. */
943 static struct ao2_container *callno_limits;
944
945 /*! Table containing ip addresses not requiring calltoken validation */
946 static struct ao2_container *calltoken_ignores;
947
948 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
949
950 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
951
952 static uint16_t global_maxcallno;
953
954 /*! Total num of call numbers allowed to be allocated without calltoken validation */
955 static uint16_t global_maxcallno_nonval;
956
957 static uint16_t total_nonval_callno_used = 0;
958
959 /*! peer connection private, keeps track of all the call numbers
960  *  consumed by a single ip address */
961 struct peercnt {
962         /*! ip address consuming call numbers */
963         struct ast_sockaddr addr;
964         /*! Number of call numbers currently used by this ip address */
965         uint16_t cur;
966         /*! Max call numbers allowed for this ip address */
967         uint16_t limit;
968         /*! Specifies whether limit is set by a registration or not, if so normal
969          *  limit setting rules do not apply to this address. */
970         unsigned char reg;
971 };
972
973 /*! used by both callno_limits and calltoken_ignores containers */
974 struct addr_range {
975         /*! ip address range for custom callno limit rule */
976         struct ast_ha ha;
977         /*! callno limit for this ip address range, only used in callno_limits container */
978         uint16_t limit;
979         /*! delete me marker for reloads */
980         unsigned char delme;
981 };
982
983 enum {
984         /*! Extension exists */
985         CACHE_FLAG_EXISTS      = (1 << 0),
986         /*! Extension is nonexistent */
987         CACHE_FLAG_NONEXISTENT = (1 << 1),
988         /*! Extension can exist */
989         CACHE_FLAG_CANEXIST    = (1 << 2),
990         /*! Waiting to hear back response */
991         CACHE_FLAG_PENDING     = (1 << 3),
992         /*! Timed out */
993         CACHE_FLAG_TIMEOUT     = (1 << 4),
994         /*! Request transmitted */
995         CACHE_FLAG_TRANSMITTED = (1 << 5),
996         /*! Timeout */
997         CACHE_FLAG_UNKNOWN     = (1 << 6),
998         /*! Matchmore */
999         CACHE_FLAG_MATCHMORE   = (1 << 7),
1000 };
1001
1002 struct iax2_dpcache {
1003         char peercontext[AST_MAX_CONTEXT];
1004         char exten[AST_MAX_EXTENSION];
1005         struct timeval orig;
1006         struct timeval expiry;
1007         int flags;
1008         unsigned short callno;
1009         int waiters[256];
1010         AST_LIST_ENTRY(iax2_dpcache) cache_list;
1011         AST_LIST_ENTRY(iax2_dpcache) peer_list;
1012 };
1013
1014 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1015
1016 static void reg_source_db(struct iax2_peer *p);
1017 static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1018 static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1019
1020 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1021 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1022 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1023
1024 enum iax2_thread_iostate {
1025         IAX_IOSTATE_IDLE,
1026         IAX_IOSTATE_READY,
1027         IAX_IOSTATE_PROCESSING,
1028         IAX_IOSTATE_SCHEDREADY,
1029 };
1030
1031 enum iax2_thread_type {
1032         IAX_THREAD_TYPE_POOL,
1033         IAX_THREAD_TYPE_DYNAMIC,
1034 };
1035
1036 struct iax2_pkt_buf {
1037         AST_LIST_ENTRY(iax2_pkt_buf) entry;
1038         size_t len;
1039         unsigned char buf[1];
1040 };
1041
1042 struct iax2_thread {
1043         AST_LIST_ENTRY(iax2_thread) list;
1044         enum iax2_thread_type type;
1045         enum iax2_thread_iostate iostate;
1046 #ifdef SCHED_MULTITHREADED
1047         void (*schedfunc)(const void *);
1048         const void *scheddata;
1049 #endif
1050 #ifdef DEBUG_SCHED_MULTITHREAD
1051         char curfunc[80];
1052 #endif
1053         int actions;
1054         pthread_t threadid;
1055         int threadnum;
1056         struct ast_sockaddr ioaddr;
1057         unsigned char readbuf[4096];
1058         unsigned char *buf;
1059         ssize_t buf_len;
1060         size_t buf_size;
1061         int iofd;
1062         time_t checktime;
1063         ast_mutex_t lock;
1064         ast_cond_t cond;
1065         ast_mutex_t init_lock;
1066         ast_cond_t init_cond;
1067         /*! if this thread is processing a full frame,
1068           some information about that frame will be stored
1069           here, so we can avoid dispatching any more full
1070           frames for that callno to other threads */
1071         struct {
1072                 unsigned short callno;
1073                 struct ast_sockaddr addr;
1074                 unsigned char type;
1075                 unsigned char csub;
1076         } ffinfo;
1077         /*! Queued up full frames for processing.  If more full frames arrive for
1078          *  a call which this thread is already processing a full frame for, they
1079          *  are queued up here. */
1080         AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1081         unsigned char stop;
1082 };
1083
1084 /* Thread lists */
1085 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1086 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1087 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1088
1089 static void *iax2_process_thread(void *data);
1090 static void iax2_destroy(int callno);
1091
1092 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1093 {
1094         ast_mutex_lock(lock);
1095         ast_cond_signal(cond);
1096         ast_mutex_unlock(lock);
1097 }
1098
1099 /*!
1100  * \brief an array of iax2 pvt structures
1101  *
1102  * The container for active chan_iax2_pvt structures is implemented as an
1103  * array for extremely quick direct access to the correct pvt structure
1104  * based on the local call number.  The local call number is used as the
1105  * index into the array where the associated pvt structure is stored.
1106  */
1107 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1108
1109 static struct ast_callid *iax_pvt_callid_get(int callno)
1110 {
1111         if (iaxs[callno]->callid) {
1112                 return ast_callid_ref(iaxs[callno]->callid);
1113         }
1114         return NULL;
1115 }
1116
1117 static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1118 {
1119         if (iaxs[callno]->callid) {
1120                 ast_callid_unref(iaxs[callno]->callid);
1121         }
1122         ast_callid_ref(callid);
1123         iaxs[callno]->callid = callid;
1124 }
1125
1126 static void iax_pvt_callid_new(int callno)
1127 {
1128         struct ast_callid *callid = ast_create_callid();
1129         char buffer[AST_CALLID_BUFFER_LENGTH];
1130         ast_callid_strnprint(buffer, sizeof(buffer), callid);
1131         iax_pvt_callid_set(callno, callid);
1132         ast_callid_unref(callid);
1133 }
1134
1135 /*!
1136  * \brief Another container of iax2_pvt structures
1137  *
1138  * Active IAX2 pvt structs are also stored in this container, if they are a part
1139  * of an active call where we know the remote side's call number.  The reason
1140  * for this is that incoming media frames do not contain our call number.  So,
1141  * instead of having to iterate the entire iaxs array, we use this container to
1142  * look up calls where the remote side is using a given call number.
1143  */
1144 static struct ao2_container *iax_peercallno_pvts;
1145
1146 /*!
1147  * \brief chan_iax2_pvt structure locks
1148  *
1149  * These locks are used when accessing a pvt structure in the iaxs array.
1150  * The index used here is the same as used in the iaxs array.  It is the
1151  * local call number for the associated pvt struct.
1152  */
1153 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1154
1155 /*!
1156  *  * \brief Another container of iax2_pvt structures
1157  *
1158  *  Active IAX2 pvt stucts used during transfering a call are stored here.
1159  */
1160 static struct ao2_container *iax_transfercallno_pvts;
1161
1162 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
1163    but keeps the division between trunked and non-trunked better. */
1164 #define TRUNK_CALL_START        (IAX_MAX_CALLS / 2)
1165
1166 /* Debug routines... */
1167 static struct ast_sockaddr debugaddr;
1168
1169 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1170 {
1171         if (iaxdebug ||
1172             (addr && !ast_sockaddr_isnull(&debugaddr) &&
1173                 (!ast_sockaddr_port(&debugaddr) ||
1174                   ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1175                   !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1176
1177                 if (iaxdebug) {
1178                         iax_showframe(f, fhi, rx, addr, datalen);
1179                 } else {
1180                         iaxdebug = 1;
1181                         iax_showframe(f, fhi, rx, addr, datalen);
1182                         iaxdebug = 0;
1183                 }
1184         }
1185 }
1186
1187 static void iax_debug_output(const char *data)
1188 {
1189         if (iaxdebug)
1190                 ast_verbose("%s", data);
1191 }
1192
1193 static void iax_error_output(const char *data)
1194 {
1195         ast_log(LOG_WARNING, "%s", data);
1196 }
1197
1198 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1199 {
1200         va_list args;
1201         char buf[1024];
1202
1203         va_start(args, fmt);
1204         vsnprintf(buf, sizeof(buf), fmt, args);
1205         va_end(args);
1206
1207         ast_log(LOG_ERROR, "%s", buf);
1208 }
1209
1210 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1211 {
1212         va_list args;
1213         char buf[1024];
1214
1215         va_start(args, fmt);
1216         vsnprintf(buf, sizeof(buf), fmt, args);
1217         va_end(args);
1218
1219         ast_log(LOG_WARNING, "%s", buf);
1220 }
1221
1222 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1223 {
1224         va_list args;
1225         char buf[1024];
1226
1227         va_start(args, fmt);
1228         vsnprintf(buf, sizeof(buf), fmt, args);
1229         va_end(args);
1230
1231         ast_verbose("%s", buf);
1232 }
1233
1234 static int expire_registry(const void *data);
1235 static int iax2_answer(struct ast_channel *c);
1236 static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1237 static int iax2_devicestate(const char *data);
1238 static int iax2_digit_begin(struct ast_channel *c, char digit);
1239 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1240 static int iax2_do_register(struct iax2_registry *reg);
1241 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1242 static int iax2_hangup(struct ast_channel *c);
1243 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1244 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1245 static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1246 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1247 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1248 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1249 static int iax2_sendtext(struct ast_channel *c, const char *text);
1250 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1251 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1252 static int iax2_transfer(struct ast_channel *c, const char *dest);
1253 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1254 static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1255
1256 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1257 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1258 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1259 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1260 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1261 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1262 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);
1263 static struct ast_frame *iax2_read(struct ast_channel *c);
1264 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1265 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1266 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1267 static void *iax2_dup_variable_datastore(void *);
1268 static void prune_peers(void);
1269 static void prune_users(void);
1270 static void iax2_free_variable_datastore(void *);
1271
1272 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1273 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1274 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1275 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1276 static void build_rand_pad(unsigned char *buf, ssize_t len);
1277 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1278 static int replace_callno(const void *obj);
1279 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1280 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1281 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1282
1283 static struct ast_channel_tech iax2_tech = {
1284         .type = "IAX2",
1285         .description = tdesc,
1286         .properties = AST_CHAN_TP_WANTSJITTER,
1287         .requester = iax2_request,
1288         .devicestate = iax2_devicestate,
1289         .send_digit_begin = iax2_digit_begin,
1290         .send_digit_end = iax2_digit_end,
1291         .send_text = iax2_sendtext,
1292         .send_image = iax2_sendimage,
1293         .send_html = iax2_sendhtml,
1294         .call = iax2_call,
1295         .hangup = iax2_hangup,
1296         .answer = iax2_answer,
1297         .read = iax2_read,
1298         .write = iax2_write,
1299         .write_video = iax2_write,
1300         .indicate = iax2_indicate,
1301         .setoption = iax2_setoption,
1302         .queryoption = iax2_queryoption,
1303         .transfer = iax2_transfer,
1304         .fixup = iax2_fixup,
1305         .func_channel_read = acf_channel_read,
1306 };
1307
1308 /*!
1309  * \internal
1310  * \brief Obtain the owner channel lock if the owner exists.
1311  *
1312  * \param callno IAX2 call id.
1313  *
1314  * \note Assumes the iaxsl[callno] lock is already obtained.
1315  *
1316  * \note
1317  * IMPORTANT NOTE!!!  Any time this function is used, even if
1318  * iaxs[callno] was valid before calling it, it may no longer be
1319  * valid after calling it.  This function may unlock and lock
1320  * the mutex associated with this callno, meaning that another
1321  * thread may grab it and destroy the call.
1322  *
1323  * \return Nothing
1324  */
1325 static void iax2_lock_owner(int callno)
1326 {
1327         for (;;) {
1328                 if (!iaxs[callno] || !iaxs[callno]->owner) {
1329                         /* There is no owner lock to get. */
1330                         break;
1331                 }
1332                 if (!ast_channel_trylock(iaxs[callno]->owner)) {
1333                         /* We got the lock */
1334                         break;
1335                 }
1336                 /* Avoid deadlock by pausing and trying again */
1337                 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1338         }
1339 }
1340
1341 /*!
1342  * \internal
1343  * \brief Check if a control subtype is allowed on the wire.
1344  *
1345  * \param subtype Control frame subtype to check if allowed to/from the wire.
1346  *
1347  * \retval non-zero if allowed.
1348  */
1349 static int iax2_is_control_frame_allowed(int subtype)
1350 {
1351         enum ast_control_frame_type control = subtype;
1352         int is_allowed;
1353
1354         /*
1355          * Note: If we compare the enumeration type, which does not have any
1356          * negative constants, the compiler may optimize this code away.
1357          * Therefore, we must perform an integer comparison here.
1358          */
1359         if (subtype == -1) {
1360                 return -1;
1361         }
1362
1363         /* Default to not allowing control frames to pass. */
1364         is_allowed = 0;
1365
1366         /*
1367          * The switch default is not present in order to take advantage
1368          * of the compiler complaining of a missing enum case.
1369          */
1370         switch (control) {
1371         /*
1372          * These control frames make sense to send/receive across the link.
1373          */
1374         case AST_CONTROL_HANGUP:
1375         case AST_CONTROL_RING:
1376         case AST_CONTROL_RINGING:
1377         case AST_CONTROL_ANSWER:
1378         case AST_CONTROL_BUSY:
1379         case AST_CONTROL_TAKEOFFHOOK:
1380         case AST_CONTROL_OFFHOOK:
1381         case AST_CONTROL_CONGESTION:
1382         case AST_CONTROL_FLASH:
1383         case AST_CONTROL_WINK:
1384         case AST_CONTROL_OPTION:
1385         case AST_CONTROL_RADIO_KEY:
1386         case AST_CONTROL_RADIO_UNKEY:
1387         case AST_CONTROL_PROGRESS:
1388         case AST_CONTROL_PROCEEDING:
1389         case AST_CONTROL_HOLD:
1390         case AST_CONTROL_UNHOLD:
1391         case AST_CONTROL_VIDUPDATE:
1392         case AST_CONTROL_CONNECTED_LINE:
1393         case AST_CONTROL_REDIRECTING:
1394         case AST_CONTROL_T38_PARAMETERS:
1395         case AST_CONTROL_AOC:
1396         case AST_CONTROL_INCOMPLETE:
1397         case AST_CONTROL_MCID:
1398                 is_allowed = -1;
1399                 break;
1400
1401         /*
1402          * These control frames do not make sense to send/receive across the link.
1403          */
1404         case _XXX_AST_CONTROL_T38:
1405                 /* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1406         case AST_CONTROL_SRCUPDATE:
1407                 /* Across an IAX link the source is still the same. */
1408         case AST_CONTROL_TRANSFER:
1409                 /* A success/fail status report from calling ast_transfer() on this machine. */
1410         case AST_CONTROL_CC:
1411                 /* The payload contains pointers that are valid for the sending machine only. */
1412         case AST_CONTROL_SRCCHANGE:
1413                 /* Across an IAX link the source is still the same. */
1414         case AST_CONTROL_READ_ACTION:
1415                 /* The action can only be done by the sending machine. */
1416         case AST_CONTROL_END_OF_Q:
1417                 /* This frame would cause the call to unexpectedly hangup. */
1418         case AST_CONTROL_UPDATE_RTP_PEER:
1419                 /* Only meaningful across a bridge on this machine for direct-media exchange. */
1420         case AST_CONTROL_PVT_CAUSE_CODE:
1421                 /* Intended only for the sending machine's local channel structure. */
1422         case AST_CONTROL_STREAM_STOP:
1423         case AST_CONTROL_STREAM_SUSPEND:
1424         case AST_CONTROL_STREAM_RESTART:
1425         case AST_CONTROL_STREAM_REVERSE:
1426         case AST_CONTROL_STREAM_FORWARD:
1427                 /* None of these playback stream control frames should go across the link. */
1428         case AST_CONTROL_RECORD_CANCEL:
1429         case AST_CONTROL_RECORD_STOP:
1430         case AST_CONTROL_RECORD_SUSPEND:
1431         case AST_CONTROL_RECORD_MUTE:
1432                 /* None of these media recording control frames should go across the link. */
1433                 break;
1434         }
1435         return is_allowed;
1436 }
1437
1438 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
1439 {
1440         /* The MWI subscriptions exist just so the core knows we care about those
1441          * mailboxes.  However, we just grab the events out of the cache when it
1442          * is time to send MWI, since it is only sent with a REGACK. */
1443 }
1444
1445 static void network_change_stasis_subscribe(void)
1446 {
1447         if (!network_change_sub) {
1448                 network_change_sub = stasis_subscribe(ast_system_topic(),
1449                         network_change_stasis_cb, NULL);
1450         }
1451 }
1452
1453 static void network_change_stasis_unsubscribe(void)
1454 {
1455         network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1456 }
1457
1458 static void acl_change_stasis_subscribe(void)
1459 {
1460         if (!acl_change_sub) {
1461                 acl_change_sub = stasis_subscribe(ast_security_topic(),
1462                         acl_change_stasis_cb, NULL);
1463         }
1464 }
1465
1466 static void acl_change_stasis_unsubscribe(void)
1467 {
1468         acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1469 }
1470
1471 static int network_change_sched_cb(const void *data)
1472 {
1473         struct iax2_registry *reg;
1474         network_change_sched_id = -1;
1475         AST_LIST_LOCK(&registrations);
1476         AST_LIST_TRAVERSE(&registrations, reg, entry) {
1477                 iax2_do_register(reg);
1478         }
1479         AST_LIST_UNLOCK(&registrations);
1480
1481         return 0;
1482 }
1483
1484 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1485         struct stasis_message *message)
1486 {
1487         /* This callback is only concerned with network change messages from the system topic. */
1488         if (stasis_message_type(message) != ast_network_change_type()) {
1489                 return;
1490         }
1491
1492         ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1493         if (network_change_sched_id == -1) {
1494                 network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1495         }
1496 }
1497
1498 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1499         struct stasis_message *message)
1500 {
1501         if (stasis_message_type(message) != ast_named_acl_change_type()) {
1502                 return;
1503         }
1504
1505         ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1506         reload_config(1);
1507 }
1508
1509 static const struct ast_datastore_info iax2_variable_datastore_info = {
1510         .type = "IAX2_VARIABLE",
1511         .duplicate = iax2_dup_variable_datastore,
1512         .destroy = iax2_free_variable_datastore,
1513 };
1514
1515 static void *iax2_dup_variable_datastore(void *old)
1516 {
1517         AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1518         struct ast_var_t *oldvar, *newvar;
1519
1520         newlist = ast_calloc(sizeof(*newlist), 1);
1521         if (!newlist) {
1522                 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1523                 return NULL;
1524         }
1525
1526         AST_LIST_HEAD_INIT(newlist);
1527         AST_LIST_LOCK(oldlist);
1528         AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1529                 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1530                 if (newvar)
1531                         AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1532                 else
1533                         ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1534         }
1535         AST_LIST_UNLOCK(oldlist);
1536         return newlist;
1537 }
1538
1539 static void iax2_free_variable_datastore(void *old)
1540 {
1541         AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1542         struct ast_var_t *oldvar;
1543
1544         AST_LIST_LOCK(oldlist);
1545         while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1546                 ast_free(oldvar);
1547         }
1548         AST_LIST_UNLOCK(oldlist);
1549         AST_LIST_HEAD_DESTROY(oldlist);
1550         ast_free(oldlist);
1551 }
1552
1553
1554 /* WARNING: insert_idle_thread should only ever be called within the
1555  * context of an iax2_process_thread() thread.
1556  */
1557 static void insert_idle_thread(struct iax2_thread *thread)
1558 {
1559         if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1560                 AST_LIST_LOCK(&dynamic_list);
1561                 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1562                 AST_LIST_UNLOCK(&dynamic_list);
1563         } else {
1564                 AST_LIST_LOCK(&idle_list);
1565                 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1566                 AST_LIST_UNLOCK(&idle_list);
1567         }
1568
1569         return;
1570 }
1571
1572 static struct iax2_thread *find_idle_thread(void)
1573 {
1574         struct iax2_thread *thread = NULL;
1575
1576         /* Pop the head of the idle list off */
1577         AST_LIST_LOCK(&idle_list);
1578         thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1579         AST_LIST_UNLOCK(&idle_list);
1580
1581         /* If we popped a thread off the idle list, just return it */
1582         if (thread) {
1583                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1584                 return thread;
1585         }
1586
1587         /* Pop the head of the dynamic list off */
1588         AST_LIST_LOCK(&dynamic_list);
1589         thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1590         AST_LIST_UNLOCK(&dynamic_list);
1591
1592         /* If we popped a thread off the dynamic list, just return it */
1593         if (thread) {
1594                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1595                 return thread;
1596         }
1597
1598         /* If we can't create a new dynamic thread for any reason, return no thread at all */
1599         if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1600                 return NULL;
1601
1602         /* Set default values */
1603         ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1604         thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1605         thread->type = IAX_THREAD_TYPE_DYNAMIC;
1606
1607         /* Initialize lock and condition */
1608         ast_mutex_init(&thread->lock);
1609         ast_cond_init(&thread->cond, NULL);
1610         ast_mutex_init(&thread->init_lock);
1611         ast_cond_init(&thread->init_cond, NULL);
1612         ast_mutex_lock(&thread->init_lock);
1613
1614         /* Create thread and send it on it's way */
1615         if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1616                 ast_cond_destroy(&thread->cond);
1617                 ast_mutex_destroy(&thread->lock);
1618                 ast_mutex_unlock(&thread->init_lock);
1619                 ast_cond_destroy(&thread->init_cond);
1620                 ast_mutex_destroy(&thread->init_lock);
1621                 ast_free(thread);
1622                 return NULL;
1623         }
1624
1625         /* this thread is not processing a full frame (since it is idle),
1626            so ensure that the field for the full frame call number is empty */
1627         memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1628
1629         /* Wait for the thread to be ready before returning it to the caller */
1630         ast_cond_wait(&thread->init_cond, &thread->init_lock);
1631
1632         /* Done with init_lock */
1633         ast_mutex_unlock(&thread->init_lock);
1634
1635         return thread;
1636 }
1637
1638 #ifdef SCHED_MULTITHREADED
1639 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1640 {
1641         struct iax2_thread *thread;
1642         static time_t lasterror;
1643         time_t t;
1644
1645         thread = find_idle_thread();
1646         if (thread != NULL) {
1647                 thread->schedfunc = func;
1648                 thread->scheddata = data;
1649                 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1650 #ifdef DEBUG_SCHED_MULTITHREAD
1651                 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1652 #endif
1653                 signal_condition(&thread->lock, &thread->cond);
1654                 return 0;
1655         }
1656         time(&t);
1657         if (t != lasterror) {
1658                 lasterror = t;
1659                 ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1660         }
1661
1662         return -1;
1663 }
1664 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1665 #endif
1666
1667 static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1668                 ast_sched_cb callback, const void *data)
1669 {
1670         return ast_sched_replace(id, con, when, callback, data);
1671 }
1672
1673 static int iax2_sched_add(struct ast_sched_context *con, int when,
1674                 ast_sched_cb callback, const void *data)
1675 {
1676         return ast_sched_add(con, when, callback, data);
1677 }
1678
1679 static int send_ping(const void *data);
1680
1681 static void __send_ping(const void *data)
1682 {
1683         int callno = (long) data;
1684
1685         ast_mutex_lock(&iaxsl[callno]);
1686
1687         if (iaxs[callno]) {
1688                 if (iaxs[callno]->peercallno) {
1689                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1690                         if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1691                                 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1692                         }
1693                 }
1694         } else {
1695                 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1696         }
1697
1698         ast_mutex_unlock(&iaxsl[callno]);
1699 }
1700
1701 static int send_ping(const void *data)
1702 {
1703         int callno = (long) data;
1704         ast_mutex_lock(&iaxsl[callno]);
1705         if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1706                 iaxs[callno]->pingid = -1;
1707         }
1708         ast_mutex_unlock(&iaxsl[callno]);
1709
1710 #ifdef SCHED_MULTITHREADED
1711         if (schedule_action(__send_ping, data))
1712 #endif
1713                 __send_ping(data);
1714
1715         return 0;
1716 }
1717
1718 static void encmethods_to_str(int e, struct ast_str **buf)
1719 {
1720         ast_str_set(buf, 0, "(");
1721         if (e & IAX_ENCRYPT_AES128) {
1722                 ast_str_append(buf, 0, "aes128");
1723         }
1724         if (e & IAX_ENCRYPT_KEYROTATE) {
1725                 ast_str_append(buf, 0, ",keyrotate");
1726         }
1727         if (ast_str_strlen(*buf) > 1) {
1728                 ast_str_append(buf, 0, ")");
1729         } else {
1730                 ast_str_set(buf, 0, "No");
1731         }
1732 }
1733
1734 static int get_encrypt_methods(const char *s)
1735 {
1736         int e;
1737         if (!strcasecmp(s, "aes128"))
1738                 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1739         else if (ast_true(s))
1740                 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1741         else
1742                 e = 0;
1743         return e;
1744 }
1745
1746 static int send_lagrq(const void *data);
1747
1748 static void __send_lagrq(const void *data)
1749 {
1750         int callno = (long) data;
1751
1752         ast_mutex_lock(&iaxsl[callno]);
1753
1754         if (iaxs[callno]) {
1755                 if (iaxs[callno]->peercallno) {
1756                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1757                         if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1758                                 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1759                         }
1760                 }
1761         } else {
1762                 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1763         }
1764
1765         ast_mutex_unlock(&iaxsl[callno]);
1766 }
1767
1768 static int send_lagrq(const void *data)
1769 {
1770         int callno = (long) data;
1771         ast_mutex_lock(&iaxsl[callno]);
1772         if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1773                 iaxs[callno]->lagid = -1;
1774         }
1775         ast_mutex_unlock(&iaxsl[callno]);
1776
1777 #ifdef SCHED_MULTITHREADED
1778         if (schedule_action(__send_lagrq, data))
1779 #endif
1780                 __send_lagrq(data);
1781         return 0;
1782 }
1783
1784 static unsigned char compress_subclass(iax2_format subclass)
1785 {
1786         int x;
1787         int power=-1;
1788         /* If it's 64 or smaller, just return it */
1789         if (subclass < IAX_FLAG_SC_LOG)
1790                 return subclass;
1791         /* Otherwise find its power */
1792         for (x = 0; x < IAX_MAX_SHIFT; x++) {
1793                 if (subclass & (1LL << x)) {
1794                         if (power > -1) {
1795                                 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1796                                 return 0;
1797                         } else
1798                                 power = x;
1799                 }
1800         }
1801         return power | IAX_FLAG_SC_LOG;
1802 }
1803
1804 static iax2_format uncompress_subclass(unsigned char csub)
1805 {
1806         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1807         if (csub & IAX_FLAG_SC_LOG) {
1808                 /* special case for 'compressed' -1 */
1809                 if (csub == 0xff)
1810                         return -1;
1811                 else
1812                         return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1813         }
1814         else
1815                 return csub;
1816 }
1817
1818 static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats, int find_best)
1819 {
1820         struct ast_format_cap *cap;
1821         struct ast_format *tmpfmt;
1822         iax2_format format = 0;
1823
1824         if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1825                 iax2_format_compatibility_bitfield2cap(formats, cap);
1826                 tmpfmt = ast_format_cap_get_format(cap, 0);
1827                 format = ast_format_compatibility_format2bitfield(tmpfmt);
1828                 ao2_ref(tmpfmt, -1);
1829                 ao2_ref(cap, -1);
1830         }
1831
1832         return format;
1833 }
1834
1835 static iax2_format iax2_best_codec(iax2_format formats)
1836 {
1837         struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1838         struct ast_format *tmpfmt;
1839         iax2_format format;
1840
1841         if (!cap) {
1842                 return 0;
1843         }
1844
1845         iax2_format_compatibility_bitfield2cap(formats, cap);
1846         tmpfmt = ast_format_cap_get_format(cap, 0);
1847         format = ast_format_compatibility_format2bitfield(tmpfmt);
1848         ao2_ref(tmpfmt, -1);
1849         ao2_ref(cap, -1);
1850
1851         return format;
1852 }
1853
1854 const char *iax2_getformatname(iax2_format format)
1855 {
1856         struct ast_format *tmpfmt;
1857
1858         tmpfmt = ast_format_compatibility_bitfield2format(format);
1859         if (!tmpfmt) {
1860                 return "Unknown";
1861         }
1862
1863         return ast_format_get_name(tmpfmt);
1864 }
1865
1866 static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1867 {
1868         struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1869
1870         if (!cap) {
1871                 return "(Nothing)";
1872         }
1873         iax2_format_compatibility_bitfield2cap(format, cap);
1874         ast_format_cap_get_names(cap, codec_buf);
1875         ao2_ref(cap, -1);
1876
1877         return ast_str_buffer(*codec_buf);
1878 }
1879
1880 static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1881 {
1882         int res, i;
1883         struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1884
1885         if (!cap) {
1886                 return 1;
1887         }
1888
1889         /* We want to add the formats to the cap in the preferred order */
1890         for (i = 0; i < IAX2_CODEC_PREF_SIZE; i++) {
1891                 uint64_t pref_as_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[i]);
1892
1893                 if (!pref_as_bitfield) {
1894                         break;
1895                 }
1896
1897                 if (iax2_format_compatibility_bitfield2cap(pref_as_bitfield, cap)) {
1898                         ao2_ref(cap, -1);
1899                         return 1;
1900                 }
1901         }
1902
1903         res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1904         *formats = iax2_format_compatibility_cap2bitfield(cap);
1905
1906         iax2_codec_pref_remove_missing(pref, *formats);
1907
1908         for (i = 0; i < ast_format_cap_count(cap); i++) {
1909                 struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1910                 iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
1911                 ao2_ref(fmt, -1);
1912         }
1913
1914         ao2_ref(cap, -1);
1915
1916         return res;
1917 }
1918
1919 static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1920 {
1921         int res;
1922         struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1923         if (!cap) {
1924                 return -1;
1925         }
1926         iax2_format_compatibility_bitfield2cap(formats, cap);
1927         res = ast_data_add_codecs(root, node_name, cap);
1928         ao2_ref(cap, -1);
1929         return res;
1930 }
1931
1932 /*!
1933  * \note The only member of the peer passed here guaranteed to be set is the name field
1934  */
1935 static int peer_hash_cb(const void *obj, const int flags)
1936 {
1937         const struct iax2_peer *peer = obj;
1938         const char *name = obj;
1939
1940         return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1941 }
1942
1943 /*!
1944  * \note The only member of the peer passed here guaranteed to be set is the name field
1945  */
1946 static int peer_cmp_cb(void *obj, void *arg, int flags)
1947 {
1948         struct iax2_peer *peer = obj, *peer2 = arg;
1949         const char *name = arg;
1950
1951         return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1952                         CMP_MATCH | CMP_STOP : 0;
1953 }
1954
1955 /*!
1956  * \note The only member of the user passed here guaranteed to be set is the name field
1957  */
1958 static int user_hash_cb(const void *obj, const int flags)
1959 {
1960         const struct iax2_user *user = obj;
1961         const char *name = obj;
1962
1963         return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1964 }
1965
1966 /*!
1967  * \note The only member of the user passed here guaranteed to be set is the name field
1968  */
1969 static int user_cmp_cb(void *obj, void *arg, int flags)
1970 {
1971         struct iax2_user *user = obj, *user2 = arg;
1972         const char *name = arg;
1973
1974         return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1975                         CMP_MATCH | CMP_STOP : 0;
1976 }
1977
1978 /*!
1979  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1980  *       so do not call it with a pvt lock held.
1981  */
1982 static struct iax2_peer *find_peer(const char *name, int realtime)
1983 {
1984         struct iax2_peer *peer = NULL;
1985
1986         peer = ao2_find(peers, name, OBJ_KEY);
1987
1988         /* Now go for realtime if applicable */
1989         if (!peer && realtime) {
1990                 peer = realtime_peer(name, NULL);
1991         }
1992         return peer;
1993 }
1994
1995 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1996 {
1997         ao2_ref(peer, +1);
1998         return peer;
1999 }
2000
2001 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2002 {
2003         ao2_ref(peer, -1);
2004         return NULL;
2005 }
2006
2007 static struct iax2_user *find_user(const char *name)
2008 {
2009         return ao2_find(users, name, OBJ_KEY);
2010 }
2011 static inline struct iax2_user *user_ref(struct iax2_user *user)
2012 {
2013         ao2_ref(user, +1);
2014         return user;
2015 }
2016
2017 static inline struct iax2_user *user_unref(struct iax2_user *user)
2018 {
2019         ao2_ref(user, -1);
2020         return NULL;
2021 }
2022
2023 static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2024 {
2025         struct iax2_peer *peer = NULL;
2026         int res = 0;
2027         struct ao2_iterator i;
2028
2029         i = ao2_iterator_init(peers, 0);
2030         while ((peer = ao2_iterator_next(&i))) {
2031
2032                 if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2033                         ast_copy_string(host, peer->name, len);
2034                         peer_unref(peer);
2035                         res = 1;
2036                         break;
2037                 }
2038                 peer_unref(peer);
2039         }
2040         ao2_iterator_destroy(&i);
2041
2042         if (!peer) {
2043                 peer = realtime_peer(NULL, &addr);
2044                 if (peer) {
2045                         ast_copy_string(host, peer->name, len);
2046                         peer_unref(peer);
2047                         res = 1;
2048                 }
2049         }
2050
2051         return res;
2052 }
2053
2054 /*!\note Assumes the lock on the pvt is already held, when
2055  * iax2_destroy_helper() is called. */
2056 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2057 {
2058         /* Decrement AUTHREQ count if needed */
2059         if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2060                 struct iax2_user *user;
2061
2062                 user = ao2_find(users, pvt->username, OBJ_KEY);
2063                 if (user) {
2064                         ast_atomic_fetchadd_int(&user->curauthreq, -1);
2065                         user_unref(user);
2066                 }
2067
2068                 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2069         }
2070         /* No more pings or lagrq's */
2071         AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
2072         pvt->pingid = DONT_RESCHEDULE;
2073         AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
2074         pvt->lagid = DONT_RESCHEDULE;
2075         AST_SCHED_DEL(sched, pvt->autoid);
2076         AST_SCHED_DEL(sched, pvt->authid);
2077         AST_SCHED_DEL(sched, pvt->initid);
2078         AST_SCHED_DEL(sched, pvt->jbid);
2079         AST_SCHED_DEL(sched, pvt->keyrotateid);
2080 }
2081
2082 static void iax2_frame_free(struct iax_frame *fr)
2083 {
2084         AST_SCHED_DEL(sched, fr->retrans);
2085         iax_frame_free(fr);
2086 }
2087
2088 static int scheduled_destroy(const void *vid)
2089 {
2090         unsigned short callno = PTR_TO_CALLNO(vid);
2091         ast_mutex_lock(&iaxsl[callno]);
2092         if (iaxs[callno]) {
2093                 ast_debug(1, "Really destroying %d now...\n", callno);
2094                 iax2_destroy(callno);
2095         }
2096         ast_mutex_unlock(&iaxsl[callno]);
2097         return 0;
2098 }
2099
2100 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2101 {
2102         if (s->f.datalen) {
2103                 ast_free(s->f.data.ptr);
2104         }
2105         ast_free(s);
2106 }
2107
2108 /*! \brief This function must be called once we are sure the other side has
2109  *  given us a call number.  All signaling is held here until that point. */
2110 static void send_signaling(struct chan_iax2_pvt *pvt)
2111 {
2112         struct signaling_queue_entry *s = NULL;
2113
2114         while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2115                 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2116                 free_signaling_queue_entry(s);
2117         }
2118         pvt->hold_signaling = 0;
2119 }
2120
2121 /*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2122  *  we have received a destination call number. */
2123 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2124 {
2125         struct signaling_queue_entry *qe;
2126
2127         if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2128                 return 1; /* do not queue this frame */
2129         } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2130                 return -1;  /* out of memory */
2131         }
2132
2133         /* copy ast_frame into our queue entry */
2134         qe->f = *f;
2135         if (qe->f.datalen) {
2136                 /* if there is data in this frame copy it over as well */
2137                 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2138                         free_signaling_queue_entry(qe);
2139                         return -1;
2140                 }
2141                 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2142         }
2143         AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2144
2145         return 0;
2146 }
2147
2148 static void pvt_destructor(void *obj)
2149 {
2150         struct chan_iax2_pvt *pvt = obj;
2151         struct iax_frame *cur = NULL;
2152         struct signaling_queue_entry *s = NULL;
2153
2154         ast_mutex_lock(&iaxsl[pvt->callno]);
2155
2156         iax2_destroy_helper(pvt);
2157
2158         sched_delay_remove(&pvt->addr, pvt->callno_entry);
2159         pvt->callno_entry = 0;
2160
2161         /* Already gone */
2162         ast_set_flag64(pvt, IAX_ALREADYGONE);
2163
2164         AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2165                 /* Cancel any pending transmissions */
2166                 cur->retries = -1;
2167         }
2168
2169         ast_mutex_unlock(&iaxsl[pvt->callno]);
2170
2171         while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2172                 free_signaling_queue_entry(s);
2173         }
2174
2175         if (pvt->reg) {
2176                 pvt->reg->callno = 0;
2177         }
2178
2179         if (!pvt->owner) {
2180                 jb_frame frame;
2181                 if (pvt->vars) {
2182                     ast_variables_destroy(pvt->vars);
2183                     pvt->vars = NULL;
2184                 }
2185
2186                 while (jb_getall(pvt->jb, &frame) == JB_OK) {
2187                         iax2_frame_free(frame.data);
2188                 }
2189
2190                 jb_destroy(pvt->jb);
2191                 ast_string_field_free_memory(pvt);
2192         }
2193
2194         if (pvt->callid) {
2195                 ast_callid_unref(pvt->callid);
2196         }
2197
2198 }
2199
2200 static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2201 {
2202         struct chan_iax2_pvt *tmp;
2203         jb_conf jbconf;
2204
2205         if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2206                 return NULL;
2207         }
2208
2209         if (ast_string_field_init(tmp, 32)) {
2210                 ao2_ref(tmp, -1);
2211                 tmp = NULL;
2212                 return NULL;
2213         }
2214
2215         tmp->prefs = prefs;
2216         tmp->pingid = -1;
2217         tmp->lagid = -1;
2218         tmp->autoid = -1;
2219         tmp->authid = -1;
2220         tmp->initid = -1;
2221         tmp->keyrotateid = -1;
2222
2223         ast_string_field_set(tmp,exten, "s");
2224         ast_string_field_set(tmp,host, host);
2225
2226         tmp->jb = jb_new();
2227         tmp->jbid = -1;
2228         jbconf.max_jitterbuf = maxjitterbuffer;
2229         jbconf.resync_threshold = resyncthreshold;
2230         jbconf.max_contig_interp = maxjitterinterps;
2231         jbconf.target_extra = jittertargetextra;
2232         jb_setconf(tmp->jb,&jbconf);
2233
2234         AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2235
2236         tmp->hold_signaling = 1;
2237         AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2238
2239         return tmp;
2240 }
2241
2242 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2243 {
2244         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2245         if (new) {
2246                 size_t afdatalen = new->afdatalen;
2247                 memcpy(new, fr, sizeof(*new));
2248                 iax_frame_wrap(new, &fr->af);
2249                 new->afdatalen = afdatalen;
2250                 new->data = NULL;
2251                 new->datalen = 0;
2252                 new->direction = DIRECTION_INGRESS;
2253                 new->retrans = -1;
2254         }
2255         return new;
2256 }
2257 /* keep these defined in this order.  They are used in find_callno to
2258  * determine whether or not a new call number should be allowed. */
2259 enum {
2260         /* do not allow a new call number, only search ones in use for match */
2261         NEW_PREVENT = 0,
2262         /* search for match first, then allow a new one to be allocated */
2263         NEW_ALLOW = 1,
2264         /* do not search for match, force a new call number */
2265         NEW_FORCE = 2,
2266         /* do not search for match, force a new call number.  Signifies call number
2267          * has been calltoken validated */
2268         NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2269 };
2270
2271 static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2272 {
2273         if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2274                 /* This is the main host */
2275                 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2276                          (check_dcallno ? dcallno == cur->callno : 1) ) {
2277                         /* That's us.  Be sure we keep track of the peer call number */
2278                         return 1;
2279                 }
2280         }
2281         if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2282                 /* We're transferring */
2283                 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2284                         return 1;
2285         }
2286         return 0;
2287 }
2288
2289 static int make_trunk(unsigned short callno, int locked)
2290 {
2291         int x;
2292         int res= 0;
2293         callno_entry entry;
2294         if (iaxs[callno]->oseqno) {
2295                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2296                 return -1;
2297         }
2298         if (callno >= TRUNK_CALL_START) {
2299                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2300                 return -1;
2301         }
2302
2303         if (get_unused_callno(
2304                         CALLNO_TYPE_TRUNK,
2305                         CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2306                         &entry)) {
2307                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2308                 return -1;
2309         }
2310
2311         x = CALLNO_ENTRY_GET_CALLNO(entry);
2312         ast_mutex_lock(&iaxsl[x]);
2313
2314         /*!
2315          * \note We delete these before switching the slot, because if
2316          * they fire in the meantime, they will generate a warning.
2317          */
2318         AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2319         AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2320         iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2321         iaxs[x] = iaxs[callno];
2322         iaxs[x]->callno = x;
2323
2324         /* since we copied over the pvt from a different callno, make sure the old entry is replaced
2325          * before assigning the new one */
2326         if (iaxs[x]->callno_entry) {
2327                 iax2_sched_add(
2328                         sched,
2329                         MIN_REUSE_TIME * 1000,
2330                         replace_callno,
2331                         CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2332
2333         }
2334         iaxs[x]->callno_entry = entry;
2335
2336         iaxs[callno] = NULL;
2337         /* Update the two timers that should have been started */
2338         iaxs[x]->pingid = iax2_sched_add(sched,
2339                 ping_time * 1000, send_ping, (void *)(long)x);
2340         iaxs[x]->lagid = iax2_sched_add(sched,
2341                 lagrq_time * 1000, send_lagrq, (void *)(long)x);
2342
2343         if (locked)
2344                 ast_mutex_unlock(&iaxsl[callno]);
2345         res = x;
2346         if (!locked)
2347                 ast_mutex_unlock(&iaxsl[x]);
2348
2349         /* We moved this call from a non-trunked to a trunked call */
2350         ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2351
2352         return res;
2353 }
2354
2355 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2356 {
2357         if (!pvt->transfercallno) {
2358                 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2359                 return;
2360         }
2361
2362         ao2_link(iax_transfercallno_pvts, pvt);
2363 }
2364
2365 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2366 {
2367         if (!pvt->transfercallno) {
2368                 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2369                 return;
2370         }
2371
2372         ao2_unlink(iax_transfercallno_pvts, pvt);
2373 }
2374 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2375 {
2376         if (!pvt->peercallno) {
2377                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2378                 return;
2379         }
2380
2381         ao2_link(iax_peercallno_pvts, pvt);
2382 }
2383
2384 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2385 {
2386         if (!pvt->peercallno) {
2387                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2388                 return;
2389         }
2390
2391         ao2_unlink(iax_peercallno_pvts, pvt);
2392 }
2393
2394 static int addr_range_delme_cb(void *obj, void *arg, int flags)
2395 {
2396         struct addr_range *lim = obj;
2397         lim->delme = 1;
2398         return 0;
2399 }
2400
2401 static int addr_range_hash_cb(const void *obj, const int flags)
2402 {
2403         const struct addr_range *lim = obj;
2404         return abs(ast_sockaddr_hash(&lim->ha.addr));
2405 }
2406
2407 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2408 {
2409         struct addr_range *lim1 = obj, *lim2 = arg;
2410         return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2411                         !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2412                         CMP_MATCH | CMP_STOP : 0;
2413 }
2414
2415 static int peercnt_hash_cb(const void *obj, const int flags)
2416 {
2417         const struct peercnt *peercnt = obj;
2418
2419         if (ast_sockaddr_isnull(&peercnt->addr)) {
2420                 return 0;
2421         }
2422         return ast_sockaddr_hash(&peercnt->addr);
2423 }
2424
2425 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2426 {
2427         struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2428         return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2429 }
2430
2431 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2432 {
2433         struct addr_range *addr_range = obj;
2434         struct ast_sockaddr *addr = arg;
2435         struct ast_sockaddr tmp_addr;
2436
2437         ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2438
2439         if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2440                 return CMP_MATCH | CMP_STOP;
2441         }
2442         return 0;
2443 }
2444
2445 /*!
2446  * \internal
2447  *
2448  * \brief compares addr to calltoken_ignores table to determine if validation is required.
2449  */
2450 static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2451 {
2452         struct addr_range *addr_range;
2453         struct iax2_peer *peer = NULL;
2454         struct iax2_user *user = NULL;
2455         /* if no username is given, check for guest accounts */
2456         const char *find = S_OR(name, "guest");
2457         int res = 1;  /* required by default */
2458         int optional = 0;
2459         enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2460         /* There are only two cases in which calltoken validation is not required.
2461          * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2462          *         the peer definition has not set the requirecalltoken option.
2463          * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2464          */
2465
2466         /* ----- Case 1 ----- */
2467         if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2468                 ao2_ref(addr_range, -1);
2469                 optional = 1;
2470         }
2471
2472         /* ----- Case 2 ----- */
2473         if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2474                 calltoken_required = user->calltoken_required;
2475         } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2476                 calltoken_required = user->calltoken_required;
2477         } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2478                 calltoken_required = peer->calltoken_required;
2479         } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2480                 calltoken_required = peer->calltoken_required;
2481         }
2482
2483         if (peer) {
2484                 peer_unref(peer);
2485         }
2486         if (user) {
2487                 user_unref(user);
2488         }
2489
2490         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);
2491         if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2492                 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2493                 res = 0;
2494         }
2495
2496         return res;
2497 }
2498
2499 /*!
2500  * \internal
2501  *
2502  * \brief set peercnt callno limit.
2503  *
2504  * \details
2505  * First looks in custom definitions. If not found, global limit
2506  * is used.  Entries marked as reg already have
2507  * a custom limit set by a registration and are not modified.
2508  */
2509 static void set_peercnt_limit(struct peercnt *peercnt)
2510 {
2511         uint16_t limit = global_maxcallno;
2512         struct addr_range *addr_range;
2513         struct ast_sockaddr addr;
2514
2515         ast_sockaddr_copy(&addr, &peercnt->addr);
2516
2517         if (peercnt->reg && peercnt->limit) {
2518                 return; /* this peercnt has a custom limit set by a registration */
2519         }
2520
2521         if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2522                 limit = addr_range->limit;
2523                 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2524                 ao2_ref(addr_range, -1);
2525         }
2526
2527         peercnt->limit = limit;
2528 }
2529
2530 /*!
2531  * \internal
2532  * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2533  */
2534 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2535 {
2536         struct peercnt *peercnt = obj;
2537
2538         set_peercnt_limit(peercnt);
2539         ast_debug(1, "Reset limits for peercnts table\n");
2540
2541         return 0;
2542 }
2543
2544 /*!
2545  * \internal
2546  * \brief returns match if delme is set.
2547  */
2548 static int prune_addr_range_cb(void *obj, void *arg, int flags)
2549 {
2550         struct addr_range *addr_range = obj;
2551
2552         return addr_range->delme ? CMP_MATCH : 0;
2553 }
2554
2555 /*!
2556  * \internal
2557  * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2558  */
2559 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2560 {
2561         /* this function turns off and on custom callno limits set by peer registration */
2562         struct peercnt *peercnt;
2563         struct peercnt tmp;
2564
2565         ast_sockaddr_copy(&tmp.addr, sockaddr);
2566
2567         if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2568                 peercnt->reg = reg;
2569                 if (limit) {
2570                         peercnt->limit = limit;
2571                 } else {
2572                         set_peercnt_limit(peercnt);
2573                 }
2574                 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2575                 ao2_ref(peercnt, -1); /* decrement ref from find */
2576         }
2577 }
2578
2579 /*!
2580  * \internal
2581  * \brief adds an ip to the peercnts table, increments connection count if it already exists
2582  *
2583  * \details First searches for the address in the peercnts table.  If found
2584  * the current count is incremented.  If not found a new peercnt is allocated
2585  * and linked into the peercnts table with a call number count of 1.
2586  */
2587 static int peercnt_add(struct ast_sockaddr *addr)
2588 {
2589         struct peercnt *peercnt;
2590         int res = 0;
2591         struct peercnt tmp;
2592
2593         ast_sockaddr_copy(&tmp.addr, addr);
2594
2595         /* Reasoning for peercnts container lock:  Two identical ip addresses
2596          * could be added by different threads at the "same time". Without the container
2597          * lock, both threads could alloc space for the same object and attempt
2598          * to link to table.  With the lock, one would create the object and link
2599          * to table while the other would find the already created peercnt object
2600          * rather than creating a new one. */
2601         ao2_lock(peercnts);
2602         if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2603                 ao2_lock(peercnt);
2604         } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2605                 ao2_lock(peercnt);
2606                 /* create and set defaults */
2607                 ast_sockaddr_copy(&peercnt->addr, addr);
2608                 set_peercnt_limit(peercnt);
2609                 /* guarantees it does not go away after unlocking table
2610                  * ao2_find automatically adds this */
2611                 ao2_link(peercnts, peercnt);
2612         } else {
2613                 ao2_unlock(peercnts);
2614                 return -1;
2615         }
2616
2617         /* check to see if the address has hit its callno limit.  If not increment cur. */
2618         if (peercnt->limit > peercnt->cur) {
2619                 peercnt->cur++;
2620                 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2621         } else { /* max num call numbers for this peer has been reached! */
2622                 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2623                 res = -1;
2624         }
2625
2626         /* clean up locks and ref count */
2627         ao2_unlock(peercnt);
2628         ao2_unlock(peercnts);
2629         ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2630
2631         return res;
2632 }
2633
2634 /*!
2635  * \internal
2636  * \brief decrements a peercnts table entry
2637  */
2638 static void peercnt_remove(struct peercnt *peercnt)
2639 {
2640         struct ast_sockaddr addr;
2641
2642         ast_sockaddr_copy(&addr, &peercnt->addr);
2643
2644         /*
2645          * Container locked here since peercnt may be unlinked from
2646          * list.  If left unlocked, peercnt_add could try and grab this
2647          * entry from the table and modify it at the "same time" this
2648          * thread attemps to unlink it.
2649          */
2650         ao2_lock(peercnts);
2651         peercnt->cur--;
2652         ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2653         /* if this was the last connection from the peer remove it from table */
2654         if (peercnt->cur == 0) {
2655                 ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2656         }
2657         ao2_unlock(peercnts);
2658 }
2659
2660 /*!
2661  * \internal
2662  * \brief called by scheduler to decrement object
2663  */
2664 static int peercnt_remove_cb(const void *obj)
2665 {
2666         struct peercnt *peercnt = (struct peercnt *) obj;
2667
2668         peercnt_remove(peercnt);
2669         ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2670
2671         return 0;
2672 }
2673
2674 /*!
2675  * \internal
2676  * \brief decrements peercnts connection count, finds by addr
2677  */
2678 static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2679 {
2680         struct peercnt *peercnt;
2681         struct peercnt tmp;
2682
2683         ast_sockaddr_copy(&tmp.addr, addr);
2684
2685         if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2686                 peercnt_remove(peercnt);
2687                 ao2_ref(peercnt, -1); /* decrement ref from find */
2688         }
2689         return 0;
2690 }
2691
2692 /*!
2693  * \internal
2694  * \brief Create callno_limit entry based on configuration
2695  */
2696 static void build_callno_limits(struct ast_variable *v)
2697 {
2698         struct addr_range *addr_range = NULL;
2699         struct addr_range tmp;
2700         struct ast_ha *ha;
2701         int limit;
2702         int error;
2703         int found;
2704
2705         for (; v; v = v->next) {
2706                 limit = -1;
2707                 error = 0;
2708                 found = 0;
2709                 ha = ast_append_ha("permit", v->name, NULL, &error);
2710
2711                 /* check for valid config information */
2712                 if (error) {
2713                         ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2714                         continue;
2715                 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2716                         ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2717                         ast_free_ha(ha);
2718                         continue;
2719                 }
2720
2721                 ast_copy_ha(ha, &tmp.ha);
2722                 /* find or create the addr_range */
2723                 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2724                         ao2_lock(addr_range);
2725                         found = 1;
2726                 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2727                         ast_free_ha(ha);
2728                         return; /* out of memory */
2729                 }
2730
2731                 /* copy over config data into addr_range object */
2732                 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2733                 ast_free_ha(ha); /* cleanup the tmp ha */
2734                 addr_range->limit = limit;
2735                 addr_range->delme = 0;
2736
2737                 /* cleanup */
2738                 if (found) {
2739                         ao2_unlock(addr_range);
2740                 } else {
2741                         ao2_link(callno_limits, addr_range);
2742                 }
2743                 ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2744         }
2745 }
2746
2747 /*!
2748  * \internal
2749  * \brief Create calltoken_ignores entry based on configuration
2750  */
2751 static int add_calltoken_ignore(const char *addr)
2752 {
2753         struct addr_range tmp;
2754         struct addr_range *addr_range = NULL;
2755         struct ast_ha *ha = NULL;
2756         int error = 0;
2757
2758         if (ast_strlen_zero(addr)) {
2759                 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2760                 return -1;
2761         }
2762
2763         ha = ast_append_ha("permit", addr, NULL, &error);
2764
2765         /* check for valid config information */
2766         if (error) {
2767                 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2768                 return -1;
2769         }
2770
2771         ast_copy_ha(ha, &tmp.ha);
2772         /* find or create the addr_range */
2773         if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2774                 ao2_lock(addr_range);
2775                 addr_range->delme = 0;
2776                 ao2_unlock(addr_range);
2777         } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2778                 /* copy over config data into addr_range object */
2779                 ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2780                 ao2_link(calltoken_ignores, addr_range);
2781         } else {
2782                 ast_free_ha(ha);
2783                 return -1;
2784         }
2785
2786         ast_free_ha(ha);
2787         ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2788
2789         return 0;
2790 }
2791
2792 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2793 {
2794         struct ao2_iterator i;
2795         struct peercnt *peercnt;
2796         struct ast_sockaddr addr;
2797         int found = 0;
2798
2799         switch (cmd) {
2800         case CLI_INIT:
2801                 e->command = "iax2 show callnumber usage";
2802                 e->usage =
2803                         "Usage: iax2 show callnumber usage [IP address]\n"
2804                         "       Shows current IP addresses which are consuming iax2 call numbers\n";
2805                 return NULL;
2806         case CLI_GENERATE:
2807                 return NULL;
2808         case CLI_HANDLER:
2809                 if (a->argc < 4 || a->argc > 5)
2810                         return CLI_SHOWUSAGE;
2811
2812                 if (a->argc == 4) {
2813                         ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2814                 }
2815
2816                 i = ao2_iterator_init(peercnts, 0);
2817                 while ((peercnt = ao2_iterator_next(&i))) {
2818                         ast_sockaddr_copy(&addr, &peercnt->addr);
2819
2820                         if (a->argc == 5) {
2821                                 if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2822                                         ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2823                                         ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2824                                         ao2_ref(peercnt, -1);
2825                                         found = 1;
2826                                         break;
2827                                 }
2828                         } else {
2829                                 ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2830                         }
2831                         ao2_ref(peercnt, -1);
2832                 }
2833                 ao2_iterator_destroy(&i);
2834
2835                 if (a->argc == 4) {
2836                         size_t pool_avail = callno_pool.available;
2837                         size_t trunk_pool_avail = callno_pool_trunk.available;
2838
2839                         ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2840                                          "Non-CallToken Validated Callno Used:   %d\n",
2841                                 global_maxcallno_nonval,
2842                                 total_nonval_callno_used);
2843
2844                         ast_cli(a->fd,   "Total Available Callno:                %zu\n"
2845                                          "Regular Callno Available:              %zu\n"
2846                                          "Trunk Callno Available:                %zu\n",
2847                                 pool_avail + trunk_pool_avail,
2848                                 pool_avail,
2849                                 trunk_pool_avail);
2850                 } else if (a->argc == 5 && !found) {
2851                         ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2852                 }
2853
2854
2855                 return CLI_SUCCESS;
2856         default:
2857                 return NULL;
2858         }
2859 }
2860
2861 static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2862 {
2863         struct call_number_pool *pool = NULL;
2864         callno_entry swap;
2865         size_t choice;
2866
2867         switch (type) {
2868         case CALLNO_TYPE_NORMAL:
2869                 pool = &callno_pool;
2870                 break;
2871         case CALLNO_TYPE_TRUNK:
2872                 pool = &callno_pool_trunk;
2873                 break;
2874         default:
2875                 ast_assert(0);
2876                 break;
2877         }
2878
2879         /* If we fail, make sure this has a defined value */
2880         *entry = 0;
2881
2882         /* We lock here primarily to ensure thread safety of the
2883          * total_nonval_callno_used check and increment */
2884         ast_mutex_lock(&callno_pool_lock);
2885
2886         /* Bail out if we don't have any available call numbers */
2887         if (!pool->available) {
2888                 ast_log(LOG_WARNING, "Out of call numbers\n");
2889                 ast_mutex_unlock(&callno_pool_lock);
2890                 return 1;
2891         }
2892
2893         /* Only a certain number of non-validated call numbers should be allocated.
2894          * If there ever is an attack, this separates the calltoken validating users
2895          * from the non-calltoken validating users. */
2896         if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2897                 ast_log(LOG_WARNING,
2898                         "NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2899                         total_nonval_callno_used,
2900                         global_maxcallno_nonval);
2901                 ast_mutex_unlock(&callno_pool_lock);
2902                 return 1;
2903         }
2904
2905         /* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2906          * available call numbers.  The array of call numbers begins as an ordered
2907          * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2908          * - let's call that x.  When a call number is needed we pick a random index
2909          * into the array between 0 and x and use that as our call number.  In a
2910          * typical FYD shuffle, we would swap the value that we are extracting with
2911          * the number at x, but in our case we swap and don't touch the value at x
2912          * because it is effectively invisible.  We rely on the rest of the IAX2 core
2913          * to return the number to us at some point.  Finally, we decrement x by 1
2914          * which establishes our new unused range.
2915          *
2916          * When numbers are returned to the pool, we put them just past x and bump x
2917          * by 1 so that this number is now available for re-use. */
2918
2919         choice = ast_random() % pool->available;
2920
2921         *entry = pool->numbers[choice];
2922         swap = pool->numbers[pool->available - 1];
2923
2924         pool->numbers[choice] = swap;
2925         pool->available--;
2926
2927         if (validated) {
2928                 CALLNO_ENTRY_SET_VALIDATED(*entry);
2929         } else {
2930                 total_nonval_callno_used++;
2931         }
2932
2933         ast_mutex_unlock(&callno_pool_lock);
2934
2935         return 0;
2936 }
2937
2938 static int replace_callno(const void *obj)
2939 {
2940         callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2941         struct call_number_pool *pool;
2942
2943         /* We lock here primarily to ensure thread safety of the
2944          * total_nonval_callno_used check and decrement */
2945         ast_mutex_lock(&callno_pool_lock);
2946
2947         if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2948                 if (total_nonval_callno_used) {
2949                         total_nonval_callno_used--;
2950                 } else {
2951                         ast_log(LOG_ERROR,
2952                                 "Attempted to decrement total non calltoken validated "
2953                                 "callnumbers below zero.  Callno is: %d\n",
2954                                 CALLNO_ENTRY_GET_CALLNO(entry));
2955                 }
2956         }
2957
2958         if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2959                 pool = &callno_pool;
2960         } else {
2961                 pool = &callno_pool_trunk;
2962         }
2963
2964         ast_assert(pool->capacity > pool->available);
2965
2966         /* This clears the validated flag */
2967         entry = CALLNO_ENTRY_GET_CALLNO(entry);
2968
2969         pool->numbers[pool->available] = entry;
2970         pool->available++;
2971
2972         ast_mutex_unlock(&callno_pool_lock);
2973
2974         return 0;
2975 }
2976
2977 static int create_callno_pools(void)
2978 {
2979         uint16_t i;
2980
2981         callno_pool.available = callno_pool_trunk.available = 0;
2982
2983         /* We start at 2.  0 and 1 are reserved. */
2984         for (i = 2; i < TRUNK_CALL_START; i++) {
2985                 callno_pool.numbers[callno_pool.available] = i;
2986                 callno_pool.available++;
2987         }
2988
2989         for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2990                 callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2991                 callno_pool_trunk.available++;
2992         }
2993
2994         callno_pool.capacity = callno_pool.available;
2995         callno_pool_trunk.capacity = callno_pool_trunk.available;
2996
2997         ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2998
2999         return 0;
3000 }
3001
3002 /*!
3003  * \internal
3004  * \brief Schedules delayed removal of iax2_pvt call number data
3005  *
3006  * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3007  * available again, and the address from the previous connection must be decremented
3008  * from the peercnts table.  This function schedules these operations to take place.
3009  */
3010 static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3011 {
3012         int i;
3013         struct peercnt *peercnt;
3014         struct peercnt tmp;
3015
3016         ast_sockaddr_copy(&tmp.addr, addr);
3017
3018         if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3019                 /* refcount is incremented with ao2_find.  keep that ref for the scheduler */
3020                 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3021                 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3022                 if (i == -1) {
3023                         ao2_ref(peercnt, -1);
3024                 }
3025         }
3026
3027         iax2_sched_add(
3028                 sched,
3029                 MIN_REUSE_TIME * 1000,
3030                 replace_callno,
3031                 CALLNO_ENTRY_TO_PTR(entry));
3032 }
3033
3034 /*!
3035  * \internal
3036  * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3037  *
3038  * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3039  * a new callno.
3040  */
3041 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3042 {
3043         if (frametype != AST_FRAME_IAX) {
3044                 return 0;
3045         }
3046         switch (subclass) {
3047         case IAX_COMMAND_NEW:
3048         case IAX_COMMAND_REGREQ:
3049         case IAX_COMMAND_FWDOWNL:
3050         case IAX_COMMAND_REGREL:
3051                 return 1;
3052         case IAX_COMMAND_POKE:
3053                 if (!inbound) {
3054                         return 1;
3055                 }
3056                 break;
3057         }
3058         return 0;
3059 }
3060
3061 /*
3062  * \note Calling this function while holding another pvt lock can cause a deadlock.
3063  */
3064 static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3065 {
3066         int res = 0;
3067         int x;
3068         /* this call is calltoken validated as long as it is either NEW_FORCE
3069          * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3070         int validated = (new > NEW_ALLOW) ? 1 : 0;
3071         char host[80];
3072
3073         if (new <= NEW_ALLOW) {
3074                 if (callno) {
3075                         struct chan_iax2_pvt *pvt;
3076                         struct chan_iax2_pvt tmp_pvt = {
3077                                 .callno = dcallno,
3078                                 .peercallno = callno,
3079                                 .transfercallno = callno,
3080                                 /* hack!! */
3081                                 .frames_received = check_dcallno,
3082                         };
3083
3084                         ast_sockaddr_copy(&tmp_pvt.addr, addr);
3085                         /* this works for finding normal call numbers not involving transfering */
3086                         if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3087                                 if (return_locked) {
3088                                         ast_mutex_lock(&iaxsl[pvt->callno]);
3089                                 }
3090                                 res = pvt->callno;
3091                                 ao2_ref(pvt, -1);
3092                                 pvt = NULL;
3093                                 return res;
3094                         }
3095                         /* this searches for transfer call numbers that might not get caught otherwise */
3096                         memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3097                         ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3098                         if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3099                                 if (return_locked) {
3100                                         ast_mutex_lock(&iaxsl[pvt->callno]);
3101                                 }
3102                                 res = pvt->callno;
3103                                 ao2_ref(pvt, -1);
3104                                 pvt = NULL;
3105                                 return res;
3106                         }
3107                 }
3108                         /* This will occur on the first response to a message that we initiated,
3109                  * such as a PING. */
3110                 if (dcallno) {
3111                         ast_mutex_lock(&iaxsl[dcallno]);
3112                 }
3113                 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3114                         iaxs[dcallno]->peercallno = callno;
3115                         res = dcallno;
3116                         store_by_peercallno(iaxs[dcallno]);
3117                         if (!res || !return_locked) {
3118                                 ast_mutex_unlock(&iaxsl[dcallno]);
3119                         }
3120                         return res;
3121                 }
3122                 if (dcallno) {
3123                         ast_mutex_unlock(&iaxsl[dcallno]);
3124                 }
3125         }
3126         if (!res && (new >= NEW_ALLOW)) {
3127                 callno_entry entry;
3128
3129                 /* It may seem odd that we look through the peer list for a name for
3130                  * this *incoming* call.  Well, it is weird.  However, users don't
3131                  * have an IP address/port number that we can match against.  So,
3132                  * this is just checking for a peer that has that IP/port and
3133                  * assuming that we have a user of the same name.  This isn't always
3134                  * correct, but it will be changed if needed after authentication. */
3135                 if (!iax2_getpeername(*addr, host, sizeof(host)))
3136                         snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3137
3138                 if (peercnt_add(addr)) {
3139                         /* This address has hit its callnumber limit.  When the limit
3140                          * is reached, the connection is not added to the peercnts table.*/
3141                         return 0;
3142                 }
3143
3144                 if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3145                         /* since we ran out of space, remove the peercnt
3146                          * entry we added earlier */
3147                         peercnt_remove_by_addr(addr);
3148                         ast_log(LOG_WARNING, "No more space\n");
3149                         return 0;
3150                 }
3151                 x = CALLNO_ENTRY_GET_CALLNO(entry);
3152                 ast_mutex_lock(&iaxsl[x]);
3153
3154                 iaxs[x] = new_iax(addr, host);
3155                 if (iaxs[x]) {
3156                         if (iaxdebug)
3157                                 ast_debug(1, "Creating new call structure %d\n", x);
3158                         iaxs[x]->callno_entry = entry;
3159                         iaxs[x]->sockfd = sockfd;
3160                         ast_sockaddr_copy(&iaxs[x]->addr, addr);
3161                         iaxs[x]->peercallno = callno;
3162                         iaxs[x]->callno = x;
3163                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3164                         iaxs[x]->expiry = min_reg_expire;
3165                         iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3166                         iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3167                         iaxs[x]->amaflags = amaflags;
3168                         ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3169                         ast_string_field_set(iaxs[x], accountcode, accountcode);
3170                         ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3171                         ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3172                         ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3173
3174                         if (iaxs[x]->peercallno) {
3175                                 store_by_peercallno(iaxs[x]);
3176                         }
3177                 } else {
3178                         ast_log(LOG_WARNING, "Out of resources\n");
3179                         ast_mutex_unlock(&iaxsl[x]);
3180                         replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3181                         return 0;
3182                 }
3183                 if (!return_locked)
3184                         ast_mutex_unlock(&iaxsl[x]);
3185                 res = x;
3186         }
3187         return res;
3188 }
3189
3190 static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3191         return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3192 }
3193
3194 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3195
3196         return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3197 }
3198
3199 /*!
3200  * \brief Queue a frame to a call's owning asterisk channel
3201  *
3202  * \pre This function assumes that iaxsl[callno] is locked when called.
3203  *
3204  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3205  * was valid before calling it, it may no longer be valid after calling it.
3206  * This function may unlock and lock the mutex associated with this callno,
3207  * meaning that another thread may grab it and destroy the call.
3208  */
3209 static int iax2_queue_frame(int callno, struct ast_frame *f)
3210 {
3211         iax2_lock_owner(callno);
3212         if (iaxs[callno] && iaxs[callno]->owner) {
3213                 ast_queue_frame(iaxs[callno]->owner, f);
3214                 ast_channel_unlock(iaxs[callno]->owner);
3215         }
3216         return 0;
3217 }
3218
3219 /*!
3220  * \brief Queue a hold frame on the ast_channel owner
3221  *
3222  * This function queues a hold frame on the owner of the IAX2 pvt struct that
3223  * is active for the given call number.
3224  *
3225  * \pre Assumes lock for callno is already held.
3226  *
3227  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3228  * was valid before calling it, it may no longer be valid after calling it.
3229  * This function may unlock and lock the mutex associated with this callno,
3230  * meaning that another thread may grab it and destroy the call.
3231  */
3232 static int iax2_queue_hold(int callno, const char *musicclass)
3233 {
3234         iax2_lock_owner(callno);
3235         if (iaxs[callno] && iaxs[callno]->owner) {
3236                 ast_queue_hold(iaxs[callno]->owner, musicclass);
3237                 ast_channel_unlock(iaxs[callno]->owner);
3238         }
3239         return 0;
3240 }
3241
3242 /*!
3243  * \brief Queue an unhold frame on the ast_channel owner
3244  *
3245  * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3246  * is active for the given call number.
3247  *
3248  * \pre Assumes lock for callno is already held.
3249  *
3250  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3251  * was valid before calling it, it may no longer be valid after calling it.
3252  * This function may unlock and lock the mutex associated with this callno,
3253  * meaning that another thread may grab it and destroy the call.
3254  */
3255 static int iax2_queue_unhold(int callno)
3256 {
3257         iax2_lock_owner(callno);
3258         if (iaxs[callno] && iaxs[callno]->owner) {
3259                 ast_queue_unhold(iaxs[callno]->owner);
3260                 ast_channel_unlock(iaxs[callno]->owner);
3261         }
3262         return 0;
3263 }
3264
3265 /*!
3266  * \brief Queue a hangup frame on the ast_channel owner
3267  *
3268  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3269  * is active for the given call number.
3270  *
3271  * \pre Assumes lock for callno is already held.
3272  *
3273  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3274  * was valid before calling it, it may no longer be valid after calling it.
3275  * This function may unlock and lock the mutex associated with this callno,
3276  * meaning that another thread may grab it and destroy the call.
3277  */
3278 static int iax2_queue_hangup(int callno)
3279 {
3280         iax2_lock_owner(callno);
3281         if (iaxs[callno] && iaxs[callno]->owner) {
3282                 ast_queue_hangup(iaxs[callno]->owner);
3283                 ast_channel_unlock(iaxs[callno]->owner);
3284         }
3285         return 0;
3286 }
3287
3288 /*!
3289  * \note This function assumes that iaxsl[callno] is locked when called.
3290  *
3291  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3292  * was valid before calling it, it may no longer be valid after calling it.
3293  * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3294  * associated with this callno, meaning that another thread may grab it and destroy the call.