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