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