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