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