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