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