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