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