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