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