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