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