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