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