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