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