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