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