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