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