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