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