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