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