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