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