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