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