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