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