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