Merged revisions 42086 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 destroy_user(struct iax2_user *user);
804 static void prune_peers(void);
805
806 static const struct ast_channel_tech iax2_tech = {
807         .type = "IAX2",
808         .description = tdesc,
809         .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
810         .properties = AST_CHAN_TP_WANTSJITTER,
811         .requester = iax2_request,
812         .devicestate = iax2_devicestate,
813         .send_digit_begin = iax2_digit_begin,
814         .send_digit_end = iax2_digit_end,
815         .send_text = iax2_sendtext,
816         .send_image = iax2_sendimage,
817         .send_html = iax2_sendhtml,
818         .call = iax2_call,
819         .hangup = iax2_hangup,
820         .answer = iax2_answer,
821         .read = iax2_read,
822         .write = iax2_write,
823         .write_video = iax2_write,
824         .indicate = iax2_indicate,
825         .setoption = iax2_setoption,
826         .bridge = iax2_bridge,
827         .transfer = iax2_transfer,
828         .fixup = iax2_fixup,
829 };
830
831 static struct iax2_thread *find_idle_thread(void)
832 {
833         struct iax2_thread *thread = NULL;
834
835         /* Pop the head of the list off */
836         AST_LIST_LOCK(&idle_list);
837         thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
838         AST_LIST_UNLOCK(&idle_list);
839
840         /* If no idle thread is available from the regular list, try dynamic */
841         if (thread == NULL) {
842                 AST_LIST_LOCK(&dynamic_list);
843                 thread = AST_LIST_FIRST(&dynamic_list);
844                 if (thread != NULL) {
845                         AST_LIST_REMOVE(&dynamic_list, thread, list);
846                 }
847                 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
848                 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
849                         /* We need to MAKE a thread! */
850                         thread = ast_calloc(1, sizeof(*thread));
851                         if (thread != NULL) {
852                                 thread->threadnum = iaxdynamicthreadcount;
853                                 thread->type = IAX_TYPE_DYNAMIC;
854                                 ast_mutex_init(&thread->lock);
855                                 ast_cond_init(&thread->cond, NULL);
856                                 if (ast_pthread_create(&thread->threadid, NULL, iax2_process_thread, thread)) {
857                                         free(thread);
858                                         thread = NULL;
859                                 } else {
860                                         /* All went well and the thread is up, so increment our count */
861                                         iaxdynamicthreadcount++;
862                                 }
863                         }
864                 }
865                 AST_LIST_UNLOCK(&dynamic_list);
866         }
867
868         return thread;
869 }
870
871 #ifdef SCHED_MULTITHREADED
872 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
873 {
874         struct iax2_thread *thread = NULL;
875         static time_t lasterror;
876         static time_t t;
877
878         thread = find_idle_thread();
879
880         if (thread != NULL) {
881                 thread->schedfunc = func;
882                 thread->scheddata = data;
883                 thread->iostate = IAX_IOSTATE_SCHEDREADY;
884 #ifdef DEBUG_SCHED_MULTITHREAD
885                 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
886 #endif
887                 signal_condition(&thread->lock, &thread->cond);
888                 return 0;
889         }
890         time(&t);
891         if (t != lasterror) 
892                 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
893         lasterror = t;
894
895         return -1;
896 }
897 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
898 #endif
899
900 static void __send_ping(void *data)
901 {
902         int callno = (long)data;
903         send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
904 }
905
906 static int send_ping(void *data)
907 {
908         int callno = (long)data;
909         if (iaxs[callno]) {
910 #ifdef SCHED_MULTITHREADED
911                 if (schedule_action(__send_ping, data))
912 #endif          
913                         __send_ping(data);
914                 return 1;
915         } else
916                 return 0;
917         return 0;
918 }
919
920 static int get_encrypt_methods(const char *s)
921 {
922         int e;
923         if (!strcasecmp(s, "aes128"))
924                 e = IAX_ENCRYPT_AES128;
925         else if (ast_true(s))
926                 e = IAX_ENCRYPT_AES128;
927         else
928                 e = 0;
929         return e;
930 }
931
932 static void __send_lagrq(void *data)
933 {
934         int callno = (long)data;
935         /* Ping only if it's real not if it's bridged */
936         send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
937 }
938
939 static int send_lagrq(void *data)
940 {
941         int callno = (long)data;
942         if (iaxs[callno]) {
943 #ifdef SCHED_MULTITHREADED
944                 if (schedule_action(__send_lagrq, data))
945 #endif          
946                         __send_lagrq(data);
947                 return 1;
948         } else
949                 return 0;
950         return 0;
951 }
952
953 static unsigned char compress_subclass(int subclass)
954 {
955         int x;
956         int power=-1;
957         /* If it's 128 or smaller, just return it */
958         if (subclass < IAX_FLAG_SC_LOG)
959                 return subclass;
960         /* Otherwise find its power */
961         for (x = 0; x < IAX_MAX_SHIFT; x++) {
962                 if (subclass & (1 << x)) {
963                         if (power > -1) {
964                                 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
965                                 return 0;
966                         } else
967                                 power = x;
968                 }
969         }
970         return power | IAX_FLAG_SC_LOG;
971 }
972
973 static int uncompress_subclass(unsigned char csub)
974 {
975         /* If the SC_LOG flag is set, return 2^csub otherwise csub */
976         if (csub & IAX_FLAG_SC_LOG) {
977                 /* special case for 'compressed' -1 */
978                 if (csub == 0xff)
979                         return -1;
980                 else
981                         return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
982         }
983         else
984                 return csub;
985 }
986
987 static struct iax2_peer *find_peer(const char *name, int realtime) 
988 {
989         struct iax2_peer *peer = NULL;
990
991         /* Grab peer from linked list */
992         AST_LIST_LOCK(&peers);
993         AST_LIST_TRAVERSE(&peers, peer, entry) {
994                 if (!strcasecmp(peer->name, name)) {
995                         break;
996                 }
997         }
998         AST_LIST_UNLOCK(&peers);
999
1000         /* Now go for realtime if applicable */
1001         if(!peer && realtime)
1002                 peer = realtime_peer(name, NULL);
1003         return peer;
1004 }
1005
1006 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1007 {
1008         struct iax2_peer *peer = NULL;
1009         int res = 0;
1010
1011         if (lockpeer)
1012                 AST_LIST_LOCK(&peers);
1013         AST_LIST_TRAVERSE(&peers, peer, entry) {
1014                 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1015                     (peer->addr.sin_port == sin.sin_port)) {
1016                         ast_copy_string(host, peer->name, len);
1017                         res = 1;
1018                         break;
1019                 }
1020         }
1021         if (lockpeer)
1022                 AST_LIST_UNLOCK(&peers);
1023         if (!peer) {
1024                 peer = realtime_peer(NULL, &sin);
1025                 if (peer) {
1026                         ast_copy_string(host, peer->name, len);
1027                         if (ast_test_flag(peer, IAX_TEMPONLY))
1028                                 destroy_peer(peer);
1029                         res = 1;
1030                 }
1031         }
1032
1033         return res;
1034 }
1035
1036 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1037 {
1038         struct chan_iax2_pvt *tmp;
1039         jb_conf jbconf;
1040
1041         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1042                 return NULL;
1043
1044         if (ast_string_field_init(tmp, 32)) {
1045                 free(tmp);
1046                 tmp = NULL;
1047                 return NULL;
1048         }
1049                 
1050         tmp->prefs = prefs;
1051         tmp->callno = 0;
1052         tmp->peercallno = 0;
1053         tmp->transfercallno = 0;
1054         tmp->bridgecallno = 0;
1055         tmp->pingid = -1;
1056         tmp->lagid = -1;
1057         tmp->autoid = -1;
1058         tmp->authid = -1;
1059         tmp->initid = -1;
1060
1061         ast_string_field_set(tmp,exten, "s");
1062         ast_string_field_set(tmp,host, host);
1063
1064         tmp->jb = jb_new();
1065         tmp->jbid = -1;
1066         jbconf.max_jitterbuf = maxjitterbuffer;
1067         jbconf.resync_threshold = resyncthreshold;
1068         jbconf.max_contig_interp = maxjitterinterps;
1069         jb_setconf(tmp->jb,&jbconf);
1070
1071         return tmp;
1072 }
1073
1074 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1075 {
1076         struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1077         if (new) {
1078                 size_t mallocd_datalen = new->mallocd_datalen;
1079                 memcpy(new, fr, sizeof(*new));
1080                 iax_frame_wrap(new, &fr->af);
1081                 new->mallocd_datalen = mallocd_datalen;
1082                 new->data = NULL;
1083                 new->datalen = 0;
1084                 new->direction = DIRECTION_INGRESS;
1085                 new->retrans = -1;
1086         }
1087         return new;
1088 }
1089
1090 #define NEW_PREVENT     0
1091 #define NEW_ALLOW       1
1092 #define NEW_FORCE       2
1093
1094 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1095 {
1096         if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1097                 (cur->addr.sin_port == sin->sin_port)) {
1098                 /* This is the main host */
1099                 if ((cur->peercallno == callno) ||
1100                         ((dcallno == cur->callno) && !cur->peercallno)) {
1101                         /* That's us.  Be sure we keep track of the peer call number */
1102                         return 1;
1103                 }
1104         }
1105         if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1106             (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1107                 /* We're transferring */
1108                 if (dcallno == cur->callno)
1109                         return 1;
1110         }
1111         return 0;
1112 }
1113
1114 static void update_max_trunk(void)
1115 {
1116         int max = TRUNK_CALL_START;
1117         int x;
1118         /* XXX Prolly don't need locks here XXX */
1119         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1120                 if (iaxs[x])
1121                         max = x + 1;
1122         }
1123         maxtrunkcall = max;
1124         if (option_debug && iaxdebug)
1125                 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1126 }
1127
1128 static void update_max_nontrunk(void)
1129 {
1130         int max = 1;
1131         int x;
1132         /* XXX Prolly don't need locks here XXX */
1133         for (x=1;x<TRUNK_CALL_START - 1; x++) {
1134                 if (iaxs[x])
1135                         max = x + 1;
1136         }
1137         maxnontrunkcall = max;
1138         if (option_debug && iaxdebug)
1139                 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1140 }
1141
1142 static int make_trunk(unsigned short callno, int locked)
1143 {
1144         int x;
1145         int res= 0;
1146         struct timeval now;
1147         if (iaxs[callno]->oseqno) {
1148                 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1149                 return -1;
1150         }
1151         if (callno & TRUNK_CALL_START) {
1152                 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1153                 return -1;
1154         }
1155         gettimeofday(&now, NULL);
1156         for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1157                 ast_mutex_lock(&iaxsl[x]);
1158                 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1159                         iaxs[x] = iaxs[callno];
1160                         iaxs[x]->callno = x;
1161                         iaxs[callno] = NULL;
1162                         /* Update the two timers that should have been started */
1163                         if (iaxs[x]->pingid > -1)
1164                                 ast_sched_del(sched, iaxs[x]->pingid);
1165                         if (iaxs[x]->lagid > -1)
1166                                 ast_sched_del(sched, iaxs[x]->lagid);
1167                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1168                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1169                         if (locked)
1170                                 ast_mutex_unlock(&iaxsl[callno]);
1171                         res = x;
1172                         if (!locked)
1173                                 ast_mutex_unlock(&iaxsl[x]);
1174                         break;
1175                 }
1176                 ast_mutex_unlock(&iaxsl[x]);
1177         }
1178         if (x >= IAX_MAX_CALLS - 1) {
1179                 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1180                 return -1;
1181         }
1182         ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1183         /* We move this call from a non-trunked to a trunked call */
1184         update_max_trunk();
1185         update_max_nontrunk();
1186         return res;
1187 }
1188
1189 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1190 {
1191         int res = 0;
1192         int x;
1193         struct timeval now;
1194         char host[80];
1195         if (new <= NEW_ALLOW) {
1196                 /* Look for an existing connection first */
1197                 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1198                         ast_mutex_lock(&iaxsl[x]);
1199                         if (iaxs[x]) {
1200                                 /* Look for an exact match */
1201                                 if (match(sin, callno, dcallno, iaxs[x])) {
1202                                         res = x;
1203                                 }
1204                         }
1205                         ast_mutex_unlock(&iaxsl[x]);
1206                 }
1207                 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1208                         ast_mutex_lock(&iaxsl[x]);
1209                         if (iaxs[x]) {
1210                                 /* Look for an exact match */
1211                                 if (match(sin, callno, dcallno, iaxs[x])) {
1212                                         res = x;
1213                                 }
1214                         }
1215                         ast_mutex_unlock(&iaxsl[x]);
1216                 }
1217         }
1218         if ((res < 1) && (new >= NEW_ALLOW)) {
1219                 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1220                         snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1221                 gettimeofday(&now, NULL);
1222                 for (x=1;x<TRUNK_CALL_START;x++) {
1223                         /* Find first unused call number that hasn't been used in a while */
1224                         ast_mutex_lock(&iaxsl[x]);
1225                         if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1226                         ast_mutex_unlock(&iaxsl[x]);
1227                 }
1228                 /* We've still got lock held if we found a spot */
1229                 if (x >= TRUNK_CALL_START) {
1230                         ast_log(LOG_WARNING, "No more space\n");
1231                         return 0;
1232                 }
1233                 iaxs[x] = new_iax(sin, lockpeer, host);
1234                 update_max_nontrunk();
1235                 if (iaxs[x]) {
1236                         if (option_debug && iaxdebug)
1237                                 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1238                         iaxs[x]->sockfd = sockfd;
1239                         iaxs[x]->addr.sin_port = sin->sin_port;
1240                         iaxs[x]->addr.sin_family = sin->sin_family;
1241                         iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1242                         iaxs[x]->peercallno = callno;
1243                         iaxs[x]->callno = x;
1244                         iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1245                         iaxs[x]->expiry = min_reg_expire;
1246                         iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1247                         iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1248                         iaxs[x]->amaflags = amaflags;
1249                         ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1250                         
1251                         ast_string_field_set(iaxs[x], accountcode, accountcode);
1252                         ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1253                         ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1254                 } else {
1255                         ast_log(LOG_WARNING, "Out of resources\n");
1256                         ast_mutex_unlock(&iaxsl[x]);
1257                         return 0;
1258                 }
1259                 ast_mutex_unlock(&iaxsl[x]);
1260                 res = x;
1261         }
1262         return res;
1263 }
1264
1265 static void iax2_frame_free(struct iax_frame *fr)
1266 {
1267         if (fr->retrans > -1)
1268                 ast_sched_del(sched, fr->retrans);
1269         iax_frame_free(fr);
1270 }
1271
1272 static int iax2_queue_frame(int callno, struct ast_frame *f)
1273 {
1274         /* Assumes lock for callno is already held... */
1275         for (;;) {
1276                 if (iaxs[callno] && iaxs[callno]->owner) {
1277                         if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1278                                 /* Avoid deadlock by pausing and trying again */
1279                                 ast_mutex_unlock(&iaxsl[callno]);
1280                                 usleep(1);
1281                                 ast_mutex_lock(&iaxsl[callno]);
1282                         } else {
1283                                 ast_queue_frame(iaxs[callno]->owner, f);
1284                                 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1285                                 break;
1286                         }
1287                 } else
1288                         break;
1289         }
1290         return 0;
1291 }
1292
1293 static void destroy_firmware(struct iax_firmware *cur)
1294 {
1295         /* Close firmware */
1296         if (cur->fwh) {
1297                 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1298         }
1299         close(cur->fd);
1300         free(cur);
1301 }
1302
1303 static int try_firmware(char *s)
1304 {
1305         struct stat stbuf;
1306         struct iax_firmware *cur;
1307         int ifd;
1308         int fd;
1309         int res;
1310         
1311         struct ast_iax2_firmware_header *fwh, fwh2;
1312         struct MD5Context md5;
1313         unsigned char sum[16];
1314         unsigned char buf[1024];
1315         int len, chunk;
1316         char *s2;
1317         char *last;
1318         s2 = alloca(strlen(s) + 100);
1319         if (!s2) {
1320                 ast_log(LOG_WARNING, "Alloca failed!\n");
1321                 return -1;
1322         }
1323         last = strrchr(s, '/');
1324         if (last)
1325                 last++;
1326         else
1327                 last = s;
1328         snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1329         res = stat(s, &stbuf);
1330         if (res < 0) {
1331                 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1332                 return -1;
1333         }
1334         /* Make sure it's not a directory */
1335         if (S_ISDIR(stbuf.st_mode))
1336                 return -1;
1337         ifd = open(s, O_RDONLY);
1338         if (ifd < 0) {
1339                 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1340                 return -1;
1341         }
1342         fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1343         if (fd < 0) {
1344                 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1345                 close(ifd);
1346                 return -1;
1347         }
1348         /* Unlink our newly created file */
1349         unlink(s2);
1350         
1351         /* Now copy the firmware into it */
1352         len = stbuf.st_size;
1353         while(len) {
1354                 chunk = len;
1355                 if (chunk > sizeof(buf))
1356                         chunk = sizeof(buf);
1357                 res = read(ifd, buf, chunk);
1358                 if (res != chunk) {
1359                         ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1360                         close(ifd);
1361                         close(fd);
1362                         return -1;
1363                 }
1364                 res = write(fd, buf, chunk);
1365                 if (res != chunk) {
1366                         ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1367                         close(ifd);
1368                         close(fd);
1369                         return -1;
1370                 }
1371                 len -= chunk;
1372         }
1373         close(ifd);
1374         /* Return to the beginning */
1375         lseek(fd, 0, SEEK_SET);
1376         if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1377                 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1378                 close(fd);
1379                 return -1;
1380         }
1381         if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1382                 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1383                 close(fd);
1384                 return -1;
1385         }
1386         if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1387                 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1388                 close(fd);
1389                 return -1;
1390         }
1391         if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1392                 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1393                 close(fd);
1394                 return -1;
1395         }
1396         fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1397         if (!fwh) {
1398                 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1399                 close(fd);
1400                 return -1;
1401         }
1402         MD5Init(&md5);
1403         MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1404         MD5Final(sum, &md5);
1405         if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1406                 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1407                 munmap(fwh, stbuf.st_size);
1408                 close(fd);
1409                 return -1;
1410         }
1411         cur = waresl.wares;
1412         while(cur) {
1413                 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1414                         /* Found a candidate */
1415                         if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1416                                 /* The version we have on loaded is older, load this one instead */
1417                                 break;
1418                         /* This version is no newer than what we have.  Don't worry about it.
1419                            We'll consider it a proper load anyhow though */
1420                         munmap(fwh, stbuf.st_size);
1421                         close(fd);
1422                         return 0;
1423                 }
1424                 cur = cur->next;
1425         }
1426         if (!cur) {
1427                 /* Allocate a new one and link it */
1428                 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1429                         cur->fd = -1;
1430                         cur->next = waresl.wares;
1431                         waresl.wares = cur;
1432                 }
1433         }
1434         if (cur) {
1435                 if (cur->fwh) {
1436                         munmap(cur->fwh, cur->mmaplen);
1437                 }
1438                 if (cur->fd > -1)
1439                         close(cur->fd);
1440                 cur->fwh = fwh;
1441                 cur->fd = fd;
1442                 cur->mmaplen = stbuf.st_size;
1443                 cur->dead = 0;
1444         }
1445         return 0;
1446 }
1447
1448 static int iax_check_version(char *dev)
1449 {
1450         int res = 0;
1451         struct iax_firmware *cur;
1452         if (!ast_strlen_zero(dev)) {
1453                 ast_mutex_lock(&waresl.lock);
1454                 cur = waresl.wares;
1455                 while(cur) {
1456                         if (!strcmp(dev, (char *)cur->fwh->devname)) {
1457                                 res = ntohs(cur->fwh->version);
1458                                 break;
1459                         }
1460                         cur = cur->next;
1461                 }
1462                 ast_mutex_unlock(&waresl.lock);
1463         }
1464         return res;
1465 }
1466
1467 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1468 {
1469         int res = -1;
1470         unsigned int bs = desc & 0xff;
1471         unsigned int start = (desc >> 8) & 0xffffff;
1472         unsigned int bytes;
1473         struct iax_firmware *cur;
1474         if (!ast_strlen_zero((char *)dev) && bs) {
1475                 start *= bs;
1476                 ast_mutex_lock(&waresl.lock);
1477                 cur = waresl.wares;
1478                 while(cur) {
1479                         if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1480                                 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1481                                 if (start < ntohl(cur->fwh->datalen)) {
1482                                         bytes = ntohl(cur->fwh->datalen) - start;
1483                                         if (bytes > bs)
1484                                                 bytes = bs;
1485                                         iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1486                                 } else {
1487                                         bytes = 0;
1488                                         iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1489                                 }
1490                                 if (bytes == bs)
1491                                         res = 0;
1492                                 else
1493                                         res = 1;
1494                                 break;
1495                         }
1496                         cur = cur->next;
1497                 }
1498                 ast_mutex_unlock(&waresl.lock);
1499         }
1500         return res;
1501 }
1502
1503
1504 static void reload_firmware(void)
1505 {
1506         struct iax_firmware *cur, *curl, *curp;
1507         DIR *fwd;
1508         struct dirent *de;
1509         char dir[256];
1510         char fn[256];
1511         /* Mark all as dead */
1512         ast_mutex_lock(&waresl.lock);
1513         cur = waresl.wares;
1514         while(cur) {
1515                 cur->dead = 1;
1516                 cur = cur->next;
1517         }
1518         /* Now that we've freed them, load the new ones */
1519         snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1520         fwd = opendir(dir);
1521         if (fwd) {
1522                 while((de = readdir(fwd))) {
1523                         if (de->d_name[0] != '.') {
1524                                 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1525                                 if (!try_firmware(fn)) {
1526                                         if (option_verbose > 1)
1527                                                 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1528                                 }
1529                         }
1530                 }
1531                 closedir(fwd);
1532         } else 
1533                 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1534
1535         /* Clean up leftovers */
1536         cur = waresl.wares;
1537         curp = NULL;
1538         while(cur) {
1539                 curl = cur;
1540                 cur = cur->next;
1541                 if (curl->dead) {
1542                         if (curp) {
1543                                 curp->next = cur;
1544                         } else {
1545                                 waresl.wares = cur;
1546                         }
1547                         destroy_firmware(curl);
1548                 } else {
1549                         curp = cur;
1550                 }
1551         }
1552         ast_mutex_unlock(&waresl.lock);
1553 }
1554
1555 static int __do_deliver(void *data)
1556 {
1557         /* Just deliver the packet by using queueing.  This is called by
1558           the IAX thread with the iaxsl lock held. */
1559         struct iax_frame *fr = data;
1560         fr->retrans = -1;
1561         fr->af.has_timing_info = 0;
1562         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1563                 iax2_queue_frame(fr->callno, &fr->af);
1564         /* Free our iax frame */
1565         iax2_frame_free(fr);
1566         /* And don't run again */
1567         return 0;
1568 }
1569
1570 static int handle_error(void)
1571 {
1572         /* XXX Ideally we should figure out why an error occured and then abort those
1573            rather than continuing to try.  Unfortunately, the published interface does
1574            not seem to work XXX */
1575 #if 0
1576         struct sockaddr_in *sin;
1577         int res;
1578         struct msghdr m;
1579         struct sock_extended_err e;
1580         m.msg_name = NULL;
1581         m.msg_namelen = 0;
1582         m.msg_iov = NULL;
1583         m.msg_control = &e;
1584         m.msg_controllen = sizeof(e);
1585         m.msg_flags = 0;
1586         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1587         if (res < 0)
1588                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1589         else {
1590                 if (m.msg_controllen) {
1591                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1592                         if (sin) 
1593                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1594                         else
1595                                 ast_log(LOG_WARNING, "No address detected??\n");
1596                 } else {
1597                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1598                 }
1599         }
1600 #endif
1601         return 0;
1602 }
1603
1604 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1605 {
1606         int res;
1607         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1608                                         sizeof(*sin));
1609         if (res < 0) {
1610                 if (option_debug)
1611                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1612                 handle_error();
1613         } else
1614                 res = 0;
1615         return res;
1616 }
1617
1618 static int send_packet(struct iax_frame *f)
1619 {
1620         int res;
1621         int callno = f->callno;
1622
1623         /* Don't send if there was an error, but return error instead */
1624         if (!callno || !iaxs[callno] || iaxs[callno]->error)
1625             return -1;
1626         
1627         /* Called with iaxsl held */
1628         if (option_debug > 2 && iaxdebug)
1629                 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));
1630         if (f->transfer) {
1631                 if (iaxdebug)
1632                         iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1633                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1634                                         sizeof(iaxs[callno]->transfer));
1635         } else {
1636                 if (iaxdebug)
1637                         iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1638                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1639                                         sizeof(iaxs[callno]->addr));
1640         }
1641         if (res < 0) {
1642                 if (option_debug && iaxdebug)
1643                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1644                 handle_error();
1645         } else
1646                 res = 0;
1647         return res;
1648 }
1649
1650 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1651 {
1652         struct iax2_user *user = NULL;
1653
1654         /* Decrement AUTHREQ count if needed */
1655         if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1656                 AST_LIST_LOCK(&users);
1657                 AST_LIST_TRAVERSE(&users, user, entry) {
1658                         if (!strcmp(user->name, pvt->username)) {
1659                                 user->curauthreq--;
1660                                 break;
1661                         }
1662                 }
1663                 AST_LIST_UNLOCK(&users);
1664                 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1665         }
1666         /* No more pings or lagrq's */
1667         if (pvt->pingid > -1)
1668                 ast_sched_del(sched, pvt->pingid);
1669         pvt->pingid = -1;
1670         if (pvt->lagid > -1)
1671                 ast_sched_del(sched, pvt->lagid);
1672         pvt->lagid = -1;
1673         if (pvt->autoid > -1)
1674                 ast_sched_del(sched, pvt->autoid);
1675         pvt->autoid = -1;
1676         if (pvt->authid > -1)
1677                 ast_sched_del(sched, pvt->authid);
1678         pvt->authid = -1;
1679         if (pvt->initid > -1)
1680                 ast_sched_del(sched, pvt->initid);
1681         pvt->initid = -1;
1682         if (pvt->jbid > -1)
1683                 ast_sched_del(sched, pvt->jbid);
1684         pvt->jbid = -1;
1685 }
1686
1687 static int iax2_predestroy(int callno)
1688 {
1689         struct ast_channel *c;
1690         struct chan_iax2_pvt *pvt;
1691         ast_mutex_lock(&iaxsl[callno]);
1692         pvt = iaxs[callno];
1693         if (!pvt) {
1694                 ast_mutex_unlock(&iaxsl[callno]);
1695                 return -1;
1696         }
1697         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1698                 iax2_destroy_helper(pvt);
1699                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1700         }
1701         c = pvt->owner;
1702         if (c) {
1703                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1704                 c->tech_pvt = NULL;
1705                 ast_queue_hangup(c);
1706                 pvt->owner = NULL;
1707                 ast_atomic_fetchadd_int(&usecnt, -1);
1708                 ast_update_use_count();
1709         }
1710         ast_mutex_unlock(&iaxsl[callno]);
1711         return 0;
1712 }
1713
1714 static int iax2_predestroy_nolock(int callno)
1715 {
1716         int res;
1717         ast_mutex_unlock(&iaxsl[callno]);
1718         res = iax2_predestroy(callno);
1719         ast_mutex_lock(&iaxsl[callno]);
1720         return res;
1721 }
1722
1723 static void iax2_destroy(int callno)
1724 {
1725         struct chan_iax2_pvt *pvt;
1726         struct iax_frame *cur;
1727         struct ast_channel *owner;
1728
1729 retry:
1730         ast_mutex_lock(&iaxsl[callno]);
1731         pvt = iaxs[callno];
1732         gettimeofday(&lastused[callno], NULL);
1733         
1734         owner = pvt ? pvt->owner : NULL;
1735
1736         if (owner) {
1737                 if (ast_mutex_trylock(&owner->lock)) {
1738                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1739                         ast_mutex_unlock(&iaxsl[callno]);
1740                         usleep(1);
1741                         goto retry;
1742                 }
1743         }
1744         if (!owner)
1745                 iaxs[callno] = NULL;
1746         if (pvt) {
1747                 if (!owner)
1748                         pvt->owner = NULL;
1749                 iax2_destroy_helper(pvt);
1750
1751                 /* Already gone */
1752                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1753
1754                 if (owner) {
1755                         /* If there's an owner, prod it to give up */
1756                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1757                         ast_queue_hangup(owner);
1758                 }
1759
1760                 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1761                         /* Cancel any pending transmissions */
1762                         if (cur->callno == pvt->callno) 
1763                                 cur->retries = -1;
1764                 }
1765                 if (pvt->reg)
1766                         pvt->reg->callno = 0;
1767                 if (!owner) {
1768                         jb_frame frame;
1769                         if (pvt->vars) {
1770                             ast_variables_destroy(pvt->vars);
1771                             pvt->vars = NULL;
1772                         }
1773
1774                         while (jb_getall(pvt->jb, &frame) == JB_OK)
1775                                 iax2_frame_free(frame.data);
1776                         jb_destroy(pvt->jb);
1777                         /* gotta free up the stringfields */
1778                         ast_string_field_free_all(pvt);
1779                         free(pvt);
1780                 }
1781         }
1782         if (owner) {
1783                 ast_mutex_unlock(&owner->lock);
1784         }
1785         ast_mutex_unlock(&iaxsl[callno]);
1786         if (callno & 0x4000)
1787                 update_max_trunk();
1788 }
1789 static void iax2_destroy_nolock(int callno)
1790 {       
1791         /* Actually it's easier to unlock, kill it, and relock */
1792         ast_mutex_unlock(&iaxsl[callno]);
1793         iax2_destroy(callno);
1794         ast_mutex_lock(&iaxsl[callno]);
1795 }
1796
1797 static int update_packet(struct iax_frame *f)
1798 {
1799         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1800         struct ast_iax2_full_hdr *fh = f->data;
1801         /* Mark this as a retransmission */
1802         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1803         /* Update iseqno */
1804         f->iseqno = iaxs[f->callno]->iseqno;
1805         fh->iseqno = f->iseqno;
1806         return 0;
1807 }
1808
1809 static int attempt_transmit(void *data);
1810 static void __attempt_transmit(void *data)
1811 {
1812         /* Attempt to transmit the frame to the remote peer...
1813            Called without iaxsl held. */
1814         struct iax_frame *f = data;
1815         int freeme=0;
1816         int callno = f->callno;
1817         /* Make sure this call is still active */
1818         if (callno) 
1819                 ast_mutex_lock(&iaxsl[callno]);
1820         if (callno && iaxs[callno]) {
1821                 if ((f->retries < 0) /* Already ACK'd */ ||
1822                     (f->retries >= max_retries) /* Too many attempts */) {
1823                                 /* Record an error if we've transmitted too many times */
1824                                 if (f->retries >= max_retries) {
1825                                         if (f->transfer) {
1826                                                 /* Transfer timeout */
1827                                                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1828                                         } else if (f->final) {
1829                                                 if (f->final) 
1830                                                         iax2_destroy_nolock(callno);
1831                                         } else {
1832                                                 if (iaxs[callno]->owner)
1833                                                         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);
1834                                                 iaxs[callno]->error = ETIMEDOUT;
1835                                                 if (iaxs[callno]->owner) {
1836                                                         struct ast_frame fr = { 0, };
1837                                                         /* Hangup the fd */
1838                                                         fr.frametype = AST_FRAME_CONTROL;
1839                                                         fr.subclass = AST_CONTROL_HANGUP;
1840                                                         iax2_queue_frame(callno, &fr);
1841                                                         /* Remember, owner could disappear */
1842                                                         if (iaxs[callno]->owner)
1843                                                                 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1844                                                 } else {
1845                                                         if (iaxs[callno]->reg) {
1846                                                                 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1847                                                                 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1848                                                                 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1849                                                         }
1850                                                         iax2_destroy_nolock(callno);
1851                                                 }
1852                                         }
1853
1854                                 }
1855                                 freeme++;
1856                 } else {
1857                         /* Update it if it needs it */
1858                         update_packet(f);
1859                         /* Attempt transmission */
1860                         send_packet(f);
1861                         f->retries++;
1862                         /* Try again later after 10 times as long */
1863                         f->retrytime *= 10;
1864                         if (f->retrytime > MAX_RETRY_TIME)
1865                                 f->retrytime = MAX_RETRY_TIME;
1866                         /* Transfer messages max out at one second */
1867                         if (f->transfer && (f->retrytime > 1000))
1868                                 f->retrytime = 1000;
1869                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1870                 }
1871         } else {
1872                 /* Make sure it gets freed */
1873                 f->retries = -1;
1874                 freeme++;
1875         }
1876         if (callno)
1877                 ast_mutex_unlock(&iaxsl[callno]);
1878         /* Do not try again */
1879         if (freeme) {
1880                 /* Don't attempt delivery, just remove it from the queue */
1881                 AST_LIST_LOCK(&iaxq.queue);
1882                 AST_LIST_REMOVE(&iaxq.queue, f, list);
1883                 iaxq.count--;
1884                 AST_LIST_UNLOCK(&iaxq.queue);
1885                 f->retrans = -1;
1886                 /* Free the IAX frame */
1887                 iax2_frame_free(f);
1888         }
1889 }
1890
1891 static int attempt_transmit(void *data)
1892 {
1893 #ifdef SCHED_MULTITHREADED
1894         if (schedule_action(__attempt_transmit, data))
1895 #endif          
1896                 __attempt_transmit(data);
1897         return 0;
1898 }
1899
1900 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1901 {
1902         struct iax2_peer *peer;
1903
1904         if (argc != 4)
1905         return RESULT_SHOWUSAGE;
1906         if (!strcmp(argv[3],"all")) {
1907                 reload_config();
1908                 ast_cli(fd, "OK cache is flushed.\n");
1909         } else if ((peer = find_peer(argv[3], 0))) {
1910                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1911                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1912                         expire_registry((void*)peer->name);
1913                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1914                 } else {
1915                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1916                 }
1917         } else {
1918                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1919         }
1920         
1921         return RESULT_SUCCESS;
1922 }
1923
1924 static int iax2_test_losspct(int fd, int argc, char *argv[])
1925 {
1926        if (argc != 4)
1927                return RESULT_SHOWUSAGE;
1928
1929        test_losspct = atoi(argv[3]);
1930
1931        return RESULT_SUCCESS;
1932 }
1933
1934 #ifdef IAXTESTS
1935 static int iax2_test_late(int fd, int argc, char *argv[])
1936 {
1937         if (argc != 4)
1938                 return RESULT_SHOWUSAGE;
1939
1940         test_late = atoi(argv[3]);
1941
1942         return RESULT_SUCCESS;
1943 }
1944
1945 static int iax2_test_resync(int fd, int argc, char *argv[])
1946 {
1947         if (argc != 4)
1948                 return RESULT_SHOWUSAGE;
1949
1950         test_resync = atoi(argv[3]);
1951
1952         return RESULT_SUCCESS;
1953 }
1954
1955 static int iax2_test_jitter(int fd, int argc, char *argv[])
1956 {
1957         if (argc < 4 || argc > 5)
1958                 return RESULT_SHOWUSAGE;
1959
1960         test_jit = atoi(argv[3]);
1961         if (argc == 5) 
1962                 test_jitpct = atoi(argv[4]);
1963
1964         return RESULT_SUCCESS;
1965 }
1966 #endif /* IAXTESTS */
1967
1968 /*! \brief  peer_status: Report Peer status in character string */
1969 /*      returns 1 if peer is online, -1 if unmonitored */
1970 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1971 {
1972         int res = 0;
1973         if (peer->maxms) {
1974                 if (peer->lastms < 0) {
1975                         ast_copy_string(status, "UNREACHABLE", statuslen);
1976                 } else if (peer->lastms > peer->maxms) {
1977                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
1978                         res = 1;
1979                 } else if (peer->lastms) {
1980                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
1981                         res = 1;
1982                 } else {
1983                         ast_copy_string(status, "UNKNOWN", statuslen);
1984                 }
1985         } else { 
1986                 ast_copy_string(status, "Unmonitored", statuslen);
1987                 res = -1;
1988         }
1989         return res;
1990 }
1991
1992 /*! \brief Show one peer in detail */
1993 static int iax2_show_peer(int fd, int argc, char *argv[])
1994 {
1995         char status[30];
1996         char cbuf[256];
1997         struct iax2_peer *peer;
1998         char codec_buf[512];
1999         int x = 0, codec = 0, load_realtime = 0;
2000
2001         if (argc < 4)
2002                 return RESULT_SHOWUSAGE;
2003
2004         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2005
2006         peer = find_peer(argv[3], load_realtime);
2007         if (peer) {
2008                 ast_cli(fd,"\n\n");
2009                 ast_cli(fd, "  * Name       : %s\n", peer->name);
2010                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2011                 ast_cli(fd, "  Context      : %s\n", peer->context);
2012                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
2013                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2014                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2015                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
2016                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
2017                 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));
2018                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2019                 ast_cli(fd, "  Username     : %s\n", peer->username);
2020                 ast_cli(fd, "  Codecs       : ");
2021                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2022                 ast_cli(fd, "%s\n", codec_buf);
2023
2024                 ast_cli(fd, "  Codec Order  : (");
2025                 for(x = 0; x < 32 ; x++) {
2026                         codec = ast_codec_pref_index(&peer->prefs,x);
2027                         if(!codec)
2028                                 break;
2029                         ast_cli(fd, "%s", ast_getformatname(codec));
2030                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2031                                 ast_cli(fd, "|");
2032                 }
2033
2034                 if (!x)
2035                         ast_cli(fd, "none");
2036                 ast_cli(fd, ")\n");
2037
2038                 ast_cli(fd, "  Status       : ");
2039                 peer_status(peer, status, sizeof(status));      
2040                 ast_cli(fd, "%s\n",status);
2041                 ast_cli(fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2042                 ast_cli(fd,"\n");
2043                 if (ast_test_flag(peer, IAX_TEMPONLY))
2044                         destroy_peer(peer);
2045         } else {
2046                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2047                 ast_cli(fd,"\n");
2048         }
2049
2050         return RESULT_SUCCESS;
2051 }
2052
2053 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2054 {
2055         int which = 0;
2056         struct iax2_peer *p = NULL;
2057         char *res = NULL;
2058         int wordlen = strlen(word);
2059
2060         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2061         if (pos == 3) {
2062                 AST_LIST_LOCK(&peers);
2063                 AST_LIST_TRAVERSE(&peers, p, entry) {
2064                         if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2065                                 res = ast_strdup(p->name);
2066                                 break;
2067                         }
2068                 }
2069                 AST_LIST_UNLOCK(&peers);
2070         }
2071
2072         return res;
2073 }
2074
2075 static int iax2_show_stats(int fd, int argc, char *argv[])
2076 {
2077         struct iax_frame *cur;
2078         int cnt = 0, dead=0, final=0;
2079         if (argc != 3)
2080                 return RESULT_SHOWUSAGE;
2081         AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2082                 if (cur->retries < 0)
2083                         dead++;
2084                 if (cur->final)
2085                         final++;
2086                 cnt++;
2087         }
2088         ast_cli(fd, "    IAX Statistics\n");
2089         ast_cli(fd, "---------------------\n");
2090         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2091         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2092         
2093         return RESULT_SUCCESS;
2094 }
2095
2096 static int iax2_show_cache(int fd, int argc, char *argv[])
2097 {
2098         struct iax2_dpcache *dp;
2099         char tmp[1024], *pc;
2100         int s;
2101         int x,y;
2102         struct timeval tv;
2103         gettimeofday(&tv, NULL);
2104         ast_mutex_lock(&dpcache_lock);
2105         dp = dpcache;
2106         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2107         while(dp) {
2108                 s = dp->expiry.tv_sec - tv.tv_sec;
2109                 tmp[0] = '\0';
2110                 if (dp->flags & CACHE_FLAG_EXISTS)
2111                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2112                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2113                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2114                 if (dp->flags & CACHE_FLAG_CANEXIST)
2115                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2116                 if (dp->flags & CACHE_FLAG_PENDING)
2117                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2118                 if (dp->flags & CACHE_FLAG_TIMEOUT)
2119                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2120                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2121                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2122                 if (dp->flags & CACHE_FLAG_MATCHMORE)
2123                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2124                 if (dp->flags & CACHE_FLAG_UNKNOWN)
2125                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2126                 /* Trim trailing pipe */
2127                 if (!ast_strlen_zero(tmp))
2128                         tmp[strlen(tmp) - 1] = '\0';
2129                 else
2130                         ast_copy_string(tmp, "(none)", sizeof(tmp));
2131                 y=0;
2132                 pc = strchr(dp->peercontext, '@');
2133                 if (!pc)
2134                         pc = dp->peercontext;
2135                 else
2136                         pc++;
2137                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2138                         if (dp->waiters[x] > -1)
2139                                 y++;
2140                 if (s > 0)
2141                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2142                 else
2143                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2144                 dp = dp->next;
2145         }
2146         ast_mutex_unlock(&dpcache_lock);
2147         return RESULT_SUCCESS;
2148 }
2149
2150 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2151
2152 static void unwrap_timestamp(struct iax_frame *fr)
2153 {
2154         int x;
2155
2156         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2157                 x = fr->ts - iaxs[fr->callno]->last;
2158                 if (x < -50000) {
2159                         /* Sudden big jump backwards in timestamp:
2160                            What likely happened here is that miniframe timestamp has circled but we haven't
2161                            gotten the update from the main packet.  We'll just pretend that we did, and
2162                            update the timestamp appropriately. */
2163                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2164                         if (option_debug && iaxdebug)
2165                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2166                 }
2167                 if (x > 50000) {
2168                         /* Sudden apparent big jump forwards in timestamp:
2169                            What's likely happened is this is an old miniframe belonging to the previous
2170                            top-16-bit timestamp that has turned up out of order.
2171                            Adjust the timestamp appropriately. */
2172                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2173                         if (option_debug && iaxdebug)
2174                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2175                 }
2176         }
2177 }
2178
2179 static int get_from_jb(void *p);
2180
2181 static void update_jbsched(struct chan_iax2_pvt *pvt)
2182 {
2183         int when;
2184         
2185         when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2186         
2187         when = jb_next(pvt->jb) - when;
2188         
2189         if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2190         
2191         if(when <= 0) {
2192                 /* XXX should really just empty until when > 0.. */
2193                 when = 1;
2194         }
2195         
2196         pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2197         
2198         /* Signal scheduler thread */
2199         signal_condition(&sched_lock, &sched_cond);
2200 }
2201
2202 static void __get_from_jb(void *p) 
2203 {
2204         int callno = PTR_TO_CALLNO(p);
2205         struct chan_iax2_pvt *pvt = NULL;
2206         struct iax_frame *fr;
2207         jb_frame frame;
2208         int ret;
2209         long now;
2210         long next;
2211         struct timeval tv;
2212         
2213         /* Make sure we have a valid private structure before going on */
2214         ast_mutex_lock(&iaxsl[callno]);
2215         pvt = iaxs[callno];
2216         if (!pvt) {
2217                 /* No go! */
2218                 ast_mutex_unlock(&iaxsl[callno]);
2219                 return;
2220         }
2221
2222         pvt->jbid = -1;
2223         
2224         gettimeofday(&tv,NULL);
2225         /* round up a millisecond since ast_sched_runq does; */
2226         /* prevents us from spinning while waiting for our now */
2227         /* to catch up with runq's now */
2228         tv.tv_usec += 1000;
2229         
2230         now = ast_tvdiff_ms(tv, pvt->rxcore);
2231         
2232         if(now >= (next = jb_next(pvt->jb))) {
2233                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2234                 switch(ret) {
2235                 case JB_OK:
2236                         fr = frame.data;
2237                         __do_deliver(fr);
2238                         break;
2239                 case JB_INTERP:
2240                 {
2241                         struct ast_frame af;
2242                         
2243                         /* create an interpolation frame */
2244                         af.frametype = AST_FRAME_VOICE;
2245                         af.subclass = pvt->voiceformat;
2246                         af.datalen  = 0;
2247                         af.samples  = frame.ms * 8;
2248                         af.mallocd  = 0;
2249                         af.src  = "IAX2 JB interpolation";
2250                         af.data  = NULL;
2251                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2252                         af.offset=AST_FRIENDLY_OFFSET;
2253                         
2254                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2255                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2256                         if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2257                                 iax2_queue_frame(callno, &af);
2258                 }
2259                 break;
2260                 case JB_DROP:
2261                         iax2_frame_free(frame.data);
2262                         break;
2263                 case JB_NOFRAME:
2264                 case JB_EMPTY:
2265                         /* do nothing */
2266                         break;
2267                 default:
2268                         /* shouldn't happen */
2269                         break;
2270                 }
2271         }
2272         update_jbsched(pvt);
2273         ast_mutex_unlock(&iaxsl[callno]);
2274 }
2275
2276 static int get_from_jb(void *data)
2277 {
2278 #ifdef SCHED_MULTITHREADED
2279         if (schedule_action(__get_from_jb, data))
2280 #endif          
2281                 __get_from_jb(data);
2282         return 0;
2283 }
2284
2285 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2286 {
2287         int type, len;
2288         int ret;
2289         int needfree = 0;
2290
2291         /* Attempt to recover wrapped timestamps */
2292         unwrap_timestamp(fr);
2293         
2294
2295         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2296         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2297                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2298         else {
2299 #if 0
2300                 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2301 #endif
2302                 fr->af.delivery = ast_tv(0,0);
2303         }
2304
2305         type = JB_TYPE_CONTROL;
2306         len = 0;
2307
2308         if(fr->af.frametype == AST_FRAME_VOICE) {
2309                 type = JB_TYPE_VOICE;
2310                 len = ast_codec_get_samples(&fr->af) / 8;
2311         } else if(fr->af.frametype == AST_FRAME_CNG) {
2312                 type = JB_TYPE_SILENCE;
2313         }
2314
2315         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2316                 if (tsout)
2317                         *tsout = fr->ts;
2318                 __do_deliver(fr);
2319                 return -1;
2320         }
2321
2322         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2323          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2324         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2325             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2326             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2327                 jb_frame frame;
2328
2329                 /* deliver any frames in the jb */
2330                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2331                         __do_deliver(frame.data);
2332
2333                 jb_reset(iaxs[fr->callno]->jb);
2334
2335                 if (iaxs[fr->callno]->jbid > -1)
2336                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2337
2338                 iaxs[fr->callno]->jbid = -1;
2339
2340                 /* deliver this frame now */
2341                 if (tsout)
2342                         *tsout = fr->ts;
2343                 __do_deliver(fr);
2344                 return -1;
2345         }
2346
2347         /* insert into jitterbuffer */
2348         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2349         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2350                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2351         if (ret == JB_DROP) {
2352                 needfree++;
2353         } else if (ret == JB_SCHED) {
2354                 update_jbsched(iaxs[fr->callno]);
2355         }
2356         if (tsout)
2357                 *tsout = fr->ts;
2358         if (needfree) {
2359                 /* Free our iax frame */
2360                 iax2_frame_free(fr);
2361                 return -1;
2362         }
2363         return 0;
2364 }
2365
2366 static int iax2_transmit(struct iax_frame *fr)
2367 {
2368         /* Lock the queue and place this packet at the end */
2369         /* By setting this to 0, the network thread will send it for us, and
2370            queue retransmission if necessary */
2371         fr->sentyet = 0;
2372         AST_LIST_LOCK(&iaxq.queue);
2373         AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2374         iaxq.count++;
2375         AST_LIST_UNLOCK(&iaxq.queue);
2376         /* Wake up the network and scheduler thread */
2377         pthread_kill(netthreadid, SIGURG);
2378         signal_condition(&sched_lock, &sched_cond);
2379         return 0;
2380 }
2381
2382
2383
2384 static int iax2_digit_begin(struct ast_channel *c, char digit)
2385 {
2386         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2387 }
2388
2389 static int iax2_digit_end(struct ast_channel *c, char digit)
2390 {
2391         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2392 }
2393
2394 static int iax2_sendtext(struct ast_channel *c, const char *text)
2395 {
2396         
2397         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2398                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2399 }
2400
2401 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2402 {
2403         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2404 }
2405
2406 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2407 {
2408         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2409 }
2410
2411 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2412 {
2413         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2414         ast_mutex_lock(&iaxsl[callno]);
2415         if (iaxs[callno])
2416                 iaxs[callno]->owner = newchan;
2417         else
2418                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2419         ast_mutex_unlock(&iaxsl[callno]);
2420         return 0;
2421 }
2422
2423 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2424 {
2425         struct ast_variable *var;
2426         struct ast_variable *tmp;
2427         struct iax2_peer *peer=NULL;
2428         time_t regseconds = 0, nowtime;
2429         int dynamic=0;
2430
2431         if (peername)
2432                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2433         else {
2434                 char porta[25];
2435                 sprintf(porta, "%d", ntohs(sin->sin_port));
2436                 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2437                 if (var) {
2438                         /* We'll need the peer name in order to build the structure! */
2439                         for (tmp = var; tmp; tmp = tmp->next) {
2440                                 if (!strcasecmp(tmp->name, "name"))
2441                                         peername = tmp->value;
2442                         }
2443                 }
2444         }
2445         if (!var)
2446                 return NULL;
2447
2448         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2449         
2450         if (!peer)
2451                 return NULL;
2452
2453         for (tmp = var; tmp; tmp = tmp->next) {
2454                 /* Make sure it's not a user only... */
2455                 if (!strcasecmp(tmp->name, "type")) {
2456                         if (strcasecmp(tmp->value, "friend") &&
2457                             strcasecmp(tmp->value, "peer")) {
2458                                 /* Whoops, we weren't supposed to exist! */
2459                                 destroy_peer(peer);
2460                                 peer = NULL;
2461                                 break;
2462                         } 
2463                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2464                         ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2465                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2466                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2467                 } else if (!strcasecmp(tmp->name, "port")) {
2468                         peer->addr.sin_port = htons(atoi(tmp->value));
2469                 } else if (!strcasecmp(tmp->name, "host")) {
2470                         if (!strcasecmp(tmp->value, "dynamic"))
2471                                 dynamic = 1;
2472                 }
2473         }
2474         if (!peer)
2475                 return NULL;
2476
2477         ast_variables_destroy(var);
2478
2479         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2480                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2481                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2482                         if (peer->expire > -1)
2483                                 ast_sched_del(sched, peer->expire);
2484                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2485                 }
2486                 AST_LIST_LOCK(&peers);
2487                 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2488                 AST_LIST_UNLOCK(&peers);
2489                 if (ast_test_flag(peer, IAX_DYNAMIC))
2490                         reg_source_db(peer);
2491         } else {
2492                 ast_set_flag(peer, IAX_TEMPONLY);       
2493         }
2494
2495         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2496                 time(&nowtime);
2497                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2498                         memset(&peer->addr, 0, sizeof(peer->addr));
2499                         if (option_debug)
2500                                 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2501                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2502                 }
2503                 else {
2504                         if (option_debug)
2505                                 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2506                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2507                 }
2508         }
2509
2510         return peer;
2511 }
2512
2513 static struct iax2_user *realtime_user(const char *username)
2514 {
2515         struct ast_variable *var;
2516         struct ast_variable *tmp;
2517         struct iax2_user *user=NULL;
2518
2519         var = ast_load_realtime("iaxusers", "name", username, NULL);
2520         if (!var)
2521                 return NULL;
2522
2523         tmp = var;
2524         while(tmp) {
2525                 /* Make sure it's not a peer only... */
2526                 if (!strcasecmp(tmp->name, "type")) {
2527                         if (strcasecmp(tmp->value, "friend") &&
2528                             strcasecmp(tmp->value, "user")) {
2529                                 return NULL;
2530                         } 
2531                 }
2532                 tmp = tmp->next;
2533         }
2534
2535         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2536         if (!user)
2537                 return NULL;
2538
2539         ast_variables_destroy(var);
2540
2541         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2542                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2543                 AST_LIST_LOCK(&users);
2544                 AST_LIST_INSERT_HEAD(&users, user, entry);
2545                 AST_LIST_UNLOCK(&users);
2546         } else {
2547                 ast_set_flag(user, IAX_TEMPONLY);       
2548         }
2549
2550         return user;
2551 }
2552
2553 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2554 {
2555         char port[10];
2556         char regseconds[20];
2557         
2558         snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2559         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2560         ast_update_realtime("iaxpeers", "name", peername, 
2561                 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
2562                 "regseconds", regseconds, NULL);
2563 }
2564
2565 struct create_addr_info {
2566         int capability;
2567         unsigned int flags;
2568         int maxtime;
2569         int encmethods;
2570         int found;
2571         int sockfd;
2572         int adsi;
2573         char username[80];
2574         char secret[80];
2575         char outkey[80];
2576         char timezone[80];
2577         char prefs[32];
2578         char context[AST_MAX_CONTEXT];
2579         char peercontext[AST_MAX_CONTEXT];
2580         char mohinterpret[MAX_MUSICCLASS];
2581         char mohsuggest[MAX_MUSICCLASS];
2582 };
2583
2584 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2585 {
2586         struct ast_hostent ahp;
2587         struct hostent *hp;
2588         struct iax2_peer *peer;
2589
2590         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2591         cai->sockfd = defaultsockfd;
2592         cai->maxtime = 0;
2593         sin->sin_family = AF_INET;
2594
2595         if (!(peer = find_peer(peername, 1))) {
2596                 cai->found = 0;
2597
2598                 hp = ast_gethostbyname(peername, &ahp);
2599                 if (hp) {
2600                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2601                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2602                         /* use global iax prefs for unknown peer/user */
2603                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2604                         return 0;
2605                 } else {
2606                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2607                         return -1;
2608                 }
2609         }
2610
2611         cai->found = 1;
2612         
2613         /* if the peer has no address (current or default), return failure */
2614         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2615                 if (ast_test_flag(peer, IAX_TEMPONLY))
2616                         destroy_peer(peer);
2617                 return -1;
2618         }
2619
2620         /* if the peer is being monitored and is currently unreachable, return failure */
2621         if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2622                 if (ast_test_flag(peer, IAX_TEMPONLY))
2623                         destroy_peer(peer);
2624                 return -1;
2625         }
2626
2627         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2628         cai->maxtime = peer->maxms;
2629         cai->capability = peer->capability;
2630         cai->encmethods = peer->encmethods;
2631         cai->sockfd = peer->sockfd;
2632         cai->adsi = peer->adsi;
2633         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2634         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2635         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2636         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2637         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2638         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2639         ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2640         ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2641         if (ast_strlen_zero(peer->dbsecret)) {
2642                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2643         } else {
2644                 char *family;
2645                 char *key = NULL;
2646
2647                 family = ast_strdupa(peer->dbsecret);
2648                 key = strchr(family, '/');
2649                 if (key)
2650                         *key++ = '\0';
2651                 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2652                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2653                         if (ast_test_flag(peer, IAX_TEMPONLY))
2654                                 destroy_peer(peer);
2655                         return -1;
2656                 }
2657         }
2658
2659         if (peer->addr.sin_addr.s_addr) {
2660                 sin->sin_addr = peer->addr.sin_addr;
2661                 sin->sin_port = peer->addr.sin_port;
2662         } else {
2663                 sin->sin_addr = peer->defaddr.sin_addr;
2664                 sin->sin_port = peer->defaddr.sin_port;
2665         }
2666
2667         if (ast_test_flag(peer, IAX_TEMPONLY))
2668                 destroy_peer(peer);
2669
2670         return 0;
2671 }
2672
2673 static void __auto_congest(void *nothing)
2674 {
2675         int callno = PTR_TO_CALLNO(nothing);
2676         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2677         ast_mutex_lock(&iaxsl[callno]);
2678         if (iaxs[callno]) {
2679                 iaxs[callno]->initid = -1;
2680                 iax2_queue_frame(callno, &f);
2681                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2682         }
2683         ast_mutex_unlock(&iaxsl[callno]);
2684 }
2685
2686 static int auto_congest(void *data)
2687 {
2688 #ifdef SCHED_MULTITHREADED
2689         if (schedule_action(__auto_congest, data))
2690 #endif          
2691                 __auto_congest(data);
2692         return 0;
2693 }
2694
2695 static unsigned int iax2_datetime(const char *tz)
2696 {
2697         time_t t;
2698         struct tm tm;
2699         unsigned int tmp;
2700         time(&t);
2701         localtime_r(&t, &tm);
2702         if (!ast_strlen_zero(tz))
2703                 ast_localtime(&t, &tm, tz);
2704         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2705         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2706         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2707         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2708         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2709         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2710         return tmp;
2711 }
2712
2713 struct parsed_dial_string {
2714         char *username;
2715         char *password;
2716         char *key;
2717         char *peer;
2718         char *port;
2719         char *exten;
2720         char *context;
2721         char *options;
2722 };
2723
2724 /*!
2725  * \brief Parses an IAX dial string into its component parts.
2726  * \param data the string to be parsed
2727  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2728  * \return nothing
2729  *
2730  * This function parses the string and fills the structure
2731  * with pointers to its component parts. The input string
2732  * will be modified.
2733  *
2734  * \note This function supports both plaintext passwords and RSA
2735  * key names; if the password string is formatted as '[keyname]',
2736  * then the keyname will be placed into the key field, and the
2737  * password field will be set to NULL.
2738  *
2739  * \note The dial string format is:
2740  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2741  */
2742 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2743 {
2744         if (ast_strlen_zero(data))
2745                 return;
2746
2747         pds->peer = strsep(&data, "/");
2748         pds->exten = strsep(&data, "/");
2749         pds->options = data;
2750
2751         if (pds->exten) {
2752                 data = pds->exten;
2753                 pds->exten = strsep(&data, "@");
2754                 pds->context = data;
2755         }
2756
2757         if (strchr(pds->peer, '@')) {
2758                 data = pds->peer;
2759                 pds->username = strsep(&data, "@");
2760                 pds->peer = data;
2761         }
2762
2763         if (pds->username) {
2764                 data = pds->username;
2765                 pds->username = strsep(&data, ":");
2766                 pds->password = data;
2767         }
2768
2769         data = pds->peer;
2770         pds->peer = strsep(&data, ":");
2771         pds->port = data;
2772
2773         /* check for a key name wrapped in [] in the secret position, if found,
2774            move it to the key field instead
2775         */
2776         if (pds->password && (pds->password[0] == '[')) {
2777                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2778                 pds->password = NULL;
2779         }
2780 }
2781
2782 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2783 {
2784         struct sockaddr_in sin;
2785         char *l=NULL, *n=NULL, *tmpstr;
2786         struct iax_ie_data ied;
2787         char *defaultrdest = "s";
2788         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2789         struct parsed_dial_string pds;
2790         struct create_addr_info cai;
2791
2792         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2793                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2794                 return -1;
2795         }
2796
2797         memset(&cai, 0, sizeof(cai));
2798         cai.encmethods = iax2_encryption;
2799
2800         memset(&pds, 0, sizeof(pds));
2801         tmpstr = ast_strdupa(dest);
2802         parse_dial_string(tmpstr, &pds);
2803
2804         if (!pds.exten)
2805                 pds.exten = defaultrdest;
2806
2807         if (create_addr(pds.peer, &sin, &cai)) {
2808                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2809                 return -1;
2810         }
2811
2812         if (!pds.username && !ast_strlen_zero(cai.username))
2813                 pds.username = cai.username;
2814         if (!pds.password && !ast_strlen_zero(cai.secret))
2815                 pds.password = cai.secret;
2816         if (!pds.key && !ast_strlen_zero(cai.outkey))
2817                 pds.key = cai.outkey;
2818         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2819                 pds.context = cai.peercontext;
2820
2821         /* Keep track of the context for outgoing calls too */
2822         ast_copy_string(c->context, cai.context, sizeof(c->context));
2823
2824         if (pds.port)
2825                 sin.sin_port = htons(atoi(pds.port));
2826
2827         l = c->cid.cid_num;
2828         n = c->cid.cid_name;
2829
2830         /* Now build request */ 
2831         memset(&ied, 0, sizeof(ied));
2832
2833         /* On new call, first IE MUST be IAX version of caller */
2834         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2835         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2836         if (pds.options && strchr(pds.options, 'a')) {
2837                 /* Request auto answer */
2838                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2839         }
2840
2841         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2842
2843         if (l) {
2844                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2845                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2846         } else {
2847                 if (n)
2848                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2849                 else
2850                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2851         }
2852
2853         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2854         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2855
2856         if (n)
2857                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2858         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2859                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2860
2861         if (!ast_strlen_zero(c->language))
2862                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2863         if (!ast_strlen_zero(c->cid.cid_dnid))
2864                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2865         if (!ast_strlen_zero(c->cid.cid_rdnis))
2866                 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2867
2868         if (pds.context)
2869                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2870
2871         if (pds.username)
2872                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2873
2874         if (cai.encmethods)
2875                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2876
2877         ast_mutex_lock(&iaxsl[callno]);
2878
2879         if (!ast_strlen_zero(c->context))
2880                 ast_string_field_set(iaxs[callno], context, c->context);
2881
2882         if (pds.username)
2883                 ast_string_field_set(iaxs[callno], username, pds.username);
2884
2885         iaxs[callno]->encmethods = cai.encmethods;
2886
2887         iaxs[callno]->adsi = cai.adsi;
2888         
2889         ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
2890         ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
2891
2892         if (pds.key)
2893                 ast_string_field_set(iaxs[callno], outkey, pds.key);
2894         if (pds.password)
2895                 ast_string_field_set(iaxs[callno], secret, pds.password);
2896
2897         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2898         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2899         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2900         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2901
2902         if (iaxs[callno]->maxtime) {
2903                 /* Initialize pingtime and auto-congest time */
2904                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2905                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2906         } else if (autokill) {
2907                 iaxs[callno]->pingtime = autokill / 2;
2908                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2909         }
2910
2911         /* Transmit the string in a "NEW" request */
2912         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2913
2914         ast_mutex_unlock(&iaxsl[callno]);
2915         ast_setstate(c, AST_STATE_RINGING);
2916         
2917         return 0;
2918 }
2919
2920 static int iax2_hangup(struct ast_channel *c) 
2921 {
2922         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2923         int alreadygone;
2924         struct iax_ie_data ied;
2925         memset(&ied, 0, sizeof(ied));
2926         ast_mutex_lock(&iaxsl[callno]);
2927         if (callno && iaxs[callno]) {
2928                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2929                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2930                 /* Send the hangup unless we have had a transmission error or are already gone */
2931                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2932                 if (!iaxs[callno]->error && !alreadygone) 
2933                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2934                 /* Explicitly predestroy it */
2935                 iax2_predestroy_nolock(callno);
2936                 /* If we were already gone to begin with, destroy us now */
2937                 if (alreadygone) {
2938                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2939                         iax2_destroy_nolock(callno);
2940                 }
2941         }
2942         ast_mutex_unlock(&iaxsl[callno]);
2943         if (option_verbose > 2) 
2944                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2945         return 0;
2946 }
2947
2948 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2949 {
2950         struct ast_option_header *h;
2951         int res;
2952
2953         switch (option) {
2954         case AST_OPTION_TXGAIN:
2955         case AST_OPTION_RXGAIN:
2956                 /* these two cannot be sent, because they require a result */
2957                 errno = ENOSYS;
2958                 return -1;
2959         default:
2960                 if (!(h = ast_malloc(datalen + sizeof(*h))))
2961                         return -1;
2962
2963                 h->flag = AST_OPTION_FLAG_REQUEST;
2964                 h->option = htons(option);
2965                 memcpy(h->data, data, datalen);
2966                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
2967                                           AST_CONTROL_OPTION, 0, (unsigned char *) h,
2968                                           datalen + sizeof(*h), -1);
2969                 free(h);
2970                 return res;
2971         }
2972 }
2973
2974 static struct ast_frame *iax2_read(struct ast_channel *c) 
2975 {
2976         ast_log(LOG_NOTICE, "I should never be called!\n");
2977         return &ast_null_frame;
2978 }
2979
2980 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
2981 {
2982         int res;
2983         struct iax_ie_data ied0;
2984         struct iax_ie_data ied1;
2985         unsigned int transferid = (unsigned int)ast_random();
2986         memset(&ied0, 0, sizeof(ied0));
2987         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
2988         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
2989         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
2990
2991         memset(&ied1, 0, sizeof(ied1));
2992         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
2993         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
2994         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
2995         
2996         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
2997         if (res)
2998                 return -1;
2999         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3000         if (res)
3001                 return -1;
3002         iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3003         iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3004         return 0;
3005 }
3006
3007 static void lock_both(unsigned short callno0, unsigned short callno1)
3008 {
3009         ast_mutex_lock(&iaxsl[callno0]);
3010         while (ast_mutex_trylock(&iaxsl[callno1])) {
3011                 ast_mutex_unlock(&iaxsl[callno0]);
3012                 usleep(10);
3013                 ast_mutex_lock(&iaxsl[callno0]);
3014         }
3015 }
3016
3017 static void unlock_both(unsigned short callno0, unsigned short callno1)
3018 {
3019         ast_mutex_unlock(&iaxsl[callno1]);
3020         ast_mutex_unlock(&iaxsl[callno0]);
3021 }
3022
3023 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)
3024 {
3025         struct ast_channel *cs[3];
3026         struct ast_channel *who, *other;
3027         int to = -1;
3028         int res = -1;
3029         int transferstarted=0;
3030         struct ast_frame *f;
3031         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3032         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3033         struct timeval waittimer = {0, 0}, tv;
3034
3035         lock_both(callno0, callno1);
3036         /* Put them in native bridge mode */
3037         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3038                 iaxs[callno0]->bridgecallno = callno1;
3039                 iaxs[callno1]->bridgecallno = callno0;
3040         }
3041         unlock_both(callno0, callno1);
3042
3043         /* If not, try to bridge until we can execute a transfer, if we can */
3044         cs[0] = c0;
3045         cs[1] = c1;
3046         for (/* ever */;;) {
3047                 /* Check in case we got masqueraded into */
3048                 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3049                         if (option_verbose > 2)
3050                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3051                         /* Remove from native mode */
3052                         if (c0->tech == &iax2_tech) {
3053                                 ast_mutex_lock(&iaxsl[callno0]);
3054                                 iaxs[callno0]->bridgecallno = 0;
3055                                 ast_mutex_unlock(&iaxsl[callno0]);
3056                         }
3057                         if (c1->tech == &iax2_tech) {
3058                                 ast_mutex_lock(&iaxsl[callno1]);
3059                                 iaxs[callno1]->bridgecallno = 0;
3060                                 ast_mutex_unlock(&iaxsl[callno1]);
3061                         }
3062                         return AST_BRIDGE_FAILED_NOWARN;
3063                 }
3064                 if (c0->nativeformats != c1->nativeformats) {
3065                         if (option_verbose > 2) {
3066                                 char buf0[255];
3067                                 char buf1[255];
3068                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3069                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3070                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3071                         }
3072                         /* Remove from native mode */
3073                         lock_both(callno0, callno1);
3074                         iaxs[callno0]->bridgecallno = 0;
3075                         iaxs[callno1]->bridgecallno = 0;
3076                         unlock_both(callno0, callno1);
3077                         return AST_BRIDGE_FAILED_NOWARN;
3078                 }
3079                 /* check if transfered and if we really want native bridging */
3080                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3081                         /* Try the transfer */
3082                         if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3083                                                         ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3084                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3085                         transferstarted = 1;
3086                 }
3087                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3088                         /* Call has been transferred.  We're no longer involved */
3089                         gettimeofday(&tv, NULL);
3090                         if (ast_tvzero(waittimer)) {
3091                                 waittimer = tv;
3092                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3093                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3094                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3095                                 *fo = NULL;
3096                                 *rc = c0;
3097                                 res = AST_BRIDGE_COMPLETE;
3098                                 break;
3099                         }
3100                 }
3101                 to = 1000;
3102                 who = ast_waitfor_n(cs, 2, &to);
3103                 if (timeoutms > -1) {
3104                         timeoutms -= (1000 - to);
3105                         if (timeoutms < 0)
3106                                 timeoutms = 0;
3107                 }
3108                 if (!who) {
3109                         if (!timeoutms) {
3110                                 res = AST_BRIDGE_RETRY;
3111                                 break;
3112                         }
3113                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3114                                 res = AST_BRIDGE_FAILED;
3115                                 break;
3116                         }
3117                         continue;
3118                 }
3119                 f = ast_read(who);
3120                 if (!f) {
3121                         *fo = NULL;
3122                         *rc = who;
3123                         res = AST_BRIDGE_COMPLETE;
3124                         break;
3125                 }
3126                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3127                         *fo = f;
3128                         *rc = who;
3129                         res =  AST_BRIDGE_COMPLETE;
3130                         break;
3131                 }
3132                 other = (who == c0) ? c1 : c0;  /* the 'other' channel */
3133                 if ((f->frametype == AST_FRAME_VOICE) ||
3134                     (f->frametype == AST_FRAME_TEXT) ||
3135                     (f->frametype == AST_FRAME_VIDEO) || 
3136                     (f->frametype == AST_FRAME_IMAGE) ||
3137                     (f->frametype == AST_FRAME_DTMF)) {
3138                         /* monitored dtmf take out of the bridge.
3139                          * check if we monitor the specific source.
3140                          */
3141                         int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3142                         if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3143                                 *rc = who;
3144                                 *fo = f;
3145                                 res = AST_BRIDGE_COMPLETE;
3146                                 /* Remove from native mode */
3147                                 break;
3148                         }
3149                         /* everything else goes to the other side */
3150                         ast_write(other, f);
3151                 }
3152            &nb