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