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