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