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