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