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