e7e6cf3d65fbd682826b677d440880ce5057210f
[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         if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1547                 iax2_queue_frame(fr->callno, &fr->af);
1548         /* Free our iax frame */
1549         iax2_frame_free(fr);
1550         /* And don't run again */
1551         return 0;
1552 }
1553
1554 static int handle_error(void)
1555 {
1556         /* XXX Ideally we should figure out why an error occured and then abort those
1557            rather than continuing to try.  Unfortunately, the published interface does
1558            not seem to work XXX */
1559 #if 0
1560         struct sockaddr_in *sin;
1561         int res;
1562         struct msghdr m;
1563         struct sock_extended_err e;
1564         m.msg_name = NULL;
1565         m.msg_namelen = 0;
1566         m.msg_iov = NULL;
1567         m.msg_control = &e;
1568         m.msg_controllen = sizeof(e);
1569         m.msg_flags = 0;
1570         res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1571         if (res < 0)
1572                 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1573         else {
1574                 if (m.msg_controllen) {
1575                         sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1576                         if (sin) 
1577                                 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1578                         else
1579                                 ast_log(LOG_WARNING, "No address detected??\n");
1580                 } else {
1581                         ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1582                 }
1583         }
1584 #endif
1585         return 0;
1586 }
1587
1588 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1589 {
1590         int res;
1591         res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1592                                         sizeof(*sin));
1593         if (res < 0) {
1594                 if (option_debug)
1595                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1596                 handle_error();
1597         } else
1598                 res = 0;
1599         return res;
1600 }
1601
1602 static int send_packet(struct iax_frame *f)
1603 {
1604         int res;
1605         char iabuf[INET_ADDRSTRLEN];
1606         int callno = f->callno;
1607
1608         /* Don't send if there was an error, but return error instead */
1609         if (!callno || !iaxs[callno] || iaxs[callno]->error)
1610             return -1;
1611         
1612         /* Called with iaxsl held */
1613         if (option_debug > 2 && iaxdebug)
1614                 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));
1615         if (f->transfer) {
1616                 if (iaxdebug)
1617                         iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1618                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1619                                         sizeof(iaxs[callno]->transfer));
1620         } else {
1621                 if (iaxdebug)
1622                         iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1623                 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1624                                         sizeof(iaxs[callno]->addr));
1625         }
1626         if (res < 0) {
1627                 if (option_debug && iaxdebug)
1628                         ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1629                 handle_error();
1630         } else
1631                 res = 0;
1632         return res;
1633 }
1634
1635 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1636 {
1637         /* No more pings or lagrq's */
1638         if (pvt->pingid > -1)
1639                 ast_sched_del(sched, pvt->pingid);
1640         pvt->pingid = -1;
1641         if (pvt->lagid > -1)
1642                 ast_sched_del(sched, pvt->lagid);
1643         pvt->lagid = -1;
1644         if (pvt->autoid > -1)
1645                 ast_sched_del(sched, pvt->autoid);
1646         pvt->autoid = -1;
1647         if (pvt->authid > -1)
1648                 ast_sched_del(sched, pvt->authid);
1649         pvt->authid = -1;
1650         if (pvt->initid > -1)
1651                 ast_sched_del(sched, pvt->initid);
1652         pvt->initid = -1;
1653         if (pvt->jbid > -1)
1654                 ast_sched_del(sched, pvt->jbid);
1655         pvt->jbid = -1;
1656 }
1657
1658 static int iax2_predestroy(int callno)
1659 {
1660         struct ast_channel *c;
1661         struct chan_iax2_pvt *pvt;
1662         ast_mutex_lock(&iaxsl[callno]);
1663         pvt = iaxs[callno];
1664         if (!pvt) {
1665                 ast_mutex_unlock(&iaxsl[callno]);
1666                 return -1;
1667         }
1668         if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1669                 iax2_destroy_helper(pvt);
1670                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1671         }
1672         c = pvt->owner;
1673         if (c) {
1674                 c->_softhangup |= AST_SOFTHANGUP_DEV;
1675                 c->tech_pvt = NULL;
1676                 ast_queue_hangup(c);
1677                 pvt->owner = NULL;
1678                 ast_mutex_lock(&usecnt_lock);
1679                 usecnt--;
1680                 if (usecnt < 0) 
1681                         ast_log(LOG_WARNING, "Usecnt < 0???\n");
1682                 ast_mutex_unlock(&usecnt_lock);
1683         }
1684         ast_mutex_unlock(&iaxsl[callno]);
1685         ast_update_use_count();
1686         return 0;
1687 }
1688
1689 static int iax2_predestroy_nolock(int callno)
1690 {
1691         int res;
1692         ast_mutex_unlock(&iaxsl[callno]);
1693         res = iax2_predestroy(callno);
1694         ast_mutex_lock(&iaxsl[callno]);
1695         return res;
1696 }
1697
1698 static void iax2_destroy(int callno)
1699 {
1700         struct chan_iax2_pvt *pvt;
1701         struct iax_frame *cur;
1702         struct ast_channel *owner;
1703
1704 retry:
1705         ast_mutex_lock(&iaxsl[callno]);
1706         pvt = iaxs[callno];
1707         gettimeofday(&lastused[callno], NULL);
1708         
1709         owner = pvt ? pvt->owner : NULL;
1710
1711         if (owner) {
1712                 if (ast_mutex_trylock(&owner->lock)) {
1713                         ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1714                         ast_mutex_unlock(&iaxsl[callno]);
1715                         usleep(1);
1716                         goto retry;
1717                 }
1718         }
1719         if (!owner)
1720                 iaxs[callno] = NULL;
1721         if (pvt) {
1722                 if (!owner)
1723                         pvt->owner = NULL;
1724                 iax2_destroy_helper(pvt);
1725                 if (pvt->bridgetrans)
1726                         ast_translator_free_path(pvt->bridgetrans);
1727                 pvt->bridgetrans = NULL;
1728
1729                 /* Already gone */
1730                 ast_set_flag(pvt, IAX_ALREADYGONE);     
1731
1732                 if (owner) {
1733                         /* If there's an owner, prod it to give up */
1734                         owner->_softhangup |= AST_SOFTHANGUP_DEV;
1735                         ast_queue_hangup(owner);
1736                 }
1737
1738                 for (cur = iaxq.head; cur ; cur = cur->next) {
1739                         /* Cancel any pending transmissions */
1740                         if (cur->callno == pvt->callno) 
1741                                 cur->retries = -1;
1742                 }
1743                 if (pvt->reg)
1744                         pvt->reg->callno = 0;
1745                 if (!owner) {
1746                         jb_frame frame;
1747                         if (pvt->vars) {
1748                             ast_variables_destroy(pvt->vars);
1749                             pvt->vars = NULL;
1750                         }
1751
1752                         while (jb_getall(pvt->jb, &frame) == JB_OK)
1753                                 iax2_frame_free(frame.data);
1754                         jb_destroy(pvt->jb);
1755                         free(pvt);
1756                 }
1757         }
1758         if (owner) {
1759                 ast_mutex_unlock(&owner->lock);
1760         }
1761         ast_mutex_unlock(&iaxsl[callno]);
1762         if (callno & 0x4000)
1763                 update_max_trunk();
1764 }
1765 static void iax2_destroy_nolock(int callno)
1766 {       
1767         /* Actually it's easier to unlock, kill it, and relock */
1768         ast_mutex_unlock(&iaxsl[callno]);
1769         iax2_destroy(callno);
1770         ast_mutex_lock(&iaxsl[callno]);
1771 }
1772
1773 static int update_packet(struct iax_frame *f)
1774 {
1775         /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1776         struct ast_iax2_full_hdr *fh = f->data;
1777         /* Mark this as a retransmission */
1778         fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1779         /* Update iseqno */
1780         f->iseqno = iaxs[f->callno]->iseqno;
1781         fh->iseqno = f->iseqno;
1782         return 0;
1783 }
1784
1785 static int attempt_transmit(void *data);
1786 static void __attempt_transmit(void *data)
1787 {
1788         /* Attempt to transmit the frame to the remote peer...
1789            Called without iaxsl held. */
1790         struct iax_frame *f = data;
1791         int freeme=0;
1792         int callno = f->callno;
1793         char iabuf[INET_ADDRSTRLEN];
1794         /* Make sure this call is still active */
1795         if (callno) 
1796                 ast_mutex_lock(&iaxsl[callno]);
1797         if (callno && iaxs[callno]) {
1798                 if ((f->retries < 0) /* Already ACK'd */ ||
1799                     (f->retries >= max_retries) /* Too many attempts */) {
1800                                 /* Record an error if we've transmitted too many times */
1801                                 if (f->retries >= max_retries) {
1802                                         if (f->transfer) {
1803                                                 /* Transfer timeout */
1804                                                 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1805                                         } else if (f->final) {
1806                                                 if (f->final) 
1807                                                         iax2_destroy_nolock(callno);
1808                                         } else {
1809                                                 if (iaxs[callno]->owner)
1810                                                         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);
1811                                                 iaxs[callno]->error = ETIMEDOUT;
1812                                                 if (iaxs[callno]->owner) {
1813                                                         struct ast_frame fr = { 0, };
1814                                                         /* Hangup the fd */
1815                                                         fr.frametype = AST_FRAME_CONTROL;
1816                                                         fr.subclass = AST_CONTROL_HANGUP;
1817                                                         iax2_queue_frame(callno, &fr);
1818                                                         /* Remember, owner could disappear */
1819                                                         if (iaxs[callno]->owner)
1820                                                                 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1821                                                 } else {
1822                                                         if (iaxs[callno]->reg) {
1823                                                                 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1824                                                                 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1825                                                                 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1826                                                         }
1827                                                         iax2_destroy_nolock(callno);
1828                                                 }
1829                                         }
1830
1831                                 }
1832                                 freeme++;
1833                 } else {
1834                         /* Update it if it needs it */
1835                         update_packet(f);
1836                         /* Attempt transmission */
1837                         send_packet(f);
1838                         f->retries++;
1839                         /* Try again later after 10 times as long */
1840                         f->retrytime *= 10;
1841                         if (f->retrytime > MAX_RETRY_TIME)
1842                                 f->retrytime = MAX_RETRY_TIME;
1843                         /* Transfer messages max out at one second */
1844                         if (f->transfer && (f->retrytime > 1000))
1845                                 f->retrytime = 1000;
1846                         f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1847                 }
1848         } else {
1849                 /* Make sure it gets freed */
1850                 f->retries = -1;
1851                 freeme++;
1852         }
1853         if (callno)
1854                 ast_mutex_unlock(&iaxsl[callno]);
1855         /* Do not try again */
1856         if (freeme) {
1857                 /* Don't attempt delivery, just remove it from the queue */
1858                 ast_mutex_lock(&iaxq.lock);
1859                 if (f->prev) 
1860                         f->prev->next = f->next;
1861                 else
1862                         iaxq.head = f->next;
1863                 if (f->next)
1864                         f->next->prev = f->prev;
1865                 else
1866                         iaxq.tail = f->prev;
1867                 iaxq.count--;
1868                 ast_mutex_unlock(&iaxq.lock);
1869                 f->retrans = -1;
1870                 /* Free the IAX frame */
1871                 iax2_frame_free(f);
1872         }
1873 }
1874
1875 static int attempt_transmit(void *data)
1876 {
1877 #ifdef SCHED_MULTITHREADED
1878         if (schedule_action(__attempt_transmit, data))
1879 #endif          
1880                 __attempt_transmit(data);
1881         return 0;
1882 }
1883
1884 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1885 {
1886         struct iax2_peer *peer;
1887
1888         if (argc != 4)
1889         return RESULT_SHOWUSAGE;
1890         if (!strcmp(argv[3],"all")) {
1891                 reload_config();
1892                 ast_cli(fd, "OK cache is flushed.\n");
1893         } else if ((peer = find_peer(argv[3], 0))) {
1894                 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1895                         ast_set_flag(peer, IAX_RTAUTOCLEAR);
1896                         expire_registry(peer);
1897                         ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1898                 } else {
1899                         ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1900                 }
1901         } else {
1902                 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1903         }
1904         
1905         return RESULT_SUCCESS;
1906 }
1907
1908 static int iax2_test_losspct(int fd, int argc, char *argv[])
1909 {
1910        if (argc != 4)
1911                return RESULT_SHOWUSAGE;
1912
1913        test_losspct = atoi(argv[3]);
1914
1915        return RESULT_SUCCESS;
1916 }
1917
1918 #ifdef IAXTESTS
1919 static int iax2_test_late(int fd, int argc, char *argv[])
1920 {
1921         if (argc != 4)
1922                 return RESULT_SHOWUSAGE;
1923
1924         test_late = atoi(argv[3]);
1925
1926         return RESULT_SUCCESS;
1927 }
1928
1929 static int iax2_test_resync(int fd, int argc, char *argv[])
1930 {
1931         if (argc != 4)
1932                 return RESULT_SHOWUSAGE;
1933
1934         test_resync = atoi(argv[3]);
1935
1936         return RESULT_SUCCESS;
1937 }
1938
1939 static int iax2_test_jitter(int fd, int argc, char *argv[])
1940 {
1941         if (argc < 4 || argc > 5)
1942                 return RESULT_SHOWUSAGE;
1943
1944         test_jit = atoi(argv[3]);
1945         if (argc == 5) 
1946                 test_jitpct = atoi(argv[4]);
1947
1948         return RESULT_SUCCESS;
1949 }
1950 #endif /* IAXTESTS */
1951
1952 /*! \brief  peer_status: Report Peer status in character string */
1953 /*      returns 1 if peer is online, -1 if unmonitored */
1954 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1955 {
1956         int res = 0;
1957         if (peer->maxms) {
1958                 if (peer->lastms < 0) {
1959                         ast_copy_string(status, "UNREACHABLE", statuslen);
1960                 } else if (peer->lastms > peer->maxms) {
1961                         snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
1962                         res = 1;
1963                 } else if (peer->lastms) {
1964                         snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
1965                         res = 1;
1966                 } else {
1967                         ast_copy_string(status, "UNKNOWN", statuslen);
1968                 }
1969         } else { 
1970                 ast_copy_string(status, "Unmonitored", statuslen);
1971                 res = -1;
1972         }
1973         return res;
1974 }
1975
1976 /*! \brief Show one peer in detail */
1977 static int iax2_show_peer(int fd, int argc, char *argv[])
1978 {
1979         char status[30];
1980         char cbuf[256];
1981         char iabuf[INET_ADDRSTRLEN];
1982         struct iax2_peer *peer;
1983         char codec_buf[512];
1984         int x = 0, codec = 0, load_realtime = 0;
1985
1986         if (argc < 4)
1987                 return RESULT_SHOWUSAGE;
1988
1989         load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1990
1991         peer = find_peer(argv[3], load_realtime);
1992         if (peer) {
1993                 ast_cli(fd,"\n\n");
1994                 ast_cli(fd, "  * Name       : %s\n", peer->name);
1995                 ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1996                 ast_cli(fd, "  Context      : %s\n", peer->context);
1997                 ast_cli(fd, "  Mailbox      : %s\n", peer->mailbox);
1998                 ast_cli(fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1999                 ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2000                 ast_cli(fd, "  Expire       : %d\n", peer->expire);
2001                 ast_cli(fd, "  ACL          : %s\n", (peer->ha?"Yes":"No"));
2002                 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));
2003                 ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2004                 ast_cli(fd, "  Username     : %s\n", peer->username);
2005                 ast_cli(fd, "  Codecs       : ");
2006                 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2007                 ast_cli(fd, "%s\n", codec_buf);
2008
2009                 ast_cli(fd, "  Codec Order  : (");
2010                 for(x = 0; x < 32 ; x++) {
2011                         codec = ast_codec_pref_index(&peer->prefs,x);
2012                         if(!codec)
2013                                 break;
2014                         ast_cli(fd, "%s", ast_getformatname(codec));
2015                         if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2016                                 ast_cli(fd, "|");
2017                 }
2018
2019                 if (!x)
2020                         ast_cli(fd, "none");
2021                 ast_cli(fd, ")\n");
2022
2023                 ast_cli(fd, "  Status       : ");
2024                 peer_status(peer, status, sizeof(status));      
2025                 ast_cli(fd, "%s\n",status);
2026                 ast_cli(fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2027                 ast_cli(fd,"\n");
2028                 if (ast_test_flag(peer, IAX_TEMPONLY))
2029                         destroy_peer(peer);
2030         } else {
2031                 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2032                 ast_cli(fd,"\n");
2033         }
2034
2035         return RESULT_SUCCESS;
2036 }
2037
2038 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2039 {
2040         int which = 0;
2041         struct iax2_peer *p = NULL;
2042         char *res = NULL;
2043         int wordlen = strlen(word);
2044
2045         /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2046         if (pos == 3) {
2047                 AST_LIST_LOCK(&peers);
2048                 AST_LIST_TRAVERSE(&peers, p, entry) {
2049                         if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2050                                 res = ast_strdup(p->name);
2051                                 break;
2052                         }
2053                 }
2054                 AST_LIST_UNLOCK(&peers);
2055         }
2056
2057         return res;
2058 }
2059
2060 static int iax2_show_stats(int fd, int argc, char *argv[])
2061 {
2062         struct iax_frame *cur;
2063         int cnt = 0, dead=0, final=0;
2064         if (argc != 3)
2065                 return RESULT_SHOWUSAGE;
2066         for (cur = iaxq.head; cur ; cur = cur->next) {
2067                 if (cur->retries < 0)
2068                         dead++;
2069                 if (cur->final)
2070                         final++;
2071                 cnt++;
2072         }
2073         ast_cli(fd, "    IAX Statistics\n");
2074         ast_cli(fd, "---------------------\n");
2075         ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2076         ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
2077         return RESULT_SUCCESS;
2078 }
2079
2080 static int iax2_show_cache(int fd, int argc, char *argv[])
2081 {
2082         struct iax2_dpcache *dp;
2083         char tmp[1024], *pc;
2084         int s;
2085         int x,y;
2086         struct timeval tv;
2087         gettimeofday(&tv, NULL);
2088         ast_mutex_lock(&dpcache_lock);
2089         dp = dpcache;
2090         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2091         while(dp) {
2092                 s = dp->expiry.tv_sec - tv.tv_sec;
2093                 tmp[0] = '\0';
2094                 if (dp->flags & CACHE_FLAG_EXISTS)
2095                         strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2096                 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2097                         strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2098                 if (dp->flags & CACHE_FLAG_CANEXIST)
2099                         strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2100                 if (dp->flags & CACHE_FLAG_PENDING)
2101                         strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2102                 if (dp->flags & CACHE_FLAG_TIMEOUT)
2103                         strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2104                 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2105                         strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2106                 if (dp->flags & CACHE_FLAG_MATCHMORE)
2107                         strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2108                 if (dp->flags & CACHE_FLAG_UNKNOWN)
2109                         strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2110                 /* Trim trailing pipe */
2111                 if (!ast_strlen_zero(tmp))
2112                         tmp[strlen(tmp) - 1] = '\0';
2113                 else
2114                         ast_copy_string(tmp, "(none)", sizeof(tmp));
2115                 y=0;
2116                 pc = strchr(dp->peercontext, '@');
2117                 if (!pc)
2118                         pc = dp->peercontext;
2119                 else
2120                         pc++;
2121                 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2122                         if (dp->waiters[x] > -1)
2123                                 y++;
2124                 if (s > 0)
2125                         ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2126                 else
2127                         ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2128                 dp = dp->next;
2129         }
2130         ast_mutex_unlock(&dpcache_lock);
2131         return RESULT_SUCCESS;
2132 }
2133
2134 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2135
2136 #ifdef BRIDGE_OPTIMIZATION
2137 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2138
2139 static int forward_delivery(struct iax_frame *fr)
2140 {
2141         struct chan_iax2_pvt *p1, *p2;
2142         char iabuf[INET_ADDRSTRLEN];
2143         int res, orig_ts;
2144
2145         p1 = iaxs[fr->callno];
2146         p2 = iaxs[p1->bridgecallno];
2147         if (!p1)
2148                 return -1;
2149         if (!p2)
2150                 return -1;
2151
2152         if (option_debug)
2153                 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2154                                 fr->ts,
2155                                 p1->callno, p1->peercallno,
2156                                 p2->callno, p2->peercallno,
2157                                 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2158                                 ntohs(p2->addr.sin_port));
2159
2160         /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2161            This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2162            send full frame on timestamp wrap when doing optimized bridging
2163            (actually current code STILL doesn't)
2164         */
2165         if (fr->ts + 50000 <= p1->last) {
2166                 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2167                 if (option_debug)
2168                         ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2169         }
2170
2171         /* Send with timestamp adjusted to the origin of the outbound leg */
2172         /* But don't destroy inbound timestamp still needed later to set "last" */
2173         orig_ts = fr->ts;
2174         fr->ts = calc_fakestamp(p1, p2, fr->ts);
2175         res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2176         fr->ts = orig_ts;
2177         return res;
2178 }
2179 #endif
2180
2181 static void unwrap_timestamp(struct iax_frame *fr)
2182 {
2183         int x;
2184
2185         if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2186                 x = fr->ts - iaxs[fr->callno]->last;
2187                 if (x < -50000) {
2188                         /* Sudden big jump backwards in timestamp:
2189                            What likely happened here is that miniframe timestamp has circled but we haven't
2190                            gotten the update from the main packet.  We'll just pretend that we did, and
2191                            update the timestamp appropriately. */
2192                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2193                         if (option_debug && iaxdebug)
2194                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2195                 }
2196                 if (x > 50000) {
2197                         /* Sudden apparent big jump forwards in timestamp:
2198                            What's likely happened is this is an old miniframe belonging to the previous
2199                            top-16-bit timestamp that has turned up out of order.
2200                            Adjust the timestamp appropriately. */
2201                         fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2202                         if (option_debug && iaxdebug)
2203                                 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2204                 }
2205         }
2206 }
2207
2208 static int get_from_jb(void *p);
2209
2210 static void update_jbsched(struct chan_iax2_pvt *pvt)
2211 {
2212         int when;
2213         
2214         when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2215         
2216         /*    fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2217         
2218         when = jb_next(pvt->jb) - when;
2219         /*   fprintf(stderr, "when = %d\n", when); */
2220         
2221         if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2222         
2223         if(when <= 0) {
2224                 /* XXX should really just empty until when > 0.. */
2225                 when = 1;
2226         }
2227         
2228         pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2229         
2230         /* Signal scheduler thread */
2231         signal_condition(&sched_lock, &sched_cond);
2232 }
2233
2234 static void __get_from_jb(void *p) 
2235 {
2236         int callno = PTR_TO_CALLNO(p);
2237         struct chan_iax2_pvt *pvt = iaxs[callno];
2238         struct iax_frame *fr;
2239         jb_frame frame;
2240         int ret;
2241         long now;
2242         long next;
2243         struct timeval tv;
2244         
2245         /* Make sure we have a valid private structure before going on */
2246         ast_mutex_lock(&iaxsl[callno]);
2247         pvt = iaxs[callno];
2248         if (!pvt) {
2249                 /* No go! */
2250                 ast_mutex_unlock(&iaxsl[callno]);
2251                 return;
2252         }
2253
2254         /*  fprintf(stderr, "get_from_jb called\n"); */
2255         pvt->jbid = -1;
2256         
2257         gettimeofday(&tv,NULL);
2258         /* round up a millisecond since ast_sched_runq does; */
2259         /* prevents us from spinning while waiting for our now */
2260         /* to catch up with runq's now */
2261         tv.tv_usec += 1000;
2262         
2263         now = ast_tvdiff_ms(tv, pvt->rxcore);
2264         
2265         if(now >= (next = jb_next(pvt->jb))) {
2266                 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2267                 switch(ret) {
2268                 case JB_OK:
2269                         /*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); */
2270                         fr = frame.data;
2271                         __do_deliver(fr);
2272                         break;
2273                 case JB_INTERP:
2274                 {
2275                         struct ast_frame af;
2276                         
2277                         /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2278                         
2279                         /* create an interpolation frame */
2280                         /*fprintf(stderr, "Making Interpolation frame\n"); */
2281                         af.frametype = AST_FRAME_VOICE;
2282                         af.subclass = pvt->voiceformat;
2283                         af.datalen  = 0;
2284                         af.samples  = frame.ms * 8;
2285                         af.mallocd  = 0;
2286                         af.src  = "IAX2 JB interpolation";
2287                         af.data  = NULL;
2288                         af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2289                         af.offset=AST_FRIENDLY_OFFSET;
2290                         
2291                         /* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2292                          * which we'd need to malloc, and then it would free it.  That seems like a drag */
2293                         if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2294                                 iax2_queue_frame(callno, &af);
2295                 }
2296                 break;
2297                 case JB_DROP:
2298                         /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2299                         iax2_frame_free(frame.data);
2300                         break;
2301                 case JB_NOFRAME:
2302                 case JB_EMPTY:
2303                         /* do nothing */
2304                         break;
2305                 default:
2306                         /* shouldn't happen */
2307                         break;
2308                 }
2309         }
2310         update_jbsched(pvt);
2311         ast_mutex_unlock(&iaxsl[callno]);
2312 }
2313
2314 static int get_from_jb(void *data)
2315 {
2316 #ifdef SCHED_MULTITHREADED
2317         if (schedule_action(__get_from_jb, data))
2318 #endif          
2319                 __get_from_jb(data);
2320         return 0;
2321 }
2322
2323 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2324 {
2325         int type, len;
2326         int ret;
2327         int needfree = 0;
2328
2329         /* Attempt to recover wrapped timestamps */
2330         unwrap_timestamp(fr);
2331         
2332
2333         /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2334         if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2335                 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2336         else {
2337 #if 0
2338                 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2339 #endif
2340                 fr->af.delivery = ast_tv(0,0);
2341         }
2342
2343         type = JB_TYPE_CONTROL;
2344         len = 0;
2345
2346         if(fr->af.frametype == AST_FRAME_VOICE) {
2347                 type = JB_TYPE_VOICE;
2348                 len = ast_codec_get_samples(&fr->af) / 8;
2349         } else if(fr->af.frametype == AST_FRAME_CNG) {
2350                 type = JB_TYPE_SILENCE;
2351         }
2352
2353         if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2354                 if (tsout)
2355                         *tsout = fr->ts;
2356                 __do_deliver(fr);
2357                 return -1;
2358         }
2359
2360         /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2361          * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2362         if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2363             iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2364             (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2365                 jb_frame frame;
2366
2367                 /* deliver any frames in the jb */
2368                 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2369                         __do_deliver(frame.data);
2370
2371                 jb_reset(iaxs[fr->callno]->jb);
2372
2373                 if (iaxs[fr->callno]->jbid > -1)
2374                         ast_sched_del(sched, iaxs[fr->callno]->jbid);
2375
2376                 iaxs[fr->callno]->jbid = -1;
2377
2378                 /* deliver this frame now */
2379                 if (tsout)
2380                         *tsout = fr->ts;
2381                 __do_deliver(fr);
2382                 return -1;
2383         }
2384
2385         /* insert into jitterbuffer */
2386         /* TODO: Perhaps we could act immediately if it's not droppable and late */
2387         ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2388                         calc_rxstamp(iaxs[fr->callno],fr->ts));
2389         if (ret == JB_DROP) {
2390                 needfree++;
2391         } else if (ret == JB_SCHED) {
2392                 update_jbsched(iaxs[fr->callno]);
2393         }
2394         if (tsout)
2395                 *tsout = fr->ts;
2396         if (needfree) {
2397                 /* Free our iax frame */
2398                 iax2_frame_free(fr);
2399                 return -1;
2400         }
2401         return 0;
2402 }
2403
2404 static int iax2_transmit(struct iax_frame *fr)
2405 {
2406         /* Lock the queue and place this packet at the end */
2407         fr->next = NULL;
2408         fr->prev = NULL;
2409         /* By setting this to 0, the network thread will send it for us, and
2410            queue retransmission if necessary */
2411         fr->sentyet = 0;
2412         ast_mutex_lock(&iaxq.lock);
2413         if (!iaxq.head) {
2414                 /* Empty queue */
2415                 iaxq.head = fr;
2416                 iaxq.tail = fr;
2417         } else {
2418                 /* Double link */
2419                 iaxq.tail->next = fr;
2420                 fr->prev = iaxq.tail;
2421                 iaxq.tail = fr;
2422         }
2423         iaxq.count++;
2424         ast_mutex_unlock(&iaxq.lock);
2425         /* Wake up the network and scheduler thread */
2426         pthread_kill(netthreadid, SIGURG);
2427         signal_condition(&sched_lock, &sched_cond);
2428         return 0;
2429 }
2430
2431
2432
2433 static int iax2_digit(struct ast_channel *c, char digit)
2434 {
2435         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2436 }
2437
2438 static int iax2_sendtext(struct ast_channel *c, const char *text)
2439 {
2440         
2441         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2442                 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2443 }
2444
2445 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2446 {
2447         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2448 }
2449
2450 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2451 {
2452         return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2453 }
2454
2455 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2456 {
2457         unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2458         ast_mutex_lock(&iaxsl[callno]);
2459         if (iaxs[callno])
2460                 iaxs[callno]->owner = newchan;
2461         else
2462                 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2463         ast_mutex_unlock(&iaxsl[callno]);
2464         return 0;
2465 }
2466
2467 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2468 {
2469         struct ast_variable *var;
2470         struct ast_variable *tmp;
2471         struct iax2_peer *peer=NULL;
2472         time_t regseconds = 0, nowtime;
2473         int dynamic=0;
2474
2475         if (peername)
2476                 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2477         else {
2478                 char iabuf[INET_ADDRSTRLEN];
2479                 char porta[25];
2480                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
2481                 sprintf(porta, "%d", ntohs(sin->sin_port));
2482                 var = ast_load_realtime("iaxpeers", "ipaddr", iabuf, "port", porta, NULL);
2483                 if (var) {
2484                         /* We'll need the peer name in order to build the structure! */
2485                         tmp = var;
2486                         while(tmp) {
2487                                 if (!strcasecmp(tmp->name, "name"))
2488                                         peername = tmp->value;
2489                                 tmp = tmp->next;
2490                         }
2491                 }
2492         }
2493         if (!var)
2494                 return NULL;
2495
2496         peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2497         
2498         if (!peer)
2499                 return NULL;
2500
2501         tmp = var;
2502         while(tmp) {
2503                 /* Make sure it's not a user only... */
2504                 if (!strcasecmp(tmp->name, "type")) {
2505                         if (strcasecmp(tmp->value, "friend") &&
2506                             strcasecmp(tmp->value, "peer")) {
2507                                 /* Whoops, we weren't supposed to exist! */
2508                                 destroy_peer(peer);
2509                                 peer = NULL;
2510                                 break;
2511                         } 
2512                 } else if (!strcasecmp(tmp->name, "regseconds")) {
2513                         ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2514                 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2515                         inet_aton(tmp->value, &(peer->addr.sin_addr));
2516                 } else if (!strcasecmp(tmp->name, "port")) {
2517                         peer->addr.sin_port = htons(atoi(tmp->value));
2518                 } else if (!strcasecmp(tmp->name, "host")) {
2519                         if (!strcasecmp(tmp->value, "dynamic"))
2520                                 dynamic = 1;
2521                 }
2522                 tmp = tmp->next;
2523         }
2524         if (!peer)
2525                 return NULL;
2526
2527         ast_variables_destroy(var);
2528
2529         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2530                 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2531                 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2532                         if (peer->expire > -1)
2533                                 ast_sched_del(sched, peer->expire);
2534                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2535                 }
2536                 AST_LIST_LOCK(&peers);
2537                 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2538                 AST_LIST_UNLOCK(&peers);
2539                 if (ast_test_flag(peer, IAX_DYNAMIC))
2540                         reg_source_db(peer);
2541         } else {
2542                 ast_set_flag(peer, IAX_TEMPONLY);       
2543         }
2544
2545         if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2546                 time(&nowtime);
2547                 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2548                         memset(&peer->addr, 0, sizeof(peer->addr));
2549                         if (option_debug)
2550                                 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2551                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2552                 }
2553                 else {
2554                         if (option_debug)
2555                                 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2556                                                 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2557                 }
2558         }
2559
2560         return peer;
2561 }
2562
2563 static struct iax2_user *realtime_user(const char *username)
2564 {
2565         struct ast_variable *var;
2566         struct ast_variable *tmp;
2567         struct iax2_user *user=NULL;
2568
2569         var = ast_load_realtime("iaxusers", "name", username, NULL);
2570         if (!var)
2571                 return NULL;
2572
2573         tmp = var;
2574         while(tmp) {
2575                 /* Make sure it's not a peer only... */
2576                 if (!strcasecmp(tmp->name, "type")) {
2577                         if (strcasecmp(tmp->value, "friend") &&
2578                             strcasecmp(tmp->value, "user")) {
2579                                 return NULL;
2580                         } 
2581                 }
2582                 tmp = tmp->next;
2583         }
2584
2585         user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2586         if (!user)
2587                 return NULL;
2588
2589         ast_variables_destroy(var);
2590
2591         if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2592                 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2593                 AST_LIST_LOCK(&users);
2594                 AST_LIST_INSERT_HEAD(&users, user, entry);
2595                 AST_LIST_UNLOCK(&users);
2596         } else {
2597                 ast_set_flag(user, IAX_TEMPONLY);       
2598         }
2599
2600         return user;
2601 }
2602
2603 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2604 {
2605         char port[10];
2606         char ipaddr[20];
2607         char regseconds[20];
2608         time_t nowtime;
2609         
2610         time(&nowtime);
2611         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);
2612         ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2613         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2614         ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2615 }
2616
2617 struct create_addr_info {
2618         int capability;
2619         unsigned int flags;
2620         int maxtime;
2621         int encmethods;
2622         int found;
2623         int sockfd;
2624         char username[80];
2625         char secret[80];
2626         char outkey[80];
2627         char timezone[80];
2628         char prefs[32];
2629         char context[AST_MAX_CONTEXT];
2630         char peercontext[AST_MAX_CONTEXT];
2631 };
2632
2633 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2634 {
2635         struct ast_hostent ahp;
2636         struct hostent *hp;
2637         struct iax2_peer *peer;
2638
2639         ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2640         cai->sockfd = defaultsockfd;
2641         cai->maxtime = 0;
2642         sin->sin_family = AF_INET;
2643
2644         if (!(peer = find_peer(peername, 1))) {
2645                 cai->found = 0;
2646
2647                 hp = ast_gethostbyname(peername, &ahp);
2648                 if (hp) {
2649                         memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2650                         sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2651                         /* use global iax prefs for unknown peer/user */
2652                         ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2653                         return 0;
2654                 } else {
2655                         ast_log(LOG_WARNING, "No such host: %s\n", peername);
2656                         return -1;
2657                 }
2658         }
2659
2660         cai->found = 1;
2661         
2662         /* if the peer has no address (current or default), return failure */
2663         if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2664                 if (ast_test_flag(peer, IAX_TEMPONLY))
2665                         destroy_peer(peer);
2666                 return -1;
2667         }
2668
2669         /* if the peer is being monitored and is currently unreachable, return failure */
2670         if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2671                 if (ast_test_flag(peer, IAX_TEMPONLY))
2672                         destroy_peer(peer);
2673                 return -1;
2674         }
2675
2676         ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2677         cai->maxtime = peer->maxms;
2678         cai->capability = peer->capability;
2679         cai->encmethods = peer->encmethods;
2680         cai->sockfd = peer->sockfd;
2681         ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2682         ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2683         ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2684         ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2685         ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2686         ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2687         if (ast_strlen_zero(peer->dbsecret)) {
2688                 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2689         } else {
2690                 char *family;
2691                 char *key = NULL;
2692
2693                 family = ast_strdupa(peer->dbsecret);
2694                 key = strchr(family, '/');
2695                 if (key)
2696                         *key++ = '\0';
2697                 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2698                         ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2699                         if (ast_test_flag(peer, IAX_TEMPONLY))
2700                                 destroy_peer(peer);
2701                         return -1;
2702                 }
2703         }
2704
2705         if (peer->addr.sin_addr.s_addr) {
2706                 sin->sin_addr = peer->addr.sin_addr;
2707                 sin->sin_port = peer->addr.sin_port;
2708         } else {
2709                 sin->sin_addr = peer->defaddr.sin_addr;
2710                 sin->sin_port = peer->defaddr.sin_port;
2711         }
2712
2713         if (ast_test_flag(peer, IAX_TEMPONLY))
2714                 destroy_peer(peer);
2715
2716         return 0;
2717 }
2718
2719 static void __auto_congest(void *nothing)
2720 {
2721         int callno = PTR_TO_CALLNO(nothing);
2722         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2723         ast_mutex_lock(&iaxsl[callno]);
2724         if (iaxs[callno]) {
2725                 iaxs[callno]->initid = -1;
2726                 iax2_queue_frame(callno, &f);
2727                 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2728         }
2729         ast_mutex_unlock(&iaxsl[callno]);
2730 }
2731
2732 static int auto_congest(void *data)
2733 {
2734 #ifdef SCHED_MULTITHREADED
2735         if (schedule_action(__auto_congest, data))
2736 #endif          
2737                 __auto_congest(data);
2738         return 0;
2739 }
2740
2741 static unsigned int iax2_datetime(char *tz)
2742 {
2743         time_t t;
2744         struct tm tm;
2745         unsigned int tmp;
2746         time(&t);
2747         localtime_r(&t, &tm);
2748         if (!ast_strlen_zero(tz))
2749                 ast_localtime(&t, &tm, tz);
2750         tmp  = (tm.tm_sec >> 1) & 0x1f;                 /* 5 bits of seconds */
2751         tmp |= (tm.tm_min & 0x3f) << 5;                 /* 6 bits of minutes */
2752         tmp |= (tm.tm_hour & 0x1f) << 11;               /* 5 bits of hours */
2753         tmp |= (tm.tm_mday & 0x1f) << 16;               /* 5 bits of day of month */
2754         tmp |= ((tm.tm_mon + 1) & 0xf) << 21;           /* 4 bits of month */
2755         tmp |= ((tm.tm_year - 100) & 0x7f) << 25;       /* 7 bits of year */
2756         return tmp;
2757 }
2758
2759 struct parsed_dial_string {
2760         char *username;
2761         char *password;
2762         char *key;
2763         char *peer;
2764         char *port;
2765         char *exten;
2766         char *context;
2767         char *options;
2768 };
2769
2770 /*!
2771  * \brief Parses an IAX dial string into its component parts.
2772  * \param data the string to be parsed
2773  * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2774  * \return nothing
2775  *
2776  * This function parses the string and fills the structure
2777  * with pointers to its component parts. The input string
2778  * will be modified.
2779  *
2780  * \note This function supports both plaintext passwords and RSA
2781  * key names; if the password string is formatted as '[keyname]',
2782  * then the keyname will be placed into the key field, and the
2783  * password field will be set to NULL.
2784  *
2785  * \note The dial string format is:
2786  *       [username[:password]@]peer[:port][/exten[@@context]][/options]
2787  */
2788 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2789 {
2790         if (ast_strlen_zero(data))
2791                 return;
2792
2793         pds->peer = strsep(&data, "/");
2794         pds->exten = strsep(&data, "/");
2795         pds->options = data;
2796
2797         if (pds->exten) {
2798                 data = pds->exten;
2799                 pds->exten = strsep(&data, "@");
2800                 pds->context = data;
2801         }
2802
2803         if (strchr(pds->peer, '@')) {
2804                 data = pds->peer;
2805                 pds->username = strsep(&data, "@");
2806                 pds->peer = data;
2807         }
2808
2809         if (pds->username) {
2810                 data = pds->username;
2811                 pds->username = strsep(&data, ":");
2812                 pds->password = data;
2813         }
2814
2815         data = pds->peer;
2816         pds->peer = strsep(&data, ":");
2817         pds->port = data;
2818
2819         /* check for a key name wrapped in [] in the secret position, if found,
2820            move it to the key field instead
2821         */
2822         if (pds->password && (pds->password[0] == '[')) {
2823                 pds->key = ast_strip_quoted(pds->password, "[", "]");
2824                 pds->password = NULL;
2825         }
2826 }
2827
2828 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2829 {
2830         struct sockaddr_in sin;
2831         char *l=NULL, *n=NULL, *tmpstr;
2832         struct iax_ie_data ied;
2833         char *defaultrdest = "s";
2834         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2835         struct parsed_dial_string pds;
2836         struct create_addr_info cai;
2837
2838         if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2839                 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2840                 return -1;
2841         }
2842
2843         memset(&cai, 0, sizeof(cai));
2844         cai.encmethods = iax2_encryption;
2845
2846         memset(&pds, 0, sizeof(pds));
2847         tmpstr = ast_strdupa(dest);
2848         parse_dial_string(tmpstr, &pds);
2849
2850         if (!pds.exten)
2851                 pds.exten = defaultrdest;
2852
2853         if (create_addr(pds.peer, &sin, &cai)) {
2854                 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2855                 return -1;
2856         }
2857
2858         if (!pds.username && !ast_strlen_zero(cai.username))
2859                 pds.username = cai.username;
2860         if (!pds.password && !ast_strlen_zero(cai.secret))
2861                 pds.password = cai.secret;
2862         if (!pds.key && !ast_strlen_zero(cai.outkey))
2863                 pds.key = cai.outkey;
2864         if (!pds.context && !ast_strlen_zero(cai.peercontext))
2865                 pds.context = cai.peercontext;
2866
2867         /* Keep track of the context for outgoing calls too */
2868         ast_copy_string(c->context, cai.context, sizeof(c->context));
2869
2870         if (pds.port)
2871                 sin.sin_port = htons(atoi(pds.port));
2872
2873         l = c->cid.cid_num;
2874         n = c->cid.cid_name;
2875
2876         /* Now build request */ 
2877         memset(&ied, 0, sizeof(ied));
2878
2879         /* On new call, first IE MUST be IAX version of caller */
2880         iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2881         iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2882         if (pds.options && strchr(pds.options, 'a')) {
2883                 /* Request auto answer */
2884                 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2885         }
2886
2887         iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2888
2889         if (l) {
2890                 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2891                 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2892         } else {
2893                 if (n)
2894                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2895                 else
2896                         iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2897         }
2898
2899         iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2900         iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2901
2902         if (n)
2903                 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2904         if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2905                 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2906
2907         if (!ast_strlen_zero(c->language))
2908                 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2909         if (!ast_strlen_zero(c->cid.cid_dnid))
2910                 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2911         if (!ast_strlen_zero(c->cid.cid_rdnis))
2912                 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2913
2914         if (pds.context)
2915                 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2916
2917         if (pds.username)
2918                 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2919
2920         if (cai.encmethods)
2921                 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2922
2923         ast_mutex_lock(&iaxsl[callno]);
2924
2925         if (!ast_strlen_zero(c->context))
2926                 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2927
2928         if (pds.username)
2929                 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2930
2931         iaxs[callno]->encmethods = cai.encmethods;
2932
2933         if (pds.key)
2934                 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2935         if (pds.password)
2936                 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2937
2938         iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2939         iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2940         iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2941         iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2942
2943         if (iaxs[callno]->maxtime) {
2944                 /* Initialize pingtime and auto-congest time */
2945                 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2946                 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2947         } else if (autokill) {
2948                 iaxs[callno]->pingtime = autokill / 2;
2949                 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2950         }
2951
2952         /* Transmit the string in a "NEW" request */
2953         send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2954
2955         ast_mutex_unlock(&iaxsl[callno]);
2956         ast_setstate(c, AST_STATE_RINGING);
2957         
2958         return 0;
2959 }
2960
2961 static int iax2_hangup(struct ast_channel *c) 
2962 {
2963         unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2964         int alreadygone;
2965         struct iax_ie_data ied;
2966         memset(&ied, 0, sizeof(ied));
2967         ast_mutex_lock(&iaxsl[callno]);
2968         if (callno && iaxs[callno]) {
2969                 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2970                 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2971                 /* Send the hangup unless we have had a transmission error or are already gone */
2972                 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2973                 if (!iaxs[callno]->error && !alreadygone) 
2974                         send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2975                 /* Explicitly predestroy it */
2976                 iax2_predestroy_nolock(callno);
2977                 /* If we were already gone to begin with, destroy us now */
2978                 if (alreadygone) {
2979                         ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2980                         iax2_destroy_nolock(callno);
2981                 }
2982         }
2983         ast_mutex_unlock(&iaxsl[callno]);
2984         if (option_verbose > 2) 
2985                 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2986         return 0;
2987 }
2988
2989 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2990 {
2991         struct ast_option_header *h;
2992         int res;
2993
2994         switch (option) {
2995         case AST_OPTION_TXGAIN:
2996         case AST_OPTION_RXGAIN:
2997                 /* these two cannot be sent, because they require a result */
2998                 errno = ENOSYS;
2999                 return -1;
3000         default:
3001                 if (!(h = ast_malloc(datalen + sizeof(*h))))
3002                         return -1;
3003
3004                 h->flag = AST_OPTION_FLAG_REQUEST;
3005                 h->option = htons(option);
3006                 memcpy(h->data, data, datalen);
3007                 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3008                                           AST_CONTROL_OPTION, 0, (unsigned char *) h,
3009                                           datalen + sizeof(*h), -1);
3010                 free(h);
3011                 return res;
3012         }
3013 }
3014
3015 static struct ast_frame *iax2_read(struct ast_channel *c) 
3016 {
3017         ast_log(LOG_NOTICE, "I should never be called!\n");
3018         return &ast_null_frame;
3019 }
3020
3021 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3022 {
3023         int res;
3024         struct iax_ie_data ied0;
3025         struct iax_ie_data ied1;
3026         unsigned int transferid = (unsigned int)ast_random();
3027         memset(&ied0, 0, sizeof(ied0));
3028         iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3029         iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3030         iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3031
3032         memset(&ied1, 0, sizeof(ied1));
3033         iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3034         iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3035         iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3036         
3037         res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3038         if (res)
3039                 return -1;
3040         res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3041         if (res)
3042                 return -1;
3043         iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3044         iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3045         return 0;
3046 }
3047
3048 static void lock_both(unsigned short callno0, unsigned short callno1)
3049 {
3050         ast_mutex_lock(&iaxsl[callno0]);
3051         while (ast_mutex_trylock(&iaxsl[callno1])) {
3052                 ast_mutex_unlock(&iaxsl[callno0]);
3053                 usleep(10);
3054                 ast_mutex_lock(&iaxsl[callno0]);
3055         }
3056 }
3057
3058 static void unlock_both(unsigned short callno0, unsigned short callno1)
3059 {
3060         ast_mutex_unlock(&iaxsl[callno1]);
3061         ast_mutex_unlock(&iaxsl[callno0]);
3062 }
3063
3064 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)
3065 {
3066         struct ast_channel *cs[3];
3067         struct ast_channel *who, *other;
3068         int to = -1;
3069         int res = -1;
3070         int transferstarted=0;
3071         struct ast_frame *f;
3072         unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3073         unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3074         struct timeval waittimer = {0, 0}, tv;
3075
3076         lock_both(callno0, callno1);
3077         /* Put them in native bridge mode */
3078         if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3079                 iaxs[callno0]->bridgecallno = callno1;
3080                 iaxs[callno1]->bridgecallno = callno0;
3081         }
3082         unlock_both(callno0, callno1);
3083
3084         /* If not, try to bridge until we can execute a transfer, if we can */
3085         cs[0] = c0;
3086         cs[1] = c1;
3087         for (/* ever */;;) {
3088                 /* Check in case we got masqueraded into */
3089                 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3090                         if (option_verbose > 2)
3091                                 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3092                         /* Remove from native mode */
3093                         if (c0->tech == &iax2_tech) {
3094                                 ast_mutex_lock(&iaxsl[callno0]);
3095                                 iaxs[callno0]->bridgecallno = 0;
3096                                 ast_mutex_unlock(&iaxsl[callno0]);
3097                         }
3098                         if (c1->tech == &iax2_tech) {
3099                                 ast_mutex_lock(&iaxsl[callno1]);
3100                                 iaxs[callno1]->bridgecallno = 0;
3101                                 ast_mutex_unlock(&iaxsl[callno1]);
3102                         }
3103                         return AST_BRIDGE_FAILED_NOWARN;
3104                 }
3105                 if (c0->nativeformats != c1->nativeformats) {
3106                         if (option_verbose > 2) {
3107                                 char buf0[255];
3108                                 char buf1[255];
3109                                 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3110                                 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3111                                 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3112                         }
3113                         /* Remove from native mode */
3114                         lock_both(callno0, callno1);
3115                         iaxs[callno0]->bridgecallno = 0;
3116                         iaxs[callno1]->bridgecallno = 0;
3117                         unlock_both(callno0, callno1);
3118                         return AST_BRIDGE_FAILED_NOWARN;
3119                 }
3120                 /* check if transfered and if we really want native bridging */
3121                 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3122                         /* Try the transfer */
3123                         if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3124                                                         ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3125                                 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3126                         transferstarted = 1;
3127                 }
3128                 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3129                         /* Call has been transferred.  We're no longer involved */
3130                         gettimeofday(&tv, NULL);
3131                         if (ast_tvzero(waittimer)) {
3132                                 waittimer = tv;
3133                         } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3134                                 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3135                                 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3136                                 *fo = NULL;
3137                                 *rc = c0;
3138                                 res = AST_BRIDGE_COMPLETE;
3139                                 break;
3140                         }
3141                 }
3142                 to = 1000;
3143                 who = ast_waitfor_n(cs, 2, &to);
3144                 if (timeoutms > -1) {
3145                         timeoutms -= (1000 - to);
3146                         if (timeoutms < 0)
3147                                 timeoutms = 0;
3148                 }
3149                 if (!who) {
3150                         if (!timeoutms) {
3151                                 res = AST_BRIDGE_RETRY;
3152                                 break;
3153                         }
3154                         if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3155                                 res = AST_BRIDGE_FAILED;
3156                                 break;
3157                         }
3158                         continue;
3159                 }
3160                 f = ast_read(who);
3161                 if (!f) {
3162                         *fo = NULL;