more strncpy -> ast_copy_string conversions, fixing some buglets along the way
[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 static int ast_cli_netstats(int fd, int limit_fmt);
607
608 static void iax_debug_output(const char *data)
609 {
610         if (iaxdebug)
611                 ast_verbose("%s", data);
612 }
613
614 static void iax_error_output(const char *data)
615 {
616         ast_log(LOG_WARNING, "%s", data);
617 }
618
619 #ifdef NEWJB
620 static void jb_error_output(const char *fmt, ...)
621 {
622         va_list args;
623         char buf[1024];
624
625         va_start(args, fmt);
626         vsnprintf(buf, 1024, fmt, args);
627         va_end(args);
628
629         ast_log(LOG_ERROR, buf);
630 }
631
632 static void jb_warning_output(const char *fmt, ...)
633 {
634         va_list args;
635         char buf[1024];
636
637         va_start(args, fmt);
638         vsnprintf(buf, 1024, fmt, args);
639         va_end(args);
640
641         ast_log(LOG_WARNING, buf);
642 }
643
644 static void jb_debug_output(const char *fmt, ...)
645 {
646         va_list args;
647         char buf[1024];
648         if(!iaxdebug) return;
649
650         va_start(args, fmt);
651         vsnprintf(buf, 1024, fmt, args);
652         va_end(args);
653
654         ast_verbose(buf);
655 }
656 #endif
657
658
659 /* XXX We probably should use a mutex when working with this XXX */
660 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
661 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
662 static struct timeval lastused[IAX_MAX_CALLS];
663
664
665 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
666 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
667 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
668 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
669 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
670 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
671 static void destroy_user(struct iax2_user *user);
672 static int expire_registry(void *data);
673 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
674 static int iax2_do_register(struct iax2_registry *reg);
675 static void prune_peers(void);
676 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
677 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
678
679 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
680 static int iax2_devicestate(void *data);
681 static int iax2_digit(struct ast_channel *c, char digit);
682 static int iax2_sendtext(struct ast_channel *c, const char *text);
683 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
684 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
685 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
686 static int iax2_hangup(struct ast_channel *c);
687 static int iax2_answer(struct ast_channel *c);
688 static struct ast_frame *iax2_read(struct ast_channel *c);
689 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
690 static int iax2_indicate(struct ast_channel *c, int condition);
691 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
692 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
693 static int iax2_transfer(struct ast_channel *c, const char *dest);
694 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
695
696 static const struct ast_channel_tech iax2_tech = {
697         .type = channeltype,
698         .description = tdesc,
699         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
700         .properties = AST_CHAN_TP_WANTSJITTER,
701         .requester = iax2_request,
702         .devicestate = iax2_devicestate,
703         .send_digit = iax2_digit,
704         .send_text = iax2_sendtext,
705         .send_image = iax2_sendimage,
706         .send_html = iax2_sendhtml,
707         .call = iax2_call,
708         .hangup = iax2_hangup,
709         .answer = iax2_answer,
710         .read = iax2_read,
711         .write = iax2_write,
712         .write_video = iax2_write,
713         .indicate = iax2_indicate,
714         .setoption = iax2_setoption,
715         .bridge = iax2_bridge,
716         .transfer = iax2_transfer,
717         .fixup = iax2_fixup,
718 };
719
720 static int send_ping(void *data)
721 {
722         int callno = (long)data;
723         /* Ping only if it's real, not if it's bridged */
724         if (iaxs[callno]) {
725 #ifdef BRIDGE_OPTIMIZATION
726                 if (!iaxs[callno]->bridgecallno)
727 #endif
728                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
729                 return 1;
730         } else
731                 return 0;
732 }
733
734 static int get_encrypt_methods(const char *s)
735 {
736         int e;
737         if (!strcasecmp(s, "aes128"))
738                 e = IAX_ENCRYPT_AES128;
739         else if (ast_true(s))
740                 e = IAX_ENCRYPT_AES128;
741         else
742                 e = 0;
743         return e;
744 }
745
746 static int send_lagrq(void *data)
747 {
748         int callno = (long)data;
749         /* Ping only if it's real not if it's bridged */
750         if (iaxs[callno]) {
751 #ifdef BRIDGE_OPTIMIZATION
752                 if (!iaxs[callno]->bridgecallno)
753 #endif          
754                         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
755                 return 1;
756         } else
757                 return 0;
758 }
759
760 static unsigned char compress_subclass(int subclass)
761 {
762         int x;
763         int power=-1;
764         /* If it's 128 or smaller, just return it */
765         if (subclass < IAX_FLAG_SC_LOG)
766                 return subclass;
767         /* Otherwise find its power */
768         for (x = 0; x < IAX_MAX_SHIFT; x++) {
769                 if (subclass & (1 << x)) {
770                         if (power > -1) {
771                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
772                                 return 0;
773                         } else
774                                 power = x;
775                 }
776         }
777         return power | IAX_FLAG_SC_LOG;
778 }
779
780 static int uncompress_subclass(unsigned char csub)
781 {
782         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
783         if (csub & IAX_FLAG_SC_LOG) {
784                 /* special case for 'compressed' -1 */
785                 if (csub == 0xff)
786                         return -1;
787                 else
788                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
789         }
790         else
791                 return csub;
792 }
793
794 static struct iax2_peer *find_peer(const char *name, int realtime) 
795 {
796         struct iax2_peer *peer;
797         ast_mutex_lock(&peerl.lock);
798         for(peer = peerl.peers; peer; peer = peer->next) {
799                 if (!strcasecmp(peer->name, name)) {
800                         break;
801                 }
802         }
803         ast_mutex_unlock(&peerl.lock);
804         if(!peer && realtime)
805                 peer = realtime_peer(name);
806         return peer;
807 }
808
809 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
810 {
811         struct iax2_peer *peer;
812         int res = 0;
813         if (lockpeer)
814                 ast_mutex_lock(&peerl.lock);
815         peer = peerl.peers;
816         while(peer) {
817                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
818                                 (peer->addr.sin_port == sin.sin_port)) {
819                                         ast_copy_string(host, peer->name, len);
820                                         res = 1;
821                                         break;
822                 }
823                 peer = peer->next;
824         }
825         if (lockpeer)
826                 ast_mutex_unlock(&peerl.lock);
827         return res;
828 }
829
830 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
831 {
832         struct chan_iax2_pvt *tmp;
833         tmp = malloc(sizeof(struct chan_iax2_pvt));
834         if (tmp) {
835                 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
836                 tmp->prefs = prefs;
837                 tmp->callno = 0;
838                 tmp->peercallno = 0;
839                 tmp->transfercallno = 0;
840                 tmp->bridgecallno = 0;
841                 tmp->pingid = -1;
842                 tmp->lagid = -1;
843                 tmp->autoid = -1;
844                 tmp->authid = -1;
845                 tmp->initid = -1;
846                 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
847                 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
848                 ast_copy_string(tmp->host, host, sizeof(tmp->host));
849 #ifdef NEWJB
850                 {
851                         jb_info jbinfo;
852
853                         tmp->jb = jb_new();
854                         tmp->jbid = -1;
855                         jbinfo.max_jitterbuf = maxjitterbuffer;
856                         jb_setinfo(tmp->jb,&jbinfo);
857                 }
858 #endif
859         }
860         return tmp;
861 }
862
863 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
864 {
865         /* Malloc() a copy of a frame */
866         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
867         if (new) {
868                 memcpy(new, fr, sizeof(struct iax_frame));      
869                 iax_frame_wrap(new, &fr->af);
870                 new->data = NULL;
871                 new->datalen = 0;
872                 new->direction = DIRECTION_INGRESS;
873                 new->retrans = -1;
874         }
875         return new;
876 }
877
878 #define NEW_PREVENT 0
879 #define NEW_ALLOW       1
880 #define NEW_FORCE       2
881
882 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
883 {
884         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
885                 (cur->addr.sin_port == sin->sin_port)) {
886                 /* This is the main host */
887                 if ((cur->peercallno == callno) ||
888                         ((dcallno == cur->callno) && !cur->peercallno)) {
889                         /* That's us.  Be sure we keep track of the peer call number */
890                         return 1;
891                 }
892         }
893         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
894             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
895                 /* We're transferring */
896                 if (dcallno == cur->callno)
897                         return 1;
898         }
899         return 0;
900 }
901
902 static void update_max_trunk(void)
903 {
904         int max = TRUNK_CALL_START;
905         int x;
906         /* XXX Prolly don't need locks here XXX */
907         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
908                 if (iaxs[x])
909                         max = x + 1;
910         }
911         maxtrunkcall = max;
912         if (option_debug)
913                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
914 }
915
916 static void update_max_nontrunk(void)
917 {
918         int max = 1;
919         int x;
920         /* XXX Prolly don't need locks here XXX */
921         for (x=1;x<TRUNK_CALL_START - 1; x++) {
922                 if (iaxs[x])
923                         max = x + 1;
924         }
925         maxnontrunkcall = max;
926         if (option_debug)
927                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
928 }
929
930 static int make_trunk(unsigned short callno, int locked)
931 {
932         int x;
933         int res= 0;
934         struct timeval now;
935         if (iaxs[callno]->oseqno) {
936                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
937                 return -1;
938         }
939         if (callno & TRUNK_CALL_START) {
940                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
941                 return -1;
942         }
943         gettimeofday(&now, NULL);
944         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
945                 ast_mutex_lock(&iaxsl[x]);
946                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
947                         iaxs[x] = iaxs[callno];
948                         iaxs[x]->callno = x;
949                         iaxs[callno] = NULL;
950                         /* Update the two timers that should have been started */
951                         if (iaxs[x]->pingid > -1)
952                                 ast_sched_del(sched, iaxs[x]->pingid);
953                         if (iaxs[x]->lagid > -1)
954                                 ast_sched_del(sched, iaxs[x]->lagid);
955                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
956                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
957                         if (locked)
958                                 ast_mutex_unlock(&iaxsl[callno]);
959                         res = x;
960                         if (!locked)
961                                 ast_mutex_unlock(&iaxsl[x]);
962                         break;
963                 }
964                 ast_mutex_unlock(&iaxsl[x]);
965         }
966         if (x >= IAX_MAX_CALLS - 1) {
967                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
968                 return -1;
969         }
970         ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
971         /* We move this call from a non-trunked to a trunked call */
972         update_max_trunk();
973         update_max_nontrunk();
974         return res;
975 }
976
977 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
978 {
979         int res = 0;
980         int x;
981         struct timeval now;
982         char iabuf[INET_ADDRSTRLEN];
983         char host[80];
984         if (new <= NEW_ALLOW) {
985                 /* Look for an existing connection first */
986                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
987                         ast_mutex_lock(&iaxsl[x]);
988                         if (iaxs[x]) {
989                                 /* Look for an exact match */
990                                 if (match(sin, callno, dcallno, iaxs[x])) {
991                                         res = x;
992                                 }
993                         }
994                         ast_mutex_unlock(&iaxsl[x]);
995                 }
996                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
997                         ast_mutex_lock(&iaxsl[x]);
998                         if (iaxs[x]) {
999                                 /* Look for an exact match */
1000                                 if (match(sin, callno, dcallno, iaxs[x])) {
1001                                         res = x;
1002                                 }
1003                         }
1004                         ast_mutex_unlock(&iaxsl[x]);
1005                 }
1006         }
1007         if ((res < 1) && (new >= NEW_ALLOW)) {
1008                 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1009                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1010                 gettimeofday(&now, NULL);
1011                 for (x=1;x<TRUNK_CALL_START;x++) {
1012                         /* Find first unused call number that hasn't been used in a while */
1013                         ast_mutex_lock(&iaxsl[x]);
1014                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1015                         ast_mutex_unlock(&iaxsl[x]);
1016                 }
1017                 /* We've still got lock held if we found a spot */
1018                 if (x >= TRUNK_CALL_START) {
1019                         ast_log(LOG_WARNING, "No more space\n");
1020                         return 0;
1021                 }
1022                 iaxs[x] = new_iax(sin, lockpeer, host);
1023                 update_max_nontrunk();
1024                 if (iaxs[x]) {
1025                         if (option_debug)
1026                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1027                         iaxs[x]->sockfd = sockfd;
1028                         iaxs[x]->addr.sin_port = sin->sin_port;
1029                         iaxs[x]->addr.sin_family = sin->sin_family;
1030                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1031                         iaxs[x]->peercallno = callno;
1032                         iaxs[x]->callno = x;
1033                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1034                         iaxs[x]->expirey = expirey;
1035                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1036                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1037                         iaxs[x]->amaflags = amaflags;
1038                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);        
1039                         ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1040                 } else {
1041                         ast_log(LOG_WARNING, "Out of resources\n");
1042                         ast_mutex_unlock(&iaxsl[x]);
1043                         return 0;
1044                 }
1045                 ast_mutex_unlock(&iaxsl[x]);
1046                 res = x;
1047         }
1048         return res;
1049 }
1050
1051 static void iax2_frame_free(struct iax_frame *fr)
1052 {
1053         if (fr->retrans > -1)
1054                 ast_sched_del(sched, fr->retrans);
1055         iax_frame_free(fr);
1056 }
1057
1058 static int iax2_queue_frame(int callno, struct ast_frame *f)
1059 {
1060         /* Assumes lock for callno is already held... */
1061         for (;;) {
1062                 if (iaxs[callno] && iaxs[callno]->owner) {
1063                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1064                                 /* Avoid deadlock by pausing and trying again */
1065                                 ast_mutex_unlock(&iaxsl[callno]);
1066                                 usleep(1);
1067                                 ast_mutex_lock(&iaxsl[callno]);
1068                         } else {
1069                                 ast_queue_frame(iaxs[callno]->owner, f);
1070                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1071                                 break;
1072                         }
1073                 } else
1074                         break;
1075         }
1076         return 0;
1077 }
1078
1079 static void destroy_firmware(struct iax_firmware *cur)
1080 {
1081         /* Close firmware */
1082         if (cur->fwh) {
1083                 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1084         }
1085         close(cur->fd);
1086         free(cur);
1087 }
1088
1089 static int try_firmware(char *s)
1090 {
1091         struct stat stbuf;
1092         struct iax_firmware *cur;
1093         int ifd;
1094         int fd;
1095         int res;
1096         
1097         struct ast_iax2_firmware_header *fwh, fwh2;
1098         struct MD5Context md5;
1099         unsigned char sum[16];
1100         unsigned char buf[1024];
1101         int len, chunk;
1102         char *s2;
1103         char *last;
1104         s2 = alloca(strlen(s) + 100);
1105         if (!s2) {
1106                 ast_log(LOG_WARNING, "Alloca failed!\n");
1107                 return -1;
1108         }
1109         last = strrchr(s, '/');
1110         if (last)
1111                 last++;
1112         else
1113                 last = s;
1114         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1115         res = stat(s, &stbuf);
1116         if (res < 0) {
1117                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1118                 return -1;
1119         }
1120         /* Make sure it's not a directory */
1121         if (S_ISDIR(stbuf.st_mode))
1122                 return -1;
1123         ifd = open(s, O_RDONLY);
1124         if (ifd < 0) {
1125                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1126                 return -1;
1127         }
1128         fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1129         if (fd < 0) {
1130                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1131                 close(ifd);
1132                 return -1;
1133         }
1134         /* Unlink our newly created file */
1135         unlink(s2);
1136         
1137         /* Now copy the firmware into it */
1138         len = stbuf.st_size;
1139         while(len) {
1140                 chunk = len;
1141                 if (chunk > sizeof(buf))
1142                         chunk = sizeof(buf);
1143                 res = read(ifd, buf, chunk);
1144                 if (res != chunk) {
1145                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1146                         close(ifd);
1147                         close(fd);
1148                         return -1;
1149                 }
1150                 res = write(fd, buf, chunk);
1151                 if (res != chunk) {
1152                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1153                         close(ifd);
1154                         close(fd);
1155                         return -1;
1156                 }
1157                 len -= chunk;
1158         }
1159         close(ifd);
1160         /* Return to the beginning */
1161         lseek(fd, 0, SEEK_SET);
1162         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1163                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1164                 close(fd);
1165                 return -1;
1166         }
1167         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1168                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1169                 close(fd);
1170                 return -1;
1171         }
1172         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1173                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1174                 close(fd);
1175                 return -1;
1176         }
1177         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1178                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1179                 close(fd);
1180                 return -1;
1181         }
1182         fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1183         if (!fwh) {
1184                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1185                 close(fd);
1186                 return -1;
1187         }
1188         MD5Init(&md5);
1189         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1190         MD5Final(sum, &md5);
1191         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1192                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1193                 munmap(fwh, stbuf.st_size);
1194                 close(fd);
1195                 return -1;
1196         }
1197         cur = waresl.wares;
1198         while(cur) {
1199                 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1200                         /* Found a candidate */
1201                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1202                                 /* The version we have on loaded is older, load this one instead */
1203                                 break;
1204                         /* This version is no newer than what we have.  Don't worry about it.
1205                            We'll consider it a proper load anyhow though */
1206                         munmap(fwh, stbuf.st_size);
1207                         close(fd);
1208                         return 0;
1209                 }
1210                 cur = cur->next;
1211         }
1212         if (!cur) {
1213                 /* Allocate a new one and link it */
1214                 cur = malloc(sizeof(struct iax_firmware));
1215                 if (cur) {
1216                         memset(cur, 0, sizeof(struct iax_firmware));
1217                         cur->fd = -1;
1218                         cur->next = waresl.wares;
1219                         waresl.wares = cur;
1220                 }
1221         }
1222         if (cur) {
1223                 if (cur->fwh) {
1224                         munmap(cur->fwh, cur->mmaplen);
1225                 }
1226                 if (cur->fd > -1)
1227                         close(cur->fd);
1228                 cur->fwh = fwh;
1229                 cur->fd = fd;
1230                 cur->mmaplen = stbuf.st_size;
1231                 cur->dead = 0;
1232         }
1233         return 0;
1234 }
1235
1236 static int iax_check_version(char *dev)
1237 {
1238         int res = 0;
1239         struct iax_firmware *cur;
1240         if (dev && !ast_strlen_zero(dev)) {
1241                 ast_mutex_lock(&waresl.lock);
1242                 cur = waresl.wares;
1243                 while(cur) {
1244                         if (!strcmp(dev, cur->fwh->devname)) {
1245                                 res = ntohs(cur->fwh->version);
1246                                 break;
1247                         }
1248                         cur = cur->next;
1249                 }
1250                 ast_mutex_unlock(&waresl.lock);
1251         }
1252         return res;
1253 }
1254
1255 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1256 {
1257         int res = -1;
1258         unsigned int bs = desc & 0xff;
1259         unsigned int start = (desc >> 8) & 0xffffff;
1260         unsigned int bytes;
1261         struct iax_firmware *cur;
1262         if (dev && !ast_strlen_zero(dev) && bs) {
1263                 start *= bs;
1264                 ast_mutex_lock(&waresl.lock);
1265                 cur = waresl.wares;
1266                 while(cur) {
1267                         if (!strcmp(dev, cur->fwh->devname)) {
1268                                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1269                                 if (start < ntohl(cur->fwh->datalen)) {
1270                                         bytes = ntohl(cur->fwh->datalen) - start;
1271                                         if (bytes > bs)
1272                                                 bytes = bs;
1273                                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1274                                 } else {
1275                                         bytes = 0;
1276                                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1277                                 }
1278                                 if (bytes == bs)
1279                                         res = 0;
1280                                 else
1281                                         res = 1;
1282                                 break;
1283                         }
1284                         cur = cur->next;
1285                 }
1286                 ast_mutex_unlock(&waresl.lock);
1287         }
1288         return res;
1289 }
1290
1291
1292 static void reload_firmware(void)
1293 {
1294         struct iax_firmware *cur, *curl, *curp;
1295         DIR *fwd;
1296         struct dirent *de;
1297         char dir[256];
1298         char fn[256];
1299         /* Mark all as dead */
1300         ast_mutex_lock(&waresl.lock);
1301         cur = waresl.wares;
1302         while(cur) {
1303                 cur->dead = 1;
1304                 cur = cur->next;
1305         }
1306         /* Now that we've freed them, load the new ones */
1307         snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1308         fwd = opendir(dir);
1309         if (fwd) {
1310                 while((de = readdir(fwd))) {
1311                         if (de->d_name[0] != '.') {
1312                                 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1313                                 if (!try_firmware(fn)) {
1314                                         if (option_verbose > 1)
1315                                                 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1316                                 }
1317                         }
1318                 }
1319                 closedir(fwd);
1320         } else 
1321                 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1322
1323         /* Clean up leftovers */
1324         cur = waresl.wares;
1325         curp = NULL;
1326         while(cur) {
1327                 curl = cur;
1328                 cur = cur->next;
1329                 if (curl->dead) {
1330                         if (curp) {
1331                                 curp->next = cur;
1332                         } else {
1333                                 waresl.wares = cur;
1334                         }
1335                         destroy_firmware(curl);
1336                 } else {
1337                         curp = cur;
1338                 }
1339         }
1340         ast_mutex_unlock(&waresl.lock);
1341 }
1342
1343 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1344
1345 static int __do_deliver(void *data)
1346 {
1347         /* Just deliver the packet by using queueing.  This is called by
1348           the IAX thread with the iaxsl lock held. */
1349         struct iax_frame *fr = data;
1350         fr->retrans = -1;
1351         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1352                 iax2_queue_frame(fr->callno, &fr->af);
1353         /* Free our iax frame */
1354         iax2_frame_free(fr);
1355         /* And don't run again */
1356         return 0;
1357 }
1358
1359 #ifndef NEWJB
1360 static int do_deliver(void *data)
1361 {
1362         /* Locking version of __do_deliver */
1363         struct iax_frame *fr = data;
1364         int callno = fr->callno;
1365         int res;
1366         ast_mutex_lock(&iaxsl[callno]);
1367         res = __do_deliver(data);
1368         ast_mutex_unlock(&iaxsl[callno]);
1369         return res;
1370 }
1371 #endif /* NEWJB */
1372
1373 static int handle_error(void)
1374 {
1375         /* XXX Ideally we should figure out why an error occured and then abort those
1376            rather than continuing to try.  Unfortunately, the published interface does
1377            not seem to work XXX */
1378 #if 0
1379         struct sockaddr_in *sin;
1380         int res;
1381         struct msghdr m;
1382         struct sock_extended_err e;
1383         m.msg_name = NULL;
1384         m.msg_namelen = 0;
1385         m.msg_iov = NULL;
1386         m.msg_control = &e;
1387         m.msg_controllen = sizeof(e);
1388         m.msg_flags = 0;
1389         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1390         if (res < 0)
1391                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1392         else {
1393                 if (m.msg_controllen) {
1394                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1395                         if (sin) 
1396                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1397                         else
1398                                 ast_log(LOG_WARNING, "No address detected??\n");
1399                 } else {
1400                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1401                 }
1402         }
1403 #endif
1404         return 0;
1405 }
1406
1407 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1408 {
1409         int res;
1410         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1411                                         sizeof(*sin));
1412         if (res < 0) {
1413                 if (option_debug)
1414                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1415                 handle_error();
1416         } else
1417                 res = 0;
1418         return res;
1419 }
1420
1421 static int send_packet(struct iax_frame *f)
1422 {
1423         int res;
1424         char iabuf[INET_ADDRSTRLEN];
1425         /* Called with iaxsl held */
1426         if (option_debug > 2)
1427                 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));
1428         /* Don't send if there was an error, but return error instead */
1429         if (!f->callno) {
1430                 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1431                 return -1;
1432         }
1433         if (!iaxs[f->callno])
1434                 return -1;
1435         if (iaxs[f->callno]->error)
1436                 return -1;
1437         if (f->transfer) {
1438                 if (iaxdebug)
1439                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1440                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1441                                         sizeof(iaxs[f->callno]->transfer));
1442         } else {
1443                 if (iaxdebug)
1444                         iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1445                 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1446                                         sizeof(iaxs[f->callno]->addr));
1447         }
1448         if (res < 0) {
1449                 if (option_debug)
1450                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1451                 handle_error();
1452         } else
1453                 res = 0;
1454         return res;
1455 }
1456
1457
1458 static int iax2_predestroy(int callno)
1459 {
1460         struct ast_channel *c;
1461         struct chan_iax2_pvt *pvt;
1462         ast_mutex_lock(&iaxsl[callno]);
1463         pvt = iaxs[callno];
1464         if (!pvt) {
1465                 ast_mutex_unlock(&iaxsl[callno]);
1466                 return -1;
1467         }
1468         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1469                 /* No more pings or lagrq's */
1470                 if (pvt->pingid > -1)
1471                         ast_sched_del(sched, pvt->pingid);
1472                 if (pvt->lagid > -1)
1473                         ast_sched_del(sched, pvt->lagid);
1474                 if (pvt->autoid > -1)
1475                         ast_sched_del(sched, pvt->autoid);
1476                 if (pvt->authid > -1)
1477                         ast_sched_del(sched, pvt->authid);
1478                 if (pvt->initid > -1)
1479                         ast_sched_del(sched, pvt->initid);
1480 #ifdef NEWJB
1481                 if (pvt->jbid > -1)
1482                         ast_sched_del(sched, pvt->jbid);
1483                 pvt->jbid = -1;
1484 #endif
1485                 pvt->pingid = -1;
1486                 pvt->lagid = -1;
1487                 pvt->autoid = -1;
1488                 pvt->initid = -1;
1489                 pvt->authid = -1;
1490                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1491         }
1492         c = pvt->owner;
1493         if (c) {
1494                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1495                 c->tech_pvt = NULL;
1496                 ast_queue_hangup(c);
1497                 pvt->owner = NULL;
1498                 ast_mutex_lock(&usecnt_lock);
1499                 usecnt--;
1500                 if (usecnt < 0) 
1501                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1502                 ast_mutex_unlock(&usecnt_lock);
1503         }
1504         ast_mutex_unlock(&iaxsl[callno]);
1505         ast_update_use_count();
1506         return 0;
1507 }
1508
1509 static int iax2_predestroy_nolock(int callno)
1510 {
1511         int res;
1512         ast_mutex_unlock(&iaxsl[callno]);
1513         res = iax2_predestroy(callno);
1514         ast_mutex_lock(&iaxsl[callno]);
1515         return res;
1516 }
1517
1518 static void iax2_destroy(int callno)
1519 {
1520         struct chan_iax2_pvt *pvt;
1521         struct iax_frame *cur;
1522         struct ast_channel *owner;
1523
1524 retry:
1525         ast_mutex_lock(&iaxsl[callno]);
1526         pvt = iaxs[callno];
1527         gettimeofday(&lastused[callno], NULL);
1528
1529         if (pvt)
1530                 owner = pvt->owner;
1531         else
1532                 owner = NULL;
1533         if (owner) {
1534                 if (ast_mutex_trylock(&owner->lock)) {
1535                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1536                         ast_mutex_unlock(&iaxsl[callno]);
1537                         usleep(1);
1538                         goto retry;
1539                 }
1540         }
1541         if (!owner)
1542                 iaxs[callno] = NULL;
1543         if (pvt) {
1544                 if (!owner)
1545                         pvt->owner = NULL;
1546                 /* No more pings or lagrq's */
1547                 if (pvt->pingid > -1)
1548                         ast_sched_del(sched, pvt->pingid);
1549                 if (pvt->lagid > -1)
1550                         ast_sched_del(sched, pvt->lagid);
1551                 if (pvt->autoid > -1)
1552                         ast_sched_del(sched, pvt->autoid);
1553                 if (pvt->authid > -1)
1554                         ast_sched_del(sched, pvt->authid);
1555                 if (pvt->initid > -1)
1556                         ast_sched_del(sched, pvt->initid);
1557 #ifdef NEWJB
1558                 if (pvt->jbid > -1)
1559                         ast_sched_del(sched, pvt->jbid);
1560                 pvt->jbid = -1;
1561 #endif
1562                 pvt->pingid = -1;
1563                 pvt->lagid = -1;
1564                 pvt->autoid = -1;
1565                 pvt->authid = -1;
1566                 pvt->initid = -1;
1567                 if (pvt->bridgetrans)
1568                         ast_translator_free_path(pvt->bridgetrans);
1569                 pvt->bridgetrans = NULL;
1570
1571                 /* Already gone */
1572                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1573
1574                 if (owner) {
1575                         /* If there's an owner, prod it to give up */
1576                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1577                         ast_queue_hangup(owner);
1578                 }
1579
1580                 for (cur = iaxq.head; cur ; cur = cur->next) {
1581                         /* Cancel any pending transmissions */
1582                         if (cur->callno == pvt->callno) 
1583                                 cur->retries = -1;
1584                 }
1585                 if (pvt->reg) {
1586                         pvt->reg->callno = 0;
1587                 }
1588                 if (!owner) {
1589                         if (pvt->vars) {
1590                                 ast_variables_destroy(pvt->vars);
1591                                 pvt->vars = NULL;
1592                         }
1593 #ifdef NEWJB
1594                         {
1595                             jb_frame frame;
1596                             while(jb_getall(pvt->jb,&frame) == JB_OK)
1597                                 iax2_frame_free(frame.data);
1598                             jb_destroy(pvt->jb);
1599                         }
1600 #endif
1601                         free(pvt);
1602                 }
1603         }
1604         if (owner) {
1605                 ast_mutex_unlock(&owner->lock);
1606         }
1607         ast_mutex_unlock(&iaxsl[callno]);
1608         if (callno & 0x4000)
1609                 update_max_trunk();
1610 }
1611 static void iax2_destroy_nolock(int callno)
1612 {       
1613         /* Actually it's easier to unlock, kill it, and relock */
1614         ast_mutex_unlock(&iaxsl[callno]);
1615         iax2_destroy(callno);
1616         ast_mutex_lock(&iaxsl[callno]);
1617 }
1618
1619 static int update_packet(struct iax_frame *f)
1620 {
1621         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1622         struct ast_iax2_full_hdr *fh = f->data;
1623         /* Mark this as a retransmission */
1624         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1625         /* Update iseqno */
1626         f->iseqno = iaxs[f->callno]->iseqno;
1627         fh->iseqno = f->iseqno;
1628         return 0;
1629 }
1630
1631 static int attempt_transmit(void *data)
1632 {
1633         /* Attempt to transmit the frame to the remote peer...
1634            Called without iaxsl held. */
1635         struct iax_frame *f = data;
1636         int freeme=0;
1637         int callno = f->callno;
1638         char iabuf[INET_ADDRSTRLEN];
1639         /* Make sure this call is still active */
1640         if (callno) 
1641                 ast_mutex_lock(&iaxsl[callno]);
1642         if ((f->callno) && iaxs[f->callno]) {
1643                 if ((f->retries < 0) /* Already ACK'd */ ||
1644                     (f->retries >= max_retries) /* Too many attempts */) {
1645                                 /* Record an error if we've transmitted too many times */
1646                                 if (f->retries >= max_retries) {
1647                                         if (f->transfer) {
1648                                                 /* Transfer timeout */
1649                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1650                                         } else if (f->final) {
1651                                                 if (f->final) 
1652                                                         iax2_destroy_nolock(f->callno);
1653                                         } else {
1654                                                 if (iaxs[f->callno]->owner)
1655                                                         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);
1656                                                 iaxs[f->callno]->error = ETIMEDOUT;
1657                                                 if (iaxs[f->callno]->owner) {
1658                                                         struct ast_frame fr = { 0, };
1659                                                         /* Hangup the fd */
1660                                                         fr.frametype = AST_FRAME_CONTROL;
1661                                                         fr.subclass = AST_CONTROL_HANGUP;
1662                                                         iax2_queue_frame(f->callno, &fr);
1663                                                         /* Remember, owner could disappear */
1664                                                         if (iaxs[f->callno]->owner)
1665                                                                 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1666                                                 } else {
1667                                                         if (iaxs[f->callno]->reg) {
1668                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1669                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1670                                                                 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1671                                                         }
1672                                                         iax2_destroy_nolock(f->callno);
1673                                                 }
1674                                         }
1675
1676                                 }
1677                                 freeme++;
1678                 } else {
1679                         /* Update it if it needs it */
1680                         update_packet(f);
1681                         /* Attempt transmission */
1682                         send_packet(f);
1683                         f->retries++;
1684                         /* Try again later after 10 times as long */
1685                         f->retrytime *= 10;
1686                         if (f->retrytime > MAX_RETRY_TIME)
1687                                 f->retrytime = MAX_RETRY_TIME;
1688                         /* Transfer messages max out at one second */
1689                         if (f->transfer && (f->retrytime > 1000))
1690                                 f->retrytime = 1000;
1691                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1692                 }
1693         } else {
1694                 /* Make sure it gets freed */
1695                 f->retries = -1;
1696                 freeme++;
1697         }
1698         if (callno)
1699                 ast_mutex_unlock(&iaxsl[callno]);
1700         /* Do not try again */
1701         if (freeme) {
1702                 /* Don't attempt delivery, just remove it from the queue */
1703                 ast_mutex_lock(&iaxq.lock);
1704                 if (f->prev) 
1705                         f->prev->next = f->next;
1706                 else
1707                         iaxq.head = f->next;
1708                 if (f->next)
1709                         f->next->prev = f->prev;
1710                 else
1711                         iaxq.tail = f->prev;
1712                 iaxq.count--;
1713                 ast_mutex_unlock(&iaxq.lock);
1714                 f->retrans = -1;
1715                 /* Free the IAX frame */
1716                 iax2_frame_free(f);
1717         }
1718         return 0;
1719 }
1720
1721 static int iax2_set_jitter(int fd, int argc, char *argv[])
1722 {
1723 #ifdef NEWJB
1724         ast_cli(fd, "sorry, this command is deprecated\n");
1725         return RESULT_SUCCESS;
1726 #else
1727         if ((argc != 4) && (argc != 5))
1728                 return RESULT_SHOWUSAGE;
1729         if (argc == 4) {
1730                 max_jitter_buffer = atoi(argv[3]);
1731                 if (max_jitter_buffer < 0)
1732                         max_jitter_buffer = 0;
1733         } else {
1734                 if (argc == 5) {
1735                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1736                                 if (iaxs[atoi(argv[3])]) {
1737                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1738                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1739                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1740                                 } else
1741                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1742                         } else
1743                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1744                 }
1745         }
1746         return RESULT_SUCCESS;
1747 #endif
1748 }
1749
1750 static char jitter_usage[] = 
1751 "Usage: iax set jitter [callid] <value>\n"
1752 "       If used with a callid, it sets the jitter buffer to the given static\n"
1753 "value (until its next calculation).  If used without a callid, the value is used\n"
1754 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1755 "buffer size is reduced.";
1756
1757 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1758 {
1759         struct iax2_peer *peer;
1760
1761         if (argc != 4)
1762         return RESULT_SHOWUSAGE;
1763         if (!strcmp(argv[3],"all")) {
1764                 reload_config();
1765                 ast_cli(fd, "OK cache is flushed.\n");
1766         } else if ((peer = find_peer(argv[3], 0))) {
1767                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1768                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1769                         expire_registry(peer);
1770                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1771                 } else {
1772                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1773                 }
1774         } else {
1775                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1776         }
1777         
1778         return RESULT_SUCCESS;
1779 }
1780
1781 static int iax2_test_losspct(int fd, int argc, char *argv[])
1782 {
1783        if (argc != 4)
1784                return RESULT_SHOWUSAGE;
1785
1786        test_losspct = atoi(argv[3]);
1787
1788        return RESULT_SUCCESS;
1789 }
1790
1791 /*--- iax2_show_peer: Show one peer in detail ---*/
1792 static int iax2_show_peer(int fd, int argc, char *argv[])
1793 {
1794         char status[30] = "";
1795         char cbuf[256];
1796         char iabuf[INET_ADDRSTRLEN];
1797         struct iax2_peer *peer;
1798         char codec_buf[512];
1799         int x = 0, codec = 0, load_realtime = 0;
1800
1801         if (argc < 4)
1802                 return RESULT_SHOWUSAGE;
1803
1804         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1805
1806         peer = find_peer(argv[3], load_realtime);
1807         if (peer) {
1808                 ast_cli(fd,"\n\n");
1809                 ast_cli(fd, "  * Name       : %s\n", peer->name);
1810                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1811                 ast_cli(fd, "  Context      : %s\n", peer->context);
1812                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
1813                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1814                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1815                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
1816                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
1817                 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));
1818                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1819                 ast_cli(fd, "  Username     : %s\n", peer->username);
1820                 ast_cli(fd, "  Codecs       : ");
1821                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1822                 ast_cli(fd, "%s\n", codec_buf);
1823
1824                 ast_cli(fd, "  Codec Order  : (");
1825                 for(x = 0; x < 32 ; x++) {
1826                         codec = ast_codec_pref_index(&peer->prefs,x);
1827                         if(!codec)
1828                                 break;
1829                         ast_cli(fd, "%s", ast_getformatname(codec));
1830                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1831                                 ast_cli(fd, "|");
1832                 }
1833
1834                 if (!x)
1835                         ast_cli(fd, "none");
1836                 ast_cli(fd, ")\n");
1837
1838                 ast_cli(fd, "  Status       : ");
1839                 if (peer->lastms < 0)
1840                         ast_copy_string(status, "UNREACHABLE", sizeof(status));
1841                 else if (peer->lastms > peer->maxms)
1842                         snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1843                 else if (peer->lastms)
1844                         snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1845                 else
1846                         ast_copy_string(status, "UNKNOWN", sizeof(status));
1847                 ast_cli(fd, "%s\n",status);
1848                 ast_cli(fd,"\n");
1849                 if (ast_test_flag(peer, IAX_TEMPONLY))
1850                         destroy_peer(peer);
1851         } else {
1852                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1853                 ast_cli(fd,"\n");
1854         }
1855
1856         return RESULT_SUCCESS;
1857 }
1858
1859 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1860 {
1861         int which = 0;
1862         struct iax2_peer *p;
1863
1864         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1865         if(pos == 3) {
1866                 ast_mutex_lock(&peerl.lock);
1867                 for(p = peerl.peers ; p ; p = p->next) {
1868                         if(!strncasecmp(p->name, word, strlen(word))) {
1869                                 if(++which > state) {
1870                                         return strdup(p->name);
1871                                 }
1872                         }
1873                 }
1874                 ast_mutex_unlock(&peerl.lock);
1875         }
1876
1877         return NULL;
1878 }
1879
1880 static int iax2_show_stats(int fd, int argc, char *argv[])
1881 {
1882         struct iax_frame *cur;
1883         int cnt = 0, dead=0, final=0;
1884         if (argc != 3)
1885                 return RESULT_SHOWUSAGE;
1886         for (cur = iaxq.head; cur ; cur = cur->next) {
1887                 if (cur->retries < 0)
1888                         dead++;
1889                 if (cur->final)
1890                         final++;
1891                 cnt++;
1892         }
1893         ast_cli(fd, "    IAX Statistics\n");
1894         ast_cli(fd, "---------------------\n");
1895         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1896         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1897         return RESULT_SUCCESS;
1898 }
1899
1900 static int iax2_show_cache(int fd, int argc, char *argv[])
1901 {
1902         struct iax2_dpcache *dp;
1903         char tmp[1024] = "", *pc;
1904         int s;
1905         int x,y;
1906         struct timeval tv;
1907         gettimeofday(&tv, NULL);
1908         ast_mutex_lock(&dpcache_lock);
1909         dp = dpcache;
1910         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1911         while(dp) {
1912                 s = dp->expirey.tv_sec - tv.tv_sec;
1913                 tmp[0] = '\0';
1914                 if (dp->flags & CACHE_FLAG_EXISTS)
1915                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1916                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1917                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1918                 if (dp->flags & CACHE_FLAG_CANEXIST)
1919                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1920                 if (dp->flags & CACHE_FLAG_PENDING)
1921                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1922                 if (dp->flags & CACHE_FLAG_TIMEOUT)
1923                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1924                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1925                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1926                 if (dp->flags & CACHE_FLAG_MATCHMORE)
1927                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1928                 if (dp->flags & CACHE_FLAG_UNKNOWN)
1929                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1930                 /* Trim trailing pipe */
1931                 if (!ast_strlen_zero(tmp))
1932                         tmp[strlen(tmp) - 1] = '\0';
1933                 else
1934                         ast_copy_string(tmp, "(none)", sizeof(tmp));
1935                 y=0;
1936                 pc = strchr(dp->peercontext, '@');
1937                 if (!pc)
1938                         pc = dp->peercontext;
1939                 else
1940                         pc++;
1941                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1942                         if (dp->waiters[x] > -1)
1943                                 y++;
1944                 if (s > 0)
1945                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
1946                 else
1947                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
1948                 dp = dp->next;
1949         }
1950         ast_mutex_unlock(&dpcache_lock);
1951         return RESULT_SUCCESS;
1952 }
1953
1954 static char show_stats_usage[] =
1955 "Usage: iax show stats\n"
1956 "       Display statistics on IAX channel driver.\n";
1957
1958
1959 static char show_cache_usage[] =
1960 "Usage: iax show cache\n"
1961 "       Display currently cached IAX Dialplan results.\n";
1962
1963 static char show_peer_usage[] =
1964 "Usage: iax show peer <name>\n"
1965 "       Display details on specific IAX peer\n";
1966
1967 static char prune_realtime_usage[] =
1968 "Usage: iax2 prune realtime [<peername>|all]\n"
1969 "       Prunes object(s) from the cache\n";
1970
1971 static char iax2_reload_usage[] =
1972 "Usage: iax2 reload\n"
1973 "       Reloads IAX configuration from iax.conf\n";
1974
1975 static struct ast_cli_entry cli_set_jitter = 
1976 { { "iax2", "set", "jitter", NULL }, iax2_set_jitter, "Sets IAX jitter buffer", jitter_usage };
1977
1978 static struct ast_cli_entry cli_show_stats =
1979 { { "iax2", "show", "stats", NULL }, iax2_show_stats, "Display IAX statistics", show_stats_usage };
1980
1981 static struct ast_cli_entry cli_show_cache =
1982 { { "iax2", "show", "cache", NULL }, iax2_show_cache, "Display IAX cached dialplan", show_cache_usage };
1983
1984 static struct ast_cli_entry  cli_show_peer =
1985         { { "iax2", "show", "peer", NULL }, iax2_show_peer, "Show details on specific IAX peer", show_peer_usage, complete_iax2_show_peer };
1986
1987 static struct ast_cli_entry  cli_prune_realtime =
1988         { { "iax2", "prune", "realtime", NULL }, iax2_prune_realtime, "Prune a cached realtime lookup", prune_realtime_usage, complete_iax2_show_peer };
1989
1990 static struct ast_cli_entry  cli_reload =
1991         { { "iax2", "reload", NULL }, iax2_reload, "Reload IAX configuration", iax2_reload_usage };
1992
1993 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
1994
1995 #ifdef BRIDGE_OPTIMIZATION
1996 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
1997
1998 static int forward_delivery(struct iax_frame *fr)
1999 {
2000         struct chan_iax2_pvt *p1, *p2;
2001         char iabuf[INET_ADDRSTRLEN];
2002         int res, orig_ts;
2003
2004         p1 = iaxs[fr->callno];
2005         p2 = iaxs[p1->bridgecallno];
2006         if (!p1)
2007                 return -1;
2008         if (!p2)
2009                 return -1;
2010
2011         if (option_debug)
2012                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2013                                 fr->ts,
2014                                 p1->callno, p1->peercallno,
2015                                 p2->callno, p2->peercallno,
2016                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2017                                 ntohs(p2->addr.sin_port));
2018
2019         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2020            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2021            send full frame on timestamp wrap when doing optimized bridging
2022            (actually current code STILL doesn't)
2023         */
2024         if (fr->ts + 50000 <= p1->last) {
2025                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2026                 if (option_debug)
2027                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2028         }
2029
2030         /* Send with timestamp adjusted to the origin of the outbound leg */
2031         /* But don't destroy inbound timestamp still needed later to set "last" */
2032         orig_ts = fr->ts;
2033         fr->ts = calc_fakestamp(p1, p2, fr->ts);
2034         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2035         fr->ts = orig_ts;
2036         return res;
2037 }
2038 #endif
2039
2040 static void unwrap_timestamp(struct iax_frame *fr)
2041 {
2042         int x;
2043
2044         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2045                 x = fr->ts - iaxs[fr->callno]->last;
2046                 if (x < -50000) {
2047                         /* Sudden big jump backwards in timestamp:
2048                            What likely happened here is that miniframe timestamp has circled but we haven't
2049                            gotten the update from the main packet.  We'll just pretend that we did, and
2050                            update the timestamp appropriately. */
2051                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2052                         if (option_debug)
2053                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2054                 }
2055                 if (x > 50000) {
2056                         /* Sudden apparent big jump forwards in timestamp:
2057                            What's likely happened is this is an old miniframe belonging to the previous
2058                            top-16-bit timestamp that has turned up out of order.
2059                            Adjust the timestamp appropriately. */
2060                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2061                         if (option_debug)
2062                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2063                 }
2064         }
2065 }
2066
2067 #ifdef NEWJB
2068 static int get_from_jb(void *p);
2069
2070 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2071     int when;
2072     struct timeval tv;
2073
2074     gettimeofday(&tv,NULL);
2075
2076     when = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2077           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2078
2079     /*    fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2080
2081     when = jb_next(pvt->jb) - when;
2082     /*   fprintf(stderr, "when = %d\n", when); */
2083
2084     if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2085
2086     if(when <= 0) {
2087       /* XXX should really just empty until when > 0.. */
2088       when = 1;
2089     }
2090
2091     pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2092 }
2093
2094 static int get_from_jb(void *p) {
2095         /* make sure pvt is valid! */   
2096     struct chan_iax2_pvt *pvt = p;
2097     struct iax_frame *fr;
2098     jb_frame frame;
2099     int ret;
2100     long now;
2101     long next;
2102     struct timeval tv;
2103
2104     ast_mutex_lock(&iaxsl[pvt->callno]);
2105     /*  fprintf(stderr, "get_from_jb called\n"); */
2106     pvt->jbid = -1;
2107
2108     gettimeofday(&tv,NULL);
2109     /* round up a millisecond since ast_sched_runq does; */
2110     /* prevents us from spinning while waiting for our now */
2111     /* to catch up with runq's now */
2112     tv.tv_usec += 1000;
2113
2114     now = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2115           (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2116
2117     if(now >= (next = jb_next(pvt->jb))) {
2118         ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2119         switch(ret) {
2120             case JB_OK:
2121                 /*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); */
2122                 fr = frame.data;
2123                 __do_deliver(fr);
2124             break;
2125             case JB_INTERP:
2126             {
2127                 struct ast_frame af;
2128
2129                 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2130
2131                 /* create an interpolation frame */
2132                 /*fprintf(stderr, "Making Interpolation frame\n"); */
2133                 af.frametype = AST_FRAME_VOICE;
2134                 af.subclass = pvt->voiceformat;
2135                 af.datalen  = 0;
2136                 af.samples  = frame.ms * 8;
2137                 af.mallocd  = 0;
2138                 af.src  = "IAX2 JB interpolation";
2139                 af.data  = NULL;
2140                 af.delivery.tv_sec = pvt->rxcore.tv_sec;
2141                 af.delivery.tv_usec = pvt->rxcore.tv_usec;
2142                 af.delivery.tv_sec += next / 1000;
2143                 af.delivery.tv_usec += (next % 1000) * 1000;
2144                 af.offset=AST_FRIENDLY_OFFSET;
2145                 if (af.delivery.tv_usec >= 1000000) {
2146                         af.delivery.tv_usec -= 1000000;
2147                         af.delivery.tv_sec += 1;
2148                 }
2149
2150                 /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2151                  * which we'd need to malloc, and then it would free it.  That seems like a drag */
2152                 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2153                         iax2_queue_frame(pvt->callno, &af);
2154             }
2155             break;
2156             case JB_DROP:
2157                 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2158                 iax2_frame_free(frame.data);
2159             break;
2160             case JB_NOFRAME:
2161             case JB_EMPTY:
2162                 /* do nothing */
2163             break;
2164             default:
2165                 /* shouldn't happen */
2166             break;
2167         }
2168     }
2169     update_jbsched(pvt);
2170     ast_mutex_unlock(&iaxsl[pvt->callno]);
2171     return 0;
2172 }
2173 #endif
2174
2175 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or 
2176  * make preprocessor swiss-cheese out of this one.  I'm not sure which is less revolting.. */
2177 static int schedule_delivery(struct iax_frame *fr, int reallydeliver, int updatehistory, int fromtrunk)
2178 {
2179         int x;
2180 #ifdef NEWJB
2181         int type, len;
2182 #else
2183         int ms;
2184         int delay;
2185         unsigned int orig_ts;
2186         int drops[MEMORY_SIZE];
2187         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2188
2189         /* Remember current jitterbuffer so we can log any change */
2190         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2191         /* Similarly for the frame timestamp */
2192         orig_ts = fr->ts;
2193 #endif
2194
2195 #if 0
2196         if (option_debug)
2197                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, really=%d, update=%d\n",
2198                                 fr->ts, iaxs[fr->callno]->last, reallydeliver, updatehistory);
2199 #endif
2200
2201         /* Attempt to recover wrapped timestamps */
2202         unwrap_timestamp(fr);
2203
2204         if (updatehistory) {
2205
2206                 /* Attempt to spot a change of timebase on timestamps coming from the other side
2207                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2208                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
2209                    for a while - in this case this code might also resync us.  But that's not a bad thing.
2210                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2211                    [that's why we only do this when updatehistory is true]
2212                 */
2213                 x = fr->ts - iaxs[fr->callno]->last;
2214                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2215                         if (option_debug)
2216                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
2217                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
2218                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2219                         iaxs[fr->callno]->rxcore.tv_sec = 0;
2220                         iaxs[fr->callno]->rxcore.tv_usec = 0;
2221                         /* wipe "last" if stamps have jumped backwards */
2222                         if (x<0)
2223                                 iaxs[fr->callno]->last = 0;
2224                         /* should we also empty history? */
2225                 }
2226 #ifndef NEWJB
2227                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2228                    frame we received.  (initially the very first, but also see code just above here).
2229                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
2230                    Called by IAX thread, with iaxsl lock held. */
2231                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2232         
2233                 /* Rotate our history queue of "lateness".  Don't worry about those initial
2234                    zeros because the first entry will always be zero */
2235                 for (x=0;x<MEMORY_SIZE - 1;x++) 
2236                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2237                 /* Add a history entry for this one */
2238                 iaxs[fr->callno]->history[x] = ms;
2239 #endif
2240         }
2241 #ifndef NEWJB
2242         else
2243                 ms = 0;
2244 #endif
2245
2246
2247         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2248         if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2249                 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2250                 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2251                 fr->af.delivery.tv_sec += fr->ts / 1000;
2252                 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2253                 if (fr->af.delivery.tv_usec >= 1000000) {
2254                         fr->af.delivery.tv_usec -= 1000000;
2255                         fr->af.delivery.tv_sec += 1;
2256                 }
2257         }
2258         else {
2259 #if 0
2260                 if (reallydeliver)
2261                         ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2262 #endif
2263                 fr->af.delivery.tv_sec = 0;
2264                 fr->af.delivery.tv_usec = 0;
2265         }
2266
2267 #ifndef NEWJB
2268         /* Initialize the minimum to reasonable values.  It's too much
2269            work to do the same for the maximum, repeatedly */
2270         min=iaxs[fr->callno]->history[0];
2271         for (z=0;z < iax2_dropcount + 1;z++) {
2272                 /* Start very optimistic ;-) */
2273                 max=-999999999;
2274                 for (x=0;x<MEMORY_SIZE;x++) {
2275                         if (max < iaxs[fr->callno]->history[x]) {
2276                                 /* We have a candidate new maximum value.  Make
2277                                    sure it's not in our drop list */
2278                                 match = 0;
2279                                 for (y=0;!match && (y<z);y++)
2280                                         match |= (drops[y] == x);
2281                                 if (!match) {
2282                                         /* It's not in our list, use it as the new maximum */
2283                                         max = iaxs[fr->callno]->history[x];
2284                                         maxone = x;
2285                                 }
2286                                 
2287                         }
2288                         if (!z) {
2289                                 /* On our first pass, find the minimum too */
2290                                 if (min > iaxs[fr->callno]->history[x])
2291                                         min = iaxs[fr->callno]->history[x];
2292                         }
2293                 }
2294 #if 1
2295                 drops[z] = maxone;
2296 #endif
2297         }
2298 #endif
2299
2300 #ifdef NEWJB
2301         if(!reallydeliver)
2302                 return 0;
2303
2304         type = JB_TYPE_CONTROL;
2305         len = 0;
2306
2307         if(fr->af.frametype == AST_FRAME_VOICE) {
2308                 type = JB_TYPE_VOICE;
2309                 len = ast_codec_get_samples(&fr->af) / 8;
2310         } else if(fr->af.frametype == AST_FRAME_CNG) {
2311                 type = JB_TYPE_SILENCE;
2312         }
2313
2314         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2315                 __do_deliver(fr);
2316                 return 0;
2317         }
2318
2319         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2320          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2321         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2322             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2323             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2324                 jb_frame frame;
2325
2326                 /* deliver any frames in the jb */
2327                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2328                         __do_deliver(frame.data);
2329
2330                 jb_reset(iaxs[fr->callno]->jb);
2331
2332                 if (iaxs[fr->callno]->jbid > -1)
2333                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2334
2335                 iaxs[fr->callno]->jbid = -1;
2336
2337                 /* deliver this frame now */
2338                 __do_deliver(fr);
2339                 return 0;
2340
2341         }
2342
2343
2344         /* insert into jitterbuffer */
2345         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2346         if(jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2347              calc_rxstamp(iaxs[fr->callno],fr->ts)) == JB_DROP) {
2348                 iax2_frame_free(fr);
2349         }
2350         update_jbsched(iaxs[fr->callno]);
2351 #else
2352         /* Just for reference, keep the "jitter" value, the difference between the
2353            earliest and the latest. */
2354         if (max >= min)
2355                 iaxs[fr->callno]->jitter = max - min;   
2356         
2357         /* IIR filter for keeping track of historic jitter, but always increase
2358            historic jitter immediately for increase */
2359         
2360         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2361                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2362         else
2363                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2364                         iaxs[fr->callno]->historicjitter;
2365
2366         /* If our jitter buffer is too big (by a significant margin), then we slowly
2367            shrink it to avoid letting the change be perceived */
2368         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2369                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2370
2371         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2372         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2373            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2374            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2375         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2376                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2377
2378         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2379            buffer immediately to accomodate it (and a little more).  */
2380         if (max > iaxs[fr->callno]->jitterbuffer)
2381                 iaxs[fr->callno]->jitterbuffer = max 
2382                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2383
2384         /* update "min", just for RRs and stats */
2385         iaxs[fr->callno]->min = min; 
2386
2387         /* If the caller just wanted us to update, return now */
2388         if (!reallydeliver)
2389                 return 0;
2390
2391         /* Subtract the lateness from our jitter buffer to know how long to wait
2392            before sending our packet.  */
2393         delay = iaxs[fr->callno]->jitterbuffer - ms;
2394
2395         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2396         if (delay > maxjitterbuffer)
2397                 delay = maxjitterbuffer;
2398         
2399         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2400         /* If frame came from trunk, also don't do any delay */
2401         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2402                 delay = 0;
2403
2404         if (option_debug) {
2405                 /* Log jitter stats for possible offline analysis */
2406                 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",
2407                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2408                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2409                                         min, max, iaxs[fr->callno]->jitterbuffer,
2410                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2411                                         ms, delay,
2412                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2413         }
2414
2415         if (delay < 1) {
2416                 /* Don't deliver it more than 4 ms late */
2417                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2418                         if (option_debug)
2419                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2420                         __do_deliver(fr);
2421                 } else {
2422                         if (option_debug)
2423                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2424                         iaxs[fr->callno]->frames_dropped++;
2425                         /* Free our iax frame */
2426                         iax2_frame_free(fr);
2427                 }
2428         } else {
2429                 if (option_debug)
2430                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2431                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2432         }
2433 #endif
2434         return 0;
2435 }
2436
2437 static int iax2_transmit(struct iax_frame *fr)
2438 {
2439         /* Lock the queue and place this packet at the end */
2440         fr->next = NULL;
2441         fr->prev = NULL;
2442         /* By setting this to 0, the network thread will send it for us, and
2443            queue retransmission if necessary */
2444         fr->sentyet = 0;
2445         ast_mutex_lock(&iaxq.lock);
2446         if (!iaxq.head) {
2447                 /* Empty queue */
2448                 iaxq.head = fr;
2449                 iaxq.tail = fr;
2450         } else {
2451                 /* Double link */
2452                 iaxq.tail->next = fr;
2453                 fr->prev = iaxq.tail;
2454                 iaxq.tail = fr;
2455         }
2456         iaxq.count++;
2457         ast_mutex_unlock(&iaxq.lock);
2458         /* Wake up the network thread */
2459         pthread_kill(netthreadid, SIGURG);
2460         return 0;
2461 }
2462
2463
2464
2465 static int iax2_digit(struct ast_channel *c, char digit)
2466 {
2467         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2468 }
2469
2470 static int iax2_sendtext(struct ast_channel *c, const char *text)
2471 {
2472         
2473         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2474                 0, 0, text, strlen(text) + 1, -1);
2475 }
2476
2477 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2478 {
2479         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2480 }
2481
2482 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2483 {
2484         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2485 }
2486
2487 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2488 {
2489         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2490         ast_mutex_lock(&iaxsl[callno]);
2491         if (iaxs[callno])
2492                 iaxs[callno]->owner = newchan;
2493         else
2494                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2495         ast_mutex_unlock(&iaxsl[callno]);
2496         return 0;
2497 }
2498
2499 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2500 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2501
2502 static void destroy_user(struct iax2_user *user);
2503 static int expire_registry(void *data);
2504
2505 static struct iax2_peer *realtime_peer(const char *peername)
2506 {
2507         struct ast_variable *var;
2508         struct ast_variable *tmp;
2509         struct iax2_peer *peer=NULL;
2510         time_t regseconds, nowtime;
2511         int dynamic=0;
2512
2513         var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2514         if (!var)
2515                 return NULL;
2516
2517         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2518         
2519         if (!peer)
2520                 return NULL;
2521
2522         tmp = var;
2523         while(tmp) {
2524                 /* Make sure it's not a user only... */
2525                 if (!strcasecmp(tmp->name, "type")) {
2526                         if (strcasecmp(tmp->value, "friend") &&
2527                             strcasecmp(tmp->value, "peer")) {
2528                                 /* Whoops, we weren't supposed to exist! */
2529                                 destroy_peer(peer);
2530                                 peer = NULL;
2531                                 break;
2532                         } 
2533                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2534                         if (sscanf(tmp->value, "%li", &regseconds) != 1)
2535                                 regseconds = 0;
2536                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2537                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2538                 } else if (!strcasecmp(tmp->name, "port")) {
2539                         peer->addr.sin_port = htons(atoi(tmp->value));
2540                 } else if (!strcasecmp(tmp->name, "host")) {
2541                         if (!strcasecmp(tmp->value, "dynamic"))
2542                                 dynamic = 1;
2543                 }
2544                 tmp = tmp->next;
2545         }
2546         if (!peer)
2547                 return NULL;
2548
2549         ast_variables_destroy(var);
2550
2551         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2552                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2553                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2554                         if (peer->expire > -1)
2555                                 ast_sched_del(sched, peer->expire);
2556                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2557                 }
2558                 ast_mutex_lock(&peerl.lock);
2559                 peer->next = peerl.peers;
2560                 peerl.peers = peer;
2561                 ast_mutex_unlock(&peerl.lock);
2562         } else {
2563                 ast_set_flag(peer, IAX_TEMPONLY);       
2564         }
2565
2566         if (dynamic) {
2567                 time(&nowtime);
2568                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2569                         memset(&peer->addr, 0, sizeof(peer->addr));
2570                         if (option_debug)
2571                                 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2572                 }
2573         }
2574
2575         return peer;
2576 }
2577
2578 static struct iax2_user *realtime_user(const char *username)
2579 {
2580         struct ast_variable *var;
2581         struct ast_variable *tmp;
2582         struct iax2_user *user=NULL;
2583
2584         var = ast_load_realtime("iaxusers", "name", username, NULL);
2585         if (!var)
2586                 return NULL;
2587
2588         tmp = var;
2589         while(tmp) {
2590                 /* Make sure it's not a peer only... */
2591                 if (!strcasecmp(tmp->name, "type")) {
2592                         if (strcasecmp(tmp->value, "friend") &&
2593                             strcasecmp(tmp->value, "user")) {
2594                                 return NULL;
2595                         } 
2596                 }
2597                 tmp = tmp->next;
2598         }
2599
2600         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2601         if (!user)
2602                 return NULL;
2603
2604         ast_variables_destroy(var);
2605
2606         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2607                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2608                 ast_mutex_lock(&userl.lock);
2609                 user->next = userl.users;
2610                 userl.users = user;
2611                 ast_mutex_unlock(&userl.lock);
2612         } else {
2613                 ast_set_flag(user, IAX_TEMPONLY);       
2614         }
2615
2616         return user;
2617 }
2618
2619 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2620 {
2621         char port[10];
2622         char ipaddr[20];
2623         char regseconds[20];
2624         time_t nowtime;
2625         
2626         time(&nowtime);
2627         snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2628         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2629         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2630         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2631 }
2632
2633
2634 static int create_addr(struct sockaddr_in *sin, int *capability, int *sendani, 
2635                                            int *maxtime, char *peer, char *context, int *trunk, 
2636                                            int *notransfer, int *usejitterbuf, int *forcejitterbuf, int *encmethods, 
2637                                            char *username, int usernlen, char *secret, int seclen, 
2638                                            int *ofound, char *peercontext, char *timezone, int tzlen, char *pref_str, size_t pref_size,
2639                                            int *sockfd)
2640 {
2641         struct ast_hostent ahp; struct hostent *hp;
2642         struct iax2_peer *p;
2643         int found=0;
2644         if (sendani)
2645                 *sendani = 0;
2646         if (maxtime)
2647                 *maxtime = 0;
2648         if (trunk)
2649                 *trunk = 0;
2650         if (sockfd)
2651                 *sockfd = defaultsockfd;
2652         sin->sin_family = AF_INET;
2653         p = find_peer(peer, 1);
2654         if (p) {
2655                 found++;
2656                 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
2657                         (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
2658
2659                         if(pref_str) {
2660                                 ast_codec_pref_convert(&p->prefs, pref_str, pref_size, 1);
2661                         }
2662                         if (sendani)
2663                                 *sendani = ast_test_flag(p, IAX_SENDANI);               /* Whether we transmit ANI */
2664                         if (maxtime)
2665                                 *maxtime = p->maxms;            /* Max time they should take */
2666                         if (context)
2667                                 ast_copy_string(context, p->context, sizeof(context));
2668                         if (peercontext)
2669                                 ast_copy_string(peercontext, p->peercontext, sizeof(peercontext));
2670                         if (trunk)
2671                                 *trunk = ast_test_flag(p, IAX_TRUNK);
2672                         if (capability)
2673                                 *capability = p->capability;
2674                         if (encmethods)
2675                                 *encmethods = p->encmethods;
2676                         if (username)
2677                                 ast_copy_string(username, p->username, usernlen);
2678                         if (p->addr.sin_addr.s_addr) {
2679                                 sin->sin_addr = p->addr.sin_addr;
2680                                 sin->sin_port = p->addr.sin_port;
2681                         } else {
2682                                 sin->sin_addr = p->defaddr.sin_addr;
2683                                 sin->sin_port = p->defaddr.sin_port;
2684                         }
2685                         if (sockfd)
2686                                 *sockfd = p->sockfd;
2687                         if (notransfer)
2688                                 *notransfer = ast_test_flag(p, IAX_NOTRANSFER);
2689                         if (usejitterbuf)
2690                                 *usejitterbuf = ast_test_flag(p, IAX_USEJITTERBUF);
2691                         if (forcejitterbuf)
2692                                 *forcejitterbuf = ast_test_flag(p, IAX_FORCEJITTERBUF);
2693                         if (secret) {
2694                                 if (!ast_strlen_zero(p->dbsecret)) {
2695                                         char *family, *key=NULL;
2696                                         family = ast_strdupa(p->dbsecret);
2697                                         if (family) {
2698                                                 key = strchr(family, '/');
2699                                                 if (key) {
2700                                                         *key = '\0';
2701                                                         key++;
2702                                                 }
2703                                         }
2704                                         if (!family || !key || ast_db_get(family, key, secret, seclen)) {
2705                                                 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", p->dbsecret);
2706                                                 if (ast_test_flag(p, IAX_TEMPONLY))
2707                                                         destroy_peer(p);
2708                                                 p = NULL;
2709                                         }
2710                                 } else
2711                                         ast_copy_string(secret, p->secret, seclen);
2712                         }
2713                         if (timezone)
2714                                 snprintf(timezone, tzlen-1, "%s", p->zonetag);
2715                 } else {
2716                         if (ast_test_flag(p, IAX_TEMPONLY))
2717                                 destroy_peer(p);
2718                         p = NULL;
2719                 }
2720         }
2721         if (ofound)
2722                 *ofound = found;
2723         if (!p && !found) {
2724                 if(pref_str) { /* use global iax prefs for unknown peer/user */
2725                         ast_codec_pref_convert(&prefs, pref_str, pref_size, 1);
2726                 }
2727
2728                 hp = ast_gethostbyname(peer, &ahp);
2729                 if (hp) {
2730                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2731                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2732                         return 0;
2733                 } else {
2734                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
2735                         return -1;
2736                 }
2737         } else if (!p)
2738                 return -1;
2739         if (ast_test_flag(p, IAX_TEMPONLY))
2740                 destroy_peer(p);
2741         return 0;
2742 }
2743
2744 static int auto_congest(void *nothing)
2745 {
2746         int callno = PTR_TO_CALLNO(nothing);
2747         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2748         ast_mutex_lock(&iaxsl[callno]);
2749         if (iaxs[callno]) {
2750                 iaxs[callno]->initid = -1;
2751                 iax2_queue_frame(callno, &f);
2752                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2753         }
2754         ast_mutex_unlock(&iaxsl[callno]);
2755         return 0;
2756 }
2757
2758 static unsigned int iax2_datetime(char *tz)
2759 {
2760         time_t t;
2761         struct tm tm;
2762         unsigned int tmp;
2763         time(&t);
2764         localtime_r(&t, &tm);
2765         if (!ast_strlen_zero(tz))
2766                 ast_localtime(&t, &tm, tz);
2767         tmp  = (tm.tm_sec >> 1) & 0x1f;   /* 5 bits of seconds */
2768         tmp |= (tm.tm_min & 0x3f) << 5;   /* 6 bits of minutes */
2769         tmp |= (tm.tm_hour & 0x1f) << 11;   /* 5 bits of hours */
2770         tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2771         tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2772         tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2773         return tmp;
2774 }
2775
2776 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2777 {
2778         struct sockaddr_in sin;
2779         char host[256];
2780         char *rdest;
2781         char *rcontext;
2782         char *username;
2783         char *secret = NULL;
2784         char *hname;
2785         char *l=NULL, *n=NULL;
2786         struct iax_ie_data ied;
2787         char myrdest [5] = "s";
2788         char context[AST_MAX_EXTENSION] ="";
2789         char peercontext[AST_MAX_EXTENSION] ="";
2790         char *portno = NULL;
2791         char *opts = "";
2792         int encmethods=iax2_encryption;
2793         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2794         char *stringp=NULL;
2795         char storedusern[80], storedsecret[80];
2796         char tz[80] = "";       
2797         char out_prefs[32];
2798
2799         memset(out_prefs,0,32);
2800
2801         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2802                 ast_log(LOG_WARNING, "Line is already in use (%s)?\n", c->name);
2803                 return -1;
2804         }
2805         ast_copy_string(host, dest, sizeof(host));
2806         stringp=host;
2807         strsep(&stringp, "/");
2808         /* If no destination extension specified, use 's' */
2809         rdest = strsep(&stringp, "/");
2810         if (!rdest) 
2811                 rdest = myrdest;
2812         else {
2813                 /* Check for trailing options */
2814                 opts = strsep(&stringp, "/");
2815                 if (!opts)
2816                         opts = "";
2817         }
2818         stringp=rdest;
2819         strsep(&stringp, "@");
2820         rcontext = strsep(&stringp, "@");
2821         stringp=host;
2822         strsep(&stringp, "@");
2823         username = strsep(&stringp, "@");
2824         if (username) {
2825                 /* Really the second argument is the host, not the username */
2826                 hname = username;
2827                 username = host;
2828         } else {
2829                 hname = host;
2830         }
2831         if (username) {
2832                 stringp=username;
2833                 username = strsep(&stringp, ":");
2834                 secret = strsep(&stringp, ":");
2835         }
2836         stringp=hname;
2837         if (strsep(&stringp, ":")) {
2838                 stringp=hname;
2839                 strsep(&stringp, ":");
2840                 portno = strsep(&stringp, ":");
2841         }
2842         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)) {
2843                 ast_log(LOG_WARNING, "No address associated with '%s'\n", hname);
2844                 return -1;
2845         }
2846         /* Keep track of the context for outgoing calls too */
2847         ast_copy_string(c->context, context, sizeof(c->context));
2848         if (portno) {
2849                 sin.sin_port = htons(atoi(portno));
2850         }
2851         l = c->cid.cid_num;
2852         n = c->cid.cid_name;
2853         /* Now build request */ 
2854         memset(&ied, 0, sizeof(ied));
2855         /* On new call, first IE MUST be IAX version of caller */
2856         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2857         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, rdest);
2858         if (strchr(opts, 'a')) {
2859                 /* Request auto answer */
2860                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2861         }
2862         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, out_prefs);
2863
2864         if (l) {
2865                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2866                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2867         } else
2868                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2869         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2870         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2871         if (n)
2872                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2873         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani) {
2874                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2875         }
2876         if (c->language && !ast_strlen_zero(c->language))
2877                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2878         if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2879                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2880         if (rcontext)
2881                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, rcontext);
2882         else if (strlen(peercontext))
2883                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, peercontext);
2884         if (!username && !ast_strlen_zero(storedusern))
2885                 username = storedusern;
2886         if (username)
2887                 iax_ie_append_str(&ied, IAX_IE_USERNAME, username);
2888         if (encmethods)
2889                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, encmethods);
2890         if (!secret && !ast_strlen_zero(storedsecret))
2891                 secret = storedsecret;
2892         ast_mutex_lock(&iaxsl[callno]);
2893         if (!ast_strlen_zero(c->context))
2894                 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2895         if (username)
2896                 ast_copy_string(iaxs[callno]->username, username, sizeof(iaxs[callno]->username));
2897         iaxs[callno]->encmethods = encmethods;
2898         if (secret) {
2899                 if (secret[0] == '[') {
2900                         /* This is an RSA key, not a normal secret */
2901                         ast_copy_string(iaxs[callno]->outkey, secret + 1, sizeof(iaxs[callno]->secret));
2902                         if (!ast_strlen_zero(iaxs[callno]->outkey)) {
2903                                 iaxs[callno]->outkey[strlen(iaxs[callno]->outkey) - 1] = '\0';
2904                         }
2905                 } else
2906                         ast_copy_string(iaxs[callno]->secret, secret, sizeof(iaxs[callno]->secret));
2907         }
2908         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2909         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2910         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2911         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(tz));
2912         /* Transmit the string in a "NEW" request */
2913 #if 0
2914         /* XXX We have no equivalent XXX */
2915         if (option_verbose > 2)
2916                 ast_verbose(VERBOSE_PREFIX_3 "Calling using options '%s'\n", requeststr);
2917 #endif          
2918         if (iaxs[callno]->maxtime) {
2919                 /* Initialize pingtime and auto-congest time */
2920                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2921                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2922         } else if (autokill) {
2923                 iaxs[callno]->pingtime = autokill / 2;
2924                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2925         }
2926         send_command(iaxs[callno], AST_FRAME_IAX,
2927                 IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2928         ast_mutex_unlock(&iaxsl[callno]);
2929         ast_setstate(c, AST_STATE_RINGING);
2930         return 0;
2931 }
2932
2933 static int iax2_hangup(struct ast_channel *c) 
2934 {
2935         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2936         int alreadygone;
2937         struct iax_ie_data ied;
2938         memset(&ied, 0, sizeof(ied));
2939         ast_mutex_lock(&iaxsl[callno]);
2940         if (callno && iaxs[callno]) {
2941                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2942                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2943                 /* Send the hangup unless we have had a transmission error or are already gone */
2944                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2945                 if (!iaxs[callno]->error && !alreadygone) 
2946                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2947                 /* Explicitly predestroy it */
2948                 iax2_predestroy_nolock(callno);
2949                 /* If we were already gone to begin with, destroy us now */
2950                 if (alreadygone) {
2951                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2952                         iax2_destroy_nolock(callno);
2953                 }
2954         }
2955         ast_mutex_unlock(&iaxsl[callno]);
2956         if (option_verbose > 2) 
2957                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2958         return 0;
2959 }
2960
2961 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2962 {
2963         struct ast_option_header *h;
2964         int res;
2965         h = malloc(datalen + sizeof(struct ast_option_header));
2966         if (h) {
2967                 h->flag = AST_OPTION_FLAG_REQUEST;
2968                 h->option = htons(option);
2969                 memcpy(h->data, data, datalen);
2970                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
2971                         AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
2972                 free(h);
2973                 return res;
2974         } else 
2975                 ast_log(LOG_WARNING, "Out of memory\n");
2976         return -1;
2977 }
2978
2979 static struct ast_frame *iax2_read(struct ast_channel *c) 
2980 {
2981         static struct ast_frame f = { AST_FRAME_NULL, };
2982         ast_log(LOG_NOTICE, "I should never be called!\n");
2983         return &f;
2984 }
2985
2986 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
2987 {
2988         int res;
2989         struct iax_ie_data ied0;
2990         struct iax_ie_data ied1;
2991         unsigned int transferid = rand();
2992         memset(&ied0, 0, sizeof(ied0));
2993         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2994         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2995         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2996
2997         memset(&ied1, 0, sizeof(ied1));
2998         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2999         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3000         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3001         
3002         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3003         if (res)
3004                 return -1;
3005         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3006         if (res)
3007                 return -1;
3008         iaxs[callno0]->transferring = TRANSFER_BEGIN;
3009         iaxs[callno1]->transferring = TRANSFER_BEGIN;
3010         return 0;
3011 }
3012
3013 static void lock_both(unsigned short callno0, unsigned short callno1)
3014 {
3015         ast_mutex_lock(&iaxsl[callno0]);
3016         while (ast_mutex_trylock(&iaxsl[callno1])) {
3017                 ast_mutex_unlock(&iaxsl[callno0]);
3018                 usleep(10);
3019                 ast_mutex_lock(&iaxsl[callno0]);
3020         }
3021 }
3022
3023 static void unlock_both(unsigned short callno0, unsigned short callno1)
3024 {
3025         ast_mutex_unlock(&iaxsl[callno1]);
3026         ast_mutex_unlock(&iaxsl[callno0]);
3027 }
3028
3029 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
3030 {
3031         struct ast_channel *cs[3];
3032         struct ast_channel *who;
3033         int to = -1;
3034         int res = -1;
3035         int transferstarted=0;
3036         struct ast_frame *f;
3037         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3038         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3039         struct timeval waittimer = {0, 0}, tv;
3040
3041         lock_both(callno0, callno1);
3042         /* Put them in native bridge mode */
3043         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3044                 iaxs[callno0]->bridgecallno = callno1;
3045                 iaxs[callno1]->bridgecallno = callno0;
3046         }
3047         unlock_both(callno0, callno1);
3048
3049         /* If not, try to bridge until we can execute a transfer, if we can */
3050         cs[0] = c0;
3051         cs[1] = c1;
3052         for (/* ever */;;) {
3053                 /* Check in case we got masqueraded into */
3054                 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3055                         if (option_verbose > 2)
3056                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3057                         /* Remove from native mode */
3058                         if (c0->type == channeltype) {
3059                                 ast_mutex_lock(&iaxsl[callno0]);
3060                                 iaxs[callno0]->bridgecallno = 0;
3061                                 ast_mutex_unlock(&iaxsl[callno0]);
3062                         }
3063                         if (c1->type == channeltype) {
3064                                 ast_mutex_lock(&iaxsl[callno1]);
3065                                 iaxs[callno1]->bridgecallno = 0;
3066                                 ast_mutex_unlock(&iaxsl[callno1]);
3067                         }
3068                         return -2;
3069                 }
3070                 if (c0->nativeformats != c1->nativeformats) {
3071                         if (option_verbose > 2) {
3072                                 char buf0[255];
3073                                 char buf1[255];
3074                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3075                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3076                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3077                         }
3078                         /* Remove from native mode */
3079                         lock_both(callno0, callno1);
3080                         iaxs[callno0]->bridgecallno = 0;
3081                         iaxs[callno1]->bridgecallno = 0;
3082                         unlock_both(callno0, callno1);
3083                         return -2;
3084                 }
3085                 /* check if transfered and if we really want native bridging */
3086                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) && 
3087                 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3088                         /* Try the transfer */
3089                         if (iax2_start_transfer(callno0, callno1))
3090                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3091                         transferstarted = 1;
3092                 }
3093                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3094                         /* Call has been transferred.  We're no longer involved */
3095                         gettimeofday(&tv, NULL);