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