Fix a bug where the trunkmtu setting was not set to the default value of 1240 on...
[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 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_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(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_flags 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 enum iax2_flags {
393         IAX_HASCALLERID =       (1 << 0),       /*!< CallerID has been specified */
394         IAX_DELME =             (1 << 1),       /*!< Needs to be deleted */
395         IAX_TEMPONLY =          (1 << 2),       /*!< Temporary (realtime) */
396         IAX_TRUNK =             (1 << 3),       /*!< Treat as a trunk */
397         IAX_NOTRANSFER =        (1 << 4),       /*!< Don't native bridge */
398         IAX_USEJITTERBUF =      (1 << 5),       /*!< Use jitter buffer */
399         IAX_DYNAMIC =           (1 << 6),       /*!< dynamic peer */
400         IAX_SENDANI =           (1 << 7),       /*!< Send ANI along with CallerID */
401         /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
402         IAX_ALREADYGONE =       (1 << 9),       /*!< Already disconnected */
403         IAX_PROVISION =         (1 << 10),      /*!< This is a provisioning request */
404         IAX_QUELCH =            (1 << 11),      /*!< Whether or not we quelch audio */
405         IAX_ENCRYPTED =         (1 << 12),      /*!< Whether we should assume encrypted tx/rx */
406         IAX_KEYPOPULATED =      (1 << 13),      /*!< Whether we have a key populated */
407         IAX_CODEC_USER_FIRST =  (1 << 14),      /*!< are we willing to let the other guy choose the codec? */
408         IAX_CODEC_NOPREFS =     (1 << 15),      /*!< Force old behaviour by turning off prefs */
409         IAX_CODEC_NOCAP =       (1 << 16),      /*!< only consider requested format and ignore capabilities*/
410         IAX_RTCACHEFRIENDS =    (1 << 17),      /*!< let realtime stay till your reload */
411         IAX_RTUPDATE =          (1 << 18),      /*!< Send a realtime update */
412         IAX_RTAUTOCLEAR =       (1 << 19),      /*!< erase me on expire */ 
413         IAX_FORCEJITTERBUF =    (1 << 20),      /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
414         IAX_RTIGNOREREGEXPIRE = (1 << 21),      /*!< When using realtime, ignore registration expiration */
415         IAX_TRUNKTIMESTAMPS =   (1 << 22),      /*!< Send trunk timestamps */
416         IAX_TRANSFERMEDIA =     (1 << 23),      /*!< When doing IAX2 transfers, transfer media only */
417         IAX_MAXAUTHREQ =        (1 << 24),      /*!< Maximum outstanding AUTHREQ restriction is in place */
418         IAX_DELAYPBXSTART =     (1 << 25),      /*!< Don't start a PBX on the channel until the peer sends us a
419                                                      response, so that we've achieved a three-way handshake with
420                                                      them before sending voice or anything else*/
421         IAX_ALLOWFWDOWNLOAD =   (1 << 26),      /*!< Allow the FWDOWNL command? */
422         IAX_IMMEDIATE =         (1 << 27),      /*!< Allow immediate off-hook to extension s */
423         IAX_SENDCONNECTEDLINE = (1 << 28), /*!< Allow sending of connected line updates */
424         IAX_RECVCONNECTEDLINE = (1 << 29), /*!< Allow receiving of connected line updates */
425         IAX_FORCE_ENCRYPT =     (1 << 30),      /*!< Forces call encryption, if encryption not possible hangup */
426 };
427
428 static int global_rtautoclear = 120;
429
430 static int reload_config(void);
431
432 struct iax2_user {
433         AST_DECLARE_STRING_FIELDS(
434                 AST_STRING_FIELD(name);
435                 AST_STRING_FIELD(secret);
436                 AST_STRING_FIELD(dbsecret);
437                 AST_STRING_FIELD(accountcode);
438                 AST_STRING_FIELD(mohinterpret);
439                 AST_STRING_FIELD(mohsuggest);
440                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
441                 AST_STRING_FIELD(language);
442                 AST_STRING_FIELD(cid_num);
443                 AST_STRING_FIELD(cid_name);
444                 AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
445         );
446         
447         int authmethods;
448         int encmethods;
449         int amaflags;
450         int adsi;
451         unsigned int flags;
452         int capability;
453         int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
454         int curauthreq; /*!< Current number of outstanding AUTHREQs */
455         struct ast_codec_pref prefs;
456         struct ast_ha *ha;
457         struct iax2_context *contexts;
458         struct ast_variable *vars;
459 };
460
461 struct iax2_peer {
462         AST_DECLARE_STRING_FIELDS(
463                 AST_STRING_FIELD(name);
464                 AST_STRING_FIELD(username);
465                 AST_STRING_FIELD(secret);
466                 AST_STRING_FIELD(dbsecret);
467                 AST_STRING_FIELD(outkey);           /*!< What key we use to talk to this peer */
468
469                 AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
470                 AST_STRING_FIELD(context);      /*!< For transfers only */
471                 AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
472                 AST_STRING_FIELD(mailbox);          /*!< Mailbox */
473                 AST_STRING_FIELD(mohinterpret);
474                 AST_STRING_FIELD(mohsuggest);
475                 AST_STRING_FIELD(inkeys);               /*!< Key(s) this peer can use to authenticate to us */
476                 /* Suggested caller id if registering */
477                 AST_STRING_FIELD(cid_num);              /*!< Default context (for transfer really) */
478                 AST_STRING_FIELD(cid_name);             /*!< Default context (for transfer really) */
479                 AST_STRING_FIELD(zonetag);              /*!< Time Zone */
480                 AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
481         );
482         struct ast_codec_pref prefs;
483         struct ast_dnsmgr_entry *dnsmgr;                /*!< DNS refresh manager */
484         struct sockaddr_in addr;
485         int formats;
486         int sockfd;                                     /*!< Socket to use for transmission */
487         struct in_addr mask;
488         int adsi;
489         unsigned int flags;
490
491         /* Dynamic Registration fields */
492         struct sockaddr_in defaddr;                     /*!< Default address if there is one */
493         int authmethods;                                /*!< Authentication methods (IAX_AUTH_*) */
494         int encmethods;                                 /*!< Encryption methods (IAX_ENCRYPT_*) */
495
496         int expire;                                     /*!< Schedule entry for expiry */
497         int expiry;                                     /*!< How soon to expire */
498         int capability;                                 /*!< Capability */
499
500         /* Qualification */
501         int callno;                                     /*!< Call number of POKE request */
502         int pokeexpire;                                 /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
503         int lastms;                                     /*!< How long last response took (in ms), or -1 for no response */
504         int maxms;                                      /*!< Max ms we will accept for the host to be up, 0 to not monitor */
505
506         int pokefreqok;                                 /*!< How often to check if the host is up */
507         int pokefreqnotok;                              /*!< How often to check when the host has been determined to be down */
508         int historicms;                                 /*!< How long recent average responses took */
509         int smoothing;                                  /*!< Sample over how many units to determine historic ms */
510
511         struct ast_event_sub *mwi_event_sub;
512
513         struct ast_ha *ha;
514 };
515
516 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
517
518 struct iax2_trunk_peer {
519         ast_mutex_t lock;
520         int sockfd;
521         struct sockaddr_in addr;
522         struct timeval txtrunktime;             /*!< Transmit trunktime */
523         struct timeval rxtrunktime;             /*!< Receive trunktime */
524         struct timeval lasttxtime;              /*!< Last transmitted trunktime */
525         struct timeval trunkact;                /*!< Last trunk activity */
526         unsigned int lastsent;                  /*!< Last sent time */
527         /* Trunk data and length */
528         unsigned char *trunkdata;
529         unsigned int trunkdatalen;
530         unsigned int trunkdataalloc;
531         int trunkmaxmtu;
532         int trunkerror;
533         int calls;
534         AST_LIST_ENTRY(iax2_trunk_peer) list;
535 };
536
537 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
538
539 struct iax_firmware {
540         AST_LIST_ENTRY(iax_firmware) list;
541         int fd;
542         int mmaplen;
543         int dead;
544         struct ast_iax2_firmware_header *fwh;
545         unsigned char *buf;
546 };
547
548 enum iax_reg_state {
549         REG_STATE_UNREGISTERED = 0,
550         REG_STATE_REGSENT,
551         REG_STATE_AUTHSENT,
552         REG_STATE_REGISTERED,
553         REG_STATE_REJECTED,
554         REG_STATE_TIMEOUT,
555         REG_STATE_NOAUTH
556 };
557
558 enum iax_transfer_state {
559         TRANSFER_NONE = 0,
560         TRANSFER_BEGIN,
561         TRANSFER_READY,
562         TRANSFER_RELEASED,
563         TRANSFER_PASSTHROUGH,
564         TRANSFER_MBEGIN,
565         TRANSFER_MREADY,
566         TRANSFER_MRELEASED,
567         TRANSFER_MPASSTHROUGH,
568         TRANSFER_MEDIA,
569         TRANSFER_MEDIAPASS
570 };
571
572 struct iax2_registry {
573         struct sockaddr_in addr;                /*!< Who we connect to for registration purposes */
574         char username[80];
575         char secret[80];                        /*!< Password or key name in []'s */
576         int expire;                             /*!< Sched ID of expiration */
577         int refresh;                            /*!< How often to refresh */
578         enum iax_reg_state regstate;
579         int messages;                           /*!< Message count, low 8 bits = new, high 8 bits = old */
580         int callno;                             /*!< Associated call number if applicable */
581         struct sockaddr_in us;                  /*!< Who the server thinks we are */
582         struct ast_dnsmgr_entry *dnsmgr;        /*!< DNS refresh manager */
583         AST_LIST_ENTRY(iax2_registry) entry;
584 };
585
586 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
587
588 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
589 #define MIN_RETRY_TIME          100
590 #define MAX_RETRY_TIME          10000
591
592 #define MAX_JITTER_BUFFER       50
593 #define MIN_JITTER_BUFFER       10
594
595 #define DEFAULT_TRUNKDATA       640 * 10        /*!< 40ms, uncompressed linear * 10 channels */
596
597 #define MAX_TIMESTAMP_SKEW      160             /*!< maximum difference between actual and predicted ts for sending */
598
599 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
600 #define TS_GAP_FOR_JB_RESYNC    5000
601
602 /* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
603 #define MARK_IAX_SUBCLASS_TX    0x8000
604
605 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
606 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
607 static int iaxdynamicthreadcount = 0;
608 static int iaxdynamicthreadnum = 0;
609 static int iaxactivethreadcount = 0;
610
611 struct iax_rr {
612         int jitter;
613         int losspct;
614         int losscnt;
615         int packets;
616         int delay;
617         int dropped;
618         int ooo;
619 };
620
621 struct iax2_pvt_ref;
622
623 struct chan_iax2_pvt {
624         /*! Socket to send/receive on for this call */
625         int sockfd;
626         /*! Last received voice format */
627         int voiceformat;
628         /*! Last received video format */
629         int videoformat;
630         /*! Last sent voice format */
631         int svoiceformat;
632         /*! Last sent video format */
633         int svideoformat;
634         /*! What we are capable of sending */
635         int capability;
636         /*! Last received timestamp */
637         unsigned int last;
638         /*! Last sent timestamp - never send the same timestamp twice in a single call */
639         unsigned int lastsent;
640         /*! Timestamp of the last video frame sent */
641         unsigned int lastvsent;
642         /*! Next outgoing timestamp if everything is good */
643         unsigned int nextpred;
644         /*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
645         int first_iax_message;
646         /*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
647         int last_iax_message;
648         /*! True if the last voice we transmitted was not silence/CNG */
649         unsigned int notsilenttx:1;
650         /*! Ping time */
651         unsigned int pingtime;
652         /*! Max time for initial response */
653         int maxtime;
654         /*! Peer Address */
655         struct sockaddr_in addr;
656         /*! Actual used codec preferences */
657         struct ast_codec_pref prefs;
658         /*! Requested codec preferences */
659         struct ast_codec_pref rprefs;
660         /*! Our call number */
661         unsigned short callno;
662         /*! Peer callno */
663         unsigned short peercallno;
664         /*! Negotiated format, this is only used to remember what format was
665             chosen for an unauthenticated call so that the channel can get
666             created later using the right format */
667         int chosenformat;
668         /*! Peer selected format */
669         int peerformat;
670         /*! Peer capability */
671         int peercapability;
672         /*! timeval that we base our transmission on */
673         struct timeval offset;
674         /*! timeval that we base our delivery on */
675         struct timeval rxcore;
676         /*! The jitterbuffer */
677         jitterbuf *jb;
678         /*! active jb read scheduler id */
679         int jbid;                       
680         /*! LAG */
681         int lag;
682         /*! Error, as discovered by the manager */
683         int error;
684         /*! Owner if we have one */
685         struct ast_channel *owner;
686         /*! What's our state? */
687         struct ast_flags state;
688         /*! Expiry (optional) */
689         int expiry;
690         /*! Next outgoing sequence number */
691         unsigned char oseqno;
692         /*! Next sequence number they have not yet acknowledged */
693         unsigned char rseqno;
694         /*! Next incoming sequence number */
695         unsigned char iseqno;
696         /*! Last incoming sequence number we have acknowledged */
697         unsigned char aseqno;
698
699         AST_DECLARE_STRING_FIELDS(
700                 /*! Peer name */
701                 AST_STRING_FIELD(peer);
702                 /*! Default Context */
703                 AST_STRING_FIELD(context);
704                 /*! Caller ID if available */
705                 AST_STRING_FIELD(cid_num);
706                 AST_STRING_FIELD(cid_name);
707                 /*! Hidden Caller ID (i.e. ANI) if appropriate */
708                 AST_STRING_FIELD(ani);
709                 /*! DNID */
710                 AST_STRING_FIELD(dnid);
711                 /*! RDNIS */
712                 AST_STRING_FIELD(rdnis);
713                 /*! Requested Extension */
714                 AST_STRING_FIELD(exten);
715                 /*! Expected Username */
716                 AST_STRING_FIELD(username);
717                 /*! Expected Secret */
718                 AST_STRING_FIELD(secret);
719                 /*! MD5 challenge */
720                 AST_STRING_FIELD(challenge);
721                 /*! Public keys permitted keys for incoming authentication */
722                 AST_STRING_FIELD(inkeys);
723                 /*! Private key for outgoing authentication */
724                 AST_STRING_FIELD(outkey);
725                 /*! Preferred language */
726                 AST_STRING_FIELD(language);
727                 /*! Hostname/peername for naming purposes */
728                 AST_STRING_FIELD(host);
729
730                 AST_STRING_FIELD(dproot);
731                 AST_STRING_FIELD(accountcode);
732                 AST_STRING_FIELD(mohinterpret);
733                 AST_STRING_FIELD(mohsuggest);
734                 /*! received OSP token */
735                 AST_STRING_FIELD(osptoken);
736                 /*! Default parkinglot */
737                 AST_STRING_FIELD(parkinglot);
738         );
739         
740         /*! permitted authentication methods */
741         int authmethods;
742         /*! permitted encryption methods */
743         int encmethods;
744         /*! Encryption AES-128 Key */
745         ast_aes_encrypt_key ecx;
746         /*! Decryption AES-128 Key corresponding to ecx */
747         ast_aes_decrypt_key mydcx;
748         /*! Decryption AES-128 Key used to decrypt peer frames */
749         ast_aes_decrypt_key dcx;
750         /*! scheduler id associated with iax_key_rotate 
751          * for encrypted calls*/
752         int keyrotateid;
753         /*! 32 bytes of semi-random data */
754         unsigned char semirand[32];
755         /*! Associated registry */
756         struct iax2_registry *reg;
757         /*! Associated peer for poking */
758         struct iax2_peer *peerpoke;
759         /*! IAX_ flags */
760         unsigned int flags;
761         int adsi;
762
763         /*! Transferring status */
764         enum iax_transfer_state transferring;
765         /*! Transfer identifier */
766         int transferid;
767         /*! Who we are IAX transferring to */
768         struct sockaddr_in transfer;
769         /*! What's the new call number for the transfer */
770         unsigned short transfercallno;
771         /*! Transfer encrypt AES-128 Key */
772         ast_aes_encrypt_key tdcx;
773
774         /*! Status of knowledge of peer ADSI capability */
775         int peeradsicpe;
776
777         /*! Who we are bridged to */
778         unsigned short bridgecallno;
779         
780         int pingid;                     /*!< Transmit PING request */
781         int lagid;                      /*!< Retransmit lag request */
782         int autoid;                     /*!< Auto hangup for Dialplan requestor */
783         int authid;                     /*!< Authentication rejection ID */
784         int authfail;                   /*!< Reason to report failure */
785         int initid;                     /*!< Initial peer auto-congest ID (based on qualified peers) */
786         int calling_ton;
787         int calling_tns;
788         int calling_pres;
789         int amaflags;
790         AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
791         /*! variables inherited from the user definition */
792         struct ast_variable *vars;
793         /*! variables transmitted in a NEW packet */
794         struct ast_variable *iaxvars;
795         /*! last received remote rr */
796         struct iax_rr remote_rr;
797         /*! Current base time: (just for stats) */
798         int min;
799         /*! Dropped frame count: (just for stats) */
800         int frames_dropped;
801         /*! received frame count: (just for stats) */
802         int frames_received;
803 };
804
805 /*!
806  * \brief a list of frames that may need to be retransmitted
807  *
808  * \note The contents of this list do not need to be explicitly destroyed
809  * on module unload.  This is because all active calls are destroyed, and
810  * all frames in this queue will get destroyed as a part of that process.
811  *
812  * \note Contents protected by the iaxsl[] locks
813  */
814 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
815
816 static struct ast_taskprocessor *transmit_processor;
817
818 /*!
819  * This module will get much higher performance when doing a lot of
820  * user and peer lookups if the number of buckets is increased from 1.
821  * However, to maintain old behavior for Asterisk 1.4, these are set to
822  * 1 by default.  When using multiple buckets, search order through these
823  * containers is considered random, so you will not be able to depend on
824  * the order the entires are specified in iax.conf for matching order. */
825 #ifdef LOW_MEMORY
826 #define MAX_PEER_BUCKETS 17
827 #else
828 #define MAX_PEER_BUCKETS 563
829 #endif
830 static struct ao2_container *peers;
831
832 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
833 static struct ao2_container *users;
834
835 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
836
837 enum {
838         /*! Extension exists */
839         CACHE_FLAG_EXISTS      = (1 << 0),
840         /*! Extension is nonexistent */
841         CACHE_FLAG_NONEXISTENT = (1 << 1),
842         /*! Extension can exist */
843         CACHE_FLAG_CANEXIST    = (1 << 2),
844         /*! Waiting to hear back response */
845         CACHE_FLAG_PENDING     = (1 << 3),
846         /*! Timed out */
847         CACHE_FLAG_TIMEOUT     = (1 << 4),
848         /*! Request transmitted */
849         CACHE_FLAG_TRANSMITTED = (1 << 5),
850         /*! Timeout */
851         CACHE_FLAG_UNKNOWN     = (1 << 6),
852         /*! Matchmore */
853         CACHE_FLAG_MATCHMORE   = (1 << 7),
854 };
855
856 struct iax2_dpcache {
857         char peercontext[AST_MAX_CONTEXT];
858         char exten[AST_MAX_EXTENSION];
859         struct timeval orig;
860         struct timeval expiry;
861         int flags;
862         unsigned short callno;
863         int waiters[256];
864         AST_LIST_ENTRY(iax2_dpcache) cache_list;
865         AST_LIST_ENTRY(iax2_dpcache) peer_list;
866 };
867
868 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
869
870 static void reg_source_db(struct iax2_peer *p);
871 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
872
873 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
874 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags);
875 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
876
877 enum iax2_thread_iostate {
878         IAX_IOSTATE_IDLE,
879         IAX_IOSTATE_READY,
880         IAX_IOSTATE_PROCESSING,
881         IAX_IOSTATE_SCHEDREADY,
882 };
883
884 enum iax2_thread_type {
885         IAX_THREAD_TYPE_POOL,
886         IAX_THREAD_TYPE_DYNAMIC,
887 };
888
889 struct iax2_pkt_buf {
890         AST_LIST_ENTRY(iax2_pkt_buf) entry;
891         size_t len;
892         unsigned char buf[1];
893 };
894
895 struct iax2_thread {
896         AST_LIST_ENTRY(iax2_thread) list;
897         enum iax2_thread_type type;
898         enum iax2_thread_iostate iostate;
899 #ifdef SCHED_MULTITHREADED
900         void (*schedfunc)(const void *);
901         const void *scheddata;
902 #endif
903 #ifdef DEBUG_SCHED_MULTITHREAD
904         char curfunc[80];
905 #endif  
906         int actions;
907         pthread_t threadid;
908         int threadnum;
909         struct sockaddr_in iosin;
910         unsigned char readbuf[4096]; 
911         unsigned char *buf;
912         ssize_t buf_len;
913         size_t buf_size;
914         int iofd;
915         time_t checktime;
916         ast_mutex_t lock;
917         ast_cond_t cond;
918         ast_mutex_t init_lock;
919         ast_cond_t init_cond;
920         /*! if this thread is processing a full frame,
921           some information about that frame will be stored
922           here, so we can avoid dispatching any more full
923           frames for that callno to other threads */
924         struct {
925                 unsigned short callno;
926                 struct sockaddr_in sin;
927                 unsigned char type;
928                 unsigned char csub;
929         } ffinfo;
930         /*! Queued up full frames for processing.  If more full frames arrive for
931          *  a call which this thread is already processing a full frame for, they
932          *  are queued up here. */
933         AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
934 };
935
936 /* Thread lists */
937 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
938 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
939 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
940
941 static void *iax2_process_thread(void *data);
942 static void iax2_destroy(int callno);
943
944 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
945 {
946         ast_mutex_lock(lock);
947         ast_cond_signal(cond);
948         ast_mutex_unlock(lock);
949 }
950
951 /*!
952  * \brief an array of iax2 pvt structures
953  *
954  * The container for active chan_iax2_pvt structures is implemented as an
955  * array for extremely quick direct access to the correct pvt structure
956  * based on the local call number.  The local call number is used as the
957  * index into the array where the associated pvt structure is stored.
958  */
959 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
960
961 /*!
962  * \brief Another container of iax2_pvt structures
963  *
964  * Active IAX2 pvt structs are also stored in this container, if they are a part
965  * of an active call where we know the remote side's call number.  The reason
966  * for this is that incoming media frames do not contain our call number.  So,
967  * instead of having to iterate the entire iaxs array, we use this container to
968  * look up calls where the remote side is using a given call number.
969  */
970 static struct ao2_container *iax_peercallno_pvts;
971
972 /*!
973  * \brief chan_iax2_pvt structure locks
974  *
975  * These locks are used when accessing a pvt structure in the iaxs array.
976  * The index used here is the same as used in the iaxs array.  It is the
977  * local call number for the associated pvt struct.
978  */
979 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
980
981 /*!
982  * \brief The last time a call number was used
983  *
984  * It is important to know the last time that a call number was used locally so
985  * that it is not used again too soon.  The reason for this is the same as the
986  * reason that the TCP protocol state machine requires a "TIME WAIT" state.
987  *
988  * For example, say that a call is up.  Then, the remote side sends a HANGUP,
989  * which we respond to with an ACK.  However, there is no way to know whether
990  * the ACK made it there successfully.  If it were to get lost, the remote
991  * side may retransmit the HANGUP.  If in the meantime, this call number has
992  * been reused locally, given the right set of circumstances, this retransmitted
993  * HANGUP could potentially improperly hang up the new session.  So, to avoid
994  * this potential issue, we must wait a specified timeout period before reusing
995  * a local call number.
996  *
997  * The specified time that we must wait before reusing a local call number is
998  * defined as MIN_REUSE_TIME, with a default of 60 seconds.
999  */
1000 static struct timeval lastused[ARRAY_LEN(iaxs)];
1001
1002 /*!
1003  *  * \brief Another container of iax2_pvt structures
1004  *  
1005  *  Active IAX2 pvt stucts used during transfering a call are stored here.  
1006  */
1007 static struct ao2_container *iax_transfercallno_pvts;
1008
1009 /* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
1010    but keeps the division between trunked and non-trunked better. */
1011 #define TRUNK_CALL_START        ARRAY_LEN(iaxs) / 2
1012
1013 /* Debug routines... */
1014 static struct sockaddr_in debugaddr;
1015
1016 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1017 {
1018         if (iaxdebug ||
1019             (sin && debugaddr.sin_addr.s_addr && 
1020              (!ntohs(debugaddr.sin_port) ||
1021               debugaddr.sin_port == sin->sin_port) &&
1022              debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1023                 if (iaxdebug) {
1024                         iax_showframe(f, fhi, rx, sin, datalen);
1025                 } else {
1026                         iaxdebug = 1;
1027                         iax_showframe(f, fhi, rx, sin, datalen);
1028                         iaxdebug = 0;
1029                 }
1030         }
1031 }
1032
1033 static void iax_debug_output(const char *data)
1034 {
1035         if (iaxdebug)
1036                 ast_verbose("%s", data);
1037 }
1038
1039 static void iax_error_output(const char *data)
1040 {
1041         ast_log(LOG_WARNING, "%s", data);
1042 }
1043
1044 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1045 {
1046         va_list args;
1047         char buf[1024];
1048
1049         va_start(args, fmt);
1050         vsnprintf(buf, sizeof(buf), fmt, args);
1051         va_end(args);
1052
1053         ast_log(LOG_ERROR, "%s", buf);
1054 }
1055
1056 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1057 {
1058         va_list args;
1059         char buf[1024];
1060
1061         va_start(args, fmt);
1062         vsnprintf(buf, sizeof(buf), fmt, args);
1063         va_end(args);
1064
1065         ast_log(LOG_WARNING, "%s", buf);
1066 }
1067
1068 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1069 {
1070         va_list args;
1071         char buf[1024];
1072
1073         va_start(args, fmt);
1074         vsnprintf(buf, sizeof(buf), fmt, args);
1075         va_end(args);
1076
1077         ast_verbose("%s", buf);
1078 }
1079
1080 static int maxtrunkcall = TRUNK_CALL_START;
1081 static int maxnontrunkcall = 1;
1082
1083 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);
1084 static int expire_registry(const void *data);
1085 static int iax2_answer(struct ast_channel *c);
1086 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
1087 static int iax2_devicestate(void *data);
1088 static int iax2_digit_begin(struct ast_channel *c, char digit);
1089 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1090 static int iax2_do_register(struct iax2_registry *reg);
1091 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1092 static int iax2_hangup(struct ast_channel *c);
1093 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1094 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1095 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1096 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1097 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1098 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1099 static int iax2_sendtext(struct ast_channel *c, const char *text);
1100 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1101 static int iax2_transfer(struct ast_channel *c, const char *dest);
1102 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1103 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1104 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1105 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1106 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1107 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1108 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1109 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
1110 static struct ast_frame *iax2_read(struct ast_channel *c);
1111 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1112 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1113 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
1114 static void *iax2_dup_variable_datastore(void *);
1115 static void prune_peers(void);
1116 static void prune_users(void);
1117 static void iax2_free_variable_datastore(void *);
1118
1119 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1120 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
1121 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1122 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1123 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1124 static void build_rand_pad(unsigned char *buf, ssize_t len);
1125
1126 static const struct ast_channel_tech iax2_tech = {
1127         .type = "IAX2",
1128         .description = tdesc,
1129         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
1130         .properties = AST_CHAN_TP_WANTSJITTER,
1131         .requester = iax2_request,
1132         .devicestate = iax2_devicestate,
1133         .send_digit_begin = iax2_digit_begin,
1134         .send_digit_end = iax2_digit_end,
1135         .send_text = iax2_sendtext,
1136         .send_image = iax2_sendimage,
1137         .send_html = iax2_sendhtml,
1138         .call = iax2_call,
1139         .hangup = iax2_hangup,
1140         .answer = iax2_answer,
1141         .read = iax2_read,
1142         .write = iax2_write,
1143         .write_video = iax2_write,
1144         .indicate = iax2_indicate,
1145         .setoption = iax2_setoption,
1146         .bridge = iax2_bridge,
1147         .transfer = iax2_transfer,
1148         .fixup = iax2_fixup,
1149         .func_channel_read = acf_channel_read,
1150         .func_channel_write = acf_channel_write,
1151 };
1152
1153 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1154 {
1155         /* The MWI subscriptions exist just so the core knows we care about those
1156          * mailboxes.  However, we just grab the events out of the cache when it
1157          * is time to send MWI, since it is only sent with a REGACK. */
1158 }
1159
1160 /*! \brief Send manager event at call setup to link between Asterisk channel name
1161         and IAX2 call identifiers */
1162 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
1163 {
1164         manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1165                 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1166                 pvt->owner ? pvt->owner->name : "",
1167                 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1168 }
1169
1170
1171 static struct ast_datastore_info iax2_variable_datastore_info = {
1172         .type = "IAX2_VARIABLE",
1173         .duplicate = iax2_dup_variable_datastore,
1174         .destroy = iax2_free_variable_datastore,
1175 };
1176
1177 static void *iax2_dup_variable_datastore(void *old)
1178 {
1179         AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1180         struct ast_var_t *oldvar, *newvar;
1181
1182         newlist = ast_calloc(sizeof(*newlist), 1);
1183         if (!newlist) {
1184                 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1185                 return NULL;
1186         }
1187
1188         AST_LIST_HEAD_INIT(newlist);
1189         AST_LIST_LOCK(oldlist);
1190         AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1191                 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1192                 if (newvar)
1193                         AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1194                 else
1195                         ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1196         }
1197         AST_LIST_UNLOCK(oldlist);
1198         return newlist;
1199 }
1200
1201 static void iax2_free_variable_datastore(void *old)
1202 {
1203         AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1204         struct ast_var_t *oldvar;
1205
1206         AST_LIST_LOCK(oldlist);
1207         while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1208                 ast_free(oldvar);
1209         }
1210         AST_LIST_UNLOCK(oldlist);
1211         AST_LIST_HEAD_DESTROY(oldlist);
1212         ast_free(oldlist);
1213 }
1214
1215
1216 /* WARNING: insert_idle_thread should only ever be called within the
1217  * context of an iax2_process_thread() thread.
1218  */
1219 static void insert_idle_thread(struct iax2_thread *thread)
1220 {
1221         if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1222                 AST_LIST_LOCK(&dynamic_list);
1223                 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1224                 AST_LIST_UNLOCK(&dynamic_list);
1225         } else {
1226                 AST_LIST_LOCK(&idle_list);
1227                 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1228                 AST_LIST_UNLOCK(&idle_list);
1229         }
1230
1231         return;
1232 }
1233
1234 static struct iax2_thread *find_idle_thread(void)
1235 {
1236         struct iax2_thread *thread = NULL;
1237
1238         /* Pop the head of the idle list off */
1239         AST_LIST_LOCK(&idle_list);
1240         thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1241         AST_LIST_UNLOCK(&idle_list);
1242
1243         /* If we popped a thread off the idle list, just return it */
1244         if (thread) {
1245                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1246                 return thread;
1247         }
1248
1249         /* Pop the head of the dynamic list off */
1250         AST_LIST_LOCK(&dynamic_list);
1251         thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1252         AST_LIST_UNLOCK(&dynamic_list);
1253
1254         /* If we popped a thread off the dynamic list, just return it */
1255         if (thread) {
1256                 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1257                 return thread;
1258         }
1259
1260         /* If we can't create a new dynamic thread for any reason, return no thread at all */
1261         if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1262                 return NULL;
1263
1264         /* Set default values */
1265         ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1266         thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1267         thread->type = IAX_THREAD_TYPE_DYNAMIC;
1268
1269         /* Initialize lock and condition */
1270         ast_mutex_init(&thread->lock);
1271         ast_cond_init(&thread->cond, NULL);
1272         ast_mutex_init(&thread->init_lock);
1273         ast_cond_init(&thread->init_cond, NULL);
1274         ast_mutex_lock(&thread->init_lock);
1275
1276         /* Create thread and send it on it's way */
1277         if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1278                 ast_cond_destroy(&thread->cond);
1279                 ast_mutex_destroy(&thread->lock);
1280                 ast_free(thread);
1281                 return NULL;
1282         }
1283
1284         /* this thread is not processing a full frame (since it is idle),
1285            so ensure that the field for the full frame call number is empty */
1286         memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1287
1288         /* Wait for the thread to be ready before returning it to the caller */
1289         ast_cond_wait(&thread->init_cond, &thread->init_lock);
1290
1291         /* Done with init_lock */
1292         ast_mutex_unlock(&thread->init_lock);
1293
1294         return thread;
1295 }
1296
1297 #ifdef SCHED_MULTITHREADED
1298 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1299 {
1300         struct iax2_thread *thread = NULL;
1301         static time_t lasterror;
1302         static time_t t;
1303
1304         thread = find_idle_thread();
1305
1306         if (thread != NULL) {
1307                 thread->schedfunc = func;
1308                 thread->scheddata = data;
1309                 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1310 #ifdef DEBUG_SCHED_MULTITHREAD
1311                 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1312 #endif
1313                 signal_condition(&thread->lock, &thread->cond);
1314                 return 0;
1315         }
1316         time(&t);
1317         if (t != lasterror) 
1318                 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1319         lasterror = t;
1320
1321         return -1;
1322 }
1323 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1324 #endif
1325
1326 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when, 
1327                 ast_sched_cb callback, const void *data)
1328 {
1329         ast_sched_thread_del(st, id);
1330
1331         return ast_sched_thread_add(st, when, callback, data);
1332 }
1333
1334 static int iax2_sched_add(struct ast_sched_thread *st, int when, 
1335                 ast_sched_cb callback, const void *data)
1336 {
1337         return ast_sched_thread_add(st, when, callback, data);
1338 }
1339
1340 static int send_ping(const void *data);
1341
1342 static void __send_ping(const void *data)
1343 {
1344         int callno = (long) data;
1345
1346         ast_mutex_lock(&iaxsl[callno]);
1347
1348         if (iaxs[callno]) {
1349                 if (iaxs[callno]->peercallno) {
1350                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1351                         iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1352                 } else {
1353                         /* I am the schedule, so I'm allowed to do this */
1354                         iaxs[callno]->pingid = -1;
1355                 }
1356         } else {
1357                 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1358         }
1359
1360         ast_mutex_unlock(&iaxsl[callno]);
1361 }
1362
1363 static int send_ping(const void *data)
1364 {
1365 #ifdef SCHED_MULTITHREADED
1366         if (schedule_action(__send_ping, data))
1367 #endif          
1368                 __send_ping(data);
1369
1370         return 0;
1371 }
1372
1373 static void encmethods_to_str(int e, struct ast_str *buf)
1374 {
1375         ast_str_set(&buf, 0, "(");
1376         if (e & IAX_ENCRYPT_AES128) {
1377                 ast_str_append(&buf, 0, "aes128");
1378         }
1379         if (e & IAX_ENCRYPT_KEYROTATE) {
1380                 ast_str_append(&buf, 0, ",keyrotate");
1381         }
1382         if (ast_str_strlen(buf) > 1) {
1383                 ast_str_append(&buf, 0, ")");
1384         } else {
1385                 ast_str_set(&buf, 0, "No");
1386         }
1387 }
1388
1389 static int get_encrypt_methods(const char *s)
1390 {
1391         int e;
1392         if (!strcasecmp(s, "aes128"))
1393                 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1394         else if (ast_true(s))
1395                 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1396         else
1397                 e = 0;
1398         return e;
1399 }
1400
1401 static int send_lagrq(const void *data);
1402
1403 static void __send_lagrq(const void *data)
1404 {
1405         int callno = (long) data;
1406
1407         ast_mutex_lock(&iaxsl[callno]);
1408
1409         if (iaxs[callno]) {
1410                 if (iaxs[callno]->peercallno) {
1411                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1412                         iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1413                 } else {
1414                         /* I am the schedule, so I'm allowed to do this */
1415                         iaxs[callno]->lagid = -1;
1416                 }
1417         } else {
1418                 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1419         }
1420
1421         ast_mutex_unlock(&iaxsl[callno]);
1422 }
1423
1424 static int send_lagrq(const void *data)
1425 {
1426 #ifdef SCHED_MULTITHREADED
1427         if (schedule_action(__send_lagrq, data))
1428 #endif          
1429                 __send_lagrq(data);
1430         
1431         return 0;
1432 }
1433
1434 static unsigned char compress_subclass(int subclass)
1435 {
1436         int x;
1437         int power=-1;
1438         /* If it's 128 or smaller, just return it */
1439         if (subclass < IAX_FLAG_SC_LOG)
1440                 return subclass;
1441         /* Otherwise find its power */
1442         for (x = 0; x < IAX_MAX_SHIFT; x++) {
1443                 if (subclass & (1 << x)) {
1444                         if (power > -1) {
1445                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1446                                 return 0;
1447                         } else
1448                                 power = x;
1449                 }
1450         }
1451         return power | IAX_FLAG_SC_LOG;
1452 }
1453
1454 static int uncompress_subclass(unsigned char csub)
1455 {
1456         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1457         if (csub & IAX_FLAG_SC_LOG) {
1458                 /* special case for 'compressed' -1 */
1459                 if (csub == 0xff)
1460                         return -1;
1461                 else
1462                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1463         }
1464         else
1465                 return csub;
1466 }
1467
1468 /*!
1469  * \note The only member of the peer passed here guaranteed to be set is the name field
1470  */
1471 static int peer_hash_cb(const void *obj, const int flags)
1472 {
1473         const struct iax2_peer *peer = obj;
1474
1475         return ast_str_hash(peer->name);
1476 }
1477
1478 /*!
1479  * \note The only member of the peer passed here guaranteed to be set is the name field
1480  */
1481 static int peer_cmp_cb(void *obj, void *arg, int flags)
1482 {
1483         struct iax2_peer *peer = obj, *peer2 = arg;
1484
1485         return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
1486 }
1487
1488 /*!
1489  * \note The only member of the user passed here guaranteed to be set is the name field
1490  */
1491 static int user_hash_cb(const void *obj, const int flags)
1492 {
1493         const struct iax2_user *user = obj;
1494
1495         return ast_str_hash(user->name);
1496 }
1497
1498 /*!
1499  * \note The only member of the user passed here guaranteed to be set is the name field
1500  */
1501 static int user_cmp_cb(void *obj, void *arg, int flags)
1502 {
1503         struct iax2_user *user = obj, *user2 = arg;
1504
1505         return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
1506 }
1507
1508 /*!
1509  * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1510  *       so do not call it with a pvt lock held.
1511  */
1512 static struct iax2_peer *find_peer(const char *name, int realtime) 
1513 {
1514         struct iax2_peer *peer = NULL;
1515         struct iax2_peer tmp_peer = {
1516                 .name = name,
1517         };
1518
1519         peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1520
1521         /* Now go for realtime if applicable */
1522         if(!peer && realtime)
1523                 peer = realtime_peer(name, NULL);
1524
1525         return peer;
1526 }
1527
1528 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1529 {
1530         ao2_ref(peer, +1);
1531         return peer;
1532 }
1533
1534 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1535 {
1536         ao2_ref(peer, -1);
1537         return NULL;
1538 }
1539
1540 static struct iax2_user *find_user(const char *name)
1541 {
1542         struct iax2_user tmp_user = {
1543                 .name = name,
1544         };
1545
1546         return ao2_find(users, &tmp_user, OBJ_POINTER);
1547 }
1548 static inline struct iax2_user *user_ref(struct iax2_user *user)
1549 {
1550         ao2_ref(user, +1);
1551         return user;
1552 }
1553
1554 static inline struct iax2_user *user_unref(struct iax2_user *user)
1555 {
1556         ao2_ref(user, -1);
1557         return NULL;
1558 }
1559
1560 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1561 {
1562         struct iax2_peer *peer = NULL;
1563         int res = 0;
1564         struct ao2_iterator i;
1565
1566         i = ao2_iterator_init(peers, 0);
1567         while ((peer = ao2_iterator_next(&i))) {
1568                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1569                     (peer->addr.sin_port == sin.sin_port)) {
1570                         ast_copy_string(host, peer->name, len);
1571                         peer_unref(peer);
1572                         res = 1;
1573                         break;
1574                 }
1575                 peer_unref(peer);
1576         }
1577
1578         if (!peer) {
1579                 peer = realtime_peer(NULL, &sin);
1580                 if (peer) {
1581                         ast_copy_string(host, peer->name, len);
1582                         peer_unref(peer);
1583                         res = 1;
1584                 }
1585         }
1586
1587         return res;
1588 }
1589
1590 /*!\note Assumes the lock on the pvt is already held, when
1591  * iax2_destroy_helper() is called. */
1592 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1593 {
1594         /* Decrement AUTHREQ count if needed */
1595         if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1596                 struct iax2_user *user;
1597                 struct iax2_user tmp_user = {
1598                         .name = pvt->username,
1599                 };
1600
1601                 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1602                 if (user) {
1603                         ast_atomic_fetchadd_int(&user->curauthreq, -1);
1604                         user_unref(user);       
1605                 }
1606
1607                 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1608         }
1609         /* No more pings or lagrq's */
1610         AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
1611         AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
1612         ast_sched_thread_del(sched, pvt->autoid);
1613         ast_sched_thread_del(sched, pvt->authid);
1614         ast_sched_thread_del(sched, pvt->initid);
1615         ast_sched_thread_del(sched, pvt->jbid);
1616         ast_sched_thread_del(sched, pvt->keyrotateid);
1617 }
1618
1619 static void iax2_frame_free(struct iax_frame *fr)
1620 {
1621         ast_sched_thread_del(sched, fr->retrans);
1622         iax_frame_free(fr);
1623 }
1624
1625 static int scheduled_destroy(const void *vid)
1626 {
1627         short callno = PTR_TO_CALLNO(vid);
1628         ast_mutex_lock(&iaxsl[callno]);
1629         if (iaxs[callno]) {
1630                 if (option_debug) {
1631                         ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1632                 }
1633                 iax2_destroy(callno);
1634         }
1635         ast_mutex_unlock(&iaxsl[callno]);
1636         return 0;
1637 }
1638
1639 static void pvt_destructor(void *obj)
1640 {
1641         struct chan_iax2_pvt *pvt = obj;
1642         struct iax_frame *cur = NULL;
1643
1644         ast_mutex_lock(&iaxsl[pvt->callno]);
1645
1646         iax2_destroy_helper(pvt);
1647
1648         /* Already gone */
1649         ast_set_flag(pvt, IAX_ALREADYGONE);
1650
1651         AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
1652                 /* Cancel any pending transmissions */
1653                 cur->retries = -1;
1654         }
1655
1656         ast_mutex_unlock(&iaxsl[pvt->callno]);
1657
1658         if (pvt->reg) {
1659                 pvt->reg->callno = 0;
1660         }
1661
1662         if (!pvt->owner) {
1663                 jb_frame frame;
1664                 if (pvt->vars) {
1665                     ast_variables_destroy(pvt->vars);
1666                     pvt->vars = NULL;
1667                 }
1668
1669                 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1670                         iax2_frame_free(frame.data);
1671                 }
1672
1673                 jb_destroy(pvt->jb);
1674                 ast_string_field_free_memory(pvt);
1675         }
1676 }
1677
1678 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1679 {
1680         struct chan_iax2_pvt *tmp;
1681         jb_conf jbconf;
1682
1683         if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1684                 return NULL;
1685         }
1686
1687         if (ast_string_field_init(tmp, 32)) {
1688                 ao2_ref(tmp, -1);
1689                 tmp = NULL;
1690                 return NULL;
1691         }
1692                 
1693         tmp->prefs = prefs;
1694         tmp->pingid = -1;
1695         tmp->lagid = -1;
1696         tmp->autoid = -1;
1697         tmp->authid = -1;
1698         tmp->initid = -1;
1699         tmp->keyrotateid = -1;
1700
1701         ast_string_field_set(tmp,exten, "s");
1702         ast_string_field_set(tmp,host, host);
1703
1704         tmp->jb = jb_new();
1705         tmp->jbid = -1;
1706         jbconf.max_jitterbuf = maxjitterbuffer;
1707         jbconf.resync_threshold = resyncthreshold;
1708         jbconf.max_contig_interp = maxjitterinterps;
1709         jbconf.target_extra = jittertargetextra;
1710         jb_setconf(tmp->jb,&jbconf);
1711
1712         AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1713
1714         return tmp;
1715 }
1716
1717 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1718 {
1719         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1720         if (new) {
1721                 size_t afdatalen = new->afdatalen;
1722                 memcpy(new, fr, sizeof(*new));
1723                 iax_frame_wrap(new, &fr->af);
1724                 new->afdatalen = afdatalen;
1725                 new->data = NULL;
1726                 new->datalen = 0;
1727                 new->direction = DIRECTION_INGRESS;
1728                 new->retrans = -1;
1729         }
1730         return new;
1731 }
1732
1733 #define NEW_PREVENT     0
1734 #define NEW_ALLOW       1
1735 #define NEW_FORCE       2
1736
1737 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1738 {
1739         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1740                 (cur->addr.sin_port == sin->sin_port)) {
1741                 /* This is the main host */
1742                 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1743                          (check_dcallno ? dcallno == cur->callno : 1) ) {
1744                         /* That's us.  Be sure we keep track of the peer call number */
1745                         return 1;
1746                 }
1747         }
1748         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1749             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1750                 /* We're transferring */
1751                 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1752                         return 1;
1753         }
1754         return 0;
1755 }
1756
1757 static void update_max_trunk(void)
1758 {
1759         int max = TRUNK_CALL_START;
1760         int x;
1761
1762         /* XXX Prolly don't need locks here XXX */
1763         for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1764                 if (iaxs[x]) {
1765                         max = x + 1;
1766                 }
1767         }
1768
1769         maxtrunkcall = max;
1770         if (iaxdebug)
1771                 ast_debug(1, "New max trunk callno is %d\n", max);
1772 }
1773
1774 static void update_max_nontrunk(void)
1775 {
1776         int max = 1;
1777         int x;
1778         /* XXX Prolly don't need locks here XXX */
1779         for (x=1;x<TRUNK_CALL_START - 1; x++) {
1780                 if (iaxs[x])
1781                         max = x + 1;
1782         }
1783         maxnontrunkcall = max;
1784         if (iaxdebug)
1785                 ast_debug(1, "New max nontrunk callno is %d\n", max);
1786 }
1787
1788 static int make_trunk(unsigned short callno, int locked)
1789 {
1790         int x;
1791         int res= 0;
1792         struct timeval now = ast_tvnow();
1793         if (iaxs[callno]->oseqno) {
1794                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1795                 return -1;
1796         }
1797         if (callno & TRUNK_CALL_START) {
1798                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1799                 return -1;
1800         }
1801         for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1802                 ast_mutex_lock(&iaxsl[x]);
1803                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1804                         /*!
1805                          * \note We delete these before switching the slot, because if
1806                          * they fire in the meantime, they will generate a warning.
1807                          */
1808                         ast_sched_thread_del(sched, iaxs[callno]->pingid);
1809                         ast_sched_thread_del(sched, iaxs[callno]->lagid);
1810                         iaxs[x] = iaxs[callno];
1811                         iaxs[x]->callno = x;
1812                         iaxs[callno] = NULL;
1813                         /* Update the two timers that should have been started */
1814                         iaxs[x]->pingid = iax2_sched_add(sched, 
1815                                 ping_time * 1000, send_ping, (void *)(long)x);
1816                         iaxs[x]->lagid = iax2_sched_add(sched, 
1817                                 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1818                         if (locked)
1819                                 ast_mutex_unlock(&iaxsl[callno]);
1820                         res = x;
1821                         if (!locked)
1822                                 ast_mutex_unlock(&iaxsl[x]);
1823                         break;
1824                 }
1825                 ast_mutex_unlock(&iaxsl[x]);
1826         }
1827         if (x >= ARRAY_LEN(iaxs) - 1) {
1828                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1829                 return -1;
1830         }
1831         ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1832         /* We move this call from a non-trunked to a trunked call */
1833         update_max_trunk();
1834         update_max_nontrunk();
1835         return res;
1836 }
1837
1838 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
1839 {
1840         if (!pvt->transfercallno) {
1841                 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1842                 return;
1843         }
1844
1845         ao2_link(iax_transfercallno_pvts, pvt);
1846 }
1847
1848 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
1849 {
1850         if (!pvt->transfercallno) {
1851                 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
1852                 return;
1853         }
1854
1855         ao2_unlink(iax_transfercallno_pvts, pvt);
1856 }
1857 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1858 {
1859         if (!pvt->peercallno) {
1860                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1861                 return;
1862         }
1863
1864         ao2_link(iax_peercallno_pvts, pvt);
1865 }
1866
1867 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1868 {
1869         if (!pvt->peercallno) {
1870                 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1871                 return;
1872         }
1873
1874         ao2_unlink(iax_peercallno_pvts, pvt);
1875 }
1876
1877 /*
1878  * \note Calling this function while holding another pvt lock can cause a deadlock.
1879  */
1880 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1881 {
1882         int res = 0;
1883         int x;
1884         struct timeval now;
1885         char host[80];
1886
1887         if (new <= NEW_ALLOW) {
1888                 if (callno) {
1889                         struct chan_iax2_pvt *pvt;
1890                         struct chan_iax2_pvt tmp_pvt = {
1891                                 .callno = dcallno,
1892                                 .peercallno = callno,
1893                                 .transfercallno = callno,
1894                                 /* hack!! */
1895                                 .frames_received = check_dcallno,
1896                         };
1897
1898                         memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1899                         /* this works for finding normal call numbers not involving transfering */ 
1900                         if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1901                                 if (return_locked) {
1902                                         ast_mutex_lock(&iaxsl[pvt->callno]);
1903                                 }
1904                                 res = pvt->callno;
1905                                 ao2_ref(pvt, -1);
1906                                 pvt = NULL;
1907                                 return res;
1908                         }
1909                         /* this searches for transfer call numbers that might not get caught otherwise */
1910                         memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
1911                         memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.addr));
1912                         if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1913                                 if (return_locked) {
1914                                         ast_mutex_lock(&iaxsl[pvt->callno]);
1915                                 }
1916                                 res = pvt->callno;
1917                                 ao2_ref(pvt, -1);
1918                                 pvt = NULL;
1919                                 return res;
1920                         }
1921                 }
1922                         /* This will occur on the first response to a message that we initiated,
1923                  * such as a PING. */
1924                 if (dcallno) {
1925                         ast_mutex_lock(&iaxsl[dcallno]);
1926                 }
1927                 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1928                         iaxs[dcallno]->peercallno = callno;
1929                         res = dcallno;
1930                         store_by_peercallno(iaxs[dcallno]);
1931                         if (!res || !return_locked) {
1932                                 ast_mutex_unlock(&iaxsl[dcallno]);
1933                         }
1934                         return res;
1935                 }
1936                 if (dcallno) {
1937                         ast_mutex_unlock(&iaxsl[dcallno]);
1938                 }
1939 #ifdef IAX_OLD_FIND
1940                 /* If we get here, we SHOULD NOT find a call structure for this
1941                    callno; if we do, it means that there is a call structure that
1942                    has a peer callno but did NOT get entered into the hash table,
1943                    which is bad.
1944
1945                    If we find a call structure using this old, slow method, output a log
1946                    message so we'll know about it. After a few months of leaving this in
1947                    place, if we don't hear about people seeing these messages, we can
1948                    remove this code for good.
1949                 */
1950
1951                 for (x = 1; !res && x < maxnontrunkcall; x++) {
1952                         ast_mutex_lock(&iaxsl[x]);
1953                         if (iaxs[x]) {
1954                                 /* Look for an exact match */
1955                                 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1956                                         res = x;
1957                                 }
1958                         }
1959                         if (!res || !return_locked)
1960                                 ast_mutex_unlock(&iaxsl[x]);
1961                 }
1962                 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1963                         ast_mutex_lock(&iaxsl[x]);
1964                         if (iaxs[x]) {
1965                                 /* Look for an exact match */
1966                                 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1967                                         res = x;
1968                                 }
1969                         }
1970                         if (!res || !return_locked)
1971                                 ast_mutex_unlock(&iaxsl[x]);
1972                 }
1973 #endif
1974         }
1975         if (!res && (new >= NEW_ALLOW)) {
1976                 int start, found = 0;
1977
1978                 /* It may seem odd that we look through the peer list for a name for
1979                  * this *incoming* call.  Well, it is weird.  However, users don't
1980                  * have an IP address/port number that we can match against.  So,
1981                  * this is just checking for a peer that has that IP/port and
1982                  * assuming that we have a user of the same name.  This isn't always
1983                  * correct, but it will be changed if needed after authentication. */
1984                 if (!iax2_getpeername(*sin, host, sizeof(host)))
1985                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1986
1987                 now = ast_tvnow();
1988                 start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1989                 for (x = start; 1; x++) {
1990                         if (x == TRUNK_CALL_START) {
1991                                 x = 1;
1992                                 continue;
1993                         }
1994
1995                         /* Find first unused call number that hasn't been used in a while */
1996                         ast_mutex_lock(&iaxsl[x]);
1997                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1998                                 found = 1;
1999                                 break;
2000                         }
2001                         ast_mutex_unlock(&iaxsl[x]);
2002                         
2003                         if (x == start - 1) {
2004                                 break;
2005                         }
2006                 }
2007                 /* We've still got lock held if we found a spot */
2008                 if (x == start - 1 && !found) {
2009                         ast_log(LOG_WARNING, "No more space\n");
2010                         return 0;
2011                 }
2012                 iaxs[x] = new_iax(sin, host);
2013                 update_max_nontrunk();
2014                 if (iaxs[x]) {
2015                         if (iaxdebug)
2016                                 ast_debug(1, "Creating new call structure %d\n", x);
2017                         iaxs[x]->sockfd = sockfd;
2018                         iaxs[x]->addr.sin_port = sin->sin_port;
2019                         iaxs[x]->addr.sin_family = sin->sin_family;
2020                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2021                         iaxs[x]->peercallno = callno;
2022                         iaxs[x]->callno = x;
2023                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2024                         iaxs[x]->expiry = min_reg_expire;
2025                         iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2026                         iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2027                         iaxs[x]->amaflags = amaflags;
2028                         ast_copy_flags(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2029                         ast_string_field_set(iaxs[x], accountcode, accountcode);
2030                         ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2031                         ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2032                         ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2033
2034                         if (iaxs[x]->peercallno) {
2035                                 store_by_peercallno(iaxs[x]);
2036                         }
2037                 } else {
2038                         ast_log(LOG_WARNING, "Out of resources\n");
2039                         ast_mutex_unlock(&iaxsl[x]);
2040                         return 0;
2041                 }
2042                 if (!return_locked)
2043                         ast_mutex_unlock(&iaxsl[x]);
2044                 res = x;
2045         }
2046         return res;
2047 }
2048
2049 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2050
2051         return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2052 }
2053
2054 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2055
2056         return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2057 }
2058
2059 /*!
2060  * \brief Queue a frame to a call's owning asterisk channel
2061  *
2062  * \pre This function assumes that iaxsl[callno] is locked when called.
2063  *
2064  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2065  * was valid before calling it, it may no longer be valid after calling it.
2066  * This function may unlock and lock the mutex associated with this callno,
2067  * meaning that another thread may grab it and destroy the call.
2068  */
2069 static int iax2_queue_frame(int callno, struct ast_frame *f)
2070 {
2071         for (;;) {
2072                 if (iaxs[callno] && iaxs[callno]->owner) {
2073                         if (ast_channel_trylock(iaxs[callno]->owner)) {
2074                                 /* Avoid deadlock by pausing and trying again */
2075                                 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2076                         } else {
2077                                 ast_queue_frame(iaxs[callno]->owner, f);
2078                                 ast_channel_unlock(iaxs[callno]->owner);
2079                                 break;
2080                         }
2081                 } else
2082                         break;
2083         }
2084         return 0;
2085 }
2086
2087 /*!
2088  * \brief Queue a hangup frame on the ast_channel owner
2089  *
2090  * This function queues a hangup frame on the owner of the IAX2 pvt struct that
2091  * is active for the given call number.
2092  *
2093  * \pre Assumes lock for callno is already held.
2094  *
2095  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2096  * was valid before calling it, it may no longer be valid after calling it.
2097  * This function may unlock and lock the mutex associated with this callno,
2098  * meaning that another thread may grab it and destroy the call.
2099  */
2100 static int iax2_queue_hangup(int callno)
2101 {
2102         for (;;) {
2103                 if (iaxs[callno] && iaxs[callno]->owner) {
2104                         if (ast_channel_trylock(iaxs[callno]->owner)) {
2105                                 /* Avoid deadlock by pausing and trying again */
2106                                 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2107                         } else {
2108                                 ast_queue_hangup(iaxs[callno]->owner);
2109                                 ast_channel_unlock(iaxs[callno]->owner);
2110                                 break;
2111                         }
2112                 } else
2113                         break;
2114         }
2115         return 0;
2116 }
2117
2118 /*!
2119  * \brief Queue a control frame on the ast_channel owner
2120  *
2121  * This function queues a control frame on the owner of the IAX2 pvt struct that
2122  * is active for the given call number.
2123  *
2124  * \pre Assumes lock for callno is already held.
2125  *
2126  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2127  * was valid before calling it, it may no longer be valid after calling it.
2128  * This function may unlock and lock the mutex associated with this callno,
2129  * meaning that another thread may grab it and destroy the call.
2130  */
2131 static int iax2_queue_control_data(int callno, 
2132         enum ast_control_frame_type control, const void *data, size_t datalen)
2133 {
2134         for (;;) {
2135                 if (iaxs[callno] && iaxs[callno]->owner) {
2136                         if (ast_channel_trylock(iaxs[callno]->owner)) {
2137                                 /* Avoid deadlock by pausing and trying again */
2138                                 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2139                         } else {
2140                                 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
2141                                 ast_channel_unlock(iaxs[callno]->owner);
2142                                 break;
2143                         }
2144                 } else
2145                         break;
2146         }
2147         return 0;
2148 }
2149 static void destroy_firmware(struct iax_firmware *cur)
2150 {
2151         /* Close firmware */
2152         if (cur->fwh) {
2153                 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
2154         }
2155         close(cur->fd);
2156         ast_free(cur);
2157 }
2158
2159 static int try_firmware(char *s)
2160 {
2161         struct stat stbuf;
2162         struct iax_firmware *cur = NULL;
2163         int ifd, fd, res, len, chunk;
2164         struct ast_iax2_firmware_header *fwh, fwh2;
2165         struct MD5Context md5;
2166         unsigned char sum[16], buf[1024];
2167         char *s2, *last;
2168
2169         if (!(s2 = alloca(strlen(s) + 100))) {
2170                 ast_log(LOG_WARNING, "Alloca failed!\n");
2171                 return -1;
2172         }
2173
2174         last = strrchr(s, '/');
2175         if (last)
2176                 last++;
2177         else
2178                 last = s;
2179
2180         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
2181
2182         if ((res = stat(s, &stbuf) < 0)) {
2183                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
2184                 return -1;
2185         }
2186
2187         /* Make sure it's not a directory */
2188         if (S_ISDIR(stbuf.st_mode))
2189                 return -1;
2190         ifd = open(s, O_RDONLY);
2191         if (ifd < 0) {
2192                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
2193                 return -1;
2194         }
2195         fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
2196         if (fd < 0) {
2197                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
2198                 close(ifd);
2199                 return -1;
2200         }
2201         /* Unlink our newly created file */
2202         unlink(s2);
2203         
2204         /* Now copy the firmware into it */
2205         len = stbuf.st_size;
2206         while(len) {
2207                 chunk = len;
2208                 if (chunk > sizeof(buf))
2209                         chunk = sizeof(buf);
2210                 res = read(ifd, buf, chunk);
2211                 if (res != chunk) {
2212                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2213                         close(ifd);
2214                         close(fd);
2215                         return -1;
2216                 }
2217                 res = write(fd, buf, chunk);
2218                 if (res != chunk) {
2219                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2220                         close(ifd);
2221                         close(fd);
2222                         return -1;
2223                 }
2224                 len -= chunk;
2225         }
2226         close(ifd);
2227         /* Return to the beginning */
2228         lseek(fd, 0, SEEK_SET);
2229         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2230                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2231                 close(fd);
2232                 return -1;
2233         }
2234         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2235                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2236                 close(fd);
2237                 return -1;
2238         }
2239         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2240                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2241                 close(fd);
2242                 return -1;
2243         }
2244         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2245                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2246                 close(fd);
2247                 return -1;
2248         }
2249         fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
2250         if (fwh == MAP_FAILED) {
2251                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
2252                 close(fd);
2253                 return -1;
2254         }
2255         MD5Init(&md5);
2256         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2257         MD5Final(sum, &md5);
2258         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2259                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2260                 munmap((void*)fwh, stbuf.st_size);
2261                 close(fd);
2262                 return -1;
2263         }
2264
2265         AST_LIST_TRAVERSE(&firmwares, cur, list) {
2266                 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
2267                         /* Found a candidate */
2268                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
2269                                 /* The version we have on loaded is older, load this one instead */
2270                                 break;
2271                         /* This version is no newer than what we have.  Don't worry about it.
2272                            We'll consider it a proper load anyhow though */
2273                         munmap((void*)fwh, stbuf.st_size);
2274                         close(fd);
2275                         return 0;
2276                 }
2277         }
2278         
2279         if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2280                 cur->fd = -1;
2281                 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2282         }
2283         
2284         if (cur) {
2285                 if (cur->fwh)
2286                         munmap((void*)cur->fwh, cur->mmaplen);
2287                 if (cur->fd > -1)
2288                         close(cur->fd);
2289                 cur->fwh = fwh;
2290                 cur->fd = fd;
2291                 cur->mmaplen = stbuf.st_size;
2292                 cur->dead = 0;
2293         }
2294         
2295         return 0;
2296 }
2297
2298 static int iax_check_version(char *dev)
2299 {
2300         int res = 0;
2301         struct iax_firmware *cur = NULL;
2302
2303         if (ast_strlen_zero(dev))
2304                 return 0;
2305
2306         AST_LIST_LOCK(&firmwares);
2307         AST_LIST_TRAVERSE(&firmwares, cur, list) {
2308                 if (!strcmp(dev, (char *)cur->fwh->devname)) {
2309                         res = ntohs(cur->fwh->version);
2310                         break;
2311                 }
2312         }
2313         AST_LIST_UNLOCK(&firmwares);
2314
2315         return res;
2316 }
2317
2318 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2319 {
2320         int res = -1;
2321         unsigned int bs = desc & 0xff;
2322         unsigned int start = (desc >> 8) & 0xffffff;
2323         unsigned int bytes;
2324         struct iax_firmware *cur;
2325
2326         if (ast_strlen_zero((char *)dev) || !bs)
2327                 return -1;
2328
2329         start *= bs;
2330         
2331         AST_LIST_LOCK(&firmwares);
2332         AST_LIST_TRAVERSE(&firmwares, cur, list) {
2333                 if (strcmp((char *)dev, (char *)cur->fwh->devname))
2334                         continue;
2335                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2336                 if (start < ntohl(cur->fwh->datalen)) {
2337                         bytes = ntohl(cur->fwh->datalen) - start;
2338                         if (bytes > bs)
2339                                 bytes = bs;
2340                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2341                 } else {
2342                         bytes = 0;
2343                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2344                 }
2345                 if (bytes == bs)
2346                         res = 0;
2347                 else
2348                         res = 1;
2349                 break;
2350         }
2351         AST_LIST_UNLOCK(&firmwares);
2352
2353         return res;
2354 }
2355
2356
2357 static void reload_firmware(int unload)
2358 {
2359         struct iax_firmware *cur = NULL;
2360         DIR *fwd;
2361         struct dirent *de;
2362         char dir[256], fn[256];
2363
2364         AST_LIST_LOCK(&firmwares);
2365
2366         /* Mark all as dead */
2367         AST_LIST_TRAVERSE(&firmwares, cur, list)
2368                 cur->dead = 1;
2369
2370         /* Now that we have marked them dead... load new ones */
2371         if (!unload) {
2372                 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2373                 fwd = opendir(dir);
2374                 if (fwd) {
2375                         while((de = readdir(fwd))) {
2376                                 if (de->d_name[0] != '.') {
2377                                         snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2378                                         if (!try_firmware(fn)) {
2379                                                 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2380                                         }
2381                                 }
2382                         }
2383                         closedir(fwd);
2384                 } else 
2385                         ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2386         }
2387
2388         /* Clean up leftovers */
2389         AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2390                 if (!cur->dead)
2391                         continue;
2392                 AST_LIST_REMOVE_CURRENT(list);
2393                 destroy_firmware(cur);
2394         }
2395         AST_LIST_TRAVERSE_SAFE_END;
2396
2397         AST_LIST_UNLOCK(&firmwares);
2398 }
2399
2400 /*!
2401  * \note This function assumes that iaxsl[callno] is locked when called.
2402  *
2403  * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2404  * was valid before calling it, it may no longer be valid after calling it.
2405  * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
2406  * associated with this callno, meaning that another thread may grab it and destroy the call.
2407  */
2408 static int __do_deliver(void *data)
2409 {
2410         /* Just deliver the packet by using queueing.  This is called by
2411           the IAX thread with the iaxsl lock held. */
2412         struct iax_frame *fr = data;
2413         fr->retrans = -1;
2414         ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2415         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2416                 iax2_queue_frame(fr->callno, &fr->af);
2417         /* Free our iax frame */
2418         iax2_frame_free(fr);
2419         /* And don't run again */
2420         return 0;
2421 }
2422
2423 static int handle_error(void)
2424 {
2425         /* XXX Ideally we should figure out why an error occurred and then abort those
2426            rather than continuing to try.  Unfortunately, the published interface does
2427            not seem to work XXX */
2428 #if 0
2429         struct sockaddr_in *sin;
2430         int res;
2431         struct msghdr m;
2432         struct sock_extended_err e;
2433         m.msg_name = NULL;
2434         m.msg_namelen = 0;
2435         m.msg_iov = NULL;
2436         m.msg_control = &e;
2437         m.msg_controllen = sizeof(e);
2438         m.msg_flags = 0;
2439         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2440         if (res < 0)
2441                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2442         else {
2443                 if (m.msg_controllen) {
2444                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2445                         if (sin) 
2446                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2447                         else
2448                                 ast_log(LOG_WARNING, "No address detected??\n");
2449                 } else {
2450                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2451                 }
2452         }
2453 #endif
2454         return 0;
2455 }
2456
2457 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2458 {
2459         int res;
2460         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2461                                         sizeof(*sin));
2462         if (res < 0) {
2463                 ast_debug(1, "Received error: %s\n", strerror(errno));
2464                 handle_error();
2465         } else
2466                 res = 0;
2467         return res;
2468 }
2469
2470 static int send_packet(struct iax_frame *f)
2471 {
2472         int res;
2473         int callno = f->callno;
2474
2475         /* Don't send if there was an error, but return error instead */
2476         if (!callno || !iaxs[callno] || iaxs[callno]->error)
2477             return -1;
2478         
2479         /* Called with iaxsl held */
2480         if (iaxdebug)
2481                 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));
2482         
2483         if (f->transfer) {
2484                 if (iaxdebug)
2485                         iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2486                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
2487         } else {
2488                 if (iaxdebug)
2489                         iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2490                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
2491         }
2492         if (res < 0) {
2493                 if (iaxdebug)
2494                         ast_debug(1, "Received error: %s\n", strerror(errno));
2495                 handle_error();
2496         } else
2497                 res = 0;
2498
2499         return res;
2500 }
2501
2502 /*!
2503  * \note Since this function calls iax2_queue_hangup(), the pvt struct
2504  *       for the given call number may disappear during its execution.
2505  */
2506 static int iax2_predestroy(int callno)
2507 {
2508         struct ast_channel *c = NULL;
2509         struct chan_iax2_pvt *pvt = iaxs[callno];
2510
2511         if (!pvt)
2512                 return -1;
2513
2514         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2515                 iax2_destroy_helper(pvt);
2516                 ast_set_flag(pvt, IAX_ALREADYGONE);     
2517         }
2518
2519         if ((c = pvt->owner)) {
2520                 c->tech_pvt = NULL;
2521                 iax2_queue_hangup(callno);
2522                 pvt->owner = NULL;
2523                 ast_module_unref(ast_module_info->self);
2524         }
2525
2526         return 0;
2527 }
2528
2529 static void iax2_destroy(int callno)
2530 {
2531         struct chan_iax2_pvt *pvt = NULL;
2532         struct ast_channel *owner = NULL;
2533
2534 retry:
2535         if ((pvt = iaxs[callno])) {
2536                 iax2_destroy_helper(pvt);
2537         }
2538
2539         lastused[callno] = ast_tvnow();
2540         
2541         owner = pvt ? pvt->owner : NULL;
2542
2543         if (owner) {
2544                 if (ast_channel_trylock(owner)) {
2545                         ast_debug(3, "Avoiding IAX destroy deadlock\n");
2546                         DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2547                         goto retry;
2548                 }
2549         }
2550
2551         if (!owner) {
2552                 iaxs[callno] = NULL;
2553         }
2554
2555         if (pvt) {
2556                 if (!owner) {
2557                         pvt->owner = NULL;
2558                 } else {
2559                         /* If there's an owner, prod it to give up */
2560                         /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2561                          * because we already hold the owner channel lock. */
2562                         ast_queue_hangup(owner);
2563                 }
2564
2565                 if (pvt->peercallno) {
2566                         remove_by_peercallno(pvt);
2567                 }
2568
2569                 if (pvt->transfercallno) {
2570                         remove_by_transfercallno(pvt);
2571                 }
2572
2573                 if (!owner) {
2574                         ao2_ref(pvt, -1);
2575                         pvt = NULL;
2576                 }
2577         }
2578
2579         if (owner) {
2580                 ast_channel_unlock(owner);
2581         }
2582
2583         if (callno & 0x4000) {
2584                 update_max_trunk();
2585         }
2586 }
2587
2588 static int update_packet(struct iax_frame *f)
2589 {
2590         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2591         struct ast_iax2_full_hdr *fh = f->data;
2592         struct ast_frame af;
2593
2594         /* if frame is encrypted. decrypt before updating it. */
2595         if (f->encmethods) {
2596                 decode_frame(&f->mydcx, fh, &af, &f->datalen);
2597         }
2598         /* Mark this as a retransmission */
2599         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2600         /* Update iseqno */
2601         f->iseqno = iaxs[f->callno]->iseqno;
2602         fh->iseqno = f->iseqno;
2603
2604         /* Now re-encrypt the frame */
2605         if (f->encmethods) {
2606         /* since this is a retransmit frame, create a new random padding
2607          * before re-encrypting. */
2608                 build_rand_pad(f->semirand, sizeof(f->semirand));
2609                 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
2610         }
2611         return 0;
2612 }
2613
2614 static int attempt_transmit(const void *data);
2615 static void __attempt_transmit(const void *data)
2616 {
2617         /* Attempt to transmit the frame to the remote peer...
2618            Called without iaxsl held. */
2619         struct iax_frame *f = (struct iax_frame *)data;
2620         int freeme = 0;
2621         int callno = f->callno;
2622         /* Make sure this call is still active */
2623         if (callno) 
2624                 ast_mutex_lock(&iaxsl[callno]);
2625         if (callno && iaxs[callno]) {
2626                 if ((f->retries < 0) /* Already ACK'd */ ||
2627                     (f->retries >= max_retries) /* Too many attempts */) {
2628                                 /* Record an error if we've transmitted too many times */
2629                                 if (f->retries >= max_retries) {
2630                                         if (f->transfer) {
2631                                                 /* Transfer timeout */
2632                                                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2633                                         } else if (f->final) {
2634                                                 iax2_destroy(callno);
2635                                         } else {
2636                                                 if (iaxs[callno]->owner)
2637                                                         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);
2638                                                 iaxs[callno]->error = ETIMEDOUT;
2639                                                 if (iaxs[callno]->owner) {
2640                                                         struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
2641                                                         /* Hangup the fd */
2642                                                         iax2_queue_frame(callno, &fr); /* XXX */
2643                                                         /* Remember, owner could disappear */
2644                                                         if (iaxs[callno] && iaxs[callno]->owner)
2645                                                                 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2646                                                 } else {
2647                                                         if (iaxs[callno]->reg) {
2648                                                                 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2649                                                                 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2650                                                                 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2651                                                         }
2652                                                         iax2_destroy(callno);
2653                                                 }
2654                                         }
2655
2656                                 }
2657                                 freeme = 1;
2658                 } else {
2659                         /* Update it if it needs it */
2660                         update_packet(f);
2661                         /* Attempt transmission */
2662                         send_packet(f);
2663                         f->retries++;
2664                         /* Try again later after 10 times as long */
2665                         f->retrytime *= 10;
2666                         if (f->retrytime > MAX_RETRY_TIME)
2667                                 f->retrytime = MAX_RETRY_TIME;
2668                         /* Transfer messages max out at one second */
2669                         if (f->transfer && (f->retrytime > 1000))
2670                                 f->retrytime = 1000;
2671                         f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2672                 }
2673         } else {
2674                 /* Make sure it gets freed */
2675                 f->retries = -1;
2676                 freeme = 1;
2677         }
2678
2679         if (freeme) {
2680                 /* Don't attempt delivery, just remove it from the queue */
2681                 AST_LIST_REMOVE(&frame_queue[callno], f, list);
2682                 ast_mutex_unlock(&iaxsl[callno]);
2683                 f->retrans = -1;
2684                 /* Free the IAX frame */
2685                 iax2_frame_free(f);
2686         } else if (callno) {
2687                 ast_mutex_unlock(&iaxsl[callno]);
2688         }
2689 }
2690
2691 static int attempt_transmit(const void *data)
2692 {
2693 #ifdef SCHED_MULTITHREADED
2694         if (schedule_action(__attempt_transmit, data))
2695 #endif          
2696                 __attempt_transmit(data);
2697         return 0;
2698 }
2699
2700 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2701 {
2702         struct iax2_peer *peer = NULL;
2703         struct iax2_user *user = NULL;
2704         static const char * const choices[] = { "all", NULL };
2705         char *cmplt;
2706
2707         switch (cmd) {
2708         case CLI_INIT:
2709                 e->command = "iax2 prune realtime";
2710                 e->usage =
2711                         "Usage: iax2 prune realtime [<peername>|all]\n"
2712                         "       Prunes object(s) from the cache\n";
2713                 return NULL;
2714         case CLI_GENERATE:
2715                 if (a->pos == 3) {
2716                         cmplt = ast_cli_complete(a->word, choices, a->n);
2717                         if (!cmplt)
2718                                 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
2719                         return cmplt;
2720                 }
2721                 return NULL;
2722         }
2723         if (a->argc != 4)
2724                 return CLI_SHOWUSAGE;
2725         if (!strcmp(a->argv[3], "all")) {
2726                 prune_users();
2727                 prune_peers();
2728                 ast_cli(a->fd, "Cache flushed successfully.\n");
2729                 return CLI_SUCCESS;
2730         }
2731         peer = find_peer(a->argv[3], 0);
2732         user = find_user(a->argv[3]);
2733         if (peer || user) {
2734                 if (peer) {
2735                         if (ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2736                                 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2737                                 expire_registry(peer_ref(peer));
2738                                 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2739                         } else {
2740                                 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2741                         }
2742                         peer_unref(peer);
2743                 }
2744                 if (user) {
2745                         if (ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
2746                                 ast_set_flag(user, IAX_RTAUTOCLEAR);
2747                                 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
2748                         } else {
2749                                 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
2750                         }
2751                         ao2_unlink(users,user);
2752                         user_unref(user);
2753                 }
2754         } else {
2755                 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
2756         }
2757
2758         return CLI_SUCCESS;
2759 }
2760
2761 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2762 {
2763         switch (cmd) {
2764         case CLI_INIT:
2765                 e->command = "iax2 test losspct";
2766                 e->usage =
2767                         "Usage: iax2 test losspct <percentage>\n"
2768                         "       For testing, throws away <percentage> percent of incoming packets\n";
2769                 return NULL;
2770         case CLI_GENERATE:
2771                 return NULL;
2772         }
2773         if (a->argc != 4)
2774                 return CLI_SHOWUSAGE;
2775
2776         test_losspct = atoi(a->argv[3]);
2777
2778         return CLI_SUCCESS;
2779 }
2780
2781 #ifdef IAXTESTS
2782 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2783 {
2784         switch (cmd) {
2785         case CLI_INIT:
2786                 e->command = "iax2 test late";
2787                 e->usage =
2788                         "Usage: iax2 test late <ms>\n"
2789                         "       For testing, count the next frame as <ms> ms late\n";
2790                 return NULL;
2791         case CLI_GENERATE:
2792                 return NULL;
2793         }
2794
2795         if (a->argc != 4)
2796                 return CLI_SHOWUSAGE;
2797
2798         test_late = atoi(a->argv[3]);
2799
2800         return CLI_SUCCESS;
2801 }
2802
2803 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2804 {
2805         switch (cmd) {
2806         case CLI_INIT:
2807                 e->command = "iax2 test resync";
2808                 e->usage =
2809                         "Usage: iax2 test resync <ms>\n"
2810                         "       For testing, adjust all future frames by <ms> ms\n";
2811                 return NULL;
2812         case CLI_GENERATE:
2813                 return NULL;
2814         }
2815
2816         if (a->argc != 4)
2817                 return CLI_SHOWUSAGE;
2818
2819         test_resync = atoi(a->argv[3]);
2820
2821         return CLI_SUCCESS;
2822 }
2823
2824 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2825 {
2826         switch (cmd) {
2827         case CLI_INIT:
2828                 e->command = "iax2 test jitter";
2829                 e->usage =
2830                         "Usage: iax2 test jitter <ms> <pct>\n"
2831                         "       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2832                         "       percentage of packets. If <pct> is not specified, adds\n"
2833                         "       jitter to all packets.\n";
2834                 return NULL;
2835         case CLI_GENERATE:
2836                 return NULL;
2837         }
2838
2839         if (a->argc < 4 || a->argc > 5)
2840                 return CLI_SHOWUSAGE;
2841
2842         test_jit = atoi(a->argv[3]);
2843         if (a->argc == 5)
2844                 test_jitpct = atoi(a->argv[4]);
2845
2846         return CLI_SUCCESS;
2847 }
2848 #endif /* IAXTESTS */
2849
2850 /*! \brief  peer_status: Report Peer status in character string */
2851 /*      returns 1 if peer is online, -1 if unmonitored */
2852 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2853 {
2854         int res = 0;
2855         if (peer->maxms) {
2856                 if (peer->lastms < 0) {
2857                         ast_copy_string(status, "UNREACHABLE", statuslen);
2858                 } else if (peer->lastms > peer->maxms) {
2859                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2860                         res = 1;
2861                 } else if (peer->lastms) {
2862                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2863                         res = 1;
2864                 } else {
2865                         ast_copy_string(status, "UNKNOWN", statuslen);
2866                 }
2867         } else { 
2868                 ast_copy_string(status, "Unmonitored", statuslen);
2869                 res = -1;
2870         }
2871         return res;
2872 }
2873
2874 /*! \brief Show one peer in detail */
2875 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2876 {
2877         char status[30];
2878         char cbuf[256];
2879         struct iax2_peer *peer;
2880         char codec_buf[512];
2881         struct ast_str *encmethods = ast_str_alloca(256);
2882         int x = 0, codec = 0, load_realtime = 0;
2883
2884         switch (cmd) {
2885         case CLI_INIT:
2886                 e->command = "iax2 show peer";
2887                 e->usage =
2888                         "Usage: iax2 show peer <name>\n"
2889                         "       Display details on specific IAX peer\n";
2890                 return NULL;
2891         case CLI_GENERATE:
2892                 if (a->pos == 3)
2893                         return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
2894                 return NULL;
2895         }
2896
2897         if (a->argc < 4)
2898                 return CLI_SHOWUSAGE;
2899
2900         load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2901
2902         peer = find_peer(a->argv[3], load_realtime);
2903         if (peer) {
2904                 encmethods_to_str(peer->encmethods, encmethods);
2905                 ast_cli(a->fd, "\n\n");
2906                 ast_cli(a->fd, "  * Name       : %s\n", peer->name);
2907                 ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2908                 ast_cli(a->fd, "  Context      : %s\n", peer->context);
2909                 ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
2910                 ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
2911                 ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2912                 ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
2913                 ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
2914                 ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2915                 ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
2916                 ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
2917                 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));
2918                 ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2919                 ast_cli(a->fd, "  Username     : %s\n", peer->username);
2920                 ast_cli(a->fd, "  Codecs       : ");
2921                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2922                 ast_cli(a->fd, "%s\n", codec_buf);
2923
2924                 ast_cli(a->fd, "  Codec Order  : (");
2925                 for(x = 0; x < 32 ; x++) {
2926                         codec = ast_codec_pref_index(&peer->prefs,x);
2927                         if(!codec)
2928                                 break;
2929                         ast_cli(a->fd, "%s", ast_getformatname(codec));
2930                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2931                                 ast_cli(a->fd, "|");
2932                 }
2933
2934                 if (!x)
2935                         ast_cli(a->fd, "none");
2936                 ast_cli(a->fd, ")\n");
2937
2938                 ast_cli(a->fd, "  Status       : ");
2939                 peer_status(peer, status, sizeof(status));      
2940                 ast_cli(a->fd, "%s\n",status);
2941                 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");
2942                 ast_cli(a->fd, "\n");
2943                 peer_unref(peer);
2944         } else {
2945                 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2946                 ast_cli(a->fd, "\n");
2947         }
2948
2949         return CLI_SUCCESS;
2950 }
2951
2952 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags)
2953 {
2954         int which = 0;
2955         struct iax2_peer *peer;
2956         char *res = NULL;
2957         int wordlen = strlen(word);
2958         struct ao2_iterator i;
2959
2960         i = ao2_iterator_init(peers, 0);
2961         while ((peer = ao2_iterator_next(&i))) {
2962                 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
2963                         && (!flags || ast_test_flag(peer, flags))) {
2964                         res = ast_strdup(peer->name);
2965                         peer_unref(peer);
2966                         break;
2967                 }
2968                 peer_unref(peer);
2969         }
2970
2971         return res;
2972 }
2973
2974 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2975 {
2976         struct iax_frame *cur;
2977         int cnt = 0, dead = 0, final = 0, i = 0;
2978
2979         switch (cmd) {
2980         case CLI_INIT:
2981                 e->command = "iax2 show stats";
2982                 e->usage =
2983                         "Usage: iax2 show stats\n"
2984                         "       Display statistics on IAX channel driver.\n";
2985                 return NULL;
2986         case CLI_GENERATE:
2987                 return NULL;
2988         }
2989
2990         if (a->argc != 3)
2991                 return CLI_SHOWUSAGE;
2992
2993         for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
2994                 ast_mutex_lock(&iaxsl[i]);
2995                 AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
2996                         if (cur->retries < 0)
2997                                 dead++;
2998                         if (cur->final)
2999                                 final++;
3000                         cnt++;
3001                 }
3002                 ast_mutex_unlock(&iaxsl[i]);
3003         }
3004
3005         ast_cli(a->fd, "    IAX Statistics\n");
3006         ast_cli(a->fd, "---------------------\n");
3007         ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3008         ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3009                 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3010         ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3011
3012         trunk_timed = trunk_untimed = 0;
3013         if (trunk_maxmtu > trunk_nmaxmtu)
3014                 trunk_nmaxmtu = trunk_maxmtu;
3015
3016         return CLI_SUCCESS;
3017 }
3018
3019 /*! \brief Set trunk MTU from CLI */
3020 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3021 {
3022         int mtuv;
3023
3024         switch (cmd) {
3025         case CLI_INIT:
3026                 e->command = "iax2 set mtu";
3027                 e->usage =
3028                         "Usage: iax2 set mtu <value>\n"
3029                         "       Set the system-wide IAX IP mtu to <value> bytes net or\n"
3030                         "       zero to disable. Disabling means that the operating system\n"
3031                         "       must handle fragmentation of UDP packets when the IAX2 trunk\n"
3032                         "       packet exceeds the UDP payload size. This is substantially\n"
3033                         "       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3034                         "       greater for G.711 samples.\n";
3035                 return NULL;
3036         case CLI_GENERATE:
3037                 return NULL;
3038         }
3039
3040         if (a->argc != 4)
3041                 return CLI_SHOWUSAGE; 
3042         if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3043                 mtuv = MAX_TRUNK_MTU;
3044         else
3045                 mtuv = atoi(a->argv[3]);
3046
3047         if (mtuv == 0) {
3048                 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
3049                 global_max_trunk_mtu = 0; 
3050                 return CLI_SUCCESS; 
3051         }
3052         if (mtuv < 172 || mtuv > 4000) {
3053                 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
3054                 return CLI_SHOWUSAGE; 
3055         }
3056         ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
3057         global_max_trunk_mtu = mtuv; 
3058         return CLI_SUCCESS;
3059 }
3060
3061 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3062 {
3063         struct iax2_dpcache *dp = NULL;
3064         char tmp[1024], *pc = NULL;
3065         int s, x, y;
3066         struct timeval now = ast_tvnow();
3067
3068         switch (cmd) {
3069         case CLI_INIT:
3070                 e->command = "iax2 show cache";
3071                 e->usage =
3072                         "Usage: iax2 show cache\n"
3073                         "       Display currently cached IAX Dialplan results.\n";
3074                 return NULL;
3075         case CLI_GENERATE:
3076                 return NULL;
3077         }
3078
3079         AST_LIST_LOCK(&dpcache);
3080
3081         ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
3082
3083         AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
3084                 s = dp->expiry.tv_sec - now.tv_sec;
3085                 tmp[0] = '\0';
3086                 if (dp->flags & CACHE_FLAG_EXISTS)
3087                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
3088                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
3089                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
3090                 if (dp->flags & CACHE_FLAG_CANEXIST)
3091                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
3092                 if (dp->flags & CACHE_FLAG_PENDING)
3093                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
3094                 if (dp->flags & CACHE_FLAG_TIMEOUT)
3095                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
3096                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
3097                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
3098                 if (dp->flags & CACHE_FLAG_MATCHMORE)
3099                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
3100                 if (dp->flags & CACHE_FLAG_UNKNOWN)
3101                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
3102                 /* Trim trailing pipe */
3103                 if (!ast_strlen_zero(tmp)) {
3104                         tmp[strlen(tmp) - 1] = '\0';
3105                 } else {
3106                         ast_copy_string(tmp, "(none)", sizeof(tmp));
3107                 }
3108                 y = 0;
3109                 pc = strchr(dp->peercontext, '@');
3110                 if (!pc) {
3111                         pc = dp->peercontext;
3112                 } else {
3113                         pc++;
3114                 }
3115                 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
3116                         if (dp->waiters[x] > -1)
3117                                 y++;
3118                 }
3119                 if (s > 0) {
3120                         ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
3121                 } else {
3122                         ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
3123                 }
3124         }
3125
3126         AST_LIST_LOCK(&dpcache);
3127
3128         return CLI_SUCCESS;
3129 }
3130
3131 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
3132
3133 static void unwrap_timestamp(struct iax_frame *fr)
3134 {
3135         /* Video mini frames only encode the lower 15 bits of the session
3136          * timestamp, but other frame types (e.g. audio) encode 16 bits. */
3137         const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
3138         const int lower_mask = (1 << ts_shift) - 1;
3139         const int upper_mask = ~lower_mask;
3140         const int last_upper = iaxs[fr->callno]->last & upper_mask;
3141
3142         if ( (fr->ts & upper_mask) == last_upper ) {
3143                 const int x = fr->ts - iaxs[fr->callno]->last;
3144                 const int threshold = (ts_shift == 15) ? 25000 : 50000;
3145
3146                 if (x < -threshold) {
3147                         /* Sudden big jump backwards in timestamp:
3148                            What likely happened here is that miniframe timestamp has circled but we haven't
3149                            gotten the update from the main packet.  We'll just pretend that we did, and
3150                            update the timestamp appropriately. */
3151                         fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
3152                &