2 * Asterisk -- A telephony toolkit for Linux.
4 * Implementation of Inter-Asterisk eXchange Version 2
6 * Copyright (C) 2003 - 2005, Digium, Inc.
8 * Mark Spencer <markster@digium.com>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
16 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
18 #include "asterisk/lock.h"
19 #include "asterisk/frame.h"
20 #include "asterisk/channel.h"
21 #include "asterisk/logger.h"
22 #include "asterisk/module.h"
23 #include "asterisk/pbx.h"
24 #include "asterisk/sched.h"
25 #include "asterisk/io.h"
26 #include "asterisk/config.h"
27 #include "asterisk/options.h"
28 #include "asterisk/cli.h"
29 #include "asterisk/translate.h"
30 #include "asterisk/md5.h"
31 #include "asterisk/cdr.h"
32 #include "asterisk/crypto.h"
33 #include "asterisk/acl.h"
34 #include "asterisk/manager.h"
35 #include "asterisk/callerid.h"
36 #include "asterisk/app.h"
37 #include "asterisk/astdb.h"
38 #include "asterisk/musiconhold.h"
39 #include "asterisk/features.h"
40 #include "asterisk/utils.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/localtime.h"
43 #include "asterisk/aes.h"
44 #include "asterisk/dnsmgr.h"
46 #include <arpa/inet.h>
48 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
53 #include <sys/signal.h>
62 #include <sys/types.h>
66 #include <sys/ioctl.h>
68 #include <linux/zaptel.h>
71 #endif /* __linux__ */
74 #include "iax2-parser.h"
75 #include "iax2-provision.h"
78 /* Define NEWJB to use the new channel independent jitterbuffer,
79 * otherwise, use the old jitterbuffer */
83 #include "../jitterbuf.h"
87 #define IPTOS_MINCOST 0x02
91 static int nochecksums = 0;
95 * Uncomment to try experimental IAX bridge optimization,
96 * designed to reduce latency when IAX calls cannot
97 * be trasnferred -- obsolete
100 /* #define BRIDGE_OPTIMIZATION */
103 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
104 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
106 #define DEFAULT_RETRY_TIME 1000
107 #define MEMORY_SIZE 100
108 #define DEFAULT_DROP 3
109 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
110 but keeps the division between trunked and non-trunked better. */
111 #define TRUNK_CALL_START 0x4000
113 #define DEBUG_SUPPORT
115 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
117 /* Sample over last 100 units to determine historic jitter */
120 static struct ast_codec_pref prefs;
122 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
123 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
124 static const char channeltype[] = "IAX2";
126 static char context[80] = "default";
128 static char language[MAX_LANGUAGE] = "";
129 static char regcontext[AST_MAX_EXTENSION] = "";
131 static int max_retries = 4;
132 static int ping_time = 20;
133 static int lagrq_time = 10;
134 static int maxtrunkcall = TRUNK_CALL_START;
135 static int maxnontrunkcall = 1;
136 static int maxjitterbuffer=1000;
138 static int resyncthreshold=1000;
139 static int maxjitterinterps=10;
141 static int jittershrinkrate=2;
142 static int trunkfreq = 20;
143 static int send_trunktimestamps = 1;
144 static int authdebug = 1;
145 static int autokill = 0;
146 static int iaxcompat = 0;
148 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
150 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
154 static int expirey = IAX_DEFAULT_REG_EXPIRE;
156 static int timingfd = -1; /* Timing file descriptor */
158 static struct ast_netsock_list netsock;
159 static int defaultsockfd = -1;
162 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
164 int (*iax2_regfunk)(char *username, int onoff) = NULL;
167 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
169 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
170 ~AST_FORMAT_SLINEAR & \
174 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
178 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
182 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
183 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
184 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
186 static struct io_context *io;
187 static struct sched_context *sched;
189 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
191 static int iax2_dropcount = DEFAULT_DROP;
193 static int iaxdebug = 0;
195 static int iaxtrunkdebug = 0;
197 static int test_losspct = 0;
199 static int test_late = 0;
200 static int test_resync = 0;
201 static int test_jit = 0;
202 static int test_jitpct = 0;
203 #endif /* IAXTESTS */
205 static char accountcode[AST_MAX_ACCOUNT_CODE];
206 static int amaflags = 0;
207 static int delayreject = 0;
208 static int iax2_encryption = 0;
210 static struct ast_flags globalflags = {0};
212 static pthread_t netthreadid = AST_PTHREADT_NULL;
214 #define IAX_STATE_STARTED (1 << 0)
215 #define IAX_STATE_AUTHENTICATED (1 << 1)
216 #define IAX_STATE_TBD (1 << 2)
218 struct iax2_context {
219 char context[AST_MAX_EXTENSION];
220 struct iax2_context *next;
223 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
224 #define IAX_DELME (1 << 1) /* Needs to be deleted */
225 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
226 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
227 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
228 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
229 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
230 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
231 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
232 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
233 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
234 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
235 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
236 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
237 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
238 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
239 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
240 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
241 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
242 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
243 #define IAX_FORCEJITTERBUF (1 << 20) /* Force jitterbuffer, even when bridged to a channel that can take jitter */
244 #define IAX_RTIGNOREREGEXPIRE (1 << 21)
246 static int global_rtautoclear = 120;
248 static int reload_config(void);
249 static int iax2_reload(int fd, int argc, char *argv[]);
258 char accountcode[AST_MAX_ACCOUNT_CODE];
259 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
260 char language[MAX_LANGUAGE];
264 char cid_num[AST_MAX_EXTENSION];
265 char cid_name[AST_MAX_EXTENSION];
266 struct ast_codec_pref prefs;
268 struct iax2_context *contexts;
269 struct iax2_user *next;
270 struct ast_variable *vars;
278 char outkey[80]; /* What key we use to talk to this peer */
279 char context[AST_MAX_EXTENSION]; /* For transfers only */
280 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
281 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
282 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
283 struct ast_codec_pref prefs;
284 struct ast_dnsmgr_entry *dnsmgr; /* DNS refresh manager */
285 struct sockaddr_in addr;
287 int sockfd; /* Socket to use for transmission */
291 /* Dynamic Registration fields */
292 struct sockaddr_in defaddr; /* Default address if there is one */
293 int authmethods; /* Authentication methods (IAX_AUTH_*) */
294 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
295 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
297 /* Suggested caller id if registering */
298 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
299 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
301 int expire; /* Schedule entry for expirey */
302 int expirey; /* How soon to expire */
303 int capability; /* Capability */
304 char zonetag[80]; /* Time Zone */
307 int callno; /* Call number of POKE request */
308 int pokeexpire; /* When to expire poke */
309 int lastms; /* How long last response took (in ms), or -1 for no response */
310 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
313 struct iax2_peer *next;
316 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
318 static struct iax2_trunk_peer {
321 struct sockaddr_in addr;
322 struct timeval txtrunktime; /* Transmit trunktime */
323 struct timeval rxtrunktime; /* Receive trunktime */
324 struct timeval lasttxtime; /* Last transmitted trunktime */
325 struct timeval trunkact; /* Last trunk activity */
326 unsigned int lastsent; /* Last sent time */
327 /* Trunk data and length */
328 unsigned char *trunkdata;
329 unsigned int trunkdatalen;
330 unsigned int trunkdataalloc;
331 struct iax2_trunk_peer *next;
336 AST_MUTEX_DEFINE_STATIC(tpeerlock);
338 struct iax_firmware {
339 struct iax_firmware *next;
343 struct ast_iax2_firmware_header *fwh;
347 #define REG_STATE_UNREGISTERED 0
348 #define REG_STATE_REGSENT 1
349 #define REG_STATE_AUTHSENT 2
350 #define REG_STATE_REGISTERED 3
351 #define REG_STATE_REJECTED 4
352 #define REG_STATE_TIMEOUT 5
353 #define REG_STATE_NOAUTH 6
355 #define TRANSFER_NONE 0
356 #define TRANSFER_BEGIN 1
357 #define TRANSFER_READY 2
358 #define TRANSFER_RELEASED 3
359 #define TRANSFER_PASSTHROUGH 4
361 struct iax2_registry {
362 struct sockaddr_in addr; /* Who we connect to for registration purposes */
364 char secret[80]; /* Password or key name in []'s */
366 int expire; /* Sched ID of expiration */
367 int refresh; /* How often to refresh */
369 int messages; /* Message count */
370 int callno; /* Associated call number if applicable */
371 struct sockaddr_in us; /* Who the server thinks we are */
372 struct iax2_registry *next;
375 static struct iax2_registry *registrations;
377 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
378 #define MIN_RETRY_TIME 100
379 #define MAX_RETRY_TIME 10000
381 #define MAX_JITTER_BUFFER 50
382 #define MIN_JITTER_BUFFER 10
384 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
385 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
387 #define MAX_TIMESTAMP_SKEW 160 /* maximum difference between actual and predicted ts for sending */
389 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
390 #define TS_GAP_FOR_JB_RESYNC 5000
392 /* If we have more than this much excess real jitter buffer, shrink it. */
393 static int max_jitter_buffer = MAX_JITTER_BUFFER;
394 /* If we have less than this much excess real jitter buffer, enlarge it. */
395 static int min_jitter_buffer = MIN_JITTER_BUFFER;
407 struct chan_iax2_pvt {
408 /* Socket to send/receive on for this call */
410 /* Last received voice format */
412 /* Last received voice format */
414 /* Last sent voice format */
416 /* Last sent video format */
418 /* What we are capable of sending */
420 /* Last received timestamp */
422 /* Last sent timestamp - never send the same timestamp twice in a single call */
423 unsigned int lastsent;
424 /* Next outgoing timestamp if everything is good */
425 unsigned int nextpred;
426 /* True if the last voice we transmitted was not silence/CNG */
429 unsigned int pingtime;
430 /* Max time for initial response */
433 struct sockaddr_in addr;
434 struct ast_codec_pref prefs;
435 /* Our call number */
436 unsigned short callno;
438 unsigned short peercallno;
439 /* Peer selected format */
441 /* Peer capability */
443 /* timeval that we base our transmission on */
444 struct timeval offset;
445 /* timeval that we base our delivery on */
446 struct timeval rxcore;
448 /* The jitterbuffer */
450 /* active jb read scheduler id */
453 /* Historical delivery time */
454 int history[MEMORY_SIZE];
455 /* Current base jitterbuffer */
457 /* Current jitter measure */
459 /* Historic jitter value */
464 /* Error, as discovered by the manager */
466 /* Owner if we have one */
467 struct ast_channel *owner;
468 /* What's our state? */
470 /* Expirey (optional) */
472 /* Next outgoing sequence number */
473 unsigned char oseqno;
474 /* Next sequence number they have not yet acknowledged */
475 unsigned char rseqno;
476 /* Next incoming sequence number */
477 unsigned char iseqno;
478 /* Last incoming sequence number we have acknowledged */
479 unsigned char aseqno;
482 /* Default Context */
484 /* Caller ID if available */
487 /* Hidden Caller ID (i.e. ANI) if appropriate */
491 /* Requested Extension */
492 char exten[AST_MAX_EXTENSION];
493 /* Expected Username */
495 /* Expected Secret */
497 /* permitted authentication methods */
499 /* permitted encryption methods */
503 /* Public keys permitted keys for incoming authentication */
505 /* Private key for outgoing authentication */
507 /* Encryption AES-128 Key */
509 /* Decryption AES-128 Key */
511 /* 32 bytes of semi-random data */
513 /* Preferred language */
514 char language[MAX_LANGUAGE];
515 /* Hostname/peername for naming purposes */
517 /* Associated registry */
518 struct iax2_registry *reg;
519 /* Associated peer for poking */
520 struct iax2_peer *peerpoke;
524 /* Transferring status */
526 /* Transfer identifier */
528 /* Who we are IAX transfering to */
529 struct sockaddr_in transfer;
530 /* What's the new call number for the transfer */
531 unsigned short transfercallno;
532 /* Transfer decrypt AES-128 Key */
533 aes_encrypt_ctx tdcx;
535 /* Status of knowledge of peer ADSI capability */
538 /* Who we are bridged to */
539 unsigned short bridgecallno;
540 unsigned int bridgesfmt;
541 struct ast_trans_pvt *bridgetrans;
543 int pingid; /* Transmit PING request */
544 int lagid; /* Retransmit lag request */
545 int autoid; /* Auto hangup for Dialplan requestor */
546 int authid; /* Authentication rejection ID */
547 int authfail; /* Reason to report failure */
548 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
552 char dproot[AST_MAX_EXTENSION];
553 char accountcode[AST_MAX_ACCOUNT_CODE];
555 struct iax2_dpcache *dpentries;
556 struct ast_variable *vars;
557 /* last received remote rr */
558 struct iax_rr remote_rr;
559 /* Current base time: (just for stats) */
561 /* Dropped frame count: (just for stats) */
563 /* received frame count: (just for stats) */
567 static struct ast_iax2_queue {
568 struct iax_frame *head;
569 struct iax_frame *tail;
574 static struct ast_user_list {
575 struct iax2_user *users;
579 static struct ast_peer_list {
580 struct iax2_peer *peers;
584 static struct ast_firmware_list {
585 struct iax_firmware *wares;
589 /* Extension exists */
590 #define CACHE_FLAG_EXISTS (1 << 0)
591 /* Extension is nonexistent */
592 #define CACHE_FLAG_NONEXISTENT (1 << 1)
593 /* Extension can exist */
594 #define CACHE_FLAG_CANEXIST (1 << 2)
595 /* Waiting to hear back response */
596 #define CACHE_FLAG_PENDING (1 << 3)
598 #define CACHE_FLAG_TIMEOUT (1 << 4)
599 /* Request transmitted */
600 #define CACHE_FLAG_TRANSMITTED (1 << 5)
602 #define CACHE_FLAG_UNKNOWN (1 << 6)
604 #define CACHE_FLAG_MATCHMORE (1 << 7)
606 static struct iax2_dpcache {
607 char peercontext[AST_MAX_EXTENSION];
608 char exten[AST_MAX_EXTENSION];
610 struct timeval expirey;
612 unsigned short callno;
614 struct iax2_dpcache *next;
615 struct iax2_dpcache *peer; /* For linking in peers */
618 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
620 static void reg_source_db(struct iax2_peer *p);
621 static struct iax2_peer *realtime_peer(const char *peername);
623 static void destroy_peer(struct iax2_peer *peer);
624 static int ast_cli_netstats(int fd, int limit_fmt);
626 static void iax_debug_output(const char *data)
629 ast_verbose("%s", data);
632 static void iax_error_output(const char *data)
634 ast_log(LOG_WARNING, "%s", data);
638 static void jb_error_output(const char *fmt, ...)
644 vsnprintf(buf, 1024, fmt, args);
647 ast_log(LOG_ERROR, buf);
650 static void jb_warning_output(const char *fmt, ...)
656 vsnprintf(buf, 1024, fmt, args);
659 ast_log(LOG_WARNING, buf);
662 static void jb_debug_output(const char *fmt, ...)
668 vsnprintf(buf, 1024, fmt, args);
676 /* XXX We probably should use a mutex when working with this XXX */
677 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
678 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
679 static struct timeval lastused[IAX_MAX_CALLS];
682 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
683 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
684 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
685 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
686 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
687 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
688 static void destroy_user(struct iax2_user *user);
689 static int expire_registry(void *data);
690 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
691 static int iax2_do_register(struct iax2_registry *reg);
692 static void prune_peers(void);
693 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
694 static int iax2_provision(struct sockaddr_in *end, char *dest, const char *template, int force);
696 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
697 static int iax2_devicestate(void *data);
698 static int iax2_digit(struct ast_channel *c, char digit);
699 static int iax2_sendtext(struct ast_channel *c, const char *text);
700 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
701 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
702 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
703 static int iax2_hangup(struct ast_channel *c);
704 static int iax2_answer(struct ast_channel *c);
705 static struct ast_frame *iax2_read(struct ast_channel *c);
706 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
707 static int iax2_indicate(struct ast_channel *c, int condition);
708 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
709 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
710 static int iax2_transfer(struct ast_channel *c, const char *dest);
711 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
713 static const struct ast_channel_tech iax2_tech = {
715 .description = tdesc,
716 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
717 .properties = AST_CHAN_TP_WANTSJITTER,
718 .requester = iax2_request,
719 .devicestate = iax2_devicestate,
720 .send_digit = iax2_digit,
721 .send_text = iax2_sendtext,
722 .send_image = iax2_sendimage,
723 .send_html = iax2_sendhtml,
725 .hangup = iax2_hangup,
726 .answer = iax2_answer,
729 .write_video = iax2_write,
730 .indicate = iax2_indicate,
731 .setoption = iax2_setoption,
732 .bridge = iax2_bridge,
733 .transfer = iax2_transfer,
737 static int send_ping(void *data)
739 int callno = (long)data;
740 /* Ping only if it's real, not if it's bridged */
742 #ifdef BRIDGE_OPTIMIZATION
743 if (!iaxs[callno]->bridgecallno)
745 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
751 static int get_encrypt_methods(const char *s)
754 if (!strcasecmp(s, "aes128"))
755 e = IAX_ENCRYPT_AES128;
756 else if (ast_true(s))
757 e = IAX_ENCRYPT_AES128;
763 static int send_lagrq(void *data)
765 int callno = (long)data;
766 /* Ping only if it's real not if it's bridged */
768 #ifdef BRIDGE_OPTIMIZATION
769 if (!iaxs[callno]->bridgecallno)
771 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
777 static unsigned char compress_subclass(int subclass)
781 /* If it's 128 or smaller, just return it */
782 if (subclass < IAX_FLAG_SC_LOG)
784 /* Otherwise find its power */
785 for (x = 0; x < IAX_MAX_SHIFT; x++) {
786 if (subclass & (1 << x)) {
788 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
794 return power | IAX_FLAG_SC_LOG;
797 static int uncompress_subclass(unsigned char csub)
799 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
800 if (csub & IAX_FLAG_SC_LOG) {
801 /* special case for 'compressed' -1 */
805 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
811 static struct iax2_peer *find_peer(const char *name, int realtime)
813 struct iax2_peer *peer;
814 ast_mutex_lock(&peerl.lock);
815 for(peer = peerl.peers; peer; peer = peer->next) {
816 if (!strcasecmp(peer->name, name)) {
820 ast_mutex_unlock(&peerl.lock);
821 if(!peer && realtime)
822 peer = realtime_peer(name);
826 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
828 struct iax2_peer *peer;
831 ast_mutex_lock(&peerl.lock);
834 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
835 (peer->addr.sin_port == sin.sin_port)) {
836 ast_copy_string(host, peer->name, len);
843 ast_mutex_unlock(&peerl.lock);
847 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
849 struct chan_iax2_pvt *tmp;
850 tmp = malloc(sizeof(struct chan_iax2_pvt));
852 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
856 tmp->transfercallno = 0;
857 tmp->bridgecallno = 0;
863 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
864 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
865 ast_copy_string(tmp->host, host, sizeof(tmp->host));
872 jbconf.max_jitterbuf = maxjitterbuffer;
873 jbconf.resync_threshold = resyncthreshold;
874 jbconf.max_contig_interp = maxjitterinterps;
875 jb_setconf(tmp->jb,&jbconf);
882 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
884 /* Malloc() a copy of a frame */
885 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
887 memcpy(new, fr, sizeof(struct iax_frame));
888 iax_frame_wrap(new, &fr->af);
891 new->direction = DIRECTION_INGRESS;
897 #define NEW_PREVENT 0
901 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
903 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
904 (cur->addr.sin_port == sin->sin_port)) {
905 /* This is the main host */
906 if ((cur->peercallno == callno) ||
907 ((dcallno == cur->callno) && !cur->peercallno)) {
908 /* That's us. Be sure we keep track of the peer call number */
912 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
913 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
914 /* We're transferring */
915 if (dcallno == cur->callno)
921 static void update_max_trunk(void)
923 int max = TRUNK_CALL_START;
925 /* XXX Prolly don't need locks here XXX */
926 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
932 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
935 static void update_max_nontrunk(void)
939 /* XXX Prolly don't need locks here XXX */
940 for (x=1;x<TRUNK_CALL_START - 1; x++) {
944 maxnontrunkcall = max;
946 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
949 static int make_trunk(unsigned short callno, int locked)
954 if (iaxs[callno]->oseqno) {
955 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
958 if (callno & TRUNK_CALL_START) {
959 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
962 gettimeofday(&now, NULL);
963 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
964 ast_mutex_lock(&iaxsl[x]);
965 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
966 iaxs[x] = iaxs[callno];
969 /* Update the two timers that should have been started */
970 if (iaxs[x]->pingid > -1)
971 ast_sched_del(sched, iaxs[x]->pingid);
972 if (iaxs[x]->lagid > -1)
973 ast_sched_del(sched, iaxs[x]->lagid);
974 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
975 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
977 ast_mutex_unlock(&iaxsl[callno]);
980 ast_mutex_unlock(&iaxsl[x]);
983 ast_mutex_unlock(&iaxsl[x]);
985 if (x >= IAX_MAX_CALLS - 1) {
986 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
989 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
990 /* We move this call from a non-trunked to a trunked call */
992 update_max_nontrunk();
996 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1001 char iabuf[INET_ADDRSTRLEN];
1003 if (new <= NEW_ALLOW) {
1004 /* Look for an existing connection first */
1005 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1006 ast_mutex_lock(&iaxsl[x]);
1008 /* Look for an exact match */
1009 if (match(sin, callno, dcallno, iaxs[x])) {
1013 ast_mutex_unlock(&iaxsl[x]);
1015 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1016 ast_mutex_lock(&iaxsl[x]);
1018 /* Look for an exact match */
1019 if (match(sin, callno, dcallno, iaxs[x])) {
1023 ast_mutex_unlock(&iaxsl[x]);
1026 if ((res < 1) && (new >= NEW_ALLOW)) {
1027 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1028 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1029 gettimeofday(&now, NULL);
1030 for (x=1;x<TRUNK_CALL_START;x++) {
1031 /* Find first unused call number that hasn't been used in a while */
1032 ast_mutex_lock(&iaxsl[x]);
1033 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1034 ast_mutex_unlock(&iaxsl[x]);
1036 /* We've still got lock held if we found a spot */
1037 if (x >= TRUNK_CALL_START) {
1038 ast_log(LOG_WARNING, "No more space\n");
1041 iaxs[x] = new_iax(sin, lockpeer, host);
1042 update_max_nontrunk();
1045 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1046 iaxs[x]->sockfd = sockfd;
1047 iaxs[x]->addr.sin_port = sin->sin_port;
1048 iaxs[x]->addr.sin_family = sin->sin_family;
1049 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1050 iaxs[x]->peercallno = callno;
1051 iaxs[x]->callno = x;
1052 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1053 iaxs[x]->expirey = expirey;
1054 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1055 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1056 iaxs[x]->amaflags = amaflags;
1057 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1058 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1060 ast_log(LOG_WARNING, "Out of resources\n");
1061 ast_mutex_unlock(&iaxsl[x]);
1064 ast_mutex_unlock(&iaxsl[x]);
1070 static void iax2_frame_free(struct iax_frame *fr)
1072 if (fr->retrans > -1)
1073 ast_sched_del(sched, fr->retrans);
1077 static int iax2_queue_frame(int callno, struct ast_frame *f)
1079 /* Assumes lock for callno is already held... */
1081 if (iaxs[callno] && iaxs[callno]->owner) {
1082 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1083 /* Avoid deadlock by pausing and trying again */
1084 ast_mutex_unlock(&iaxsl[callno]);
1086 ast_mutex_lock(&iaxsl[callno]);
1088 ast_queue_frame(iaxs[callno]->owner, f);
1089 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1098 static void destroy_firmware(struct iax_firmware *cur)
1100 /* Close firmware */
1102 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1108 static int try_firmware(char *s)
1111 struct iax_firmware *cur;
1116 struct ast_iax2_firmware_header *fwh, fwh2;
1117 struct MD5Context md5;
1118 unsigned char sum[16];
1119 unsigned char buf[1024];
1123 s2 = alloca(strlen(s) + 100);
1125 ast_log(LOG_WARNING, "Alloca failed!\n");
1128 last = strrchr(s, '/');
1133 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1134 res = stat(s, &stbuf);
1136 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1139 /* Make sure it's not a directory */
1140 if (S_ISDIR(stbuf.st_mode))
1142 ifd = open(s, O_RDONLY);
1144 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1147 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1149 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1153 /* Unlink our newly created file */
1156 /* Now copy the firmware into it */
1157 len = stbuf.st_size;
1160 if (chunk > sizeof(buf))
1161 chunk = sizeof(buf);
1162 res = read(ifd, buf, chunk);
1164 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1169 res = write(fd, buf, chunk);
1171 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1179 /* Return to the beginning */
1180 lseek(fd, 0, SEEK_SET);
1181 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1182 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1186 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1187 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1191 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1192 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1196 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1197 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1201 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1203 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1208 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1209 MD5Final(sum, &md5);
1210 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1211 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1212 munmap(fwh, stbuf.st_size);
1218 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1219 /* Found a candidate */
1220 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1221 /* The version we have on loaded is older, load this one instead */
1223 /* This version is no newer than what we have. Don't worry about it.
1224 We'll consider it a proper load anyhow though */
1225 munmap(fwh, stbuf.st_size);
1232 /* Allocate a new one and link it */
1233 cur = malloc(sizeof(struct iax_firmware));
1235 memset(cur, 0, sizeof(struct iax_firmware));
1237 cur->next = waresl.wares;
1243 munmap(cur->fwh, cur->mmaplen);
1249 cur->mmaplen = stbuf.st_size;
1255 static int iax_check_version(char *dev)
1258 struct iax_firmware *cur;
1259 if (dev && !ast_strlen_zero(dev)) {
1260 ast_mutex_lock(&waresl.lock);
1263 if (!strcmp(dev, cur->fwh->devname)) {
1264 res = ntohs(cur->fwh->version);
1269 ast_mutex_unlock(&waresl.lock);
1274 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1277 unsigned int bs = desc & 0xff;
1278 unsigned int start = (desc >> 8) & 0xffffff;
1280 struct iax_firmware *cur;
1281 if (dev && !ast_strlen_zero(dev) && bs) {
1283 ast_mutex_lock(&waresl.lock);
1286 if (!strcmp(dev, cur->fwh->devname)) {
1287 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1288 if (start < ntohl(cur->fwh->datalen)) {
1289 bytes = ntohl(cur->fwh->datalen) - start;
1292 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1295 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1305 ast_mutex_unlock(&waresl.lock);
1311 static void reload_firmware(void)
1313 struct iax_firmware *cur, *curl, *curp;
1318 /* Mark all as dead */
1319 ast_mutex_lock(&waresl.lock);
1325 /* Now that we've freed them, load the new ones */
1326 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1329 while((de = readdir(fwd))) {
1330 if (de->d_name[0] != '.') {
1331 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1332 if (!try_firmware(fn)) {
1333 if (option_verbose > 1)
1334 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1340 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1342 /* Clean up leftovers */
1354 destroy_firmware(curl);
1359 ast_mutex_unlock(&waresl.lock);
1362 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1364 static int __do_deliver(void *data)
1366 /* Just deliver the packet by using queueing. This is called by
1367 the IAX thread with the iaxsl lock held. */
1368 struct iax_frame *fr = data;
1370 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1371 iax2_queue_frame(fr->callno, &fr->af);
1372 /* Free our iax frame */
1373 iax2_frame_free(fr);
1374 /* And don't run again */
1379 static int do_deliver(void *data)
1381 /* Locking version of __do_deliver */
1382 struct iax_frame *fr = data;
1383 int callno = fr->callno;
1385 ast_mutex_lock(&iaxsl[callno]);
1386 res = __do_deliver(data);
1387 ast_mutex_unlock(&iaxsl[callno]);
1392 static int handle_error(void)
1394 /* XXX Ideally we should figure out why an error occured and then abort those
1395 rather than continuing to try. Unfortunately, the published interface does
1396 not seem to work XXX */
1398 struct sockaddr_in *sin;
1401 struct sock_extended_err e;
1406 m.msg_controllen = sizeof(e);
1408 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1410 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1412 if (m.msg_controllen) {
1413 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1415 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1417 ast_log(LOG_WARNING, "No address detected??\n");
1419 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1426 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1429 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1433 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1440 static int send_packet(struct iax_frame *f)
1443 char iabuf[INET_ADDRSTRLEN];
1444 /* Called with iaxsl held */
1445 if (option_debug > 2)
1446 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, f->callno, iaxs[f->callno]->peercallno, ast_inet_ntoa(iabuf, sizeof(iabuf), iaxs[f->callno]->addr.sin_addr), ntohs(iaxs[f->callno]->addr.sin_port));
1447 /* Don't send if there was an error, but return error instead */
1449 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1452 if (!iaxs[f->callno])
1454 if (iaxs[f->callno]->error)
1458 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1459 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1460 sizeof(iaxs[f->callno]->transfer));
1463 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1464 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1465 sizeof(iaxs[f->callno]->addr));
1469 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1477 static int iax2_predestroy(int callno)
1479 struct ast_channel *c;
1480 struct chan_iax2_pvt *pvt;
1481 ast_mutex_lock(&iaxsl[callno]);
1484 ast_mutex_unlock(&iaxsl[callno]);
1487 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1488 /* No more pings or lagrq's */
1489 if (pvt->pingid > -1)
1490 ast_sched_del(sched, pvt->pingid);
1491 if (pvt->lagid > -1)
1492 ast_sched_del(sched, pvt->lagid);
1493 if (pvt->autoid > -1)
1494 ast_sched_del(sched, pvt->autoid);
1495 if (pvt->authid > -1)
1496 ast_sched_del(sched, pvt->authid);
1497 if (pvt->initid > -1)
1498 ast_sched_del(sched, pvt->initid);
1501 ast_sched_del(sched, pvt->jbid);
1509 ast_set_flag(pvt, IAX_ALREADYGONE);
1513 c->_softhangup |= AST_SOFTHANGUP_DEV;
1515 ast_queue_hangup(c);
1517 ast_mutex_lock(&usecnt_lock);
1520 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1521 ast_mutex_unlock(&usecnt_lock);
1523 ast_mutex_unlock(&iaxsl[callno]);
1524 ast_update_use_count();
1528 static int iax2_predestroy_nolock(int callno)
1531 ast_mutex_unlock(&iaxsl[callno]);
1532 res = iax2_predestroy(callno);
1533 ast_mutex_lock(&iaxsl[callno]);
1537 static void iax2_destroy(int callno)
1539 struct chan_iax2_pvt *pvt;
1540 struct iax_frame *cur;
1541 struct ast_channel *owner;
1544 ast_mutex_lock(&iaxsl[callno]);
1546 gettimeofday(&lastused[callno], NULL);
1553 if (ast_mutex_trylock(&owner->lock)) {
1554 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1555 ast_mutex_unlock(&iaxsl[callno]);
1561 iaxs[callno] = NULL;
1565 /* No more pings or lagrq's */
1566 if (pvt->pingid > -1)
1567 ast_sched_del(sched, pvt->pingid);
1568 if (pvt->lagid > -1)
1569 ast_sched_del(sched, pvt->lagid);
1570 if (pvt->autoid > -1)
1571 ast_sched_del(sched, pvt->autoid);
1572 if (pvt->authid > -1)
1573 ast_sched_del(sched, pvt->authid);
1574 if (pvt->initid > -1)
1575 ast_sched_del(sched, pvt->initid);
1578 ast_sched_del(sched, pvt->jbid);
1586 if (pvt->bridgetrans)
1587 ast_translator_free_path(pvt->bridgetrans);
1588 pvt->bridgetrans = NULL;
1591 ast_set_flag(pvt, IAX_ALREADYGONE);
1594 /* If there's an owner, prod it to give up */
1595 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1596 ast_queue_hangup(owner);
1599 for (cur = iaxq.head; cur ; cur = cur->next) {
1600 /* Cancel any pending transmissions */
1601 if (cur->callno == pvt->callno)
1605 pvt->reg->callno = 0;
1609 ast_variables_destroy(pvt->vars);
1615 while(jb_getall(pvt->jb,&frame) == JB_OK)
1616 iax2_frame_free(frame.data);
1617 jb_destroy(pvt->jb);
1624 ast_mutex_unlock(&owner->lock);
1626 ast_mutex_unlock(&iaxsl[callno]);
1627 if (callno & 0x4000)
1630 static void iax2_destroy_nolock(int callno)
1632 /* Actually it's easier to unlock, kill it, and relock */
1633 ast_mutex_unlock(&iaxsl[callno]);
1634 iax2_destroy(callno);
1635 ast_mutex_lock(&iaxsl[callno]);
1638 static int update_packet(struct iax_frame *f)
1640 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1641 struct ast_iax2_full_hdr *fh = f->data;
1642 /* Mark this as a retransmission */
1643 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1645 f->iseqno = iaxs[f->callno]->iseqno;
1646 fh->iseqno = f->iseqno;
1650 static int attempt_transmit(void *data)
1652 /* Attempt to transmit the frame to the remote peer...
1653 Called without iaxsl held. */
1654 struct iax_frame *f = data;
1656 int callno = f->callno;
1657 char iabuf[INET_ADDRSTRLEN];
1658 /* Make sure this call is still active */
1660 ast_mutex_lock(&iaxsl[callno]);
1661 if ((f->callno) && iaxs[f->callno]) {
1662 if ((f->retries < 0) /* Already ACK'd */ ||
1663 (f->retries >= max_retries) /* Too many attempts */) {
1664 /* Record an error if we've transmitted too many times */
1665 if (f->retries >= max_retries) {
1667 /* Transfer timeout */
1668 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1669 } else if (f->final) {
1671 iax2_destroy_nolock(f->callno);
1673 if (iaxs[f->callno]->owner)
1674 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);
1675 iaxs[f->callno]->error = ETIMEDOUT;
1676 if (iaxs[f->callno]->owner) {
1677 struct ast_frame fr = { 0, };
1679 fr.frametype = AST_FRAME_CONTROL;
1680 fr.subclass = AST_CONTROL_HANGUP;
1681 iax2_queue_frame(f->callno, &fr);
1682 /* Remember, owner could disappear */
1683 if (iaxs[f->callno]->owner)
1684 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1686 if (iaxs[f->callno]->reg) {
1687 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1688 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1689 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1691 iax2_destroy_nolock(f->callno);
1698 /* Update it if it needs it */
1700 /* Attempt transmission */
1703 /* Try again later after 10 times as long */
1705 if (f->retrytime > MAX_RETRY_TIME)
1706 f->retrytime = MAX_RETRY_TIME;
1707 /* Transfer messages max out at one second */
1708 if (f->transfer && (f->retrytime > 1000))
1709 f->retrytime = 1000;
1710 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1713 /* Make sure it gets freed */
1718 ast_mutex_unlock(&iaxsl[callno]);
1719 /* Do not try again */
1721 /* Don't attempt delivery, just remove it from the queue */
1722 ast_mutex_lock(&iaxq.lock);
1724 f->prev->next = f->next;
1726 iaxq.head = f->next;
1728 f->next->prev = f->prev;
1730 iaxq.tail = f->prev;
1732 ast_mutex_unlock(&iaxq.lock);
1734 /* Free the IAX frame */
1740 static int iax2_set_jitter(int fd, int argc, char *argv[])
1743 ast_cli(fd, "sorry, this command is deprecated\n");
1744 return RESULT_SUCCESS;
1746 if ((argc != 4) && (argc != 5))
1747 return RESULT_SHOWUSAGE;
1749 max_jitter_buffer = atoi(argv[3]);
1750 if (max_jitter_buffer < 0)
1751 max_jitter_buffer = 0;
1754 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1755 if (iaxs[atoi(argv[3])]) {
1756 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1757 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1758 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1760 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1762 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1765 return RESULT_SUCCESS;
1769 static char jitter_usage[] =
1770 "Usage: iax set jitter [callid] <value>\n"
1771 " If used with a callid, it sets the jitter buffer to the given static\n"
1772 "value (until its next calculation). If used without a callid, the value is used\n"
1773 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1774 "buffer size is reduced.";
1776 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1778 struct iax2_peer *peer;
1781 return RESULT_SHOWUSAGE;
1782 if (!strcmp(argv[3],"all")) {
1784 ast_cli(fd, "OK cache is flushed.\n");
1785 } else if ((peer = find_peer(argv[3], 0))) {
1786 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1787 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1788 expire_registry(peer);
1789 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1791 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1794 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1797 return RESULT_SUCCESS;
1800 static int iax2_test_losspct(int fd, int argc, char *argv[])
1803 return RESULT_SHOWUSAGE;
1805 test_losspct = atoi(argv[3]);
1807 return RESULT_SUCCESS;
1811 static int iax2_test_late(int fd, int argc, char *argv[])
1814 return RESULT_SHOWUSAGE;
1816 test_late = atoi(argv[3]);
1818 return RESULT_SUCCESS;
1821 static int iax2_test_resync(int fd, int argc, char *argv[])
1824 return RESULT_SHOWUSAGE;
1826 test_resync = atoi(argv[3]);
1828 return RESULT_SUCCESS;
1831 static int iax2_test_jitter(int fd, int argc, char *argv[])
1833 if (argc < 4 || argc > 5)
1834 return RESULT_SHOWUSAGE;
1836 test_jit = atoi(argv[3]);
1838 test_jitpct = atoi(argv[4]);
1840 return RESULT_SUCCESS;
1842 #endif /* IAXTESTS */
1844 /*--- iax2_show_peer: Show one peer in detail ---*/
1845 static int iax2_show_peer(int fd, int argc, char *argv[])
1847 char status[30] = "";
1849 char iabuf[INET_ADDRSTRLEN];
1850 struct iax2_peer *peer;
1851 char codec_buf[512];
1852 int x = 0, codec = 0, load_realtime = 0;
1855 return RESULT_SHOWUSAGE;
1857 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1859 peer = find_peer(argv[3], load_realtime);
1862 ast_cli(fd, " * Name : %s\n", peer->name);
1863 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1864 ast_cli(fd, " Context : %s\n", peer->context);
1865 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1866 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1867 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1868 ast_cli(fd, " Expire : %d\n", peer->expire);
1869 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1870 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));
1871 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1872 ast_cli(fd, " Username : %s\n", peer->username);
1873 ast_cli(fd, " Codecs : ");
1874 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1875 ast_cli(fd, "%s\n", codec_buf);
1877 ast_cli(fd, " Codec Order : (");
1878 for(x = 0; x < 32 ; x++) {
1879 codec = ast_codec_pref_index(&peer->prefs,x);
1882 ast_cli(fd, "%s", ast_getformatname(codec));
1883 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1888 ast_cli(fd, "none");
1891 ast_cli(fd, " Status : ");
1892 if (peer->lastms < 0)
1893 ast_copy_string(status, "UNREACHABLE", sizeof(status));
1894 else if (peer->lastms > peer->maxms)
1895 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->lastms);
1896 else if (peer->lastms)
1897 snprintf(status, sizeof(status), "OK (%d ms)", peer->lastms);
1899 ast_copy_string(status, "UNKNOWN", sizeof(status));
1900 ast_cli(fd, "%s\n",status);
1902 if (ast_test_flag(peer, IAX_TEMPONLY))
1905 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1909 return RESULT_SUCCESS;
1912 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1915 struct iax2_peer *p;
1917 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1919 ast_mutex_lock(&peerl.lock);
1920 for(p = peerl.peers ; p ; p = p->next) {
1921 if(!strncasecmp(p->name, word, strlen(word))) {
1922 if(++which > state) {
1923 return strdup(p->name);
1927 ast_mutex_unlock(&peerl.lock);
1933 static int iax2_show_stats(int fd, int argc, char *argv[])
1935 struct iax_frame *cur;
1936 int cnt = 0, dead=0, final=0;
1938 return RESULT_SHOWUSAGE;
1939 for (cur = iaxq.head; cur ; cur = cur->next) {
1940 if (cur->retries < 0)
1946 ast_cli(fd, " IAX Statistics\n");
1947 ast_cli(fd, "---------------------\n");
1948 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d outgress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1949 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1950 return RESULT_SUCCESS;
1953 static int iax2_show_cache(int fd, int argc, char *argv[])
1955 struct iax2_dpcache *dp;
1956 char tmp[1024] = "", *pc;
1960 gettimeofday(&tv, NULL);
1961 ast_mutex_lock(&dpcache_lock);
1963 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1965 s = dp->expirey.tv_sec - tv.tv_sec;
1967 if (dp->flags & CACHE_FLAG_EXISTS)
1968 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1969 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1970 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1971 if (dp->flags & CACHE_FLAG_CANEXIST)
1972 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1973 if (dp->flags & CACHE_FLAG_PENDING)
1974 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1975 if (dp->flags & CACHE_FLAG_TIMEOUT)
1976 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1977 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1978 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1979 if (dp->flags & CACHE_FLAG_MATCHMORE)
1980 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1981 if (dp->flags & CACHE_FLAG_UNKNOWN)
1982 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1983 /* Trim trailing pipe */
1984 if (!ast_strlen_zero(tmp))
1985 tmp[strlen(tmp) - 1] = '\0';
1987 ast_copy_string(tmp, "(none)", sizeof(tmp));
1989 pc = strchr(dp->peercontext, '@');
1991 pc = dp->peercontext;
1994 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
1995 if (dp->waiters[x] > -1)
1998 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2000 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2003 ast_mutex_unlock(&dpcache_lock);
2004 return RESULT_SUCCESS;
2007 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2009 #ifdef BRIDGE_OPTIMIZATION
2010 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2012 static int forward_delivery(struct iax_frame *fr)
2014 struct chan_iax2_pvt *p1, *p2;
2015 char iabuf[INET_ADDRSTRLEN];
2018 p1 = iaxs[fr->callno];
2019 p2 = iaxs[p1->bridgecallno];
2026 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2028 p1->callno, p1->peercallno,
2029 p2->callno, p2->peercallno,
2030 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2031 ntohs(p2->addr.sin_port));
2033 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2034 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2035 send full frame on timestamp wrap when doing optimized bridging
2036 (actually current code STILL doesn't)
2038 if (fr->ts + 50000 <= p1->last) {
2039 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2041 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2044 /* Send with timestamp adjusted to the origin of the outbound leg */
2045 /* But don't destroy inbound timestamp still needed later to set "last" */
2047 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2048 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2054 static void unwrap_timestamp(struct iax_frame *fr)
2058 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2059 x = fr->ts - iaxs[fr->callno]->last;
2061 /* Sudden big jump backwards in timestamp:
2062 What likely happened here is that miniframe timestamp has circled but we haven't
2063 gotten the update from the main packet. We'll just pretend that we did, and
2064 update the timestamp appropriately. */
2065 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2067 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2070 /* Sudden apparent big jump forwards in timestamp:
2071 What's likely happened is this is an old miniframe belonging to the previous
2072 top-16-bit timestamp that has turned up out of order.
2073 Adjust the timestamp appropriately. */
2074 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2076 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2082 static int get_from_jb(void *p);
2084 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2088 gettimeofday(&tv,NULL);
2090 when = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2091 (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2093 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2095 when = jb_next(pvt->jb) - when;
2096 /* fprintf(stderr, "when = %d\n", when); */
2098 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2101 /* XXX should really just empty until when > 0.. */
2105 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2108 static int get_from_jb(void *p) {
2109 /* make sure pvt is valid! */
2110 struct chan_iax2_pvt *pvt = p;
2111 struct iax_frame *fr;
2118 ast_mutex_lock(&iaxsl[pvt->callno]);
2119 /* fprintf(stderr, "get_from_jb called\n"); */
2122 gettimeofday(&tv,NULL);
2123 /* round up a millisecond since ast_sched_runq does; */
2124 /* prevents us from spinning while waiting for our now */
2125 /* to catch up with runq's now */
2128 now = (tv.tv_sec - pvt->rxcore.tv_sec) * 1000 +
2129 (tv.tv_usec - pvt->rxcore.tv_usec) / 1000;
2131 if(now >= (next = jb_next(pvt->jb))) {
2132 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2135 /*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); */
2141 struct ast_frame af;
2143 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2145 /* create an interpolation frame */
2146 /*fprintf(stderr, "Making Interpolation frame\n"); */
2147 af.frametype = AST_FRAME_VOICE;
2148 af.subclass = pvt->voiceformat;
2150 af.samples = frame.ms * 8;
2152 af.src = "IAX2 JB interpolation";
2154 af.delivery.tv_sec = pvt->rxcore.tv_sec;
2155 af.delivery.tv_usec = pvt->rxcore.tv_usec;
2156 af.delivery.tv_sec += next / 1000;
2157 af.delivery.tv_usec += (next % 1000) * 1000;
2158 af.offset=AST_FRIENDLY_OFFSET;
2159 if (af.delivery.tv_usec >= 1000000) {
2160 af.delivery.tv_usec -= 1000000;
2161 af.delivery.tv_sec += 1;
2164 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2165 * which we'd need to malloc, and then it would free it. That seems like a drag */
2166 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2167 iax2_queue_frame(pvt->callno, &af);
2171 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2172 iax2_frame_free(frame.data);
2179 /* shouldn't happen */
2183 update_jbsched(pvt);
2184 ast_mutex_unlock(&iaxsl[pvt->callno]);
2189 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2190 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2191 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk)
2200 unsigned int orig_ts;
2201 int drops[MEMORY_SIZE];
2202 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2204 /* Remember current jitterbuffer so we can log any change */
2205 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2206 /* Similarly for the frame timestamp */
2212 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2213 fr->ts, iaxs[fr->callno]->last, updatehistory);
2216 /* Attempt to recover wrapped timestamps */
2217 unwrap_timestamp(fr);
2219 if (updatehistory) {
2222 /* Attempt to spot a change of timebase on timestamps coming from the other side
2223 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2224 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2225 for a while - in this case this code might also resync us. But that's not a bad thing.
2226 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2227 [that's why we only do this when updatehistory is true]
2229 x = fr->ts - iaxs[fr->callno]->last;
2230 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2232 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2233 fr->callno, fr->ts, iaxs[fr->callno]->last);
2234 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2235 iaxs[fr->callno]->rxcore.tv_sec = 0;
2236 iaxs[fr->callno]->rxcore.tv_usec = 0;
2237 /* wipe "last" if stamps have jumped backwards */
2239 iaxs[fr->callno]->last = 0;
2240 /* should we also empty history? */
2242 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2243 frame we received. (initially the very first, but also see code just above here).
2244 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2245 Called by IAX thread, with iaxsl lock held. */
2246 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2248 /* Rotate our history queue of "lateness". Don't worry about those initial
2249 zeros because the first entry will always be zero */
2250 for (x=0;x<MEMORY_SIZE - 1;x++)
2251 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2252 /* Add a history entry for this one */
2253 iaxs[fr->callno]->history[x] = ms;
2262 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2263 if ( (!fromtrunk) && (iaxs[fr->callno]->rxcore.tv_sec || iaxs[fr->callno]->rxcore.tv_usec) ) {
2264 fr->af.delivery.tv_sec = iaxs[fr->callno]->rxcore.tv_sec;
2265 fr->af.delivery.tv_usec = iaxs[fr->callno]->rxcore.tv_usec;
2266 fr->af.delivery.tv_sec += fr->ts / 1000;
2267 fr->af.delivery.tv_usec += (fr->ts % 1000) * 1000;
2268 if (fr->af.delivery.tv_usec >= 1000000) {
2269 fr->af.delivery.tv_usec -= 1000000;
2270 fr->af.delivery.tv_sec += 1;
2275 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2277 fr->af.delivery.tv_sec = 0;
2278 fr->af.delivery.tv_usec = 0;
2282 /* Initialize the minimum to reasonable values. It's too much
2283 work to do the same for the maximum, repeatedly */
2284 min=iaxs[fr->callno]->history[0];
2285 for (z=0;z < iax2_dropcount + 1;z++) {
2286 /* Start very optimistic ;-) */
2288 for (x=0;x<MEMORY_SIZE;x++) {
2289 if (max < iaxs[fr->callno]->history[x]) {
2290 /* We have a candidate new maximum value. Make
2291 sure it's not in our drop list */
2293 for (y=0;!match && (y<z);y++)
2294 match |= (drops[y] == x);
2296 /* It's not in our list, use it as the new maximum */
2297 max = iaxs[fr->callno]->history[x];
2303 /* On our first pass, find the minimum too */
2304 if (min > iaxs[fr->callno]->history[x])
2305 min = iaxs[fr->callno]->history[x];
2315 type = JB_TYPE_CONTROL;
2318 if(fr->af.frametype == AST_FRAME_VOICE) {
2319 type = JB_TYPE_VOICE;
2320 len = ast_codec_get_samples(&fr->af) / 8;
2321 } else if(fr->af.frametype == AST_FRAME_CNG) {
2322 type = JB_TYPE_SILENCE;
2325 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2330 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2331 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2332 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2333 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2334 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2337 /* deliver any frames in the jb */
2338 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2339 __do_deliver(frame.data);
2341 jb_reset(iaxs[fr->callno]->jb);
2343 if (iaxs[fr->callno]->jbid > -1)
2344 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2346 iaxs[fr->callno]->jbid = -1;
2348 /* deliver this frame now */
2355 /* insert into jitterbuffer */
2356 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2357 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2358 calc_rxstamp(iaxs[fr->callno],fr->ts));
2359 if (ret == JB_DROP) {
2360 iax2_frame_free(fr);
2361 } else if (ret == JB_SCHED) {
2362 update_jbsched(iaxs[fr->callno]);
2365 /* Just for reference, keep the "jitter" value, the difference between the
2366 earliest and the latest. */
2368 iaxs[fr->callno]->jitter = max - min;
2370 /* IIR filter for keeping track of historic jitter, but always increase
2371 historic jitter immediately for increase */
2373 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2374 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2376 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2377 iaxs[fr->callno]->historicjitter;
2379 /* If our jitter buffer is too big (by a significant margin), then we slowly
2380 shrink it to avoid letting the change be perceived */
2381 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2382 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2384 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2385 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2386 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2387 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2388 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2389 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2391 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2392 buffer immediately to accomodate it (and a little more). */
2393 if (max > iaxs[fr->callno]->jitterbuffer)
2394 iaxs[fr->callno]->jitterbuffer = max
2395 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2397 /* update "min", just for RRs and stats */
2398 iaxs[fr->callno]->min = min;
2400 /* Subtract the lateness from our jitter buffer to know how long to wait
2401 before sending our packet. */
2402 delay = iaxs[fr->callno]->jitterbuffer - ms;
2404 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2405 if (delay > maxjitterbuffer)
2406 delay = maxjitterbuffer;
2408 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2409 /* If frame came from trunk, also don't do any delay */
2410 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2414 /* Log jitter stats for possible offline analysis */
2415 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",
2416 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2417 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2418 min, max, iaxs[fr->callno]->jitterbuffer,
2419 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2421 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2425 /* Don't deliver it more than 4 ms late */
2426 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2428 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2432 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2433 iaxs[fr->callno]->frames_dropped++;
2434 /* Free our iax frame */
2435 iax2_frame_free(fr);
2439 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2440 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2446 static int iax2_transmit(struct iax_frame *fr)
2448 /* Lock the queue and place this packet at the end */
2451 /* By setting this to 0, the network thread will send it for us, and
2452 queue retransmission if necessary */
2454 ast_mutex_lock(&iaxq.lock);
2461 iaxq.tail->next = fr;
2462 fr->prev = iaxq.tail;
2466 ast_mutex_unlock(&iaxq.lock);
2467 /* Wake up the network thread */
2468 pthread_kill(netthreadid, SIGURG);
2474 static int iax2_digit(struct ast_channel *c, char digit)
2476 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2479 static int iax2_sendtext(struct ast_channel *c, const char *text)
2482 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2483 0, 0, text, strlen(text) + 1, -1);
2486 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2488 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2491 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2493 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2496 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2498 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2499 ast_mutex_lock(&iaxsl[callno]);
2501 iaxs[callno]->owner = newchan;
2503 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2504 ast_mutex_unlock(&iaxsl[callno]);
2508 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2509 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2511 static void destroy_user(struct iax2_user *user);
2512 static int expire_registry(void *data);
2514 static struct iax2_peer *realtime_peer(const char *peername)
2516 struct ast_variable *var;
2517 struct ast_variable *tmp;
2518 struct iax2_peer *peer=NULL;
2519 time_t regseconds, nowtime;
2522 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2526 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2533 /* Make sure it's not a user only... */
2534 if (!strcasecmp(tmp->name, "type")) {
2535 if (strcasecmp(tmp->value, "friend") &&
2536 strcasecmp(tmp->value, "peer")) {
2537 /* Whoops, we weren't supposed to exist! */
2542 } else if (!strcasecmp(tmp->name, "regseconds")) {
2543 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2545 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2546 inet_aton(tmp->value, &(peer->addr.sin_addr));
2547 } else if (!strcasecmp(tmp->name, "port")) {
2548 peer->addr.sin_port = htons(atoi(tmp->value));
2549 } else if (!strcasecmp(tmp->name, "host")) {
2550 if (!strcasecmp(tmp->value, "dynamic"))
2558 ast_variables_destroy(var);
2560 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2561 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2562 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2563 if (peer->expire > -1)
2564 ast_sched_del(sched, peer->expire);
2565 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2567 ast_mutex_lock(&peerl.lock);
2568 peer->next = peerl.peers;
2570 ast_mutex_unlock(&peerl.lock);
2571 if (ast_test_flag(peer, IAX_DYNAMIC))
2572 reg_source_db(peer);
2574 ast_set_flag(peer, IAX_TEMPONLY);
2577 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2579 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2580 memset(&peer->addr, 0, sizeof(peer->addr));
2582 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2589 static struct iax2_user *realtime_user(const char *username)
2591 struct ast_variable *var;
2592 struct ast_variable *tmp;
2593 struct iax2_user *user=NULL;
2595 var = ast_load_realtime("iaxusers", "name", username, NULL);
2601 /* Make sure it's not a peer only... */
2602 if (!strcasecmp(tmp->name, "type")) {
2603 if (strcasecmp(tmp->value, "friend") &&
2604 strcasecmp(tmp->value, "user")) {
2611 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2615 ast_variables_destroy(var);
2617 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2618 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2619 ast_mutex_lock(&userl.lock);
2620 user->next = userl.users;
2622 ast_mutex_unlock(&userl.lock);
2624 ast_set_flag(user, IAX_TEMPONLY);
2630 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2634 char regseconds[20];
2638 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2639 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2640 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2641 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2644 struct create_addr_info {
2656 char context[AST_MAX_EXTENSION];
2657 char peercontext[AST_MAX_EXTENSION];
2660 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2662 struct ast_hostent ahp;
2664 struct iax2_peer *peer;
2666 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2667 cai->sockfd = defaultsockfd;
2669 sin->sin_family = AF_INET;
2671 if (!(peer = find_peer(peername, 1))) {
2674 hp = ast_gethostbyname(peername, &ahp);
2676 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2677 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2678 /* use global iax prefs for unknown peer/user */
2679 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2682 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2689 /* if the peer has no address (current or default), return failure */
2690 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2691 if (ast_test_flag(peer, IAX_TEMPONLY))
2696 /* if the peer is being monitored and is currently unreachable, return failure */
2697 if (peer->maxms && (peer->lastms > peer->maxms)) {
2698 if (ast_test_flag(peer, IAX_TEMPONLY))
2703 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2704 cai->maxtime = peer->maxms;
2705 cai->capability = peer->capability;
2706 cai->encmethods = peer->encmethods;
2707 cai->sockfd = peer->sockfd;
2708 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2709 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2710 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2711 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2712 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2713 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2714 if (ast_strlen_zero(peer->dbsecret)) {
2715 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2720 family = ast_strdupa(peer->dbsecret);
2722 key = strchr(family, '/');
2726 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2727 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2728 if (ast_test_flag(peer, IAX_TEMPONLY))
2734 if (peer->addr.sin_addr.s_addr) {
2735 sin->sin_addr = peer->addr.sin_addr;
2736 sin->sin_port = peer->addr.sin_port;
2738 sin->sin_addr = peer->defaddr.sin_addr;
2739 sin->sin_port = peer->defaddr.sin_port;
2742 if (ast_test_flag(peer, IAX_TEMPONLY))
2748 static int auto_congest(void *nothing)
2750 int callno = PTR_TO_CALLNO(nothing);
2751 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2752 ast_mutex_lock(&iaxsl[callno]);
2754 iaxs[callno]->initid = -1;
2755 iax2_queue_frame(callno, &f);
2756 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2758 ast_mutex_unlock(&iaxsl[callno]);
2762 static unsigned int iax2_datetime(char *tz)
2768 localtime_r(&t, &tm);
2769 if (!ast_strlen_zero(tz))
2770 ast_localtime(&t, &tm, tz);
2771 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2772 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2773 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2774 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2775 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2776 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2780 struct parsed_dial_string {
2792 * \brief Parses an IAX dial string into its component parts.
2793 * \param data the string to be parsed
2794 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2797 * This function parses the string and fills the structure
2798 * with pointers to its component parts. The input string
2801 * \note This function supports both plaintext passwords and RSA
2802 * key names; if the password string is formatted as '[keyname]',
2803 * then the keyname will be placed into the key field, and the
2804 * password field will be set to NULL.
2806 * \note The dial string format is:
2807 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2809 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2811 if (!data || ast_strlen_zero(data))
2814 pds->peer = strsep(&data, "/");
2815 pds->exten = strsep(&data, "/");
2816 pds->options = data;
2820 pds->exten = strsep(&data, "@");
2821 pds->context = data;
2824 if (strchr(pds->peer, '@')) {
2826 pds->username = strsep(&data, "@");
2830 if (pds->username) {
2831 data = pds->username;
2832 pds->username = strsep(&data, ":");
2833 pds->password = data;
2837 pds->peer = strsep(&data, ":");
2840 /* check for a key name wrapped in [] in the secret position, if found,
2841 move it to the key field instead
2843 if (pds->password && (pds->password[0] == '[')) {
2844 pds->key = ast_strip_quoted(pds->password, "[", "]");
2845 pds->password = NULL;
2849 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2851 struct sockaddr_in sin;
2852 char *l=NULL, *n=NULL, *tmpstr;
2853 struct iax_ie_data ied;
2854 char *defaultrdest = "s";
2855 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2856 struct parsed_dial_string pds;
2857 struct create_addr_info cai;
2859 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2860 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2864 memset(&cai, 0, sizeof(cai));
2865 cai.encmethods = iax2_encryption;
2867 memset(&pds, 0, sizeof(pds));
2868 tmpstr = ast_strdupa(dest);
2869 parse_dial_string(tmpstr, &pds);
2872 pds.exten = defaultrdest;
2874 if (create_addr(pds.peer, &sin, &cai)) {
2875 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2879 if (!pds.username && !ast_strlen_zero(cai.username))
2880 pds.username = cai.username;
2881 if (!pds.password && !ast_strlen_zero(cai.secret))
2882 pds.password = cai.secret;
2883 if (!pds.key && !ast_strlen_zero(cai.outkey))
2884 pds.key = cai.outkey;
2885 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2886 pds.context = cai.peercontext;
2888 /* Keep track of the context for outgoing calls too */
2889 ast_copy_string(c->context, cai.context, sizeof(c->context));
2892 sin.sin_port = htons(atoi(pds.port));
2895 n = c->cid.cid_name;
2897 /* Now build request */
2898 memset(&ied, 0, sizeof(ied));
2900 /* On new call, first IE MUST be IAX version of caller */
2901 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2902 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2903 if (pds.options && strchr(pds.options, 'a')) {
2904 /* Request auto answer */
2905 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2908 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2911 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2912 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2914 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2917 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2918 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2921 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2922 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2923 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2925 if (c->language && !ast_strlen_zero(c->language))
2926 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2927 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2928 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2931 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2934 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2937 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2939 ast_mutex_lock(&iaxsl[callno]);
2941 if (!ast_strlen_zero(c->context))
2942 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2945 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2947 iaxs[callno]->encmethods = cai.encmethods;
2950 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2952 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2954 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2955 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2956 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2957 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2959 if (iaxs[callno]->maxtime) {
2960 /* Initialize pingtime and auto-congest time */
2961 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2962 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2963 } else if (autokill) {
2964 iaxs[callno]->pingtime = autokill / 2;
2965 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2968 /* Transmit the string in a "NEW" request */
2969 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2971 ast_mutex_unlock(&iaxsl[callno]);
2972 ast_setstate(c, AST_STATE_RINGING);
2977 static int iax2_hangup(struct ast_channel *c)
2979 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2981 struct iax_ie_data ied;
2982 memset(&ied, 0, sizeof(ied));
2983 ast_mutex_lock(&iaxsl[callno]);
2984 if (callno && iaxs[callno]) {
2985 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2986 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2987 /* Send the hangup unless we have had a transmission error or are already gone */
2988 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2989 if (!iaxs[callno]->error && !alreadygone)
2990 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2991 /* Explicitly predestroy it */
2992 iax2_predestroy_nolock(callno);
2993 /* If we were already gone to begin with, destroy us now */
2995 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2996 iax2_destroy_nolock(callno);
2999 ast_mutex_unlock(&iaxsl[callno]);
3000 if (option_verbose > 2)
3001 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3005 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3007 struct ast_option_header *h;
3009 h = malloc(datalen + sizeof(struct ast_option_header));
3011 h->flag = AST_OPTION_FLAG_REQUEST;
3012 h->option = htons(option);
3013 memcpy(h->data, data, datalen);
3014 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3015 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
3019 ast_log(LOG_WARNING, "Out of memory\n");
3023 static struct ast_frame *iax2_read(struct ast_channel *c)
3025 static struct ast_frame f = { AST_FRAME_NULL, };
3026 ast_log(LOG_NOTICE, "I should never be called!\n");
3030 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3033 struct iax_ie_data ied0;
3034 struct iax_ie_data ied1;
3035 unsigned int transferid = rand();
3036 memset(&ied0, 0, sizeof(ied0));
3037 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3038 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3039 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3041 memset(&ied1, 0, sizeof(ied1));
3042 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3043 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3044 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3046 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3049 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3052 iaxs[callno0]->transferring = TRANSFER_BEGIN;
3053 iaxs[callno1]->transferring = TRANSFER_BEGIN;
3057 static void lock_both(unsigned short callno0, unsigned short callno1)
3059 ast_mutex_lock(&iaxsl[callno0]);
3060 while (ast_mutex_trylock(&iaxsl[callno1])) {
3061 ast_mutex_unlock(&iaxsl[callno0]);
3063 ast_mutex_lock(&iaxsl[callno0]);
3067 static void unlock_both(unsigned short callno0, unsigned short callno1)
3069 ast_mutex_unlock(&iaxsl[callno1]);
3070 ast_mutex_unlock(&iaxsl[callno0]);
3073 static int iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
3075 struct ast_channel *cs[3];
3076 struct ast_channel *who;
3079 int transferstarted=0;
3080 struct ast_frame *f;
3081 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3082 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3083 struct timeval waittimer = {0, 0}, tv;
3085 lock_both(callno0, callno1);
3086 /* Put them in native bridge mode */
3087 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3088 iaxs[callno0]->bridgecallno = callno1;
3089 iaxs[callno1]->bridgecallno = callno0;
3091 unlock_both(callno0, callno1);
3093 /* If not, try to bridge until we can execute a transfer, if we can */
3096 for (/* ever */;;) {
3097 /* Check in case we got masqueraded into */
3098 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3099 if (option_verbose > 2)
3100 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3101 /* Remove from native mode */
3102 if (c0->type == channeltype) {
3103 ast_mutex_lock(&iaxsl[callno0]);
3104 iaxs[callno0]->bridgecallno = 0;
3105 ast_mutex_unlock(&iaxsl[callno0]);
3107 if (c1->type == channeltype) {
3108 ast_mutex_lock(&iaxsl[callno1]);
3109 iaxs[callno1]->bridgecallno = 0;
3110 ast_mutex_unlock(&iaxsl[callno1]);
3114 if (c0->nativeformats != c1->nativeformats) {
3115 if (option_verbose > 2) {
3118 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3119 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3120 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3122 /* Remove from native mode */
3123 lock_both(callno0, callno1);
3124 iaxs[callno0]->bridgecallno = 0;
3125 iaxs[callno1]->bridgecallno = 0;
3126 unlock_both(callno0, callno1);
3129 /* check if transfered and if we really want native bridging */
3130 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
3131 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3132 /* Try the transfer */
3133 if (iax2_start_transfer(callno0, callno1))
3134 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3135 transferstarted = 1;
3137 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3138 /* Call has been transferred. We're no longer involved */
3139 gettimeofday(&tv, NULL);
3140 if (!waittimer.tv_sec