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