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