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