store f->callno in a local var (issue #6818)
[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         int callno = f->callno;
1611         
1612         /* Called with iaxsl held */
1613         if (option_debug > 2 && iaxdebug)
1614                 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1615         /* Don't send if there was an error, but return error instead */
1616         if (!callno) {
1617                 ast_log(LOG_WARNING, "Call number = %d\n", callno);
1618                 return -1;
1619         }
1620         if (!iaxs[callno])
1621                 return -1;
1622         if (iaxs[callno]->error)
1623                 return -1;
1624         if (f->transfer) {
1625                 if (iaxdebug)
1626                         iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1627                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1628                                         sizeof(iaxs[callno]->transfer));
1629         } else {
1630                 if (iaxdebug)
1631                         iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1632                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1633                                         sizeof(iaxs[callno]->addr));
1634         }
1635         if (res < 0) {
1636                 if (option_debug && iaxdebug)
1637                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1638                 handle_error();
1639         } else
1640                 res = 0;
1641         return res;
1642 }
1643
1644
1645 static int iax2_predestroy(int callno)
1646 {
1647         struct ast_channel *c;
1648         struct chan_iax2_pvt *pvt;
1649         ast_mutex_lock(&iaxsl[callno]);
1650         pvt = iaxs[callno];
1651         if (!pvt) {
1652                 ast_mutex_unlock(&iaxsl[callno]);
1653                 return -1;
1654         }
1655         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1656                 /* No more pings or lagrq's */
1657                 if (pvt->pingid > -1)
1658                         ast_sched_del(sched, pvt->pingid);
1659                 if (pvt->lagid > -1)
1660                         ast_sched_del(sched, pvt->lagid);
1661                 if (pvt->autoid > -1)
1662                         ast_sched_del(sched, pvt->autoid);
1663                 if (pvt->authid > -1)
1664                         ast_sched_del(sched, pvt->authid);
1665                 if (pvt->initid > -1)
1666                         ast_sched_del(sched, pvt->initid);
1667 #ifdef NEWJB
1668                 if (pvt->jbid > -1)
1669                         ast_sched_del(sched, pvt->jbid);
1670                 pvt->jbid = -1;
1671 #endif
1672                 pvt->pingid = -1;
1673                 pvt->lagid = -1;
1674                 pvt->autoid = -1;
1675                 pvt->initid = -1;
1676                 pvt->authid = -1;
1677                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1678         }
1679         c = pvt->owner;
1680         if (c) {
1681                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1682                 c->tech_pvt = NULL;
1683                 ast_queue_hangup(c);
1684                 pvt->owner = NULL;
1685                 ast_mutex_lock(&usecnt_lock);
1686                 usecnt--;
1687                 if (usecnt < 0) 
1688                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1689                 ast_mutex_unlock(&usecnt_lock);
1690         }
1691         ast_mutex_unlock(&iaxsl[callno]);
1692         ast_update_use_count();
1693         return 0;
1694 }
1695
1696 static int iax2_predestroy_nolock(int callno)
1697 {
1698         int res;
1699         ast_mutex_unlock(&iaxsl[callno]);
1700         res = iax2_predestroy(callno);
1701         ast_mutex_lock(&iaxsl[callno]);
1702         return res;
1703 }
1704
1705 static void iax2_destroy(int callno)
1706 {
1707         struct chan_iax2_pvt *pvt;
1708         struct iax_frame *cur;
1709         struct ast_channel *owner;
1710
1711 retry:
1712         ast_mutex_lock(&iaxsl[callno]);
1713         pvt = iaxs[callno];
1714         gettimeofday(&lastused[callno], NULL);
1715
1716         if (pvt)
1717                 owner = pvt->owner;
1718         else
1719                 owner = NULL;
1720         if (owner) {
1721                 if (ast_mutex_trylock(&owner->lock)) {
1722                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1723                         ast_mutex_unlock(&iaxsl[callno]);
1724                         usleep(1);
1725                         goto retry;
1726                 }
1727         }
1728         if (!owner)
1729                 iaxs[callno] = NULL;
1730         if (pvt) {
1731                 if (!owner)
1732                         pvt->owner = NULL;
1733                 /* No more pings or lagrq's */
1734                 if (pvt->pingid > -1)
1735                         ast_sched_del(sched, pvt->pingid);
1736                 if (pvt->lagid > -1)
1737                         ast_sched_del(sched, pvt->lagid);
1738                 if (pvt->autoid > -1)
1739                         ast_sched_del(sched, pvt->autoid);
1740                 if (pvt->authid > -1)
1741                         ast_sched_del(sched, pvt->authid);
1742                 if (pvt->initid > -1)
1743                         ast_sched_del(sched, pvt->initid);
1744 #ifdef NEWJB
1745                 if (pvt->jbid > -1)
1746                         ast_sched_del(sched, pvt->jbid);
1747                 pvt->jbid = -1;
1748 #endif
1749                 pvt->pingid = -1;
1750                 pvt->lagid = -1;
1751                 pvt->autoid = -1;
1752                 pvt->authid = -1;
1753                 pvt->initid = -1;
1754                 if (pvt->bridgetrans)
1755                         ast_translator_free_path(pvt->bridgetrans);
1756                 pvt->bridgetrans = NULL;
1757
1758                 /* Already gone */
1759                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1760
1761                 if (owner) {
1762                         /* If there's an owner, prod it to give up */
1763                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1764                         ast_queue_hangup(owner);
1765                 }
1766
1767                 for (cur = iaxq.head; cur ; cur = cur->next) {
1768                         /* Cancel any pending transmissions */
1769                         if (cur->callno == pvt->callno) 
1770                                 cur->retries = -1;
1771                 }
1772                 if (pvt->reg) {
1773                         pvt->reg->callno = 0;
1774                 }
1775                 if (!owner) {
1776                         if (pvt->vars) {
1777                                 ast_variables_destroy(pvt->vars);
1778                                 pvt->vars = NULL;
1779                         }
1780 #ifdef NEWJB
1781                         {
1782                             jb_frame frame;
1783                             while(jb_getall(pvt->jb,&frame) == JB_OK)
1784                                 iax2_frame_free(frame.data);
1785                             jb_destroy(pvt->jb);
1786                         }
1787 #endif
1788                         free(pvt);
1789                 }
1790         }
1791         if (owner) {
1792                 ast_mutex_unlock(&owner->lock);
1793         }
1794         ast_mutex_unlock(&iaxsl[callno]);
1795         if (callno & 0x4000)
1796                 update_max_trunk();
1797 }
1798 static void iax2_destroy_nolock(int callno)
1799 {       
1800         /* Actually it's easier to unlock, kill it, and relock */
1801         ast_mutex_unlock(&iaxsl[callno]);
1802         iax2_destroy(callno);
1803         ast_mutex_lock(&iaxsl[callno]);
1804 }
1805
1806 static int update_packet(struct iax_frame *f)
1807 {
1808         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1809         struct ast_iax2_full_hdr *fh = f->data;
1810         /* Mark this as a retransmission */
1811         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1812         /* Update iseqno */
1813         f->iseqno = iaxs[f->callno]->iseqno;
1814         fh->iseqno = f->iseqno;
1815         return 0;
1816 }
1817
1818 static int attempt_transmit(void *data);
1819 static void __attempt_transmit(void *data)
1820 {
1821         /* Attempt to transmit the frame to the remote peer...
1822            Called without iaxsl held. */
1823         struct iax_frame *f = data;
1824         int freeme=0;
1825         int callno = f->callno;
1826         char iabuf[INET_ADDRSTRLEN];
1827         /* Make sure this call is still active */
1828         if (callno) 
1829                 ast_mutex_lock(&iaxsl[callno]);
1830         if ((f->callno) && iaxs[f->callno]) {
1831                 if ((f->retries < 0) /* Already ACK'd */ ||
1832                     (f->retries >= max_retries) /* Too many attempts */) {
1833                                 /* Record an error if we've transmitted too many times */
1834                                 if (f->retries >= max_retries) {
1835                                         if (f->transfer) {
1836                                                 /* Transfer timeout */
1837                                                 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1838                                         } else if (f->final) {
1839                                                 if (f->final) 
1840                                                         iax2_destroy_nolock(f->callno);
1841                                         } else {
1842                                                 if (iaxs[f->callno]->owner)
1843                                                         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);
1844                                                 iaxs[f->callno]->error = ETIMEDOUT;
1845                                                 if (iaxs[f->callno]->owner) {
1846                                                         struct ast_frame fr = { 0, };
1847                                                         /* Hangup the fd */
1848                                                         fr.frametype = AST_FRAME_CONTROL;
1849                                                         fr.subclass = AST_CONTROL_HANGUP;
1850                                                         iax2_queue_frame(f->callno, &fr);
1851                                                         /* Remember, owner could disappear */
1852                                                         if (iaxs[f->callno]->owner)
1853                                                                 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1854                                                 } else {
1855                                                         if (iaxs[f->callno]->reg) {
1856                                                                 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1857                                                                 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1858                                                                 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1859                                                         }
1860                                                         iax2_destroy_nolock(f->callno);
1861                                                 }
1862                                         }
1863
1864                                 }
1865                                 freeme++;
1866                 } else {
1867                         /* Update it if it needs it */
1868                         update_packet(f);
1869                         /* Attempt transmission */
1870                         send_packet(f);
1871                         f->retries++;
1872                         /* Try again later after 10 times as long */
1873                         f->retrytime *= 10;
1874                         if (f->retrytime > MAX_RETRY_TIME)
1875                                 f->retrytime = MAX_RETRY_TIME;
1876                         /* Transfer messages max out at one second */
1877                         if (f->transfer && (f->retrytime > 1000))
1878                                 f->retrytime = 1000;
1879                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1880                 }
1881         } else {
1882                 /* Make sure it gets freed */
1883                 f->retries = -1;
1884                 freeme++;
1885         }
1886         if (callno)
1887                 ast_mutex_unlock(&iaxsl[callno]);
1888         /* Do not try again */
1889         if (freeme) {
1890                 /* Don't attempt delivery, just remove it from the queue */
1891                 ast_mutex_lock(&iaxq.lock);
1892                 if (f->prev) 
1893                         f->prev->next = f->next;
1894                 else
1895                         iaxq.head = f->next;
1896                 if (f->next)
1897                         f->next->prev = f->prev;
1898                 else
1899                         iaxq.tail = f->prev;
1900                 iaxq.count--;
1901                 ast_mutex_unlock(&iaxq.lock);
1902                 f->retrans = -1;
1903                 /* Free the IAX frame */
1904                 iax2_frame_free(f);
1905         }
1906 }
1907
1908 static int attempt_transmit(void *data)
1909 {
1910 #ifdef SCHED_MULTITHREADED
1911         if (schedule_action(__attempt_transmit, data))
1912 #endif          
1913                 __attempt_transmit(data);
1914         return 0;
1915 }
1916
1917 static int iax2_set_jitter(int fd, int argc, char *argv[])
1918 {
1919 #ifdef NEWJB
1920         ast_cli(fd, "sorry, this command is deprecated\n");
1921         return RESULT_SUCCESS;
1922 #else
1923         if ((argc != 4) && (argc != 5))
1924                 return RESULT_SHOWUSAGE;
1925         if (argc == 4) {
1926                 max_jitter_buffer = atoi(argv[3]);
1927                 if (max_jitter_buffer < 0)
1928                         max_jitter_buffer = 0;
1929         } else {
1930                 if (argc == 5) {
1931                         if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1932                                 if (iaxs[atoi(argv[3])]) {
1933                                         iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1934                                         if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1935                                                 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1936                                 } else
1937                                         ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1938                         } else
1939                                 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1940                 }
1941         }
1942         return RESULT_SUCCESS;
1943 #endif
1944 }
1945
1946 static char jitter_usage[] = 
1947 "Usage: iax set jitter [callid] <value>\n"
1948 "       If used with a callid, it sets the jitter buffer to the given static\n"
1949 "value (until its next calculation).  If used without a callid, the value is used\n"
1950 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1951 "buffer size is reduced.";
1952
1953 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1954 {
1955         struct iax2_peer *peer;
1956
1957         if (argc != 4)
1958         return RESULT_SHOWUSAGE;
1959         if (!strcmp(argv[3],"all")) {
1960                 reload_config();
1961                 ast_cli(fd, "OK cache is flushed.\n");
1962         } else if ((peer = find_peer(argv[3], 0))) {
1963                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1964                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1965                         expire_registry(peer);
1966                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1967                 } else {
1968                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1969                 }
1970         } else {
1971                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1972         }
1973         
1974         return RESULT_SUCCESS;
1975 }
1976
1977 static int iax2_test_losspct(int fd, int argc, char *argv[])
1978 {
1979        if (argc != 4)
1980                return RESULT_SHOWUSAGE;
1981
1982        test_losspct = atoi(argv[3]);
1983
1984        return RESULT_SUCCESS;
1985 }
1986
1987 #ifdef IAXTESTS
1988 static int iax2_test_late(int fd, int argc, char *argv[])
1989 {
1990         if (argc != 4)
1991                 return RESULT_SHOWUSAGE;
1992
1993         test_late = atoi(argv[3]);
1994
1995         return RESULT_SUCCESS;
1996 }
1997
1998 static int iax2_test_resync(int fd, int argc, char *argv[])
1999 {
2000         if (argc != 4)
2001                 return RESULT_SHOWUSAGE;
2002
2003         test_resync = atoi(argv[3]);
2004
2005         return RESULT_SUCCESS;
2006 }
2007
2008 static int iax2_test_jitter(int fd, int argc, char *argv[])
2009 {
2010         if (argc < 4 || argc > 5)
2011                 return RESULT_SHOWUSAGE;
2012
2013         test_jit = atoi(argv[3]);
2014         if (argc == 5) 
2015                 test_jitpct = atoi(argv[4]);
2016
2017         return RESULT_SUCCESS;
2018 }
2019 #endif /* IAXTESTS */
2020
2021 /*! \brief  peer_status: Report Peer status in character string */
2022 /*      returns 1 if peer is online, -1 if unmonitored */
2023 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2024 {
2025         int res = 0;
2026         if (peer->maxms) {
2027                 if (peer->lastms < 0) {
2028                         ast_copy_string(status, "UNREACHABLE", statuslen);
2029                 } else if (peer->lastms > peer->maxms) {
2030                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2031                         res = 1;
2032                 } else if (peer->lastms) {
2033                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2034                         res = 1;
2035                 } else {
2036                         ast_copy_string(status, "UNKNOWN", statuslen);
2037                 }
2038         } else { 
2039                 ast_copy_string(status, "Unmonitored", statuslen);
2040                 res = -1;
2041         }
2042         return res;
2043 }
2044
2045 /*! \brief Show one peer in detail */
2046 static int iax2_show_peer(int fd, int argc, char *argv[])
2047 {
2048         char status[30];
2049         char cbuf[256];
2050         char iabuf[INET_ADDRSTRLEN];
2051         struct iax2_peer *peer;
2052         char codec_buf[512];
2053         int x = 0, codec = 0, load_realtime = 0;
2054
2055         if (argc < 4)
2056                 return RESULT_SHOWUSAGE;
2057
2058         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2059
2060         peer = find_peer(argv[3], load_realtime);
2061         if (peer) {
2062                 ast_cli(fd,"\n\n");
2063                 ast_cli(fd, "  * Name       : %s\n", peer->name);
2064                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2065                 ast_cli(fd, "  Context      : %s\n", peer->context);
2066                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
2067                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2068                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2069                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
2070                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
2071                 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));
2072                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2073                 ast_cli(fd, "  Username     : %s\n", peer->username);
2074                 ast_cli(fd, "  Codecs       : ");
2075                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2076                 ast_cli(fd, "%s\n", codec_buf);
2077
2078                 ast_cli(fd, "  Codec Order  : (");
2079                 for(x = 0; x < 32 ; x++) {
2080                         codec = ast_codec_pref_index(&peer->prefs,x);
2081                         if(!codec)
2082                                 break;
2083                         ast_cli(fd, "%s", ast_getformatname(codec));
2084                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2085                                 ast_cli(fd, "|");
2086                 }
2087
2088                 if (!x)
2089                         ast_cli(fd, "none");
2090                 ast_cli(fd, ")\n");
2091
2092                 ast_cli(fd, "  Status       : ");
2093                 peer_status(peer, status, sizeof(status));      
2094                 ast_cli(fd, "%s\n",status);
2095                 ast_cli(fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2096                 ast_cli(fd,"\n");
2097                 if (ast_test_flag(peer, IAX_TEMPONLY))
2098                         destroy_peer(peer);
2099         } else {
2100                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2101                 ast_cli(fd,"\n");
2102         }
2103
2104         return RESULT_SUCCESS;
2105 }
2106
2107 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2108 {
2109         int which = 0;
2110         struct iax2_peer *p;
2111         char *res = NULL;
2112         int wordlen = strlen(word);
2113
2114         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2115         if (pos == 3) {
2116                 ast_mutex_lock(&peerl.lock);
2117                 for (p = peerl.peers ; p ; p = p->next) {
2118                         if (!strncasecmp(p->name, word, wordlen)) {
2119                                 if (++which > state) {
2120                                         res = ast_strdup(p->name);
2121                                         break;
2122                                 }
2123                         }
2124                 }
2125                 ast_mutex_unlock(&peerl.lock);
2126         }
2127
2128         return res;
2129 }
2130
2131 static int iax2_show_stats(int fd, int argc, char *argv[])
2132 {
2133         struct iax_frame *cur;
2134         int cnt = 0, dead=0, final=0;
2135         if (argc != 3)
2136                 return RESULT_SHOWUSAGE;
2137         for (cur = iaxq.head; cur ; cur = cur->next) {
2138                 if (cur->retries < 0)
2139                         dead++;
2140                 if (cur->final)
2141                         final++;
2142                 cnt++;
2143         }
2144         ast_cli(fd, "    IAX Statistics\n");
2145         ast_cli(fd, "---------------------\n");
2146         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2147         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
2148         return RESULT_SUCCESS;
2149 }
2150
2151 static int iax2_show_cache(int fd, int argc, char *argv[])
2152 {
2153         struct iax2_dpcache *dp;
2154         char tmp[1024], *pc;
2155         int s;
2156         int x,y;
2157         struct timeval tv;
2158         gettimeofday(&tv, NULL);
2159         ast_mutex_lock(&dpcache_lock);
2160         dp = dpcache;
2161         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2162         while(dp) {
2163                 s = dp->expiry.tv_sec - tv.tv_sec;
2164                 tmp[0] = '\0';
2165                 if (dp->flags & CACHE_FLAG_EXISTS)
2166                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2167                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2168                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2169                 if (dp->flags & CACHE_FLAG_CANEXIST)
2170                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2171                 if (dp->flags & CACHE_FLAG_PENDING)
2172                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2173                 if (dp->flags & CACHE_FLAG_TIMEOUT)
2174                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2175                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2176                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2177                 if (dp->flags & CACHE_FLAG_MATCHMORE)
2178                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2179                 if (dp->flags & CACHE_FLAG_UNKNOWN)
2180                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2181                 /* Trim trailing pipe */
2182                 if (!ast_strlen_zero(tmp))
2183                         tmp[strlen(tmp) - 1] = '\0';
2184                 else
2185                         ast_copy_string(tmp, "(none)", sizeof(tmp));
2186                 y=0;
2187                 pc = strchr(dp->peercontext, '@');
2188                 if (!pc)
2189                         pc = dp->peercontext;
2190                 else
2191                         pc++;
2192                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2193                         if (dp->waiters[x] > -1)
2194                                 y++;
2195                 if (s > 0)
2196                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2197                 else
2198                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2199                 dp = dp->next;
2200         }
2201         ast_mutex_unlock(&dpcache_lock);
2202         return RESULT_SUCCESS;
2203 }
2204
2205 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2206
2207 #ifdef BRIDGE_OPTIMIZATION
2208 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2209
2210 static int forward_delivery(struct iax_frame *fr)
2211 {
2212         struct chan_iax2_pvt *p1, *p2;
2213         char iabuf[INET_ADDRSTRLEN];
2214         int res, orig_ts;
2215
2216         p1 = iaxs[fr->callno];
2217         p2 = iaxs[p1->bridgecallno];
2218         if (!p1)
2219                 return -1;
2220         if (!p2)
2221                 return -1;
2222
2223         if (option_debug)
2224                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2225                                 fr->ts,
2226                                 p1->callno, p1->peercallno,
2227                                 p2->callno, p2->peercallno,
2228                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2229                                 ntohs(p2->addr.sin_port));
2230
2231         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2232            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2233            send full frame on timestamp wrap when doing optimized bridging
2234            (actually current code STILL doesn't)
2235         */
2236         if (fr->ts + 50000 <= p1->last) {
2237                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2238                 if (option_debug)
2239                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2240         }
2241
2242         /* Send with timestamp adjusted to the origin of the outbound leg */
2243         /* But don't destroy inbound timestamp still needed later to set "last" */
2244         orig_ts = fr->ts;
2245         fr->ts = calc_fakestamp(p1, p2, fr->ts);
2246         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2247         fr->ts = orig_ts;
2248         return res;
2249 }
2250 #endif
2251
2252 static void unwrap_timestamp(struct iax_frame *fr)
2253 {
2254         int x;
2255
2256         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2257                 x = fr->ts - iaxs[fr->callno]->last;
2258                 if (x < -50000) {
2259                         /* Sudden big jump backwards in timestamp:
2260                            What likely happened here is that miniframe timestamp has circled but we haven't
2261                            gotten the update from the main packet.  We'll just pretend that we did, and
2262                            update the timestamp appropriately. */
2263                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2264                         if (option_debug && iaxdebug)
2265                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2266                 }
2267                 if (x > 50000) {
2268                         /* Sudden apparent big jump forwards in timestamp:
2269                            What's likely happened is this is an old miniframe belonging to the previous
2270                            top-16-bit timestamp that has turned up out of order.
2271                            Adjust the timestamp appropriately. */
2272                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2273                         if (option_debug && iaxdebug)
2274                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2275                 }
2276         }
2277 }
2278
2279 #ifdef NEWJB
2280 static int get_from_jb(void *p);
2281
2282 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2283     int when;
2284
2285     when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2286
2287     /*    fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2288
2289     when = jb_next(pvt->jb) - when;
2290     /*   fprintf(stderr, "when = %d\n", when); */
2291
2292     if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2293
2294     if(when <= 0) {
2295       /* XXX should really just empty until when > 0.. */
2296       when = 1;
2297     }
2298
2299     pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2300
2301     /* Signal scheduler thread */
2302     signal_condition(&sched_lock, &sched_cond);
2303 }
2304
2305 static void __get_from_jb(void *p) 
2306 {
2307         /* make sure pvt is valid! */   
2308     struct chan_iax2_pvt *pvt = p;
2309     struct iax_frame *fr;
2310     jb_frame frame;
2311     int ret;
2312     long now;
2313     long next;
2314     struct timeval tv;
2315
2316     ast_mutex_lock(&iaxsl[pvt->callno]);
2317     /*  fprintf(stderr, "get_from_jb called\n"); */
2318     pvt->jbid = -1;
2319
2320     gettimeofday(&tv,NULL);
2321     /* round up a millisecond since ast_sched_runq does; */
2322     /* prevents us from spinning while waiting for our now */
2323     /* to catch up with runq's now */
2324     tv.tv_usec += 1000;
2325
2326     now = ast_tvdiff_ms(tv, pvt->rxcore);
2327
2328     if(now >= (next = jb_next(pvt->jb))) {
2329                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2330                 switch(ret) {
2331                 case JB_OK:
2332                         /*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); */
2333                         fr = frame.data;
2334                         __do_deliver(fr);
2335                     break;
2336                 case JB_INTERP:
2337                     {
2338                         struct ast_frame af;
2339         
2340                         /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2341         
2342                         /* create an interpolation frame */
2343                         /*fprintf(stderr, "Making Interpolation frame\n"); */
2344                         af.frametype = AST_FRAME_VOICE;
2345                         af.subclass = pvt->voiceformat;
2346                         af.datalen  = 0;
2347                         af.samples  = frame.ms * 8;
2348                         af.mallocd  = 0;
2349                         af.src  = "IAX2 JB interpolation";
2350                         af.data  = NULL;
2351                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2352                         af.offset=AST_FRIENDLY_OFFSET;
2353         
2354                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2355                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2356                         if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2357                                 iax2_queue_frame(pvt->callno, &af);
2358                     }
2359                     break;
2360                 case JB_DROP:
2361                         /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2362                         iax2_frame_free(frame.data);
2363                     break;
2364                 case JB_NOFRAME:
2365                 case JB_EMPTY:
2366                         /* do nothing */
2367                     break;
2368                 default:
2369                         /* shouldn't happen */
2370                     break;
2371                 }
2372     }
2373     update_jbsched(pvt);
2374     ast_mutex_unlock(&iaxsl[pvt->callno]);
2375 }
2376
2377 static int get_from_jb(void *data)
2378 {
2379 #ifdef SCHED_MULTITHREADED
2380         if (schedule_action(__get_from_jb, data))
2381 #endif          
2382                 __get_from_jb(data);
2383         return 0;
2384 }
2385 #endif
2386
2387 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or 
2388  * make preprocessor swiss-cheese out of this one.  I'm not sure which is less revolting.. */
2389 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2390 {
2391 #ifdef NEWJB
2392         int type, len;
2393         int ret;
2394         int needfree = 0;
2395 #else
2396         int x;
2397         int ms;
2398         int delay;
2399         unsigned int orig_ts;
2400         int drops[MEMORY_SIZE];
2401         int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2402
2403         /* Remember current jitterbuffer so we can log any change */
2404         prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2405         /* Similarly for the frame timestamp */
2406         orig_ts = fr->ts;
2407 #endif
2408
2409 #if 0
2410         if (option_debug && iaxdebug)
2411                 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2412                                 fr->ts, iaxs[fr->callno]->last, updatehistory);
2413 #endif
2414
2415         /* Attempt to recover wrapped timestamps */
2416         unwrap_timestamp(fr);
2417         
2418         if (updatehistory) {
2419 #ifndef NEWJB
2420
2421                 /* Attempt to spot a change of timebase on timestamps coming from the other side
2422                    We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2423                    by network jitter or reordering.  Sometimes, also, the peer stops sending us frames
2424                    for a while - in this case this code might also resync us.  But that's not a bad thing.
2425                    Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2426                    [that's why we only do this when updatehistory is true]
2427                 */
2428                 x = fr->ts - iaxs[fr->callno]->last;
2429                 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2430                         if (option_debug && iaxdebug)
2431                                 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped.  resyncing rxcore (ts=%d, last=%d)\n",
2432                                                         fr->callno, fr->ts, iaxs[fr->callno]->last);
2433                         /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2434                         iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2435                         /* wipe "last" if stamps have jumped backwards */
2436                         if (x<0)
2437                                 iaxs[fr->callno]->last = 0;
2438                         /* should we also empty history? */
2439                 }
2440                 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2441                    frame we received.  (initially the very first, but also see code just above here).
2442                    Understand that "ms" can easily be -ve if lag improves since the reference frame.
2443                    Called by IAX thread, with iaxsl lock held. */
2444                 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2445         
2446                 /* Rotate our history queue of "lateness".  Don't worry about those initial
2447                    zeros because the first entry will always be zero */
2448                 for (x=0;x<MEMORY_SIZE - 1;x++) 
2449                         iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2450                 /* Add a history entry for this one */
2451                 iaxs[fr->callno]->history[x] = ms;
2452 #endif
2453         }
2454 #ifndef NEWJB
2455         else
2456                 ms = 0;
2457 #endif
2458
2459
2460         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2461         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2462                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2463         else {
2464 #if 0
2465                 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2466 #endif
2467                 fr->af.delivery = ast_tv(0,0);
2468         }
2469
2470 #ifndef NEWJB
2471         /* Initialize the minimum to reasonable values.  It's too much
2472            work to do the same for the maximum, repeatedly */
2473         min=iaxs[fr->callno]->history[0];
2474         for (z=0;z < iax2_dropcount + 1;z++) {
2475                 /* Start very optimistic ;-) */
2476                 max=-999999999;
2477                 for (x=0;x<MEMORY_SIZE;x++) {
2478                         if (max < iaxs[fr->callno]->history[x]) {
2479                                 /* We have a candidate new maximum value.  Make
2480                                    sure it's not in our drop list */
2481                                 match = 0;
2482                                 for (y=0;!match && (y<z);y++)
2483                                         match |= (drops[y] == x);
2484                                 if (!match) {
2485                                         /* It's not in our list, use it as the new maximum */
2486                                         max = iaxs[fr->callno]->history[x];
2487                                         maxone = x;
2488                                 }
2489                                 
2490                         }
2491                         if (!z) {
2492                                 /* On our first pass, find the minimum too */
2493                                 if (min > iaxs[fr->callno]->history[x])
2494                                         min = iaxs[fr->callno]->history[x];
2495                         }
2496                 }
2497 #if 1
2498                 drops[z] = maxone;
2499 #endif
2500         }
2501 #endif
2502
2503 #ifdef NEWJB
2504         type = JB_TYPE_CONTROL;
2505         len = 0;
2506
2507         if(fr->af.frametype == AST_FRAME_VOICE) {
2508                 type = JB_TYPE_VOICE;
2509                 len = ast_codec_get_samples(&fr->af) / 8;
2510         } else if(fr->af.frametype == AST_FRAME_CNG) {
2511                 type = JB_TYPE_SILENCE;
2512         }
2513
2514         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2515                 if (tsout)
2516                         *tsout = fr->ts;
2517                 __do_deliver(fr);
2518                 return -1;
2519         }
2520
2521         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2522          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2523         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2524             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2525             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2526                 jb_frame frame;
2527
2528                 /* deliver any frames in the jb */
2529                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2530                         __do_deliver(frame.data);
2531
2532                 jb_reset(iaxs[fr->callno]->jb);
2533
2534                 if (iaxs[fr->callno]->jbid > -1)
2535                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2536
2537                 iaxs[fr->callno]->jbid = -1;
2538
2539                 /* deliver this frame now */
2540                 if (tsout)
2541                         *tsout = fr->ts;
2542                 __do_deliver(fr);
2543                 return -1;
2544
2545         }
2546
2547
2548         /* insert into jitterbuffer */
2549         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2550         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2551                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2552         if (ret == JB_DROP) {
2553                 needfree++;
2554         } else if (ret == JB_SCHED) {
2555                 update_jbsched(iaxs[fr->callno]);
2556         }
2557 #else
2558         /* Just for reference, keep the "jitter" value, the difference between the
2559            earliest and the latest. */
2560         if (max >= min)
2561                 iaxs[fr->callno]->jitter = max - min;   
2562         
2563         /* IIR filter for keeping track of historic jitter, but always increase
2564            historic jitter immediately for increase */
2565         
2566         if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2567                 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2568         else
2569                 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) * 
2570                         iaxs[fr->callno]->historicjitter;
2571
2572         /* If our jitter buffer is too big (by a significant margin), then we slowly
2573            shrink it to avoid letting the change be perceived */
2574         if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2575                 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2576
2577         /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2578         /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2579            in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2580            disruption.  Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2581         if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2582                 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2583
2584         /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2585            buffer immediately to accomodate it (and a little more).  */
2586         if (max > iaxs[fr->callno]->jitterbuffer)
2587                 iaxs[fr->callno]->jitterbuffer = max 
2588                         /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2589
2590         /* update "min", just for RRs and stats */
2591         iaxs[fr->callno]->min = min; 
2592
2593         /* Subtract the lateness from our jitter buffer to know how long to wait
2594            before sending our packet.  */
2595         delay = iaxs[fr->callno]->jitterbuffer - ms;
2596
2597         /* Whatever happens, no frame waits longer than maxjitterbuffer */
2598         if (delay > maxjitterbuffer)
2599                 delay = maxjitterbuffer;
2600         
2601         /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2602         /* If frame came from trunk, also don't do any delay */
2603         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2604                 delay = 0;
2605
2606         if (option_debug && iaxdebug) {
2607                 /* Log jitter stats for possible offline analysis */
2608                 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",
2609                                         fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2610                                         (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2611                                         min, max, iaxs[fr->callno]->jitterbuffer,
2612                                         iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2613                                         ms, delay,
2614                                         iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2615         }
2616
2617         if (delay < 1) {
2618                 /* Don't deliver it more than 4 ms late */
2619                 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2620                         if (option_debug && iaxdebug)
2621                                 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2622                         if (tsout)
2623                                 *tsout = fr->ts;
2624                         __do_deliver(fr);
2625                         return -1;
2626                 } else {
2627                         if (option_debug && iaxdebug)
2628                                 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2629                         iaxs[fr->callno]->frames_dropped++;
2630                         needfree++;
2631                 }
2632         } else {
2633                 if (option_debug && iaxdebug)
2634                         ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2635                 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2636                 signal_condition(&sched_lock, &sched_cond);
2637         }
2638 #endif
2639         if (tsout)
2640                 *tsout = fr->ts;
2641         if (needfree) {
2642                 /* Free our iax frame */
2643                 iax2_frame_free(fr);
2644                 return -1;
2645         }
2646         return 0;
2647 }
2648
2649 static int iax2_transmit(struct iax_frame *fr)
2650 {
2651         /* Lock the queue and place this packet at the end */
2652         fr->next = NULL;
2653         fr->prev = NULL;
2654         /* By setting this to 0, the network thread will send it for us, and
2655            queue retransmission if necessary */
2656         fr->sentyet = 0;
2657         ast_mutex_lock(&iaxq.lock);
2658         if (!iaxq.head) {
2659                 /* Empty queue */
2660                 iaxq.head = fr;
2661                 iaxq.tail = fr;
2662         } else {
2663                 /* Double link */
2664                 iaxq.tail->next = fr;
2665                 fr->prev = iaxq.tail;
2666                 iaxq.tail = fr;
2667         }
2668         iaxq.count++;
2669         ast_mutex_unlock(&iaxq.lock);
2670         /* Wake up the network and scheduler thread */
2671         pthread_kill(netthreadid, SIGURG);
2672         signal_condition(&sched_lock, &sched_cond);
2673         return 0;
2674 }
2675
2676
2677
2678 static int iax2_digit(struct ast_channel *c, char digit)
2679 {
2680         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2681 }
2682
2683 static int iax2_sendtext(struct ast_channel *c, const char *text)
2684 {
2685         
2686         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2687                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2688 }
2689
2690 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2691 {
2692         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2693 }
2694
2695 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2696 {
2697         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2698 }
2699
2700 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2701 {
2702         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2703         ast_mutex_lock(&iaxsl[callno]);
2704         if (iaxs[callno])
2705                 iaxs[callno]->owner = newchan;
2706         else
2707                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2708         ast_mutex_unlock(&iaxsl[callno]);
2709         return 0;
2710 }
2711
2712 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2713 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2714
2715 static void destroy_user(struct iax2_user *user);
2716 static int expire_registry(void *data);
2717
2718 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2719 {
2720         struct ast_variable *var;
2721         struct ast_variable *tmp;
2722         struct iax2_peer *peer=NULL;
2723         time_t regseconds = 0, nowtime;
2724         int dynamic=0;
2725
2726         if (peername)
2727                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2728         else {
2729                 char iabuf[INET_ADDRSTRLEN];
2730                 char porta[25];
2731                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2732                 sprintf(porta, "%d", ntohs(sin->sin_port));
2733                 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2734                 if (var) {
2735                         /* We'll need the peer name in order to build the structure! */
2736                         tmp = var;
2737                         while(tmp) {
2738                                 if (!strcasecmp(tmp->name, "name"))
2739                                         peername = tmp->value;
2740                                 tmp = tmp->next;
2741                         }
2742                 }
2743         }
2744         if (!var)
2745                 return NULL;
2746
2747         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2748         
2749         if (!peer)
2750                 return NULL;
2751
2752         tmp = var;
2753         while(tmp) {
2754                 /* Make sure it's not a user only... */
2755                 if (!strcasecmp(tmp->name, "type")) {
2756                         if (strcasecmp(tmp->value, "friend") &&
2757                             strcasecmp(tmp->value, "peer")) {
2758                                 /* Whoops, we weren't supposed to exist! */
2759                                 destroy_peer(peer);
2760                                 peer = NULL;
2761                                 break;
2762                         } 
2763                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2764                         ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2765                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2766                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2767                 } else if (!strcasecmp(tmp->name, "port")) {
2768                         peer->addr.sin_port = htons(atoi(tmp->value));
2769                 } else if (!strcasecmp(tmp->name, "host")) {
2770                         if (!strcasecmp(tmp->value, "dynamic"))
2771                                 dynamic = 1;
2772                 }
2773                 tmp = tmp->next;
2774         }
2775         if (!peer)
2776                 return NULL;
2777
2778         ast_variables_destroy(var);
2779
2780         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2781                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2782                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2783                         if (peer->expire > -1)
2784                                 ast_sched_del(sched, peer->expire);
2785                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2786                 }
2787                 ast_mutex_lock(&peerl.lock);
2788                 peer->next = peerl.peers;
2789                 peerl.peers = peer;
2790                 ast_mutex_unlock(&peerl.lock);
2791                 if (ast_test_flag(peer, IAX_DYNAMIC))
2792                         reg_source_db(peer);
2793         } else {
2794                 ast_set_flag(peer, IAX_TEMPONLY);       
2795         }
2796
2797         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2798                 time(&nowtime);
2799                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2800                         memset(&peer->addr, 0, sizeof(peer->addr));
2801                         if (option_debug)
2802                                 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2803                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2804                 }
2805                 else {
2806                         if (option_debug)
2807                                 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2808                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2809                 }
2810         }
2811
2812         return peer;
2813 }
2814
2815 static struct iax2_user *realtime_user(const char *username)
2816 {
2817         struct ast_variable *var;
2818         struct ast_variable *tmp;
2819         struct iax2_user *user=NULL;
2820
2821         var = ast_load_realtime("iaxusers", "name", username, NULL);
2822         if (!var)
2823                 return NULL;
2824
2825         tmp = var;
2826         while(tmp) {
2827                 /* Make sure it's not a peer only... */
2828                 if (!strcasecmp(tmp->name, "type")) {
2829                         if (strcasecmp(tmp->value, "friend") &&
2830                             strcasecmp(tmp->value, "user")) {
2831                                 return NULL;
2832                         } 
2833                 }
2834                 tmp = tmp->next;
2835         }
2836
2837         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2838         if (!user)
2839                 return NULL;
2840
2841         ast_variables_destroy(var);
2842
2843         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2844                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2845                 ast_mutex_lock(&userl.lock);
2846                 user->next = userl.users;
2847                 userl.users = user;
2848                 ast_mutex_unlock(&userl.lock);
2849         } else {
2850                 ast_set_flag(user, IAX_TEMPONLY);       
2851         }
2852
2853         return user;
2854 }
2855
2856 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2857 {
2858         char port[10];
2859         char ipaddr[20];
2860         char regseconds[20];
2861         time_t nowtime;
2862         
2863         time(&nowtime);
2864         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
2865         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2866         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2867         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2868 }
2869
2870 struct create_addr_info {
2871         int capability;
2872         unsigned int flags;
2873         int maxtime;
2874         int encmethods;
2875         int found;
2876         int sockfd;
2877         char username[80];
2878         char secret[80];
2879         char outkey[80];
2880         char timezone[80];
2881         char prefs[32];
2882         char context[AST_MAX_CONTEXT];
2883         char peercontext[AST_MAX_CONTEXT];
2884 };
2885
2886 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2887 {
2888         struct ast_hostent ahp;
2889         struct hostent *hp;
2890         struct iax2_peer *peer;
2891
2892         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2893         cai->sockfd = defaultsockfd;
2894         cai->maxtime = 0;
2895         sin->sin_family = AF_INET;
2896
2897         if (!(peer = find_peer(peername, 1))) {
2898                 cai->found = 0;
2899
2900                 hp = ast_gethostbyname(peername, &ahp);
2901                 if (hp) {
2902                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2903                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2904                         /* use global iax prefs for unknown peer/user */
2905                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2906                         return 0;
2907                 } else {
2908                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2909                         return -1;
2910                 }
2911         }
2912
2913         cai->found = 1;
2914         
2915         /* if the peer has no address (current or default), return failure */
2916         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2917                 if (ast_test_flag(peer, IAX_TEMPONLY))
2918                         destroy_peer(peer);
2919                 return -1;
2920         }
2921
2922         /* if the peer is being monitored and is currently unreachable, return failure */
2923         if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2924                 if (ast_test_flag(peer, IAX_TEMPONLY))
2925                         destroy_peer(peer);
2926                 return -1;
2927         }
2928
2929         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2930         cai->maxtime = peer->maxms;
2931         cai->capability = peer->capability;
2932         cai->encmethods = peer->encmethods;
2933         cai->sockfd = peer->sockfd;
2934         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2935         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2936         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2937         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2938         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2939         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2940         if (ast_strlen_zero(peer->dbsecret)) {
2941                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2942         } else {
2943                 char *family;
2944                 char *key = NULL;
2945
2946                 family = ast_strdupa(peer->dbsecret);
2947                 if (family) {
2948                         key = strchr(family, '/');
2949                         if (key)
2950                                 *key++ = '\0';
2951                 }
2952                 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2953                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2954                         if (ast_test_flag(peer, IAX_TEMPONLY))
2955                                 destroy_peer(peer);
2956                         return -1;
2957                 }
2958         }
2959
2960         if (peer->addr.sin_addr.s_addr) {
2961                 sin->sin_addr = peer->addr.sin_addr;
2962                 sin->sin_port = peer->addr.sin_port;
2963         } else {
2964                 sin->sin_addr = peer->defaddr.sin_addr;
2965                 sin->sin_port = peer->defaddr.sin_port;
2966         }
2967
2968         if (ast_test_flag(peer, IAX_TEMPONLY))
2969                 destroy_peer(peer);
2970
2971         return 0;
2972 }
2973
2974 static void __auto_congest(void *nothing)
2975 {
2976         int callno = PTR_TO_CALLNO(nothing);
2977         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2978         ast_mutex_lock(&iaxsl[callno]);
2979         if (iaxs[callno]) {
2980                 iaxs[callno]->initid = -1;
2981                 iax2_queue_frame(callno, &f);
2982                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2983         }
2984         ast_mutex_unlock(&iaxsl[callno]);
2985 }
2986
2987 static int auto_congest(void *data)
2988 {
2989 #ifdef SCHED_MULTITHREADED
2990         if (schedule_action(__auto_congest, data))
2991 #endif          
2992                 __auto_congest(data);
2993         return 0;
2994 }
2995
2996 static unsigned int iax2_datetime(char *tz)
2997 {
2998         time_t t;
2999         struct tm tm;
3000         unsigned int tmp;
3001         time(&t);
3002         localtime_r(&t, &tm);
3003         if (!ast_strlen_zero(tz))
3004                 ast_localtime(&t, &tm, tz);
3005         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
3006         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
3007         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
3008         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
3009         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
3010         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
3011         return tmp;
3012 }
3013
3014 struct parsed_dial_string {
3015         char *username;
3016         char *password;
3017         char *key;
3018         char *peer;
3019         char *port;
3020         char *exten;
3021         char *context;
3022         char *options;
3023 };
3024
3025 /*!
3026  * \brief Parses an IAX dial string into its component parts.
3027  * \param data the string to be parsed
3028  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3029  * \return nothing
3030  *
3031  * This function parses the string and fills the structure
3032  * with pointers to its component parts. The input string
3033  * will be modified.
3034  *
3035  * \note This function supports both plaintext passwords and RSA
3036  * key names; if the password string is formatted as '[keyname]',
3037  * then the keyname will be placed into the key field, and the
3038  * password field will be set to NULL.
3039  *
3040  * \note The dial string format is:
3041  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
3042  */
3043 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3044 {
3045         if (ast_strlen_zero(data))
3046                 return;
3047
3048         pds->peer = strsep(&data, "/");
3049         pds->exten = strsep(&data, "/");
3050         pds->options = data;
3051
3052         if (pds->exten) {
3053                 data = pds->exten;
3054                 pds->exten = strsep(&data, "@");
3055                 pds->context = data;
3056         }
3057
3058         if (strchr(pds->peer, '@')) {
3059                 data = pds->peer;
3060                 pds->username = strsep(&data, "@");
3061                 pds->peer = data;
3062         }
3063
3064         if (pds->username) {
3065                 data = pds->username;
3066                 pds->username = strsep(&data, ":");
3067                 pds->password = data;
3068         }
3069
3070         data = pds->peer;
3071         pds->peer = strsep(&data, ":");
3072         pds->port = data;
3073
3074         /* check for a key name wrapped in [] in the secret position, if found,
3075            move it to the key field instead
3076         */
3077         if (pds->password && (pds->password[0] == '[')) {
3078                 pds->key = ast_strip_quoted(pds->password, "[", "]");
3079                 pds->password = NULL;
3080         }
3081 }
3082
3083 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3084 {
3085         struct sockaddr_in sin;
3086         char *l=NULL, *n=NULL, *tmpstr;
3087         struct iax_ie_data ied;
3088         char *defaultrdest = "s";
3089         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3090         struct parsed_dial_string pds;
3091         struct create_addr_info cai;
3092
3093         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3094                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3095                 return -1;
3096         }
3097
3098         memset(&cai, 0, sizeof(cai));
3099         cai.encmethods = iax2_encryption;
3100
3101         memset(&pds, 0, sizeof(pds));
3102         tmpstr = ast_strdupa(dest);
3103         parse_dial_string(tmpstr, &pds);
3104
3105         if (!pds.exten)
3106                 pds.exten = defaultrdest;
3107
3108         if (create_addr(pds.peer, &sin, &cai)) {
3109                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3110                 return -1;
3111         }
3112
3113         if (!pds.username && !ast_strlen_zero(cai.username))
3114                 pds.username = cai.username;
3115         if (!pds.password && !ast_strlen_zero(cai.secret))
3116                 pds.password = cai.secret;
3117         if (!pds.key && !ast_strlen_zero(cai.outkey))
3118                 pds.key = cai.outkey;
3119         if (!pds.context && !ast_strlen_zero(cai.peercontext))
3120                 pds.context = cai.peercontext;
3121
3122         /* Keep track of the context for outgoing calls too */
3123         ast_copy_string(c->context, cai.context, sizeof(c->context));
3124
3125         if (pds.port)
3126                 sin.sin_port = htons(atoi(pds.port));
3127
3128         l = c->cid.cid_num;
3129         n = c->cid.cid_name;
3130
3131         /* Now build request */ 
3132         memset(&ied, 0, sizeof(ied));
3133
3134         /* On new call, first IE MUST be IAX version of caller */
3135         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3136         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3137         if (pds.options && strchr(pds.options, 'a')) {
3138                 /* Request auto answer */
3139                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3140         }
3141
3142         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3143
3144         if (l) {
3145                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3146                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3147         } else {
3148                 if (n)
3149                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3150                 else
3151                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3152         }
3153
3154         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3155         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3156
3157         if (n)
3158                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3159         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3160