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