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