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