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