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"
45 #include "asterisk/devicestate.h"
46 #include "asterisk/netsock.h"
49 #include <arpa/inet.h>
51 #include <sys/socket.h>
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
56 #include <sys/signal.h>
65 #include <sys/types.h>
69 #include <sys/ioctl.h>
71 #include <linux/zaptel.h>
74 #endif /* __linux__ */
77 #include "iax2-parser.h"
78 #include "iax2-provision.h"
80 /* Define NEWJB to use the new channel independent jitterbuffer,
81 * otherwise, use the old jitterbuffer */
85 #include "../jitterbuf.h"
89 #define IPTOS_MINCOST 0x02
93 static int nochecksums = 0;
97 * Uncomment to try experimental IAX bridge optimization,
98 * designed to reduce latency when IAX calls cannot
99 * be trasnferred -- obsolete
102 /* #define BRIDGE_OPTIMIZATION */
105 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
106 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
108 #define DEFAULT_RETRY_TIME 1000
109 #define MEMORY_SIZE 100
110 #define DEFAULT_DROP 3
111 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
112 but keeps the division between trunked and non-trunked better. */
113 #define TRUNK_CALL_START 0x4000
115 #define DEBUG_SUPPORT
117 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
119 /* Sample over last 100 units to determine historic jitter */
122 static struct ast_codec_pref prefs;
124 static const char desc[] = "Inter Asterisk eXchange (Ver 2)";
125 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
126 static const char channeltype[] = "IAX2";
128 static char context[80] = "default";
130 static char language[MAX_LANGUAGE] = "";
131 static char regcontext[AST_MAX_CONTEXT] = "";
133 static int max_retries = 4;
134 static int ping_time = 20;
135 static int lagrq_time = 10;
136 static int maxtrunkcall = TRUNK_CALL_START;
137 static int maxnontrunkcall = 1;
138 static int maxjitterbuffer=1000;
140 static int resyncthreshold=1000;
141 static int maxjitterinterps=10;
143 static int jittershrinkrate=2;
144 static int trunkfreq = 20;
145 static int authdebug = 1;
146 static int autokill = 0;
147 static int iaxcompat = 0;
149 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
151 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
155 static int expirey = IAX_DEFAULT_REG_EXPIRE;
157 static int timingfd = -1; /* Timing file descriptor */
159 static struct ast_netsock_list *netsock;
160 static int defaultsockfd = -1;
163 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
165 int (*iax2_regfunk)(char *username, int onoff) = NULL;
168 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
170 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
171 ~AST_FORMAT_SLINEAR & \
175 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
179 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
183 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
184 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
185 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
187 static struct io_context *io;
188 static struct sched_context *sched;
190 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
192 static int iax2_dropcount = DEFAULT_DROP;
194 static int iaxdebug = 0;
196 static int iaxtrunkdebug = 0;
198 static int test_losspct = 0;
200 static int test_late = 0;
201 static int test_resync = 0;
202 static int test_jit = 0;
203 static int test_jitpct = 0;
204 #endif /* IAXTESTS */
206 static char accountcode[AST_MAX_ACCOUNT_CODE];
207 static int amaflags = 0;
208 static int delayreject = 0;
209 static int iax2_encryption = 0;
211 static struct ast_flags globalflags = { 0 };
213 static pthread_t netthreadid = AST_PTHREADT_NULL;
215 #define IAX_STATE_STARTED (1 << 0)
216 #define IAX_STATE_AUTHENTICATED (1 << 1)
217 #define IAX_STATE_TBD (1 << 2)
219 struct iax2_context {
220 char context[AST_MAX_CONTEXT];
221 struct iax2_context *next;
224 #define IAX_HASCALLERID (1 << 0) /* CallerID has been specified */
225 #define IAX_DELME (1 << 1) /* Needs to be deleted */
226 #define IAX_TEMPONLY (1 << 2) /* Temporary (realtime) */
227 #define IAX_TRUNK (1 << 3) /* Treat as a trunk */
228 #define IAX_NOTRANSFER (1 << 4) /* Don't native bridge */
229 #define IAX_USEJITTERBUF (1 << 5) /* Use jitter buffer */
230 #define IAX_DYNAMIC (1 << 6) /* dynamic peer */
231 #define IAX_SENDANI (1 << 7) /* Send ANI along with CallerID */
232 #define IAX_MESSAGEDETAIL (1 << 8) /* Show exact numbers */
233 #define IAX_ALREADYGONE (1 << 9) /* Already disconnected */
234 #define IAX_PROVISION (1 << 10) /* This is a provisioning request */
235 #define IAX_QUELCH (1 << 11) /* Whether or not we quelch audio */
236 #define IAX_ENCRYPTED (1 << 12) /* Whether we should assume encrypted tx/rx */
237 #define IAX_KEYPOPULATED (1 << 13) /* Whether we have a key populated */
238 #define IAX_CODEC_USER_FIRST (1 << 14) /* are we willing to let the other guy choose the codec? */
239 #define IAX_CODEC_NOPREFS (1 << 15) /* Force old behaviour by turning off prefs */
240 #define IAX_CODEC_NOCAP (1 << 16) /* only consider requested format and ignore capabilities*/
241 #define IAX_RTCACHEFRIENDS (1 << 17) /* let realtime stay till your reload */
242 #define IAX_RTNOUPDATE (1 << 18) /* Don't send a realtime update */
243 #define IAX_RTAUTOCLEAR (1 << 19) /* erase me on expire */
244 #define IAX_FORCEJITTERBUF (1 << 20) /* Force jitterbuffer, even when bridged to a channel that can take jitter */
245 #define IAX_RTIGNOREREGEXPIRE (1 << 21)
246 #define IAX_TRUNKTIMESTAMPS (1 << 22) /* Send trunk timestamps */
248 static int global_rtautoclear = 120;
250 static int reload_config(void);
251 static int iax2_reload(int fd, int argc, char *argv[]);
260 char accountcode[AST_MAX_ACCOUNT_CODE];
261 char inkeys[80]; /* Key(s) this user can use to authenticate to us */
262 char language[MAX_LANGUAGE];
266 char cid_num[AST_MAX_EXTENSION];
267 char cid_name[AST_MAX_EXTENSION];
268 struct ast_codec_pref prefs;
270 struct iax2_context *contexts;
271 struct iax2_user *next;
272 struct ast_variable *vars;
280 char outkey[80]; /* What key we use to talk to this peer */
281 char context[AST_MAX_CONTEXT]; /* For transfers only */
282 char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
283 char peercontext[AST_MAX_EXTENSION]; /* Context to pass to peer */
284 char mailbox[AST_MAX_EXTENSION]; /* Mailbox */
285 struct ast_codec_pref prefs;
286 struct ast_dnsmgr_entry *dnsmgr; /* DNS refresh manager */
287 struct sockaddr_in addr;
289 int sockfd; /* Socket to use for transmission */
293 /* Dynamic Registration fields */
294 struct sockaddr_in defaddr; /* Default address if there is one */
295 int authmethods; /* Authentication methods (IAX_AUTH_*) */
296 int encmethods; /* Encryption methods (IAX_ENCRYPT_*) */
297 char inkeys[80]; /* Key(s) this peer can use to authenticate to us */
299 /* Suggested caller id if registering */
300 char cid_num[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
301 char cid_name[AST_MAX_EXTENSION]; /* Default context (for transfer really) */
303 int expire; /* Schedule entry for expirey */
304 int expirey; /* How soon to expire */
305 int capability; /* Capability */
306 char zonetag[80]; /* Time Zone */
309 int callno; /* Call number of POKE request */
310 int pokeexpire; /* When to expire poke */
311 int lastms; /* How long last response took (in ms), or -1 for no response */
312 int maxms; /* Max ms we will accept for the host to be up, 0 to not monitor */
314 int pokefreqok; /* How often to check if the host is up */
315 int pokefreqnotok; /* How often to check when the host has been determined to be down */
316 int historicms; /* How long recent average responses took */
317 int smoothing; /* Sample over how many units to determine historic ms */
320 struct iax2_peer *next;
323 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
325 static struct iax2_trunk_peer {
328 struct sockaddr_in addr;
329 struct timeval txtrunktime; /* Transmit trunktime */
330 struct timeval rxtrunktime; /* Receive trunktime */
331 struct timeval lasttxtime; /* Last transmitted trunktime */
332 struct timeval trunkact; /* Last trunk activity */
333 unsigned int lastsent; /* Last sent time */
334 /* Trunk data and length */
335 unsigned char *trunkdata;
336 unsigned int trunkdatalen;
337 unsigned int trunkdataalloc;
338 struct iax2_trunk_peer *next;
343 AST_MUTEX_DEFINE_STATIC(tpeerlock);
345 struct iax_firmware {
346 struct iax_firmware *next;
350 struct ast_iax2_firmware_header *fwh;
354 #define REG_STATE_UNREGISTERED 0
355 #define REG_STATE_REGSENT 1
356 #define REG_STATE_AUTHSENT 2
357 #define REG_STATE_REGISTERED 3
358 #define REG_STATE_REJECTED 4
359 #define REG_STATE_TIMEOUT 5
360 #define REG_STATE_NOAUTH 6
362 #define TRANSFER_NONE 0
363 #define TRANSFER_BEGIN 1
364 #define TRANSFER_READY 2
365 #define TRANSFER_RELEASED 3
366 #define TRANSFER_PASSTHROUGH 4
368 struct iax2_registry {
369 struct sockaddr_in addr; /* Who we connect to for registration purposes */
371 char secret[80]; /* Password or key name in []'s */
373 int expire; /* Sched ID of expiration */
374 int refresh; /* How often to refresh */
376 int messages; /* Message count */
377 int callno; /* Associated call number if applicable */
378 struct sockaddr_in us; /* Who the server thinks we are */
379 struct iax2_registry *next;
382 static struct iax2_registry *registrations;
384 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
385 #define MIN_RETRY_TIME 100
386 #define MAX_RETRY_TIME 10000
388 #define MAX_JITTER_BUFFER 50
389 #define MIN_JITTER_BUFFER 10
391 #define DEFAULT_TRUNKDATA 640 * 10 /* 40ms, uncompressed linear * 10 channels */
392 #define MAX_TRUNKDATA 640 * 200 /* 40ms, uncompressed linear * 200 channels */
394 #define MAX_TIMESTAMP_SKEW 160 /* maximum difference between actual and predicted ts for sending */
396 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
397 #define TS_GAP_FOR_JB_RESYNC 5000
399 /* If we have more than this much excess real jitter buffer, shrink it. */
400 static int max_jitter_buffer = MAX_JITTER_BUFFER;
401 /* If we have less than this much excess real jitter buffer, enlarge it. */
402 static int min_jitter_buffer = MIN_JITTER_BUFFER;
414 struct chan_iax2_pvt {
415 /* Socket to send/receive on for this call */
417 /* Last received voice format */
419 /* Last received voice format */
421 /* Last sent voice format */
423 /* Last sent video format */
425 /* What we are capable of sending */
427 /* Last received timestamp */
429 /* Last sent timestamp - never send the same timestamp twice in a single call */
430 unsigned int lastsent;
431 /* Next outgoing timestamp if everything is good */
432 unsigned int nextpred;
433 /* True if the last voice we transmitted was not silence/CNG */
436 unsigned int pingtime;
437 /* Max time for initial response */
440 struct sockaddr_in addr;
441 struct ast_codec_pref prefs;
442 /* Our call number */
443 unsigned short callno;
445 unsigned short peercallno;
446 /* Peer selected format */
448 /* Peer capability */
450 /* timeval that we base our transmission on */
451 struct timeval offset;
452 /* timeval that we base our delivery on */
453 struct timeval rxcore;
455 /* The jitterbuffer */
457 /* active jb read scheduler id */
460 /* Historical delivery time */
461 int history[MEMORY_SIZE];
462 /* Current base jitterbuffer */
464 /* Current jitter measure */
466 /* Historic jitter value */
471 /* Error, as discovered by the manager */
473 /* Owner if we have one */
474 struct ast_channel *owner;
475 /* What's our state? */
477 /* Expirey (optional) */
479 /* Next outgoing sequence number */
480 unsigned char oseqno;
481 /* Next sequence number they have not yet acknowledged */
482 unsigned char rseqno;
483 /* Next incoming sequence number */
484 unsigned char iseqno;
485 /* Last incoming sequence number we have acknowledged */
486 unsigned char aseqno;
489 /* Default Context */
491 /* Caller ID if available */
494 /* Hidden Caller ID (i.e. ANI) if appropriate */
498 /* Requested Extension */
499 char exten[AST_MAX_EXTENSION];
500 /* Expected Username */
502 /* Expected Secret */
504 /* permitted authentication methods */
506 /* permitted encryption methods */
510 /* Public keys permitted keys for incoming authentication */
512 /* Private key for outgoing authentication */
514 /* Encryption AES-128 Key */
516 /* Decryption AES-128 Key */
518 /* 32 bytes of semi-random data */
520 /* Preferred language */
521 char language[MAX_LANGUAGE];
522 /* Hostname/peername for naming purposes */
524 /* Associated registry */
525 struct iax2_registry *reg;
526 /* Associated peer for poking */
527 struct iax2_peer *peerpoke;
531 /* Transferring status */
533 /* Transfer identifier */
535 /* Who we are IAX transfering to */
536 struct sockaddr_in transfer;
537 /* What's the new call number for the transfer */
538 unsigned short transfercallno;
539 /* Transfer decrypt AES-128 Key */
540 aes_encrypt_ctx tdcx;
542 /* Status of knowledge of peer ADSI capability */
545 /* Who we are bridged to */
546 unsigned short bridgecallno;
547 unsigned int bridgesfmt;
548 struct ast_trans_pvt *bridgetrans;
550 int pingid; /* Transmit PING request */
551 int lagid; /* Retransmit lag request */
552 int autoid; /* Auto hangup for Dialplan requestor */
553 int authid; /* Authentication rejection ID */
554 int authfail; /* Reason to report failure */
555 int initid; /* Initial peer auto-congest ID (based on qualified peers) */
559 char dproot[AST_MAX_EXTENSION];
560 char accountcode[AST_MAX_ACCOUNT_CODE];
562 struct iax2_dpcache *dpentries;
563 struct ast_variable *vars;
564 /* last received remote rr */
565 struct iax_rr remote_rr;
566 /* Current base time: (just for stats) */
568 /* Dropped frame count: (just for stats) */
570 /* received frame count: (just for stats) */
574 static struct ast_iax2_queue {
575 struct iax_frame *head;
576 struct iax_frame *tail;
581 static struct ast_user_list {
582 struct iax2_user *users;
586 static struct ast_peer_list {
587 struct iax2_peer *peers;
591 static struct ast_firmware_list {
592 struct iax_firmware *wares;
596 /* Extension exists */
597 #define CACHE_FLAG_EXISTS (1 << 0)
598 /* Extension is nonexistent */
599 #define CACHE_FLAG_NONEXISTENT (1 << 1)
600 /* Extension can exist */
601 #define CACHE_FLAG_CANEXIST (1 << 2)
602 /* Waiting to hear back response */
603 #define CACHE_FLAG_PENDING (1 << 3)
605 #define CACHE_FLAG_TIMEOUT (1 << 4)
606 /* Request transmitted */
607 #define CACHE_FLAG_TRANSMITTED (1 << 5)
609 #define CACHE_FLAG_UNKNOWN (1 << 6)
611 #define CACHE_FLAG_MATCHMORE (1 << 7)
613 static struct iax2_dpcache {
614 char peercontext[AST_MAX_CONTEXT];
615 char exten[AST_MAX_EXTENSION];
617 struct timeval expirey;
619 unsigned short callno;
621 struct iax2_dpcache *next;
622 struct iax2_dpcache *peer; /* For linking in peers */
625 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
627 static void reg_source_db(struct iax2_peer *p);
628 static struct iax2_peer *realtime_peer(const char *peername);
630 static void destroy_peer(struct iax2_peer *peer);
631 static int ast_cli_netstats(int fd, int limit_fmt);
633 static void iax_debug_output(const char *data)
636 ast_verbose("%s", data);
639 static void iax_error_output(const char *data)
641 ast_log(LOG_WARNING, "%s", data);
645 static void jb_error_output(const char *fmt, ...)
651 vsnprintf(buf, 1024, fmt, args);
654 ast_log(LOG_ERROR, buf);
657 static void jb_warning_output(const char *fmt, ...)
663 vsnprintf(buf, 1024, fmt, args);
666 ast_log(LOG_WARNING, buf);
669 static void jb_debug_output(const char *fmt, ...)
675 vsnprintf(buf, 1024, fmt, args);
683 /* XXX We probably should use a mutex when working with this XXX */
684 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
685 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
686 static struct timeval lastused[IAX_MAX_CALLS];
689 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
690 static int send_command_locked(unsigned short callno, char, int, unsigned int, const char *, int, int);
691 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
692 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int, int);
693 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const char *, int);
694 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
695 static void destroy_user(struct iax2_user *user);
696 static int expire_registry(void *data);
697 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
698 static int iax2_do_register(struct iax2_registry *reg);
699 static void prune_peers(void);
700 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
701 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
703 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
704 static int iax2_devicestate(void *data);
705 static int iax2_digit(struct ast_channel *c, char digit);
706 static int iax2_sendtext(struct ast_channel *c, const char *text);
707 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
708 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
709 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
710 static int iax2_hangup(struct ast_channel *c);
711 static int iax2_answer(struct ast_channel *c);
712 static struct ast_frame *iax2_read(struct ast_channel *c);
713 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
714 static int iax2_indicate(struct ast_channel *c, int condition);
715 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
716 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);
717 static int iax2_transfer(struct ast_channel *c, const char *dest);
718 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
720 static const struct ast_channel_tech iax2_tech = {
722 .description = tdesc,
723 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
724 .properties = AST_CHAN_TP_WANTSJITTER,
725 .requester = iax2_request,
726 .devicestate = iax2_devicestate,
727 .send_digit = iax2_digit,
728 .send_text = iax2_sendtext,
729 .send_image = iax2_sendimage,
730 .send_html = iax2_sendhtml,
732 .hangup = iax2_hangup,
733 .answer = iax2_answer,
736 .write_video = iax2_write,
737 .indicate = iax2_indicate,
738 .setoption = iax2_setoption,
739 .bridge = iax2_bridge,
740 .transfer = iax2_transfer,
744 static int send_ping(void *data)
746 int callno = (long)data;
747 /* Ping only if it's real, not if it's bridged */
749 #ifdef BRIDGE_OPTIMIZATION
750 if (!iaxs[callno]->bridgecallno)
752 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
758 static int get_encrypt_methods(const char *s)
761 if (!strcasecmp(s, "aes128"))
762 e = IAX_ENCRYPT_AES128;
763 else if (ast_true(s))
764 e = IAX_ENCRYPT_AES128;
770 static int send_lagrq(void *data)
772 int callno = (long)data;
773 /* Ping only if it's real not if it's bridged */
775 #ifdef BRIDGE_OPTIMIZATION
776 if (!iaxs[callno]->bridgecallno)
778 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
784 static unsigned char compress_subclass(int subclass)
788 /* If it's 128 or smaller, just return it */
789 if (subclass < IAX_FLAG_SC_LOG)
791 /* Otherwise find its power */
792 for (x = 0; x < IAX_MAX_SHIFT; x++) {
793 if (subclass & (1 << x)) {
795 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
801 return power | IAX_FLAG_SC_LOG;
804 static int uncompress_subclass(unsigned char csub)
806 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
807 if (csub & IAX_FLAG_SC_LOG) {
808 /* special case for 'compressed' -1 */
812 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
818 static struct iax2_peer *find_peer(const char *name, int realtime)
820 struct iax2_peer *peer;
821 ast_mutex_lock(&peerl.lock);
822 for(peer = peerl.peers; peer; peer = peer->next) {
823 if (!strcasecmp(peer->name, name)) {
827 ast_mutex_unlock(&peerl.lock);
828 if(!peer && realtime)
829 peer = realtime_peer(name);
833 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
835 struct iax2_peer *peer;
838 ast_mutex_lock(&peerl.lock);
841 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
842 (peer->addr.sin_port == sin.sin_port)) {
843 ast_copy_string(host, peer->name, len);
850 ast_mutex_unlock(&peerl.lock);
854 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
856 struct chan_iax2_pvt *tmp;
857 tmp = malloc(sizeof(struct chan_iax2_pvt));
859 memset(tmp, 0, sizeof(struct chan_iax2_pvt));
863 tmp->transfercallno = 0;
864 tmp->bridgecallno = 0;
870 /* ast_copy_string(tmp->context, context, sizeof(tmp->context)); */
871 ast_copy_string(tmp->exten, "s", sizeof(tmp->exten));
872 ast_copy_string(tmp->host, host, sizeof(tmp->host));
879 jbconf.max_jitterbuf = maxjitterbuffer;
880 jbconf.resync_threshold = resyncthreshold;
881 jbconf.max_contig_interp = maxjitterinterps;
882 jb_setconf(tmp->jb,&jbconf);
889 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
891 /* Malloc() a copy of a frame */
892 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
894 memcpy(new, fr, sizeof(struct iax_frame));
895 iax_frame_wrap(new, &fr->af);
898 new->direction = DIRECTION_INGRESS;
904 #define NEW_PREVENT 0
908 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
910 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
911 (cur->addr.sin_port == sin->sin_port)) {
912 /* This is the main host */
913 if ((cur->peercallno == callno) ||
914 ((dcallno == cur->callno) && !cur->peercallno)) {
915 /* That's us. Be sure we keep track of the peer call number */
919 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
920 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
921 /* We're transferring */
922 if (dcallno == cur->callno)
928 static void update_max_trunk(void)
930 int max = TRUNK_CALL_START;
932 /* XXX Prolly don't need locks here XXX */
933 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
939 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
942 static void update_max_nontrunk(void)
946 /* XXX Prolly don't need locks here XXX */
947 for (x=1;x<TRUNK_CALL_START - 1; x++) {
951 maxnontrunkcall = max;
953 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
956 static int make_trunk(unsigned short callno, int locked)
961 if (iaxs[callno]->oseqno) {
962 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
965 if (callno & TRUNK_CALL_START) {
966 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
969 gettimeofday(&now, NULL);
970 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
971 ast_mutex_lock(&iaxsl[x]);
972 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
973 iaxs[x] = iaxs[callno];
976 /* Update the two timers that should have been started */
977 if (iaxs[x]->pingid > -1)
978 ast_sched_del(sched, iaxs[x]->pingid);
979 if (iaxs[x]->lagid > -1)
980 ast_sched_del(sched, iaxs[x]->lagid);
981 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
982 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
984 ast_mutex_unlock(&iaxsl[callno]);
987 ast_mutex_unlock(&iaxsl[x]);
990 ast_mutex_unlock(&iaxsl[x]);
992 if (x >= IAX_MAX_CALLS - 1) {
993 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
996 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
997 /* We move this call from a non-trunked to a trunked call */
999 update_max_nontrunk();
1003 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1008 char iabuf[INET_ADDRSTRLEN];
1010 if (new <= NEW_ALLOW) {
1011 /* Look for an existing connection first */
1012 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1013 ast_mutex_lock(&iaxsl[x]);
1015 /* Look for an exact match */
1016 if (match(sin, callno, dcallno, iaxs[x])) {
1020 ast_mutex_unlock(&iaxsl[x]);
1022 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1023 ast_mutex_lock(&iaxsl[x]);
1025 /* Look for an exact match */
1026 if (match(sin, callno, dcallno, iaxs[x])) {
1030 ast_mutex_unlock(&iaxsl[x]);
1033 if ((res < 1) && (new >= NEW_ALLOW)) {
1034 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1035 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr), ntohs(sin->sin_port));
1036 gettimeofday(&now, NULL);
1037 for (x=1;x<TRUNK_CALL_START;x++) {
1038 /* Find first unused call number that hasn't been used in a while */
1039 ast_mutex_lock(&iaxsl[x]);
1040 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1041 ast_mutex_unlock(&iaxsl[x]);
1043 /* We've still got lock held if we found a spot */
1044 if (x >= TRUNK_CALL_START) {
1045 ast_log(LOG_WARNING, "No more space\n");
1048 iaxs[x] = new_iax(sin, lockpeer, host);
1049 update_max_nontrunk();
1052 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1053 iaxs[x]->sockfd = sockfd;
1054 iaxs[x]->addr.sin_port = sin->sin_port;
1055 iaxs[x]->addr.sin_family = sin->sin_family;
1056 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1057 iaxs[x]->peercallno = callno;
1058 iaxs[x]->callno = x;
1059 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1060 iaxs[x]->expirey = expirey;
1061 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1062 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1063 iaxs[x]->amaflags = amaflags;
1064 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1065 ast_copy_string(iaxs[x]->accountcode, accountcode, sizeof(iaxs[x]->accountcode));
1067 ast_log(LOG_WARNING, "Out of resources\n");
1068 ast_mutex_unlock(&iaxsl[x]);
1071 ast_mutex_unlock(&iaxsl[x]);
1077 static void iax2_frame_free(struct iax_frame *fr)
1079 if (fr->retrans > -1)
1080 ast_sched_del(sched, fr->retrans);
1084 static int iax2_queue_frame(int callno, struct ast_frame *f)
1086 /* Assumes lock for callno is already held... */
1088 if (iaxs[callno] && iaxs[callno]->owner) {
1089 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1090 /* Avoid deadlock by pausing and trying again */
1091 ast_mutex_unlock(&iaxsl[callno]);
1093 ast_mutex_lock(&iaxsl[callno]);
1095 ast_queue_frame(iaxs[callno]->owner, f);
1096 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1105 static void destroy_firmware(struct iax_firmware *cur)
1107 /* Close firmware */
1109 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1115 static int try_firmware(char *s)
1118 struct iax_firmware *cur;
1123 struct ast_iax2_firmware_header *fwh, fwh2;
1124 struct MD5Context md5;
1125 unsigned char sum[16];
1126 unsigned char buf[1024];
1130 s2 = alloca(strlen(s) + 100);
1132 ast_log(LOG_WARNING, "Alloca failed!\n");
1135 last = strrchr(s, '/');
1140 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)rand());
1141 res = stat(s, &stbuf);
1143 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1146 /* Make sure it's not a directory */
1147 if (S_ISDIR(stbuf.st_mode))
1149 ifd = open(s, O_RDONLY);
1151 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1154 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1156 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1160 /* Unlink our newly created file */
1163 /* Now copy the firmware into it */
1164 len = stbuf.st_size;
1167 if (chunk > sizeof(buf))
1168 chunk = sizeof(buf);
1169 res = read(ifd, buf, chunk);
1171 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1176 res = write(fd, buf, chunk);
1178 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1186 /* Return to the beginning */
1187 lseek(fd, 0, SEEK_SET);
1188 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1189 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1193 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1194 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1198 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1199 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1203 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero(fwh2.devname)) {
1204 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1208 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1210 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1215 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1216 MD5Final(sum, &md5);
1217 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1218 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1219 munmap(fwh, stbuf.st_size);
1225 if (!strcmp(cur->fwh->devname, fwh->devname)) {
1226 /* Found a candidate */
1227 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1228 /* The version we have on loaded is older, load this one instead */
1230 /* This version is no newer than what we have. Don't worry about it.
1231 We'll consider it a proper load anyhow though */
1232 munmap(fwh, stbuf.st_size);
1239 /* Allocate a new one and link it */
1240 cur = malloc(sizeof(struct iax_firmware));
1242 memset(cur, 0, sizeof(struct iax_firmware));
1244 cur->next = waresl.wares;
1250 munmap(cur->fwh, cur->mmaplen);
1256 cur->mmaplen = stbuf.st_size;
1262 static int iax_check_version(char *dev)
1265 struct iax_firmware *cur;
1266 if (dev && !ast_strlen_zero(dev)) {
1267 ast_mutex_lock(&waresl.lock);
1270 if (!strcmp(dev, cur->fwh->devname)) {
1271 res = ntohs(cur->fwh->version);
1276 ast_mutex_unlock(&waresl.lock);
1281 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1284 unsigned int bs = desc & 0xff;
1285 unsigned int start = (desc >> 8) & 0xffffff;
1287 struct iax_firmware *cur;
1288 if (dev && !ast_strlen_zero(dev) && bs) {
1290 ast_mutex_lock(&waresl.lock);
1293 if (!strcmp(dev, cur->fwh->devname)) {
1294 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1295 if (start < ntohl(cur->fwh->datalen)) {
1296 bytes = ntohl(cur->fwh->datalen) - start;
1299 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1302 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1312 ast_mutex_unlock(&waresl.lock);
1318 static void reload_firmware(void)
1320 struct iax_firmware *cur, *curl, *curp;
1325 /* Mark all as dead */
1326 ast_mutex_lock(&waresl.lock);
1332 /* Now that we've freed them, load the new ones */
1333 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_VAR_DIR);
1336 while((de = readdir(fwd))) {
1337 if (de->d_name[0] != '.') {
1338 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1339 if (!try_firmware(fn)) {
1340 if (option_verbose > 1)
1341 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1347 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1349 /* Clean up leftovers */
1361 destroy_firmware(curl);
1366 ast_mutex_unlock(&waresl.lock);
1369 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1371 static int __do_deliver(void *data)
1373 /* Just deliver the packet by using queueing. This is called by
1374 the IAX thread with the iaxsl lock held. */
1375 struct iax_frame *fr = data;
1377 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1378 iax2_queue_frame(fr->callno, &fr->af);
1379 /* Free our iax frame */
1380 iax2_frame_free(fr);
1381 /* And don't run again */
1386 static int do_deliver(void *data)
1388 /* Locking version of __do_deliver */
1389 struct iax_frame *fr = data;
1390 int callno = fr->callno;
1392 ast_mutex_lock(&iaxsl[callno]);
1393 res = __do_deliver(data);
1394 ast_mutex_unlock(&iaxsl[callno]);
1399 static int handle_error(void)
1401 /* XXX Ideally we should figure out why an error occured and then abort those
1402 rather than continuing to try. Unfortunately, the published interface does
1403 not seem to work XXX */
1405 struct sockaddr_in *sin;
1408 struct sock_extended_err e;
1413 m.msg_controllen = sizeof(e);
1415 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1417 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1419 if (m.msg_controllen) {
1420 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1422 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr));
1424 ast_log(LOG_WARNING, "No address detected??\n");
1426 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1433 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1436 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1440 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1447 static int send_packet(struct iax_frame *f)
1450 char iabuf[INET_ADDRSTRLEN];
1451 /* Called with iaxsl held */
1452 if (option_debug > 2)
1453 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));
1454 /* Don't send if there was an error, but return error instead */
1456 ast_log(LOG_WARNING, "Call number = %d\n", f->callno);
1459 if (!iaxs[f->callno])
1461 if (iaxs[f->callno]->error)
1465 iax_showframe(f, NULL, 0, &iaxs[f->callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1466 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->transfer,
1467 sizeof(iaxs[f->callno]->transfer));
1470 iax_showframe(f, NULL, 0, &iaxs[f->callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1471 res = sendto(iaxs[f->callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[f->callno]->addr,
1472 sizeof(iaxs[f->callno]->addr));
1476 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1484 static int iax2_predestroy(int callno)
1486 struct ast_channel *c;
1487 struct chan_iax2_pvt *pvt;
1488 ast_mutex_lock(&iaxsl[callno]);
1491 ast_mutex_unlock(&iaxsl[callno]);
1494 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1495 /* No more pings or lagrq's */
1496 if (pvt->pingid > -1)
1497 ast_sched_del(sched, pvt->pingid);
1498 if (pvt->lagid > -1)
1499 ast_sched_del(sched, pvt->lagid);
1500 if (pvt->autoid > -1)
1501 ast_sched_del(sched, pvt->autoid);
1502 if (pvt->authid > -1)
1503 ast_sched_del(sched, pvt->authid);
1504 if (pvt->initid > -1)
1505 ast_sched_del(sched, pvt->initid);
1508 ast_sched_del(sched, pvt->jbid);
1516 ast_set_flag(pvt, IAX_ALREADYGONE);
1520 c->_softhangup |= AST_SOFTHANGUP_DEV;
1522 ast_queue_hangup(c);
1524 ast_mutex_lock(&usecnt_lock);
1527 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1528 ast_mutex_unlock(&usecnt_lock);
1530 ast_mutex_unlock(&iaxsl[callno]);
1531 ast_update_use_count();
1535 static int iax2_predestroy_nolock(int callno)
1538 ast_mutex_unlock(&iaxsl[callno]);
1539 res = iax2_predestroy(callno);
1540 ast_mutex_lock(&iaxsl[callno]);
1544 static void iax2_destroy(int callno)
1546 struct chan_iax2_pvt *pvt;
1547 struct iax_frame *cur;
1548 struct ast_channel *owner;
1551 ast_mutex_lock(&iaxsl[callno]);
1553 gettimeofday(&lastused[callno], NULL);
1560 if (ast_mutex_trylock(&owner->lock)) {
1561 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1562 ast_mutex_unlock(&iaxsl[callno]);
1568 iaxs[callno] = NULL;
1572 /* No more pings or lagrq's */
1573 if (pvt->pingid > -1)
1574 ast_sched_del(sched, pvt->pingid);
1575 if (pvt->lagid > -1)
1576 ast_sched_del(sched, pvt->lagid);
1577 if (pvt->autoid > -1)
1578 ast_sched_del(sched, pvt->autoid);
1579 if (pvt->authid > -1)
1580 ast_sched_del(sched, pvt->authid);
1581 if (pvt->initid > -1)
1582 ast_sched_del(sched, pvt->initid);
1585 ast_sched_del(sched, pvt->jbid);
1593 if (pvt->bridgetrans)
1594 ast_translator_free_path(pvt->bridgetrans);
1595 pvt->bridgetrans = NULL;
1598 ast_set_flag(pvt, IAX_ALREADYGONE);
1601 /* If there's an owner, prod it to give up */
1602 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1603 ast_queue_hangup(owner);
1606 for (cur = iaxq.head; cur ; cur = cur->next) {
1607 /* Cancel any pending transmissions */
1608 if (cur->callno == pvt->callno)
1612 pvt->reg->callno = 0;
1616 ast_variables_destroy(pvt->vars);
1622 while(jb_getall(pvt->jb,&frame) == JB_OK)
1623 iax2_frame_free(frame.data);
1624 jb_destroy(pvt->jb);
1631 ast_mutex_unlock(&owner->lock);
1633 ast_mutex_unlock(&iaxsl[callno]);
1634 if (callno & 0x4000)
1637 static void iax2_destroy_nolock(int callno)
1639 /* Actually it's easier to unlock, kill it, and relock */
1640 ast_mutex_unlock(&iaxsl[callno]);
1641 iax2_destroy(callno);
1642 ast_mutex_lock(&iaxsl[callno]);
1645 static int update_packet(struct iax_frame *f)
1647 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1648 struct ast_iax2_full_hdr *fh = f->data;
1649 /* Mark this as a retransmission */
1650 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1652 f->iseqno = iaxs[f->callno]->iseqno;
1653 fh->iseqno = f->iseqno;
1657 static int attempt_transmit(void *data)
1659 /* Attempt to transmit the frame to the remote peer...
1660 Called without iaxsl held. */
1661 struct iax_frame *f = data;
1663 int callno = f->callno;
1664 char iabuf[INET_ADDRSTRLEN];
1665 /* Make sure this call is still active */
1667 ast_mutex_lock(&iaxsl[callno]);
1668 if ((f->callno) && iaxs[f->callno]) {
1669 if ((f->retries < 0) /* Already ACK'd */ ||
1670 (f->retries >= max_retries) /* Too many attempts */) {
1671 /* Record an error if we've transmitted too many times */
1672 if (f->retries >= max_retries) {
1674 /* Transfer timeout */
1675 send_command(iaxs[f->callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1676 } else if (f->final) {
1678 iax2_destroy_nolock(f->callno);
1680 if (iaxs[f->callno]->owner)
1681 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);
1682 iaxs[f->callno]->error = ETIMEDOUT;
1683 if (iaxs[f->callno]->owner) {
1684 struct ast_frame fr = { 0, };
1686 fr.frametype = AST_FRAME_CONTROL;
1687 fr.subclass = AST_CONTROL_HANGUP;
1688 iax2_queue_frame(f->callno, &fr);
1689 /* Remember, owner could disappear */
1690 if (iaxs[f->callno]->owner)
1691 iaxs[f->callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1693 if (iaxs[f->callno]->reg) {
1694 memset(&iaxs[f->callno]->reg->us, 0, sizeof(iaxs[f->callno]->reg->us));
1695 iaxs[f->callno]->reg->regstate = REG_STATE_TIMEOUT;
1696 iaxs[f->callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1698 iax2_destroy_nolock(f->callno);
1705 /* Update it if it needs it */
1707 /* Attempt transmission */
1710 /* Try again later after 10 times as long */
1712 if (f->retrytime > MAX_RETRY_TIME)
1713 f->retrytime = MAX_RETRY_TIME;
1714 /* Transfer messages max out at one second */
1715 if (f->transfer && (f->retrytime > 1000))
1716 f->retrytime = 1000;
1717 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1720 /* Make sure it gets freed */
1725 ast_mutex_unlock(&iaxsl[callno]);
1726 /* Do not try again */
1728 /* Don't attempt delivery, just remove it from the queue */
1729 ast_mutex_lock(&iaxq.lock);
1731 f->prev->next = f->next;
1733 iaxq.head = f->next;
1735 f->next->prev = f->prev;
1737 iaxq.tail = f->prev;
1739 ast_mutex_unlock(&iaxq.lock);
1741 /* Free the IAX frame */
1747 static int iax2_set_jitter(int fd, int argc, char *argv[])
1750 ast_cli(fd, "sorry, this command is deprecated\n");
1751 return RESULT_SUCCESS;
1753 if ((argc != 4) && (argc != 5))
1754 return RESULT_SHOWUSAGE;
1756 max_jitter_buffer = atoi(argv[3]);
1757 if (max_jitter_buffer < 0)
1758 max_jitter_buffer = 0;
1761 if ((atoi(argv[3]) >= 0) && (atoi(argv[3]) < IAX_MAX_CALLS)) {
1762 if (iaxs[atoi(argv[3])]) {
1763 iaxs[atoi(argv[3])]->jitterbuffer = atoi(argv[4]);
1764 if (iaxs[atoi(argv[3])]->jitterbuffer < 0)
1765 iaxs[atoi(argv[3])]->jitterbuffer = 0;
1767 ast_cli(fd, "No such call '%d'\n", atoi(argv[3]));
1769 ast_cli(fd, "%d is not a valid call number\n", atoi(argv[3]));
1772 return RESULT_SUCCESS;
1776 static char jitter_usage[] =
1777 "Usage: iax set jitter [callid] <value>\n"
1778 " If used with a callid, it sets the jitter buffer to the given static\n"
1779 "value (until its next calculation). If used without a callid, the value is used\n"
1780 "to establish the maximum excess jitter buffer that is permitted before the jitter\n"
1781 "buffer size is reduced.";
1783 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1785 struct iax2_peer *peer;
1788 return RESULT_SHOWUSAGE;
1789 if (!strcmp(argv[3],"all")) {
1791 ast_cli(fd, "OK cache is flushed.\n");
1792 } else if ((peer = find_peer(argv[3], 0))) {
1793 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1794 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1795 expire_registry(peer);
1796 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1798 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1801 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1804 return RESULT_SUCCESS;
1807 static int iax2_test_losspct(int fd, int argc, char *argv[])
1810 return RESULT_SHOWUSAGE;
1812 test_losspct = atoi(argv[3]);
1814 return RESULT_SUCCESS;
1818 static int iax2_test_late(int fd, int argc, char *argv[])
1821 return RESULT_SHOWUSAGE;
1823 test_late = atoi(argv[3]);
1825 return RESULT_SUCCESS;
1828 static int iax2_test_resync(int fd, int argc, char *argv[])
1831 return RESULT_SHOWUSAGE;
1833 test_resync = atoi(argv[3]);
1835 return RESULT_SUCCESS;
1838 static int iax2_test_jitter(int fd, int argc, char *argv[])
1840 if (argc < 4 || argc > 5)
1841 return RESULT_SHOWUSAGE;
1843 test_jit = atoi(argv[3]);
1845 test_jitpct = atoi(argv[4]);
1847 return RESULT_SUCCESS;
1849 #endif /* IAXTESTS */
1851 /*--- iax2_show_peer: Show one peer in detail ---*/
1852 static int iax2_show_peer(int fd, int argc, char *argv[])
1854 char status[30] = "";
1856 char iabuf[INET_ADDRSTRLEN];
1857 struct iax2_peer *peer;
1858 char codec_buf[512];
1859 int x = 0, codec = 0, load_realtime = 0;
1862 return RESULT_SHOWUSAGE;
1864 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1866 peer = find_peer(argv[3], load_realtime);
1869 ast_cli(fd, " * Name : %s\n", peer->name);
1870 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1871 ast_cli(fd, " Context : %s\n", peer->context);
1872 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1873 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1874 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1875 ast_cli(fd, " Expire : %d\n", peer->expire);
1876 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1877 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));
1878 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1879 ast_cli(fd, " Username : %s\n", peer->username);
1880 ast_cli(fd, " Codecs : ");
1881 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1882 ast_cli(fd, "%s\n", codec_buf);
1884 ast_cli(fd, " Codec Order : (");
1885 for(x = 0; x < 32 ; x++) {
1886 codec = ast_codec_pref_index(&peer->prefs,x);
1889 ast_cli(fd, "%s", ast_getformatname(codec));
1890 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
1895 ast_cli(fd, "none");
1898 ast_cli(fd, " Status : ");
1899 if (peer->lastms < 0)
1900 ast_copy_string(status, "UNREACHABLE", sizeof(status));
1901 else if (peer->historicms > peer->maxms)
1902 snprintf(status, sizeof(status), "LAGGED (%d ms)", peer->historicms);
1903 else if (peer->historicms)
1904 snprintf(status, sizeof(status), "OK (%d ms)", peer->historicms);
1906 ast_copy_string(status, "UNKNOWN", sizeof(status));
1907 ast_cli(fd, " Qualify : every %d when OK, every %d when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, (peer->smoothing == 1) ? "On" : "Off");
1908 ast_cli(fd, "%s\n",status);
1910 if (ast_test_flag(peer, IAX_TEMPONLY))
1913 ast_cli(fd,"Peer %s not found.\n", argv[3]);
1917 return RESULT_SUCCESS;
1920 static char *complete_iax2_show_peer(char *line, char *word, int pos, int state)
1923 struct iax2_peer *p;
1925 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
1927 ast_mutex_lock(&peerl.lock);
1928 for(p = peerl.peers ; p ; p = p->next) {
1929 if(!strncasecmp(p->name, word, strlen(word))) {
1930 if(++which > state) {
1931 return strdup(p->name);
1935 ast_mutex_unlock(&peerl.lock);
1941 static int iax2_show_stats(int fd, int argc, char *argv[])
1943 struct iax_frame *cur;
1944 int cnt = 0, dead=0, final=0;
1946 return RESULT_SHOWUSAGE;
1947 for (cur = iaxq.head; cur ; cur = cur->next) {
1948 if (cur->retries < 0)
1954 ast_cli(fd, " IAX Statistics\n");
1955 ast_cli(fd, "---------------------\n");
1956 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
1957 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n", dead, final, cnt);
1958 return RESULT_SUCCESS;
1961 static int iax2_show_cache(int fd, int argc, char *argv[])
1963 struct iax2_dpcache *dp;
1964 char tmp[1024] = "", *pc;
1968 gettimeofday(&tv, NULL);
1969 ast_mutex_lock(&dpcache_lock);
1971 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
1973 s = dp->expirey.tv_sec - tv.tv_sec;
1975 if (dp->flags & CACHE_FLAG_EXISTS)
1976 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
1977 if (dp->flags & CACHE_FLAG_NONEXISTENT)
1978 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
1979 if (dp->flags & CACHE_FLAG_CANEXIST)
1980 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
1981 if (dp->flags & CACHE_FLAG_PENDING)
1982 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
1983 if (dp->flags & CACHE_FLAG_TIMEOUT)
1984 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
1985 if (dp->flags & CACHE_FLAG_TRANSMITTED)
1986 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
1987 if (dp->flags & CACHE_FLAG_MATCHMORE)
1988 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
1989 if (dp->flags & CACHE_FLAG_UNKNOWN)
1990 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
1991 /* Trim trailing pipe */
1992 if (!ast_strlen_zero(tmp))
1993 tmp[strlen(tmp) - 1] = '\0';
1995 ast_copy_string(tmp, "(none)", sizeof(tmp));
1997 pc = strchr(dp->peercontext, '@');
1999 pc = dp->peercontext;
2002 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2003 if (dp->waiters[x] > -1)
2006 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2008 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2011 ast_mutex_unlock(&dpcache_lock);
2012 return RESULT_SUCCESS;
2015 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2017 #ifdef BRIDGE_OPTIMIZATION
2018 static unsigned int calc_fakestamp(struct chan_iax2_pvt *from, struct chan_iax2_pvt *to, unsigned int ts);
2020 static int forward_delivery(struct iax_frame *fr)
2022 struct chan_iax2_pvt *p1, *p2;
2023 char iabuf[INET_ADDRSTRLEN];
2026 p1 = iaxs[fr->callno];
2027 p2 = iaxs[p1->bridgecallno];
2034 ast_log(LOG_DEBUG, "forward_delivery: Forwarding ts=%d on %d/%d to %d/%d on %s:%d\n",
2036 p1->callno, p1->peercallno,
2037 p2->callno, p2->peercallno,
2038 ast_inet_ntoa(iabuf, sizeof(iabuf), p2->addr.sin_addr),
2039 ntohs(p2->addr.sin_port));
2041 /* Undo wraparound - which can happen when full VOICE frame wasn't sent by our peer.
2042 This is necessary for when our peer is chan_iax2.c v1.1nn or earlier which didn't
2043 send full frame on timestamp wrap when doing optimized bridging
2044 (actually current code STILL doesn't)
2046 if (fr->ts + 50000 <= p1->last) {
2047 fr->ts = ( (p1->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2049 ast_log(LOG_DEBUG, "forward_delivery: pushed forward timestamp to %u\n", fr->ts);
2052 /* Send with timestamp adjusted to the origin of the outbound leg */
2053 /* But don't destroy inbound timestamp still needed later to set "last" */
2055 fr->ts = calc_fakestamp(p1, p2, fr->ts);
2056 res = iax2_send(p2, &fr->af, fr->ts, -1, 0, 0, 0);
2062 static void unwrap_timestamp(struct iax_frame *fr)
2066 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2067 x = fr->ts - iaxs[fr->callno]->last;
2069 /* Sudden big jump backwards in timestamp:
2070 What likely happened here is that miniframe timestamp has circled but we haven't
2071 gotten the update from the main packet. We'll just pretend that we did, and
2072 update the timestamp appropriately. */
2073 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2075 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2078 /* Sudden apparent big jump forwards in timestamp:
2079 What's likely happened is this is an old miniframe belonging to the previous
2080 top-16-bit timestamp that has turned up out of order.
2081 Adjust the timestamp appropriately. */
2082 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2084 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2090 static int get_from_jb(void *p);
2092 static void update_jbsched(struct chan_iax2_pvt *pvt) {
2095 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2097 /* fprintf(stderr, "now = %d, next=%d\n", when, jb_next(pvt->jb)); */
2099 when = jb_next(pvt->jb) - when;
2100 /* fprintf(stderr, "when = %d\n", when); */
2102 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2105 /* XXX should really just empty until when > 0.. */
2109 pvt->jbid = ast_sched_add(sched, when, get_from_jb, (void *)pvt);
2112 static int get_from_jb(void *p) {
2113 /* make sure pvt is valid! */
2114 struct chan_iax2_pvt *pvt = p;
2115 struct iax_frame *fr;
2122 ast_mutex_lock(&iaxsl[pvt->callno]);
2123 /* fprintf(stderr, "get_from_jb called\n"); */
2126 gettimeofday(&tv,NULL);
2127 /* round up a millisecond since ast_sched_runq does; */
2128 /* prevents us from spinning while waiting for our now */
2129 /* to catch up with runq's now */
2132 now = ast_tvdiff_ms(tv, pvt->rxcore);
2134 if(now >= (next = jb_next(pvt->jb))) {
2135 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2138 /*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); */
2144 struct ast_frame af;
2146 /*if(next + 20 != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not %ld+20!\n", jb_next(pvt->jb), next); */
2148 /* create an interpolation frame */
2149 /*fprintf(stderr, "Making Interpolation frame\n"); */
2150 af.frametype = AST_FRAME_VOICE;
2151 af.subclass = pvt->voiceformat;
2153 af.samples = frame.ms * 8;
2155 af.src = "IAX2 JB interpolation";
2157 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2158 af.offset=AST_FRIENDLY_OFFSET;
2160 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2161 * which we'd need to malloc, and then it would free it. That seems like a drag */
2162 if (iaxs[pvt->callno] && !ast_test_flag(iaxs[pvt->callno], IAX_ALREADYGONE))
2163 iax2_queue_frame(pvt->callno, &af);
2167 /*if(next != jb_next(pvt->jb)) fprintf(stderr, "NEXT %ld is not next %ld!\n", jb_next(pvt->jb), next); */
2168 iax2_frame_free(frame.data);
2175 /* shouldn't happen */
2179 update_jbsched(pvt);
2180 ast_mutex_unlock(&iaxsl[pvt->callno]);
2185 /* while we transition from the old JB to the new one, we can either make two schedule_delivery functions, or
2186 * make preprocessor swiss-cheese out of this one. I'm not sure which is less revolting.. */
2187 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk)
2196 unsigned int orig_ts;
2197 int drops[MEMORY_SIZE];
2198 int min, max=0, prevjitterbuffer, maxone=0,y,z, match;
2200 /* Remember current jitterbuffer so we can log any change */
2201 prevjitterbuffer = iaxs[fr->callno]->jitterbuffer;
2202 /* Similarly for the frame timestamp */
2208 ast_log(LOG_DEBUG, "schedule_delivery: ts=%d, last=%d, update=%d\n",
2209 fr->ts, iaxs[fr->callno]->last, updatehistory);
2212 /* Attempt to recover wrapped timestamps */
2213 unwrap_timestamp(fr);
2215 if (updatehistory) {
2218 /* Attempt to spot a change of timebase on timestamps coming from the other side
2219 We detect by noticing a jump in consecutive timestamps that can't reasonably be explained
2220 by network jitter or reordering. Sometimes, also, the peer stops sending us frames
2221 for a while - in this case this code might also resync us. But that's not a bad thing.
2222 Be careful of non-voice frames which are timestamped differently (especially ACKS!)
2223 [that's why we only do this when updatehistory is true]
2225 x = fr->ts - iaxs[fr->callno]->last;
2226 if (x > TS_GAP_FOR_JB_RESYNC || x < -TS_GAP_FOR_JB_RESYNC) {
2228 ast_log(LOG_DEBUG, "schedule_delivery: call=%d: TS jumped. resyncing rxcore (ts=%d, last=%d)\n",
2229 fr->callno, fr->ts, iaxs[fr->callno]->last);
2230 /* zap rxcore - calc_rxstamp will make a new one based on this frame */
2231 iaxs[fr->callno]->rxcore = ast_tv(0, 0);
2232 /* wipe "last" if stamps have jumped backwards */
2234 iaxs[fr->callno]->last = 0;
2235 /* should we also empty history? */
2237 /* ms is a measure of the "lateness" of the frame relative to the "reference"
2238 frame we received. (initially the very first, but also see code just above here).
2239 Understand that "ms" can easily be -ve if lag improves since the reference frame.
2240 Called by IAX thread, with iaxsl lock held. */
2241 ms = calc_rxstamp(iaxs[fr->callno], fr->ts) - fr->ts;
2243 /* Rotate our history queue of "lateness". Don't worry about those initial
2244 zeros because the first entry will always be zero */
2245 for (x=0;x<MEMORY_SIZE - 1;x++)
2246 iaxs[fr->callno]->history[x] = iaxs[fr->callno]->history[x+1];
2247 /* Add a history entry for this one */
2248 iaxs[fr->callno]->history[x] = ms;
2257 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2258 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2259 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2262 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2264 fr->af.delivery = ast_tv(0,0);
2268 /* Initialize the minimum to reasonable values. It's too much
2269 work to do the same for the maximum, repeatedly */
2270 min=iaxs[fr->callno]->history[0];
2271 for (z=0;z < iax2_dropcount + 1;z++) {
2272 /* Start very optimistic ;-) */
2274 for (x=0;x<MEMORY_SIZE;x++) {
2275 if (max < iaxs[fr->callno]->history[x]) {
2276 /* We have a candidate new maximum value. Make
2277 sure it's not in our drop list */
2279 for (y=0;!match && (y<z);y++)
2280 match |= (drops[y] == x);
2282 /* It's not in our list, use it as the new maximum */
2283 max = iaxs[fr->callno]->history[x];
2289 /* On our first pass, find the minimum too */
2290 if (min > iaxs[fr->callno]->history[x])
2291 min = iaxs[fr->callno]->history[x];
2301 type = JB_TYPE_CONTROL;
2304 if(fr->af.frametype == AST_FRAME_VOICE) {
2305 type = JB_TYPE_VOICE;
2306 len = ast_codec_get_samples(&fr->af) / 8;
2307 } else if(fr->af.frametype == AST_FRAME_CNG) {
2308 type = JB_TYPE_SILENCE;
2311 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2316 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2317 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2318 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2319 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2320 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2323 /* deliver any frames in the jb */
2324 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2325 __do_deliver(frame.data);
2327 jb_reset(iaxs[fr->callno]->jb);
2329 if (iaxs[fr->callno]->jbid > -1)
2330 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2332 iaxs[fr->callno]->jbid = -1;
2334 /* deliver this frame now */
2341 /* insert into jitterbuffer */
2342 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2343 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2344 calc_rxstamp(iaxs[fr->callno],fr->ts));
2345 if (ret == JB_DROP) {
2346 iax2_frame_free(fr);
2347 } else if (ret == JB_SCHED) {
2348 update_jbsched(iaxs[fr->callno]);
2351 /* Just for reference, keep the "jitter" value, the difference between the
2352 earliest and the latest. */
2354 iaxs[fr->callno]->jitter = max - min;
2356 /* IIR filter for keeping track of historic jitter, but always increase
2357 historic jitter immediately for increase */
2359 if (iaxs[fr->callno]->jitter > iaxs[fr->callno]->historicjitter )
2360 iaxs[fr->callno]->historicjitter = iaxs[fr->callno]->jitter;
2362 iaxs[fr->callno]->historicjitter = GAMMA * (double)iaxs[fr->callno]->jitter + (1-GAMMA) *
2363 iaxs[fr->callno]->historicjitter;
2365 /* If our jitter buffer is too big (by a significant margin), then we slowly
2366 shrink it to avoid letting the change be perceived */
2367 if (max < iaxs[fr->callno]->jitterbuffer - max_jitter_buffer)
2368 iaxs[fr->callno]->jitterbuffer -= jittershrinkrate;
2370 /* If our jitter buffer headroom is too small (by a significant margin), then we slowly enlarge it */
2371 /* min_jitter_buffer should be SMALLER than max_jitter_buffer - leaving a "no mans land"
2372 in between - otherwise the jitterbuffer size will hunt up and down causing unnecessary
2373 disruption. Set maxexcessbuffer to say 150msec, minexcessbuffer to say 50 */
2374 if (max > iaxs[fr->callno]->jitterbuffer - min_jitter_buffer)
2375 iaxs[fr->callno]->jitterbuffer += jittershrinkrate;
2377 /* If our jitter buffer is smaller than our maximum delay, grow the jitter
2378 buffer immediately to accomodate it (and a little more). */
2379 if (max > iaxs[fr->callno]->jitterbuffer)
2380 iaxs[fr->callno]->jitterbuffer = max
2381 /* + ((float)iaxs[fr->callno]->jitter) * 0.1 */;
2383 /* update "min", just for RRs and stats */
2384 iaxs[fr->callno]->min = min;
2386 /* Subtract the lateness from our jitter buffer to know how long to wait
2387 before sending our packet. */
2388 delay = iaxs[fr->callno]->jitterbuffer - ms;
2390 /* Whatever happens, no frame waits longer than maxjitterbuffer */
2391 if (delay > maxjitterbuffer)
2392 delay = maxjitterbuffer;
2394 /* If jitter buffer is disabled then just pretend the frame is "right on time" */
2395 /* If frame came from trunk, also don't do any delay */
2396 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) || fromtrunk )
2400 /* Log jitter stats for possible offline analysis */
2401 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",
2402 fr->callno, fr->ts, orig_ts, iaxs[fr->callno]->last,
2403 (fr->af.frametype == AST_FRAME_VOICE) ? "VOICE" : "CONTROL",
2404 min, max, iaxs[fr->callno]->jitterbuffer,
2405 iaxs[fr->callno]->jitterbuffer - prevjitterbuffer,
2407 iaxs[fr->callno]->jitter, iaxs[fr->callno]->historicjitter);
2411 /* Don't deliver it more than 4 ms late */
2412 if ((delay > -4) || (fr->af.frametype != AST_FRAME_VOICE)) {
2414 ast_log(LOG_DEBUG, "schedule_delivery: Delivering immediately (Calculated delay is %d)\n", delay);
2418 ast_log(LOG_DEBUG, "schedule_delivery: Dropping voice packet since %dms delay is too old\n", delay);
2419 iaxs[fr->callno]->frames_dropped++;
2420 /* Free our iax frame */
2421 iax2_frame_free(fr);
2425 ast_log(LOG_DEBUG, "schedule_delivery: Scheduling delivery in %d ms\n", delay);
2426 fr->retrans = ast_sched_add(sched, delay, do_deliver, fr);
2432 static int iax2_transmit(struct iax_frame *fr)
2434 /* Lock the queue and place this packet at the end */
2437 /* By setting this to 0, the network thread will send it for us, and
2438 queue retransmission if necessary */
2440 ast_mutex_lock(&iaxq.lock);
2447 iaxq.tail->next = fr;
2448 fr->prev = iaxq.tail;
2452 ast_mutex_unlock(&iaxq.lock);
2453 /* Wake up the network thread */
2454 pthread_kill(netthreadid, SIGURG);
2460 static int iax2_digit(struct ast_channel *c, char digit)
2462 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF, digit, 0, NULL, 0, -1);
2465 static int iax2_sendtext(struct ast_channel *c, const char *text)
2468 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2469 0, 0, text, strlen(text) + 1, -1);
2472 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2474 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2477 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2479 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, data, datalen, -1);
2482 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2484 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2485 ast_mutex_lock(&iaxsl[callno]);
2487 iaxs[callno]->owner = newchan;
2489 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2490 ast_mutex_unlock(&iaxsl[callno]);
2494 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, int temponly);
2495 static struct iax2_user *build_user(const char *name, struct ast_variable *v, int temponly);
2497 static void destroy_user(struct iax2_user *user);
2498 static int expire_registry(void *data);
2500 static struct iax2_peer *realtime_peer(const char *peername)
2502 struct ast_variable *var;
2503 struct ast_variable *tmp;
2504 struct iax2_peer *peer=NULL;
2505 time_t regseconds, nowtime;
2508 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2512 peer = build_peer(peername, var, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2519 /* Make sure it's not a user only... */
2520 if (!strcasecmp(tmp->name, "type")) {
2521 if (strcasecmp(tmp->value, "friend") &&
2522 strcasecmp(tmp->value, "peer")) {
2523 /* Whoops, we weren't supposed to exist! */
2528 } else if (!strcasecmp(tmp->name, "regseconds")) {
2529 if (sscanf(tmp->value, "%li", ®seconds) != 1)
2531 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2532 inet_aton(tmp->value, &(peer->addr.sin_addr));
2533 } else if (!strcasecmp(tmp->name, "port")) {
2534 peer->addr.sin_port = htons(atoi(tmp->value));
2535 } else if (!strcasecmp(tmp->name, "host")) {
2536 if (!strcasecmp(tmp->value, "dynamic"))
2544 ast_variables_destroy(var);
2546 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2547 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2548 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2549 if (peer->expire > -1)
2550 ast_sched_del(sched, peer->expire);
2551 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer);
2553 ast_mutex_lock(&peerl.lock);
2554 peer->next = peerl.peers;
2556 ast_mutex_unlock(&peerl.lock);
2557 if (ast_test_flag(peer, IAX_DYNAMIC))
2558 reg_source_db(peer);
2560 ast_set_flag(peer, IAX_TEMPONLY);
2563 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2565 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2566 memset(&peer->addr, 0, sizeof(peer->addr));
2568 ast_log(LOG_DEBUG, "Bah, we're expired (%ld/%ld/%ld)!\n", nowtime - regseconds, regseconds, nowtime);
2575 static struct iax2_user *realtime_user(const char *username)
2577 struct ast_variable *var;
2578 struct ast_variable *tmp;
2579 struct iax2_user *user=NULL;
2581 var = ast_load_realtime("iaxusers", "name", username, NULL);
2587 /* Make sure it's not a peer only... */
2588 if (!strcasecmp(tmp->name, "type")) {
2589 if (strcasecmp(tmp->value, "friend") &&
2590 strcasecmp(tmp->value, "user")) {
2597 user = build_user(username, var, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2601 ast_variables_destroy(var);
2603 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2604 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2605 ast_mutex_lock(&userl.lock);
2606 user->next = userl.users;
2608 ast_mutex_unlock(&userl.lock);
2610 ast_set_flag(user, IAX_TEMPONLY);
2616 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin)
2620 char regseconds[20];
2624 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);
2625 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
2626 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2627 ast_update_realtime("iaxpeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, NULL);
2630 struct create_addr_info {
2642 char context[AST_MAX_CONTEXT];
2643 char peercontext[AST_MAX_CONTEXT];
2646 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2648 struct ast_hostent ahp;
2650 struct iax2_peer *peer;
2652 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2653 cai->sockfd = defaultsockfd;
2655 sin->sin_family = AF_INET;
2657 if (!(peer = find_peer(peername, 1))) {
2660 hp = ast_gethostbyname(peername, &ahp);
2662 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2663 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2664 /* use global iax prefs for unknown peer/user */
2665 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2668 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2675 /* if the peer has no address (current or default), return failure */
2676 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2677 if (ast_test_flag(peer, IAX_TEMPONLY))
2682 /* if the peer is being monitored and is currently unreachable, return failure */
2683 if (peer->maxms && (peer->lastms > peer->maxms)) {
2684 if (ast_test_flag(peer, IAX_TEMPONLY))
2689 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2690 cai->maxtime = peer->maxms;
2691 cai->capability = peer->capability;
2692 cai->encmethods = peer->encmethods;
2693 cai->sockfd = peer->sockfd;
2694 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2695 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2696 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2697 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2698 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2699 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2700 if (ast_strlen_zero(peer->dbsecret)) {
2701 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2706 family = ast_strdupa(peer->dbsecret);
2708 key = strchr(family, '/');
2712 if (!family || !key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2713 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2714 if (ast_test_flag(peer, IAX_TEMPONLY))
2720 if (peer->addr.sin_addr.s_addr) {
2721 sin->sin_addr = peer->addr.sin_addr;
2722 sin->sin_port = peer->addr.sin_port;
2724 sin->sin_addr = peer->defaddr.sin_addr;
2725 sin->sin_port = peer->defaddr.sin_port;
2728 if (ast_test_flag(peer, IAX_TEMPONLY))
2734 static int auto_congest(void *nothing)
2736 int callno = PTR_TO_CALLNO(nothing);
2737 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2738 ast_mutex_lock(&iaxsl[callno]);
2740 iaxs[callno]->initid = -1;
2741 iax2_queue_frame(callno, &f);
2742 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2744 ast_mutex_unlock(&iaxsl[callno]);
2748 static unsigned int iax2_datetime(char *tz)
2754 localtime_r(&t, &tm);
2755 if (!ast_strlen_zero(tz))
2756 ast_localtime(&t, &tm, tz);
2757 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2758 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2759 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2760 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2761 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2762 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2766 struct parsed_dial_string {
2778 * \brief Parses an IAX dial string into its component parts.
2779 * \param data the string to be parsed
2780 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2783 * This function parses the string and fills the structure
2784 * with pointers to its component parts. The input string
2787 * \note This function supports both plaintext passwords and RSA
2788 * key names; if the password string is formatted as '[keyname]',
2789 * then the keyname will be placed into the key field, and the
2790 * password field will be set to NULL.
2792 * \note The dial string format is:
2793 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2795 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2797 if (!data || ast_strlen_zero(data))
2800 pds->peer = strsep(&data, "/");
2801 pds->exten = strsep(&data, "/");
2802 pds->options = data;
2806 pds->exten = strsep(&data, "@");
2807 pds->context = data;
2810 if (strchr(pds->peer, '@')) {
2812 pds->username = strsep(&data, "@");
2816 if (pds->username) {
2817 data = pds->username;
2818 pds->username = strsep(&data, ":");
2819 pds->password = data;
2823 pds->peer = strsep(&data, ":");
2826 /* check for a key name wrapped in [] in the secret position, if found,
2827 move it to the key field instead
2829 if (pds->password && (pds->password[0] == '[')) {
2830 pds->key = ast_strip_quoted(pds->password, "[", "]");
2831 pds->password = NULL;
2835 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2837 struct sockaddr_in sin;
2838 char *l=NULL, *n=NULL, *tmpstr;
2839 struct iax_ie_data ied;
2840 char *defaultrdest = "s";
2841 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2842 struct parsed_dial_string pds;
2843 struct create_addr_info cai;
2845 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2846 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2850 memset(&cai, 0, sizeof(cai));
2851 cai.encmethods = iax2_encryption;
2853 memset(&pds, 0, sizeof(pds));
2854 tmpstr = ast_strdupa(dest);
2855 parse_dial_string(tmpstr, &pds);
2858 pds.exten = defaultrdest;
2860 if (create_addr(pds.peer, &sin, &cai)) {
2861 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2865 if (!pds.username && !ast_strlen_zero(cai.username))
2866 pds.username = cai.username;
2867 if (!pds.password && !ast_strlen_zero(cai.secret))
2868 pds.password = cai.secret;
2869 if (!pds.key && !ast_strlen_zero(cai.outkey))
2870 pds.key = cai.outkey;
2871 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2872 pds.context = cai.peercontext;
2874 /* Keep track of the context for outgoing calls too */
2875 ast_copy_string(c->context, cai.context, sizeof(c->context));
2878 sin.sin_port = htons(atoi(pds.port));
2881 n = c->cid.cid_name;
2883 /* Now build request */
2884 memset(&ied, 0, sizeof(ied));
2886 /* On new call, first IE MUST be IAX version of caller */
2887 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2888 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2889 if (pds.options && strchr(pds.options, 'a')) {
2890 /* Request auto answer */
2891 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2894 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2897 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2898 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2900 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2903 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2904 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2907 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2908 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2909 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2911 if (c->language && !ast_strlen_zero(c->language))
2912 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2913 if (c->cid.cid_dnid && !ast_strlen_zero(c->cid.cid_dnid))
2914 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2917 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2920 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2923 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2925 ast_mutex_lock(&iaxsl[callno]);
2927 if (!ast_strlen_zero(c->context))
2928 ast_copy_string(iaxs[callno]->context, c->context, sizeof(iaxs[callno]->context));
2931 ast_copy_string(iaxs[callno]->username, pds.username, sizeof(iaxs[callno]->username));
2933 iaxs[callno]->encmethods = cai.encmethods;
2936 ast_copy_string(iaxs[callno]->outkey, pds.key, sizeof(iaxs[callno]->outkey));
2938 ast_copy_string(iaxs[callno]->secret, pds.password, sizeof(iaxs[callno]->secret));
2940 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2941 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2942 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2943 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2945 if (iaxs[callno]->maxtime) {
2946 /* Initialize pingtime and auto-congest time */
2947 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2948 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2949 } else if (autokill) {
2950 iaxs[callno]->pingtime = autokill / 2;
2951 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2954 /* Transmit the string in a "NEW" request */
2955 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2957 ast_mutex_unlock(&iaxsl[callno]);
2958 ast_setstate(c, AST_STATE_RINGING);
2963 static int iax2_hangup(struct ast_channel *c)
2965 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2967 struct iax_ie_data ied;
2968 memset(&ied, 0, sizeof(ied));
2969 ast_mutex_lock(&iaxsl[callno]);
2970 if (callno && iaxs[callno]) {
2971 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2972 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2973 /* Send the hangup unless we have had a transmission error or are already gone */
2974 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2975 if (!iaxs[callno]->error && !alreadygone)
2976 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2977 /* Explicitly predestroy it */
2978 iax2_predestroy_nolock(callno);
2979 /* If we were already gone to begin with, destroy us now */
2981 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2982 iax2_destroy_nolock(callno);
2985 ast_mutex_unlock(&iaxsl[callno]);
2986 if (option_verbose > 2)
2987 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2991 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2993 struct ast_option_header *h;
2995 h = malloc(datalen + sizeof(struct ast_option_header));
2997 h->flag = AST_OPTION_FLAG_REQUEST;
2998 h->option = htons(option);
2999 memcpy(h->data, data, datalen);
3000 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3001 AST_CONTROL_OPTION, 0, (char *)h, datalen + sizeof(struct ast_option_header), -1);
3005 ast_log(LOG_WARNING, "Out of memory\n");
3009 static struct ast_frame *iax2_read(struct ast_channel *c)
3011 static struct ast_frame f = { AST_FRAME_NULL, };
3012 ast_log(LOG_NOTICE, "I should never be called!\n");
3016 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1)
3019 struct iax_ie_data ied0;
3020 struct iax_ie_data ied1;
3021 unsigned int transferid = rand();
3022 memset(&ied0, 0, sizeof(ied0));
3023 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3024 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3025 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3027 memset(&ied1, 0, sizeof(ied1));
3028 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3029 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3030 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3032 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3035 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3038 iaxs[callno0]->transferring = TRANSFER_BEGIN;
3039 iaxs[callno1]->transferring = TRANSFER_BEGIN;
3043 static void lock_both(unsigned short callno0, unsigned short callno1)
3045 ast_mutex_lock(&iaxsl[callno0]);
3046 while (ast_mutex_trylock(&iaxsl[callno1])) {
3047 ast_mutex_unlock(&iaxsl[callno0]);
3049 ast_mutex_lock(&iaxsl[callno0]);
3053 static void unlock_both(unsigned short callno0, unsigned short callno1)
3055 ast_mutex_unlock(&iaxsl[callno1]);
3056 ast_mutex_unlock(&iaxsl[callno0]);
3059 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)
3061 struct ast_channel *cs[3];
3062 struct ast_channel *who;
3065 int transferstarted=0;
3066 struct ast_frame *f;
3067 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3068 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3069 struct timeval waittimer = {0, 0}, tv;
3071 lock_both(callno0, callno1);
3072 /* Put them in native bridge mode */
3073 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3074 iaxs[callno0]->bridgecallno = callno1;
3075 iaxs[callno1]->bridgecallno = callno0;
3077 unlock_both(callno0, callno1);
3079 /* If not, try to bridge until we can execute a transfer, if we can */
3082 for (/* ever */;;) {
3083 /* Check in case we got masqueraded into */
3084 if ((c0->type != channeltype) || (c1->type != channeltype)) {
3085 if (option_verbose > 2)
3086 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3087 /* Remove from native mode */
3088 if (c0->type == channeltype) {
3089 ast_mutex_lock(&iaxsl[callno0]);
3090 iaxs[callno0]->bridgecallno = 0;
3091 ast_mutex_unlock(&iaxsl[callno0]);
3093 if (c1->type == channeltype) {
3094 ast_mutex_lock(&iaxsl[callno1]);
3095 iaxs[callno1]->bridgecallno = 0;
3096 ast_mutex_unlock(&iaxsl[callno1]);
3098 return AST_BRIDGE_FAILED_NOWARN;
3100 if (c0->nativeformats != c1->nativeformats) {
3101 if (option_verbose > 2) {
3104 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3105 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3106 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3108 /* Remove from native mode */
3109 lock_both(callno0, callno1);
3110 iaxs[callno0]->bridgecallno = 0;
3111 iaxs[callno1]->bridgecallno = 0;
3112 unlock_both(callno0, callno1);
3113 return AST_BRIDGE_FAILED_NOWARN;
3115 /* check if transfered and if we really want native bridging */
3116 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER) &&
3117 !(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
3118 /* Try the transfer */
3119 if (iax2_start_transfer(callno0, callno1))
3120 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3121 transferstarted = 1;
3123 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3124 /* Call has been transferred. We're no longer involved */
3125 gettimeofday(&tv, NULL);
3126 if (ast_tvzero(waittimer)) {
3128 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3129 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3130 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3133 res = AST_BRIDGE_COMPLETE;