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