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