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