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