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