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