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