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