Asterisk - The Open Source Telephony Project GIT-master-4f2b068
Loading...
Searching...
No Matches
res_rtp_asterisk.c
Go to the documentation of this file.
1/*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2008, Digium, Inc.
5 *
6 * Mark Spencer <markster@digium.com>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19/*!
20 * \file
21 *
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
23 *
24 * \author Mark Spencer <markster@digium.com>
25 *
26 * \note RTP is defined in RFC 3550.
27 *
28 * \ingroup rtp_engines
29 */
30
31/*** MODULEINFO
32 <use type="external">openssl</use>
33 <use type="external">pjproject</use>
34 <support_level>core</support_level>
35 ***/
36
37#include "asterisk.h"
38
39#include <arpa/nameser.h>
40#include "asterisk/dns_core.h"
43
44#include <sys/time.h>
45#include <signal.h>
46#include <fcntl.h>
47#include <math.h>
48
49#ifdef HAVE_OPENSSL
50#include <openssl/opensslconf.h>
51#include <openssl/opensslv.h>
52#if !defined(OPENSSL_NO_SRTP) && (OPENSSL_VERSION_NUMBER >= 0x10001000L)
53#include <openssl/ssl.h>
54#include <openssl/err.h>
55#include <openssl/bio.h>
56#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
57#include <openssl/bn.h>
58#endif
59#ifndef OPENSSL_NO_DH
60#include <openssl/dh.h>
61#endif
62#endif
63#endif
64
65#ifdef HAVE_PJPROJECT
66#include <pjlib.h>
67#include <pjlib-util.h>
68#include <pjnath.h>
69#include <ifaddrs.h>
70#endif
71
73#include "asterisk/options.h"
75#include "asterisk/stun.h"
76#include "asterisk/pbx.h"
77#include "asterisk/frame.h"
79#include "asterisk/channel.h"
80#include "asterisk/acl.h"
81#include "asterisk/config.h"
82#include "asterisk/lock.h"
83#include "asterisk/utils.h"
84#include "asterisk/cli.h"
85#include "asterisk/manager.h"
86#include "asterisk/unaligned.h"
87#include "asterisk/module.h"
88#include "asterisk/rtp_engine.h"
89#include "asterisk/smoother.h"
90#include "asterisk/uuid.h"
91#include "asterisk/test.h"
93#ifdef HAVE_PJPROJECT
96#endif
97
98#define MAX_TIMESTAMP_SKEW 640
99
100#define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
101#define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
102#define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
103#define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
104
105#define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
106#define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
107
108#define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
109#define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
110
111#define DEFAULT_TURN_PORT 3478
112
113#define TURN_STATE_WAIT_TIME 2000
114
115#define DEFAULT_RTP_SEND_BUFFER_SIZE 250 /*!< The initial size of the RTP send buffer */
116#define MAXIMUM_RTP_SEND_BUFFER_SIZE (DEFAULT_RTP_SEND_BUFFER_SIZE + 200) /*!< Maximum RTP send buffer size */
117#define DEFAULT_RTP_RECV_BUFFER_SIZE 20 /*!< The initial size of the RTP receiver buffer */
118#define MAXIMUM_RTP_RECV_BUFFER_SIZE (DEFAULT_RTP_RECV_BUFFER_SIZE + 20) /*!< Maximum RTP receive buffer size */
119#define OLD_PACKET_COUNT 1000 /*!< The number of previous packets that are considered old */
120#define MISSING_SEQNOS_ADDED_TRIGGER 2 /*!< The number of immediate missing packets that will trigger an immediate NACK */
121
122#define SEQNO_CYCLE_OVER 65536 /*!< The number after the maximum allowed sequence number */
123
124/*! Full INTRA-frame Request / Fast Update Request (From RFC2032) */
125#define RTCP_PT_FUR 192
126/*! Sender Report (From RFC3550) */
127#define RTCP_PT_SR AST_RTP_RTCP_SR
128/*! Receiver Report (From RFC3550) */
129#define RTCP_PT_RR AST_RTP_RTCP_RR
130/*! Source Description (From RFC3550) */
131#define RTCP_PT_SDES 202
132/*! Goodbye (To remove SSRC's from tables) (From RFC3550) */
133#define RTCP_PT_BYE 203
134/*! Application defined (From RFC3550) */
135#define RTCP_PT_APP 204
136/* VP8: RTCP Feedback */
137/*! Payload Specific Feed Back (From RFC4585 also RFC5104) */
138#define RTCP_PT_PSFB AST_RTP_RTCP_PSFB
139
140#define RTP_MTU 1200
141
142#define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
143
144#define ZFONE_PROFILE_ID 0x505a
145
146#define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
147/*!
148 * \brief Calculate the min learning duration in ms.
149 *
150 * \details
151 * The min supported packet size represents 10 ms and we need to account
152 * for some jitter and fast clocks while learning. Some messed up devices
153 * have very bad jitter for a small packet sample size. Jitter can also
154 * be introduced by the network itself.
155 *
156 * So we'll allow packets to come in every 9ms on average for fast clocking
157 * with the last one coming in 5ms early for jitter.
158 */
159#define CALC_LEARNING_MIN_DURATION(count) (((count) - 1) * 9 - 5)
160#define DEFAULT_LEARNING_MIN_DURATION CALC_LEARNING_MIN_DURATION(DEFAULT_LEARNING_MIN_SEQUENTIAL)
161
162#define SRTP_MASTER_KEY_LEN 16
163#define SRTP_MASTER_SALT_LEN 14
164#define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
165
166#define RTP_DTLS_ESTABLISHED -37
167
169 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
170 STRICT_RTP_LEARN, /*! Accept next packet as source */
171 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
172};
173
175 STRICT_RTP_NO = 0, /*! Don't adhere to any strict RTP rules */
176 STRICT_RTP_YES, /*! Strict RTP that restricts packets based on time and sequence number */
177 STRICT_RTP_SEQNO, /*! Strict RTP that restricts packets based on sequence number */
178};
179
180/*!
181 * \brief Strict RTP learning timeout time in milliseconds
182 *
183 * \note Set to 5 seconds to allow reinvite chains for direct media
184 * to settle before media actually starts to arrive. There may be a
185 * reinvite collision involved on the other leg.
186 */
187#define STRICT_RTP_LEARN_TIMEOUT 5000
188
189#define DEFAULT_STRICT_RTP STRICT_RTP_YES /*!< Enabled by default */
190#define DEFAULT_SRTP_REPLAY_PROTECTION 1
191#define DEFAULT_ICESUPPORT 1
192#define DEFAULT_STUN_SOFTWARE_ATTRIBUTE 1
193#define DEFAULT_DTLS_MTU 1200
194
195/*!
196 * Because both ends usually don't start sending RTP
197 * at the same time, some of the calculations like
198 * rtt and jitter will probably be unstable for a while
199 * so we'll skip some received packets before starting
200 * analyzing. This just affects analyzing; we still
201 * process the RTP as normal.
202 */
203#define RTP_IGNORE_FIRST_PACKETS_COUNT 15
204
205extern struct ast_srtp_res *res_srtp;
207
209
210static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
211static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
212static int rtcpstats; /*!< Are we debugging RTCP? */
213static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
214static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
215static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
216static int rtpdebugport; /*!< Debug only RTP packets from IP or IP+Port if port is > 0 */
217static int rtcpdebugport; /*!< Debug only RTCP packets from IP or IP+Port if port is > 0 */
218#ifdef SO_NO_CHECK
219static int nochecksums;
220#endif
221static int strictrtp = DEFAULT_STRICT_RTP; /*!< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
222static int learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL; /*!< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
223static int learning_min_duration = DEFAULT_LEARNING_MIN_DURATION; /*!< Lowest acceptable timeout between the first and the last sequential RTP frame. */
225#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
226static int dtls_mtu = DEFAULT_DTLS_MTU;
227#endif
228#ifdef HAVE_PJPROJECT
229static int icesupport = DEFAULT_ICESUPPORT;
230static int stun_software_attribute = DEFAULT_STUN_SOFTWARE_ATTRIBUTE;
231static struct sockaddr_in stunaddr;
232static pj_str_t turnaddr;
233static int turnport = DEFAULT_TURN_PORT;
234static pj_str_t turnusername;
235static pj_str_t turnpassword;
237static struct ast_sockaddr lo6 = { .len = 0 };
238
239/*! ACL for ICE addresses */
240static struct ast_acl_list *ice_acl = NULL;
241static ast_rwlock_t ice_acl_lock = AST_RWLOCK_INIT_VALUE;
242
243/*! ACL for STUN requests */
244static struct ast_acl_list *stun_acl = NULL;
245static ast_rwlock_t stun_acl_lock = AST_RWLOCK_INIT_VALUE;
246
247/*! stunaddr recurring resolution */
248static ast_rwlock_t stunaddr_lock = AST_RWLOCK_INIT_VALUE;
249static struct ast_dns_query_recurring *stunaddr_resolver = NULL;
250
251/*! \brief Pool factory used by pjlib to allocate memory. */
252static pj_caching_pool cachingpool;
253
254/*! \brief Global memory pool for configuration and timers */
255static pj_pool_t *pool;
256
257/*! \brief Global timer heap */
258static pj_timer_heap_t *timer_heap;
259
260/*! \brief Thread executing the timer heap */
261static pj_thread_t *timer_thread;
262
263/*! \brief Used to tell the timer thread to terminate */
264static int timer_terminate;
265
266/*! \brief Structure which contains ioqueue thread information */
267struct ast_rtp_ioqueue_thread {
268 /*! \brief Pool used by the thread */
269 pj_pool_t *pool;
270 /*! \brief The thread handling the queue and timer heap */
271 pj_thread_t *thread;
272 /*! \brief Ioqueue which polls on sockets */
273 pj_ioqueue_t *ioqueue;
274 /*! \brief Timer heap for scheduled items */
275 pj_timer_heap_t *timerheap;
276 /*! \brief Termination request */
277 int terminate;
278 /*! \brief Current number of descriptors being waited on */
279 unsigned int count;
280 /*! \brief Linked list information */
281 AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
282};
283
284/*! \brief List of ioqueue threads */
285static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
286
287/*! \brief Structure which contains ICE host candidate mapping information */
288struct ast_ice_host_candidate {
289 struct ast_sockaddr local;
290 struct ast_sockaddr advertised;
291 unsigned int include_local;
292 AST_RWLIST_ENTRY(ast_ice_host_candidate) next;
293};
294
295/*! \brief List of ICE host candidate mappings */
296static AST_RWLIST_HEAD_STATIC(host_candidates, ast_ice_host_candidate);
297
298static char *generate_random_string(char *buf, size_t size);
299
300#endif
301
302#define FLAG_3389_WARNING (1 << 0)
303#define FLAG_NAT_ACTIVE (3 << 1)
304#define FLAG_NAT_INACTIVE (0 << 1)
305#define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
306#define FLAG_NEED_MARKER_BIT (1 << 3)
307#define FLAG_DTMF_COMPENSATE (1 << 4)
308#define FLAG_REQ_LOCAL_BRIDGE_BIT (1 << 5)
309
310#define TRANSPORT_SOCKET_RTP 0
311#define TRANSPORT_SOCKET_RTCP 1
312#define TRANSPORT_TURN_RTP 2
313#define TRANSPORT_TURN_RTCP 3
314
315/*! \brief RTP learning mode tracking information */
317 struct ast_sockaddr proposed_address; /*!< Proposed remote address for strict RTP */
318 struct timeval start; /*!< The time learning mode was started */
319 struct timeval received; /*!< The time of the first received packet */
320 int max_seq; /*!< The highest sequence number received */
321 int packets; /*!< The number of remaining packets before the source is accepted */
322 /*! Type of media stream carried by the RTP instance */
324};
325
326#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
327struct dtls_details {
328 SSL *ssl; /*!< SSL session */
329 BIO *read_bio; /*!< Memory buffer for reading */
330 BIO *write_bio; /*!< Memory buffer for writing */
331 enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
332 enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
333 int timeout_timer; /*!< Scheduler id for timeout timer */
334};
335#endif
336
337#ifdef HAVE_PJPROJECT
338/*! An ao2 wrapper protecting the PJPROJECT ice structure with ref counting. */
339struct ice_wrap {
340 pj_ice_sess *real_ice; /*!< ICE session */
341};
342#endif
343
344/*! \brief Structure used for mapping an incoming SSRC to an RTP instance */
346 /*! \brief The received SSRC */
347 unsigned int ssrc;
348 /*! True if the SSRC is available. Otherwise, this is a placeholder mapping until the SSRC is set. */
349 unsigned int ssrc_valid;
350 /*! \brief The RTP instance this SSRC belongs to*/
352};
353
354/*! \brief Packet statistics (used for transport-cc) */
356 /*! The transport specific sequence number */
357 unsigned int seqno;
358 /*! The time at which the packet was received */
359 struct timeval received;
360 /*! The delta between this packet and the previous */
361 int delta;
362};
363
364/*! \brief Statistics information (used for transport-cc) */
366 /*! A vector of packet statistics */
367 AST_VECTOR(, struct rtp_transport_wide_cc_packet_statistics) packet_statistics; /*!< Packet statistics, used for transport-cc */
368 /*! The last sequence number received */
369 unsigned int last_seqno;
370 /*! The last extended sequence number */
372 /*! How many feedback packets have gone out */
373 unsigned int feedback_count;
374 /*! How many cycles have occurred for the sequence numbers */
375 unsigned int cycles;
376 /*! Scheduler id for periodic feedback transmission */
378};
379
380typedef struct {
381 unsigned int ts;
382 unsigned char is_set;
384
385/*! \brief RTP session description */
386struct ast_rtp {
387 int s;
388 /*! \note The f.subclass.format holds a ref. */
389 struct ast_frame f;
390 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
391 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
392 unsigned int ssrc_orig; /*!< SSRC used before native bridge activated */
393 unsigned char ssrc_saved; /*!< indicates if ssrc_orig has a value */
394 char cname[AST_UUID_STR_LEN]; /*!< Our local CNAME */
395 unsigned int themssrc; /*!< Their SSRC */
396 unsigned int themssrc_valid; /*!< True if their SSRC is available. */
397 unsigned int lastts;
398 unsigned int lastividtimestamp;
399 unsigned int lastovidtimestamp;
400 unsigned int lastitexttimestamp;
401 unsigned int lastotexttimestamp;
402 int prevrxseqno; /*!< Previous received packeted sequence number, from the network */
403 int lastrxseqno; /*!< Last received sequence number, from the network */
404 int expectedrxseqno; /*!< Next expected sequence number, from the network */
405 AST_VECTOR(, int) missing_seqno; /*!< A vector of sequence numbers we never received */
406 int expectedseqno; /*!< Next expected sequence number, from the core */
407 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
408 unsigned int rxcount; /*!< How many packets have we received? */
409 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
410 unsigned int txcount; /*!< How many packets have we sent? */
411 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
412 unsigned int cycles; /*!< Shifted count of sequence number cycles */
415
416 /*
417 * RX RTP Timestamp and Jitter calculation.
418 */
419 double rxstart; /*!< RX time of the first packet in the session in seconds since EPOCH. */
420 double rxstart_stable; /*!< RX time of the first packet after RTP_IGNORE_FIRST_PACKETS_COUNT */
421 unsigned int remote_seed_rx_rtp_ts; /*!< RTP timestamp of first RX packet. */
422 unsigned int remote_seed_rx_rtp_ts_stable; /*!< RTP timestamp of first packet after RTP_IGNORE_FIRST_PACKETS_COUNT */
423 unsigned int last_transit_time_samples; /*!< The last transit time in samples */
424 double rxjitter; /*!< Last calculated Interarrival jitter in seconds. */
425 double rxjitter_samples; /*!< Last calculated Interarrival jitter in samples. */
426 double rxmes; /*!< Media Experince Score at the moment to be reported */
427
428 /* DTMF Reception Variables */
429 char resp; /*!< The current digit being processed */
430 unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
431 optional_ts last_end_timestamp; /*!< The last known timestamp received from an END packet */
432 unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
433 unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
434 unsigned int dtmfsamples;
435 enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
436 unsigned int dtmf_samplerate_ms; /*!< The sample rate of the current RTP stream in ms (sample rate / 1000) */
437 /* DTMF Transmission Variables */
438 unsigned int lastdigitts;
439 char sending_digit; /*!< boolean - are we sending digits */
440 char send_digit; /*!< digit we are sending */
443 unsigned int flags;
444 struct timeval rxcore;
445 struct timeval txcore;
446
447 struct timeval dtmfmute;
449 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
451 struct ast_rtcp *rtcp;
452 unsigned int asymmetric_codec; /*!< Indicate if asymmetric send/receive codecs are allowed */
453
454 struct ast_rtp_instance *bundled; /*!< The RTP instance we are bundled to */
455 /*!
456 * \brief The RTP instance owning us (used for debugging purposes)
457 * We don't hold a reference to the instance because it created
458 * us in the first place. It can't go away.
459 */
461 int stream_num; /*!< Stream num for this RTP instance */
462 AST_VECTOR(, struct rtp_ssrc_mapping) ssrc_mapping; /*!< Mappings of SSRC to RTP instances */
463 struct ast_sockaddr bind_address; /*!< Requested bind address for the sockets */
464
465 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
466 struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
467
468 /*
469 * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
470 * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
471 */
472 struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
473
474 struct rtp_red *red;
475
476 struct ast_data_buffer *send_buffer; /*!< Buffer for storing sent packets for retransmission */
477 struct ast_data_buffer *recv_buffer; /*!< Buffer for storing received packets for retransmission */
478
479 struct rtp_transport_wide_cc_statistics transport_wide_cc; /*!< Transport-cc statistics information */
480
481#ifdef HAVE_PJPROJECT
482 ast_cond_t cond; /*!< ICE/TURN condition for signaling */
483
484 struct ice_wrap *ice; /*!< ao2 wrapped ICE session */
485 enum ast_rtp_ice_role role; /*!< Our role in ICE negotiation */
486 pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
487 pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
488 pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
489 unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
490 unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
491 unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
492 unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
493 struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
494 struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
495
496 struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
497
498 char remote_ufrag[257]; /*!< The remote ICE username */
499 char remote_passwd[257]; /*!< The remote ICE password */
500
501 char local_ufrag[257]; /*!< The local ICE username */
502 char local_passwd[257]; /*!< The local ICE password */
503
504 struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
505 struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
506 struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
507 struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
508 unsigned int ice_num_components; /*!< The number of ICE components */
509 unsigned int ice_media_started:1; /*!< ICE media has started, either on a valid pair or on ICE completion */
510#endif
511
512#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
513 SSL_CTX *ssl_ctx; /*!< SSL context */
514 enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
515 enum ast_srtp_suite suite; /*!< SRTP crypto suite */
516 enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
517 char local_fingerprint[160]; /*!< Fingerprint of our certificate */
518 enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
519 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
520 unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
521 int rekeyid; /*!< Scheduled item id for rekeying */
522 struct dtls_details dtls; /*!< DTLS state information */
523#endif
524};
525
526/*!
527 * \brief Structure defining an RTCP session.
528 *
529 * The concept "RTCP session" is not defined in RFC 3550, but since
530 * this structure is analogous to ast_rtp, which tracks a RTP session,
531 * it is logical to think of this as a RTCP session.
532 *
533 * RTCP packet is defined on page 9 of RFC 3550.
534 *
535 */
536struct ast_rtcp {
538 int s; /*!< Socket */
539 struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
540 struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
541 unsigned int soc; /*!< What they told us */
542 unsigned int spc; /*!< What they told us */
543 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
544 struct timeval rxlsr; /*!< Time when we got their last SR */
545 struct timeval txlsr; /*!< Time when we sent or last SR*/
546 unsigned int expected_prior; /*!< no. packets in previous interval */
547 unsigned int received_prior; /*!< no. packets received in previous interval */
548 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
549 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
550 unsigned int sr_count; /*!< number of SRs we've sent */
551 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
552 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
553 double rtt; /*!< Last reported rtt */
554 double reported_jitter; /*!< The contents of their last jitter entry in the RR in seconds */
555 unsigned int reported_lost; /*!< Reported lost packets in their RR */
556
557 double reported_maxjitter; /*!< Maximum reported interarrival jitter */
558 double reported_minjitter; /*!< Minimum reported interarrival jitter */
559 double reported_normdev_jitter; /*!< Mean of reported interarrival jitter */
560 double reported_stdev_jitter; /*!< Standard deviation of reported interarrival jitter */
561 unsigned int reported_jitter_count; /*!< Reported interarrival jitter count */
562
563 double reported_maxlost; /*!< Maximum reported packets lost */
564 double reported_minlost; /*!< Minimum reported packets lost */
565 double reported_normdev_lost; /*!< Mean of reported packets lost */
566 double reported_stdev_lost; /*!< Standard deviation of reported packets lost */
567 unsigned int reported_lost_count; /*!< Reported packets lost count */
568
569 double rxlost; /*!< Calculated number of lost packets since last report */
570 double maxrxlost; /*!< Maximum calculated lost number of packets between reports */
571 double minrxlost; /*!< Minimum calculated lost number of packets between reports */
572 double normdev_rxlost; /*!< Mean of calculated lost packets between reports */
573 double stdev_rxlost; /*!< Standard deviation of calculated lost packets between reports */
574 unsigned int rxlost_count; /*!< Calculated lost packets sample count */
575
576 double maxrxjitter; /*!< Maximum of calculated interarrival jitter */
577 double minrxjitter; /*!< Minimum of calculated interarrival jitter */
578 double normdev_rxjitter; /*!< Mean of calculated interarrival jitter */
579 double stdev_rxjitter; /*!< Standard deviation of calculated interarrival jitter */
580 unsigned int rxjitter_count; /*!< Calculated interarrival jitter count */
581
582 double maxrtt; /*!< Maximum of calculated round trip time */
583 double minrtt; /*!< Minimum of calculated round trip time */
584 double normdevrtt; /*!< Mean of calculated round trip time */
585 double stdevrtt; /*!< Standard deviation of calculated round trip time */
586 unsigned int rtt_count; /*!< Calculated round trip time count */
587
588 double reported_mes; /*!< The calculated MES from their last RR */
589 double reported_maxmes; /*!< Maximum reported mes */
590 double reported_minmes; /*!< Minimum reported mes */
591 double reported_normdev_mes; /*!< Mean of reported mes */
592 double reported_stdev_mes; /*!< Standard deviation of reported mes */
593 unsigned int reported_mes_count; /*!< Reported mes count */
594
595 double maxrxmes; /*!< Maximum of calculated mes */
596 double minrxmes; /*!< Minimum of calculated mes */
597 double normdev_rxmes; /*!< Mean of calculated mes */
598 double stdev_rxmes; /*!< Standard deviation of calculated mes */
599 unsigned int rxmes_count; /*!< mes count */
600
601 /* VP8: sequence number for the RTCP FIR FCI */
603
604#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
605 struct dtls_details dtls; /*!< DTLS state information */
606#endif
607
608 /* Cached local address string allows us to generate
609 * RTCP stasis messages without having to look up our
610 * own address every time
611 */
614 /* Buffer for frames created during RTCP interpretation */
615 unsigned char frame_buf[512 + AST_FRIENDLY_OFFSET];
616};
617
618struct rtp_red {
619 struct ast_frame t140; /*!< Primary data */
620 struct ast_frame t140red; /*!< Redundant t140*/
621 unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
622 unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
623 unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
624 int num_gen; /*!< Number of generations */
625 int schedid; /*!< Timer id */
626 unsigned char t140red_data[64000];
627 unsigned char buf_data[64000]; /*!< buffered primary data */
629 long int prev_ts;
630};
631
632/*! \brief Structure for storing RTP packets for retransmission */
634 size_t size; /*!< The size of the payload */
635 unsigned char buf[0]; /*!< The payload data */
636};
637
639
640/* Forward Declarations */
641static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
642static int ast_rtp_destroy(struct ast_rtp_instance *instance);
643static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
644static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
645static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
646static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
647static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
648static void ast_rtp_update_source(struct ast_rtp_instance *instance);
649static void ast_rtp_change_source(struct ast_rtp_instance *instance);
650static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
651static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
652static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
653static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
654static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
655static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
656static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
657static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
658static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
659static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
660static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
661static void ast_rtp_stop(struct ast_rtp_instance *instance);
662static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
663static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
664static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance);
665static const char *ast_rtp_get_cname(struct ast_rtp_instance *instance);
666static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc);
667static void ast_rtp_set_stream_num(struct ast_rtp_instance *instance, int stream_num);
669static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent);
670static void update_reported_mes_stats(struct ast_rtp *rtp);
671static void update_local_mes_stats(struct ast_rtp *rtp);
672
673#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
674static int ast_rtp_activate(struct ast_rtp_instance *instance);
675static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
676static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
677static int dtls_bio_write(BIO *bio, const char *buf, int len);
678static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2);
679static int dtls_bio_new(BIO *bio);
680static int dtls_bio_free(BIO *bio);
681
682#ifndef HAVE_OPENSSL_BIO_METHOD
683static BIO_METHOD dtls_bio_methods = {
684 .type = BIO_TYPE_BIO,
685 .name = "rtp write",
686 .bwrite = dtls_bio_write,
687 .ctrl = dtls_bio_ctrl,
688 .create = dtls_bio_new,
689 .destroy = dtls_bio_free,
690};
691#else
692static BIO_METHOD *dtls_bio_methods;
693#endif
694#endif
695
696static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp);
697
698#ifdef HAVE_PJPROJECT
699static void stunaddr_resolve_callback(const struct ast_dns_query *query);
700static int store_stunaddr_resolved(const struct ast_dns_query *query);
701#endif
702
703#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
704static int dtls_bio_new(BIO *bio)
705{
706#ifdef HAVE_OPENSSL_BIO_METHOD
707 BIO_set_init(bio, 1);
708 BIO_set_data(bio, NULL);
709 BIO_set_shutdown(bio, 0);
710#else
711 bio->init = 1;
712 bio->ptr = NULL;
713 bio->flags = 0;
714#endif
715 return 1;
716}
717
718static int dtls_bio_free(BIO *bio)
719{
720 /* The pointer on the BIO is that of the RTP instance. It is not reference counted as the BIO
721 * lifetime is tied to the instance, and actions on the BIO are taken by the thread handling
722 * the RTP instance - not another thread.
723 */
724#ifdef HAVE_OPENSSL_BIO_METHOD
725 BIO_set_data(bio, NULL);
726#else
727 bio->ptr = NULL;
728#endif
729 return 1;
730}
731
732static int dtls_bio_write(BIO *bio, const char *buf, int len)
733{
734#ifdef HAVE_OPENSSL_BIO_METHOD
735 struct ast_rtp_instance *instance = BIO_get_data(bio);
736#else
737 struct ast_rtp_instance *instance = bio->ptr;
738#endif
739 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
740 int rtcp = 0;
741 struct ast_sockaddr remote_address = { {0, } };
742 int ice;
743 int bytes_sent;
744
745 /* OpenSSL can't tolerate a packet not being sent, so we always state that
746 * we sent the packet. If it isn't then retransmission will occur.
747 */
748
749 if (rtp->rtcp && rtp->rtcp->dtls.write_bio == bio) {
750 rtcp = 1;
751 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
752 } else {
753 ast_rtp_instance_get_remote_address(instance, &remote_address);
754 }
755
756 if (ast_sockaddr_isnull(&remote_address)) {
757 return len;
758 }
759
760 bytes_sent = __rtp_sendto(instance, (char *)buf, len, 0, &remote_address, rtcp, &ice, 0);
761
762 if (bytes_sent > 0 && ast_debug_dtls_packet_is_allowed) {
763 ast_debug(0, "(%p) DTLS - sent %s packet to %s%s (len %-6.6d)\n",
764 instance, rtcp ? "RTCP" : "RTP", ast_sockaddr_stringify(&remote_address),
765 ice ? " (via ICE)" : "", bytes_sent);
766 }
767
768 return len;
769}
770
771static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2)
772{
773 switch (cmd) {
774 case BIO_CTRL_FLUSH:
775 return 1;
776 case BIO_CTRL_DGRAM_QUERY_MTU:
777 return dtls_mtu;
778 case BIO_CTRL_WPENDING:
779 case BIO_CTRL_PENDING:
780 return 0L;
781 default:
782 return 0;
783 }
784}
785
786#endif
787
788#ifdef HAVE_PJPROJECT
789/*! \brief Helper function which clears the ICE host candidate mapping */
790static void host_candidate_overrides_clear(void)
791{
792 struct ast_ice_host_candidate *candidate;
793
794 AST_RWLIST_WRLOCK(&host_candidates);
795 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&host_candidates, candidate, next) {
797 ast_free(candidate);
798 }
800 AST_RWLIST_UNLOCK(&host_candidates);
801}
802
803/*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
804static void update_address_with_ice_candidate(pj_ice_sess *ice, enum ast_rtp_ice_component_type component,
805 struct ast_sockaddr *cand_address)
806{
807 char address[PJ_INET6_ADDRSTRLEN];
808
809 if (component < 1 || !ice->comp[component - 1].valid_check) {
810 return;
811 }
812
813 ast_sockaddr_parse(cand_address,
814 pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr, address,
815 sizeof(address), 0), 0);
816 ast_sockaddr_set_port(cand_address,
817 pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
818}
819
820/*! \brief Destructor for locally created ICE candidates */
821static void ast_rtp_ice_candidate_destroy(void *obj)
822{
823 struct ast_rtp_engine_ice_candidate *candidate = obj;
824
825 if (candidate->foundation) {
826 ast_free(candidate->foundation);
827 }
828
829 if (candidate->transport) {
830 ast_free(candidate->transport);
831 }
832}
833
834/*! \pre instance is locked */
835static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
836{
837 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
838 int ice_attrb_reset = 0;
839
840 if (!ast_strlen_zero(ufrag)) {
841 if (!ast_strlen_zero(rtp->remote_ufrag) && strcmp(ufrag, rtp->remote_ufrag)) {
842 ice_attrb_reset = 1;
843 }
844 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
845 }
846
847 if (!ast_strlen_zero(password)) {
848 if (!ast_strlen_zero(rtp->remote_passwd) && strcmp(password, rtp->remote_passwd)) {
849 ice_attrb_reset = 1;
850 }
851 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
852 }
853
854 /* If the remote ufrag or passwd changed, local ufrag and passwd need to regenerate */
855 if (ice_attrb_reset) {
856 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
857 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
858 }
859}
860
861static int ice_candidate_cmp(void *obj, void *arg, int flags)
862{
863 struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
864
865 if (strcmp(candidate1->foundation, candidate2->foundation) ||
866 candidate1->id != candidate2->id ||
867 candidate1->type != candidate2->type ||
868 ast_sockaddr_cmp(&candidate1->address, &candidate2->address)) {
869 return 0;
870 }
871
872 return CMP_MATCH | CMP_STOP;
873}
874
875/*! \pre instance is locked */
876static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
877{
878 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
879 struct ast_rtp_engine_ice_candidate *remote_candidate;
880
881 /* ICE sessions only support UDP candidates */
882 if (strcasecmp(candidate->transport, "udp")) {
883 return;
884 }
885
886 if (!rtp->ice_proposed_remote_candidates) {
887 rtp->ice_proposed_remote_candidates = ao2_container_alloc_list(
888 AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, ice_candidate_cmp);
889 if (!rtp->ice_proposed_remote_candidates) {
890 return;
891 }
892 }
893
894 /* If this is going to exceed the maximum number of ICE candidates don't even add it */
895 if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
896 return;
897 }
898
899 if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
900 return;
901 }
902
903 remote_candidate->foundation = ast_strdup(candidate->foundation);
904 remote_candidate->id = candidate->id;
905 remote_candidate->transport = ast_strdup(candidate->transport);
906 remote_candidate->priority = candidate->priority;
907 ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
908 ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
909 remote_candidate->type = candidate->type;
910
911 ast_debug_ice(2, "(%p) ICE add remote candidate\n", instance);
912
913 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
914 ao2_ref(remote_candidate, -1);
915}
916
917AST_THREADSTORAGE(pj_thread_storage);
918
919/*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
920static void pj_thread_register_check(void)
921{
922 pj_thread_desc *desc;
923 pj_thread_t *thread;
924
925 if (pj_thread_is_registered() == PJ_TRUE) {
926 return;
927 }
928
929 desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
930 if (!desc) {
931 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
932 return;
933 }
934 pj_bzero(*desc, sizeof(*desc));
935
936 if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
937 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
938 }
939 return;
940}
941
942static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
943 int port, int replace);
944
945/*! \pre instance is locked */
946static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
947{
948 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
949 struct ice_wrap *ice;
950
951 ice = rtp->ice;
952 rtp->ice = NULL;
953 if (ice) {
954 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
955 ao2_unlock(instance);
956 ao2_ref(ice, -1);
957 ao2_lock(instance);
958 ast_debug_ice(2, "(%p) ICE stopped\n", instance);
959 }
960}
961
962/*!
963 * \brief ao2 ICE wrapper object destructor.
964 *
965 * \param vdoomed Object being destroyed.
966 *
967 * \note The associated struct ast_rtp_instance object must not
968 * be locked when unreffing the object. Otherwise we could
969 * deadlock trying to destroy the PJPROJECT ICE structure.
970 */
971static void ice_wrap_dtor(void *vdoomed)
972{
973 struct ice_wrap *ice = vdoomed;
974
975 if (ice->real_ice) {
976 pj_thread_register_check();
977
978 pj_ice_sess_destroy(ice->real_ice);
979 }
980}
981
982static void ast2pj_rtp_ice_role(enum ast_rtp_ice_role ast_role, enum pj_ice_sess_role *pj_role)
983{
984 switch (ast_role) {
986 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
987 break;
989 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
990 break;
991 }
992}
993
994static void pj2ast_rtp_ice_role(enum pj_ice_sess_role pj_role, enum ast_rtp_ice_role *ast_role)
995{
996 switch (pj_role) {
997 case PJ_ICE_SESS_ROLE_CONTROLLED:
998 *ast_role = AST_RTP_ICE_ROLE_CONTROLLED;
999 return;
1000 case PJ_ICE_SESS_ROLE_CONTROLLING:
1001 *ast_role = AST_RTP_ICE_ROLE_CONTROLLING;
1002 return;
1003 case PJ_ICE_SESS_ROLE_UNKNOWN:
1004 /* Don't change anything */
1005 return;
1006 default:
1007 /* If we aren't explicitly handling something, it's a bug */
1008 ast_assert(0);
1009 return;
1010 }
1011}
1012
1013/*! \pre instance is locked */
1014static int ice_reset_session(struct ast_rtp_instance *instance)
1015{
1016 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1017 int res;
1018
1019 ast_debug_ice(3, "(%p) ICE resetting\n", instance);
1020 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1021 ast_debug_ice(3, " (%p) ICE nevermind, not ready for a reset\n", instance);
1022 return 0;
1023 }
1024
1025 ast_debug_ice(3, "(%p) ICE recreating ICE session %s (%d)\n",
1026 instance, ast_sockaddr_stringify(&rtp->ice_original_rtp_addr), rtp->ice_port);
1027 res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
1028 if (!res) {
1029 /* Use the current expected role for the ICE session */
1030 enum pj_ice_sess_role role = PJ_ICE_SESS_ROLE_UNKNOWN;
1031 ast2pj_rtp_ice_role(rtp->role, &role);
1032 pj_ice_sess_change_role(rtp->ice->real_ice, role);
1033 }
1034
1035 /* If we only have one component now, and we previously set up TURN for RTCP,
1036 * we need to destroy that TURN socket.
1037 */
1038 if (rtp->ice_num_components == 1 && rtp->turn_rtcp) {
1039 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1040 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1041
1042 rtp->turn_state = PJ_TURN_STATE_NULL;
1043
1044 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1045 ao2_unlock(instance);
1046 pj_turn_sock_destroy(rtp->turn_rtcp);
1047 ao2_lock(instance);
1048 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1049 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1050 }
1051 }
1052
1053 rtp->ice_media_started = 0;
1054
1055 return res;
1056}
1057
1058static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
1059{
1060 struct ao2_iterator i;
1061 struct ast_rtp_engine_ice_candidate *right_candidate;
1062
1063 if (ao2_container_count(left) != ao2_container_count(right)) {
1064 return -1;
1065 }
1066
1067 i = ao2_iterator_init(right, 0);
1068 while ((right_candidate = ao2_iterator_next(&i))) {
1069 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
1070
1071 if (!left_candidate) {
1072 ao2_ref(right_candidate, -1);
1074 return -1;
1075 }
1076
1077 ao2_ref(left_candidate, -1);
1078 ao2_ref(right_candidate, -1);
1079 }
1081
1082 return 0;
1083}
1084
1085/*! \pre instance is locked */
1086static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
1087{
1088 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1089 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
1090 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
1091 struct ao2_iterator i;
1092 struct ast_rtp_engine_ice_candidate *candidate;
1093 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
1094
1095 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
1096 return;
1097 }
1098
1099 /* Check for equivalence in the lists */
1100 if (rtp->ice_active_remote_candidates &&
1101 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
1102 ast_debug_ice(2, "(%p) ICE proposed equals active candidates\n", instance);
1103 ao2_cleanup(rtp->ice_proposed_remote_candidates);
1104 rtp->ice_proposed_remote_candidates = NULL;
1105 /* If this ICE session is being preserved then go back to the role it currently is */
1106 pj2ast_rtp_ice_role(rtp->ice->real_ice->role, &rtp->role);
1107 return;
1108 }
1109
1110 /* Out with the old, in with the new */
1111 ao2_cleanup(rtp->ice_active_remote_candidates);
1112 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
1113 rtp->ice_proposed_remote_candidates = NULL;
1114
1115 ast_debug_ice(2, "(%p) ICE start\n", instance);
1116
1117 /* Reset the ICE session. Is this going to work? */
1118 if (ice_reset_session(instance)) {
1119 ast_log(LOG_NOTICE, "(%p) ICE failed to create replacement session\n", instance);
1120 return;
1121 }
1122
1123 pj_thread_register_check();
1124
1125 i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
1126
1127 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
1128 pj_str_t address;
1129
1130 /* there needs to be at least one rtp and rtcp candidate in the list */
1131 has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
1132 has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
1133
1134 pj_strdup2(rtp->ice->real_ice->pool, &candidates[cand_cnt].foundation,
1135 candidate->foundation);
1136 candidates[cand_cnt].comp_id = candidate->id;
1137 candidates[cand_cnt].prio = candidate->priority;
1138
1139 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
1140
1141 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
1142 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
1143 }
1144
1145 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
1146 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
1147 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
1148 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
1149 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
1150 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
1151 }
1152
1153 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
1154 ast_debug_ice(2, "(%p) ICE RTP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1155 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1156 ao2_unlock(instance);
1157 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
1158 ao2_lock(instance);
1159 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
1160 ast_debug_ice(2, "(%p) ICE RTCP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1161 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1162 ao2_unlock(instance);
1163 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
1164 ao2_lock(instance);
1165 }
1166
1167 cand_cnt++;
1168 ao2_ref(candidate, -1);
1169 }
1170
1172
1173 if (cand_cnt < ao2_container_count(rtp->ice_active_remote_candidates)) {
1174 ast_log(LOG_WARNING, "(%p) ICE lost %d candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP\n",
1175 instance, ao2_container_count(rtp->ice_active_remote_candidates) - cand_cnt);
1176 }
1177
1178 if (!has_rtp) {
1179 ast_log(LOG_WARNING, "(%p) ICE no RTP candidates; skipping checklist\n", instance);
1180 }
1181
1182 /* If we're only dealing with one ICE component, then we don't care about the lack of RTCP candidates */
1183 if (!has_rtcp && rtp->ice_num_components > 1) {
1184 ast_log(LOG_WARNING, "(%p) ICE no RTCP candidates; skipping checklist\n", instance);
1185 }
1186
1187 if (rtp->ice && has_rtp && (has_rtcp || rtp->ice_num_components == 1)) {
1188 pj_status_t res;
1189 char reason[80];
1190 struct ice_wrap *ice;
1191
1192 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1193 ice = rtp->ice;
1194 ao2_ref(ice, +1);
1195 ao2_unlock(instance);
1196 res = pj_ice_sess_create_check_list(ice->real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
1197 if (res == PJ_SUCCESS) {
1198 ast_debug_ice(2, "(%p) ICE successfully created checklist\n", instance);
1199 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
1200 pj_ice_sess_start_check(ice->real_ice);
1201 pj_timer_heap_poll(timer_heap, NULL);
1202 ao2_ref(ice, -1);
1203 ao2_lock(instance);
1205 return;
1206 }
1207 ao2_ref(ice, -1);
1208 ao2_lock(instance);
1209
1210 pj_strerror(res, reason, sizeof(reason));
1211 ast_log(LOG_WARNING, "(%p) ICE failed to create session check list: %s\n", instance, reason);
1212 }
1213
1214 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
1215
1216 /* even though create check list failed don't stop ice as
1217 it might still work */
1218 /* however we do need to reset remote candidates since
1219 this function may be re-entered */
1220 ao2_ref(rtp->ice_active_remote_candidates, -1);
1221 rtp->ice_active_remote_candidates = NULL;
1222 if (rtp->ice) {
1223 rtp->ice->real_ice->rcand_cnt = rtp->ice->real_ice->clist.count = 0;
1224 }
1225}
1226
1227/*! \pre instance is locked */
1228static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
1229{
1230 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1231
1232 return rtp->local_ufrag;
1233}
1234
1235/*! \pre instance is locked */
1236static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
1237{
1238 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1239
1240 return rtp->local_passwd;
1241}
1242
1243/*! \pre instance is locked */
1244static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
1245{
1246 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1247
1248 if (rtp->ice_local_candidates) {
1249 ao2_ref(rtp->ice_local_candidates, +1);
1250 }
1251
1252 return rtp->ice_local_candidates;
1253}
1254
1255/*! \pre instance is locked */
1256static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
1257{
1258 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1259
1260 if (!rtp->ice) {
1261 return;
1262 }
1263
1264 pj_thread_register_check();
1265
1266 pj_ice_sess_change_role(rtp->ice->real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
1267}
1268
1269/*! \pre instance is locked */
1270static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
1271{
1272 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1273
1274 if (!rtp->ice) {
1275 ast_debug_ice(3, "(%p) ICE set role failed; no ice instance\n", instance);
1276 return;
1277 }
1278
1279 rtp->role = role;
1280
1281 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1282 pj_thread_register_check();
1283 ast_debug_ice(2, "(%p) ICE set role to %s\n",
1284 instance, role == AST_RTP_ICE_ROLE_CONTROLLED ? "CONTROLLED" : "CONTROLLING");
1285 pj_ice_sess_change_role(rtp->ice->real_ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
1286 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
1287 } else {
1288 ast_debug_ice(2, "(%p) ICE not setting role because state is %s\n",
1289 instance, rtp->ice->real_ice->is_nominating ? "nominating" : "complete");
1290 }
1291}
1292
1293/*! \pre instance is locked */
1294static void ast_rtp_ice_add_cand(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
1295 unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
1296 const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr,
1297 int addr_len)
1298{
1299 pj_str_t foundation;
1300 struct ast_rtp_engine_ice_candidate *candidate, *existing;
1301 struct ice_wrap *ice;
1302 char address[PJ_INET6_ADDRSTRLEN];
1303 pj_status_t status;
1304
1305 if (!rtp->ice) {
1306 return;
1307 }
1308
1309 pj_thread_register_check();
1310
1311 pj_ice_calc_foundation(rtp->ice->real_ice->pool, &foundation, type, addr);
1312
1313 if (!rtp->ice_local_candidates) {
1314 rtp->ice_local_candidates = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1315 NULL, ice_candidate_cmp);
1316 if (!rtp->ice_local_candidates) {
1317 return;
1318 }
1319 }
1320
1321 if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
1322 return;
1323 }
1324
1325 candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
1326 candidate->id = comp_id;
1327 candidate->transport = ast_strdup("UDP");
1328
1329 ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
1330 ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
1331
1332 if (rel_addr) {
1333 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
1334 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
1335 }
1336
1337 if (type == PJ_ICE_CAND_TYPE_HOST) {
1339 } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
1341 } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
1343 }
1344
1345 if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
1346 ao2_ref(existing, -1);
1347 ao2_ref(candidate, -1);
1348 return;
1349 }
1350
1351 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1352 ice = rtp->ice;
1353 ao2_ref(ice, +1);
1354 ao2_unlock(instance);
1355 status = pj_ice_sess_add_cand(ice->real_ice, comp_id, transport_id, type, local_pref,
1356 &foundation, addr, base_addr, rel_addr, addr_len, NULL);
1357 ao2_ref(ice, -1);
1358 ao2_lock(instance);
1359 if (!rtp->ice || status != PJ_SUCCESS) {
1360 ast_debug_ice(2, "(%p) ICE unable to add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1361 &candidate->address), candidate->priority);
1362 ao2_ref(candidate, -1);
1363 return;
1364 }
1365
1366 /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
1367 candidate->priority = rtp->ice->real_ice->lcand[rtp->ice->real_ice->lcand_cnt - 1].prio;
1368
1369 ast_debug_ice(2, "(%p) ICE add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1370 &candidate->address), candidate->priority);
1371
1372 ao2_link(rtp->ice_local_candidates, candidate);
1373 ao2_ref(candidate, -1);
1374}
1375
1376/* PJPROJECT TURN callback */
1377static void ast_rtp_on_turn_rx_rtp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
1378{
1379 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1380 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1381 struct ice_wrap *ice;
1382 pj_status_t status;
1383
1384 ao2_lock(instance);
1385 ice = ao2_bump(rtp->ice);
1386 ao2_unlock(instance);
1387
1388 if (ice) {
1389 status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTP,
1390 TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr, addr_len);
1391 ao2_ref(ice, -1);
1392 if (status != PJ_SUCCESS) {
1393 char buf[100];
1394
1395 pj_strerror(status, buf, sizeof(buf));
1396 ast_log(LOG_WARNING, "(%p) ICE PJ Rx error status code: %d '%s'.\n",
1397 instance, (int)status, buf);
1398 return;
1399 }
1400 if (!rtp->rtp_passthrough) {
1401 return;
1402 }
1403 rtp->rtp_passthrough = 0;
1404 }
1405
1406 ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
1407}
1408
1409/* PJPROJECT TURN callback */
1410static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1411{
1412 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1413 struct ast_rtp *rtp;
1414
1415 /* If this is a leftover from an already notified RTP instance just ignore the state change */
1416 if (!instance) {
1417 return;
1418 }
1419
1420 rtp = ast_rtp_instance_get_data(instance);
1421
1422 ao2_lock(instance);
1423
1424 /* We store the new state so the other thread can actually handle it */
1425 rtp->turn_state = new_state;
1426 ast_cond_signal(&rtp->cond);
1427
1428 if (new_state == PJ_TURN_STATE_DESTROYING) {
1429 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
1430 rtp->turn_rtp = NULL;
1431 }
1432
1433 ao2_unlock(instance);
1434}
1435
1436/* RTP TURN Socket interface declaration */
1437static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1438 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1439 .on_state = ast_rtp_on_turn_rtp_state,
1440};
1441
1442/* PJPROJECT TURN callback */
1443static void ast_rtp_on_turn_rx_rtcp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
1444{
1445 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1446 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1447 struct ice_wrap *ice;
1448 pj_status_t status;
1449
1450 ao2_lock(instance);
1451 ice = ao2_bump(rtp->ice);
1452 ao2_unlock(instance);
1453
1454 if (ice) {
1455 status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTCP,
1456 TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr, addr_len);
1457 ao2_ref(ice, -1);
1458 if (status != PJ_SUCCESS) {
1459 char buf[100];
1460
1461 pj_strerror(status, buf, sizeof(buf));
1462 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
1463 (int)status, buf);
1464 return;
1465 }
1466 if (!rtp->rtcp_passthrough) {
1467 return;
1468 }
1469 rtp->rtcp_passthrough = 0;
1470 }
1471
1472 ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
1473}
1474
1475/* PJPROJECT TURN callback */
1476static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1477{
1478 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1479 struct ast_rtp *rtp;
1480
1481 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
1482 if (!instance) {
1483 return;
1484 }
1485
1486 rtp = ast_rtp_instance_get_data(instance);
1487
1488 ao2_lock(instance);
1489
1490 /* We store the new state so the other thread can actually handle it */
1491 rtp->turn_state = new_state;
1492 ast_cond_signal(&rtp->cond);
1493
1494 if (new_state == PJ_TURN_STATE_DESTROYING) {
1495 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
1496 rtp->turn_rtcp = NULL;
1497 }
1498
1499 ao2_unlock(instance);
1500}
1501
1502/* RTCP TURN Socket interface declaration */
1503static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1504 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1505 .on_state = ast_rtp_on_turn_rtcp_state,
1506};
1507
1508/*! \brief Worker thread for ioqueue and timerheap */
1509static int ioqueue_worker_thread(void *data)
1510{
1511 struct ast_rtp_ioqueue_thread *ioqueue = data;
1512
1513 while (!ioqueue->terminate) {
1514 const pj_time_val delay = {0, 10};
1515
1516 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
1517
1518 pj_timer_heap_poll(ioqueue->timerheap, NULL);
1519 }
1520
1521 return 0;
1522}
1523
1524/*! \brief Destroyer for ioqueue thread */
1525static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
1526{
1527 if (ioqueue->thread) {
1528 ioqueue->terminate = 1;
1529 pj_thread_join(ioqueue->thread);
1530 pj_thread_destroy(ioqueue->thread);
1531 }
1532
1533 if (ioqueue->pool) {
1534 /* This mimics the behavior of pj_pool_safe_release
1535 * which was introduced in pjproject 2.6.
1536 */
1537 pj_pool_t *temp_pool = ioqueue->pool;
1538
1539 ioqueue->pool = NULL;
1540 pj_pool_release(temp_pool);
1541 }
1542
1543 ast_free(ioqueue);
1544}
1545
1546/*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
1547static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
1548{
1549 int destroy = 0;
1550
1551 /* If nothing is using this ioqueue thread destroy it */
1552 AST_LIST_LOCK(&ioqueues);
1553 if ((ioqueue->count -= 2) == 0) {
1554 destroy = 1;
1555 AST_LIST_REMOVE(&ioqueues, ioqueue, next);
1556 }
1557 AST_LIST_UNLOCK(&ioqueues);
1558
1559 if (!destroy) {
1560 return;
1561 }
1562
1563 rtp_ioqueue_thread_destroy(ioqueue);
1564}
1565
1566/*! \brief Finder and allocator for an ioqueue thread */
1567static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
1568{
1569 struct ast_rtp_ioqueue_thread *ioqueue;
1570 pj_lock_t *lock;
1571
1572 AST_LIST_LOCK(&ioqueues);
1573
1574 /* See if an ioqueue thread exists that can handle more */
1575 AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1576 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1577 break;
1578 }
1579 }
1580
1581 /* If we found one bump it up and return it */
1582 if (ioqueue) {
1583 ioqueue->count += 2;
1584 goto end;
1585 }
1586
1587 ioqueue = ast_calloc(1, sizeof(*ioqueue));
1588 if (!ioqueue) {
1589 goto end;
1590 }
1591
1592 ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1593
1594 /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1595 * on a session at the same time
1596 */
1597 if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1598 goto fatal;
1599 }
1600
1601 if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1602 goto fatal;
1603 }
1604
1605 pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1606
1607 if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1608 goto fatal;
1609 }
1610
1611 if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1612 goto fatal;
1613 }
1614
1615 AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1616
1617 /* Since this is being returned to an active session the count always starts at 2 */
1618 ioqueue->count = 2;
1619
1620 goto end;
1621
1622fatal:
1623 rtp_ioqueue_thread_destroy(ioqueue);
1624 ioqueue = NULL;
1625
1626end:
1627 AST_LIST_UNLOCK(&ioqueues);
1628 return ioqueue;
1629}
1630
1631/*! \pre instance is locked */
1632static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1633 enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1634{
1635 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1636 pj_turn_sock **turn_sock;
1637 const pj_turn_sock_cb *turn_cb;
1638 pj_turn_tp_type conn_type;
1639 int conn_transport;
1640 pj_stun_auth_cred cred = { 0, };
1641 pj_str_t turn_addr;
1642 struct ast_sockaddr addr = { { 0, } };
1643 pj_stun_config stun_config;
1644 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1645 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1646 pj_turn_session_info info;
1647 struct ast_sockaddr local, loop;
1648 pj_status_t status;
1649 pj_turn_sock_cfg turn_sock_cfg;
1650 struct ice_wrap *ice;
1651
1652 ast_rtp_instance_get_local_address(instance, &local);
1653 if (ast_sockaddr_is_ipv4(&local)) {
1654 ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1655 } else {
1657 }
1658
1659 /* Determine what component we are requesting a TURN session for */
1660 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1661 turn_sock = &rtp->turn_rtp;
1662 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1663 conn_transport = TRANSPORT_TURN_RTP;
1665 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1666 turn_sock = &rtp->turn_rtcp;
1667 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1668 conn_transport = TRANSPORT_TURN_RTCP;
1670 } else {
1671 return;
1672 }
1673
1674 if (transport == AST_TRANSPORT_UDP) {
1675 conn_type = PJ_TURN_TP_UDP;
1676 } else if (transport == AST_TRANSPORT_TCP) {
1677 conn_type = PJ_TURN_TP_TCP;
1678 } else {
1679 ast_assert(0);
1680 return;
1681 }
1682
1683 ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1684
1685 if (*turn_sock) {
1686 rtp->turn_state = PJ_TURN_STATE_NULL;
1687
1688 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1689 ao2_unlock(instance);
1690 pj_turn_sock_destroy(*turn_sock);
1691 ao2_lock(instance);
1692 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1693 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1694 }
1695 }
1696
1697 if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1698 /*
1699 * We cannot hold the instance lock because we could wait
1700 * for the ioqueue thread to die and we might deadlock as
1701 * a result.
1702 */
1703 ao2_unlock(instance);
1704 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1705 ao2_lock(instance);
1706 if (!rtp->ioqueue) {
1707 return;
1708 }
1709 }
1710
1711 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1712 if (!stun_software_attribute) {
1713 stun_config.software_name = pj_str(NULL);
1714 }
1715
1716 /* Use ICE session group lock for TURN session to avoid deadlock */
1717 pj_turn_sock_cfg_default(&turn_sock_cfg);
1718 ice = rtp->ice;
1719 if (ice) {
1720 turn_sock_cfg.grp_lock = ice->real_ice->grp_lock;
1721 ao2_ref(ice, +1);
1722 }
1723
1724 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1725 ao2_unlock(instance);
1726 status = pj_turn_sock_create(&stun_config,
1727 ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1728 turn_cb, &turn_sock_cfg, instance, turn_sock);
1729 ao2_cleanup(ice);
1730 if (status != PJ_SUCCESS) {
1731 ast_log(LOG_WARNING, "(%p) Could not create a TURN client socket\n", instance);
1732 ao2_lock(instance);
1733 return;
1734 }
1735
1736 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1737 pj_strset2(&cred.data.static_cred.username, (char*)username);
1738 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1739 pj_strset2(&cred.data.static_cred.data, (char*)password);
1740
1741 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1742
1743 ast_debug_ice(2, "(%p) ICE request TURN %s %s candidate\n", instance,
1744 transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
1745 component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
1746
1747 ao2_lock(instance);
1748
1749 /*
1750 * Because the TURN socket is asynchronous and we are synchronous we need to
1751 * wait until it is done
1752 */
1753 while (rtp->turn_state < PJ_TURN_STATE_READY) {
1754 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1755 }
1756
1757 /* If a TURN session was allocated add it as a candidate */
1758 if (rtp->turn_state != PJ_TURN_STATE_READY) {
1759 return;
1760 }
1761
1762 pj_turn_sock_get_info(*turn_sock, &info);
1763
1764 ast_rtp_ice_add_cand(instance, rtp, component, conn_transport,
1765 PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
1766 &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1767
1768 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1769 ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1770 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1771 ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1772 }
1773}
1774
1775static char *generate_random_string(char *buf, size_t size)
1776{
1777 long val[4];
1778 int x;
1779
1780 for (x=0; x<4; x++) {
1781 val[x] = ast_random();
1782 }
1783 snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1784
1785 return buf;
1786}
1787
1788/*! \pre instance is locked */
1789static void ast_rtp_ice_change_components(struct ast_rtp_instance *instance, int num_components)
1790{
1791 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1792
1793 /* Don't do anything if ICE is unsupported or if we're not changing the
1794 * number of components
1795 */
1796 if (!icesupport || !rtp->ice || rtp->ice_num_components == num_components) {
1797 return;
1798 }
1799
1800 ast_debug_ice(2, "(%p) ICE change number of components %u -> %u\n", instance,
1801 rtp->ice_num_components, num_components);
1802
1803 rtp->ice_num_components = num_components;
1804 ice_reset_session(instance);
1805}
1806
1807/* ICE RTP Engine interface declaration */
1808static struct ast_rtp_engine_ice ast_rtp_ice = {
1810 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1811 .start = ast_rtp_ice_start,
1812 .stop = ast_rtp_ice_stop,
1813 .get_ufrag = ast_rtp_ice_get_ufrag,
1814 .get_password = ast_rtp_ice_get_password,
1815 .get_local_candidates = ast_rtp_ice_get_local_candidates,
1816 .ice_lite = ast_rtp_ice_lite,
1817 .set_role = ast_rtp_ice_set_role,
1818 .turn_request = ast_rtp_ice_turn_request,
1819 .change_components = ast_rtp_ice_change_components,
1820};
1821#endif
1822
1823#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
1825{
1826 /* We don't want to actually verify the certificate so just accept what they have provided */
1827 return 1;
1828}
1829
1830static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1831 enum ast_rtp_dtls_setup setup, struct ast_rtp_instance *instance)
1832{
1833 dtls->dtls_setup = setup;
1834
1835 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1836 ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1837 goto error;
1838 }
1839
1840 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1841 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1842 goto error;
1843 }
1844 BIO_set_mem_eof_return(dtls->read_bio, -1);
1845
1846#ifdef HAVE_OPENSSL_BIO_METHOD
1847 if (!(dtls->write_bio = BIO_new(dtls_bio_methods))) {
1848 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1849 goto error;
1850 }
1851
1852 BIO_set_data(dtls->write_bio, instance);
1853#else
1854 if (!(dtls->write_bio = BIO_new(&dtls_bio_methods))) {
1855 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1856 goto error;
1857 }
1858 dtls->write_bio->ptr = instance;
1859#endif
1860 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1861
1862 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1863 SSL_set_accept_state(dtls->ssl);
1864 } else {
1865 SSL_set_connect_state(dtls->ssl);
1866 }
1867 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1868
1869 return 0;
1870
1871error:
1872 if (dtls->read_bio) {
1873 BIO_free(dtls->read_bio);
1874 dtls->read_bio = NULL;
1875 }
1876
1877 if (dtls->write_bio) {
1878 BIO_free(dtls->write_bio);
1879 dtls->write_bio = NULL;
1880 }
1881
1882 if (dtls->ssl) {
1883 SSL_free(dtls->ssl);
1884 dtls->ssl = NULL;
1885 }
1886 return -1;
1887}
1888
1889static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1890{
1891 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1892
1893 if (!rtp->ssl_ctx || !rtp->rtcp) {
1894 return 0;
1895 }
1896
1897 ast_debug_dtls(3, "(%p) DTLS RTCP setup\n", instance);
1898 return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup, instance);
1899}
1900
1901static const SSL_METHOD *get_dtls_method(void)
1902{
1903#if OPENSSL_VERSION_NUMBER < 0x10002000L
1904 return DTLSv1_method();
1905#else
1906 return DTLS_method();
1907#endif
1908}
1909
1910struct dtls_cert_info {
1911 EVP_PKEY *private_key;
1912 X509 *certificate;
1913};
1914
1915static int apply_dh_params(SSL_CTX *ctx, BIO *bio)
1916{
1917 int res = 0;
1918
1919#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1920 EVP_PKEY *dhpkey = PEM_read_bio_Parameters(bio, NULL);
1921 if (dhpkey && EVP_PKEY_is_a(dhpkey, "DH")) {
1922 res = SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey);
1923 }
1924 if (!res) {
1925 /* A successful call to SSL_CTX_set0_tmp_dh_pkey() means
1926 that we lost ownership of dhpkey and should not free
1927 it ourselves */
1928 EVP_PKEY_free(dhpkey);
1929 }
1930#else
1931 DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1932 if (dh) {
1933 res = SSL_CTX_set_tmp_dh(ctx, dh);
1934 }
1935 DH_free(dh);
1936#endif
1937
1938 return res;
1939}
1940
1941static void configure_dhparams(const struct ast_rtp *rtp, const struct ast_rtp_dtls_cfg *dtls_cfg)
1942{
1943#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1944 EC_KEY *ecdh;
1945#endif
1946
1947#ifndef OPENSSL_NO_DH
1948 if (!ast_strlen_zero(dtls_cfg->pvtfile)) {
1949 BIO *bio = BIO_new_file(dtls_cfg->pvtfile, "r");
1950 if (bio) {
1951 if (apply_dh_params(rtp->ssl_ctx, bio)) {
1952 long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
1953 SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
1954 options = SSL_CTX_set_options(rtp->ssl_ctx, options);
1955 ast_verb(2, "DTLS DH initialized, PFS enabled\n");
1956 }
1957 BIO_free(bio);
1958 }
1959 }
1960#endif /* !OPENSSL_NO_DH */
1961
1962#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1963 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
1964 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1965 if (ecdh) {
1966 if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
1967 #ifndef SSL_CTRL_SET_ECDH_AUTO
1968 #define SSL_CTRL_SET_ECDH_AUTO 94
1969 #endif
1970 /* SSL_CTX_set_ecdh_auto(rtp->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
1971 if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
1972 ast_verb(2, "DTLS ECDH initialized (automatic), faster PFS enabled\n");
1973 } else {
1974 ast_verb(2, "DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
1975 }
1976 }
1977 EC_KEY_free(ecdh);
1978 }
1979#endif /* !OPENSSL_NO_ECDH */
1980}
1981
1982#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
1983
1984static int create_ephemeral_ec_keypair(EVP_PKEY **keypair)
1985{
1986#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1987 *keypair = EVP_EC_gen(SN_X9_62_prime256v1);
1988 return *keypair ? 0 : -1;
1989#else
1990 EC_KEY *eckey = NULL;
1991 EC_GROUP *group = NULL;
1992
1993 group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1994 if (!group) {
1995 goto error;
1996 }
1997
1998 EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
1999 EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED);
2000
2001 eckey = EC_KEY_new();
2002 if (!eckey) {
2003 goto error;
2004 }
2005
2006 if (!EC_KEY_set_group(eckey, group)) {
2007 goto error;
2008 }
2009
2010 if (!EC_KEY_generate_key(eckey)) {
2011 goto error;
2012 }
2013
2014 *keypair = EVP_PKEY_new();
2015 if (!*keypair) {
2016 goto error;
2017 }
2018
2019 EVP_PKEY_assign_EC_KEY(*keypair, eckey);
2020 EC_GROUP_free(group);
2021
2022 return 0;
2023
2024error:
2025 EC_KEY_free(eckey);
2026 EC_GROUP_free(group);
2027
2028 return -1;
2029#endif
2030}
2031
2032/* From OpenSSL's x509 command */
2033#define SERIAL_RAND_BITS 159
2034
2035static int create_ephemeral_certificate(EVP_PKEY *keypair, X509 **certificate)
2036{
2037 X509 *cert = NULL;
2038 BIGNUM *serial = NULL;
2039 X509_NAME *name = NULL;
2040
2041 cert = X509_new();
2042 if (!cert) {
2043 goto error;
2044 }
2045
2046 if (!X509_set_version(cert, 2)) {
2047 goto error;
2048 }
2049
2050 /* Set the public key */
2051 X509_set_pubkey(cert, keypair);
2052
2053 /* Generate a random serial number */
2054 if (!(serial = BN_new())
2055 || !BN_rand(serial, SERIAL_RAND_BITS, -1, 0)
2056 || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) {
2057 BN_free(serial);
2058 goto error;
2059 }
2060
2061 BN_free(serial);
2062
2063 /*
2064 * Validity period - Current Chrome & Firefox make it 31 days starting
2065 * with yesterday at the current time, so we will do the same.
2066 */
2067#if OPENSSL_VERSION_NUMBER < 0x10100000L
2068 if (!X509_time_adj_ex(X509_get_notBefore(cert), -1, 0, NULL)
2069 || !X509_time_adj_ex(X509_get_notAfter(cert), 30, 0, NULL)) {
2070 goto error;
2071 }
2072#else
2073 if (!X509_time_adj_ex(X509_getm_notBefore(cert), -1, 0, NULL)
2074 || !X509_time_adj_ex(X509_getm_notAfter(cert), 30, 0, NULL)) {
2075 goto error;
2076 }
2077#endif
2078
2079 /* Set the name and issuer */
2080 if (!(name = X509_get_subject_name(cert))
2081 || !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC,
2082 (unsigned char *) "asterisk", -1, -1, 0)
2083 || !X509_set_issuer_name(cert, name)) {
2084 goto error;
2085 }
2086
2087 /* Sign it */
2088 if (!X509_sign(cert, keypair, EVP_sha256())) {
2089 goto error;
2090 }
2091
2092 *certificate = cert;
2093
2094 return 0;
2095
2096error:
2097 X509_free(cert);
2098
2099 return -1;
2100}
2101
2102static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2103 const struct ast_rtp_dtls_cfg *dtls_cfg,
2104 struct dtls_cert_info *cert_info)
2105{
2106 /* Make sure these are initialized */
2107 cert_info->private_key = NULL;
2108 cert_info->certificate = NULL;
2109
2110 if (create_ephemeral_ec_keypair(&cert_info->private_key)) {
2111 ast_log(LOG_ERROR, "Failed to create ephemeral ECDSA keypair\n");
2112 goto error;
2113 }
2114
2115 if (create_ephemeral_certificate(cert_info->private_key, &cert_info->certificate)) {
2116 ast_log(LOG_ERROR, "Failed to create ephemeral X509 certificate\n");
2117 goto error;
2118 }
2119
2120 return 0;
2121
2122 error:
2123 X509_free(cert_info->certificate);
2124 EVP_PKEY_free(cert_info->private_key);
2125
2126 return -1;
2127}
2128
2129#else
2130
2131static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2132 const struct ast_rtp_dtls_cfg *dtls_cfg,
2133 struct dtls_cert_info *cert_info)
2134{
2135 ast_log(LOG_ERROR, "Your version of OpenSSL does not support ECDSA keys\n");
2136 return -1;
2137}
2138
2139#endif /* !OPENSSL_NO_ECDH */
2140
2141static int create_certificate_from_file(struct ast_rtp_instance *instance,
2142 const struct ast_rtp_dtls_cfg *dtls_cfg,
2143 struct dtls_cert_info *cert_info)
2144{
2145 FILE *fp;
2146 BIO *certbio = NULL;
2147 EVP_PKEY *private_key = NULL;
2148 X509 *cert = NULL;
2149 char *private_key_file = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
2150
2151 fp = fopen(private_key_file, "r");
2152 if (!fp) {
2153 ast_log(LOG_ERROR, "Failed to read private key from file '%s': %s\n", private_key_file, strerror(errno));
2154 goto error;
2155 }
2156
2157 if (!PEM_read_PrivateKey(fp, &private_key, NULL, NULL)) {
2158 ast_log(LOG_ERROR, "Failed to read private key from PEM file '%s'\n", private_key_file);
2159 fclose(fp);
2160 goto error;
2161 }
2162
2163 if (fclose(fp)) {
2164 ast_log(LOG_ERROR, "Failed to close private key file '%s': %s\n", private_key_file, strerror(errno));
2165 goto error;
2166 }
2167
2168 certbio = BIO_new(BIO_s_file());
2169 if (!certbio) {
2170 ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
2171 instance);
2172 goto error;
2173 }
2174
2175 if (!BIO_read_filename(certbio, dtls_cfg->certfile)
2176 || !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
2177 ast_log(LOG_ERROR, "Failed to read certificate from file '%s'\n", dtls_cfg->certfile);
2178 goto error;
2179 }
2180
2181 cert_info->private_key = private_key;
2182 cert_info->certificate = cert;
2183
2184 BIO_free_all(certbio);
2185
2186 return 0;
2187
2188error:
2189 X509_free(cert);
2190 BIO_free_all(certbio);
2191 EVP_PKEY_free(private_key);
2192
2193 return -1;
2194}
2195
2196static int load_dtls_certificate(struct ast_rtp_instance *instance,
2197 const struct ast_rtp_dtls_cfg *dtls_cfg,
2198 struct dtls_cert_info *cert_info)
2199{
2200 if (dtls_cfg->ephemeral_cert) {
2201 return create_certificate_ephemeral(instance, dtls_cfg, cert_info);
2202 } else if (!ast_strlen_zero(dtls_cfg->certfile)) {
2203 return create_certificate_from_file(instance, dtls_cfg, cert_info);
2204 } else {
2205 return -1;
2206 }
2207}
2208
2209/*! \pre instance is locked */
2210static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
2211{
2212 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2213 struct dtls_cert_info cert_info = { 0 };
2214 int res;
2215
2216 if (!dtls_cfg->enabled) {
2217 return 0;
2218 }
2219
2220 ast_debug_dtls(3, "(%p) DTLS RTP setup\n", instance);
2221
2223 ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
2224 return -1;
2225 }
2226
2227 if (rtp->ssl_ctx) {
2228 return 0;
2229 }
2230
2231 rtp->ssl_ctx = SSL_CTX_new(get_dtls_method());
2232 if (!rtp->ssl_ctx) {
2233 return -1;
2234 }
2235
2236 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
2237
2238 configure_dhparams(rtp, dtls_cfg);
2239
2240 rtp->dtls_verify = dtls_cfg->verify;
2241
2242 SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2243 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2244 dtls_verify_callback : NULL);
2245
2246 if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
2247 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
2248 } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
2249 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
2250 } else {
2251 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
2252 return -1;
2253 }
2254
2255 rtp->local_hash = dtls_cfg->hash;
2256
2257 if (!load_dtls_certificate(instance, dtls_cfg, &cert_info)) {
2258 const EVP_MD *type;
2259 unsigned int size, i;
2260 unsigned char fingerprint[EVP_MAX_MD_SIZE];
2261 char *local_fingerprint = rtp->local_fingerprint;
2262
2263 if (!SSL_CTX_use_certificate(rtp->ssl_ctx, cert_info.certificate)) {
2264 ast_log(LOG_ERROR, "Specified certificate for RTP instance '%p' could not be used\n",
2265 instance);
2266 return -1;
2267 }
2268
2269 if (!SSL_CTX_use_PrivateKey(rtp->ssl_ctx, cert_info.private_key)
2270 || !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
2271 ast_log(LOG_ERROR, "Specified private key for RTP instance '%p' could not be used\n",
2272 instance);
2273 return -1;
2274 }
2275
2276 if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
2277 type = EVP_sha1();
2278 } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
2279 type = EVP_sha256();
2280 } else {
2281 ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
2282 instance);
2283 return -1;
2284 }
2285
2286 if (!X509_digest(cert_info.certificate, type, fingerprint, &size) || !size) {
2287 ast_log(LOG_ERROR, "Could not produce fingerprint from certificate for RTP instance '%p'\n",
2288 instance);
2289 return -1;
2290 }
2291
2292 for (i = 0; i < size; i++) {
2293 sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
2294 local_fingerprint += 3;
2295 }
2296
2297 *(local_fingerprint - 1) = 0;
2298
2299 EVP_PKEY_free(cert_info.private_key);
2300 X509_free(cert_info.certificate);
2301 }
2302
2303 if (!ast_strlen_zero(dtls_cfg->cipher)) {
2304 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
2305 ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
2306 dtls_cfg->cipher, instance);
2307 return -1;
2308 }
2309 }
2310
2311 if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
2312 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
2313 ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
2314 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
2315 return -1;
2316 }
2317 }
2318
2319 rtp->rekey = dtls_cfg->rekey;
2320 rtp->suite = dtls_cfg->suite;
2321
2322 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup, instance);
2323 if (!res) {
2324 dtls_setup_rtcp(instance);
2325 }
2326
2327 return res;
2328}
2329
2330/*! \pre instance is locked */
2331static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
2332{
2333 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2334
2335 return !rtp->ssl_ctx ? 0 : 1;
2336}
2337
2338/*! \pre instance is locked */
2339static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
2340{
2341 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2342 SSL *ssl = rtp->dtls.ssl;
2343
2344 ast_debug_dtls(3, "(%p) DTLS stop\n", instance);
2345 ao2_unlock(instance);
2346 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
2347 ao2_lock(instance);
2348
2349 if (rtp->ssl_ctx) {
2350 SSL_CTX_free(rtp->ssl_ctx);
2351 rtp->ssl_ctx = NULL;
2352 }
2353
2354 if (rtp->dtls.ssl) {
2355 SSL_free(rtp->dtls.ssl);
2356 rtp->dtls.ssl = NULL;
2357 }
2358
2359 if (rtp->rtcp) {
2360 ao2_unlock(instance);
2361 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
2362 ao2_lock(instance);
2363
2364 if (rtp->rtcp->dtls.ssl) {
2365 if (rtp->rtcp->dtls.ssl != ssl) {
2366 SSL_free(rtp->rtcp->dtls.ssl);
2367 }
2368 rtp->rtcp->dtls.ssl = NULL;
2369 }
2370 }
2371}
2372
2373/*! \pre instance is locked */
2374static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
2375{
2376 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2377
2378 if (SSL_is_init_finished(rtp->dtls.ssl)) {
2379 SSL_shutdown(rtp->dtls.ssl);
2380 rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2381 }
2382
2383 if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
2384 SSL_shutdown(rtp->rtcp->dtls.ssl);
2385 rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2386 }
2387}
2388
2389/*! \pre instance is locked */
2390static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
2391{
2392 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2393
2394 return rtp->dtls.connection;
2395}
2396
2397/*! \pre instance is locked */
2398static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
2399{
2400 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2401
2402 return rtp->dtls.dtls_setup;
2403}
2404
2405static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
2406{
2407 enum ast_rtp_dtls_setup old = *dtls_setup;
2408
2409 switch (setup) {
2411 *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2412 break;
2414 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2415 break;
2417 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
2418 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2419 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2420 }
2421 break;
2423 *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
2424 break;
2425 default:
2426 /* This should never occur... if it does exit early as we don't know what state things are in */
2427 return;
2428 }
2429
2430 /* If the setup state did not change we go on as if nothing happened */
2431 if (old == *dtls_setup) {
2432 return;
2433 }
2434
2435 /* If they don't want us to establish a connection wait until later */
2436 if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
2437 return;
2438 }
2439
2440 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
2441 SSL_set_connect_state(ssl);
2442 } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2443 SSL_set_accept_state(ssl);
2444 } else {
2445 return;
2446 }
2447}
2448
2449/*! \pre instance is locked */
2450static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
2451{
2452 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2453
2454 if (rtp->dtls.ssl) {
2455 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
2456 }
2457
2458 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
2459 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
2460 }
2461}
2462
2463/*! \pre instance is locked */
2464static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
2465{
2466 char *tmp = ast_strdupa(fingerprint), *value;
2467 int pos = 0;
2468 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2469
2470 if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
2471 return;
2472 }
2473
2474 rtp->remote_hash = hash;
2475
2476 while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
2477 sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
2478 }
2479}
2480
2481/*! \pre instance is locked */
2482static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
2483{
2484 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2485
2486 return rtp->local_hash;
2487}
2488
2489/*! \pre instance is locked */
2490static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
2491{
2492 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2493
2494 return rtp->local_fingerprint;
2495}
2496
2497/* DTLS RTP Engine interface declaration */
2498static struct ast_rtp_engine_dtls ast_rtp_dtls = {
2499 .set_configuration = ast_rtp_dtls_set_configuration,
2500 .active = ast_rtp_dtls_active,
2501 .stop = ast_rtp_dtls_stop,
2502 .reset = ast_rtp_dtls_reset,
2503 .get_connection = ast_rtp_dtls_get_connection,
2504 .get_setup = ast_rtp_dtls_get_setup,
2505 .set_setup = ast_rtp_dtls_set_setup,
2506 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
2507 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
2508 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
2509};
2510
2511#endif
2512
2513#ifdef TEST_FRAMEWORK
2514static size_t get_recv_buffer_count(struct ast_rtp_instance *instance)
2515{
2516 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2517
2518 if (rtp && rtp->recv_buffer) {
2520 }
2521
2522 return 0;
2523}
2524
2525static size_t get_recv_buffer_max(struct ast_rtp_instance *instance)
2526{
2527 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2528
2529 if (rtp && rtp->recv_buffer) {
2530 return ast_data_buffer_max(rtp->recv_buffer);
2531 }
2532
2533 return 0;
2534}
2535
2536static size_t get_send_buffer_count(struct ast_rtp_instance *instance)
2537{
2538 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2539
2540 if (rtp && rtp->send_buffer) {
2542 }
2543
2544 return 0;
2545}
2546
2547static void set_rtp_rtcp_schedid(struct ast_rtp_instance *instance, int id)
2548{
2549 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2550
2551 if (rtp && rtp->rtcp) {
2552 rtp->rtcp->schedid = id;
2553 }
2554}
2555
2556static struct ast_rtp_engine_test ast_rtp_test = {
2557 .packets_to_drop = 0,
2558 .send_report = 0,
2559 .sdes_received = 0,
2560 .recv_buffer_count = get_recv_buffer_count,
2561 .recv_buffer_max = get_recv_buffer_max,
2562 .send_buffer_count = get_send_buffer_count,
2563 .set_schedid = set_rtp_rtcp_schedid,
2564};
2565#endif
2566
2567/* RTP Engine Declaration */
2569 .name = "asterisk",
2570 .new = ast_rtp_new,
2571 .destroy = ast_rtp_destroy,
2572 .dtmf_begin = ast_rtp_dtmf_begin,
2573 .dtmf_end = ast_rtp_dtmf_end,
2574 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
2575 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
2576 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
2577 .update_source = ast_rtp_update_source,
2578 .change_source = ast_rtp_change_source,
2579 .write = ast_rtp_write,
2580 .read = ast_rtp_read,
2581 .prop_set = ast_rtp_prop_set,
2582 .fd = ast_rtp_fd,
2583 .remote_address_set = ast_rtp_remote_address_set,
2584 .red_init = rtp_red_init,
2585 .red_buffer = rtp_red_buffer,
2586 .local_bridge = ast_rtp_local_bridge,
2587 .get_stat = ast_rtp_get_stat,
2588 .dtmf_compatible = ast_rtp_dtmf_compatible,
2589 .stun_request = ast_rtp_stun_request,
2590 .stop = ast_rtp_stop,
2591 .qos = ast_rtp_qos_set,
2592 .sendcng = ast_rtp_sendcng,
2593#ifdef HAVE_PJPROJECT
2594 .ice = &ast_rtp_ice,
2595#endif
2596#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2597 .dtls = &ast_rtp_dtls,
2598 .activate = ast_rtp_activate,
2599#endif
2600 .ssrc_get = ast_rtp_get_ssrc,
2601 .cname_get = ast_rtp_get_cname,
2602 .set_remote_ssrc = ast_rtp_set_remote_ssrc,
2603 .set_stream_num = ast_rtp_set_stream_num,
2604 .extension_enable = ast_rtp_extension_enable,
2605 .bundle = ast_rtp_bundle,
2606#ifdef TEST_FRAMEWORK
2607 .test = &ast_rtp_test,
2608#endif
2609};
2610
2611#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2612/*! \pre instance is locked */
2613static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
2614{
2615 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2616
2617 ast_debug_dtls(3, "(%p) DTLS perform handshake - ssl = %p, setup = %d\n",
2618 rtp, dtls->ssl, dtls->dtls_setup);
2619
2620 /* If we are not acting as a client connecting to the remote side then
2621 * don't start the handshake as it will accomplish nothing and would conflict
2622 * with the handshake we receive from the remote side.
2623 */
2624 if (!dtls->ssl || (dtls->dtls_setup != AST_RTP_DTLS_SETUP_ACTIVE)) {
2625 return;
2626 }
2627
2628 SSL_do_handshake(dtls->ssl);
2629
2630 /*
2631 * A race condition is prevented between this function and __rtp_recvfrom()
2632 * because both functions have to get the instance lock before they can do
2633 * anything. Without holding the instance lock, this function could start
2634 * the SSL handshake above in one thread and the __rtp_recvfrom() function
2635 * called by the channel thread could read the response and stop the timeout
2636 * timer before we have a chance to even start it.
2637 */
2638 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
2639}
2640#endif
2641
2642#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2643static void dtls_perform_setup(struct dtls_details *dtls)
2644{
2645 if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
2646 return;
2647 }
2648
2649 SSL_clear(dtls->ssl);
2650 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2651 SSL_set_accept_state(dtls->ssl);
2652 } else {
2653 SSL_set_connect_state(dtls->ssl);
2654 }
2655 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
2656
2657 ast_debug_dtls(3, "DTLS perform setup - connection reset\n");
2658}
2659#endif
2660
2661#ifdef HAVE_PJPROJECT
2662static void rtp_learning_start(struct ast_rtp *rtp);
2663
2664/* Handles start of media during ICE negotiation or completion */
2665static void ast_rtp_ice_start_media(pj_ice_sess *ice, pj_status_t status)
2666{
2667 struct ast_rtp_instance *instance = ice->user_data;
2668 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2669
2670 ao2_lock(instance);
2671
2672 if (status == PJ_SUCCESS) {
2673 struct ast_sockaddr remote_address;
2674
2675 ast_sockaddr_setnull(&remote_address);
2676 update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2677 if (!ast_sockaddr_isnull(&remote_address)) {
2678 /* Symmetric RTP must be disabled for the remote address to not get overwritten */
2680
2681 ast_rtp_instance_set_remote_address(instance, &remote_address);
2682 }
2683
2684 if (rtp->rtcp) {
2685 update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
2686 }
2687 }
2688
2689#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2690 /* If we've already started media, no need to do all of this again */
2691 if (rtp->ice_media_started) {
2692 ao2_unlock(instance);
2693 return;
2694 }
2695
2697 "(%p) ICE starting media - perform DTLS - (%p)\n", instance, rtp);
2698
2699 /*
2700 * Seemingly no reason to call dtls_perform_setup here. Currently we'll do a full
2701 * protocol level renegotiation if things do change. And if bundled is being used
2702 * then ICE is reused when a stream is added.
2703 *
2704 * Note, if for some reason in the future dtls_perform_setup does need to done here
2705 * be aware that creates a race condition between the call here (on ice completion)
2706 * and potential DTLS handshaking when receiving RTP. What happens is the ssl object
2707 * can get cleared (SSL_clear) during that handshaking process (DTLS init). If that
2708 * happens then Asterisk won't complete DTLS initialization. RTP packets are still
2709 * sent/received but won't be encrypted/decrypted.
2710 */
2711 dtls_perform_handshake(instance, &rtp->dtls, 0);
2712
2713 if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
2714 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
2715 }
2716#endif
2717
2718 rtp->ice_media_started = 1;
2719
2720 if (!strictrtp) {
2721 ao2_unlock(instance);
2722 return;
2723 }
2724
2725 ast_verb(4, "%p -- Strict RTP learning after ICE completion\n", rtp);
2726 rtp_learning_start(rtp);
2727 ao2_unlock(instance);
2728}
2729
2730#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2731/* PJPROJECT ICE optional callback */
2732static void ast_rtp_on_valid_pair(pj_ice_sess *ice)
2733{
2734 ast_debug_ice(2, "(%p) ICE valid pair, start media\n", ice->user_data);
2735 ast_rtp_ice_start_media(ice, PJ_SUCCESS);
2736}
2737#endif
2738
2739/* PJPROJECT ICE callback */
2740static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
2741{
2742 ast_debug_ice(2, "(%p) ICE complete, start media\n", ice->user_data);
2743 ast_rtp_ice_start_media(ice, status);
2744}
2745
2746/* PJPROJECT ICE callback */
2747static void ast_rtp_on_ice_rx_data(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, void *pkt, pj_size_t size, const pj_sockaddr_t *src_addr, unsigned src_addr_len)
2748{
2749 struct ast_rtp_instance *instance = ice->user_data;
2750 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2751
2752 /* Instead of handling the packet here (which really doesn't work with our architecture) we set a bit to indicate that it should be handled after pj_ice_sess_on_rx_pkt
2753 * returns */
2754 if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
2755 rtp->passthrough = 1;
2756 } else if (transport_id == TRANSPORT_TURN_RTP) {
2757 rtp->rtp_passthrough = 1;
2758 } else if (transport_id == TRANSPORT_TURN_RTCP) {
2759 rtp->rtcp_passthrough = 1;
2760 }
2761}
2762
2763/* PJPROJECT ICE callback */
2764static pj_status_t ast_rtp_on_ice_tx_pkt(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, const void *pkt, pj_size_t size, const pj_sockaddr_t *dst_addr, unsigned dst_addr_len)
2765{
2766 struct ast_rtp_instance *instance = ice->user_data;
2767 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2768 pj_status_t status = PJ_EINVALIDOP;
2769 pj_ssize_t _size = (pj_ssize_t)size;
2770
2771 if (transport_id == TRANSPORT_SOCKET_RTP) {
2772 /* Traffic is destined to go right out the RTP socket we already have */
2773 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2774 /* sendto on a connectionless socket should send all the data, or none at all */
2775 ast_assert(_size == size || status != PJ_SUCCESS);
2776 } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
2777 /* Traffic is destined to go right out the RTCP socket we already have */
2778 if (rtp->rtcp) {
2779 status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2780 /* sendto on a connectionless socket should send all the data, or none at all */
2781 ast_assert(_size == size || status != PJ_SUCCESS);
2782 } else {
2783 status = PJ_SUCCESS;
2784 }
2785 } else if (transport_id == TRANSPORT_TURN_RTP) {
2786 /* Traffic is going through the RTP TURN relay */
2787 if (rtp->turn_rtp) {
2788 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
2789 }
2790 } else if (transport_id == TRANSPORT_TURN_RTCP) {
2791 /* Traffic is going through the RTCP TURN relay */
2792 if (rtp->turn_rtcp) {
2793 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
2794 }
2795 }
2796
2797 return status;
2798}
2799
2800/* ICE Session interface declaration */
2801static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
2802#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2803 .on_valid_pair = ast_rtp_on_valid_pair,
2804#endif
2805 .on_ice_complete = ast_rtp_on_ice_complete,
2806 .on_rx_data = ast_rtp_on_ice_rx_data,
2807 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
2808};
2809
2810/*! \brief Worker thread for timerheap */
2811static int timer_worker_thread(void *data)
2812{
2813 pj_ioqueue_t *ioqueue;
2814
2815 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
2816 return -1;
2817 }
2818
2819 while (!timer_terminate) {
2820 const pj_time_val delay = {0, 10};
2821
2822 pj_timer_heap_poll(timer_heap, NULL);
2823 pj_ioqueue_poll(ioqueue, &delay);
2824 }
2825
2826 return 0;
2827}
2828#endif
2829
2830static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
2831{
2833 return 0;
2834 }
2836 if (rtpdebugport) {
2837 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
2838 } else {
2839 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
2840 }
2841 }
2842
2843 return 1;
2844}
2845
2846static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
2847{
2849 return 0;
2850 }
2852 if (rtcpdebugport) {
2853 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
2854 } else {
2855 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
2856 }
2857 }
2858
2859 return 1;
2860}
2861
2862#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2863/*!
2864 * \brief Handles DTLS timer expiration
2865 *
2866 * \param instance
2867 * \param timeout
2868 * \param rtcp
2869 *
2870 * If DTLSv1_get_timeout() returns 0, it's an error or no timeout was set.
2871 * We need to unref instance and stop the timer in this case. Otherwise,
2872 * new timeout may be a number of milliseconds or 0. If it's 0, OpenSSL
2873 * is telling us to call DTLSv1_handle_timeout() immediately so we'll set
2874 * timeout to 1ms so we get rescheduled almost immediately.
2875 *
2876 * \retval 0 - success
2877 * \retval -1 - failure
2878 */
2879static int dtls_srtp_handle_timeout(struct ast_rtp_instance *instance, int *timeout, int rtcp)
2880{
2881 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2882 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2883 struct timeval dtls_timeout;
2884 int res = 0;
2885
2886 res = DTLSv1_handle_timeout(dtls->ssl);
2887 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d result: %d\n", instance, rtcp, res);
2888
2889 /* If a timeout can't be retrieved then this recurring scheduled item must stop */
2890 res = DTLSv1_get_timeout(dtls->ssl, &dtls_timeout);
2891 if (!res) {
2892 /* Make sure we don't try to stop the timer later if it's already been stopped */
2893 dtls->timeout_timer = -1;
2894 ao2_ref(instance, -1);
2895 *timeout = 0;
2896 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d get timeout failure\n", instance, rtcp);
2897 return -1;
2898 }
2899 *timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2900 if (*timeout == 0) {
2901 /*
2902 * If DTLSv1_get_timeout() succeeded with a timeout of 0, OpenSSL
2903 * is telling us to call DTLSv1_handle_timeout() again now HOWEVER...
2904 * Do NOT be tempted to call DTLSv1_handle_timeout() and
2905 * DTLSv1_get_timeout() in a loop while the timeout is 0. There is only
2906 * 1 thread running the scheduler for all PJSIP related RTP instances
2907 * so we don't want to delay here any more than necessary. It's also
2908 * possible that an OpenSSL bug or change in behavior could cause
2909 * DTLSv1_get_timeout() to return 0 forever. If that happens, we'll
2910 * be stuck here and no other RTP instances will get serviced.
2911 * This RTP instance is also locked while this callback runs so we
2912 * don't want to delay other threads that may need to lock this
2913 * RTP instance for their own purpose.
2914 *
2915 * Just set the timeout to 1ms and let the scheduler reschedule us
2916 * as quickly as possible.
2917 */
2918 *timeout = 1;
2919 }
2920 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d timeout=%d\n", instance, rtcp, *timeout);
2921
2922 return 0;
2923}
2924
2925/* Scheduler callback */
2926static int dtls_srtp_handle_rtp_timeout(const void *data)
2927{
2928 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2929 int timeout = 0;
2930 int res = 0;
2931
2932 ao2_lock(instance);
2933 res = dtls_srtp_handle_timeout(instance, &timeout, 0);
2934 ao2_unlock(instance);
2935 if (res < 0) {
2936 /* Tells the scheduler to stop rescheduling */
2937 return 0;
2938 }
2939
2940 /* Reschedule based on the timeout value */
2941 return timeout;
2942}
2943
2944/* Scheduler callback */
2945static int dtls_srtp_handle_rtcp_timeout(const void *data)
2946{
2947 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2948 int timeout = 0;
2949 int res = 0;
2950
2951 ao2_lock(instance);
2952 res = dtls_srtp_handle_timeout(instance, &timeout, 1);
2953 ao2_unlock(instance);
2954 if (res < 0) {
2955 /* Tells the scheduler to stop rescheduling */
2956 return 0;
2957 }
2958
2959 /* Reschedule based on the timeout value */
2960 return timeout;
2961}
2962
2963static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
2964{
2965 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2966 ast_sched_cb cb = !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout;
2967 struct timeval dtls_timeout;
2968 int res = 0;
2969 int timeout = 0;
2970
2971 ast_assert(dtls->timeout_timer == -1);
2972
2973 res = DTLSv1_get_timeout(dtls->ssl, &dtls_timeout);
2974 if (res == 0) {
2975 ast_debug_dtls(3, "(%p) DTLS srtp - DTLSv1_get_timeout return an error or there was no timeout set for %s\n",
2976 instance, rtcp ? "RTCP" : "RTP");
2977 return;
2978 }
2979
2980 timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2981
2982 ao2_ref(instance, +1);
2983 /*
2984 * We want the timer to fire again based on calling DTLSv1_get_timeout()
2985 * inside the callback, not at a fixed interval.
2986 */
2987 if ((dtls->timeout_timer = ast_sched_add_variable(rtp->sched, timeout, cb, instance, 1)) < 0) {
2988 ao2_ref(instance, -1);
2989 ast_log(LOG_WARNING, "Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
2990 !rtcp ? "RTP" : "RTCP", instance);
2991 } else {
2992 ast_debug_dtls(3, "(%p) DTLS srtp - scheduled timeout timer for '%d' %s\n",
2993 instance, timeout, rtcp ? "RTCP" : "RTP");
2994 }
2995}
2996
2997/*! \pre Must not be called with the instance locked. */
2998static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
2999{
3000 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3001
3002 AST_SCHED_DEL_UNREF(rtp->sched, dtls->timeout_timer, ao2_ref(instance, -1));
3003 ast_debug_dtls(3, "(%p) DTLS srtp - stopped timeout timer'\n", instance);
3004}
3005
3006/* Scheduler callback */
3007static int dtls_srtp_renegotiate(const void *data)
3008{
3009 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
3010 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3011
3012 ao2_lock(instance);
3013
3014 ast_debug_dtls(3, "(%p) DTLS srtp - renegotiate'\n", instance);
3015 SSL_renegotiate(rtp->dtls.ssl);
3016 SSL_do_handshake(rtp->dtls.ssl);
3017
3018 if (rtp->rtcp && rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
3019 SSL_renegotiate(rtp->rtcp->dtls.ssl);
3020 SSL_do_handshake(rtp->rtcp->dtls.ssl);
3021 }
3022
3023 rtp->rekeyid = -1;
3024
3025 ao2_unlock(instance);
3026 ao2_ref(instance, -1);
3027
3028 return 0;
3029}
3030
3031static int dtls_srtp_add_local_ssrc(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp, unsigned int ssrc, int set_remote_policy)
3032{
3033 unsigned char material[SRTP_MASTER_LEN * 2];
3034 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
3035 struct ast_srtp_policy *local_policy, *remote_policy = NULL;
3036 int res = -1;
3037 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3038
3039 ast_debug_dtls(3, "(%p) DTLS srtp - add local ssrc - rtcp=%d, set_remote_policy=%d'\n",
3040 instance, rtcp, set_remote_policy);
3041
3042 /* Produce key information and set up SRTP */
3043 if (!SSL_export_keying_material(dtls->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
3044 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
3045 instance);
3046 return -1;
3047 }
3048
3049 /* Whether we are acting as a server or client determines where the keys/salts are */
3050 if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
3051 local_key = material;
3052 remote_key = local_key + SRTP_MASTER_KEY_LEN;
3053 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
3054 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
3055 } else {
3056 remote_key = material;
3057 local_key = remote_key + SRTP_MASTER_KEY_LEN;
3058 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
3059 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
3060 }
3061
3062 if (!(local_policy = res_srtp_policy->alloc())) {
3063 return -1;
3064 }
3065
3066 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
3067 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
3068 goto error;
3069 }
3070
3071 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
3072 ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3073 goto error;
3074 }
3075
3076 res_srtp_policy->set_ssrc(local_policy, ssrc, 0);
3077
3078 if (set_remote_policy) {
3079 if (!(remote_policy = res_srtp_policy->alloc())) {
3080 goto error;
3081 }
3082
3083 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
3084 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
3085 goto error;
3086 }
3087
3088 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
3089 ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3090 goto error;
3091 }
3092
3093 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
3094 }
3095
3096 if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy, rtcp)) {
3097 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
3098 goto error;
3099 }
3100
3101 res = 0;
3102
3103error:
3104 /* policy->destroy() called even on success to release local reference to these resources */
3105 res_srtp_policy->destroy(local_policy);
3106
3107 if (remote_policy) {
3108 res_srtp_policy->destroy(remote_policy);
3109 }
3110
3111 return res;
3112}
3113
3114static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp)
3115{
3116 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3117 int index;
3118
3119 ast_debug_dtls(3, "(%p) DTLS setup SRTP rtp=%p'\n", instance, rtp);
3120
3121 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
3122 if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
3123 X509 *certificate;
3124
3125 if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
3126 ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
3127 return -1;
3128 }
3129
3130 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
3131 if (rtp->remote_fingerprint[0]) {
3132 const EVP_MD *type;
3133 unsigned char fingerprint[EVP_MAX_MD_SIZE];
3134 unsigned int size;
3135
3136 if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
3137 type = EVP_sha1();
3138 } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
3139 type = EVP_sha256();
3140 } else {
3141 ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
3142 return -1;
3143 }
3144
3145 if (!X509_digest(certificate, type, fingerprint, &size) ||
3146 !size ||
3147 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
3148 X509_free(certificate);
3149 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
3150 instance);
3151 return -1;
3152 }
3153 }
3154
3155 X509_free(certificate);
3156 }
3157
3158 if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(instance), 1)) {
3159 ast_log(LOG_ERROR, "Failed to add local source '%p'\n", rtp);
3160 return -1;
3161 }
3162
3163 for (index = 0; index < AST_VECTOR_SIZE(&rtp->ssrc_mapping); ++index) {
3164 struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&rtp->ssrc_mapping, index);
3165
3166 if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(mapping->instance), 0)) {
3167 return -1;
3168 }
3169 }
3170
3171 if (rtp->rekey) {
3172 ao2_ref(instance, +1);
3173 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
3174 ao2_ref(instance, -1);
3175 return -1;
3176 }
3177 }
3178
3179 return 0;
3180}
3181#endif
3182
3183/*! \brief Helper function to compare an elem in a vector by value */
3184static int compare_by_value(int elem, int value)
3185{
3186 return elem - value;
3187}
3188
3189/*! \brief Helper function to find an elem in a vector by value */
3190static int find_by_value(int elem, int value)
3191{
3192 return elem == value;
3193}
3194
3195static int rtcp_mux(struct ast_rtp *rtp, const unsigned char *packet)
3196{
3197 uint8_t version;
3198 uint8_t pt;
3199 uint8_t m;
3200
3201 if (!rtp->rtcp || rtp->rtcp->type != AST_RTP_INSTANCE_RTCP_MUX) {
3202 return 0;
3203 }
3204
3205 version = (packet[0] & 0XC0) >> 6;
3206 if (version == 0) {
3207 /* version 0 indicates this is a STUN packet and shouldn't
3208 * be interpreted as a possible RTCP packet
3209 */
3210 return 0;
3211 }
3212
3213 /* The second octet of a packet will be one of the following:
3214 * For RTP: The marker bit (1 bit) and the RTP payload type (7 bits)
3215 * For RTCP: The payload type (8)
3216 *
3217 * RTP has a forbidden range of payload types (64-95) since these
3218 * will conflict with RTCP payload numbers if the marker bit is set.
3219 */
3220 m = packet[1] & 0x80;
3221 pt = packet[1] & 0x7F;
3222 if (m && pt >= 64 && pt <= 95) {
3223 return 1;
3224 }
3225 return 0;
3226}
3227
3228/*! \pre instance is locked */
3229static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
3230{
3231 int len;
3232 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3233#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3234 char *in = buf;
3235#endif
3236#ifdef HAVE_PJPROJECT
3237 struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
3238#endif
3239#ifdef TEST_FRAMEWORK
3240 struct ast_rtp_engine_test *test = ast_rtp_instance_get_test(instance);
3241#endif
3242
3243 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
3244 return len;
3245 }
3246
3247#ifdef TEST_FRAMEWORK
3248 if (test && test->packets_to_drop > 0) {
3249 test->packets_to_drop--;
3250 return 0;
3251 }
3252#endif
3253
3254#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3255 /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
3256 * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
3257 if ((*in >= 20) && (*in <= 63)) {
3258 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3259 int res = 0;
3260
3261 /* If no SSL session actually exists terminate things */
3262 if (!dtls->ssl) {
3263 ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
3264 instance);
3265 return -1;
3266 }
3267
3268 ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - Got SSL packet '%d'\n", instance, rtp, *in);
3269
3270 /*
3271 * If ICE is in use, we can prevent a possible DOS attack
3272 * by allowing DTLS protocol messages (client hello, etc)
3273 * only from sources that are in the active remote
3274 * candidates list.
3275 */
3276
3277#ifdef HAVE_PJPROJECT
3278 if (rtp->ice) {
3279 int pass_src_check = 0;
3280 int ix = 0;
3281
3282 /*
3283 * You'd think that this check would cause a "deadlock"
3284 * because ast_rtp_ice_start_media calls dtls_perform_handshake
3285 * before it sets ice_media_started = 1 so how can we do a
3286 * handshake if we're dropping packets before we send them
3287 * to openssl. Fortunately, dtls_perform_handshake just sets
3288 * up openssl to do the handshake and doesn't actually perform it
3289 * itself and the locking prevents __rtp_recvfrom from
3290 * running before the ice_media_started flag is set. So only
3291 * unexpected DTLS packets can get dropped here.
3292 */
3293 if (!rtp->ice_media_started) {
3294 ast_log(LOG_WARNING, "%s: DTLS packet from %s dropped. ICE not completed yet.\n",
3297 return 0;
3298 }
3299
3300 /*
3301 * If we got this far, then there have to be candidates.
3302 * We have to use pjproject's rcands because they may have
3303 * peer reflexive candidates that our ice_active_remote_candidates
3304 * won't.
3305 */
3306 for (ix = 0; ix < rtp->ice->real_ice->rcand_cnt; ix++) {
3307 pj_ice_sess_cand *rcand = &rtp->ice->real_ice->rcand[ix];
3308 if (ast_sockaddr_pj_sockaddr_cmp(sa, &rcand->addr) == 0) {
3309 pass_src_check = 1;
3310 break;
3311 }
3312 }
3313
3314 if (!pass_src_check) {
3315 ast_log(LOG_WARNING, "%s: DTLS packet from %s dropped. Source not in ICE active candidate list.\n",
3318 return 0;
3319 }
3320 }
3321#endif
3322
3323 /*
3324 * A race condition is prevented between dtls_perform_handshake()
3325 * and this function because both functions have to get the
3326 * instance lock before they can do anything. The
3327 * dtls_perform_handshake() function needs to start the timer
3328 * before we stop it below.
3329 */
3330
3331 /* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
3332 ao2_unlock(instance);
3333 dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
3334 ao2_lock(instance);
3335
3336 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
3337 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
3338 dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
3339 SSL_set_accept_state(dtls->ssl);
3340 }
3341
3342 BIO_write(dtls->read_bio, buf, len);
3343
3344 len = SSL_read(dtls->ssl, buf, len);
3345
3346 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
3347 unsigned long error = ERR_get_error();
3348 ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
3349 instance, ERR_reason_error_string(error));
3350 return -1;
3351 }
3352
3353 if (SSL_is_init_finished(dtls->ssl)) {
3354 /* Any further connections will be existing since this is now established */
3355 dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
3356 /* Use the keying material to set up key/salt information */
3357 if ((res = dtls_srtp_setup(rtp, instance, rtcp))) {
3358 return res;
3359 }
3360 /* Notify that dtls has been established */
3362
3363 ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - established'\n", instance, rtp);
3364 } else {
3365 /* Since we've sent additional traffic start the timeout timer for retransmission */
3366 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
3367 }
3368
3369 return res;
3370 }
3371#endif
3372
3373#ifdef HAVE_PJPROJECT
3374 if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
3375 /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
3376 * so it reflects the actual source and not the loopback
3377 */
3378 if (rtcp) {
3379 ast_sockaddr_copy(sa, &rtp->rtcp->them);
3380 } else {
3382 }
3383 } else if (rtp->ice) {
3384 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
3385 pj_sockaddr address;
3386 pj_status_t status;
3387 struct ice_wrap *ice;
3388
3389 pj_thread_register_check();
3390
3391 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
3392
3393 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3394 ice = rtp->ice;
3395 ao2_ref(ice, +1);
3396 ao2_unlock(instance);
3397 status = pj_ice_sess_on_rx_pkt(ice->real_ice,
3400 pj_sockaddr_get_len(&address));
3401 ao2_ref(ice, -1);
3402 ao2_lock(instance);
3403 if (status != PJ_SUCCESS) {
3404 char err_buf[100];
3405
3406 pj_strerror(status, err_buf, sizeof(err_buf));
3407 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
3408 (int)status, err_buf);
3409 return -1;
3410 }
3411 if (!rtp->passthrough) {
3412 /* If a unidirectional ICE negotiation occurs then lock on to the source of the
3413 * ICE traffic and use it as the target. This will occur if the remote side only
3414 * wants to receive media but never send to us.
3415 */
3416 if (!rtp->ice_active_remote_candidates && !rtp->ice_proposed_remote_candidates) {
3417 if (rtcp) {
3418 ast_sockaddr_copy(&rtp->rtcp->them, sa);
3419 } else {
3421 }
3422 }
3423 return 0;
3424 }
3425 rtp->passthrough = 0;
3426 }
3427#endif
3428
3429 return len;
3430}
3431
3432/*! \pre instance is locked */
3433static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3434{
3435 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
3436}
3437
3438/*! \pre instance is locked */
3439static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3440{
3441 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
3442}
3443
3444/*! \pre instance is locked */
3445static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp)
3446{
3447 int len = size;
3448 void *temp = buf;
3449 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3450 struct ast_rtp_instance *transport = rtp->bundled ? rtp->bundled : instance;
3451 struct ast_rtp *transport_rtp = ast_rtp_instance_get_data(transport);
3452 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(transport, rtcp);
3453 int res;
3454#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3455 char *out = buf;
3456 struct dtls_details *dtls = (!rtcp || rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_MUX) ? &rtp->dtls : &rtp->rtcp->dtls;
3457
3458 /* Don't send RTP if DTLS hasn't finished yet */
3459 if (dtls->ssl && ((*out < 20) || (*out > 63)) && dtls->connection == AST_RTP_DTLS_CONNECTION_NEW) {
3460 *via_ice = 0;
3461 return 0;
3462 }
3463#endif
3464
3465 *via_ice = 0;
3466
3467 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
3468 return -1;
3469 }
3470
3471#ifdef HAVE_PJPROJECT
3472 if (transport_rtp->ice) {
3474 pj_status_t status;
3475 struct ice_wrap *ice;
3476
3477 /* If RTCP is sharing the same socket then use the same component */
3478 if (rtcp && rtp->rtcp->s == rtp->s) {
3479 component = AST_RTP_ICE_COMPONENT_RTP;
3480 }
3481
3482 pj_thread_register_check();
3483
3484 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3485 ice = transport_rtp->ice;
3486 ao2_ref(ice, +1);
3487 if (instance == transport) {
3488 ao2_unlock(instance);
3489 }
3490 status = pj_ice_sess_send_data(ice->real_ice, component, temp, len);
3491 ao2_ref(ice, -1);
3492 if (instance == transport) {
3493 ao2_lock(instance);
3494 }
3495 if (status == PJ_SUCCESS) {
3496 *via_ice = 1;
3497 return len;
3498 }
3499 }
3500#endif
3501
3502 res = ast_sendto(rtcp ? transport_rtp->rtcp->s : transport_rtp->s, temp, len, flags, sa);
3503 if (res > 0) {
3504 ast_rtp_instance_set_last_tx(instance, time(NULL));
3505 }
3506
3507 return res;
3508}
3509
3510/*! \pre instance is locked */
3511static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3512{
3513 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
3514}
3515
3516/*! \pre instance is locked */
3517static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3518{
3519 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3520 int hdrlen = 12;
3521 int res;
3522
3523 if ((res = __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1)) > 0) {
3524 rtp->txcount++;
3525 rtp->txoctetcount += (res - hdrlen);
3526 }
3527
3528 return res;
3529}
3530
3531static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
3532{
3533 unsigned int interval;
3534 /*! \todo XXX Do a more reasonable calculation on this one
3535 * Look in RFC 3550 Section A.7 for an example*/
3536 interval = rtcpinterval;
3537 return interval;
3538}
3539
3540static void calc_mean_and_standard_deviation(double new_sample, double *mean, double *std_dev, unsigned int *count)
3541{
3542 double delta1;
3543 double delta2;
3544
3545 /* First convert the standard deviation back into a sum of squares. */
3546 double last_sum_of_squares = (*std_dev) * (*std_dev) * (*count ?: 1);
3547
3548 if (++(*count) == 0) {
3549 /* Avoid potential divide by zero on an overflow */
3550 *count = 1;
3551 }
3552
3553 /*
3554 * Below is an implementation of Welford's online algorithm [1] for calculating
3555 * mean and variance in a single pass.
3556 *
3557 * [1] https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
3558 */
3559
3560 delta1 = new_sample - *mean;
3561 *mean += (delta1 / *count);
3562 delta2 = new_sample - *mean;
3563
3564 /* Now calculate the new variance, and subsequent standard deviation */
3565 *std_dev = sqrt((last_sum_of_squares + (delta1 * delta2)) / *count);
3566}
3567
3568static int create_new_socket(const char *type, struct ast_sockaddr *bind_addr)
3569{
3570 int af, sock;
3571
3572 af = ast_sockaddr_is_ipv4(bind_addr) ? AF_INET :
3573 ast_sockaddr_is_ipv6(bind_addr) ? AF_INET6 : -1;
3574 sock = ast_socket_nonblock(af, SOCK_DGRAM, 0);
3575
3576 if (sock < 0) {
3577 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
3578 return sock;
3579 }
3580
3581#ifdef SO_NO_CHECK
3582 if (nochecksums) {
3583 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3584 }
3585#endif
3586
3587#ifdef HAVE_SOCK_IPV6_V6ONLY
3588 if (AF_INET6 == af && ast_sockaddr_is_any(bind_addr)) {
3589 /* ICE relies on dual-stack behavior. Ensure it is enabled. */
3590 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &(int){0}, sizeof(int)) != 0) {
3591 ast_log(LOG_WARNING, "setsockopt IPV6_V6ONLY=0 failed: %s\n", strerror(errno));
3592 }
3593 }
3594#endif
3595
3596 return sock;
3597}
3598
3599/*!
3600 * \internal
3601 * \brief Initializes sequence values and probation for learning mode.
3602 * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
3603 *
3604 * \param info The learning information to track
3605 * \param seq sequence number read from the rtp header to initialize the information with
3606 */
3607static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
3608{
3609 info->max_seq = seq;
3610 info->packets = learning_min_sequential;
3611 memset(&info->received, 0, sizeof(info->received));
3612}
3613
3614/*!
3615 * \internal
3616 * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
3617 * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
3618 *
3619 * \param info Structure tracking the learning progress of some address
3620 * \param seq sequence number read from the rtp header
3621 * \retval 0 if probation mode should exit for this address
3622 * \retval non-zero if probation mode should continue
3623 */
3624static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
3625{
3626 if (seq == (uint16_t) (info->max_seq + 1)) {
3627 /* packet is in sequence */
3628 info->packets--;
3629 } else {
3630 /* Sequence discontinuity; reset */
3631 info->packets = learning_min_sequential - 1;
3632 info->received = ast_tvnow();
3633 }
3634
3635 /* Only check time if strictrtp is set to yes. Otherwise, we only needed to check seqno */
3636 if (strictrtp == STRICT_RTP_YES) {
3637 switch (info->stream_type) {
3640 /*
3641 * Protect against packet floods by checking that we
3642 * received the packet sequence in at least the minimum
3643 * allowed time.
3644 */
3645 if (ast_tvzero(info->received)) {
3646 info->received = ast_tvnow();
3647 } else if (!info->packets
3648 && ast_tvdiff_ms(ast_tvnow(), info->received) < learning_min_duration) {
3649 /* Packet flood; reset */
3650 info->packets = learning_min_sequential - 1;
3651 info->received = ast_tvnow();
3652 }
3653 break;
3657 case AST_MEDIA_TYPE_END:
3658 break;
3659 }
3660 }
3661
3662 info->max_seq = seq;
3663
3664 return info->packets;
3665}
3666
3667/*!
3668 * \brief Start the strictrtp learning mode.
3669 *
3670 * \param rtp RTP session description
3671 */
3672static void rtp_learning_start(struct ast_rtp *rtp)
3673{
3675 memset(&rtp->rtp_source_learn.proposed_address, 0,
3676 sizeof(rtp->rtp_source_learn.proposed_address));
3678 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t) rtp->lastrxseqno);
3679}
3680
3681#ifdef HAVE_PJPROJECT
3682static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
3683
3684/*!
3685 * \internal
3686 * \brief Resets and ACL to empty state.
3687 */
3688static void rtp_unload_acl(ast_rwlock_t *lock, struct ast_acl_list **acl)
3689{
3693}
3694
3695/*!
3696 * \internal
3697 * \brief Checks an address against the ICE blacklist
3698 * \note If there is no ice_blacklist list, always returns 0
3699 *
3700 * \param address The address to consider
3701 * \retval 0 if address is not ICE blacklisted
3702 * \retval 1 if address is ICE blacklisted
3703 */
3704static int rtp_address_is_ice_blacklisted(const struct ast_sockaddr *address)
3705{
3706 int result = 0;
3707
3708 ast_rwlock_rdlock(&ice_acl_lock);
3710 ast_rwlock_unlock(&ice_acl_lock);
3711
3712 return result;
3713}
3714
3715/*!
3716 * \internal
3717 * \brief Checks an address against the STUN blacklist
3718 * \since 13.16.0
3719 *
3720 * \note If there is no stun_blacklist list, always returns 0
3721 *
3722 * \param addr The address to consider
3723 *
3724 * \retval 0 if address is not STUN blacklisted
3725 * \retval 1 if address is STUN blacklisted
3726 */
3727static int stun_address_is_blacklisted(const struct ast_sockaddr *addr)
3728{
3729 int result = 0;
3730
3731 ast_rwlock_rdlock(&stun_acl_lock);
3732 result |= ast_apply_acl_nolog(stun_acl, addr) == AST_SENSE_DENY;
3733 ast_rwlock_unlock(&stun_acl_lock);
3734
3735 return result;
3736}
3737
3738/*! \pre instance is locked */
3739static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
3740 int transport)
3741{
3742 unsigned int count = 0;
3743 struct ifaddrs *ifa, *ia;
3744 struct ast_sockaddr tmp;
3745 pj_sockaddr pjtmp;
3746 struct ast_ice_host_candidate *candidate;
3747 int af_inet_ok = 0, af_inet6_ok = 0;
3748 struct sockaddr_in stunaddr_copy;
3749
3750 if (ast_sockaddr_is_ipv4(addr)) {
3751 af_inet_ok = 1;
3752 } else if (ast_sockaddr_is_any(addr)) {
3753 af_inet_ok = af_inet6_ok = 1;
3754 } else {
3755 af_inet6_ok = 1;
3756 }
3757
3758 if (getifaddrs(&ifa) < 0) {
3759 /* If we can't get addresses, we can't load ICE candidates */
3760 ast_log(LOG_ERROR, "(%p) ICE Error obtaining list of local addresses: %s\n",
3761 instance, strerror(errno));
3762 } else {
3763 ast_debug_ice(2, "(%p) ICE add system candidates\n", instance);
3764 /* Iterate through the list of addresses obtained from the system,
3765 * until we've iterated through all of them, or accepted
3766 * PJ_ICE_MAX_CAND candidates */
3767 for (ia = ifa; ia && count < PJ_ICE_MAX_CAND; ia = ia->ifa_next) {
3768 /* Interface is either not UP or doesn't have an address assigned,
3769 * eg, a ppp that just completed LCP but no IPCP yet */
3770 if (!ia->ifa_addr || (ia->ifa_flags & IFF_UP) == 0) {
3771 continue;
3772 }
3773
3774 /* Filter out non-IPvX addresses, eg, link-layer */
3775 if (ia->ifa_addr->sa_family != AF_INET && ia->ifa_addr->sa_family != AF_INET6) {
3776 continue;
3777 }
3778
3779 ast_sockaddr_from_sockaddr(&tmp, ia->ifa_addr);
3780
3781 if (ia->ifa_addr->sa_family == AF_INET) {
3782 const struct sockaddr_in *sa_in = (struct sockaddr_in*)ia->ifa_addr;
3783 if (!af_inet_ok) {
3784 continue;
3785 }
3786
3787 /* Skip 127.0.0.0/8 (loopback) */
3788 /* Don't use IFF_LOOPBACK check since one could assign usable
3789 * publics to the loopback */
3790 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) {
3791 continue;
3792 }
3793
3794 /* Skip 0.0.0.0/8 based on RFC1122, and from pjproject */
3795 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == 0) {
3796 continue;
3797 }
3798 } else { /* ia->ifa_addr->sa_family == AF_INET6 */
3799 if (!af_inet6_ok) {
3800 continue;
3801 }
3802
3803 /* Filter ::1 */
3804 if (!ast_sockaddr_cmp_addr(&lo6, &tmp)) {
3805 continue;
3806 }
3807 }
3808
3809 /* Pull in the host candidates from [ice_host_candidates] */
3810 AST_RWLIST_RDLOCK(&host_candidates);
3811 AST_LIST_TRAVERSE(&host_candidates, candidate, next) {
3812 if (!ast_sockaddr_cmp(&candidate->local, &tmp)) {
3813 /* candidate->local matches actual assigned, so check if
3814 * advertised is blacklisted, if not, add it to the
3815 * advertised list. Not that it would make sense to remap
3816 * a local address to a blacklisted address, but honour it
3817 * anyway. */
3818 if (!rtp_address_is_ice_blacklisted(&candidate->advertised)) {
3819 ast_sockaddr_to_pj_sockaddr(&candidate->advertised, &pjtmp);
3820 pj_sockaddr_set_port(&pjtmp, port);
3821 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3822 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3823 pj_sockaddr_get_len(&pjtmp));
3824 ++count;
3825 }
3826
3827 if (!candidate->include_local) {
3828 /* We don't want to advertise the actual address */
3830 }
3831
3832 break;
3833 }
3834 }
3835 AST_RWLIST_UNLOCK(&host_candidates);
3836
3837 /* we had an entry in [ice_host_candidates] that matched, and
3838 * didn't have include_local_address set. Alternatively, adding
3839 * that match resulted in us going to PJ_ICE_MAX_CAND */
3840 if (ast_sockaddr_isnull(&tmp) || count == PJ_ICE_MAX_CAND) {
3841 continue;
3842 }
3843
3844 if (rtp_address_is_ice_blacklisted(&tmp)) {
3845 continue;
3846 }
3847
3848 ast_sockaddr_to_pj_sockaddr(&tmp, &pjtmp);
3849 pj_sockaddr_set_port(&pjtmp, port);
3850 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3851 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3852 pj_sockaddr_get_len(&pjtmp));
3853 ++count;
3854 }
3855 freeifaddrs(ifa);
3856 }
3857
3858 ast_rwlock_rdlock(&stunaddr_lock);
3859 memcpy(&stunaddr_copy, &stunaddr, sizeof(stunaddr));
3860 ast_rwlock_unlock(&stunaddr_lock);
3861
3862 /* If configured to use a STUN server to get our external mapped address do so */
3863 if (stunaddr_copy.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
3864 (ast_sockaddr_is_ipv4(addr) || ast_sockaddr_is_any(addr)) &&
3865 count < PJ_ICE_MAX_CAND) {
3866 struct sockaddr_in answer;
3867 int rsp;
3868
3870 "(%p) ICE request STUN %s %s candidate\n", instance,
3871 transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
3872 component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
3873
3874 /*
3875 * The instance should not be locked because we can block
3876 * waiting for a STUN respone.
3877 */
3878 ao2_unlock(instance);
3880 ? rtp->rtcp->s : rtp->s, &stunaddr_copy, NULL, &answer);
3881 ao2_lock(instance);
3882 if (!rsp) {
3883 struct ast_rtp_engine_ice_candidate *candidate;
3884 pj_sockaddr ext, base;
3885 pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
3886 int srflx = 1, baseset = 0;
3887 struct ao2_iterator i;
3888
3889 pj_sockaddr_init(pj_AF_INET(), &ext, &mapped, ntohs(answer.sin_port));
3890
3891 /*
3892 * If the returned address is the same as one of our host
3893 * candidates, don't send the srflx. At the same time,
3894 * we need to set the base address (raddr).
3895 */
3896 i = ao2_iterator_init(rtp->ice_local_candidates, 0);
3897 while (srflx && (candidate = ao2_iterator_next(&i))) {
3898 if (!baseset && ast_sockaddr_is_ipv4(&candidate->address)) {
3899 baseset = 1;
3900 ast_sockaddr_to_pj_sockaddr(&candidate->address, &base);
3901 }
3902
3903 if (!pj_sockaddr_cmp(&candidate->address, &ext)) {
3904 srflx = 0;
3905 }
3906
3907 ao2_ref(candidate, -1);
3908 }
3910
3911 if (srflx && baseset) {
3912 pj_sockaddr_set_port(&base, port);
3913 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3914 PJ_ICE_CAND_TYPE_SRFLX, 65535, &ext, &base, &base,
3915 pj_sockaddr_get_len(&ext));
3916 }
3917 }
3918 }
3919
3920 /* If configured to use a TURN relay create a session and allocate */
3921 if (pj_strlen(&turnaddr)) {
3922 ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
3923 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
3924 }
3925}
3926#endif
3927
3928/*!
3929 * \internal
3930 * \brief Calculates the elapsed time from issue of the first tx packet in an
3931 * rtp session and a specified time
3932 *
3933 * \param rtp pointer to the rtp struct with the transmitted rtp packet
3934 * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
3935 *
3936 * \return time elapsed in milliseconds
3937 */
3938static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
3939{
3940 struct timeval t;
3941 long ms;
3942
3943 if (ast_tvzero(rtp->txcore)) {
3944 rtp->txcore = ast_tvnow();
3945 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
3946 }
3947
3948 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
3949 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
3950 ms = 0;
3951 }
3952 rtp->txcore = t;
3953
3954 return (unsigned int) ms;
3955}
3956
3957#ifdef HAVE_PJPROJECT
3958/*!
3959 * \internal
3960 * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
3961 *
3962 * \param instance RTP instance for which the ICE session is being replaced
3963 * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
3964 * \param port port to use for adding RTP candidates to the ICE session
3965 * \param replace 0 when creating a new session, 1 when replacing a destroyed session
3966 *
3967 * \pre instance is locked
3968 *
3969 * \retval 0 on success
3970 * \retval -1 on failure
3971 */
3972static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
3973 int port, int replace)
3974{
3975 pj_stun_config stun_config;
3976 pj_str_t ufrag, passwd;
3977 pj_status_t status;
3978 struct ice_wrap *ice_old;
3979 struct ice_wrap *ice;
3980 pj_ice_sess *real_ice = NULL;
3981 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3982
3983 ao2_cleanup(rtp->ice_local_candidates);
3984 rtp->ice_local_candidates = NULL;
3985
3986 ast_debug_ice(2, "(%p) ICE create%s\n", instance, replace ? " and replace" : "");
3987
3988 ice = ao2_alloc_options(sizeof(*ice), ice_wrap_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
3989 if (!ice) {
3990 ast_rtp_ice_stop(instance);
3991 return -1;
3992 }
3993
3994 pj_thread_register_check();
3995
3996 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
3997 if (!stun_software_attribute) {
3998 stun_config.software_name = pj_str(NULL);
3999 }
4000
4001 ufrag = pj_str(rtp->local_ufrag);
4002 passwd = pj_str(rtp->local_passwd);
4003
4004 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
4005 ao2_unlock(instance);
4006 /* Create an ICE session for ICE negotiation */
4007 status = pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
4008 rtp->ice_num_components, &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &real_ice);
4009 ao2_lock(instance);
4010 if (status == PJ_SUCCESS) {
4011 /* Safely complete linking the ICE session into the instance */
4012 real_ice->user_data = instance;
4013 ice->real_ice = real_ice;
4014 ice_old = rtp->ice;
4015 rtp->ice = ice;
4016 if (ice_old) {
4017 ao2_unlock(instance);
4018 ao2_ref(ice_old, -1);
4019 ao2_lock(instance);
4020 }
4021
4022 /* Add all of the available candidates to the ICE session */
4023 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
4025
4026 /* Only add the RTCP candidates to ICE when replacing the session and if
4027 * the ICE session contains more than just an RTP component. New sessions
4028 * handle this in a separate part of the setup phase */
4029 if (replace && rtp->rtcp && rtp->ice_num_components > 1) {
4030 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
4033 }
4034
4035 return 0;
4036 }
4037
4038 /*
4039 * It is safe to unref this while instance is locked here.
4040 * It was not initialized with a real_ice pointer.
4041 */
4042 ao2_ref(ice, -1);
4043
4044 ast_rtp_ice_stop(instance);
4045 return -1;
4046
4047}
4048#endif
4049
4050static int rtp_allocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
4051{
4052 int x, startplace, i, maxloops;
4053
4055
4056 /* Create a new socket for us to listen on and use */
4057 if ((rtp->s = create_new_socket("RTP", &rtp->bind_address)) < 0) {
4058 ast_log(LOG_WARNING, "Failed to create a new socket for RTP instance '%p'\n", instance);
4059 return -1;
4060 }
4061
4062 /* Now actually find a free RTP port to use */
4063 x = (ast_random() % (rtpend - rtpstart)) + rtpstart;
4064 x = x & ~1;
4065 startplace = x;
4066
4067 /* Protection against infinite loops in the case there is a potential case where the loop is not broken such as an odd
4068 start port sneaking in (even though this condition is checked at load.) */
4069 maxloops = rtpend - rtpstart;
4070 for (i = 0; i <= maxloops; i++) {
4072 /* Try to bind, this will tell us whether the port is available or not */
4073 if (!ast_bind(rtp->s, &rtp->bind_address)) {
4074 ast_debug_rtp(1, "(%p) RTP allocated port %d\n", instance, x);
4076 ast_test_suite_event_notify("RTP_PORT_ALLOCATED", "Port: %d", x);
4077 break;
4078 }
4079
4080 x += 2;
4081 if (x > rtpend) {
4082 x = (rtpstart + 1) & ~1;
4083 }
4084
4085 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
4086 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
4087 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
4088 close(rtp->s);
4089 rtp->s = -1;
4090 return -1;
4091 }
4092 }
4093
4094#ifdef HAVE_PJPROJECT
4095 /* Initialize synchronization aspects */
4096 ast_cond_init(&rtp->cond, NULL);
4097
4098 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
4099 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
4100
4101 /* Create an ICE session for ICE negotiation */
4102 if (icesupport) {
4103 rtp->ice_num_components = 2;
4104 ast_debug_ice(2, "(%p) ICE creating session %s (%d)\n", instance,
4106 if (ice_create(instance, &rtp->bind_address, x, 0)) {
4107 ast_log(LOG_NOTICE, "(%p) ICE failed to create session\n", instance);
4108 } else {
4109 rtp->ice_port = x;
4110 ast_sockaddr_copy(&rtp->ice_original_rtp_addr, &rtp->bind_address);
4111 }
4112 }
4113#endif
4114
4115#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4116 rtp->rekeyid = -1;
4117 rtp->dtls.timeout_timer = -1;
4118#endif
4119
4120 return 0;
4121}
4122
4123static void rtp_deallocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
4124{
4125 int saved_rtp_s = rtp->s;
4126#ifdef HAVE_PJPROJECT
4127 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
4128 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
4129#endif
4130
4131#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4132 ast_rtp_dtls_stop(instance);
4133#endif
4134
4135 /* Close our own socket so we no longer get packets */
4136 if (rtp->s > -1) {
4137 close(rtp->s);
4138 rtp->s = -1;
4139 }
4140
4141 /* Destroy RTCP if it was being used */
4142 if (rtp->rtcp && rtp->rtcp->s > -1) {
4143 if (saved_rtp_s != rtp->rtcp->s) {
4144 close(rtp->rtcp->s);
4145 }
4146 rtp->rtcp->s = -1;
4147 }
4148
4149#ifdef HAVE_PJPROJECT
4150 pj_thread_register_check();
4151
4152 /*
4153 * The instance lock is already held.
4154 *
4155 * Destroy the RTP TURN relay if being used
4156 */
4157 if (rtp->turn_rtp) {
4158 rtp->turn_state = PJ_TURN_STATE_NULL;
4159
4160 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
4161 ao2_unlock(instance);
4162 pj_turn_sock_destroy(rtp->turn_rtp);
4163 ao2_lock(instance);
4164 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4165 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
4166 }
4167 rtp->turn_rtp = NULL;
4168 }
4169
4170 /* Destroy the RTCP TURN relay if being used */
4171 if (rtp->turn_rtcp) {
4172 rtp->turn_state = PJ_TURN_STATE_NULL;
4173
4174 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
4175 ao2_unlock(instance);
4176 pj_turn_sock_destroy(rtp->turn_rtcp);
4177 ao2_lock(instance);
4178 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4179 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
4180 }
4181 rtp->turn_rtcp = NULL;
4182 }
4183
4184 ast_debug_ice(2, "(%p) ICE RTP transport deallocating\n", instance);
4185 /* Destroy any ICE session */
4186 ast_rtp_ice_stop(instance);
4187
4188 /* Destroy any candidates */
4189 if (rtp->ice_local_candidates) {
4190 ao2_ref(rtp->ice_local_candidates, -1);
4191 rtp->ice_local_candidates = NULL;
4192 }
4193
4194 if (rtp->ice_active_remote_candidates) {
4195 ao2_ref(rtp->ice_active_remote_candidates, -1);
4196 rtp->ice_active_remote_candidates = NULL;
4197 }
4198
4199 if (rtp->ice_proposed_remote_candidates) {
4200 ao2_ref(rtp->ice_proposed_remote_candidates, -1);
4201 rtp->ice_proposed_remote_candidates = NULL;
4202 }
4203
4204 if (rtp->ioqueue) {
4205 /*
4206 * We cannot hold the instance lock because we could wait
4207 * for the ioqueue thread to die and we might deadlock as
4208 * a result.
4209 */
4210 ao2_unlock(instance);
4211 rtp_ioqueue_thread_remove(rtp->ioqueue);
4212 ao2_lock(instance);
4213 rtp->ioqueue = NULL;
4214 }
4215#endif
4216}
4217
4218/*! \pre instance is locked */
4219static int ast_rtp_new(struct ast_rtp_instance *instance,
4220 struct ast_sched_context *sched, struct ast_sockaddr *addr,
4221 void *data)
4222{
4223 struct ast_rtp *rtp = NULL;
4224
4225 /* Create a new RTP structure to hold all of our data */
4226 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
4227 return -1;
4228 }
4229 rtp->owner = instance;
4230 /* Set default parameters on the newly created RTP structure */
4231 rtp->ssrc = ast_random();
4232 ast_uuid_generate_str(rtp->cname, sizeof(rtp->cname));
4233 rtp->seqno = ast_random() & 0xffff;
4234 rtp->expectedrxseqno = -1;
4235 rtp->expectedseqno = -1;
4236 rtp->rxstart = -1;
4237 rtp->sched = sched;
4238 ast_sockaddr_copy(&rtp->bind_address, addr);
4239 /* Transport creation operations can grab the RTP data from the instance, so set it */
4240 ast_rtp_instance_set_data(instance, rtp);
4241
4242 if (rtp_allocate_transport(instance, rtp)) {
4243 return -1;
4244 }
4245
4246 if (AST_VECTOR_INIT(&rtp->ssrc_mapping, 1)) {
4247 return -1;
4248 }
4249
4251 return -1;
4252 }
4253 rtp->transport_wide_cc.schedid = -1;
4254
4258 rtp->stream_num = -1;
4259
4260 return 0;
4261}
4262
4263/*!
4264 * \brief SSRC mapping comparator for AST_VECTOR_REMOVE_CMP_UNORDERED()
4265 *
4266 * \param elem Element to compare against
4267 * \param value Value to compare with the vector element.
4268 *
4269 * \retval 0 if element does not match.
4270 * \retval Non-zero if element matches.
4271 */
4272#define SSRC_MAPPING_ELEM_CMP(elem, value) ((elem).instance == (value))
4273
4274/*! \pre instance is locked */
4275static int ast_rtp_destroy(struct ast_rtp_instance *instance)
4276{
4277 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4278
4279 if (rtp->bundled) {
4280 struct ast_rtp *bundled_rtp;
4281
4282 /* We can't hold our instance lock while removing ourselves from the parent */
4283 ao2_unlock(instance);
4284
4285 ao2_lock(rtp->bundled);
4286 bundled_rtp = ast_rtp_instance_get_data(rtp->bundled);
4288 ao2_unlock(rtp->bundled);
4289
4290 ao2_lock(instance);
4291 ao2_ref(rtp->bundled, -1);
4292 }
4293
4294 rtp_deallocate_transport(instance, rtp);
4295
4296 /* Destroy the smoother that was smoothing out audio if present */
4297 if (rtp->smoother) {
4299 }
4300
4301 /* Destroy RTCP if it was being used */
4302 if (rtp->rtcp) {
4303 /*
4304 * It is not possible for there to be an active RTCP scheduler
4305 * entry at this point since it holds a reference to the
4306 * RTP instance while it's active.
4307 */
4309 ast_free(rtp->rtcp);
4310 }
4311
4312 /* Destroy RED if it was being used */
4313 if (rtp->red) {
4314 ao2_unlock(instance);
4315 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
4316 ao2_lock(instance);
4317 ast_free(rtp->red);
4318 rtp->red = NULL;
4319 }
4320
4321 /* Destroy the send buffer if it was being used */
4322 if (rtp->send_buffer) {
4324 }
4325
4326 /* Destroy the recv buffer if it was being used */
4327 if (rtp->recv_buffer) {
4329 }
4330
4332
4338
4339 /* Finally destroy ourselves */
4340 rtp->owner = NULL;
4341 ast_free(rtp);
4342
4343 return 0;
4344}
4345
4346/*! \pre instance is locked */
4347static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
4348{
4349 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4350 rtp->dtmfmode = dtmf_mode;
4351 return 0;
4352}
4353
4354/*! \pre instance is locked */
4356{
4357 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4358 return rtp->dtmfmode;
4359}
4360
4361/*! \pre instance is locked */
4362static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
4363{
4364 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4365 struct ast_sockaddr remote_address = { {0,} };
4366 int hdrlen = 12, res = 0, i = 0, payload = -1, sample_rate = -1;
4367 char data[256];
4368 unsigned int *rtpheader = (unsigned int*)data;
4369 RAII_VAR(struct ast_format *, payload_format, NULL, ao2_cleanup);
4370
4371 ast_rtp_instance_get_remote_address(instance, &remote_address);
4372
4373 /* If we have no remote address information bail out now */
4374 if (ast_sockaddr_isnull(&remote_address)) {
4375 return -1;
4376 }
4377
4378 /* Convert given digit into what we want to transmit */
4379 if ((digit <= '9') && (digit >= '0')) {
4380 digit -= '0';
4381 } else if (digit == '*') {
4382 digit = 10;
4383 } else if (digit == '#') {
4384 digit = 11;
4385 } else if ((digit >= 'A') && (digit <= 'D')) {
4386 digit = digit - 'A' + 12;
4387 } else if ((digit >= 'a') && (digit <= 'd')) {
4388 digit = digit - 'a' + 12;
4389 } else {
4390 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4391 return -1;
4392 }
4393
4394 if (rtp->lasttxformat == ast_format_none) {
4395 /* No audio frames have been written yet so we have to lookup both the preferred payload type and bitrate. */
4397 if (payload_format) {
4398 /* If we have a preferred type, use that. Otherwise default to 8K. */
4399 sample_rate = ast_format_get_sample_rate(payload_format);
4400 }
4401 } else {
4402 sample_rate = ast_format_get_sample_rate(rtp->lasttxformat);
4403 }
4404
4405 if (sample_rate != -1) {
4407 }
4408
4409 if (payload == -1 ||
4412 /* Fall back to the preferred DTMF payload type and sample rate as either we couldn't find an audio codec to try and match
4413 sample rates with or we could, but a telephone-event matching that audio codec's sample rate was not included in the
4414 sdp negotiated by the far end. */
4417 }
4418
4419 /* The sdp negotiation has not yeilded a usable RFC 2833/4733 format. Try a default-rate one as a last resort. */
4420 if (payload == -1 || sample_rate == -1) {
4421 sample_rate = DEFAULT_DTMF_SAMPLE_RATE_MS;
4423 }
4424 /* Even trying a default payload has failed. We are trying to send a digit outside of what was negotiated for. */
4425 if (payload == -1) {
4426 return -1;
4427 }
4428
4429 ast_test_suite_event_notify("DTMF_BEGIN", "Digit: %d\r\nPayload: %d\r\nRate: %d\r\n", digit, payload, sample_rate);
4430 ast_debug(1, "Sending digit '%d' at rate %d with payload %d\n", digit, sample_rate, payload);
4431
4432 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4433 rtp->send_duration = 160;
4434 rtp->dtmf_samplerate_ms = (sample_rate / 1000);
4435 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4436 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
4437
4438 /* Create the actual packet that we will be sending */
4439 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
4440 rtpheader[1] = htonl(rtp->lastdigitts);
4441 rtpheader[2] = htonl(rtp->ssrc);
4442
4443 /* Actually send the packet */
4444 for (i = 0; i < 2; i++) {
4445 int ice;
4446
4447 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4448 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4449 if (res < 0) {
4450 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4451 ast_sockaddr_stringify(&remote_address),
4452 strerror(errno));
4453 }
4454 if (rtp_debug_test_addr(&remote_address)) {
4455 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4456 ast_sockaddr_stringify(&remote_address),
4457 ice ? " (via ICE)" : "",
4458 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4459 }
4460 rtp->seqno++;
4461 rtp->send_duration += 160;
4462 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
4463 }
4464
4465 /* Record that we are in the process of sending a digit and information needed to continue doing so */
4466 rtp->sending_digit = 1;
4467 rtp->send_digit = digit;
4468 rtp->send_payload = payload;
4469
4470 return 0;
4471}
4472
4473/*! \pre instance is locked */
4475{
4476 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4477 struct ast_sockaddr remote_address = { {0,} };
4478 int hdrlen = 12, res = 0;
4479 char data[256];
4480 unsigned int *rtpheader = (unsigned int*)data;
4481 int ice;
4482
4483 ast_rtp_instance_get_remote_address(instance, &remote_address);
4484
4485 /* Make sure we know where the other side is so we can send them the packet */
4486 if (ast_sockaddr_isnull(&remote_address)) {
4487 return -1;
4488 }
4489
4490 /* Actually create the packet we will be sending */
4491 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4492 rtpheader[1] = htonl(rtp->lastdigitts);
4493 rtpheader[2] = htonl(rtp->ssrc);
4494 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
4495
4496 /* Boom, send it on out */
4497 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4498 if (res < 0) {
4499 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4500 ast_sockaddr_stringify(&remote_address),
4501 strerror(errno));
4502 }
4503
4504 if (rtp_debug_test_addr(&remote_address)) {
4505 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4506 ast_sockaddr_stringify(&remote_address),
4507 ice ? " (via ICE)" : "",
4508 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4509 }
4510
4511 /* And now we increment some values for the next time we swing by */
4512 rtp->seqno++;
4513 rtp->send_duration += 160;
4514 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4515
4516 return 0;
4517}
4518
4519/*! \pre instance is locked */
4520static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
4521{
4522 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4523 struct ast_sockaddr remote_address = { {0,} };
4524 int hdrlen = 12, res = -1, i = 0;
4525 char data[256];
4526 unsigned int *rtpheader = (unsigned int*)data;
4527 unsigned int measured_samples;
4528
4529 ast_rtp_instance_get_remote_address(instance, &remote_address);
4530
4531 /* Make sure we know where the remote side is so we can send them the packet we construct */
4532 if (ast_sockaddr_isnull(&remote_address)) {
4533 goto cleanup;
4534 }
4535
4536 /* Convert the given digit to the one we are going to send */
4537 if ((digit <= '9') && (digit >= '0')) {
4538 digit -= '0';
4539 } else if (digit == '*') {
4540 digit = 10;
4541 } else if (digit == '#') {
4542 digit = 11;
4543 } else if ((digit >= 'A') && (digit <= 'D')) {
4544 digit = digit - 'A' + 12;
4545 } else if ((digit >= 'a') && (digit <= 'd')) {
4546 digit = digit - 'a' + 12;
4547 } else {
4548 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4549 goto cleanup;
4550 }
4551
4552 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4553
4554 if (duration > 0 && (measured_samples = duration * ast_rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
4555 ast_debug_rtp(2, "(%p) RTP adjusting final end duration from %d to %u\n",
4556 instance, rtp->send_duration, measured_samples);
4557 rtp->send_duration = measured_samples;
4558 }
4559
4560 /* Construct the packet we are going to send */
4561 rtpheader[1] = htonl(rtp->lastdigitts);
4562 rtpheader[2] = htonl(rtp->ssrc);
4563 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4564 rtpheader[3] |= htonl((1 << 23));
4565
4566 /* Send it 3 times, that's the magical number */
4567 for (i = 0; i < 3; i++) {
4568 int ice;
4569
4570 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4571
4572 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4573
4574 if (res < 0) {
4575 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4576 ast_sockaddr_stringify(&remote_address),
4577 strerror(errno));
4578 }
4579
4580 if (rtp_debug_test_addr(&remote_address)) {
4581 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4582 ast_sockaddr_stringify(&remote_address),
4583 ice ? " (via ICE)" : "",
4584 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4585 }
4586
4587 rtp->seqno++;
4588 }
4589 res = 0;
4590
4591 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
4592 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4593
4594 /* Reset the smoother as the delivery time stored in it is now out of date */
4595 if (rtp->smoother) {
4597 rtp->smoother = NULL;
4598 }
4599cleanup:
4600 rtp->sending_digit = 0;
4601 rtp->send_digit = 0;
4602
4603 /* Re-Learn expected seqno */
4604 rtp->expectedseqno = -1;
4605
4606 return res;
4607}
4608
4609/*! \pre instance is locked */
4610static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
4611{
4612 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
4613}
4614
4615/*! \pre instance is locked */
4616static void ast_rtp_update_source(struct ast_rtp_instance *instance)
4617{
4618 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4619
4620 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4622 ast_debug_rtp(3, "(%p) RTP setting the marker bit due to a source update\n", instance);
4623
4624 return;
4625}
4626
4627/*! \pre instance is locked */
4628static void ast_rtp_change_source(struct ast_rtp_instance *instance)
4629{
4630 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4631 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, 0);
4632 struct ast_srtp *rtcp_srtp = ast_rtp_instance_get_srtp(instance, 1);
4633 unsigned int ssrc = ast_random();
4634
4635 if (rtp->lastts) {
4636 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4638 }
4639
4640 ast_debug_rtp(3, "(%p) RTP changing ssrc from %u to %u due to a source change\n",
4641 instance, rtp->ssrc, ssrc);
4642
4643 if (srtp) {
4644 ast_debug_rtp(3, "(%p) RTP changing ssrc for SRTP from %u to %u\n",
4645 instance, rtp->ssrc, ssrc);
4646 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
4647 if (rtcp_srtp != srtp) {
4648 res_srtp->change_source(rtcp_srtp, rtp->ssrc, ssrc);
4649 }
4650 }
4651
4652 rtp->ssrc = ssrc;
4653
4654 /* Since the source is changing, we don't know what sequence number to expect next */
4655 rtp->expectedrxseqno = -1;
4656
4657 return;
4658}
4659
4660static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
4661{
4662 unsigned int sec, usec, frac;
4663 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
4664 usec = tv.tv_usec;
4665 /*
4666 * Convert usec to 0.32 bit fixed point without overflow.
4667 *
4668 * = usec * 2^32 / 10^6
4669 * = usec * 2^32 / (2^6 * 5^6)
4670 * = usec * 2^26 / 5^6
4671 *
4672 * The usec value needs 20 bits to represent 999999 usec. So
4673 * splitting the 2^26 to get the most precision using 32 bit
4674 * values gives:
4675 *
4676 * = ((usec * 2^12) / 5^6) * 2^14
4677 *
4678 * Splitting the division into two stages preserves all the
4679 * available significant bits of usec over doing the division
4680 * all at once.
4681 *
4682 * = ((((usec * 2^12) / 5^3) * 2^7) / 5^3) * 2^7
4683 */
4684 frac = ((((usec << 12) / 125) << 7) / 125) << 7;
4685 *msw = sec;
4686 *lsw = frac;
4687}
4688
4689static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
4690{
4691 tv->tv_sec = msw - 2208988800u;
4692 /* Reverse the sequence in timeval2ntp() */
4693 tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
4694}
4695
4697 unsigned int *lost_packets,
4698 int *fraction_lost)
4699{
4700 unsigned int extended_seq_no;
4701 unsigned int expected_packets;
4702 unsigned int expected_interval;
4703 unsigned int received_interval;
4704 int lost_interval;
4705
4706 /* Compute statistics */
4707 extended_seq_no = rtp->cycles + rtp->lastrxseqno;
4708 expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
4709 if (rtp->rxcount > expected_packets) {
4710 expected_packets += rtp->rxcount - expected_packets;
4711 }
4712 *lost_packets = expected_packets - rtp->rxcount;
4713 expected_interval = expected_packets - rtp->rtcp->expected_prior;
4714 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
4715 if (received_interval > expected_interval) {
4716 /* If we receive some late packets it is possible for the packets
4717 * we received in this interval to exceed the number we expected.
4718 * We update the expected so that the packet loss calculations
4719 * show that no packets are lost.
4720 */
4721 expected_interval = received_interval;
4722 }
4723 lost_interval = expected_interval - received_interval;
4724 if (expected_interval == 0 || lost_interval <= 0) {
4725 *fraction_lost = 0;
4726 } else {
4727 *fraction_lost = (lost_interval << 8) / expected_interval;
4728 }
4729
4730 /* Update RTCP statistics */
4731 rtp->rtcp->received_prior = rtp->rxcount;
4732 rtp->rtcp->expected_prior = expected_packets;
4733
4734 /*
4735 * While rxlost represents the number of packets lost since the last report was sent, for
4736 * the calculations below it should be thought of as a single sample. Thus min/max are the
4737 * lowest/highest sample value seen, and the mean is the average number of packets lost
4738 * between each report. As such rxlost_count only needs to be incremented per report.
4739 */
4740 if (lost_interval <= 0) {
4741 rtp->rtcp->rxlost = 0;
4742 } else {
4743 rtp->rtcp->rxlost = lost_interval;
4744 }
4745 if (rtp->rtcp->rxlost_count == 0) {
4746 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4747 }
4748 if (lost_interval && lost_interval < rtp->rtcp->minrxlost) {
4749 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4750 }
4751 if (lost_interval > rtp->rtcp->maxrxlost) {
4752 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
4753 }
4754
4755 calc_mean_and_standard_deviation(rtp->rtcp->rxlost, &rtp->rtcp->normdev_rxlost,
4756 &rtp->rtcp->stdev_rxlost, &rtp->rtcp->rxlost_count);
4757}
4758
4759static int ast_rtcp_generate_report(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4760 struct ast_rtp_rtcp_report *rtcp_report, int *sr)
4761{
4762 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4763 int len = 0;
4764 struct timeval now;
4765 unsigned int now_lsw;
4766 unsigned int now_msw;
4767 unsigned int lost_packets;
4768 int fraction_lost;
4769 struct timeval dlsr = { 0, };
4770 struct ast_rtp_rtcp_report_block *report_block = NULL;
4771
4772 if (!rtp || !rtp->rtcp) {
4773 return 0;
4774 }
4775
4776 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
4777 /* RTCP was stopped. */
4778 return 0;
4779 }
4780
4781 if (!rtcp_report) {
4782 return 1;
4783 }
4784
4785 *sr = rtp->txcount > rtp->rtcp->lastsrtxcount ? 1 : 0;
4786
4787 /* Compute statistics */
4788 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
4789 /*
4790 * update_local_mes_stats must be called AFTER
4791 * calculate_lost_packet_statistics
4792 */
4794
4795 gettimeofday(&now, NULL);
4796 rtcp_report->reception_report_count = rtp->themssrc_valid ? 1 : 0;
4797 rtcp_report->ssrc = rtp->ssrc;
4798 rtcp_report->type = *sr ? RTCP_PT_SR : RTCP_PT_RR;
4799 if (*sr) {
4800 rtcp_report->sender_information.ntp_timestamp = now;
4801 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
4802 rtcp_report->sender_information.packet_count = rtp->txcount;
4803 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
4804 }
4805
4806 if (rtp->themssrc_valid) {
4807 report_block = ast_calloc(1, sizeof(*report_block));
4808 if (!report_block) {
4809 return 1;
4810 }
4811
4812 rtcp_report->report_block[0] = report_block;
4813 report_block->source_ssrc = rtp->themssrc;
4814 report_block->lost_count.fraction = (fraction_lost & 0xff);
4815 report_block->lost_count.packets = (lost_packets & 0xffffff);
4816 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
4817 report_block->ia_jitter = (unsigned int)rtp->rxjitter_samples;
4818 report_block->lsr = rtp->rtcp->themrxlsr;
4819 /* If we haven't received an SR report, DLSR should be 0 */
4820 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
4821 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
4822 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
4823 }
4824 }
4825 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
4826 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc)); /* Our SSRC */
4827 len += 8;
4828 if (*sr) {
4829 put_unaligned_uint32(rtcpheader + len, htonl(now_msw)); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970 */
4830 put_unaligned_uint32(rtcpheader + len + 4, htonl(now_lsw)); /* now, LSW */
4831 put_unaligned_uint32(rtcpheader + len + 8, htonl(rtcp_report->sender_information.rtp_timestamp));
4832 put_unaligned_uint32(rtcpheader + len + 12, htonl(rtcp_report->sender_information.packet_count));
4833 put_unaligned_uint32(rtcpheader + len + 16, htonl(rtcp_report->sender_information.octet_count));
4834 len += 20;
4835 }
4836 if (report_block) {
4837 put_unaligned_uint32(rtcpheader + len, htonl(report_block->source_ssrc)); /* Their SSRC */
4838 put_unaligned_uint32(rtcpheader + len + 4, htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets));
4839 put_unaligned_uint32(rtcpheader + len + 8, htonl(report_block->highest_seq_no));
4840 put_unaligned_uint32(rtcpheader + len + 12, htonl(report_block->ia_jitter));
4841 put_unaligned_uint32(rtcpheader + len + 16, htonl(report_block->lsr));
4842 put_unaligned_uint32(rtcpheader + len + 20, htonl(report_block->dlsr));
4843 len += 24;
4844 }
4845
4846 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
4847 | ((*sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1)));
4848
4849 return len;
4850}
4851
4853 struct ast_rtp_rtcp_report *rtcp_report, struct ast_sockaddr remote_address, int ice, int sr)
4854{
4855 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4856 struct ast_rtp_rtcp_report_block *report_block = NULL;
4857 RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
4858
4859 if (!rtp || !rtp->rtcp) {
4860 return 0;
4861 }
4862
4863 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4864 return 0;
4865 }
4866
4867 if (!rtcp_report) {
4868 return -1;
4869 }
4870
4871 report_block = rtcp_report->report_block[0];
4872
4873 if (sr) {
4874 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
4875 rtp->rtcp->sr_count++;
4876 rtp->rtcp->lastsrtxcount = rtp->txcount;
4877 } else {
4878 rtp->rtcp->rr_count++;
4879 }
4880
4881 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
4882 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
4883 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
4884 ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
4885 if (sr) {
4886 ast_verbose(" Sent(NTP): %u.%06u\n",
4887 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
4888 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
4889 ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
4890 ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
4891 ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
4892 }
4893 if (report_block) {
4894 int rate = ast_rtp_get_rate(rtp->f.subclass.format);
4895 ast_verbose(" Report block:\n");
4896 ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
4897 ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
4898 ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
4899 ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
4900 ast_verbose(" IA jitter (samp): %u\n", report_block->ia_jitter);
4901 ast_verbose(" IA jitter (secs): %.6f\n", ast_samp2sec(report_block->ia_jitter, rate));
4902 ast_verbose(" Their last SR: %u\n", report_block->lsr);
4903 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
4904 }
4905 }
4906
4907 message_blob = ast_json_pack("{s: s, s: s, s: f}",
4908 "to", ast_sockaddr_stringify(&remote_address),
4909 "from", rtp->rtcp->local_addr_str,
4910 "mes", rtp->rxmes);
4911
4913 rtcp_report, message_blob);
4914
4915 return 1;
4916}
4917
4918static int ast_rtcp_generate_sdes(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4919 struct ast_rtp_rtcp_report *rtcp_report)
4920{
4921 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4922 int len = 0;
4923 uint16_t sdes_packet_len_bytes;
4924 uint16_t sdes_packet_len_rounded;
4925
4926 if (!rtp || !rtp->rtcp) {
4927 return 0;
4928 }
4929
4930 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4931 return 0;
4932 }
4933
4934 if (!rtcp_report) {
4935 return -1;
4936 }
4937
4938 sdes_packet_len_bytes =
4939 4 + /* RTCP Header */
4940 4 + /* SSRC */
4941 1 + /* Type (CNAME) */
4942 1 + /* Text Length */
4943 AST_UUID_STR_LEN /* Text and NULL terminator */
4944 ;
4945
4946 /* Round to 32 bit boundary */
4947 sdes_packet_len_rounded = (sdes_packet_len_bytes + 3) & ~0x3;
4948
4949 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | ((sdes_packet_len_rounded / 4) - 1)));
4950 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc));
4951 rtcpheader[8] = 0x01; /* CNAME */
4952 rtcpheader[9] = AST_UUID_STR_LEN - 1; /* Number of bytes of text */
4953 memcpy(rtcpheader + 10, rtp->cname, AST_UUID_STR_LEN);
4954 len += 10 + AST_UUID_STR_LEN;
4955
4956 /* Padding - Note that we don't set the padded bit on the packet. From
4957 * RFC 3550 Section 6.5:
4958 *
4959 * No length octet follows the null item type octet, but additional null
4960 * octets MUST be included if needd to pad until the next 32-bit
4961 * boundary. Note that this padding is separate from that indicated by
4962 * the P bit in the RTCP header.
4963 *
4964 * These bytes will already be zeroed out during array initialization.
4965 */
4966 len += (sdes_packet_len_rounded - sdes_packet_len_bytes);
4967
4968 return len;
4969}
4970
4971/* Lock instance before calling this if it isn't already
4972 *
4973 * If successful, the overall packet length is returned
4974 * If not, then 0 is returned
4975 */
4976static int ast_rtcp_generate_compound_prefix(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4977 struct ast_rtp_rtcp_report *report, int *sr)
4978{
4979 int packet_len = 0;
4980 int res;
4981
4982 /* Every RTCP packet needs to be sent out with a SR/RR and SDES prefixing it.
4983 * At the end of this function, rtcpheader should contain both of those packets,
4984 * and will return the length of the overall packet. This can be used to determine
4985 * where further packets can be inserted in the compound packet.
4986 */
4987 res = ast_rtcp_generate_report(instance, rtcpheader, report, sr);
4988
4989 if (res == 0 || res == 1) {
4990 ast_debug_rtcp(1, "(%p) RTCP failed to generate %s report!\n", instance, sr ? "SR" : "RR");
4991 return 0;
4992 }
4993
4994 packet_len += res;
4995
4996 res = ast_rtcp_generate_sdes(instance, rtcpheader + packet_len, report);
4997
4998 if (res == 0 || res == 1) {
4999 ast_debug_rtcp(1, "(%p) RTCP failed to generate SDES!\n", instance);
5000 return 0;
5001 }
5002
5003 return packet_len + res;
5004}
5005
5006static int ast_rtcp_generate_nack(struct ast_rtp_instance *instance, unsigned char *rtcpheader)
5007{
5008 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5009 int packet_len;
5010 int blp_index = -1;
5011 int current_seqno;
5012 unsigned int fci = 0;
5013 size_t remaining_missing_seqno;
5014
5015 if (!rtp || !rtp->rtcp) {
5016 return 0;
5017 }
5018
5019 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
5020 return 0;
5021 }
5022
5023 current_seqno = rtp->expectedrxseqno;
5024 remaining_missing_seqno = AST_VECTOR_SIZE(&rtp->missing_seqno);
5025 packet_len = 12; /* The header length is 12 (version line, packet source SSRC, media source SSRC) */
5026
5027 /* If there are no missing sequence numbers then don't bother sending a NACK needlessly */
5028 if (!remaining_missing_seqno) {
5029 return 0;
5030 }
5031
5032 /* This iterates through the possible forward sequence numbers seeing which ones we
5033 * have no packet for, adding it to the NACK until we are out of missing packets.
5034 */
5035 while (remaining_missing_seqno) {
5036 int *missing_seqno;
5037
5038 /* On the first entry to this loop blp_index will be -1, so this will become 0
5039 * and the sequence number will be placed into the packet as the PID.
5040 */
5041 blp_index++;
5042
5043 missing_seqno = AST_VECTOR_GET_CMP(&rtp->missing_seqno, current_seqno,
5045 if (missing_seqno) {
5046 /* We hit the max blp size, reset */
5047 if (blp_index >= 17) {
5048 put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
5049 fci = 0;
5050 blp_index = 0;
5051 packet_len += 4;
5052 }
5053
5054 if (blp_index == 0) {
5055 fci |= (current_seqno << 16);
5056 } else {
5057 fci |= (1 << (blp_index - 1));
5058 }
5059
5060 /* Since we've used a missing sequence number, we're down one */
5061 remaining_missing_seqno--;
5062 }
5063
5064 /* Handle cycling of the sequence number */
5065 current_seqno++;
5066 if (current_seqno == SEQNO_CYCLE_OVER) {
5067 current_seqno = 0;
5068 }
5069 }
5070
5071 put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
5072 packet_len += 4;
5073
5074 /* Length MUST be 2+n, where n is the number of NACKs. Same as length in words minus 1 */
5075 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (AST_RTP_RTCP_FMT_NACK << 24)
5076 | (AST_RTP_RTCP_RTPFB << 16) | ((packet_len / 4) - 1)));
5077 put_unaligned_uint32(rtcpheader + 4, htonl(rtp->ssrc));
5078 put_unaligned_uint32(rtcpheader + 8, htonl(rtp->themssrc));
5079
5080 return packet_len;
5081}
5082
5083/*!
5084 * \brief Write a RTCP packet to the far end
5085 *
5086 * \note Decide if we are going to send an SR (with Reception Block) or RR
5087 * RR is sent if we have not sent any rtp packets in the previous interval
5088 *
5089 * Scheduler callback
5090 */
5091static int ast_rtcp_write(const void *data)
5092{
5093 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
5094 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5095 int res;
5096 int sr = 0;
5097 int packet_len = 0;
5098 int ice;
5099 struct ast_sockaddr remote_address = { { 0, } };
5100 unsigned char *rtcpheader;
5101 unsigned char bdata[AST_UUID_STR_LEN + 128] = ""; /* More than enough */
5102 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
5103
5104 if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
5105 ao2_ref(instance, -1);
5106 return 0;
5107 }
5108
5109 ao2_lock(instance);
5110 rtcpheader = bdata;
5111 rtcp_report = ast_rtp_rtcp_report_alloc(rtp->themssrc_valid ? 1 : 0);
5112 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5113
5114 if (res == 0 || res == 1) {
5115 goto cleanup;
5116 }
5117
5118 packet_len += res;
5119
5120 if (rtp->bundled) {
5121 ast_rtp_instance_get_remote_address(instance, &remote_address);
5122 } else {
5123 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
5124 }
5125
5126 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, packet_len, 0, &remote_address, &ice);
5127 if (res < 0) {
5128 ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
5129 sr ? "SR" : "RR",
5131 strerror(errno));
5132 res = 0;
5133 } else {
5134 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, remote_address, ice, sr);
5135 }
5136
5137cleanup:
5138 ao2_unlock(instance);
5139
5140 if (!res) {
5141 /*
5142 * Not being rescheduled.
5143 */
5144 rtp->rtcp->schedid = -1;
5145 ao2_ref(instance, -1);
5146 }
5147
5148 return res;
5149}
5150
5151static void put_unaligned_time24(void *p, uint32_t time_msw, uint32_t time_lsw)
5152{
5153 unsigned char *cp = p;
5154 uint32_t datum;
5155
5156 /* Convert the time to 6.18 format */
5157 datum = (time_msw << 18) & 0x00fc0000;
5158 datum |= (time_lsw >> 14) & 0x0003ffff;
5159
5160 cp[0] = datum >> 16;
5161 cp[1] = datum >> 8;
5162 cp[2] = datum;
5163}
5164
5165/*! \pre instance is locked */
5166static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
5167{
5168 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5169 int pred, mark = 0;
5170 unsigned int ms = calc_txstamp(rtp, &frame->delivery);
5171 struct ast_sockaddr remote_address = { {0,} };
5172 int rate = ast_rtp_get_rate(frame->subclass.format) / 1000;
5173 unsigned int seqno;
5174#ifdef TEST_FRAMEWORK
5175 struct ast_rtp_engine_test *test = ast_rtp_instance_get_test(instance);
5176#endif
5177
5179 frame->samples /= 2;
5180 }
5181
5182 if (rtp->sending_digit) {
5183 return 0;
5184 }
5185
5186#ifdef TEST_FRAMEWORK
5187 if (test && test->send_report) {
5188 test->send_report = 0;
5189 ast_rtcp_write(instance);
5190 return 0;
5191 }
5192#endif
5193
5194 if (frame->frametype == AST_FRAME_VOICE) {
5195 pred = rtp->lastts + frame->samples;
5196
5197 /* Re-calculate last TS */
5198 rtp->lastts = rtp->lastts + ms * rate;
5199 if (ast_tvzero(frame->delivery)) {
5200 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
5201 and if so, go with our prediction */
5202 if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
5203 rtp->lastts = pred;
5204 } else {
5205 ast_debug_rtp(3, "(%p) RTP audio difference is %d, ms is %u\n",
5206 instance, abs((int)rtp->lastts - pred), ms);
5207 mark = 1;
5208 }
5209 }
5210 } else if (frame->frametype == AST_FRAME_VIDEO) {
5211 mark = frame->subclass.frame_ending;
5212 pred = rtp->lastovidtimestamp + frame->samples;
5213 /* Re-calculate last TS */
5214 rtp->lastts = rtp->lastts + ms * 90;
5215 /* If it's close to our prediction, go for it */
5216 if (ast_tvzero(frame->delivery)) {
5217 if (abs((int)rtp->lastts - pred) < 7200) {
5218 rtp->lastts = pred;
5219 rtp->lastovidtimestamp += frame->samples;
5220 } else {
5221 ast_debug_rtp(3, "(%p) RTP video difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n",
5222 instance, abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
5223 rtp->lastovidtimestamp = rtp->lastts;
5224 }
5225 }
5226 } else {
5227 pred = rtp->lastotexttimestamp + frame->samples;
5228 /* Re-calculate last TS */
5229 rtp->lastts = rtp->lastts + ms;
5230 /* If it's close to our prediction, go for it */
5231 if (ast_tvzero(frame->delivery)) {
5232 if (abs((int)rtp->lastts - pred) < 7200) {
5233 rtp->lastts = pred;
5234 rtp->lastotexttimestamp += frame->samples;
5235 } else {
5236 ast_debug_rtp(3, "(%p) RTP other difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n",
5237 instance, abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
5238 rtp->lastotexttimestamp = rtp->lastts;
5239 }
5240 }
5241 }
5242
5243 /* If we have been explicitly told to set the marker bit then do so */
5245 mark = 1;
5247 }
5248
5249 /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
5250 if (rtp->lastts > rtp->lastdigitts) {
5251 rtp->lastdigitts = rtp->lastts;
5252 }
5253
5254 /* Assume that the sequence number we expect to use is what will be used until proven otherwise */
5255 seqno = rtp->seqno;
5256
5257 /* If the frame contains sequence number information use it to influence our sequence number */
5259 if (rtp->expectedseqno != -1) {
5260 /* Determine where the frame from the core is in relation to where we expected */
5261 int difference = frame->seqno - rtp->expectedseqno;
5262
5263 /* If there is a substantial difference then we've either got packets really out
5264 * of order, or the source is RTP and it has cycled. If this happens we resync
5265 * the sequence number adjustments to this frame. If we also have packet loss
5266 * things won't be reflected correctly but it will sort itself out after a bit.
5267 */
5268 if (abs(difference) > 100) {
5269 difference = 0;
5270 }
5271
5272 /* Adjust the sequence number being used for this packet accordingly */
5273 seqno += difference;
5274
5275 if (difference >= 0) {
5276 /* This frame is on time or in the future */
5277 rtp->expectedseqno = frame->seqno + 1;
5278 rtp->seqno += difference;
5279 }
5280 } else {
5281 /* This is the first frame with sequence number we've seen, so start keeping track */
5282 rtp->expectedseqno = frame->seqno + 1;
5283 }
5284 } else {
5285 rtp->expectedseqno = -1;
5286 }
5287
5289 rtp->lastts = frame->ts * rate;
5290 }
5291
5292 ast_rtp_instance_get_remote_address(instance, &remote_address);
5293
5294 /* If we know the remote address construct a packet and send it out */
5295 if (!ast_sockaddr_isnull(&remote_address)) {
5296 int hdrlen = 12;
5297 int res;
5298 int ice;
5299 int ext = 0;
5300 int abs_send_time_id;
5301 int packet_len;
5302 unsigned char *rtpheader;
5303
5304 /* If the abs-send-time extension has been negotiated determine how much space we need */
5306 if (abs_send_time_id != -1) {
5307 /* 4 bytes for the shared information, 1 byte for identifier, 3 bytes for abs-send-time */
5308 hdrlen += 8;
5309 ext = 1;
5310 }
5311
5312 packet_len = frame->datalen + hdrlen;
5313 rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
5314
5315 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (ext << 28) | (codec << 16) | (seqno) | (mark << 23)));
5316 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
5317 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
5318
5319 /* We assume right now that we will only ever have the abs-send-time extension in the packet
5320 * which simplifies things a bit.
5321 */
5322 if (abs_send_time_id != -1) {
5323 unsigned int now_msw;
5324 unsigned int now_lsw;
5325
5326 /* This happens before being placed into the retransmission buffer so that when we
5327 * retransmit we only have to update the timestamp, not everything else.
5328 */
5329 put_unaligned_uint32(rtpheader + 12, htonl((0xBEDE << 16) | 1));
5330 rtpheader[16] = (abs_send_time_id << 4) | 2;
5331
5332 timeval2ntp(ast_tvnow(), &now_msw, &now_lsw);
5333 put_unaligned_time24(rtpheader + 17, now_msw, now_lsw);
5334 }
5335
5336 /* If retransmissions are enabled, we need to store this packet for future use */
5337 if (rtp->send_buffer) {
5338 struct ast_rtp_rtcp_nack_payload *payload;
5339
5340 payload = ast_malloc(sizeof(*payload) + packet_len);
5341 if (payload) {
5342 payload->size = packet_len;
5343 memcpy(payload->buf, rtpheader, packet_len);
5344 if (ast_data_buffer_put(rtp->send_buffer, rtp->seqno, payload) == -1) {
5345 ast_free(payload);
5346 }
5347 }
5348 }
5349
5350 res = rtp_sendto(instance, (void *)rtpheader, packet_len, 0, &remote_address, &ice);
5351 if (res < 0) {
5353 ast_debug_rtp(1, "(%p) RTP transmission error of packet %d to %s: %s\n",
5354 instance, rtp->seqno,
5355 ast_sockaddr_stringify(&remote_address),
5356 strerror(errno));
5358 /* Only give this error message once if we are not RTP debugging */
5360 ast_debug(0, "(%p) RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
5361 instance, ast_sockaddr_stringify(&remote_address));
5363 }
5364 } else {
5365 if (rtp->rtcp && rtp->rtcp->schedid < 0) {
5366 ast_debug_rtcp(2, "(%s) RTCP starting transmission in %u ms\n",
5368 ao2_ref(instance, +1);
5370 if (rtp->rtcp->schedid < 0) {
5371 ao2_ref(instance, -1);
5372 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
5373 }
5374 }
5375 }
5376
5377 if (rtp_debug_test_addr(&remote_address)) {
5378 ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
5379 ast_sockaddr_stringify(&remote_address),
5380 ice ? " (via ICE)" : "",
5381 codec, rtp->seqno, rtp->lastts, res - hdrlen);
5382 }
5383 }
5384
5385 /* If the sequence number that has been used doesn't match what we expected then this is an out of
5386 * order late packet, so we don't need to increment as we haven't yet gotten the expected frame from
5387 * the core.
5388 */
5389 if (seqno == rtp->seqno) {
5390 rtp->seqno++;
5391 }
5392
5393 return 0;
5394}
5395
5396static struct ast_frame *red_t140_to_red(struct rtp_red *red)
5397{
5398 unsigned char *data = red->t140red.data.ptr;
5399 int len = 0;
5400 int i;
5401
5402 /* replace most aged generation */
5403 if (red->len[0]) {
5404 for (i = 1; i < red->num_gen+1; i++)
5405 len += red->len[i];
5406
5407 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
5408 }
5409
5410 /* Store length of each generation and primary data length*/
5411 for (i = 0; i < red->num_gen; i++)
5412 red->len[i] = red->len[i+1];
5413 red->len[i] = red->t140.datalen;
5414
5415 /* write each generation length in red header */
5416 len = red->hdrlen;
5417 for (i = 0; i < red->num_gen; i++) {
5418 len += data[i*4+3] = red->len[i];
5419 }
5420
5421 /* add primary data to buffer */
5422 memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
5423 red->t140red.datalen = len + red->t140.datalen;
5424
5425 /* no primary data and no generations to send */
5426 if (len == red->hdrlen && !red->t140.datalen) {
5427 return NULL;
5428 }
5429
5430 /* reset t.140 buffer */
5431 red->t140.datalen = 0;
5432
5433 return &red->t140red;
5434}
5435
5436static void rtp_write_rtcp_fir(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *remote_address)
5437{
5438 unsigned char *rtcpheader;
5439 unsigned char bdata[1024];
5440 int packet_len = 0;
5441 int fir_len = 20;
5442 int ice;
5443 int res;
5444 int sr;
5445 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
5446
5447 if (!rtp || !rtp->rtcp) {
5448 return;
5449 }
5450
5451 if (ast_sockaddr_isnull(&rtp->rtcp->them) || rtp->rtcp->schedid < 0) {
5452 /*
5453 * RTCP was stopped.
5454 */
5455 return;
5456 }
5457
5458 if (!rtp->themssrc_valid) {
5459 /* We don't know their SSRC value so we don't know who to update. */
5460 return;
5461 }
5462
5463 /* Prepare RTCP FIR (PT=206, FMT=4) */
5464 rtp->rtcp->firseq++;
5465 if(rtp->rtcp->firseq == 256) {
5466 rtp->rtcp->firseq = 0;
5467 }
5468
5469 rtcpheader = bdata;
5470
5471 ao2_lock(instance);
5472 rtcp_report = ast_rtp_rtcp_report_alloc(rtp->themssrc_valid ? 1 : 0);
5473 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5474
5475 if (res == 0 || res == 1) {
5476 ao2_unlock(instance);
5477 return;
5478 }
5479
5480 packet_len += res;
5481
5482 put_unaligned_uint32(rtcpheader + packet_len + 0, htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((fir_len/4)-1)));
5483 put_unaligned_uint32(rtcpheader + packet_len + 4, htonl(rtp->ssrc));
5484 put_unaligned_uint32(rtcpheader + packet_len + 8, htonl(rtp->themssrc));
5485 put_unaligned_uint32(rtcpheader + packet_len + 12, htonl(rtp->themssrc)); /* FCI: SSRC */
5486 put_unaligned_uint32(rtcpheader + packet_len + 16, htonl(rtp->rtcp->firseq << 24)); /* FCI: Sequence number */
5487 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, packet_len + fir_len, 0, rtp->bundled ? remote_address : &rtp->rtcp->them, &ice);
5488 if (res < 0) {
5489 ast_log(LOG_ERROR, "RTCP FIR transmission error: %s\n", strerror(errno));
5490 } else {
5491 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, rtp->bundled ? *remote_address : rtp->rtcp->them, ice, sr);
5492 }
5493
5494 ao2_unlock(instance);
5495}
5496
5497static void rtp_write_rtcp_psfb(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_frame *frame, struct ast_sockaddr *remote_address)
5498{
5499 struct ast_rtp_rtcp_feedback *feedback = frame->data.ptr;
5500 unsigned char *rtcpheader;
5501 unsigned char bdata[1024];
5502 int remb_len = 24;
5503 int ice;
5504 int res;
5505 int sr = 0;
5506 int packet_len = 0;
5507 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
5508
5509 if (feedback->fmt != AST_RTP_RTCP_FMT_REMB) {
5510 ast_debug_rtcp(1, "(%p) RTCP provided feedback frame of format %d to write, but only REMB is supported\n",
5511 instance, feedback->fmt);
5512 return;
5513 }
5514
5515 if (!rtp || !rtp->rtcp) {
5516 return;
5517 }
5518
5519 /* If REMB support is not enabled don't send this RTCP packet */
5521 ast_debug_rtcp(1, "(%p) RTCP provided feedback REMB report to write, but REMB support not enabled\n",
5522 instance);
5523 return;
5524 }
5525
5526 if (ast_sockaddr_isnull(&rtp->rtcp->them) || rtp->rtcp->schedid < 0) {
5527 /*
5528 * RTCP was stopped.
5529 */
5530 return;
5531 }
5532
5533 rtcpheader = bdata;
5534
5535 ao2_lock(instance);
5536 rtcp_report = ast_rtp_rtcp_report_alloc(rtp->themssrc_valid ? 1 : 0);
5537 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5538
5539 if (res == 0 || res == 1) {
5540 ao2_unlock(instance);
5541 return;
5542 }
5543
5544 packet_len += res;
5545
5546 put_unaligned_uint32(rtcpheader + packet_len + 0, htonl((2 << 30) | (AST_RTP_RTCP_FMT_REMB << 24) | (RTCP_PT_PSFB << 16) | ((remb_len/4)-1)));
5547 put_unaligned_uint32(rtcpheader + packet_len + 4, htonl(rtp->ssrc));
5548 put_unaligned_uint32(rtcpheader + packet_len + 8, htonl(0)); /* Per the draft, this should always be 0 */
5549 put_unaligned_uint32(rtcpheader + packet_len + 12, htonl(('R' << 24) | ('E' << 16) | ('M' << 8) | ('B'))); /* Unique identifier 'R' 'E' 'M' 'B' */
5550 put_unaligned_uint32(rtcpheader + packet_len + 16, htonl((1 << 24) | (feedback->remb.br_exp << 18) | (feedback->remb.br_mantissa))); /* Number of SSRCs / BR Exp / BR Mantissa */
5551 put_unaligned_uint32(rtcpheader + packet_len + 20, htonl(rtp->ssrc)); /* The SSRC this feedback message applies to */
5552 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, packet_len + remb_len, 0, rtp->bundled ? remote_address : &rtp->rtcp->them, &ice);
5553 if (res < 0) {
5554 ast_log(LOG_ERROR, "RTCP PSFB transmission error: %s\n", strerror(errno));
5555 } else {
5556 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, rtp->bundled ? *remote_address : rtp->rtcp->them, ice, sr);
5557 }
5558
5559 ao2_unlock(instance);
5560}
5561
5562/*! \pre instance is locked */
5563static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
5564{
5565 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5566 struct ast_sockaddr remote_address = { {0,} };
5567 struct ast_format *format;
5568 int codec;
5569
5570 ast_rtp_instance_get_remote_address(instance, &remote_address);
5571
5572 /* If we don't actually know the remote address don't even bother doing anything */
5573 if (ast_sockaddr_isnull(&remote_address)) {
5574 ast_debug_rtp(1, "(%p) RTP no remote address on instance, so dropping frame\n", instance);
5575 return 0;
5576 }
5577
5578 /* VP8: is this a request to send a RTCP FIR? */
5580 rtp_write_rtcp_fir(instance, rtp, &remote_address);
5581 return 0;
5582 } else if (frame->frametype == AST_FRAME_RTCP) {
5583 if (frame->subclass.integer == AST_RTP_RTCP_PSFB) {
5584 rtp_write_rtcp_psfb(instance, rtp, frame, &remote_address);
5585 }
5586 return 0;
5587 }
5588
5589 /* If there is no data length we can't very well send the packet */
5590 if (!frame->datalen) {
5591 ast_debug_rtp(1, "(%p) RTP received frame with no data for instance, so dropping frame\n", instance);
5592 return 0;
5593 }
5594
5595 /* If the packet is not one our RTP stack supports bail out */
5596 if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
5597 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
5598 return -1;
5599 }
5600
5601 if (rtp->red) {
5602 /* return 0; */
5603 /* no primary data or generations to send */
5604 if ((frame = red_t140_to_red(rtp->red)) == NULL)
5605 return 0;
5606 }
5607
5608 /* Grab the subclass and look up the payload we are going to use */
5610 1, frame->subclass.format, 0);
5611 if (codec < 0) {
5612 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n",
5614 return -1;
5615 }
5616
5617 /* Note that we do not increase the ref count here as this pointer
5618 * will not be held by any thing explicitly. The format variable is
5619 * merely a convenience reference to frame->subclass.format */
5620 format = frame->subclass.format;
5622 /* Oh dear, if the format changed we will have to set up a new smoother */
5623 ast_debug_rtp(1, "(%s) RTP ooh, format changed from %s to %s\n",
5627 ao2_replace(rtp->lasttxformat, format);
5628 if (rtp->smoother) {
5630 rtp->smoother = NULL;
5631 }
5632 }
5633
5634 /* If no smoother is present see if we have to set one up */
5635 if (!rtp->smoother && ast_format_can_be_smoothed(format)) {
5636 unsigned int smoother_flags = ast_format_get_smoother_flags(format);
5637 unsigned int framing_ms = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(instance));
5638
5639 if (!framing_ms && (smoother_flags & AST_SMOOTHER_FLAG_FORCED)) {
5640 framing_ms = ast_format_get_default_ms(format);
5641 }
5642
5643 if (framing_ms) {
5645 if (!rtp->smoother) {
5646 ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %u len: %u\n",
5647 ast_format_get_name(format), framing_ms, ast_format_get_minimum_bytes(format));
5648 return -1;
5649 }
5650 ast_smoother_set_flags(rtp->smoother, smoother_flags);
5651 }
5652 }
5653
5654 /* Feed audio frames into the actual function that will create a frame and send it */
5655 if (rtp->smoother) {
5656 struct ast_frame *f;
5657
5659 ast_smoother_feed_be(rtp->smoother, frame);
5660 } else {
5661 ast_smoother_feed(rtp->smoother, frame);
5662 }
5663
5664 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
5665 rtp_raw_write(instance, f, codec);
5666 }
5667 } else {
5668 int hdrlen = 12;
5669 struct ast_frame *f = NULL;
5670
5671 if (frame->offset < hdrlen) {
5672 f = ast_frdup(frame);
5673 } else {
5674 f = frame;
5675 }
5676 if (f->data.ptr) {
5677 rtp_raw_write(instance, f, codec);
5678 }
5679 if (f != frame) {
5680 ast_frfree(f);
5681 }
5682
5683 }
5684
5685 return 0;
5686}
5687
5688static void calc_rxstamp_and_jitter(struct timeval *tv,
5689 struct ast_rtp *rtp, unsigned int rx_rtp_ts,
5690 int mark)
5691{
5692 int rate = ast_rtp_get_rate(rtp->f.subclass.format);
5693
5694 double jitter = 0.0;
5695 double prev_jitter = 0.0;
5696 struct timeval now;
5697 struct timeval tmp;
5698 double rxnow;
5699 double arrival_sec;
5700 unsigned int arrival;
5701 int transit;
5702 int d;
5703
5704 gettimeofday(&now,NULL);
5705
5706 if (rtp->rxcount == 1 || mark) {
5707 rtp->rxstart = ast_tv2double(&now);
5708 rtp->remote_seed_rx_rtp_ts = rx_rtp_ts;
5709
5710 /*
5711 * "tv" is placed in the received frame's
5712 * "delivered" field and when this frame is
5713 * sent out again on the other side, it's
5714 * used to calculate the timestamp on the
5715 * outgoing RTP packets.
5716 *
5717 * NOTE: We need to do integer math here
5718 * because double math rounding issues can
5719 * generate incorrect timestamps.
5720 */
5721 rtp->rxcore = now;
5722 tmp = ast_samp2tv(rx_rtp_ts, rate);
5723 rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
5724 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
5725 *tv = ast_tvadd(rtp->rxcore, tmp);
5726
5727 ast_debug_rtcp(3, "%s: "
5728 "Seed ts: %u current time: %f\n",
5730 , rx_rtp_ts
5731 , rtp->rxstart
5732 );
5733
5734 return;
5735 }
5736
5737 tmp = ast_samp2tv(rx_rtp_ts, rate);
5738 /* See the comment about "tv" above. Even if
5739 * we don't use this received packet for jitter
5740 * calculations, we still need to set tv so the
5741 * timestamp will be correct when this packet is
5742 * sent out again.
5743 */
5744 *tv = ast_tvadd(rtp->rxcore, tmp);
5745
5746 /*
5747 * The first few packets are generally unstable so let's
5748 * not use them in the calculations.
5749 */
5751 ast_debug_rtcp(3, "%s: Packet %d < %d. Ignoring\n",
5753 , rtp->rxcount
5755 );
5756
5757 return;
5758 }
5759
5760 /*
5761 * First good packet. Capture the start time and timestamp
5762 * but don't actually use this packet for calculation.
5763 */
5765 rtp->rxstart_stable = ast_tv2double(&now);
5766 rtp->remote_seed_rx_rtp_ts_stable = rx_rtp_ts;
5767 rtp->last_transit_time_samples = -rx_rtp_ts;
5768
5769 ast_debug_rtcp(3, "%s: "
5770 "pkt: %5u Stable Seed ts: %u current time: %f\n",
5772 , rtp->rxcount
5773 , rx_rtp_ts
5774 , rtp->rxstart_stable
5775 );
5776
5777 return;
5778 }
5779
5780 /*
5781 * If the current packet isn't in sequence, don't
5782 * use it in any calculations as remote_current_rx_rtp_ts
5783 * is not going to be correct.
5784 */
5785 if (rtp->lastrxseqno != rtp->prevrxseqno + 1) {
5786 ast_debug_rtcp(3, "%s: Current packet seq %d != last packet seq %d + 1. Ignoring\n",
5788 , rtp->lastrxseqno
5789 , rtp->prevrxseqno
5790 );
5791
5792 return;
5793 }
5794
5795 /*
5796 * The following calculations are taken from
5797 * https://www.rfc-editor.org/rfc/rfc3550#appendix-A.8
5798 *
5799 * The received rtp timestamp is the random "seed"
5800 * timestamp chosen by the sender when they sent the
5801 * first packet, plus the number of samples since then.
5802 *
5803 * To get our arrival time in the same units, we
5804 * calculate the time difference in seconds between
5805 * when we received the first packet and when we
5806 * received this packet and convert that to samples.
5807 */
5808 rxnow = ast_tv2double(&now);
5809 arrival_sec = rxnow - rtp->rxstart_stable;
5810 arrival = ast_sec2samp(arrival_sec, rate);
5811
5812 /*
5813 * Now we can use the exact formula in
5814 * https://www.rfc-editor.org/rfc/rfc3550#appendix-A.8 :
5815 *
5816 * int transit = arrival - r->ts;
5817 * int d = transit - s->transit;
5818 * s->transit = transit;
5819 * if (d < 0) d = -d;
5820 * s->jitter += (1./16.) * ((double)d - s->jitter);
5821 *
5822 * Our rx_rtp_ts is their r->ts.
5823 * Our rtp->last_transit_time_samples is their s->transit.
5824 * Our rtp->rxjitter is their s->jitter.
5825 */
5826 transit = arrival - rx_rtp_ts;
5827 d = transit - rtp->last_transit_time_samples;
5828
5829 if (d < 0) {
5830 d = -d;
5831 }
5832
5833 prev_jitter = rtp->rxjitter_samples;
5834 jitter = (1.0/16.0) * (((double)d) - prev_jitter);
5835 rtp->rxjitter_samples = prev_jitter + jitter;
5836
5837 /*
5838 * We need to hang on to jitter in both samples and seconds.
5839 */
5840 rtp->rxjitter = ast_samp2sec(rtp->rxjitter_samples, rate);
5841
5842 ast_debug_rtcp(3, "%s: pkt: %5u "
5843 "Arrival sec: %7.3f Arrival ts: %10u RX ts: %10u "
5844 "Transit samp: %6d Last transit samp: %6d d: %4d "
5845 "Curr jitter: %7.0f(%7.3f) Prev Jitter: %7.0f(%7.3f) New Jitter: %7.0f(%7.3f)\n",
5847 , rtp->rxcount
5848 , arrival_sec
5849 , arrival
5850 , rx_rtp_ts
5851 , transit
5853 , d
5854 , jitter
5855 , ast_samp2sec(jitter, rate)
5856 , prev_jitter
5857 , ast_samp2sec(prev_jitter, rate)
5858 , rtp->rxjitter_samples
5859 , rtp->rxjitter
5860 );
5861
5862 rtp->last_transit_time_samples = transit;
5863
5864 /*
5865 * Update all the stats.
5866 */
5867 if (rtp->rtcp) {
5868 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
5869 rtp->rtcp->maxrxjitter = rtp->rxjitter;
5870 if (rtp->rtcp->rxjitter_count == 1)
5871 rtp->rtcp->minrxjitter = rtp->rxjitter;
5872 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
5873 rtp->rtcp->minrxjitter = rtp->rxjitter;
5874
5877 &rtp->rtcp->rxjitter_count);
5878 }
5879
5880 return;
5881}
5882
5883static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
5884{
5885 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5886 struct ast_sockaddr remote_address = { {0,} };
5887
5888 ast_rtp_instance_get_remote_address(instance, &remote_address);
5889
5890 if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
5891 ast_debug_rtp(1, "(%p) RTP ignore potential DTMF echo from '%s'\n",
5892 instance, ast_sockaddr_stringify(&remote_address));
5893 rtp->resp = 0;
5894 rtp->dtmfsamples = 0;
5895 return &ast_null_frame;
5896 } else if (type == AST_FRAME_DTMF_BEGIN && rtp->resp == 'X') {
5897 ast_debug_rtp(1, "(%p) RTP ignore flash begin from '%s'\n",
5898 instance, ast_sockaddr_stringify(&remote_address));
5899 rtp->resp = 0;
5900 rtp->dtmfsamples = 0;
5901 return &ast_null_frame;
5902 }
5903
5904 if (rtp->resp == 'X') {
5905 ast_debug_rtp(1, "(%p) RTP creating flash Frame at %s\n",
5906 instance, ast_sockaddr_stringify(&remote_address));
5909 } else {
5910 ast_debug_rtp(1, "(%p) RTP creating %s DTMF Frame: %d (%c), at %s\n",
5911 instance, type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
5912 rtp->resp, rtp->resp,
5913 ast_sockaddr_stringify(&remote_address));
5914 rtp->f.frametype = type;
5915 rtp->f.subclass.integer = rtp->resp;
5916 }
5917 rtp->f.datalen = 0;
5918 rtp->f.samples = 0;
5919 rtp->f.mallocd = 0;
5920 rtp->f.src = "RTP";
5921 AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
5922
5923 return &rtp->f;
5924}
5925
5926static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark, struct frame_list *frames)
5927{
5928 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
5929 struct ast_sockaddr remote_address = { {0,} };
5930 unsigned int event, event_end, samples;
5931 char resp = 0;
5932 struct ast_frame *f = NULL;
5933
5934 ast_rtp_instance_get_remote_address(instance, &remote_address);
5935
5936 /* Figure out event, event end, and samples */
5937 event = ntohl(*((unsigned int *)(data)));
5938 event >>= 24;
5939 event_end = ntohl(*((unsigned int *)(data)));
5940 event_end <<= 8;
5941 event_end >>= 24;
5942 samples = ntohl(*((unsigned int *)(data)));
5943 samples &= 0xFFFF;
5944
5945 if (rtp_debug_test_addr(&remote_address)) {
5946 ast_verbose("Got RTP RFC2833 from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d, mark %d, event %08x, end %d, duration %-5.5u) \n",
5947 ast_sockaddr_stringify(&remote_address),
5948 payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
5949 }
5950
5951 /* Print out debug if turned on */
5953 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
5954
5955 /* Figure out what digit was pressed */
5956 if (event < 10) {
5957 resp = '0' + event;
5958 } else if (event < 11) {
5959 resp = '*';
5960 } else if (event < 12) {
5961 resp = '#';
5962 } else if (event < 16) {
5963 resp = 'A' + (event - 12);
5964 } else if (event < 17) { /* Event 16: Hook flash */
5965 resp = 'X';
5966 } else {
5967 /* Not a supported event */
5968 ast_debug_rtp(1, "(%p) RTP ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", instance, event);
5969 return;
5970 }
5971
5973 if (!rtp->last_end_timestamp.is_set || rtp->last_end_timestamp.ts != timestamp || (rtp->resp && rtp->resp != resp)) {
5974 rtp->resp = resp;
5975 rtp->dtmf_timeout = 0;
5977 f->len = 0;
5978 rtp->last_end_timestamp.ts = timestamp;
5979 rtp->last_end_timestamp.is_set = 1;
5981 }
5982 } else {
5983 /* The duration parameter measures the complete
5984 duration of the event (from the beginning) - RFC2833.
5985 Account for the fact that duration is only 16 bits long
5986 (about 8 seconds at 8000 Hz) and can wrap is digit
5987 is hold for too long. */
5988 unsigned int new_duration = rtp->dtmf_duration;
5989 unsigned int last_duration = new_duration & 0xFFFF;
5990
5991 if (last_duration > 64000 && samples < last_duration) {
5992 new_duration += 0xFFFF + 1;
5993 }
5994 new_duration = (new_duration & ~0xFFFF) | samples;
5995
5996 if (event_end & 0x80) {
5997 /* End event */
5998 if (rtp->last_seqno != seqno && (!rtp->last_end_timestamp.is_set || timestamp > rtp->last_end_timestamp.ts)) {
5999 rtp->last_end_timestamp.ts = timestamp;
6000 rtp->last_end_timestamp.is_set = 1;
6001 rtp->dtmf_duration = new_duration;
6002 rtp->resp = resp;
6005 rtp->resp = 0;
6006 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
6009 ast_debug_rtp(1, "(%p) RTP dropping duplicate or out of order DTMF END frame (seqno: %u, ts %u, digit %c)\n",
6010 instance, seqno, timestamp, resp);
6011 }
6012 } else {
6013 /* Begin/continuation */
6014
6015 /* The second portion of the seqno check is to not mistakenly
6016 * stop accepting DTMF if the seqno rolls over beyond
6017 * 65535.
6018 */
6019 if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
6020 || (rtp->last_end_timestamp.is_set
6021 && timestamp <= rtp->last_end_timestamp.ts)) {
6022 /* Out of order frame. Processing this can cause us to
6023 * improperly duplicate incoming DTMF, so just drop
6024 * this.
6025 */
6027 ast_debug(0, "Dropping out of order DTMF frame (seqno %u, ts %u, digit %c)\n",
6028 seqno, timestamp, resp);
6029 }
6030 return;
6031 }
6032
6033 if (rtp->resp && rtp->resp != resp) {
6034 /* Another digit already began. End it */
6037 rtp->resp = 0;
6038 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
6040 }
6041
6042 if (rtp->resp) {
6043 /* Digit continues */
6044 rtp->dtmf_duration = new_duration;
6045 } else {
6046 /* New digit began */
6047 rtp->resp = resp;
6049 rtp->dtmf_duration = samples;
6051 }
6052
6053 rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
6054 }
6055
6056 rtp->last_seqno = seqno;
6057 }
6058
6059 rtp->dtmfsamples = samples;
6060
6061 return;
6062}
6063
6064static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark)
6065{
6066 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
6067 unsigned int event, flags, power;
6068 char resp = 0;
6069 unsigned char seq;
6070 struct ast_frame *f = NULL;
6071
6072 if (len < 4) {
6073 return NULL;
6074 }
6075
6076 /* The format of Cisco RTP DTMF packet looks like next:
6077 +0 - sequence number of DTMF RTP packet (begins from 1,
6078 wrapped to 0)
6079 +1 - set of flags
6080 +1 (bit 0) - flaps by different DTMF digits delimited by audio
6081 or repeated digit without audio???
6082 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
6083 then falls to 0 at its end)
6084 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
6085 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
6086 by each new packet and thus provides some redundancy.
6087
6088 Sample of Cisco RTP DTMF packet is (all data in hex):
6089 19 07 00 02 12 02 20 02
6090 showing end of DTMF digit '2'.
6091
6092 The packets
6093 27 07 00 02 0A 02 20 02
6094 28 06 20 02 00 02 0A 02
6095 shows begin of new digit '2' with very short pause (20 ms) after
6096 previous digit '2'. Bit +1.0 flips at begin of new digit.
6097
6098 Cisco RTP DTMF packets comes as replacement of audio RTP packets
6099 so its uses the same sequencing and timestamping rules as replaced
6100 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
6101 on audio framing parameters. Marker bit isn't used within stream of
6102 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
6103 are not sequential at borders between DTMF and audio streams,
6104 */
6105
6106 seq = data[0];
6107 flags = data[1];
6108 power = data[2];
6109 event = data[3] & 0x1f;
6110
6112 ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%u, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
6113 if (event < 10) {
6114 resp = '0' + event;
6115 } else if (event < 11) {
6116 resp = '*';
6117 } else if (event < 12) {
6118 resp = '#';
6119 } else if (event < 16) {
6120 resp = 'A' + (event - 12);
6121 } else if (event < 17) {
6122 resp = 'X';
6123 }
6124 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
6125 rtp->resp = resp;
6126 /* Why we should care on DTMF compensation at reception? */
6128 f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
6129 rtp->dtmfsamples = 0;
6130 }
6131 } else if ((rtp->resp == resp) && !power) {
6133 f->samples = rtp->dtmfsamples * (ast_rtp_get_rate(rtp->lastrxformat) / 1000);
6134 rtp->resp = 0;
6135 } else if (rtp->resp == resp) {
6136 rtp->dtmfsamples += 20 * (ast_rtp_get_rate(rtp->lastrxformat) / 1000);
6137 }
6138
6139 rtp->dtmf_timeout = 0;
6140
6141 return f;
6142}
6143
6144static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark)
6145{
6146 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
6147
6148 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
6149 totally help us out because we don't have an engine to keep it going and we are not
6150 guaranteed to have it every 20ms or anything */
6152 ast_debug(0, "- RTP 3389 Comfort noise event: Format %s (len = %d)\n",
6154 }
6155
6156 if (!ast_test_flag(rtp, FLAG_3389_WARNING)) {
6157 struct ast_sockaddr remote_address = { {0,} };
6158
6159 ast_rtp_instance_get_remote_address(instance, &remote_address);
6160
6161 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
6162 ast_sockaddr_stringify(&remote_address));
6164 }
6165
6166 /* Must have at least one byte */
6167 if (!len) {
6168 return NULL;
6169 }
6170 if (len < 24) {
6171 rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
6172 rtp->f.datalen = len - 1;
6174 memcpy(rtp->f.data.ptr, data + 1, len - 1);
6175 } else {
6176 rtp->f.data.ptr = NULL;
6177 rtp->f.offset = 0;
6178 rtp->f.datalen = 0;
6179 }
6180 rtp->f.frametype = AST_FRAME_CNG;
6181 rtp->f.subclass.integer = data[0] & 0x7f;
6182 rtp->f.samples = 0;
6183 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
6184
6185 return &rtp->f;
6186}
6187
6188static int update_rtt_stats(struct ast_rtp *rtp, unsigned int lsr, unsigned int dlsr)
6189{
6190 struct timeval now;
6191 struct timeval rtt_tv;
6192 unsigned int msw;
6193 unsigned int lsw;
6194 unsigned int rtt_msw;
6195 unsigned int rtt_lsw;
6196 unsigned int lsr_a;
6197 unsigned int rtt;
6198
6199 gettimeofday(&now, NULL);
6200 timeval2ntp(now, &msw, &lsw);
6201
6202 lsr_a = ((msw & 0x0000ffff) << 16) | ((lsw & 0xffff0000) >> 16);
6203 rtt = lsr_a - lsr - dlsr;
6204 rtt_msw = (rtt & 0xffff0000) >> 16;
6205 rtt_lsw = (rtt & 0x0000ffff);
6206 rtt_tv.tv_sec = rtt_msw;
6207 /*
6208 * Convert 16.16 fixed point rtt_lsw to usec without
6209 * overflow.
6210 *
6211 * = rtt_lsw * 10^6 / 2^16
6212 * = rtt_lsw * (2^6 * 5^6) / 2^16
6213 * = rtt_lsw * 5^6 / 2^10
6214 *
6215 * The rtt_lsw value is in 16.16 fixed point format and 5^6
6216 * requires 14 bits to represent. We have enough space to
6217 * directly do the conversion because there is no integer
6218 * component in rtt_lsw.
6219 */
6220 rtt_tv.tv_usec = (rtt_lsw * 15625) >> 10;
6221 rtp->rtcp->rtt = (double)rtt_tv.tv_sec + ((double)rtt_tv.tv_usec / 1000000);
6222 if (lsr_a - dlsr < lsr) {
6223 return 1;
6224 }
6225
6226 rtp->rtcp->accumulated_transit += rtp->rtcp->rtt;
6227 if (rtp->rtcp->rtt_count == 0 || rtp->rtcp->minrtt > rtp->rtcp->rtt) {
6228 rtp->rtcp->minrtt = rtp->rtcp->rtt;
6229 }
6230 if (rtp->rtcp->maxrtt < rtp->rtcp->rtt) {
6231 rtp->rtcp->maxrtt = rtp->rtcp->rtt;
6232 }
6233
6235 &rtp->rtcp->stdevrtt, &rtp->rtcp->rtt_count);
6236
6237 return 0;
6238}
6239
6240/*!
6241 * \internal
6242 * \brief Update RTCP interarrival jitter stats
6243 */
6244static void update_jitter_stats(struct ast_rtp *rtp, unsigned int ia_jitter)
6245{
6246 int rate = ast_rtp_get_rate(rtp->f.subclass.format);
6247
6248 rtp->rtcp->reported_jitter = ast_samp2sec(ia_jitter, rate);
6249
6250 if (rtp->rtcp->reported_jitter_count == 0) {
6252 }
6253 if (rtp->rtcp->reported_jitter < rtp->rtcp->reported_minjitter) {
6255 }
6256 if (rtp->rtcp->reported_jitter > rtp->rtcp->reported_maxjitter) {
6258 }
6259
6263}
6264
6265/*!
6266 * \internal
6267 * \brief Update RTCP lost packet stats
6268 */
6269static void update_lost_stats(struct ast_rtp *rtp, unsigned int lost_packets)
6270{
6271 double reported_lost;
6272
6273 rtp->rtcp->reported_lost = lost_packets;
6274 reported_lost = (double)rtp->rtcp->reported_lost;
6275 if (rtp->rtcp->reported_lost_count == 0) {
6276 rtp->rtcp->reported_minlost = reported_lost;
6277 }
6278 if (reported_lost < rtp->rtcp->reported_minlost) {
6279 rtp->rtcp->reported_minlost = reported_lost;
6280 }
6281 if (reported_lost > rtp->rtcp->reported_maxlost) {
6282 rtp->rtcp->reported_maxlost = reported_lost;
6283 }
6284
6287}
6288
6289#define RESCALE(in, inmin, inmax, outmin, outmax) ((((in - inmin)/(inmax-inmin))*(outmax-outmin))+outmin)
6290/*!
6291 * \brief Calculate a "media experience score" based on given data
6292 *
6293 * Technically, a mean opinion score (MOS) cannot be calculated without the involvement
6294 * of human eyes (video) and ears (audio). Thus instead we'll approximate an opinion
6295 * using the given parameters, and call it a media experience score.
6296 *
6297 * The tallied score is based upon recommendations and formulas from ITU-T G.107,
6298 * ITU-T G.109, ITU-T G.113, and other various internet sources.
6299 *
6300 * \param instance RTP instance
6301 * \param normdevrtt The average round trip time
6302 * \param normdev_rxjitter The smoothed jitter
6303 * \param stdev_rxjitter The jitter standard deviation value
6304 * \param normdev_rxlost The average number of packets lost since last check
6305 *
6306 * \return A media experience score.
6307 *
6308 * \note The calculations in this function could probably be simplified
6309 * but calculating a MOS using the information available publicly,
6310 * then re-scaling it to 0.0 -> 100.0 makes the process clearer and
6311 * easier to troubleshoot or change.
6312 */
6313static double calc_media_experience_score(struct ast_rtp_instance *instance,
6314 double normdevrtt, double normdev_rxjitter, double stdev_rxjitter,
6315 double normdev_rxlost)
6316{
6317 double r_value;
6318 double pseudo_mos;
6319 double mes = 0;
6320
6321 /*
6322 * While the media itself might be okay, a significant enough delay could make
6323 * for an unpleasant user experience.
6324 *
6325 * Calculate the effective latency by using the given round trip time, and adding
6326 * jitter scaled according to its standard deviation. The scaling is done in order
6327 * to increase jitter's weight since a higher deviation can result in poorer overall
6328 * quality.
6329 */
6330 double effective_latency = (normdevrtt * 1000)
6331 + ((normdev_rxjitter * 2) * (stdev_rxjitter / 3))
6332 + 10;
6333
6334 /*
6335 * Using the defaults for the standard transmission rating factor ("R" value)
6336 * one arrives at 93.2 (see ITU-T G.107 for more details), so we'll use that
6337 * as the starting value and subtract deficiencies that could affect quality.
6338 *
6339 * Calculate the impact of the effective latency. Influence increases with
6340 * values over 160 as the significant "lag" can degrade user experience.
6341 */
6342 if (effective_latency < 160) {
6343 r_value = 93.2 - (effective_latency / 40);
6344 } else {
6345 r_value = 93.2 - (effective_latency - 120) / 10;
6346 }
6347
6348 /* Next evaluate the impact of lost packets */
6349 r_value = r_value - (normdev_rxlost * 2.0);
6350
6351 /*
6352 * Finally convert the "R" value into a opinion/quality score between 1 (really anything
6353 * below 3 should be considered poor) and 4.5 (the highest achievable for VOIP).
6354 */
6355 if (r_value < 0) {
6356 pseudo_mos = 1.0;
6357 } else if (r_value > 100) {
6358 pseudo_mos = 4.5;
6359 } else {
6360 pseudo_mos = 1 + (0.035 * r_value) + (r_value * (r_value - 60) * (100 - r_value) * 0.000007);
6361 }
6362
6363 /*
6364 * We're going to rescale the 0.0->5.0 pseudo_mos to the 0.0->100.0 MES.
6365 * For those ranges, we could actually just multiply the pseudo_mos
6366 * by 20 but we may want to change the scale later.
6367 */
6368 mes = RESCALE(pseudo_mos, 0.0, 5.0, 0.0, 100.0);
6369
6370 return mes;
6371}
6372
6373/*!
6374 * \internal
6375 * \brief Update MES stats based on info received in an SR or RR.
6376 * This is RTP we sent and they received.
6377 */
6378static void update_reported_mes_stats(struct ast_rtp *rtp)
6379{
6380 double mes = calc_media_experience_score(rtp->owner,
6381 rtp->rtcp->normdevrtt,
6382 rtp->rtcp->reported_jitter,
6385
6386 rtp->rtcp->reported_mes = mes;
6387 if (rtp->rtcp->reported_mes_count == 0) {
6388 rtp->rtcp->reported_minmes = mes;
6389 }
6390 if (mes < rtp->rtcp->reported_minmes) {
6391 rtp->rtcp->reported_minmes = mes;
6392 }
6393 if (mes > rtp->rtcp->reported_maxmes) {
6394 rtp->rtcp->reported_maxmes = mes;
6395 }
6396
6399
6400 ast_debug_rtcp(2, "%s: rtt: %.9f j: %.9f sjh: %.9f lost: %.9f mes: %4.1f\n",
6402 rtp->rtcp->normdevrtt,
6403 rtp->rtcp->reported_jitter,
6405 rtp->rtcp->reported_normdev_lost, mes);
6406}
6407
6408/*!
6409 * \internal
6410 * \brief Update MES stats based on info we will send in an SR or RR.
6411 * This is RTP they sent and we received.
6412 */
6413static void update_local_mes_stats(struct ast_rtp *rtp)
6414{
6416 rtp->rtcp->normdevrtt,
6417 rtp->rxjitter,
6418 rtp->rtcp->stdev_rxjitter,
6419 rtp->rtcp->normdev_rxlost);
6420
6421 if (rtp->rtcp->rxmes_count == 0) {
6422 rtp->rtcp->minrxmes = rtp->rxmes;
6423 }
6424 if (rtp->rxmes < rtp->rtcp->minrxmes) {
6425 rtp->rtcp->minrxmes = rtp->rxmes;
6426 }
6427 if (rtp->rxmes > rtp->rtcp->maxrxmes) {
6428 rtp->rtcp->maxrxmes = rtp->rxmes;
6429 }
6430
6432 &rtp->rtcp->stdev_rxmes, &rtp->rtcp->rxmes_count);
6433
6434 ast_debug_rtcp(2, " %s: rtt: %.9f j: %.9f sjh: %.9f lost: %.9f mes: %4.1f\n",
6436 rtp->rtcp->normdevrtt,
6437 rtp->rxjitter,
6438 rtp->rtcp->stdev_rxjitter,
6439 rtp->rtcp->normdev_rxlost, rtp->rxmes);
6440}
6441
6442/*! \pre instance is locked */
6444 struct ast_rtp *rtp, unsigned int ssrc, int source)
6445{
6446 int index;
6447
6448 if (!AST_VECTOR_SIZE(&rtp->ssrc_mapping)) {
6449 /* This instance is not bundled */
6450 return instance;
6451 }
6452
6453 /* Find the bundled child instance */
6454 for (index = 0; index < AST_VECTOR_SIZE(&rtp->ssrc_mapping); ++index) {
6455 struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&rtp->ssrc_mapping, index);
6456 unsigned int mapping_ssrc = source ? ast_rtp_get_ssrc(mapping->instance) : mapping->ssrc;
6457
6458 if (mapping->ssrc_valid && mapping_ssrc == ssrc) {
6459 return mapping->instance;
6460 }
6461 }
6462
6463 /* Does the SSRC match the bundled parent? */
6464 if (rtp->themssrc_valid && rtp->themssrc == ssrc) {
6465 return instance;
6466 }
6467 return NULL;
6468}
6469
6470/*! \pre instance is locked */
6472 struct ast_rtp *rtp, unsigned int ssrc)
6473{
6474 return __rtp_find_instance_by_ssrc(instance, rtp, ssrc, 0);
6475}
6476
6477/*! \pre instance is locked */
6479 struct ast_rtp *rtp, unsigned int ssrc)
6480{
6481 return __rtp_find_instance_by_ssrc(instance, rtp, ssrc, 1);
6482}
6483
6484static const char *rtcp_payload_type2str(unsigned int pt)
6485{
6486 const char *str;
6487
6488 switch (pt) {
6489 case RTCP_PT_SR:
6490 str = "Sender Report";
6491 break;
6492 case RTCP_PT_RR:
6493 str = "Receiver Report";
6494 break;
6495 case RTCP_PT_FUR:
6496 /* Full INTRA-frame Request / Fast Update Request */
6497 str = "H.261 FUR";
6498 break;
6499 case RTCP_PT_PSFB:
6500 /* Payload Specific Feed Back */
6501 str = "PSFB";
6502 break;
6503 case RTCP_PT_SDES:
6504 str = "Source Description";
6505 break;
6506 case RTCP_PT_BYE:
6507 str = "BYE";
6508 break;
6509 default:
6510 str = "Unknown";
6511 break;
6512 }
6513 return str;
6514}
6515
6516static const char *rtcp_payload_subtype2str(unsigned int pt, unsigned int subtype)
6517{
6518 switch (pt) {
6519 case AST_RTP_RTCP_RTPFB:
6520 if (subtype == AST_RTP_RTCP_FMT_NACK) {
6521 return "NACK";
6522 }
6523 break;
6524 case RTCP_PT_PSFB:
6525 if (subtype == AST_RTP_RTCP_FMT_REMB) {
6526 return "REMB";
6527 }
6528 break;
6529 default:
6530 break;
6531 }
6532
6533 return NULL;
6534}
6535
6536/*! \pre instance is locked */
6537static int ast_rtp_rtcp_handle_nack(struct ast_rtp_instance *instance, unsigned int *nackdata, unsigned int position,
6538 unsigned int length)
6539{
6540 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
6541 int res = 0;
6542 int blp_index;
6543 int packet_index;
6544 int ice;
6545 struct ast_rtp_rtcp_nack_payload *payload;
6546 unsigned int current_word;
6547 unsigned int pid; /* Packet ID which refers to seqno of lost packet */
6548 unsigned int blp; /* Bitmask of following lost packets */
6549 struct ast_sockaddr remote_address = { {0,} };
6550 int abs_send_time_id;
6551 unsigned int now_msw = 0;
6552 unsigned int now_lsw = 0;
6553 unsigned int packets_not_found = 0;
6554
6555 if (!rtp->send_buffer) {
6556 ast_debug_rtcp(1, "(%p) RTCP tried to handle NACK request, "
6557 "but we don't have a RTP packet storage!\n", instance);
6558 return res;
6559 }
6560
6562 if (abs_send_time_id != -1) {
6563 timeval2ntp(ast_tvnow(), &now_msw, &now_lsw);
6564 }
6565
6566 ast_rtp_instance_get_remote_address(instance, &remote_address);
6567
6568 /*
6569 * We use index 3 because with feedback messages, the FCI (Feedback Control Information)
6570 * does not begin until after the version, packet SSRC, and media SSRC words.
6571 */
6572 for (packet_index = 3; packet_index < length; packet_index++) {
6573 current_word = ntohl(nackdata[position + packet_index]);
6574 pid = current_word >> 16;
6575 /* We know the remote end is missing this packet. Go ahead and send it if we still have it. */
6576 payload = (struct ast_rtp_rtcp_nack_payload *)ast_data_buffer_get(rtp->send_buffer, pid);
6577 if (payload) {
6578 if (abs_send_time_id != -1) {
6579 /* On retransmission we need to update the timestamp within the packet, as it
6580 * is supposed to contain when the packet was actually sent.
6581 */
6582 put_unaligned_time24(payload->buf + 17, now_msw, now_lsw);
6583 }
6584 res += rtp_sendto(instance, payload->buf, payload->size, 0, &remote_address, &ice);
6585 } else {
6586 ast_debug_rtcp(1, "(%p) RTCP received NACK request for RTP packet with seqno %d, "
6587 "but we don't have it\n", instance, pid);
6588 packets_not_found++;
6589 }
6590 /*
6591 * The bitmask. Denoting the least significant bit as 1 and its most significant bit
6592 * as 16, then bit i of the bitmask is set to 1 if the receiver has not received RTP
6593 * packet (pid+i)(modulo 2^16). Otherwise, it is set to 0. We cannot assume bits set
6594 * to 0 after a bit set to 1 have actually been received.
6595 */
6596 blp = current_word & 0xffff;
6597 blp_index = 1;
6598 while (blp) {
6599 if (blp & 1) {
6600 /* Packet (pid + i)(modulo 2^16) is missing too. */
6601 unsigned int seqno = (pid + blp_index) % 65536;
6602 payload = (struct ast_rtp_rtcp_nack_payload *)ast_data_buffer_get(rtp->send_buffer, seqno);
6603 if (payload) {
6604 if (abs_send_time_id != -1) {
6605 put_unaligned_time24(payload->buf + 17, now_msw, now_lsw);
6606 }
6607 res += rtp_sendto(instance, payload->buf, payload->size, 0, &remote_address, &ice);
6608 } else {
6609 ast_debug_rtcp(1, "(%p) RTCP remote end also requested RTP packet with seqno %d, "
6610 "but we don't have it\n", instance, seqno);
6611 packets_not_found++;
6612 }
6613 }
6614 blp >>= 1;
6615 blp_index++;
6616 }
6617 }
6618
6619 if (packets_not_found) {
6620 /* Grow the send buffer based on how many packets were not found in the buffer, but
6621 * enforce a maximum.
6622 */
6624 ast_data_buffer_max(rtp->send_buffer) + packets_not_found));
6625 ast_debug_rtcp(2, "(%p) RTCP send buffer on RTP instance is now at maximum of %zu\n",
6626 instance, ast_data_buffer_max(rtp->send_buffer));
6627 }
6628
6629 return res;
6630}
6631
6632/*
6633 * Unshifted RTCP header bit field masks
6634 */
6635#define RTCP_LENGTH_MASK 0xFFFF
6636#define RTCP_PAYLOAD_TYPE_MASK 0xFF
6637#define RTCP_REPORT_COUNT_MASK 0x1F
6638#define RTCP_PADDING_MASK 0x01
6639#define RTCP_VERSION_MASK 0x03
6640
6641/*
6642 * RTCP header bit field shift offsets
6643 */
6644#define RTCP_LENGTH_SHIFT 0
6645#define RTCP_PAYLOAD_TYPE_SHIFT 16
6646#define RTCP_REPORT_COUNT_SHIFT 24
6647#define RTCP_PADDING_SHIFT 29
6648#define RTCP_VERSION_SHIFT 30
6649
6650#define RTCP_VERSION 2U
6651#define RTCP_VERSION_SHIFTED (RTCP_VERSION << RTCP_VERSION_SHIFT)
6652#define RTCP_VERSION_MASK_SHIFTED (RTCP_VERSION_MASK << RTCP_VERSION_SHIFT)
6653
6654/*
6655 * RTCP first packet record validity header mask and value.
6656 *
6657 * RFC3550 intentionally defines the encoding of RTCP_PT_SR and RTCP_PT_RR
6658 * such that they differ in the least significant bit. Either of these two
6659 * payload types MUST be the first RTCP packet record in a compound packet.
6660 *
6661 * RFC3550 checks the padding bit in the algorithm they use to check the
6662 * RTCP packet for validity. However, we aren't masking the padding bit
6663 * to check since we don't know if it is a compound RTCP packet or not.
6664 */
6665#define RTCP_VALID_MASK (RTCP_VERSION_MASK_SHIFTED | (((RTCP_PAYLOAD_TYPE_MASK & ~0x1)) << RTCP_PAYLOAD_TYPE_SHIFT))
6666#define RTCP_VALID_VALUE (RTCP_VERSION_SHIFTED | (RTCP_PT_SR << RTCP_PAYLOAD_TYPE_SHIFT))
6667
6668#define RTCP_SR_BLOCK_WORD_LENGTH 5
6669#define RTCP_RR_BLOCK_WORD_LENGTH 6
6670#define RTCP_HEADER_SSRC_LENGTH 2
6671#define RTCP_FB_REMB_BLOCK_WORD_LENGTH 4
6672#define RTCP_FB_NACK_BLOCK_WORD_LENGTH 2
6673
6674static struct ast_frame *ast_rtcp_interpret(struct ast_rtp_instance *instance, struct ast_srtp *srtp,
6675 const unsigned char *rtcpdata, size_t size, struct ast_sockaddr *addr)
6676{
6677 struct ast_rtp_instance *transport = instance;
6678 struct ast_rtp *transport_rtp = ast_rtp_instance_get_data(instance);
6679 int len = size;
6680 unsigned int *rtcpheader = (unsigned int *)(rtcpdata);
6681 unsigned int packetwords;
6682 unsigned int position;
6683 unsigned int first_word;
6684 /*! True if we have seen an acceptable SSRC to learn the remote RTCP address */
6685 unsigned int ssrc_seen;
6686 struct ast_rtp_rtcp_report_block *report_block;
6687 struct ast_frame *f = &ast_null_frame;
6688#ifdef TEST_FRAMEWORK
6689 struct ast_rtp_engine_test *test_engine;
6690#endif
6691
6692 /* If this is encrypted then decrypt the payload */
6693 if ((*rtcpheader & 0xC0) && res_srtp && srtp && res_srtp->unprotect(
6694 srtp, rtcpheader, &len, 1 | (srtp_replay_protection << 1)) < 0) {
6695 return &ast_null_frame;
6696 }
6697
6698 packetwords = len / 4;
6699
6700 ast_debug_rtcp(2, "(%s) RTCP got report of %d bytes from %s\n",
6703
6704 /*
6705 * Validate the RTCP packet according to an adapted and slightly
6706 * modified RFC3550 validation algorithm.
6707 */
6708 if (packetwords < RTCP_HEADER_SSRC_LENGTH) {
6709 ast_debug_rtcp(2, "(%s) RTCP %p -- from %s: Frame size (%u words) is too short\n",
6711 transport_rtp, ast_sockaddr_stringify(addr), packetwords);
6712 return &ast_null_frame;
6713 }
6714 position = 0;
6715 first_word = ntohl(rtcpheader[position]);
6716 if ((first_word & RTCP_VALID_MASK) != RTCP_VALID_VALUE) {
6717 ast_debug_rtcp(2, "(%s) RTCP %p -- from %s: Failed first packet validity check\n",
6719 transport_rtp, ast_sockaddr_stringify(addr));
6720 return &ast_null_frame;
6721 }
6722 do {
6723 position += ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
6724 if (packetwords <= position) {
6725 break;
6726 }
6727 first_word = ntohl(rtcpheader[position]);
6728 } while ((first_word & RTCP_VERSION_MASK_SHIFTED) == RTCP_VERSION_SHIFTED);
6729 if (position != packetwords) {
6730 ast_debug_rtcp(2, "(%s) RTCP %p -- from %s: Failed packet version or length check\n",
6732 transport_rtp, ast_sockaddr_stringify(addr));
6733 return &ast_null_frame;
6734 }
6735
6736 /*
6737 * Note: RFC3605 points out that true NAT (vs NAPT) can cause RTCP
6738 * to have a different IP address and port than RTP. Otherwise, when
6739 * strictrtp is enabled we could reject RTCP packets not coming from
6740 * the learned RTP IP address if it is available.
6741 */
6742
6743 /*
6744 * strictrtp safety needs SSRC to match before we use the
6745 * sender's address for symmetrical RTP to send our RTCP
6746 * reports.
6747 *
6748 * If strictrtp is not enabled then claim to have already seen
6749 * a matching SSRC so we'll accept this packet's address for
6750 * symmetrical RTP.
6751 */
6752 ssrc_seen = transport_rtp->strict_rtp_state == STRICT_RTP_OPEN;
6753
6754 position = 0;
6755 while (position < packetwords) {
6756 unsigned int i;
6757 unsigned int pt;
6758 unsigned int rc;
6759 unsigned int ssrc;
6760 /*! True if the ssrc value we have is valid and not garbage because it doesn't exist. */
6761 unsigned int ssrc_valid;
6762 unsigned int length;
6763 unsigned int min_length;
6764 /*! Always use packet source SSRC to find the rtp instance unless explicitly told not to. */
6765 unsigned int use_packet_source = 1;
6766
6767 struct ast_json *message_blob;
6768 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report, NULL, ao2_cleanup);
6769 struct ast_rtp_instance *child;
6770 struct ast_rtp *rtp;
6771 struct ast_rtp_rtcp_feedback *feedback;
6772
6773 i = position;
6774 first_word = ntohl(rtcpheader[i]);
6775 pt = (first_word >> RTCP_PAYLOAD_TYPE_SHIFT) & RTCP_PAYLOAD_TYPE_MASK;
6776 rc = (first_word >> RTCP_REPORT_COUNT_SHIFT) & RTCP_REPORT_COUNT_MASK;
6777 /* RFC3550 says 'length' is the number of words in the packet - 1 */
6778 length = ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
6779
6780 /* Check expected RTCP packet record length */
6781 min_length = RTCP_HEADER_SSRC_LENGTH;
6782 switch (pt) {
6783 case RTCP_PT_SR:
6784 min_length += RTCP_SR_BLOCK_WORD_LENGTH;
6785 /* fall through */
6786 case RTCP_PT_RR:
6787 min_length += (rc * RTCP_RR_BLOCK_WORD_LENGTH);
6788 use_packet_source = 0;
6789 break;
6790 case RTCP_PT_FUR:
6791 break;
6792 case AST_RTP_RTCP_RTPFB:
6793 switch (rc) {
6795 min_length += RTCP_FB_NACK_BLOCK_WORD_LENGTH;
6796 break;
6797 default:
6798 break;
6799 }
6800 use_packet_source = 0;
6801 break;
6802 case RTCP_PT_PSFB:
6803 switch (rc) {
6805 min_length += RTCP_FB_REMB_BLOCK_WORD_LENGTH;
6806 break;
6807 default:
6808 break;
6809 }
6810 break;
6811 case RTCP_PT_SDES:
6812 case RTCP_PT_BYE:
6813 /*
6814 * There may not be a SSRC/CSRC present. The packet is
6815 * useless but still valid if it isn't present.
6816 *
6817 * We don't know what min_length should be so disable the check
6818 */
6819 min_length = length;
6820 break;
6821 default:
6822 ast_debug_rtcp(1, "(%p) RTCP %p -- from %s: %u(%s) skipping record\n",
6823 instance, transport_rtp, ast_sockaddr_stringify(addr), pt, rtcp_payload_type2str(pt));
6824 if (rtcp_debug_test_addr(addr)) {
6825 ast_verbose("\n");
6826 ast_verbose("RTCP from %s: %u(%s) skipping record\n",
6828 }
6829 position += length;
6830 continue;
6831 }
6832 if (length < min_length) {
6833 ast_debug_rtcp(1, "(%p) RTCP %p -- from %s: %u(%s) length field less than expected minimum. Min:%u Got:%u\n",
6834 instance, transport_rtp, ast_sockaddr_stringify(addr), pt, rtcp_payload_type2str(pt),
6835 min_length - 1, length - 1);
6836 return &ast_null_frame;
6837 }
6838
6839 /* Get the RTCP record SSRC if defined for the record */
6840 ssrc_valid = 1;
6841 switch (pt) {
6842 case RTCP_PT_SR:
6843 case RTCP_PT_RR:
6844 rtcp_report = ast_rtp_rtcp_report_alloc(rc);
6845 if (!rtcp_report) {
6846 return &ast_null_frame;
6847 }
6848 rtcp_report->reception_report_count = rc;
6849
6850 ssrc = ntohl(rtcpheader[i + 2]);
6851 rtcp_report->ssrc = ssrc;
6852 break;
6853 case RTCP_PT_FUR:
6854 case RTCP_PT_PSFB:
6855 ssrc = ntohl(rtcpheader[i + 1]);
6856 break;
6857 case AST_RTP_RTCP_RTPFB:
6858 ssrc = ntohl(rtcpheader[i + 2]);
6859 break;
6860 case RTCP_PT_SDES:
6861 case RTCP_PT_BYE:
6862 default:
6863 ssrc = 0;
6864 ssrc_valid = 0;
6865 break;
6866 }
6867
6868 if (rtcp_debug_test_addr(addr)) {
6869 const char *subtype = rtcp_payload_subtype2str(pt, rc);
6870
6871 ast_verbose("\n");
6872 ast_verbose("RTCP from %s\n", ast_sockaddr_stringify(addr));
6873 ast_verbose("PT: %u (%s)\n", pt, rtcp_payload_type2str(pt));
6874 if (subtype) {
6875 ast_verbose("Packet Subtype: %u (%s)\n", rc, subtype);
6876 } else {
6877 ast_verbose("Reception reports: %u\n", rc);
6878 }
6879 ast_verbose("SSRC of sender: %u\n", ssrc);
6880 }
6881
6882 /* Determine the appropriate instance for this */
6883 if (ssrc_valid) {
6884 /*
6885 * Depending on the payload type, either the packet source or media source
6886 * SSRC is used.
6887 */
6888 if (use_packet_source) {
6889 child = rtp_find_instance_by_packet_source_ssrc(transport, transport_rtp, ssrc);
6890 } else {
6891 child = rtp_find_instance_by_media_source_ssrc(transport, transport_rtp, ssrc);
6892 }
6893 if (child && child != transport) {
6894 /*
6895 * It is safe to hold the child lock while holding the parent lock.
6896 * We guarantee that the locking order is always parent->child or
6897 * that the child lock is not held when acquiring the parent lock.
6898 */
6899 ao2_lock(child);
6900 instance = child;
6901 rtp = ast_rtp_instance_get_data(instance);
6902 } else {
6903 /* The child is the parent! We don't need to unlock it. */
6904 child = NULL;
6905 rtp = transport_rtp;
6906 }
6907 } else {
6908 child = NULL;
6909 rtp = transport_rtp;
6910 }
6911
6912 if (ssrc_valid && rtp->themssrc_valid) {
6913 /*
6914 * If the SSRC is 1, we still need to handle RTCP since this could be a
6915 * special case. For example, if we have a unidirectional video stream, the
6916 * SSRC may be set to 1 by the browser (in the case of chromium), and requests
6917 * will still need to be processed so that video can flow as expected. This
6918 * should only be done for PLI and FUR, since there is not a way to get the
6919 * appropriate rtp instance when the SSRC is 1.
6920 */
6921 int exception = (ssrc == 1 && !((pt == RTCP_PT_PSFB && rc == AST_RTP_RTCP_FMT_PLI) || pt == RTCP_PT_FUR));
6922 if ((ssrc != rtp->themssrc && use_packet_source && ssrc != 1)
6923 || exception) {
6924 /*
6925 * Skip over this RTCP record as it does not contain the
6926 * correct SSRC. We should not act upon RTCP records
6927 * for a different stream.
6928 */
6929 position += length;
6930 ast_debug_rtcp(1, "(%p) RTCP %p -- from %s: Skipping record, received SSRC '%u' != expected '%u'\n",
6931 instance, rtp, ast_sockaddr_stringify(addr), ssrc, rtp->themssrc);
6932 if (child) {
6933 ao2_unlock(child);
6934 }
6935 continue;
6936 }
6937 ssrc_seen = 1;
6938 }
6939
6940 if (ssrc_seen && ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
6941 /* Send to whoever sent to us */
6942 if (ast_sockaddr_cmp(&rtp->rtcp->them, addr)) {
6943 ast_sockaddr_copy(&rtp->rtcp->them, addr);
6945 ast_debug(0, "(%p) RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
6946 instance, ast_sockaddr_stringify(addr));
6947 }
6948 }
6949 }
6950
6951 i += RTCP_HEADER_SSRC_LENGTH; /* Advance past header and ssrc */
6952 switch (pt) {
6953 case RTCP_PT_SR:
6954 gettimeofday(&rtp->rtcp->rxlsr, NULL);
6955 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16);
6956 rtp->rtcp->spc = ntohl(rtcpheader[i + 3]);
6957 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
6958
6959 rtcp_report->type = RTCP_PT_SR;
6960 rtcp_report->sender_information.packet_count = rtp->rtcp->spc;
6961 rtcp_report->sender_information.octet_count = rtp->rtcp->soc;
6962 ntp2timeval((unsigned int)ntohl(rtcpheader[i]),
6963 (unsigned int)ntohl(rtcpheader[i + 1]),
6964 &rtcp_report->sender_information.ntp_timestamp);
6965 rtcp_report->sender_information.rtp_timestamp = ntohl(rtcpheader[i + 2]);
6966 if (rtcp_debug_test_addr(addr)) {
6967 ast_verbose("NTP timestamp: %u.%06u\n",
6968 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
6969 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
6970 ast_verbose("RTP timestamp: %u\n", rtcp_report->sender_information.rtp_timestamp);
6971 ast_verbose("SPC: %u\tSOC: %u\n",
6972 rtcp_report->sender_information.packet_count,
6973 rtcp_report->sender_information.octet_count);
6974 }
6976 /* Intentional fall through */
6977 case RTCP_PT_RR:
6978 if (rtcp_report->type != RTCP_PT_SR) {
6979 rtcp_report->type = RTCP_PT_RR;
6980 }
6981
6982 if (rc > 0) {
6983 /* Don't handle multiple reception reports (rc > 1) yet */
6984 report_block = ast_calloc(1, sizeof(*report_block));
6985 if (!report_block) {
6986 if (child) {
6987 ao2_unlock(child);
6988 }
6989 return &ast_null_frame;
6990 }
6991 rtcp_report->report_block[0] = report_block;
6992 report_block->source_ssrc = ntohl(rtcpheader[i]);
6993 report_block->lost_count.packets = ntohl(rtcpheader[i + 1]) & 0x00ffffff;
6994 report_block->lost_count.fraction = ((ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24);
6995 report_block->highest_seq_no = ntohl(rtcpheader[i + 2]);
6996 report_block->ia_jitter = ntohl(rtcpheader[i + 3]);
6997 report_block->lsr = ntohl(rtcpheader[i + 4]);
6998 report_block->dlsr = ntohl(rtcpheader[i + 5]);
6999 if (report_block->lsr) {
7000 int skewed = update_rtt_stats(rtp, report_block->lsr, report_block->dlsr);
7001 if (skewed && rtcp_debug_test_addr(addr)) {
7002 struct timeval now;
7003 unsigned int lsr_now, lsw, msw;
7004 gettimeofday(&now, NULL);
7005 timeval2ntp(now, &msw, &lsw);
7006 lsr_now = (((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16));
7007 ast_verbose("Internal RTCP NTP clock skew detected: "
7008 "lsr=%u, now=%u, dlsr=%u (%u:%03ums), "
7009 "diff=%u\n",
7010 report_block->lsr, lsr_now, report_block->dlsr, report_block->dlsr / 65536,
7011 (report_block->dlsr % 65536) * 1000 / 65536,
7012 report_block->dlsr - (lsr_now - report_block->lsr));
7013 }
7014 }
7015 update_jitter_stats(rtp, report_block->ia_jitter);
7016 update_lost_stats(rtp, report_block->lost_count.packets);
7017 /*
7018 * update_reported_mes_stats must be called AFTER
7019 * update_rtt_stats, update_jitter_stats and
7020 * update_lost_stats.
7021 */
7023
7024 if (rtcp_debug_test_addr(addr)) {
7025 int rate = ast_rtp_get_rate(rtp->f.subclass.format);
7026
7027 ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
7028 ast_verbose(" Packets lost so far: %u\n", report_block->lost_count.packets);
7029 ast_verbose(" Highest sequence number: %u\n", report_block->highest_seq_no & 0x0000ffff);
7030 ast_verbose(" Sequence number cycles: %u\n", report_block->highest_seq_no >> 16);
7031 ast_verbose(" Interarrival jitter (samp): %u\n", report_block->ia_jitter);
7032 ast_verbose(" Interarrival jitter (secs): %.6f\n", ast_samp2sec(report_block->ia_jitter, rate));
7033 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long)(report_block->lsr) >> 16,((unsigned long)(report_block->lsr) << 16) * 4096);
7034 ast_verbose(" DLSR: %4.4f (sec)\n",(double)report_block->dlsr / 65536.0);
7035 ast_verbose(" RTT: %4.4f(sec)\n", rtp->rtcp->rtt);
7036 ast_verbose(" MES: %4.1f\n", rtp->rtcp->reported_mes);
7037 }
7038 }
7039 /* If and when we handle more than one report block, this should occur outside
7040 * this loop.
7041 */
7042
7043 message_blob = ast_json_pack("{s: s, s: s, s: f, s: f}",
7044 "from", ast_sockaddr_stringify(addr),
7045 "to", transport_rtp->rtcp->local_addr_str,
7046 "rtt", rtp->rtcp->rtt,
7047 "mes", rtp->rtcp->reported_mes);
7049 rtcp_report,
7050 message_blob);
7051 ast_json_unref(message_blob);
7052
7053 /* Return an AST_FRAME_RTCP frame with the ast_rtp_rtcp_report
7054 * object as a its data */
7055 transport_rtp->f.frametype = AST_FRAME_RTCP;
7056 transport_rtp->f.subclass.integer = pt;
7057 transport_rtp->f.data.ptr = rtp->rtcp->frame_buf + AST_FRIENDLY_OFFSET;
7058 memcpy(transport_rtp->f.data.ptr, rtcp_report, sizeof(struct ast_rtp_rtcp_report));
7059 transport_rtp->f.datalen = sizeof(struct ast_rtp_rtcp_report);
7060 if (rc > 0) {
7061 /* There's always a single report block stored, here */
7062 struct ast_rtp_rtcp_report *rtcp_report2;
7063 report_block = transport_rtp->f.data.ptr + transport_rtp->f.datalen + sizeof(struct ast_rtp_rtcp_report_block *);
7064 memcpy(report_block, rtcp_report->report_block[0], sizeof(struct ast_rtp_rtcp_report_block));
7065 rtcp_report2 = (struct ast_rtp_rtcp_report *)transport_rtp->f.data.ptr;
7066 rtcp_report2->report_block[0] = report_block;
7067 transport_rtp->f.datalen += sizeof(struct ast_rtp_rtcp_report_block);
7068 }
7069 transport_rtp->f.offset = AST_FRIENDLY_OFFSET;
7070 transport_rtp->f.samples = 0;
7071 transport_rtp->f.mallocd = 0;
7072 transport_rtp->f.delivery.tv_sec = 0;
7073 transport_rtp->f.delivery.tv_usec = 0;
7074 transport_rtp->f.src = "RTP";
7075 transport_rtp->f.stream_num = rtp->stream_num;
7076 f = &transport_rtp->f;
7077 break;
7078 case AST_RTP_RTCP_RTPFB:
7079 switch (rc) {
7081 /* If retransmissions are not enabled ignore this message */
7082 if (!rtp->send_buffer) {
7083 break;
7084 }
7085
7086 if (rtcp_debug_test_addr(addr)) {
7087 ast_verbose("Received generic RTCP NACK message\n");
7088 }
7089
7090 ast_rtp_rtcp_handle_nack(instance, rtcpheader, position, length);
7091 break;
7092 default:
7093 break;
7094 }
7095 break;
7096 case RTCP_PT_FUR:
7097 /* Handle RTCP FUR as FIR by setting the format to 4 */
7099 case RTCP_PT_PSFB:
7100 switch (rc) {
7103 if (rtcp_debug_test_addr(addr)) {
7104 ast_verbose("Received an RTCP Fast Update Request\n");
7105 }
7106 transport_rtp->f.frametype = AST_FRAME_CONTROL;
7107 transport_rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
7108 transport_rtp->f.datalen = 0;
7109 transport_rtp->f.samples = 0;
7110 transport_rtp->f.mallocd = 0;
7111 transport_rtp->f.src = "RTP";
7112 f = &transport_rtp->f;
7113 break;
7115 /* If REMB support is not enabled ignore this message */
7117 break;
7118 }
7119
7120 if (rtcp_debug_test_addr(addr)) {
7121 ast_verbose("Received REMB report\n");
7122 }
7123 transport_rtp->f.frametype = AST_FRAME_RTCP;
7124 transport_rtp->f.subclass.integer = pt;
7125 transport_rtp->f.stream_num = rtp->stream_num;
7126 transport_rtp->f.data.ptr = rtp->rtcp->frame_buf + AST_FRIENDLY_OFFSET;
7127 feedback = transport_rtp->f.data.ptr;
7128 feedback->fmt = rc;
7129
7130 /* We don't actually care about the SSRC information in the feedback message */
7131 first_word = ntohl(rtcpheader[i + 2]);
7132 feedback->remb.br_exp = (first_word >> 18) & ((1 << 6) - 1);
7133 feedback->remb.br_mantissa = first_word & ((1 << 18) - 1);
7134
7135 transport_rtp->f.datalen = sizeof(struct ast_rtp_rtcp_feedback);
7136 transport_rtp->f.offset = AST_FRIENDLY_OFFSET;
7137 transport_rtp->f.samples = 0;
7138 transport_rtp->f.mallocd = 0;
7139 transport_rtp->f.delivery.tv_sec = 0;
7140 transport_rtp->f.delivery.tv_usec = 0;
7141 transport_rtp->f.src = "RTP";
7142 f = &transport_rtp->f;
7143 break;
7144 default:
7145 break;
7146 }
7147 break;
7148 case RTCP_PT_SDES:
7149 if (rtcp_debug_test_addr(addr)) {
7150 ast_verbose("Received an SDES from %s\n",
7152 }
7153#ifdef TEST_FRAMEWORK
7154 if ((test_engine = ast_rtp_instance_get_test(instance))) {
7155 test_engine->sdes_received = 1;
7156 }
7157#endif
7158 break;
7159 case RTCP_PT_BYE:
7160 if (rtcp_debug_test_addr(addr)) {
7161 ast_verbose("Received a BYE from %s\n",
7163 }
7164 break;
7165 default:
7166 break;
7167 }
7168 position += length;
7169 rtp->rtcp->rtcp_info = 1;
7170
7171 if (child) {
7172 ao2_unlock(child);
7173 }
7174 }
7175
7176 return f;
7177}
7178
7179/*! \pre instance is locked */
7180static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
7181{
7182 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
7183 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, 1);
7184 struct ast_sockaddr addr;
7185 unsigned char rtcpdata[8192 + AST_FRIENDLY_OFFSET];
7186 unsigned char *read_area = rtcpdata + AST_FRIENDLY_OFFSET;
7187 size_t read_area_size = sizeof(rtcpdata) - AST_FRIENDLY_OFFSET;
7188 int res;
7189
7190 /* Read in RTCP data from the socket */
7191 if ((res = rtcp_recvfrom(instance, read_area, read_area_size,
7192 0, &addr)) < 0) {
7193 if (res == RTP_DTLS_ESTABLISHED) {
7196 return &rtp->f;
7197 }
7198
7199 ast_assert(errno != EBADF);
7200 if (errno != EAGAIN) {
7201 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n",
7202 (errno) ? strerror(errno) : "Unspecified");
7203 return NULL;
7204 }
7205 return &ast_null_frame;
7206 }
7207
7208 /* If this was handled by the ICE session don't do anything further */
7209 if (!res) {
7210 return &ast_null_frame;
7211 }
7212
7213 if (!*read_area) {
7214 struct sockaddr_in addr_tmp;
7215 struct ast_sockaddr addr_v4;
7216
7217 if (ast_sockaddr_is_ipv4(&addr)) {
7218 ast_sockaddr_to_sin(&addr, &addr_tmp);
7219 } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
7220 ast_debug_stun(2, "(%p) STUN using IPv6 mapped address %s\n",
7221 instance, ast_sockaddr_stringify(&addr));
7222 ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
7223 } else {
7224 ast_debug_stun(2, "(%p) STUN cannot do for non IPv4 address %s\n",
7225 instance, ast_sockaddr_stringify(&addr));
7226 return &ast_null_frame;
7227 }
7228 if ((ast_stun_handle_packet(rtp->rtcp->s, &addr_tmp, read_area, res, NULL, NULL) == AST_STUN_ACCEPT)) {
7229 ast_sockaddr_from_sin(&addr, &addr_tmp);
7230 ast_sockaddr_copy(&rtp->rtcp->them, &addr);
7231 }
7232 return &ast_null_frame;
7233 }
7234
7235 return ast_rtcp_interpret(instance, srtp, read_area, res, &addr);
7236}
7237
7238/*! \pre instance is locked */
7239static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance,
7240 struct ast_rtp_instance *instance1, unsigned int *rtpheader, int len, int hdrlen)
7241{
7242 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
7243 struct ast_rtp *bridged;
7244 int res = 0, payload = 0, bridged_payload = 0, mark;
7245 RAII_VAR(struct ast_rtp_payload_type *, payload_type, NULL, ao2_cleanup);
7246 int reconstruct = ntohl(rtpheader[0]);
7247 struct ast_sockaddr remote_address = { {0,} };
7248 int ice;
7249 unsigned int timestamp = ntohl(rtpheader[1]);
7250
7251 /* Get fields from packet */
7252 payload = (reconstruct & 0x7f0000) >> 16;
7253 mark = (reconstruct & 0x800000) >> 23;
7254
7255 /* Check what the payload value should be */
7256 payload_type = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payload);
7257 if (!payload_type) {
7258 return -1;
7259 }
7260
7261 /* Otherwise adjust bridged payload to match */
7263 payload_type->asterisk_format, payload_type->format, payload_type->rtp_code, payload_type->sample_rate);
7264
7265 /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged. Bail. */
7266 if (bridged_payload < 0) {
7267 return -1;
7268 }
7269
7270 /* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
7271 if (ast_rtp_codecs_find_payload_code(ast_rtp_instance_get_codecs(instance1), bridged_payload) == -1) {
7272 ast_debug_rtp(1, "(%p, %p) RTP unsupported payload type received\n", instance, instance1);
7273 return -1;
7274 }
7275
7276 /*
7277 * Even if we are no longer in dtmf, we could still be receiving
7278 * re-transmissions of the last dtmf end still. Feed those to the
7279 * core so they can be filtered accordingly.
7280 */
7281 if (rtp->last_end_timestamp.is_set && rtp->last_end_timestamp.ts == timestamp) {
7282 ast_debug_rtp(1, "(%p, %p) RTP feeding packet with duplicate timestamp to core\n", instance, instance1);
7283 return -1;
7284 }
7285
7286 if (payload_type->asterisk_format) {
7287 ao2_replace(rtp->lastrxformat, payload_type->format);
7288 }
7289
7290 /*
7291 * We have now determined that we need to send the RTP packet
7292 * out the bridged instance to do local bridging so we must unlock
7293 * the receiving instance to prevent deadlock with the bridged
7294 * instance.
7295 *
7296 * Technically we should grab a ref to instance1 so it won't go
7297 * away on us. However, we should be safe because the bridged
7298 * instance won't change without both channels involved being
7299 * locked and we currently have the channel lock for the receiving
7300 * instance.
7301 */
7302 ao2_unlock(instance);
7303 ao2_lock(instance1);
7304
7305 /*
7306 * Get the peer rtp pointer now to emphasize that using it
7307 * must happen while instance1 is locked.
7308 */
7309 bridged = ast_rtp_instance_get_data(instance1);
7310
7311
7312 /* If bridged peer is in dtmf, feed all packets to core until it finishes to avoid infinite dtmf */
7313 if (bridged->sending_digit) {
7314 ast_debug_rtp(1, "(%p, %p) RTP Feeding packet to core until DTMF finishes\n", instance, instance1);
7315 ao2_unlock(instance1);
7316 ao2_lock(instance);
7317 return -1;
7318 }
7319
7320 if (payload_type->asterisk_format) {
7321 /*
7322 * If bridged peer has already received rtp, perform the asymmetric codec check
7323 * if that feature has been activated
7324 */
7325 if (!bridged->asymmetric_codec
7326 && bridged->lastrxformat != ast_format_none
7327 && ast_format_cmp(payload_type->format, bridged->lastrxformat) == AST_FORMAT_CMP_NOT_EQUAL) {
7328 ast_debug_rtp(1, "(%p, %p) RTP asymmetric RTP codecs detected (TX: %s, RX: %s) sending frame to core\n",
7329 instance, instance1, ast_format_get_name(payload_type->format),
7331 ao2_unlock(instance1);
7332 ao2_lock(instance);
7333 return -1;
7334 }
7335
7336 ao2_replace(bridged->lasttxformat, payload_type->format);
7337 }
7338
7339 ast_rtp_instance_get_remote_address(instance1, &remote_address);
7340
7341 if (ast_sockaddr_isnull(&remote_address)) {
7342 ast_debug_rtp(5, "(%p, %p) RTP remote address is null, most likely RTP has been stopped\n",
7343 instance, instance1);
7344 ao2_unlock(instance1);
7345 ao2_lock(instance);
7346 return 0;
7347 }
7348
7349 /* If the marker bit has been explicitly set turn it on */
7350 if (ast_test_flag(bridged, FLAG_NEED_MARKER_BIT)) {
7351 mark = 1;
7353 }
7354
7355 /* Set the marker bit for the first local bridged packet which has the first bridged peer's SSRC. */
7357 mark = 1;
7359 }
7360
7361 /* Reconstruct part of the packet */
7362 reconstruct &= 0xFF80FFFF;
7363 reconstruct |= (bridged_payload << 16);
7364 reconstruct |= (mark << 23);
7365 rtpheader[0] = htonl(reconstruct);
7366
7367 if (mark) {
7368 /* make this rtp instance aware of the new ssrc it is sending */
7369 bridged->ssrc = ntohl(rtpheader[2]);
7370 }
7371
7372 /* Send the packet back out */
7373 res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address, &ice);
7374 if (res < 0) {
7377 "RTP Transmission error of packet to %s: %s\n",
7378 ast_sockaddr_stringify(&remote_address),
7379 strerror(errno));
7383 "RTP NAT: Can't write RTP to private "
7384 "address %s, waiting for other end to "
7385 "send audio...\n",
7386 ast_sockaddr_stringify(&remote_address));
7387 }
7389 }
7390 ao2_unlock(instance1);
7391 ao2_lock(instance);
7392 return 0;
7393 }
7394
7395 if (rtp_debug_test_addr(&remote_address)) {
7396 ast_verbose("Sent RTP P2P packet to %s%s (type %-2.2d, len %-6.6d)\n",
7397 ast_sockaddr_stringify(&remote_address),
7398 ice ? " (via ICE)" : "",
7399 bridged_payload, len - hdrlen);
7400 }
7401
7402 ao2_unlock(instance1);
7403 ao2_lock(instance);
7404 return 0;
7405}
7406
7407static void rtp_instance_unlock(struct ast_rtp_instance *instance)
7408{
7409 if (instance) {
7410 ao2_unlock(instance);
7411 }
7412}
7413
7419
7420static void rtp_transport_wide_cc_feedback_status_vector_append(unsigned char *rtcpheader, int *packet_len, int *status_vector_chunk_bits,
7421 uint16_t *status_vector_chunk, int status)
7422{
7423 /* Appending this status will use up 2 bits */
7424 *status_vector_chunk_bits -= 2;
7425
7426 /* We calculate which bits we want to update the status of. Since a status vector
7427 * is 16 bits we take away 2 (for the header), and then we take away any that have
7428 * already been used.
7429 */
7430 *status_vector_chunk |= (status << (16 - 2 - (14 - *status_vector_chunk_bits)));
7431
7432 /* If there are still bits available we can return early */
7433 if (*status_vector_chunk_bits) {
7434 return;
7435 }
7436
7437 /* Otherwise we have to place this chunk into the packet */
7438 put_unaligned_uint16(rtcpheader + *packet_len, htons(*status_vector_chunk));
7439 *status_vector_chunk_bits = 14;
7440
7441 /* The first bit being 1 indicates that this is a status vector chunk and the second
7442 * bit being 1 indicates that we are using 2 bits to represent each status for a
7443 * packet.
7444 */
7445 *status_vector_chunk = (1 << 15) | (1 << 14);
7446 *packet_len += 2;
7447}
7448
7449static void rtp_transport_wide_cc_feedback_status_append(unsigned char *rtcpheader, int *packet_len, int *status_vector_chunk_bits,
7450 uint16_t *status_vector_chunk, int *run_length_chunk_count, int *run_length_chunk_status, int status)
7451{
7452 if (*run_length_chunk_status != status) {
7453 while (*run_length_chunk_count > 0 && *run_length_chunk_count < 8) {
7454 /* Realistically it only makes sense to use a run length chunk if there were 8 or more
7455 * consecutive packets of the same type, otherwise we could end up making the packet larger
7456 * if we have lots of small blocks of the same type. To help with this we backfill the status
7457 * vector (since it always represents 7 packets). Best case we end up with only that single
7458 * status vector and the rest are run length chunks.
7459 */
7460 rtp_transport_wide_cc_feedback_status_vector_append(rtcpheader, packet_len, status_vector_chunk_bits,
7461 status_vector_chunk, *run_length_chunk_status);
7462 *run_length_chunk_count -= 1;
7463 }
7464
7465 if (*run_length_chunk_count) {
7466 /* There is a run length chunk which needs to be written out */
7467 put_unaligned_uint16(rtcpheader + *packet_len, htons((0 << 15) | (*run_length_chunk_status << 13) | *run_length_chunk_count));
7468 *packet_len += 2;
7469 }
7470
7471 /* In all cases the run length chunk has to be reset */
7472 *run_length_chunk_count = 0;
7473 *run_length_chunk_status = -1;
7474
7475 if (*status_vector_chunk_bits == 14) {
7476 /* We aren't in the middle of a status vector so we can try for a run length chunk */
7477 *run_length_chunk_status = status;
7478 *run_length_chunk_count = 1;
7479 } else {
7480 /* We're doing a status vector so populate it accordingly */
7481 rtp_transport_wide_cc_feedback_status_vector_append(rtcpheader, packet_len, status_vector_chunk_bits,
7482 status_vector_chunk, status);
7483 }
7484 } else {
7485 /* This is easy, the run length chunk count can just get bumped up */
7486 *run_length_chunk_count += 1;
7487 }
7488}
7489
7490static int rtp_transport_wide_cc_feedback_produce(const void *data)
7491{
7492 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
7493 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
7494 unsigned char *rtcpheader;
7495 char bdata[1024];
7496 struct rtp_transport_wide_cc_packet_statistics *first_packet;
7497 struct rtp_transport_wide_cc_packet_statistics *previous_packet;
7498 int i;
7499 int status_vector_chunk_bits = 14;
7500 uint16_t status_vector_chunk = (1 << 15) | (1 << 14);
7501 int run_length_chunk_count = 0;
7502 int run_length_chunk_status = -1;
7503 int packet_len = 20;
7504 int delta_len = 0;
7505 int packet_count = 0;
7506 unsigned int received_msw;
7507 unsigned int received_lsw;
7508 struct ast_sockaddr remote_address = { { 0, } };
7509 int res;
7510 int ice;
7511 unsigned int large_delta_count = 0;
7512 unsigned int small_delta_count = 0;
7513 unsigned int lost_count = 0;
7514
7515 if (!rtp || !rtp->rtcp || rtp->transport_wide_cc.schedid == -1) {
7516 ao2_ref(instance, -1);
7517 return 0;
7518 }
7519
7520 ao2_lock(instance);
7521
7522 /* If no packets have been received then do nothing */
7524 ao2_unlock(instance);
7525 return 1000;
7526 }
7527
7528 rtcpheader = (unsigned char *)bdata;
7529
7530 /* The first packet in the vector acts as our base sequence number and reference time */
7532 previous_packet = first_packet;
7533
7534 /* We go through each packet that we have statistics for, adding it either to a status
7535 * vector chunk or a run length chunk. The code tries to be as efficient as possible to
7536 * reduce packet size and will favor run length chunks when it makes sense.
7537 */
7538 for (i = 0; i < AST_VECTOR_SIZE(&rtp->transport_wide_cc.packet_statistics); ++i) {
7540 int lost = 0;
7541 int res = 0;
7542
7544
7545 packet_count++;
7546
7547 if (first_packet != statistics) {
7548 /* The vector stores statistics in a sorted fashion based on the sequence
7549 * number. This ensures we can detect any packets that have been lost/not
7550 * received by comparing the sequence numbers.
7551 */
7552 lost = statistics->seqno - (previous_packet->seqno + 1);
7553 lost_count += lost;
7554 }
7555
7556 while (lost) {
7557 /* We append a not received status until all the lost packets have been accounted for */
7558 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7559 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 0);
7560 packet_count++;
7561
7562 /* If there is no more room left for storing packets stop now, we leave 20
7563 * extra bits at the end just in case.
7564 */
7565 if (packet_len + delta_len + 20 > sizeof(bdata)) {
7566 res = -1;
7567 break;
7568 }
7569
7570 lost--;
7571 }
7572
7573 /* If the lost packet appending bailed out because we have no more space, then exit here too */
7574 if (res) {
7575 break;
7576 }
7577
7578 /* Per the spec the delta is in increments of 250 */
7579 statistics->delta = ast_tvdiff_us(statistics->received, previous_packet->received) / 250;
7580
7581 /* Based on the delta determine the status of this packet */
7582 if (statistics->delta < 0 || statistics->delta > 127) {
7583 /* Large or negative delta */
7584 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7585 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 2);
7586 delta_len += 2;
7587 large_delta_count++;
7588 } else {
7589 /* Small delta */
7590 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7591 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 1);
7592 delta_len += 1;
7593 small_delta_count++;
7594 }
7595
7596 previous_packet = statistics;
7597
7598 /* If there is no more room left in the packet stop handling of any subsequent packets */
7599 if (packet_len + delta_len + 20 > sizeof(bdata)) {
7600 break;
7601 }
7602 }
7603
7604 if (status_vector_chunk_bits != 14) {
7605 /* If the status vector chunk has packets in it then place it in the RTCP packet */
7606 put_unaligned_uint16(rtcpheader + packet_len, htons(status_vector_chunk));
7607 packet_len += 2;
7608 } else if (run_length_chunk_count) {
7609 /* If there is a run length chunk in progress then place it in the RTCP packet */
7610 put_unaligned_uint16(rtcpheader + packet_len, htons((0 << 15) | (run_length_chunk_status << 13) | run_length_chunk_count));
7611 packet_len += 2;
7612 }
7613
7614 /* We iterate again to build delta chunks */
7615 for (i = 0; i < AST_VECTOR_SIZE(&rtp->transport_wide_cc.packet_statistics); ++i) {
7617
7619
7620 if (statistics->delta < 0 || statistics->delta > 127) {
7621 /* We need 2 bytes to store this delta */
7622 put_unaligned_uint16(rtcpheader + packet_len, htons(statistics->delta));
7623 packet_len += 2;
7624 } else {
7625 /* We can store this delta in 1 byte */
7626 rtcpheader[packet_len] = statistics->delta;
7627 packet_len += 1;
7628 }
7629
7630 /* If this is the last packet handled by the run length chunk or status vector chunk code
7631 * then we can go no further.
7632 */
7633 if (statistics == previous_packet) {
7634 break;
7635 }
7636 }
7637
7638 /* Zero pad the end of the packet */
7639 while (packet_len % 4) {
7640 rtcpheader[packet_len++] = 0;
7641 }
7642
7643 /* Add the general RTCP header information */
7644 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (AST_RTP_RTCP_FMT_TRANSPORT_WIDE_CC << 24)
7645 | (AST_RTP_RTCP_RTPFB << 16) | ((packet_len / 4) - 1)));
7646 put_unaligned_uint32(rtcpheader + 4, htonl(rtp->ssrc));
7647 put_unaligned_uint32(rtcpheader + 8, htonl(rtp->themssrc));
7648
7649 /* Add the transport-cc specific header information */
7650 put_unaligned_uint32(rtcpheader + 12, htonl((first_packet->seqno << 16) | packet_count));
7651
7652 timeval2ntp(first_packet->received, &received_msw, &received_lsw);
7653 put_unaligned_time24(rtcpheader + 16, received_msw, received_lsw);
7654 rtcpheader[19] = rtp->transport_wide_cc.feedback_count;
7655
7656 /* The packet is now fully constructed so send it out */
7657 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
7658
7659 ast_debug_rtcp(2, "(%p) RTCP sending transport-cc feedback packet of size '%d' on '%s' with packet count of %d (small = %d, large = %d, lost = %d)\n",
7660 instance, packet_len, ast_rtp_instance_get_channel_id(instance), packet_count, small_delta_count, large_delta_count, lost_count);
7661
7662 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, packet_len, 0, &remote_address, &ice);
7663 if (res < 0) {
7664 ast_log(LOG_ERROR, "RTCP transport-cc feedback error to %s due to %s\n",
7665 ast_sockaddr_stringify(&remote_address), strerror(errno));
7666 }
7667
7669
7671
7672 ao2_unlock(instance);
7673
7674 return 1000;
7675}
7676
7677static void rtp_instance_parse_transport_wide_cc(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
7678 unsigned char *data, int len)
7679{
7680 uint16_t *seqno = (uint16_t *)data;
7682 struct ast_rtp_instance *transport = rtp->bundled ? rtp->bundled : instance;
7683 struct ast_rtp *transport_rtp = ast_rtp_instance_get_data(transport);
7684
7685 /* If the sequence number has cycled over then record it as such */
7686 if (((int)transport_rtp->transport_wide_cc.last_seqno - (int)ntohs(*seqno)) > 100) {
7687 transport_rtp->transport_wide_cc.cycles += RTP_SEQ_MOD;
7688 }
7689
7690 /* Populate the statistics information for this packet */
7691 statistics.seqno = transport_rtp->transport_wide_cc.cycles + ntohs(*seqno);
7692 statistics.received = ast_tvnow();
7693
7694 /* We allow at a maximum 1000 packet statistics in play at a time, if we hit the
7695 * limit we give up and start fresh.
7696 */
7697 if (AST_VECTOR_SIZE(&transport_rtp->transport_wide_cc.packet_statistics) > 1000) {
7699 }
7700
7701 if (!AST_VECTOR_SIZE(&transport_rtp->transport_wide_cc.packet_statistics) ||
7702 statistics.seqno > transport_rtp->transport_wide_cc.last_extended_seqno) {
7703 /* This is the expected path */
7705 return;
7706 }
7707
7708 transport_rtp->transport_wide_cc.last_extended_seqno = statistics.seqno;
7709 transport_rtp->transport_wide_cc.last_seqno = ntohs(*seqno);
7710 } else {
7711 /* This packet was out of order, so reorder it within the vector accordingly */
7714 return;
7715 }
7716 }
7717
7718 /* If we have not yet scheduled the periodic sending of feedback for this transport then do so */
7719 if (transport_rtp->transport_wide_cc.schedid < 0 && transport_rtp->rtcp) {
7720 ast_debug_rtcp(1, "(%p) RTCP starting transport-cc feedback transmission on RTP instance '%p'\n", instance, transport);
7721 ao2_ref(transport, +1);
7722 transport_rtp->transport_wide_cc.schedid = ast_sched_add(rtp->sched, 1000,
7724 if (transport_rtp->transport_wide_cc.schedid < 0) {
7725 ao2_ref(transport, -1);
7726 ast_log(LOG_WARNING, "Scheduling RTCP transport-cc feedback transmission failed on RTP instance '%p'\n",
7727 transport);
7728 }
7729 }
7730}
7731
7732static void rtp_instance_parse_extmap_extensions(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
7733 unsigned char *extension, int len)
7734{
7735 int transport_wide_cc_id = ast_rtp_instance_extmap_get_id(instance, AST_RTP_EXTENSION_TRANSPORT_WIDE_CC);
7736 int pos = 0;
7737
7738 /* We currently only care about the transport-cc extension, so if that's not negotiated then do nothing */
7739 if (transport_wide_cc_id == -1) {
7740 return;
7741 }
7742
7743 /* Only while we do not exceed available extension data do we continue */
7744 while (pos < len) {
7745 int id = extension[pos] >> 4;
7746 int extension_len = (extension[pos] & 0xF) + 1;
7747
7748 /* We've handled the first byte as it contains the extension id and length, so always
7749 * skip ahead now
7750 */
7751 pos += 1;
7752
7753 if (id == 0) {
7754 /* From the RFC:
7755 * In both forms, padding bytes have the value of 0 (zero). They may be
7756 * placed between extension elements, if desired for alignment, or after
7757 * the last extension element, if needed for padding. A padding byte
7758 * does not supply the ID of an element, nor the length field. When a
7759 * padding byte is found, it is ignored and the parser moves on to
7760 * interpreting the next byte.
7761 */
7762 continue;
7763 } else if (id == 15) {
7764 /* From the RFC:
7765 * The local identifier value 15 is reserved for future extension and
7766 * MUST NOT be used as an identifier. If the ID value 15 is
7767 * encountered, its length field should be ignored, processing of the
7768 * entire extension should terminate at that point, and only the
7769 * extension elements present prior to the element with ID 15
7770 * considered.
7771 */
7772 break;
7773 } else if ((pos + extension_len) > len) {
7774 /* The extension is corrupted and is stating that it contains more data than is
7775 * available in the extensions data.
7776 */
7777 break;
7778 }
7779
7780 /* If this is transport-cc then we need to parse it further */
7781 if (id == transport_wide_cc_id) {
7782 rtp_instance_parse_transport_wide_cc(instance, rtp, extension + pos, extension_len);
7783 }
7784
7785 /* Skip ahead to the next extension */
7786 pos += extension_len;
7787 }
7788}
7789
7790static struct ast_frame *ast_rtp_interpret(struct ast_rtp_instance *instance, struct ast_srtp *srtp,
7791 const struct ast_sockaddr *remote_address, unsigned char *read_area, int length, int prev_seqno,
7792 unsigned int bundled)
7793{
7794 unsigned int *rtpheader = (unsigned int*)(read_area);
7795 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
7796 struct ast_rtp_instance *instance1;
7797 int res = length, hdrlen = 12, ssrc, seqno, payloadtype, padding, mark, ext, cc;
7798 unsigned int timestamp;
7799 RAII_VAR(struct ast_rtp_payload_type *, payload, NULL, ao2_cleanup);
7800 struct frame_list frames;
7801
7802 /* If this payload is encrypted then decrypt it using the given SRTP instance */
7803 if ((*read_area & 0xC0) && res_srtp && srtp && res_srtp->unprotect(
7804 srtp, read_area, &res, 0 | (srtp_replay_protection << 1)) < 0) {
7805 return &ast_null_frame;
7806 }
7807
7808 /* If we are currently sending DTMF to the remote party send a continuation packet */
7809 if (rtp->sending_digit) {
7810 ast_rtp_dtmf_continuation(instance);
7811 }
7812
7813 /* Pull out the various other fields we will need */
7814 ssrc = ntohl(rtpheader[2]);
7815 seqno = ntohl(rtpheader[0]);
7816 payloadtype = (seqno & 0x7f0000) >> 16;
7817 padding = seqno & (1 << 29);
7818 mark = seqno & (1 << 23);
7819 ext = seqno & (1 << 28);
7820 cc = (seqno & 0xF000000) >> 24;
7821 seqno &= 0xffff;
7822 timestamp = ntohl(rtpheader[1]);
7823
7825
7826 /* Remove any padding bytes that may be present */
7827 if (padding) {
7828 res -= read_area[res - 1];
7829 }
7830
7831 /* Skip over any CSRC fields */
7832 if (cc) {
7833 hdrlen += cc * 4;
7834 }
7835
7836 /* Look for any RTP extensions, currently we do not support any */
7837 if (ext) {
7838 int extensions_size = (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
7839 unsigned int profile;
7840 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
7841
7842 if (profile == 0xbede) {
7843 /* We skip over the first 4 bytes as they are just for the one byte extension header */
7844 rtp_instance_parse_extmap_extensions(instance, rtp, read_area + hdrlen + 4, extensions_size);
7845 } else if (DEBUG_ATLEAST(1)) {
7846 if (profile == 0x505a) {
7847 ast_log(LOG_DEBUG, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
7848 } else {
7849 /* SDP negotiated RTP extensions can not currently be output in logging */
7850 ast_log(LOG_DEBUG, "Found unknown RTP Extensions %x\n", profile);
7851 }
7852 }
7853
7854 hdrlen += extensions_size;
7855 hdrlen += 4;
7856 }
7857
7858 /* Make sure after we potentially mucked with the header length that it is once again valid */
7859 if (res < hdrlen) {
7860 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
7862 }
7863
7864 /* Only non-bundled instances can change/learn the remote's SSRC implicitly. */
7865 if (!bundled) {
7866 /* Force a marker bit and change SSRC if the SSRC changes */
7867 if (rtp->themssrc_valid && rtp->themssrc != ssrc) {
7868 struct ast_frame *f, srcupdate = {
7871 };
7872
7873 if (!mark) {
7875 ast_debug(0, "(%p) RTP forcing Marker bit, because SSRC has changed\n", instance);
7876 }
7877 mark = 1;
7878 }
7879
7880 f = ast_frisolate(&srcupdate);
7882
7883 rtp->seedrxseqno = 0;
7884 rtp->rxcount = 0;
7885 rtp->rxoctetcount = 0;
7886 rtp->cycles = 0;
7887 prev_seqno = 0;
7888 rtp->last_seqno = 0;
7889 rtp->last_end_timestamp.ts = 0;
7890 rtp->last_end_timestamp.is_set = 0;
7891 if (rtp->rtcp) {
7892 rtp->rtcp->expected_prior = 0;
7893 rtp->rtcp->received_prior = 0;
7894 }
7895 }
7896
7897 rtp->themssrc = ssrc; /* Record their SSRC to put in future RR */
7898 rtp->themssrc_valid = 1;
7899 }
7900
7901 rtp->rxcount++;
7902 rtp->rxoctetcount += (res - hdrlen);
7903 if (rtp->rxcount == 1) {
7904 rtp->seedrxseqno = seqno;
7905 }
7906
7907 /* Do not schedule RR if RTCP isn't run */
7908 if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 0) {
7909 /* Schedule transmission of Receiver Report */
7910 ao2_ref(instance, +1);
7912 if (rtp->rtcp->schedid < 0) {
7913 ao2_ref(instance, -1);
7914 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
7915 }
7916 }
7917 if ((int)prev_seqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
7918 rtp->cycles += RTP_SEQ_MOD;
7919
7920 /* If we are directly bridged to another instance send the audio directly out,
7921 * but only after updating core information about the received traffic so that
7922 * outgoing RTCP reflects it.
7923 */
7924 instance1 = ast_rtp_instance_get_bridged(instance);
7925 if (instance1
7926 && !bridge_p2p_rtp_write(instance, instance1, rtpheader, res, hdrlen)) {
7927 struct timeval rxtime;
7928 struct ast_frame *f;
7929
7930 /* Update statistics for jitter so they are correct in RTCP */
7931 calc_rxstamp_and_jitter(&rxtime, rtp, timestamp, mark);
7932
7933
7934 /* When doing P2P we don't need to raise any frames about SSRC change to the core */
7935 while ((f = AST_LIST_REMOVE_HEAD(&frames, frame_list)) != NULL) {
7936 ast_frfree(f);
7937 }
7938
7939 return &ast_null_frame;
7940 }
7941
7942 payload = ast_rtp_codecs_get_payload(ast_rtp_instance_get_codecs(instance), payloadtype);
7943 if (!payload) {
7944 /* Unknown payload type. */
7946 }
7947
7948 /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
7949 if (!payload->asterisk_format) {
7950 struct ast_frame *f = NULL;
7951 if (payload->rtp_code == AST_RTP_DTMF) {
7952 /* process_dtmf_rfc2833 may need to return multiple frames. We do this
7953 * by passing the pointer to the frame list to it so that the method
7954 * can append frames to the list as needed.
7955 */
7956 process_dtmf_rfc2833(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark, &frames);
7957 } else if (payload->rtp_code == AST_RTP_CISCO_DTMF) {
7958 f = process_dtmf_cisco(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark);
7959 } else if (payload->rtp_code == AST_RTP_CN) {
7960 f = process_cn_rfc3389(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark);
7961 } else {
7962 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
7963 payloadtype,
7964 ast_sockaddr_stringify(remote_address));
7965 }
7966
7967 if (f) {
7969 }
7970 /* Even if no frame was returned by one of the above methods,
7971 * we may have a frame to return in our frame list
7972 */
7974 }
7975
7976 ao2_replace(rtp->lastrxformat, payload->format);
7977 ao2_replace(rtp->f.subclass.format, payload->format);
7978 switch (ast_format_get_type(rtp->f.subclass.format)) {
7981 break;
7984 break;
7986 rtp->f.frametype = AST_FRAME_TEXT;
7987 break;
7989 /* Fall through */
7990 default:
7991 ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
7993 return &ast_null_frame;
7994 }
7995
7996 if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
7997 rtp->dtmf_timeout = 0;
7998
7999 if (rtp->resp) {
8000 struct ast_frame *f;
8001 f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
8003 rtp->resp = 0;
8004 rtp->dtmf_timeout = rtp->dtmf_duration = 0;
8006 return AST_LIST_FIRST(&frames);
8007 }
8008 }
8009
8010 rtp->f.src = "RTP";
8011 rtp->f.mallocd = 0;
8012 rtp->f.datalen = res - hdrlen;
8013 rtp->f.data.ptr = read_area + hdrlen;
8014 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
8016 rtp->f.seqno = seqno;
8017 rtp->f.stream_num = rtp->stream_num;
8018
8020 && ((int)seqno - (prev_seqno + 1) > 0)
8021 && ((int)seqno - (prev_seqno + 1) < 10)) {
8022 unsigned char *data = rtp->f.data.ptr;
8023
8024 memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
8025 rtp->f.datalen +=3;
8026 *data++ = 0xEF;
8027 *data++ = 0xBF;
8028 *data = 0xBD;
8029 }
8030
8032 unsigned char *data = rtp->f.data.ptr;
8033 unsigned char *header_end;
8034 int num_generations;
8035 int header_length;
8036 int len;
8037 int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
8038 int x;
8039
8041 header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
8042 if (header_end == NULL) {
8044 }
8045 header_end++;
8046
8047 header_length = header_end - data;
8048 num_generations = header_length / 4;
8049 len = header_length;
8050
8051 if (!diff) {
8052 for (x = 0; x < num_generations; x++)
8053 len += data[x * 4 + 3];
8054
8055 if (!(rtp->f.datalen - len))
8057
8058 rtp->f.data.ptr += len;
8059 rtp->f.datalen -= len;
8060 } else if (diff > num_generations && diff < 10) {
8061 len -= 3;
8062 rtp->f.data.ptr += len;
8063 rtp->f.datalen -= len;
8064
8065 data = rtp->f.data.ptr;
8066 *data++ = 0xEF;
8067 *data++ = 0xBF;
8068 *data = 0xBD;
8069 } else {
8070 for ( x = 0; x < num_generations - diff; x++)
8071 len += data[x * 4 + 3];
8072
8073 rtp->f.data.ptr += len;
8074 rtp->f.datalen -= len;
8075 }
8076 }
8077
8079 rtp->f.samples = ast_codec_samples_count(&rtp->f);
8081 ast_frame_byteswap_be(&rtp->f);
8082 }
8083 calc_rxstamp_and_jitter(&rtp->f.delivery, rtp, timestamp, mark);
8084 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
8086 rtp->f.ts = timestamp / (ast_rtp_get_rate(rtp->f.subclass.format) / 1000);
8087 rtp->f.len = rtp->f.samples / ((ast_format_get_sample_rate(rtp->f.subclass.format) / 1000));
8089 /* Video -- samples is # of samples vs. 90000 */
8090 if (!rtp->lastividtimestamp)
8091 rtp->lastividtimestamp = timestamp;
8092 calc_rxstamp_and_jitter(&rtp->f.delivery, rtp, timestamp, mark);
8094 rtp->f.ts = timestamp / (ast_rtp_get_rate(rtp->f.subclass.format) / 1000);
8095 rtp->f.samples = timestamp - rtp->lastividtimestamp;
8096 rtp->lastividtimestamp = timestamp;
8097 rtp->f.delivery.tv_sec = 0;
8098 rtp->f.delivery.tv_usec = 0;
8099 /* Pass the RTP marker bit as bit */
8100 rtp->f.subclass.frame_ending = mark ? 1 : 0;
8102 /* TEXT -- samples is # of samples vs. 1000 */
8103 if (!rtp->lastitexttimestamp)
8104 rtp->lastitexttimestamp = timestamp;
8105 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
8106 rtp->lastitexttimestamp = timestamp;
8107 rtp->f.delivery.tv_sec = 0;
8108 rtp->f.delivery.tv_usec = 0;
8109 } else {
8110 ast_log(LOG_WARNING, "Unknown or unsupported media type: %s\n",
8112 return &ast_null_frame;
8113 }
8114
8116 return AST_LIST_FIRST(&frames);
8117}
8118
8119#ifdef AST_DEVMODE
8120
8121struct rtp_drop_packets_data {
8122 /* Whether or not to randomize the number of packets to drop. */
8123 unsigned int use_random_num;
8124 /* Whether or not to randomize the time interval between packets drops. */
8125 unsigned int use_random_interval;
8126 /* The total number of packets to drop. If 'use_random_num' is true then this
8127 * value becomes the upper bound for a number of random packets to drop. */
8128 unsigned int num_to_drop;
8129 /* The current number of packets that have been dropped during an interval. */
8130 unsigned int num_dropped;
8131 /* The optional interval to use between packet drops. If 'use_random_interval'
8132 * is true then this values becomes the upper bound for a random interval used. */
8133 struct timeval interval;
8134 /* The next time a packet drop should be triggered. */
8135 struct timeval next;
8136 /* An optional IP address from which to drop packets from. */
8137 struct ast_sockaddr addr;
8138 /* The optional port from which to drop packets from. */
8139 unsigned int port;
8140};
8141
8142static struct rtp_drop_packets_data drop_packets_data;
8143
8144static void drop_packets_data_update(struct timeval tv)
8145{
8146 /*
8147 * num_dropped keeps up with the number of packets that have been dropped for a
8148 * given interval. Once the specified number of packets have been dropped and
8149 * the next time interval is ready to trigger then set this number to zero (drop
8150 * the next 'n' packets up to 'num_to_drop'), or if 'use_random_num' is set to
8151 * true then set to a random number between zero and 'num_to_drop'.
8152 */
8153 drop_packets_data.num_dropped = drop_packets_data.use_random_num ?
8154 ast_random() % drop_packets_data.num_to_drop : 0;
8155
8156 /*
8157 * A specified number of packets can be dropped at a given interval (e.g every
8158 * 30 seconds). If 'use_random_interval' is false simply add the interval to
8159 * the given time to get the next trigger point. If set to true, then get a
8160 * random time between the given time and up to the specified interval.
8161 */
8162 if (drop_packets_data.use_random_interval) {
8163 /* Calculate as a percentage of the specified drop packets interval */
8164 struct timeval interval = ast_time_create_by_unit(ast_time_tv_to_usec(
8165 &drop_packets_data.interval) * ((double)(ast_random() % 100 + 1) / 100),
8167
8168 drop_packets_data.next = ast_tvadd(tv, interval);
8169 } else {
8170 drop_packets_data.next = ast_tvadd(tv, drop_packets_data.interval);
8171 }
8172}
8173
8174static int should_drop_packets(struct ast_sockaddr *addr)
8175{
8176 struct timeval tv;
8177
8178 if (!drop_packets_data.num_to_drop) {
8179 return 0;
8180 }
8181
8182 /*
8183 * If an address has been specified then filter on it, and also the port if
8184 * it too was included.
8185 */
8186 if (!ast_sockaddr_isnull(&drop_packets_data.addr) &&
8187 (drop_packets_data.port ?
8188 ast_sockaddr_cmp(&drop_packets_data.addr, addr) :
8189 ast_sockaddr_cmp_addr(&drop_packets_data.addr, addr)) != 0) {
8190 /* Address and/or port does not match */
8191 return 0;
8192 }
8193
8194 /* Keep dropping packets until we've reached the total to drop */
8195 if (drop_packets_data.num_dropped < drop_packets_data.num_to_drop) {
8196 ++drop_packets_data.num_dropped;
8197 return 1;
8198 }
8199
8200 /*
8201 * Once the set number of packets has been dropped check to see if it's
8202 * time to drop more.
8203 */
8204
8205 if (ast_tvzero(drop_packets_data.interval)) {
8206 /* If no interval then drop specified number of packets and be done */
8207 drop_packets_data.num_to_drop = 0;
8208 return 0;
8209 }
8210
8211 tv = ast_tvnow();
8212 if (ast_tvcmp(tv, drop_packets_data.next) == -1) {
8213 /* Still waiting for the next time interval to elapse */
8214 return 0;
8215 }
8216
8217 /*
8218 * The next time interval has elapsed so update the tracking structure
8219 * in order to start dropping more packets, and figure out when the next
8220 * time interval is.
8221 */
8222 drop_packets_data_update(tv);
8223 return 1;
8224}
8225
8226#endif
8227
8228/*! \pre instance is locked */
8229static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
8230{
8231 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
8232 struct ast_srtp *srtp;
8234 struct ast_sockaddr addr;
8235 int res, hdrlen = 12, version, payloadtype;
8236 unsigned char *read_area = rtp->rawdata + AST_FRIENDLY_OFFSET;
8237 size_t read_area_size = sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET;
8238 unsigned int *rtpheader = (unsigned int*)(read_area), seqno, ssrc, timestamp, prev_seqno;
8239 struct ast_sockaddr remote_address = { {0,} };
8240 struct frame_list frames;
8241 struct ast_frame *frame;
8242 unsigned int bundled;
8243
8244 /* If this is actually RTCP let's hop on over and handle it */
8245 if (rtcp) {
8246 if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
8247 return ast_rtcp_read(instance);
8248 }
8249 return &ast_null_frame;
8250 }
8251
8252 /* Actually read in the data from the socket */
8253 if ((res = rtp_recvfrom(instance, read_area, read_area_size, 0,
8254 &addr)) < 0) {
8255 if (res == RTP_DTLS_ESTABLISHED) {
8258 return &rtp->f;
8259 }
8260
8261 ast_assert(errno != EBADF);
8262 if (errno != EAGAIN) {
8263 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n",
8264 (errno) ? strerror(errno) : "Unspecified");
8265 return NULL;
8266 }
8267 return &ast_null_frame;
8268 }
8269
8270 /* If this was handled by the ICE session don't do anything */
8271 if (!res) {
8272 return &ast_null_frame;
8273 }
8274
8275 /* This could be a multiplexed RTCP packet. If so, be sure to interpret it correctly */
8276 if (rtcp_mux(rtp, read_area)) {
8277 return ast_rtcp_interpret(instance, ast_rtp_instance_get_srtp(instance, 1), read_area, res, &addr);
8278 }
8279
8280 /* Make sure the data that was read in is actually enough to make up an RTP packet */
8281 if (res < hdrlen) {
8282 /* If this is a keepalive containing only nulls, don't bother with a warning */
8283 int i;
8284 for (i = 0; i < res; ++i) {
8285 if (read_area[i] != '\0') {
8286 ast_log(LOG_WARNING, "RTP Read too short\n");
8287 return &ast_null_frame;
8288 }
8289 }
8290 return &ast_null_frame;
8291 }
8292
8293 /* Get fields and verify this is an RTP packet */
8294 seqno = ntohl(rtpheader[0]);
8295
8296 ast_rtp_instance_get_remote_address(instance, &remote_address);
8297
8298 if (!(version = (seqno & 0xC0000000) >> 30)) {
8299 struct sockaddr_in addr_tmp;
8300 struct ast_sockaddr addr_v4;
8301 if (ast_sockaddr_is_ipv4(&addr)) {
8302 ast_sockaddr_to_sin(&addr, &addr_tmp);
8303 } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
8304 ast_debug_stun(1, "(%p) STUN using IPv6 mapped address %s\n",
8305 instance, ast_sockaddr_stringify(&addr));
8306 ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
8307 } else {
8308 ast_debug_stun(1, "(%p) STUN cannot do for non IPv4 address %s\n",
8309 instance, ast_sockaddr_stringify(&addr));
8310 return &ast_null_frame;
8311 }
8312 if ((ast_stun_handle_packet(rtp->s, &addr_tmp, read_area, res, NULL, NULL) == AST_STUN_ACCEPT) &&
8313 ast_sockaddr_isnull(&remote_address)) {
8314 ast_sockaddr_from_sin(&addr, &addr_tmp);
8315 ast_rtp_instance_set_remote_address(instance, &addr);
8316 }
8317 return &ast_null_frame;
8318 }
8319
8320 /* If the version is not what we expected by this point then just drop the packet */
8321 if (version != 2) {
8322 return &ast_null_frame;
8323 }
8324
8325 /* We use the SSRC to determine what RTP instance this packet is actually for */
8326 ssrc = ntohl(rtpheader[2]);
8327
8328 /* We use the SRTP data from the provided instance that it came in on, not the child */
8329 srtp = ast_rtp_instance_get_srtp(instance, 0);
8330
8331 /* Determine the appropriate instance for this */
8332 child = rtp_find_instance_by_packet_source_ssrc(instance, rtp, ssrc);
8333 if (!child) {
8334 /* Neither the bundled parent nor any child has this SSRC */
8335 return &ast_null_frame;
8336 }
8337 if (child != instance) {
8338 /* It is safe to hold the child lock while holding the parent lock, we guarantee that the locking order
8339 * is always parent->child or that the child lock is not held when acquiring the parent lock.
8340 */
8341 ao2_lock(child);
8342 instance = child;
8343 rtp = ast_rtp_instance_get_data(instance);
8344 } else {
8345 /* The child is the parent! We don't need to unlock it. */
8346 child = NULL;
8347 }
8348
8349 /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
8350 switch (rtp->strict_rtp_state) {
8351 case STRICT_RTP_LEARN:
8352 /*
8353 * Scenario setup:
8354 * PartyA -- Ast1 -- Ast2 -- PartyB
8355 *
8356 * The learning timeout is necessary for Ast1 to handle the above
8357 * setup where PartyA calls PartyB and Ast2 initiates direct media
8358 * between Ast1 and PartyB. Ast1 may lock onto the Ast2 stream and
8359 * never learn the PartyB stream when it starts. The timeout makes
8360 * Ast1 stay in the learning state long enough to see and learn the
8361 * RTP stream from PartyB.
8362 *
8363 * To mitigate against attack, the learning state cannot switch
8364 * streams while there are competing streams. The competing streams
8365 * interfere with each other's qualification. Once we accept a
8366 * stream and reach the timeout, an attacker cannot interfere
8367 * anymore.
8368 *
8369 * Here are a few scenarios and each one assumes that the streams
8370 * are continuous:
8371 *
8372 * 1) We already have a known stream source address and the known
8373 * stream wants to change to a new source address. An attacking
8374 * stream will block learning the new stream source. After the
8375 * timeout we re-lock onto the original stream source address which
8376 * likely went away. The result is one way audio.
8377 *
8378 * 2) We already have a known stream source address and the known
8379 * stream doesn't want to change source addresses. An attacking
8380 * stream will not be able to replace the known stream. After the
8381 * timeout we re-lock onto the known stream. The call is not
8382 * affected.
8383 *
8384 * 3) We don't have a known stream source address. This presumably
8385 * is the start of a call. Competing streams will result in staying
8386 * in learning mode until a stream becomes the victor and we reach
8387 * the timeout. We cannot exit learning if we have no known stream
8388 * to lock onto. The result is one way audio until there is a victor.
8389 *
8390 * If we learn a stream source address before the timeout we will be
8391 * in scenario 1) or 2) when a competing stream starts.
8392 */
8395 ast_verb(4, "%p -- Strict RTP learning complete - Locking on source address %s\n",
8397 ast_test_suite_event_notify("STRICT_RTP_LEARN", "Source: %s",
8400 } else {
8401 struct ast_sockaddr target_address;
8402
8403 if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
8404 /*
8405 * We are open to learning a new address but have received
8406 * traffic from the current address, accept it and reset
8407 * the learning counts for a new source. When no more
8408 * current source packets arrive a new source can take over
8409 * once sufficient traffic is received.
8410 */
8412 break;
8413 }
8414
8415 /*
8416 * We give preferential treatment to the requested target address
8417 * (negotiated SDP address) where we are to send our RTP. However,
8418 * the other end has no obligation to send from that address even
8419 * though it is practically a requirement when NAT is involved.
8420 */
8421 ast_rtp_instance_get_requested_target_address(instance, &target_address);
8422 if (!ast_sockaddr_cmp(&target_address, &addr)) {
8423 /* Accept the negotiated target RTP stream as the source */
8424 ast_verb(4, "%p -- Strict RTP switching to RTP target address %s as source\n",
8425 rtp, ast_sockaddr_stringify(&addr));
8428 break;
8429 }
8430
8431 /*
8432 * Trying to learn a new address. If we pass a probationary period
8433 * with it, that means we've stopped getting RTP from the original
8434 * source and we should switch to it.
8435 */
8438 struct ast_rtp_codecs *codecs;
8439
8443 ast_verb(4, "%p -- Strict RTP qualifying stream type: %s\n",
8445 }
8446 if (!rtp_learning_rtp_seq_update(&rtp->rtp_source_learn, seqno)) {
8447 /* Accept the new RTP stream */
8448 ast_verb(4, "%p -- Strict RTP switching source address to %s\n",
8449 rtp, ast_sockaddr_stringify(&addr));
8452 break;
8453 }
8454 /* Not ready to accept the RTP stream candidate */
8455 ast_debug_rtp(1, "(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection. Will switch to it in %d packets.\n",
8456 instance, rtp, ast_sockaddr_stringify(&addr), rtp->rtp_source_learn.packets);
8457 } else {
8458 /*
8459 * This is either an attacking stream or
8460 * the start of the expected new stream.
8461 */
8464 ast_debug_rtp(1, "(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection. Qualifying new stream.\n",
8465 instance, rtp, ast_sockaddr_stringify(&addr));
8466 }
8467 return &ast_null_frame;
8468 }
8469 /* Fall through */
8470 case STRICT_RTP_CLOSED:
8471 /*
8472 * We should not allow a stream address change if the SSRC matches
8473 * once strictrtp learning is closed. Any kind of address change
8474 * like this should have happened while we were in the learning
8475 * state. We do not want to allow the possibility of an attacker
8476 * interfering with the RTP stream after the learning period.
8477 * An attacker could manage to get an RTCP packet redirected to
8478 * them which can contain the SSRC value.
8479 */
8480 if (!ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
8481 break;
8482 }
8483 ast_debug_rtp(1, "(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection.\n",
8484 instance, rtp, ast_sockaddr_stringify(&addr));
8485#ifdef TEST_FRAMEWORK
8486 {
8487 static int strict_rtp_test_event = 1;
8488 if (strict_rtp_test_event) {
8489 ast_test_suite_event_notify("STRICT_RTP_CLOSED", "Source: %s",
8490 ast_sockaddr_stringify(&addr));
8491 strict_rtp_test_event = 0; /* Only run this event once to prevent possible spam */
8492 }
8493 }
8494#endif
8495 return &ast_null_frame;
8496 case STRICT_RTP_OPEN:
8497 break;
8498 }
8499
8500 /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
8502 if (ast_sockaddr_cmp(&remote_address, &addr)) {
8503 /* do not update the originally given address, but only the remote */
8505 ast_sockaddr_copy(&remote_address, &addr);
8506 if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
8507 ast_sockaddr_copy(&rtp->rtcp->them, &addr);
8509 }
8512 ast_debug(0, "(%p) RTP NAT: Got audio from other end. Now sending to address %s\n",
8513 instance, ast_sockaddr_stringify(&remote_address));
8514 }
8515 }
8516
8517 /* Pull out the various other fields we will need */
8518 payloadtype = (seqno & 0x7f0000) >> 16;
8519 seqno &= 0xffff;
8520 timestamp = ntohl(rtpheader[1]);
8521
8522#ifdef AST_DEVMODE
8523 if (should_drop_packets(&addr)) {
8524 ast_debug(0, "(%p) RTP: drop received packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
8525 instance, ast_sockaddr_stringify(&addr), payloadtype, seqno, timestamp, res - hdrlen);
8526 return &ast_null_frame;
8527 }
8528#endif
8529
8530 if (rtp_debug_test_addr(&addr)) {
8531 ast_verbose("Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
8533 payloadtype, seqno, timestamp, res - hdrlen);
8534 }
8535
8537
8538 bundled = (child || AST_VECTOR_SIZE(&rtp->ssrc_mapping)) ? 1 : 0;
8539
8540 prev_seqno = rtp->lastrxseqno;
8541 /* We need to save lastrxseqno for use by jitter before resetting it. */
8542 rtp->prevrxseqno = rtp->lastrxseqno;
8543 rtp->lastrxseqno = seqno;
8544
8545 if (!rtp->recv_buffer) {
8546 /* If there is no receive buffer then we can pass back the frame directly */
8547 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8549 return AST_LIST_FIRST(&frames);
8550 } else if (rtp->expectedrxseqno == -1 || seqno == rtp->expectedrxseqno) {
8551 rtp->expectedrxseqno = seqno + 1;
8552
8553 /* We've cycled over, so go back to 0 */
8554 if (rtp->expectedrxseqno == SEQNO_CYCLE_OVER) {
8555 rtp->expectedrxseqno = 0;
8556 }
8557
8558 /* If there are no buffered packets that will be placed after this frame then we can
8559 * return it directly without duplicating it.
8560 */
8562 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8564 return AST_LIST_FIRST(&frames);
8565 }
8566
8569 ast_debug_rtp(2, "(%p) RTP Packet with sequence number '%d' on instance is no longer missing\n",
8570 instance, seqno);
8571 }
8572
8573 /* If we don't have the next packet after this we can directly return the frame, as there is no
8574 * chance it will be overwritten.
8575 */
8577 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8579 return AST_LIST_FIRST(&frames);
8580 }
8581
8582 /* Otherwise we need to dupe the frame so that the potential processing of frames placed after
8583 * it do not overwrite the data. You may be thinking that we could just add the current packet
8584 * to the head of the frames list and avoid having to duplicate it but this would result in out
8585 * of order packet processing by libsrtp which we are trying to avoid.
8586 */
8587 frame = ast_frdup(ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled));
8588 if (frame) {
8590 prev_seqno = seqno;
8591 }
8592
8593 /* Add any additional packets that we have buffered and that are available */
8594 while (ast_data_buffer_count(rtp->recv_buffer)) {
8595 struct ast_rtp_rtcp_nack_payload *payload;
8596
8598 if (!payload) {
8599 break;
8600 }
8601
8602 frame = ast_frdup(ast_rtp_interpret(instance, srtp, &addr, payload->buf, payload->size, prev_seqno, bundled));
8603 ast_free(payload);
8604
8605 if (!frame) {
8606 /* If this packet can't be interpreted due to being out of memory we return what we have and assume
8607 * that we will determine it is a missing packet later and NACK for it.
8608 */
8609 return AST_LIST_FIRST(&frames);
8610 }
8611
8612 ast_debug_rtp(2, "(%p) RTP pulled buffered packet with sequence number '%d' to additionally return\n",
8613 instance, frame->seqno);
8615 prev_seqno = rtp->expectedrxseqno;
8616 rtp->expectedrxseqno++;
8617 if (rtp->expectedrxseqno == SEQNO_CYCLE_OVER) {
8618 rtp->expectedrxseqno = 0;
8619 }
8620 }
8621
8622 return AST_LIST_FIRST(&frames);
8623 } else if ((((seqno - rtp->expectedrxseqno) > 100) && timestamp > rtp->lastividtimestamp) ||
8625 int inserted = 0;
8626
8627 /* We have a large number of outstanding buffered packets or we've jumped far ahead in time.
8628 * To compensate we dump what we have in the buffer and place the current packet in a logical
8629 * spot. In the case of video we also require a full frame to give the decoding side a fighting
8630 * chance.
8631 */
8632
8634 ast_debug_rtp(2, "(%p) RTP source has wild gap or packet loss, sending FIR\n",
8635 instance);
8636 rtp_write_rtcp_fir(instance, rtp, &remote_address);
8637 }
8638
8639 /* This works by going through the progression of the sequence number retrieving buffered packets
8640 * or inserting the current received packet until we've run out of packets. This ensures that the
8641 * packets are in the correct sequence number order.
8642 */
8643 while (ast_data_buffer_count(rtp->recv_buffer)) {
8644 struct ast_rtp_rtcp_nack_payload *payload;
8645
8646 /* If the packet we received is the one we are expecting at this point then add it in */
8647 if (rtp->expectedrxseqno == seqno) {
8648 frame = ast_frdup(ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled));
8649 if (frame) {
8651 prev_seqno = seqno;
8652 ast_debug_rtp(2, "(%p) RTP inserted just received packet with sequence number '%d' in correct order\n",
8653 instance, seqno);
8654 }
8655 /* It is possible due to packet retransmission for this packet to also exist in the receive
8656 * buffer so we explicitly remove it in case this occurs, otherwise the receive buffer will
8657 * never be empty.
8658 */
8659 payload = (struct ast_rtp_rtcp_nack_payload *)ast_data_buffer_remove(rtp->recv_buffer, seqno);
8660 if (payload) {
8661 ast_free(payload);
8662 }
8663 rtp->expectedrxseqno++;
8664 if (rtp->expectedrxseqno == SEQNO_CYCLE_OVER) {
8665 rtp->expectedrxseqno = 0;
8666 }
8667 inserted = 1;
8668 continue;
8669 }
8670
8672 if (payload) {
8673 frame = ast_frdup(ast_rtp_interpret(instance, srtp, &addr, payload->buf, payload->size, prev_seqno, bundled));
8674 if (frame) {
8676 prev_seqno = rtp->expectedrxseqno;
8677 ast_debug_rtp(2, "(%p) RTP emptying queue and returning packet with sequence number '%d'\n",
8678 instance, frame->seqno);
8679 }
8680 ast_free(payload);
8681 }
8682
8683 rtp->expectedrxseqno++;
8684 if (rtp->expectedrxseqno == SEQNO_CYCLE_OVER) {
8685 rtp->expectedrxseqno = 0;
8686 }
8687 }
8688
8689 if (!inserted) {
8690 /* This current packet goes after them, and we assume that packets going forward will follow
8691 * that new sequence number increment. It is okay for this to not be duplicated as it is guaranteed
8692 * to be the last packet processed right now and it is also guaranteed that it will always return
8693 * non-NULL.
8694 */
8695 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8697 rtp->expectedrxseqno = seqno + 1;
8698 if (rtp->expectedrxseqno == SEQNO_CYCLE_OVER) {
8699 rtp->expectedrxseqno = 0;
8700 }
8701
8702 ast_debug_rtp(2, "(%p) RTP adding just received packet with sequence number '%d' to end of dumped queue\n",
8703 instance, seqno);
8704 }
8705
8706 /* When we flush increase our chance for next time by growing the receive buffer when possible
8707 * by how many packets we missed, to give ourselves a bit more breathing room.
8708 */
8711 ast_debug_rtp(2, "(%p) RTP receive buffer is now at maximum of %zu\n", instance, ast_data_buffer_max(rtp->recv_buffer));
8712
8713 /* As there is such a large gap we don't want to flood the order side with missing packets, so we
8714 * give up and start anew.
8715 */
8717
8718 return AST_LIST_FIRST(&frames);
8719 }
8720
8721 /* We're finished with the frames list */
8723
8724 /* Determine if the received packet is from the last OLD_PACKET_COUNT (1000 by default) packets or not.
8725 * For the case where the received sequence number exceeds that of the expected sequence number we calculate
8726 * the past sequence number that would be 1000 sequence numbers ago. If the received sequence number
8727 * exceeds or meets that then it is within OLD_PACKET_COUNT packets ago. For example if the expected
8728 * sequence number is 100 and we receive 65530, then it would be considered old. This is because
8729 * 65535 - 1000 + 100 = 64635 which gives us the sequence number at which we would consider the packets
8730 * old. Since 65530 is above that, it would be considered old.
8731 * For the case where the received sequence number is less than the expected sequence number we can do
8732 * a simple subtraction to see if it is 1000 packets ago or not.
8733 */
8734 if ((seqno < rtp->expectedrxseqno && ((rtp->expectedrxseqno - seqno) <= OLD_PACKET_COUNT)) ||
8735 (seqno > rtp->expectedrxseqno && (seqno >= (65535 - OLD_PACKET_COUNT + rtp->expectedrxseqno)))) {
8736 /* If this is a packet from the past then we have received a duplicate packet, so just drop it */
8737 ast_debug_rtp(2, "(%p) RTP received an old packet with sequence number '%d', dropping it\n",
8738 instance, seqno);
8739 return &ast_null_frame;
8740 } else if (ast_data_buffer_get(rtp->recv_buffer, seqno)) {
8741 /* If this is a packet we already have buffered then it is a duplicate, so just drop it */
8742 ast_debug_rtp(2, "(%p) RTP received a duplicate transmission of packet with sequence number '%d', dropping it\n",
8743 instance, seqno);
8744 return &ast_null_frame;
8745 } else {
8746 /* This is an out of order packet from the future */
8747 struct ast_rtp_rtcp_nack_payload *payload;
8748 int missing_seqno;
8749 int remove_failed;
8750 unsigned int missing_seqnos_added = 0;
8751
8752 ast_debug_rtp(2, "(%p) RTP received an out of order packet with sequence number '%d' while expecting '%d' from the future\n",
8753 instance, seqno, rtp->expectedrxseqno);
8754
8755 payload = ast_malloc(sizeof(*payload) + res);
8756 if (!payload) {
8757 /* If the payload can't be allocated then we can't defer this packet right now.
8758 * Instead of dumping what we have we pretend we lost this packet. It will then
8759 * get NACKed later or the existing buffer will be returned entirely. Well, we may
8760 * try since we're seemingly out of memory. It's a bad situation all around and
8761 * packets are likely to get lost anyway.
8762 */
8763 return &ast_null_frame;
8764 }
8765
8766 payload->size = res;
8767 memcpy(payload->buf, rtpheader, res);
8768 if (ast_data_buffer_put(rtp->recv_buffer, seqno, payload) == -1) {
8769 ast_free(payload);
8770 }
8771
8772 /* If this sequence number is removed that means we had a gap and this packet has filled it in
8773 * some. Since it was part of the gap we will have already added any other missing sequence numbers
8774 * before it (and possibly after it) to the vector so we don't need to do that again. Note that
8775 * remove_failed will be set to -1 if the sequence number isn't removed, and 0 if it is.
8776 */
8777 remove_failed = AST_VECTOR_REMOVE_CMP_ORDERED(&rtp->missing_seqno, seqno, find_by_value,
8779 if (!remove_failed) {
8780 ast_debug_rtp(2, "(%p) RTP packet with sequence number '%d' is no longer missing\n",
8781 instance, seqno);
8782 }
8783
8784 /* The missing sequence number code works by taking the sequence number of the
8785 * packet we've just received and going backwards until we hit the sequence number
8786 * of the last packet we've received. While doing so we check to make sure that the
8787 * sequence number is not already missing and that it is not already buffered.
8788 */
8789 missing_seqno = seqno;
8790 while (remove_failed) {
8791 missing_seqno -= 1;
8792
8793 /* If we've cycled backwards then start back at the top */
8794 if (missing_seqno < 0) {
8795 missing_seqno = 65535;
8796 }
8797
8798 /* We've gone backwards enough such that we've hit the previous sequence number */
8799 if (missing_seqno == prev_seqno) {
8800 break;
8801 }
8802
8803 /* We don't want missing sequence number duplicates. If, for some reason,
8804 * packets are really out of order, we could end up in this scenario:
8805 *
8806 * We are expecting sequence number 100
8807 * We receive sequence number 105
8808 * Sequence numbers 100 through 104 get added to the vector
8809 * We receive sequence number 101 (this section is skipped)
8810 * We receive sequence number 103
8811 * Sequence number 102 is added to the vector
8812 *
8813 * This will prevent the duplicate from being added.
8814 */
8815 if (AST_VECTOR_GET_CMP(&rtp->missing_seqno, missing_seqno,
8816 find_by_value)) {
8817 continue;
8818 }
8819
8820 /* If this packet has been buffered already then don't count it amongst the
8821 * missing.
8822 */
8823 if (ast_data_buffer_get(rtp->recv_buffer, missing_seqno)) {
8824 continue;
8825 }
8826
8827 ast_debug_rtp(2, "(%p) RTP added missing sequence number '%d'\n",
8828 instance, missing_seqno);
8829 AST_VECTOR_ADD_SORTED(&rtp->missing_seqno, missing_seqno,
8831 missing_seqnos_added++;
8832 }
8833
8834 /* When we add a large number of missing sequence numbers we assume there was a substantial
8835 * gap in reception so we trigger an immediate NACK. When our data buffer is 1/4 full we
8836 * assume that the packets aren't just out of order but have actually been lost. At 1/2
8837 * full we get more aggressive and ask for retransmission when we get a new packet.
8838 * To get them back we construct and send a NACK causing the sender to retransmit them.
8839 */
8840 if (missing_seqnos_added >= MISSING_SEQNOS_ADDED_TRIGGER ||
8843 int packet_len = 0;
8844 int res = 0;
8845 int ice;
8846 int sr;
8847 size_t data_size = AST_UUID_STR_LEN + 128 + (AST_VECTOR_SIZE(&rtp->missing_seqno) * 4);
8848 RAII_VAR(unsigned char *, rtcpheader, NULL, ast_free_ptr);
8849 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
8851 ao2_cleanup);
8852
8853 /* Sufficient space for RTCP headers and report, SDES with CNAME, NACK header,
8854 * and worst case 4 bytes per missing sequence number.
8855 */
8856 rtcpheader = ast_malloc(sizeof(*rtcpheader) + data_size);
8857 if (!rtcpheader) {
8858 ast_debug_rtcp(1, "(%p) RTCP failed to allocate memory for NACK\n", instance);
8859 return &ast_null_frame;
8860 }
8861
8862 memset(rtcpheader, 0, data_size);
8863
8864 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
8865
8866 if (res == 0 || res == 1) {
8867 return &ast_null_frame;
8868 }
8869
8870 packet_len += res;
8871
8872 res = ast_rtcp_generate_nack(instance, rtcpheader + packet_len);
8873
8874 if (res == 0) {
8875 ast_debug_rtcp(1, "(%p) RTCP failed to construct NACK, stopping here\n", instance);
8876 return &ast_null_frame;
8877 }
8878
8879 packet_len += res;
8880
8881 res = rtcp_sendto(instance, rtcpheader, packet_len, 0, &remote_address, &ice);
8882 if (res < 0) {
8883 ast_debug_rtcp(1, "(%p) RTCP failed to send NACK request out\n", instance);
8884 } else {
8885 ast_debug_rtcp(2, "(%p) RTCP sending a NACK request to get missing packets\n", instance);
8886 /* Update RTCP SR/RR statistics */
8887 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, remote_address, ice, sr);
8888 }
8889 }
8890 }
8891
8892 return &ast_null_frame;
8893}
8894
8895/*! \pre instance is locked */
8896static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
8897{
8898 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
8899
8900 if (property == AST_RTP_PROPERTY_RTCP) {
8901 if (value) {
8902 struct ast_sockaddr local_addr;
8903
8904 if (rtp->rtcp && rtp->rtcp->type == value) {
8905 ast_debug_rtcp(1, "(%p) RTCP ignoring duplicate property\n", instance);
8906 return;
8907 }
8908
8909 if (!rtp->rtcp) {
8910 rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp));
8911 if (!rtp->rtcp) {
8912 return;
8913 }
8914 rtp->rtcp->s = -1;
8915#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8916 rtp->rtcp->dtls.timeout_timer = -1;
8917#endif
8918 rtp->rtcp->schedid = -1;
8919 }
8920
8921 rtp->rtcp->type = value;
8922
8923 /* Grab the IP address and port we are going to use */
8924 ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
8927 ast_sockaddr_port(&rtp->rtcp->us) + 1);
8928 }
8929
8930 ast_sockaddr_copy(&local_addr, &rtp->rtcp->us);
8931 if (!ast_find_ourip(&local_addr, &rtp->rtcp->us, 0)) {
8932 ast_sockaddr_set_port(&local_addr, ast_sockaddr_port(&rtp->rtcp->us));
8933 } else {
8934 /* Failed to get local address reset to use default. */
8935 ast_sockaddr_copy(&local_addr, &rtp->rtcp->us);
8936 }
8937
8940 if (!rtp->rtcp->local_addr_str) {
8941 ast_free(rtp->rtcp);
8942 rtp->rtcp = NULL;
8943 return;
8944 }
8945
8947 /* We're either setting up RTCP from scratch or
8948 * switching from MUX. Either way, we won't have
8949 * a socket set up, and we need to set it up
8950 */
8951 if ((rtp->rtcp->s = create_new_socket("RTCP", &rtp->rtcp->us)) < 0) {
8952 ast_debug_rtcp(1, "(%p) RTCP failed to create a new socket\n", instance);
8954 ast_free(rtp->rtcp);
8955 rtp->rtcp = NULL;
8956 return;
8957 }
8958
8959 /* Try to actually bind to the IP address and port we are going to use for RTCP, if this fails we have to bail out */
8960 if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
8961 ast_debug_rtcp(1, "(%p) RTCP failed to setup RTP instance\n", instance);
8962 close(rtp->rtcp->s);
8964 ast_free(rtp->rtcp);
8965 rtp->rtcp = NULL;
8966 return;
8967 }
8968#ifdef HAVE_PJPROJECT
8969 if (rtp->ice) {
8970 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us, ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_SOCKET_RTCP);
8971 }
8972#endif
8973#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8974 dtls_setup_rtcp(instance);
8975#endif
8976 } else {
8977 struct ast_sockaddr addr;
8978 /* RTCPMUX uses the same socket as RTP. If we were previously using standard RTCP
8979 * then close the socket we previously created.
8980 *
8981 * It may seem as though there is a possible race condition here where we might try
8982 * to close the RTCP socket while it is being used to send data. However, this is not
8983 * a problem in practice since setting and adjusting of RTCP properties happens prior
8984 * to activating RTP. It is not until RTP is activated that timers start for RTCP
8985 * transmission
8986 */
8987 if (rtp->rtcp->s > -1 && rtp->rtcp->s != rtp->s) {
8988 close(rtp->rtcp->s);
8989 }
8990 rtp->rtcp->s = rtp->s;
8991 ast_rtp_instance_get_remote_address(instance, &addr);
8992 ast_sockaddr_copy(&rtp->rtcp->them, &addr);
8993#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8994 if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
8995 SSL_free(rtp->rtcp->dtls.ssl);
8996 }
8997 rtp->rtcp->dtls.ssl = rtp->dtls.ssl;
8998#endif
8999 }
9000
9001 ast_debug_rtcp(1, "(%s) RTCP setup on RTP instance\n",
9003 } else {
9004 if (rtp->rtcp) {
9005 if (rtp->rtcp->schedid > -1) {
9006 ao2_unlock(instance);
9007 if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
9008 /* Successfully cancelled scheduler entry. */
9009 ao2_ref(instance, -1);
9010 } else {
9011 /* Unable to cancel scheduler entry */
9012 ast_debug_rtcp(1, "(%p) RTCP failed to tear down RTCP\n", instance);
9013 ao2_lock(instance);
9014 return;
9015 }
9016 ao2_lock(instance);
9017 rtp->rtcp->schedid = -1;
9018 }
9019 if (rtp->transport_wide_cc.schedid > -1) {
9020 ao2_unlock(instance);
9021 if (!ast_sched_del(rtp->sched, rtp->transport_wide_cc.schedid)) {
9022 ao2_ref(instance, -1);
9023 } else {
9024 ast_debug_rtcp(1, "(%p) RTCP failed to tear down transport-cc feedback\n", instance);
9025 ao2_lock(instance);
9026 return;
9027 }
9028 ao2_lock(instance);
9029 rtp->transport_wide_cc.schedid = -1;
9030 }
9031 if (rtp->rtcp->s > -1 && rtp->rtcp->s != rtp->s) {
9032 close(rtp->rtcp->s);
9033 }
9034#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9035 ao2_unlock(instance);
9036 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
9037 ao2_lock(instance);
9038
9039 if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
9040 SSL_free(rtp->rtcp->dtls.ssl);
9041 }
9042#endif
9044 ast_free(rtp->rtcp);
9045 rtp->rtcp = NULL;
9046 ast_debug_rtcp(1, "(%s) RTCP torn down on RTP instance\n",
9048 }
9049 }
9050 } else if (property == AST_RTP_PROPERTY_ASYMMETRIC_CODEC) {
9051 rtp->asymmetric_codec = value;
9052 } else if (property == AST_RTP_PROPERTY_RETRANS_SEND) {
9053 if (value) {
9054 if (!rtp->send_buffer) {
9056 }
9057 } else {
9058 if (rtp->send_buffer) {
9060 rtp->send_buffer = NULL;
9061 }
9062 }
9063 } else if (property == AST_RTP_PROPERTY_RETRANS_RECV) {
9064 if (value) {
9065 if (!rtp->recv_buffer) {
9068 }
9069 } else {
9070 if (rtp->recv_buffer) {
9072 rtp->recv_buffer = NULL;
9074 }
9075 }
9076 }
9077}
9078
9079/*! \pre instance is locked */
9080static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
9081{
9082 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9083
9084 return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
9085}
9086
9087/*! \pre instance is locked */
9088static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
9089{
9090 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9091 struct ast_sockaddr local;
9092 int index;
9093
9094 ast_rtp_instance_get_local_address(instance, &local);
9095 if (!ast_sockaddr_isnull(addr)) {
9096 /* Update the local RTP address with what is being used */
9097 if (ast_ouraddrfor(addr, &local)) {
9098 /* Failed to update our address so reuse old local address */
9099 ast_rtp_instance_get_local_address(instance, &local);
9100 } else {
9101 ast_rtp_instance_set_local_address(instance, &local);
9102 }
9103 }
9104
9105 if (rtp->rtcp && !ast_sockaddr_isnull(addr)) {
9106 ast_debug_rtcp(1, "(%p) RTCP setting address on RTP instance\n", instance);
9107 ast_sockaddr_copy(&rtp->rtcp->them, addr);
9108
9111
9112 /* Update the local RTCP address with what is being used */
9113 ast_sockaddr_set_port(&local, ast_sockaddr_port(&local) + 1);
9114 }
9115 ast_sockaddr_copy(&rtp->rtcp->us, &local);
9116
9119 }
9120
9121 /* Update any bundled RTP instances */
9122 for (index = 0; index < AST_VECTOR_SIZE(&rtp->ssrc_mapping); ++index) {
9123 struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&rtp->ssrc_mapping, index);
9124
9126 }
9127
9128 /* Need to reset the DTMF last sequence number and the timestamp of the last END packet */
9129 rtp->last_seqno = 0;
9130 rtp->last_end_timestamp.ts = 0;
9131 rtp->last_end_timestamp.is_set = 0;
9132
9134 && !ast_sockaddr_isnull(addr) && ast_sockaddr_cmp(addr, &rtp->strict_rtp_address)) {
9135 /* We only need to learn a new strict source address if we've been told the source is
9136 * changing to something different.
9137 */
9138 ast_verb(4, "%p -- Strict RTP learning after remote address set to: %s\n",
9139 rtp, ast_sockaddr_stringify(addr));
9140 rtp_learning_start(rtp);
9141 }
9142}
9143
9144/*!
9145 * \brief Write t140 redundancy frame
9146 *
9147 * \param data primary data to be buffered
9148 *
9149 * Scheduler callback
9150 */
9151static int red_write(const void *data)
9152{
9153 struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
9154 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9155
9156 ao2_lock(instance);
9157 if (rtp->red->t140.datalen > 0) {
9158 ast_rtp_write(instance, &rtp->red->t140);
9159 }
9160 ao2_unlock(instance);
9161
9162 return 1;
9163}
9164
9165/*! \pre instance is locked */
9166static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
9167{
9168 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9169 int x;
9170
9171 rtp->red = ast_calloc(1, sizeof(*rtp->red));
9172 if (!rtp->red) {
9173 return -1;
9174 }
9175
9178 rtp->red->t140.data.ptr = &rtp->red->buf_data;
9179
9180 rtp->red->t140red = rtp->red->t140;
9181 rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
9182
9183 rtp->red->num_gen = generations;
9184 rtp->red->hdrlen = generations * 4 + 1;
9185
9186 for (x = 0; x < generations; x++) {
9187 rtp->red->pt[x] = payloads[x];
9188 rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
9189 rtp->red->t140red_data[x*4] = rtp->red->pt[x];
9190 }
9191 rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
9192 rtp->red->schedid = ast_sched_add(rtp->sched, buffer_time, red_write, instance);
9193
9194 return 0;
9195}
9196
9197/*! \pre instance is locked */
9198static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
9199{
9200 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9201 struct rtp_red *red = rtp->red;
9202
9203 if (!red) {
9204 return 0;
9205 }
9206
9207 if (frame->datalen > 0) {
9208 if (red->t140.datalen > 0) {
9209 const unsigned char *primary = red->buf_data;
9210
9211 /* There is something already in the T.140 buffer */
9212 if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
9213 /* Flush the previous T.140 packet if it is a command */
9214 ast_rtp_write(instance, &rtp->red->t140);
9215 } else {
9216 primary = frame->data.ptr;
9217 if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
9218 /* Flush the previous T.140 packet if we are buffering a command now */
9219 ast_rtp_write(instance, &rtp->red->t140);
9220 }
9221 }
9222 }
9223
9224 memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
9225 red->t140.datalen += frame->datalen;
9226 red->t140.ts = frame->ts;
9227 }
9228
9229 return 0;
9230}
9231
9232/*! \pre Neither instance0 nor instance1 are locked */
9233static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
9234{
9235 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
9236
9237 ao2_lock(instance0);
9239 if (rtp->smoother) {
9241 rtp->smoother = NULL;
9242 }
9243
9244 /* We must use a new SSRC when local bridge ends */
9245 if (!instance1) {
9246 rtp->ssrc = rtp->ssrc_orig;
9247 rtp->ssrc_orig = 0;
9248 rtp->ssrc_saved = 0;
9249 } else if (!rtp->ssrc_saved) {
9250 /* In case ast_rtp_local_bridge is called multiple times, only save the ssrc from before local bridge began */
9251 rtp->ssrc_orig = rtp->ssrc;
9252 rtp->ssrc_saved = 1;
9253 }
9254
9255 ao2_unlock(instance0);
9256
9257 return 0;
9258}
9259
9260/*! \pre instance is locked */
9261static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
9262{
9263 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9264
9265 if (!rtp->rtcp) {
9266 return -1;
9267 }
9268
9273
9285
9297
9304
9316
9317
9321
9322 return 0;
9323}
9324
9325/*! \pre Neither instance0 nor instance1 are locked */
9326static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
9327{
9328 /* If both sides are not using the same method of DTMF transmission
9329 * (ie: one is RFC2833, other is INFO... then we can not do direct media.
9330 * --------------------------------------------------
9331 * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
9332 * |-----------|------------|-----------------------|
9333 * | Inband | False | True |
9334 * | RFC2833 | True | True |
9335 * | SIP INFO | False | False |
9336 * --------------------------------------------------
9337 */
9339 (!ast_channel_tech(chan0)->send_digit_begin != !ast_channel_tech(chan1)->send_digit_begin)) ? 0 : 1);
9340}
9341
9342/*! \pre instance is NOT locked */
9343static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
9344{
9345 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9346 struct sockaddr_in suggestion_tmp;
9347
9348 /*
9349 * The instance should not be locked because we can block
9350 * waiting for a STUN respone.
9351 */
9352 ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
9353 ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
9354 ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
9355}
9356
9357/*! \pre instance is locked */
9358static void ast_rtp_stop(struct ast_rtp_instance *instance)
9359{
9360 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9361 struct ast_sockaddr addr = { {0,} };
9362
9363#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9364 ao2_unlock(instance);
9365 AST_SCHED_DEL_UNREF(rtp->sched, rtp->rekeyid, ao2_ref(instance, -1));
9366
9367 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
9368 if (rtp->rtcp) {
9369 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
9370 }
9371 ao2_lock(instance);
9372#endif
9373 ast_debug_rtp(1, "(%s) RTP Stop\n",
9375
9376 if (rtp->rtcp && rtp->rtcp->schedid > -1) {
9377 ao2_unlock(instance);
9378 if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
9379 /* successfully cancelled scheduler entry. */
9380 ao2_ref(instance, -1);
9381 }
9382 ao2_lock(instance);
9383 rtp->rtcp->schedid = -1;
9384 }
9385
9386 if (rtp->transport_wide_cc.schedid > -1) {
9387 ao2_unlock(instance);
9388 if (!ast_sched_del(rtp->sched, rtp->transport_wide_cc.schedid)) {
9389 ao2_ref(instance, -1);
9390 }
9391 ao2_lock(instance);
9392 rtp->transport_wide_cc.schedid = -1;
9393 }
9394
9395 if (rtp->red) {
9396 ao2_unlock(instance);
9397 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
9398 ao2_lock(instance);
9399 ast_free(rtp->red);
9400 rtp->red = NULL;
9401 }
9402
9403 ast_rtp_instance_set_remote_address(instance, &addr);
9404
9406}
9407
9408/*! \pre instance is locked */
9409static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
9410{
9411 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9412
9413 return ast_set_qos(rtp->s, tos, cos, desc);
9414}
9415
9416/*!
9417 * \brief generate comfort noice (CNG)
9418 *
9419 * \pre instance is locked
9420 */
9421static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
9422{
9423 unsigned int *rtpheader;
9424 int hdrlen = 12;
9425 int res, payload = 0;
9426 char data[256];
9427 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9428 struct ast_sockaddr remote_address = { {0,} };
9429 int ice;
9430
9431 ast_rtp_instance_get_remote_address(instance, &remote_address);
9432
9433 if (ast_sockaddr_isnull(&remote_address)) {
9434 return -1;
9435 }
9436
9438
9439 level = 127 - (level & 0x7f);
9440
9441 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
9442
9443 /* Get a pointer to the header */
9444 rtpheader = (unsigned int *)data;
9445 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
9446 rtpheader[1] = htonl(rtp->lastts);
9447 rtpheader[2] = htonl(rtp->ssrc);
9448 data[12] = level;
9449
9450 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address, &ice);
9451
9452 if (res < 0) {
9453 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
9454 return res;
9455 }
9456
9457 if (rtp_debug_test_addr(&remote_address)) {
9458 ast_verbose("Sent Comfort Noise RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
9459 ast_sockaddr_stringify(&remote_address),
9460 ice ? " (via ICE)" : "",
9461 AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
9462 }
9463
9464 rtp->seqno++;
9465
9466 return res;
9467}
9468
9469/*! \pre instance is locked */
9470static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance)
9471{
9472 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9473
9474 return rtp->ssrc;
9475}
9476
9477/*! \pre instance is locked */
9478static const char *ast_rtp_get_cname(struct ast_rtp_instance *instance)
9479{
9480 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9481
9482 return rtp->cname;
9483}
9484
9485/*! \pre instance is locked */
9486static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc)
9487{
9488 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9489
9490 if (rtp->themssrc_valid && rtp->themssrc == ssrc) {
9491 return;
9492 }
9493
9494 rtp->themssrc = ssrc;
9495 rtp->themssrc_valid = 1;
9496
9497 /* If this is bundled we need to update the SSRC mapping */
9498 if (rtp->bundled) {
9499 struct ast_rtp *bundled_rtp;
9500 int index;
9501
9502 ao2_unlock(instance);
9503
9504 /* The child lock can't be held while accessing the parent */
9505 ao2_lock(rtp->bundled);
9506 bundled_rtp = ast_rtp_instance_get_data(rtp->bundled);
9507
9508 for (index = 0; index < AST_VECTOR_SIZE(&bundled_rtp->ssrc_mapping); ++index) {
9509 struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&bundled_rtp->ssrc_mapping, index);
9510
9511 if (mapping->instance == instance) {
9512 mapping->ssrc = ssrc;
9513 mapping->ssrc_valid = 1;
9514 break;
9515 }
9516 }
9517
9518 ao2_unlock(rtp->bundled);
9519
9521 }
9522}
9523
9524static void ast_rtp_set_stream_num(struct ast_rtp_instance *instance, int stream_num)
9525{
9526 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9527
9528 rtp->stream_num = stream_num;
9529}
9530
9532{
9533 switch (extension) {
9536 return 1;
9537 default:
9538 return 0;
9539 }
9540}
9541
9542/*! \pre child is locked */
9543static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent)
9544{
9545 struct ast_rtp *child_rtp = ast_rtp_instance_get_data(child);
9546 struct ast_rtp *parent_rtp;
9547 struct rtp_ssrc_mapping mapping;
9548 struct ast_sockaddr them = { { 0, } };
9549
9550 if (child_rtp->bundled == parent) {
9551 return 0;
9552 }
9553
9554 /* If this instance was already bundled then remove the SSRC mapping */
9555 if (child_rtp->bundled) {
9556 struct ast_rtp *bundled_rtp;
9557
9558 ao2_unlock(child);
9559
9560 /* The child lock can't be held while accessing the parent */
9561 ao2_lock(child_rtp->bundled);
9562 bundled_rtp = ast_rtp_instance_get_data(child_rtp->bundled);
9564 ao2_unlock(child_rtp->bundled);
9565
9566 ao2_lock(child);
9567 ao2_ref(child_rtp->bundled, -1);
9568 child_rtp->bundled = NULL;
9569 }
9570
9571 if (!parent) {
9572 /* We transitioned away from bundle so we need our own transport resources once again */
9573 rtp_allocate_transport(child, child_rtp);
9574 return 0;
9575 }
9576
9577 parent_rtp = ast_rtp_instance_get_data(parent);
9578
9579 /* We no longer need any transport related resources as we will use our parent RTP instance instead */
9580 rtp_deallocate_transport(child, child_rtp);
9581
9582 /* Children maintain a reference to the parent to guarantee that the transport doesn't go away on them */
9583 child_rtp->bundled = ao2_bump(parent);
9584
9585 mapping.ssrc = child_rtp->themssrc;
9586 mapping.ssrc_valid = child_rtp->themssrc_valid;
9587 mapping.instance = child;
9588
9589 ao2_unlock(child);
9590
9591 ao2_lock(parent);
9592
9593 AST_VECTOR_APPEND(&parent_rtp->ssrc_mapping, mapping);
9594
9595#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9596 /* If DTLS-SRTP is already in use then add the local SSRC to it, otherwise it will get added once DTLS
9597 * negotiation has been completed.
9598 */
9599 if (parent_rtp->dtls.connection == AST_RTP_DTLS_CONNECTION_EXISTING) {
9600 dtls_srtp_add_local_ssrc(parent_rtp, parent, 0, child_rtp->ssrc, 0);
9601 }
9602#endif
9603
9604 /* Bundle requires that RTCP-MUX be in use so only the main remote address needs to match */
9606
9607 ao2_unlock(parent);
9608
9609 ao2_lock(child);
9610
9612
9613 return 0;
9614}
9615
9616#ifdef HAVE_PJPROJECT
9617static void stunaddr_resolve_callback(const struct ast_dns_query *query)
9618{
9619 const int lowest_ttl = ast_dns_result_get_lowest_ttl(ast_dns_query_get_result(query));
9620 const char *stunaddr_name = ast_dns_query_get_name(query);
9621 const char *stunaddr_resolved_str;
9622
9623 if (!store_stunaddr_resolved(query)) {
9624 ast_log(LOG_WARNING, "Failed to resolve stunaddr '%s'. Cancelling recurring resolution.\n", stunaddr_name);
9625 return;
9626 }
9627
9628 if (DEBUG_ATLEAST(2)) {
9629 ast_rwlock_rdlock(&stunaddr_lock);
9630 stunaddr_resolved_str = ast_inet_ntoa(stunaddr.sin_addr);
9631 ast_rwlock_unlock(&stunaddr_lock);
9632
9633 ast_debug_stun(2, "Resolved stunaddr '%s' to '%s'. Lowest TTL = %d.\n",
9634 stunaddr_name,
9635 stunaddr_resolved_str,
9636 lowest_ttl);
9637 }
9638
9639 if (!lowest_ttl) {
9640 ast_log(LOG_WARNING, "Resolution for stunaddr '%s' returned TTL = 0. Recurring resolution was cancelled.\n", ast_dns_query_get_name(query));
9641 }
9642}
9643
9644static int store_stunaddr_resolved(const struct ast_dns_query *query)
9645{
9646 const struct ast_dns_result *result = ast_dns_query_get_result(query);
9647 const struct ast_dns_record *record;
9648
9649 for (record = ast_dns_result_get_records(result); record; record = ast_dns_record_get_next(record)) {
9650 const size_t data_size = ast_dns_record_get_data_size(record);
9651 const unsigned char *data = (unsigned char *)ast_dns_record_get_data(record);
9652 const int rr_type = ast_dns_record_get_rr_type(record);
9653
9654 if (rr_type == ns_t_a && data_size == 4) {
9655 ast_rwlock_wrlock(&stunaddr_lock);
9656 memcpy(&stunaddr.sin_addr, data, data_size);
9657 stunaddr.sin_family = AF_INET;
9658 ast_rwlock_unlock(&stunaddr_lock);
9659
9660 return 1;
9661 } else {
9662 ast_debug_stun(3, "Unrecognized rr_type '%u' or data_size '%zu' from DNS query for stunaddr '%s'\n",
9663 rr_type, data_size, ast_dns_query_get_name(query));
9664 continue;
9665 }
9666 }
9667 return 0;
9668}
9669
9670static void clean_stunaddr(void) {
9671 if (stunaddr_resolver) {
9672 if (ast_dns_resolve_recurring_cancel(stunaddr_resolver)) {
9673 ast_log(LOG_ERROR, "Failed to cancel recurring DNS resolution of previous stunaddr.\n");
9674 }
9675 ao2_ref(stunaddr_resolver, -1);
9676 stunaddr_resolver = NULL;
9677 }
9678 ast_rwlock_wrlock(&stunaddr_lock);
9679 memset(&stunaddr, 0, sizeof(stunaddr));
9680 ast_rwlock_unlock(&stunaddr_lock);
9681}
9682#endif
9683
9684#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9685/*! \pre instance is locked */
9686static int ast_rtp_activate(struct ast_rtp_instance *instance)
9687{
9688 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
9689
9690 /* If ICE negotiation is enabled the DTLS Handshake will be performed upon completion of it */
9691#ifdef HAVE_PJPROJECT
9692 if (rtp->ice) {
9693 return 0;
9694 }
9695#endif
9696
9697 ast_debug_dtls(3, "(%p) DTLS - ast_rtp_activate rtp=%p - setup and perform DTLS'\n", instance, rtp);
9698
9699 dtls_perform_setup(&rtp->dtls);
9700 dtls_perform_handshake(instance, &rtp->dtls, 0);
9701
9702 if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
9703 dtls_perform_setup(&rtp->rtcp->dtls);
9704 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
9705 }
9706
9707 return 0;
9708}
9709#endif
9710
9711static char *rtp_do_debug_ip(struct ast_cli_args *a)
9712{
9713 char *arg = ast_strdupa(a->argv[4]);
9714 char *debughost = NULL;
9715 char *debugport = NULL;
9716
9717 if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
9718 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
9719 return CLI_FAILURE;
9720 }
9721 rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
9722 ast_cli(a->fd, "RTP Packet Debugging Enabled for address: %s\n",
9725 return CLI_SUCCESS;
9726}
9727
9728static char *rtcp_do_debug_ip(struct ast_cli_args *a)
9729{
9730 char *arg = ast_strdupa(a->argv[4]);
9731 char *debughost = NULL;
9732 char *debugport = NULL;
9733
9734 if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
9735 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
9736 return CLI_FAILURE;
9737 }
9738 rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
9739 ast_cli(a->fd, "RTCP Packet Debugging Enabled for address: %s\n",
9742 return CLI_SUCCESS;
9743}
9744
9745static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9746{
9747 switch (cmd) {
9748 case CLI_INIT:
9749 e->command = "rtp set debug {on|off|ip}";
9750 e->usage =
9751 "Usage: rtp set debug {on|off|ip host[:port]}\n"
9752 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
9753 " specified, limit the dumped packets to those to and from\n"
9754 " the specified 'host' with optional port.\n";
9755 return NULL;
9756 case CLI_GENERATE:
9757 return NULL;
9758 }
9759
9760 if (a->argc == e->args) { /* set on or off */
9761 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
9763 memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
9764 ast_cli(a->fd, "RTP Packet Debugging Enabled\n");
9765 return CLI_SUCCESS;
9766 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
9768 ast_cli(a->fd, "RTP Packet Debugging Disabled\n");
9769 return CLI_SUCCESS;
9770 }
9771 } else if (a->argc == e->args +1) { /* ip */
9772 return rtp_do_debug_ip(a);
9773 }
9774
9775 return CLI_SHOWUSAGE; /* default, failure */
9776}
9777
9778
9779static char *handle_cli_rtp_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9780{
9781#ifdef HAVE_PJPROJECT
9782 struct sockaddr_in stunaddr_copy;
9783#endif
9784 switch (cmd) {
9785 case CLI_INIT:
9786 e->command = "rtp show settings";
9787 e->usage =
9788 "Usage: rtp show settings\n"
9789 " Display RTP configuration settings\n";
9790 return NULL;
9791 case CLI_GENERATE:
9792 return NULL;
9793 }
9794
9795 if (a->argc != 3) {
9796 return CLI_SHOWUSAGE;
9797 }
9798
9799 ast_cli(a->fd, "\n\nGeneral Settings:\n");
9800 ast_cli(a->fd, "----------------\n");
9801 ast_cli(a->fd, " Port start: %d\n", rtpstart);
9802 ast_cli(a->fd, " Port end: %d\n", rtpend);
9803#ifdef SO_NO_CHECK
9804 ast_cli(a->fd, " Checksums: %s\n", AST_CLI_YESNO(nochecksums == 0));
9805#endif
9806 ast_cli(a->fd, " DTMF Timeout: %d\n", dtmftimeout);
9807 ast_cli(a->fd, " Strict RTP: %s\n", AST_CLI_YESNO(strictrtp));
9808
9809 if (strictrtp) {
9810 ast_cli(a->fd, " Probation: %d frames\n", learning_min_sequential);
9811 }
9812
9813 ast_cli(a->fd, " Replay Protect: %s\n", AST_CLI_YESNO(srtp_replay_protection));
9814#ifdef HAVE_PJPROJECT
9815 ast_cli(a->fd, " ICE support: %s\n", AST_CLI_YESNO(icesupport));
9816
9817 ast_rwlock_rdlock(&stunaddr_lock);
9818 memcpy(&stunaddr_copy, &stunaddr, sizeof(stunaddr));
9819 ast_rwlock_unlock(&stunaddr_lock);
9820 ast_cli(a->fd, " STUN address: %s:%d\n", ast_inet_ntoa(stunaddr_copy.sin_addr), htons(stunaddr_copy.sin_port));
9821#endif
9822 return CLI_SUCCESS;
9823}
9824
9825
9826static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9827{
9828 switch (cmd) {
9829 case CLI_INIT:
9830 e->command = "rtcp set debug {on|off|ip}";
9831 e->usage =
9832 "Usage: rtcp set debug {on|off|ip host[:port]}\n"
9833 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
9834 " specified, limit the dumped packets to those to and from\n"
9835 " the specified 'host' with optional port.\n";
9836 return NULL;
9837 case CLI_GENERATE:
9838 return NULL;
9839 }
9840
9841 if (a->argc == e->args) { /* set on or off */
9842 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
9844 memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
9845 ast_cli(a->fd, "RTCP Packet Debugging Enabled\n");
9846 return CLI_SUCCESS;
9847 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
9849 ast_cli(a->fd, "RTCP Packet Debugging Disabled\n");
9850 return CLI_SUCCESS;
9851 }
9852 } else if (a->argc == e->args +1) { /* ip */
9853 return rtcp_do_debug_ip(a);
9854 }
9855
9856 return CLI_SHOWUSAGE; /* default, failure */
9857}
9858
9859static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9860{
9861 switch (cmd) {
9862 case CLI_INIT:
9863 e->command = "rtcp set stats {on|off}";
9864 e->usage =
9865 "Usage: rtcp set stats {on|off}\n"
9866 " Enable/Disable dumping of RTCP stats.\n";
9867 return NULL;
9868 case CLI_GENERATE:
9869 return NULL;
9870 }
9871
9872 if (a->argc != e->args)
9873 return CLI_SHOWUSAGE;
9874
9875 if (!strncasecmp(a->argv[e->args-1], "on", 2))
9876 rtcpstats = 1;
9877 else if (!strncasecmp(a->argv[e->args-1], "off", 3))
9878 rtcpstats = 0;
9879 else
9880 return CLI_SHOWUSAGE;
9881
9882 ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
9883 return CLI_SUCCESS;
9884}
9885
9886#ifdef AST_DEVMODE
9887
9888static unsigned int use_random(struct ast_cli_args *a, int pos, unsigned int index)
9889{
9890 return pos >= index && !ast_strlen_zero(a->argv[index - 1]) &&
9891 !strcasecmp(a->argv[index - 1], "random");
9892}
9893
9894static char *handle_cli_rtp_drop_incoming_packets(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9895{
9896 static const char * const completions_2[] = { "stop", "<N>", NULL };
9897 static const char * const completions_3[] = { "random", "incoming packets", NULL };
9898 static const char * const completions_5[] = { "on", "every", NULL };
9899 static const char * const completions_units[] = { "random", "usec", "msec", "sec", "min", NULL };
9900
9901 unsigned int use_random_num = 0;
9902 unsigned int use_random_interval = 0;
9903 unsigned int num_to_drop = 0;
9904 unsigned int interval = 0;
9905 const char *interval_s = NULL;
9906 const char *unit_s = NULL;
9907 struct ast_sockaddr addr;
9908 const char *addr_s = NULL;
9909
9910 switch (cmd) {
9911 case CLI_INIT:
9912 e->command = "rtp drop";
9913 e->usage =
9914 "Usage: rtp drop [stop|[<N> [random] incoming packets[ every <N> [random] {usec|msec|sec|min}][ on <ip[:port]>]]\n"
9915 " Drop RTP incoming packets.\n";
9916 return NULL;
9917 case CLI_GENERATE:
9918 use_random_num = use_random(a, a->pos, 4);
9919 use_random_interval = use_random(a, a->pos, 8 + use_random_num) ||
9920 use_random(a, a->pos, 10 + use_random_num);
9921
9922 switch (a->pos - use_random_num - use_random_interval) {
9923 case 2:
9924 return ast_cli_complete(a->word, completions_2, a->n);
9925 case 3:
9926 return ast_cli_complete(a->word, completions_3 + use_random_num, a->n);
9927 case 5:
9928 return ast_cli_complete(a->word, completions_5, a->n);
9929 case 7:
9930 if (!strcasecmp(a->argv[a->pos - 2], "on")) {
9932 break;
9933 }
9934 /* Fall through */
9935 case 9:
9936 if (!strcasecmp(a->argv[a->pos - 2 - use_random_interval], "every")) {
9937 return ast_cli_complete(a->word, completions_units + use_random_interval, a->n);
9938 }
9939 break;
9940 case 8:
9941 if (!strcasecmp(a->argv[a->pos - 3 - use_random_interval], "every")) {
9943 }
9944 break;
9945 }
9946
9947 return NULL;
9948 }
9949
9950 if (a->argc < 3) {
9951 return CLI_SHOWUSAGE;
9952 }
9953
9954 use_random_num = use_random(a, a->argc, 4);
9955 use_random_interval = use_random(a, a->argc, 8 + use_random_num) ||
9956 use_random(a, a->argc, 10 + use_random_num);
9957
9958 if (!strcasecmp(a->argv[2], "stop")) {
9959 /* rtp drop stop */
9960 } else if (a->argc < 5) {
9961 return CLI_SHOWUSAGE;
9962 } else if (ast_str_to_uint(a->argv[2], &num_to_drop)) {
9963 ast_cli(a->fd, "%s is not a valid number of packets to drop\n", a->argv[2]);
9964 return CLI_FAILURE;
9965 } else if (a->argc - use_random_num == 5) {
9966 /* rtp drop <N> [random] incoming packets */
9967 } else if (a->argc - use_random_num >= 7 && !strcasecmp(a->argv[5 + use_random_num], "on")) {
9968 /* rtp drop <N> [random] incoming packets on <ip[:port]> */
9969 addr_s = a->argv[6 + use_random_num];
9970 if (a->argc - use_random_num - use_random_interval == 10 &&
9971 !strcasecmp(a->argv[7 + use_random_num], "every")) {
9972 /* rtp drop <N> [random] incoming packets on <ip[:port]> every <N> [random] {usec|msec|sec|min} */
9973 interval_s = a->argv[8 + use_random_num];
9974 unit_s = a->argv[9 + use_random_num + use_random_interval];
9975 }
9976 } else if (a->argc - use_random_num >= 8 && !strcasecmp(a->argv[5 + use_random_num], "every")) {
9977 /* rtp drop <N> [random] incoming packets every <N> [random] {usec|msec|sec|min} */
9978 interval_s = a->argv[6 + use_random_num];
9979 unit_s = a->argv[7 + use_random_num + use_random_interval];
9980 if (a->argc == 10 + use_random_num + use_random_interval &&
9981 !strcasecmp(a->argv[8 + use_random_num + use_random_interval], "on")) {
9982 /* rtp drop <N> [random] incoming packets every <N> [random] {usec|msec|sec|min} on <ip[:port]> */
9983 addr_s = a->argv[9 + use_random_num + use_random_interval];
9984 }
9985 } else {
9986 return CLI_SHOWUSAGE;
9987 }
9988
9989 if (a->argc - use_random_num >= 8 && !interval_s && !addr_s) {
9990 return CLI_SHOWUSAGE;
9991 }
9992
9993 if (interval_s && ast_str_to_uint(interval_s, &interval)) {
9994 ast_cli(a->fd, "%s is not a valid interval number\n", interval_s);
9995 return CLI_FAILURE;
9996 }
9997
9998 memset(&addr, 0, sizeof(addr));
9999 if (addr_s && !ast_sockaddr_parse(&addr, addr_s, 0)) {
10000 ast_cli(a->fd, "%s is not a valid hostname[:port]\n", addr_s);
10001 return CLI_FAILURE;
10002 }
10003
10004 drop_packets_data.use_random_num = use_random_num;
10005 drop_packets_data.use_random_interval = use_random_interval;
10006 drop_packets_data.num_to_drop = num_to_drop;
10007 drop_packets_data.interval = ast_time_create_by_unit_str(interval, unit_s);
10008 ast_sockaddr_copy(&drop_packets_data.addr, &addr);
10009 drop_packets_data.port = ast_sockaddr_port(&addr);
10010
10011 drop_packets_data_update(ast_tvnow());
10012
10013 return CLI_SUCCESS;
10014}
10015#endif
10016
10017static struct ast_cli_entry cli_rtp[] = {
10018 AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging"),
10019 AST_CLI_DEFINE(handle_cli_rtp_settings, "Display RTP settings"),
10020 AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
10021 AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
10022#ifdef AST_DEVMODE
10023 AST_CLI_DEFINE(handle_cli_rtp_drop_incoming_packets, "Drop RTP incoming packets"),
10024#endif
10025};
10026
10027static int rtp_reload(int reload, int by_external_config)
10028{
10029 struct ast_config *cfg;
10030 const char *s;
10031 struct ast_flags config_flags = { (reload && !by_external_config) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
10032
10033#ifdef HAVE_PJPROJECT
10034 struct ast_variable *var;
10035 struct ast_ice_host_candidate *candidate;
10036 int acl_subscription_flag = 0;
10037#endif
10038
10039 cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
10040 if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
10041 return 0;
10042 }
10043
10044#ifdef SO_NO_CHECK
10045 nochecksums = 0;
10046#endif
10047
10056
10057 /** This resource is not "reloaded" so much as unloaded and loaded again.
10058 * In the case of the TURN related variables, the memory referenced by a
10059 * previously loaded instance *should* have been released when the
10060 * corresponding pool was destroyed. If at some point in the future this
10061 * resource were to support ACTUAL live reconfiguration and did NOT release
10062 * the pool this will cause a small memory leak.
10063 */
10064
10065#ifdef HAVE_PJPROJECT
10066 icesupport = DEFAULT_ICESUPPORT;
10067 stun_software_attribute = DEFAULT_STUN_SOFTWARE_ATTRIBUTE;
10068 turnport = DEFAULT_TURN_PORT;
10069 clean_stunaddr();
10070 turnaddr = pj_str(NULL);
10071 turnusername = pj_str(NULL);
10072 turnpassword = pj_str(NULL);
10073 host_candidate_overrides_clear();
10074#endif
10075
10076#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
10077 dtls_mtu = DEFAULT_DTLS_MTU;
10078#endif
10079
10080 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
10081 rtpstart = atoi(s);
10086 }
10087 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
10088 rtpend = atoi(s);
10093 }
10094 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
10095 rtcpinterval = atoi(s);
10096 if (rtcpinterval == 0)
10097 rtcpinterval = 0; /* Just so we're clear... it's zero */
10099 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
10102 }
10103 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
10104#ifdef SO_NO_CHECK
10105 nochecksums = ast_false(s) ? 1 : 0;
10106#else
10107 if (ast_false(s))
10108 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
10109#endif
10110 }
10111 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
10112 dtmftimeout = atoi(s);
10113 if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
10114 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
10117 };
10118 }
10119 if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
10120 if (ast_true(s)) {
10122 } else if (!strcasecmp(s, "seqno")) {
10124 } else {
10126 }
10127 }
10128 if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
10129 if ((sscanf(s, "%d", &learning_min_sequential) != 1) || learning_min_sequential <= 1) {
10130 ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
10133 }
10135 }
10136 if ((s = ast_variable_retrieve(cfg, "general", "srtpreplayprotection"))) {
10138 }
10139#ifdef HAVE_PJPROJECT
10140 if ((s = ast_variable_retrieve(cfg, "general", "icesupport"))) {
10141 icesupport = ast_true(s);
10142 }
10143 if ((s = ast_variable_retrieve(cfg, "general", "stun_software_attribute"))) {
10144 stun_software_attribute = ast_true(s);
10145 }
10146 if ((s = ast_variable_retrieve(cfg, "general", "stunaddr"))) {
10147 char *hostport, *host, *port;
10148 unsigned int port_parsed = STANDARD_STUN_PORT;
10149 struct ast_sockaddr stunaddr_parsed;
10150
10151 hostport = ast_strdupa(s);
10152
10153 if (!ast_parse_arg(hostport, PARSE_ADDR, &stunaddr_parsed)) {
10154 ast_debug_stun(3, "stunaddr = '%s' does not need name resolution\n",
10155 ast_sockaddr_stringify_host(&stunaddr_parsed));
10156 if (!ast_sockaddr_port(&stunaddr_parsed)) {
10157 ast_sockaddr_set_port(&stunaddr_parsed, STANDARD_STUN_PORT);
10158 }
10159 ast_rwlock_wrlock(&stunaddr_lock);
10160 ast_sockaddr_to_sin(&stunaddr_parsed, &stunaddr);
10161 ast_rwlock_unlock(&stunaddr_lock);
10162 } else if (ast_sockaddr_split_hostport(hostport, &host, &port, 0)) {
10163 if (port) {
10164 ast_parse_arg(port, PARSE_UINT32|PARSE_IN_RANGE, &port_parsed, 1, 65535);
10165 }
10166 stunaddr.sin_port = htons(port_parsed);
10167
10168 stunaddr_resolver = ast_dns_resolve_recurring(host, T_A, C_IN,
10169 &stunaddr_resolve_callback, NULL);
10170 if (!stunaddr_resolver) {
10171 ast_log(LOG_ERROR, "Failed to setup recurring DNS resolution of stunaddr '%s'",
10172 host);
10173 }
10174 } else {
10175 ast_log(LOG_ERROR, "Failed to parse stunaddr '%s'", hostport);
10176 }
10177 }
10178 if ((s = ast_variable_retrieve(cfg, "general", "turnaddr"))) {
10179 struct sockaddr_in addr;
10180 addr.sin_port = htons(DEFAULT_TURN_PORT);
10181 if (ast_parse_arg(s, PARSE_INADDR, &addr)) {
10182 ast_log(LOG_WARNING, "Invalid TURN server address: %s\n", s);
10183 } else {
10184 pj_strdup2_with_null(pool, &turnaddr, ast_inet_ntoa(addr.sin_addr));
10185 /* ntohs() is not a bug here. The port number is used in host byte order with
10186 * a pjnat API. */
10187 turnport = ntohs(addr.sin_port);
10188 }
10189 }
10190 if ((s = ast_variable_retrieve(cfg, "general", "turnusername"))) {
10191 pj_strdup2_with_null(pool, &turnusername, s);
10192 }
10193 if ((s = ast_variable_retrieve(cfg, "general", "turnpassword"))) {
10194 pj_strdup2_with_null(pool, &turnpassword, s);
10195 }
10196
10197 AST_RWLIST_WRLOCK(&host_candidates);
10198 for (var = ast_variable_browse(cfg, "ice_host_candidates"); var; var = var->next) {
10199 struct ast_sockaddr local_addr, advertised_addr;
10200 unsigned int include_local_address = 0;
10201 char *sep;
10202
10203 ast_sockaddr_setnull(&local_addr);
10204 ast_sockaddr_setnull(&advertised_addr);
10205
10206 if (ast_parse_arg(var->name, PARSE_ADDR | PARSE_PORT_IGNORE, &local_addr)) {
10207 ast_log(LOG_WARNING, "Invalid local ICE host address: %s\n", var->name);
10208 continue;
10209 }
10210
10211 sep = strchr(var->value,',');
10212 if (sep) {
10213 *sep = '\0';
10214 sep++;
10215 sep = ast_skip_blanks(sep);
10216 include_local_address = strcmp(sep, "include_local_address") == 0;
10217 }
10218
10219 if (ast_parse_arg(var->value, PARSE_ADDR | PARSE_PORT_IGNORE, &advertised_addr)) {
10220 ast_log(LOG_WARNING, "Invalid advertised ICE host address: %s\n", var->value);
10221 continue;
10222 }
10223
10224 if (!(candidate = ast_calloc(1, sizeof(*candidate)))) {
10225 ast_log(LOG_ERROR, "Failed to allocate ICE host candidate mapping.\n");
10226 break;
10227 }
10228
10229 candidate->include_local = include_local_address;
10230
10231 ast_sockaddr_copy(&candidate->local, &local_addr);
10232 ast_sockaddr_copy(&candidate->advertised, &advertised_addr);
10233
10234 AST_RWLIST_INSERT_TAIL(&host_candidates, candidate, next);
10235 }
10236 AST_RWLIST_UNLOCK(&host_candidates);
10237
10238 ast_rwlock_wrlock(&ice_acl_lock);
10239 ast_rwlock_wrlock(&stun_acl_lock);
10240
10241 ice_acl = ast_free_acl_list(ice_acl);
10242 stun_acl = ast_free_acl_list(stun_acl);
10243
10244 for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
10245 const char* sense = NULL;
10246 struct ast_acl_list **acl = NULL;
10247 if (strncasecmp(var->name, "ice_", 4) == 0) {
10248 sense = var->name + 4;
10249 acl = &ice_acl;
10250 } else if (strncasecmp(var->name, "stun_", 5) == 0) {
10251 sense = var->name + 5;
10252 acl = &stun_acl;
10253 } else {
10254 continue;
10255 }
10256
10257 if (strcasecmp(sense, "blacklist") == 0) {
10258 sense = "deny";
10259 }
10260
10261 if (strcasecmp(sense, "acl") && strcasecmp(sense, "permit") && strcasecmp(sense, "deny")) {
10262 continue;
10263 }
10264
10265 ast_append_acl(sense, var->value, acl, NULL, &acl_subscription_flag);
10266 }
10267 ast_rwlock_unlock(&ice_acl_lock);
10268 ast_rwlock_unlock(&stun_acl_lock);
10269
10270 if (acl_subscription_flag && !acl_change_sub) {
10274 } else if (!acl_subscription_flag && acl_change_sub) {
10276 }
10277#endif
10278#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
10279 if ((s = ast_variable_retrieve(cfg, "general", "dtls_mtu"))) {
10280 if ((sscanf(s, "%d", &dtls_mtu) != 1) || dtls_mtu < 256) {
10281 ast_log(LOG_WARNING, "Value for 'dtls_mtu' could not be read, using default of '%d' instead\n",
10283 dtls_mtu = DEFAULT_DTLS_MTU;
10284 }
10285 }
10286#endif
10287
10288 ast_config_destroy(cfg);
10289
10290 /* Choosing an odd start port casues issues (like a potential infinite loop) and as odd parts are not
10291 chosen anyway, we are going to round up and issue a warning */
10292 if (rtpstart & 1) {
10293 rtpstart++;
10294 ast_log(LOG_WARNING, "Odd start value for RTP port in rtp.conf, rounding up to %d\n", rtpstart);
10295 }
10296
10297 if (rtpstart >= rtpend) {
10298 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
10301 }
10302 ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
10303 return 0;
10304}
10305
10306static int reload_module(void)
10307{
10308 rtp_reload(1, 0);
10309 return 0;
10310}
10311
10312#ifdef HAVE_PJPROJECT
10313static void rtp_terminate_pjproject(void)
10314{
10315 pj_thread_register_check();
10316
10317 if (timer_thread) {
10318 timer_terminate = 1;
10319 pj_thread_join(timer_thread);
10320 pj_thread_destroy(timer_thread);
10321 }
10322
10324 pj_shutdown();
10325}
10326
10327static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
10328{
10330 return;
10331 }
10332
10333 /* There is no simple way to just reload the ACLs, so just execute a forced reload. */
10334 rtp_reload(1, 1);
10335}
10336#endif
10337
10338static int load_module(void)
10339{
10340#ifdef HAVE_PJPROJECT
10341 pj_lock_t *lock;
10342
10344
10346 if (pj_init() != PJ_SUCCESS) {
10348 }
10349
10350 if (pjlib_util_init() != PJ_SUCCESS) {
10351 rtp_terminate_pjproject();
10353 }
10354
10355 if (pjnath_init() != PJ_SUCCESS) {
10356 rtp_terminate_pjproject();
10358 }
10359
10360 ast_pjproject_caching_pool_init(&cachingpool, &pj_pool_factory_default_policy, 0);
10361
10362 pool = pj_pool_create(&cachingpool.factory, "timer", 512, 512, NULL);
10363
10364 if (pj_timer_heap_create(pool, 100, &timer_heap) != PJ_SUCCESS) {
10365 rtp_terminate_pjproject();
10367 }
10368
10369 if (pj_lock_create_recursive_mutex(pool, "rtp%p", &lock) != PJ_SUCCESS) {
10370 rtp_terminate_pjproject();
10372 }
10373
10374 pj_timer_heap_set_lock(timer_heap, lock, PJ_TRUE);
10375
10376 if (pj_thread_create(pool, "timer", &timer_worker_thread, NULL, 0, 0, &timer_thread) != PJ_SUCCESS) {
10377 rtp_terminate_pjproject();
10379 }
10380
10381#endif
10382
10383#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10384 dtls_bio_methods = BIO_meth_new(BIO_TYPE_BIO, "rtp write");
10385 if (!dtls_bio_methods) {
10386#ifdef HAVE_PJPROJECT
10387 rtp_terminate_pjproject();
10388#endif
10390 }
10391 BIO_meth_set_write(dtls_bio_methods, dtls_bio_write);
10392 BIO_meth_set_ctrl(dtls_bio_methods, dtls_bio_ctrl);
10393 BIO_meth_set_create(dtls_bio_methods, dtls_bio_new);
10394 BIO_meth_set_destroy(dtls_bio_methods, dtls_bio_free);
10395#endif
10396
10398#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10399 BIO_meth_free(dtls_bio_methods);
10400#endif
10401#ifdef HAVE_PJPROJECT
10402 rtp_terminate_pjproject();
10403#endif
10405 }
10406
10408#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10409 BIO_meth_free(dtls_bio_methods);
10410#endif
10411#ifdef HAVE_PJPROJECT
10413 rtp_terminate_pjproject();
10414#endif
10416 }
10417
10418 rtp_reload(0, 0);
10419
10421}
10422
10423static int unload_module(void)
10424{
10427
10428#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10429 if (dtls_bio_methods) {
10430 BIO_meth_free(dtls_bio_methods);
10431 }
10432#endif
10433
10434#ifdef HAVE_PJPROJECT
10435 host_candidate_overrides_clear();
10436 pj_thread_register_check();
10437 rtp_terminate_pjproject();
10438
10440 rtp_unload_acl(&ice_acl_lock, &ice_acl);
10441 rtp_unload_acl(&stun_acl_lock, &stun_acl);
10442 clean_stunaddr();
10443#endif
10444
10445 return 0;
10446}
10447
10449 .support_level = AST_MODULE_SUPPORT_CORE,
10450 .load = load_module,
10451 .unload = unload_module,
10453 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
10454#ifdef HAVE_PJPROJECT
10455 .requires = "res_pjproject",
10456#endif
Access Control of various sorts.
struct stasis_message_type * ast_named_acl_change_type(void)
a stasis_message_type for changes against a named ACL or the set of all named ACLs
int ast_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us)
Get our local IP address when contacting a remote host.
Definition acl.c:1021
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
Add a rule to an ACL struct.
Definition acl.c:429
int ast_find_ourip(struct ast_sockaddr *ourip, const struct ast_sockaddr *bindaddr, int family)
Find our IP address.
Definition acl.c:1068
@ AST_SENSE_DENY
Definition acl.h:37
enum ast_acl_sense ast_apply_acl_nolog(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr)
Apply a set of rules to a given IP address, don't log failure.
Definition acl.c:803
struct ast_acl_list * ast_free_acl_list(struct ast_acl_list *acl)
Free a list of ACLs.
Definition acl.c:233
void ast_cli_unregister_multiple(void)
Definition ael_main.c:408
char digit
jack_status_t status
Definition app_jack.c:149
const char * str
Definition app_jack.c:150
enum queue_result id
Definition app_queue.c:1790
pthread_t thread
Definition app_sla.c:335
ast_cond_t cond
Definition app_sla.c:336
ast_mutex_t lock
Definition app_sla.c:337
static volatile unsigned int seq
Definition app_sms.c:126
#define var
Definition ast_expr2f.c:605
void timersub(struct timeval *tvend, struct timeval *tvstart, struct timeval *tvdiff)
char * strsep(char **str, const char *delims)
Asterisk main include file. File version handling, generic pbx functions.
#define ast_free(a)
Definition astmm.h:180
#define ast_strndup(str, len)
A wrapper for strndup()
Definition astmm.h:256
#define ast_strdup(str)
A wrapper for strdup()
Definition astmm.h:241
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition astmm.h:298
void ast_free_ptr(void *ptr)
free() wrapper
Definition astmm.c:1739
#define ast_calloc(num, len)
A wrapper for calloc()
Definition astmm.h:202
#define ast_malloc(len)
A wrapper for malloc()
Definition astmm.h:191
#define ast_log
Definition astobj2.c:42
#define ao2_iterator_next(iter)
Definition astobj2.h:1911
#define ao2_link(container, obj)
Add an object to a container.
Definition astobj2.h:1532
@ CMP_MATCH
Definition astobj2.h:1027
@ CMP_STOP
Definition astobj2.h:1028
#define OBJ_POINTER
Definition astobj2.h:1150
@ AO2_ALLOC_OPT_LOCK_NOLOCK
Definition astobj2.h:367
@ AO2_ALLOC_OPT_LOCK_MUTEX
Definition astobj2.h:363
int ao2_container_count(struct ao2_container *c)
Returns the number of elements in a container.
#define ao2_cleanup(obj)
Definition astobj2.h:1934
#define ao2_find(container, arg, flags)
Definition astobj2.h:1736
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
#define ao2_unlock(a)
Definition astobj2.h:729
#define ao2_replace(dst, src)
Replace one object reference with another cleaning up the original.
Definition astobj2.h:501
#define ao2_lock(a)
Definition astobj2.h:717
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition astobj2.h:459
#define ao2_alloc_options(data_size, destructor_fn, options)
Definition astobj2.h:404
void * ao2_object_get_lockaddr(void *obj)
Return the mutex lock address of an object.
Definition astobj2.c:476
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition astobj2.h:480
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
#define ao2_container_alloc_list(ao2_options, container_options, sort_fn, cmp_fn)
Allocate and initialize a list container.
Definition astobj2.h:1327
#define ao2_alloc(data_size, destructor_fn)
Definition astobj2.h:409
static const char desc[]
Definition cdr_radius.c:84
static PGresult * result
Definition cel_pgsql.c:84
unsigned int tos
Definition chan_iax2.c:379
static struct stasis_subscription * acl_change_sub
Definition chan_iax2.c:352
unsigned int cos
Definition chan_iax2.c:380
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
Definition chan_iax2.c:1584
static const char type[]
static char version[AST_MAX_EXTENSION]
static int answer(void *data)
Definition chan_pjsip.c:687
General Asterisk PBX channel definitions.
Standard Command Line Interface.
#define CLI_SHOWUSAGE
Definition cli.h:45
#define AST_CLI_YESNO(x)
Return Yes or No depending on the argument.
Definition cli.h:71
#define CLI_SUCCESS
Definition cli.h:44
#define AST_CLI_DEFINE(fn, txt,...)
Definition cli.h:197
int ast_cli_completion_add(char *value)
Add a result to a request for completion options.
Definition main/cli.c:2845
void ast_cli(int fd, const char *fmt,...)
Definition clicompat.c:6
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
Definition main/cli.c:1931
@ CLI_INIT
Definition cli.h:152
@ CLI_GENERATE
Definition cli.h:153
#define CLI_FAILURE
Definition cli.h:46
#define ast_cli_register_multiple(e, len)
Register multiple commands.
Definition cli.h:265
static struct ao2_container * codecs
Registered codecs.
Definition codec.c:48
ast_media_type
Types of media.
Definition codec.h:30
@ AST_MEDIA_TYPE_AUDIO
Definition codec.h:32
@ AST_MEDIA_TYPE_UNKNOWN
Definition codec.h:31
@ AST_MEDIA_TYPE_VIDEO
Definition codec.h:33
@ AST_MEDIA_TYPE_END
Definition codec.h:36
@ AST_MEDIA_TYPE_IMAGE
Definition codec.h:34
@ AST_MEDIA_TYPE_TEXT
Definition codec.h:35
unsigned int ast_codec_samples_count(struct ast_frame *frame)
Get the number of samples contained within a frame.
Definition codec.c:379
const char * ast_codec_media_type2str(enum ast_media_type type)
Conversion function to take a media type and turn it into a string.
Definition codec.c:348
static int reconstruct(int sign, int dqln, int y)
Definition codec_g726.c:331
Conversion utility functions.
int ast_str_to_uint(const char *str, unsigned int *res)
Convert the given string to an unsigned integer.
Definition conversions.c:56
Data Buffer API.
void * ast_data_buffer_get(const struct ast_data_buffer *buffer, size_t pos)
Retrieve a data payload from the data buffer.
struct ast_data_buffer * ast_data_buffer_alloc(ast_data_buffer_free_callback free_fn, size_t size)
Allocate a data buffer.
size_t ast_data_buffer_count(const struct ast_data_buffer *buffer)
Return the number of payloads in a data buffer.
void ast_data_buffer_resize(struct ast_data_buffer *buffer, size_t size)
Resize a data buffer.
int ast_data_buffer_put(struct ast_data_buffer *buffer, size_t pos, void *payload)
Place a data payload at a position in the data buffer.
size_t ast_data_buffer_max(const struct ast_data_buffer *buffer)
Return the maximum number of payloads a data buffer can hold.
void * ast_data_buffer_remove(struct ast_data_buffer *buffer, size_t pos)
Remove a data payload from the data buffer.
void ast_data_buffer_free(struct ast_data_buffer *buffer)
Free a data buffer (and all held data payloads)
Core DNS API.
const struct ast_dns_record * ast_dns_record_get_next(const struct ast_dns_record *record)
Get the next DNS record.
Definition dns_core.c:170
int ast_dns_result_get_lowest_ttl(const struct ast_dns_result *result)
Retrieve the lowest TTL from a result.
Definition dns_core.c:112
const char * ast_dns_record_get_data(const struct ast_dns_record *record)
Retrieve the raw DNS record.
Definition dns_core.c:160
const struct ast_dns_record * ast_dns_result_get_records(const struct ast_dns_result *result)
Get the first record of a DNS Result.
Definition dns_core.c:102
struct ast_dns_result * ast_dns_query_get_result(const struct ast_dns_query *query)
Get the result information for a DNS query.
Definition dns_core.c:77
int ast_dns_record_get_rr_type(const struct ast_dns_record *record)
Get the resource record type of a DNS record.
Definition dns_core.c:145
const char * ast_dns_query_get_name(const struct ast_dns_query *query)
Get the name queried in a DNS query.
Definition dns_core.c:57
size_t ast_dns_record_get_data_size(const struct ast_dns_record *record)
Retrieve the size of the raw DNS record.
Definition dns_core.c:165
Internal DNS structure definitions.
DNS Recurring Resolution API.
int ast_dns_resolve_recurring_cancel(struct ast_dns_query_recurring *recurring)
Cancel an asynchronous recurring DNS resolution.
struct ast_dns_query_recurring * ast_dns_resolve_recurring(const char *name, int rr_type, int rr_class, ast_dns_resolve_callback callback, void *data)
Asynchronously resolve a DNS query, and continue resolving it according to the lowest TTL available.
char * end
Definition eagi_proxy.c:73
char buf[BUFSIZE]
Definition eagi_proxy.c:66
char * address
Definition f2c.h:59
#define abs(x)
Definition f2c.h:195
int ast_format_get_smoother_flags(const struct ast_format *format)
Get smoother flags for this format.
Definition format.c:349
enum ast_media_type ast_format_get_type(const struct ast_format *format)
Get the media type of a format.
Definition format.c:354
int ast_format_can_be_smoothed(const struct ast_format *format)
Get whether or not the format can be smoothed.
Definition format.c:344
unsigned int ast_format_get_minimum_bytes(const struct ast_format *format)
Get the minimum number of bytes expected in a frame for this format.
Definition format.c:374
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition format.c:379
unsigned int ast_format_get_minimum_ms(const struct ast_format *format)
Get the minimum amount of media carried in this format.
Definition format.c:364
enum ast_format_cmp_res ast_format_cmp(const struct ast_format *format1, const struct ast_format *format2)
Compare two formats.
Definition format.c:201
@ AST_FORMAT_CMP_EQUAL
Definition format.h:36
@ AST_FORMAT_CMP_NOT_EQUAL
Definition format.h:38
const char * ast_format_get_name(const struct ast_format *format)
Get the name associated with a format.
Definition format.c:334
unsigned int ast_format_get_default_ms(const struct ast_format *format)
Get the default framing size (in milliseconds) for a format.
Definition format.c:359
Media Format Cache API.
int ast_format_cache_is_slinear(struct ast_format *format)
Determines if a format is one of the cached slin formats.
struct ast_format * ast_format_none
Built-in "null" format.
struct ast_format * ast_format_t140_red
Built-in cached t140 red format.
struct ast_format * ast_format_g722
Built-in cached g722 format.
struct ast_format * ast_format_t140
Built-in cached t140 format.
static const char name[]
Definition format_mp3.c:68
static int replace(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
struct stasis_message_type * ast_rtp_rtcp_sent_type(void)
Message type for an RTCP message sent from this Asterisk instance.
struct stasis_message_type * ast_rtp_rtcp_received_type(void)
Message type for an RTCP message received from some external source.
const char * ext
Definition http.c:150
Configuration File Parser.
struct ast_config * ast_config_load2(const char *filename, const char *who_asked, struct ast_flags flags)
Load a config file.
#define CONFIG_STATUS_FILEUNCHANGED
#define CONFIG_STATUS_FILEINVALID
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
Definition extconf.c:1287
@ CONFIG_FLAG_FILEUNCHANGED
const char * ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
struct ast_variable * ast_variable_browse(const struct ast_config *config, const char *category_name)
Definition extconf.c:1213
Asterisk internal frame definitions.
#define ast_frame_byteswap_be(fr)
#define ast_frisolate(fr)
Makes a frame independent of any static storage.
void ast_frame_free(struct ast_frame *frame, int cache)
Frees a frame or list of frames.
Definition main/frame.c:176
@ AST_FRFLAG_HAS_SEQUENCE_NUMBER
@ AST_FRFLAG_HAS_TIMING_INFO
#define ast_frdup(fr)
Copies a frame.
#define ast_frfree(fr)
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
ast_frame_type
Frame types.
@ AST_FRAME_DTMF_END
@ AST_FRAME_DTMF_BEGIN
@ AST_FRAME_CONTROL
@ AST_CONTROL_VIDUPDATE
@ AST_CONTROL_FLASH
@ AST_CONTROL_SRCCHANGE
struct ast_frame ast_null_frame
Definition main/frame.c:79
#define DEBUG_ATLEAST(level)
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_DEBUG
#define LOG_ERROR
#define ast_verb(level,...)
#define LOG_NOTICE
#define LOG_WARNING
#define ast_verbose(...)
struct ssl_ctx_st SSL_CTX
Definition iostream.h:38
struct ssl_st SSL
Definition iostream.h:37
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
Definition json.c:73
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
Definition json.c:612
#define AST_RWLIST_REMOVE_CURRENT
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
Definition linkedlists.h:78
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition linkedlists.h:52
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized.
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
#define AST_RWLIST_TRAVERSE_SAFE_END
#define AST_LIST_LOCK(head)
Locks a list.
Definition linkedlists.h:40
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
#define AST_RWLIST_INSERT_TAIL
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
#define AST_RWLIST_ENTRY
#define AST_LIST_FIRST(head)
Returns the first entry contained in a list.
#define AST_LIST_NEXT(elm, field)
Returns the next entry in the list after the given entry.
Asterisk locking-related definitions:
#define ast_rwlock_wrlock(a)
Definition lock.h:243
#define AST_RWLOCK_INIT_VALUE
Definition lock.h:105
#define ast_cond_init(cond, attr)
Definition lock.h:208
#define ast_cond_timedwait(cond, mutex, time)
Definition lock.h:213
#define ast_rwlock_rdlock(a)
Definition lock.h:242
pthread_cond_t ast_cond_t
Definition lock.h:185
#define ast_rwlock_unlock(a)
Definition lock.h:241
#define ast_cond_signal(cond)
Definition lock.h:210
#define AST_LOG_CATEGORY_DISABLED
#define AST_LOG_CATEGORY_ENABLED
#define ast_debug_category(sublevel, ids,...)
Log for a debug category.
int ast_debug_category_set_sublevel(const char *name, int sublevel)
Set the debug category's sublevel.
int errno
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
Asterisk module definitions.
@ AST_MODFLAG_LOAD_ORDER
Definition module.h:331
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition module.h:557
@ AST_MODPRI_CHANNEL_DEPEND
Definition module.h:340
@ AST_MODULE_SUPPORT_CORE
Definition module.h:121
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition module.h:46
@ AST_MODULE_LOAD_SUCCESS
Definition module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition module.h:78
int ast_sockaddr_ipv4_mapped(const struct ast_sockaddr *addr, struct ast_sockaddr *ast_mapped)
Convert an IPv4-mapped IPv6 address into an IPv4 address.
Definition netsock2.c:37
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition netsock2.h:256
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
Definition netsock2.h:517
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
Definition netsock2.h:167
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
Definition netsock2.c:524
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
Definition netsock2.c:590
#define ast_sockaddr_from_sockaddr(addr, sa)
Converts a struct sockaddr to a struct ast_sockaddr.
Definition netsock2.h:819
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
Definition netsock2.c:413
static char * ast_sockaddr_stringify_host(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only, suitable for a URL (with brack...
Definition netsock2.h:327
ssize_t ast_sendto(int sockfd, const void *buf, size_t len, int flags, const struct ast_sockaddr *dest_addr)
Wrapper around sendto(2) that uses ast_sockaddr.
Definition netsock2.c:614
int ast_sockaddr_is_any(const struct ast_sockaddr *addr)
Determine if the address type is unspecified, or "any" address.
Definition netsock2.c:534
int ast_sockaddr_split_hostport(char *str, char **host, char **port, int flags)
Splits a string into its host and port components.
Definition netsock2.c:164
int ast_set_qos(int sockfd, int tos, int cos, const char *desc)
Set type of service.
Definition netsock2.c:621
ast_transport
Definition netsock2.h:59
@ AST_TRANSPORT_UDP
Definition netsock2.h:60
@ AST_TRANSPORT_TCP
Definition netsock2.h:61
#define ast_sockaddr_to_sin(addr, sin)
Converts a struct ast_sockaddr to a struct sockaddr_in.
Definition netsock2.h:765
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
Definition netsock2.c:230
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized,...
Definition netsock2.h:127
ssize_t ast_recvfrom(int sockfd, void *buf, size_t len, int flags, struct ast_sockaddr *src_addr)
Wrapper around recvfrom(2) that uses struct ast_sockaddr.
Definition netsock2.c:606
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
Definition netsock2.c:388
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
Definition netsock2.h:532
#define ast_sockaddr_from_sin(addr, sin)
Converts a struct sockaddr_in to a struct ast_sockaddr.
Definition netsock2.h:778
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
Definition netsock2.h:138
int ast_sockaddr_is_ipv4(const struct ast_sockaddr *addr)
Determine if the address is an IPv4 address.
Definition netsock2.c:497
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
Definition utils.c:964
Options provided by main asterisk program.
#define AST_PJPROJECT_INIT_LOG_LEVEL()
Get maximum log level pjproject was compiled with.
Definition options.h:177
static int frames
Definition parser.c:51
Core PBX routines and definitions.
static char * generate_random_string(char *buf, size_t size)
Generate 32 byte random string (stolen from chan_sip.c)
static struct stasis_subscription * sub
Statsd channel stats. Exmaple of how to subscribe to Stasis events.
static int reload(void)
int ast_sockaddr_to_pj_sockaddr(const struct ast_sockaddr *addr, pj_sockaddr *pjaddr)
Fill a pj_sockaddr from an ast_sockaddr.
void ast_pjproject_caching_pool_destroy(pj_caching_pool *cp)
Destroy caching pool factory and all cached pools.
int ast_sockaddr_pj_sockaddr_cmp(const struct ast_sockaddr *addr, const pj_sockaddr *pjaddr)
Compare an ast_sockaddr to a pj_sockaddr.
void ast_pjproject_caching_pool_init(pj_caching_pool *cp, const pj_pool_factory_policy *policy, pj_size_t max_capacity)
Initialize the caching pool factory.
static pj_caching_pool cachingpool
Pool factory used by pjlib to allocate memory.
#define OLD_PACKET_COUNT
#define TURN_STATE_WAIT_TIME
static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
static int rtpdebugport
static void ast_rtp_update_source(struct ast_rtp_instance *instance)
#define TRANSPORT_TURN_RTCP
static int ast_rtp_destroy(struct ast_rtp_instance *instance)
#define RTCP_LENGTH_SHIFT
struct ast_srtp_res * res_srtp
Definition rtp_engine.c:182
static int ast_rtp_rtcp_handle_nack(struct ast_rtp_instance *instance, unsigned int *nackdata, unsigned int position, unsigned int length)
static int rtp_reload(int reload, int by_external_config)
#define RTCP_PAYLOAD_TYPE_SHIFT
#define DEFAULT_RTP_RECV_BUFFER_SIZE
#define MAX_TIMESTAMP_SKEW
#define DEFAULT_ICESUPPORT
static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
#define RTCP_VALID_VALUE
#define RTCP_FB_NACK_BLOCK_WORD_LENGTH
static struct ast_sockaddr rtpdebugaddr
#define DEFAULT_LEARNING_MIN_SEQUENTIAL
#define FLAG_3389_WARNING
static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
static int create_new_socket(const char *type, struct ast_sockaddr *bind_addr)
static int rtp_transport_wide_cc_feedback_produce(const void *data)
#define RTCP_RR_BLOCK_WORD_LENGTH
static struct ast_frame * ast_rtcp_interpret(struct ast_rtp_instance *instance, struct ast_srtp *srtp, const unsigned char *rtcpdata, size_t size, struct ast_sockaddr *addr)
static const char * rtcp_payload_subtype2str(unsigned int pt, unsigned int subtype)
static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data)
static char * handle_cli_rtp_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static struct ast_frame * ast_rtcp_read(struct ast_rtp_instance *instance)
#define RTP_IGNORE_FIRST_PACKETS_COUNT
static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
static int rtcpdebugport
#define RTCP_SR_BLOCK_WORD_LENGTH
static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
#define DEFAULT_RTP_END
static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
static struct ast_rtp_instance * rtp_find_instance_by_packet_source_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc)
#define SRTP_MASTER_LEN
#define RTCP_REPORT_COUNT_SHIFT
#define RTCP_PT_FUR
#define RTCP_DEFAULT_INTERVALMS
static void rtp_deallocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
#define RTP_DTLS_ESTABLISHED
static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, struct ast_rtp_instance *instance1, unsigned int *rtpheader, int len, int hdrlen)
#define DEFAULT_DTMF_TIMEOUT
static void put_unaligned_time24(void *p, uint32_t time_msw, uint32_t time_lsw)
#define RTCP_MAX_INTERVALMS
static int ast_rtcp_generate_nack(struct ast_rtp_instance *instance, unsigned char *rtcpheader)
static char * handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
strict_rtp_mode
@ STRICT_RTP_SEQNO
@ STRICT_RTP_YES
@ STRICT_RTP_NO
static void rtp_transport_wide_cc_feedback_status_append(unsigned char *rtcpheader, int *packet_len, int *status_vector_chunk_bits, uint16_t *status_vector_chunk, int *run_length_chunk_count, int *run_length_chunk_status, int status)
static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent)
static struct ast_rtp_engine asterisk_rtp_engine
static const char * rtcp_payload_type2str(unsigned int pt)
#define TRANSPORT_SOCKET_RTP
static int rtpend
static void rtp_instance_parse_transport_wide_cc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned char *data, int len)
static void calc_rxstamp_and_jitter(struct timeval *tv, struct ast_rtp *rtp, unsigned int rx_rtp_ts, int mark)
static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
#define RTCP_PT_RR
#define SRTP_MASTER_KEY_LEN
static int learning_min_sequential
static int rtp_allocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
static char * rtcp_do_debug_ip(struct ast_cli_args *a)
static int ast_rtcp_generate_report(struct ast_rtp_instance *instance, unsigned char *rtcpheader, struct ast_rtp_rtcp_report *rtcp_report, int *sr)
static struct ast_frame * ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
static char * handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
struct ast_srtp_policy_res * res_srtp_policy
Definition rtp_engine.c:183
#define RTCP_PT_BYE
static struct ast_rtp_instance * __rtp_find_instance_by_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc, int source)
static void calculate_lost_packet_statistics(struct ast_rtp *rtp, unsigned int *lost_packets, int *fraction_lost)
#define RTCP_HEADER_SSRC_LENGTH
static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark, struct frame_list *frames)
#define RTCP_VALID_MASK
static int srtp_replay_protection
static void ast_rtp_set_stream_num(struct ast_rtp_instance *instance, int stream_num)
static int learning_min_duration
static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
static int ast_rtcp_generate_compound_prefix(struct ast_rtp_instance *instance, unsigned char *rtcpheader, struct ast_rtp_rtcp_report *report, int *sr)
static void update_jitter_stats(struct ast_rtp *rtp, unsigned int ia_jitter)
#define RTCP_FB_REMB_BLOCK_WORD_LENGTH
#define RTCP_PT_PSFB
static struct ast_frame * process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark)
#define DEFAULT_SRTP_REPLAY_PROTECTION
#define DEFAULT_DTLS_MTU
static int reload_module(void)
#define FLAG_NAT_INACTIVE
static int rtcp_debug_test_addr(struct ast_sockaddr *addr)
static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
static void ast_rtp_change_source(struct ast_rtp_instance *instance)
static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
static void calc_mean_and_standard_deviation(double new_sample, double *mean, double *std_dev, unsigned int *count)
static int compare_by_value(int elem, int value)
Helper function to compare an elem in a vector by value.
static int update_rtt_stats(struct ast_rtp *rtp, unsigned int lsr, unsigned int dlsr)
static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
static struct ast_sockaddr rtcpdebugaddr
static struct ast_rtp_instance * rtp_find_instance_by_media_source_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc)
#define MAXIMUM_RTP_RECV_BUFFER_SIZE
static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
#define STRICT_RTP_LEARN_TIMEOUT
Strict RTP learning timeout time in milliseconds.
#define RTCP_VERSION_SHIFTED
static int rtcpinterval
static int strictrtp
static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
static void rtp_instance_parse_extmap_extensions(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned char *extension, int len)
static int find_by_value(int elem, int value)
Helper function to find an elem in a vector by value.
#define RTCP_REPORT_COUNT_MASK
static void rtp_instance_unlock(struct ast_rtp_instance *instance)
#define DEFAULT_RTP_START
#define TRANSPORT_TURN_RTP
static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
static int rtpstart
#define MINIMUM_RTP_PORT
static struct ast_cli_entry cli_rtp[]
static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
#define RESCALE(in, inmin, inmax, outmin, outmax)
#define RTCP_PT_SDES
#define MISSING_SEQNOS_ADDED_TRIGGER
#define SRTP_MASTER_SALT_LEN
static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
#define RTCP_PAYLOAD_TYPE_MASK
#define DEFAULT_RTP_SEND_BUFFER_SIZE
#define FLAG_NAT_ACTIVE
#define FLAG_NEED_MARKER_BIT
static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
#define RTCP_MIN_INTERVALMS
static void ast_rtp_stop(struct ast_rtp_instance *instance)
#define FLAG_REQ_LOCAL_BRIDGE_BIT
#define RTCP_PT_SR
static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp)
static int load_module(void)
static int ast_rtcp_calculate_sr_rr_statistics(struct ast_rtp_instance *instance, struct ast_rtp_rtcp_report *rtcp_report, struct ast_sockaddr remote_address, int ice, int sr)
#define RTCP_VERSION_MASK_SHIFTED
#define CALC_LEARNING_MIN_DURATION(count)
Calculate the min learning duration in ms.
static int rtp_transport_wide_cc_packet_statistics_cmp(struct rtp_transport_wide_cc_packet_statistics a, struct rtp_transport_wide_cc_packet_statistics b)
#define SSRC_MAPPING_ELEM_CMP(elem, value)
SSRC mapping comparator for AST_VECTOR_REMOVE_CMP_UNORDERED()
static int rtp_debug_test_addr(struct ast_sockaddr *addr)
static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
strict_rtp_state
@ STRICT_RTP_LEARN
@ STRICT_RTP_OPEN
@ STRICT_RTP_CLOSED
static int unload_module(void)
static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc)
static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
#define FLAG_NAT_INACTIVE_NOWARN
static int rtcp_mux(struct ast_rtp *rtp, const unsigned char *packet)
static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
#define TRANSPORT_SOCKET_RTCP
static void rtp_learning_start(struct ast_rtp *rtp)
Start the strictrtp learning mode.
static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
static char * rtp_do_debug_ip(struct ast_cli_args *a)
static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance)
#define MAXIMUM_RTP_PORT
static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
static struct ast_frame * ast_rtp_interpret(struct ast_rtp_instance *instance, struct ast_srtp *srtp, const struct ast_sockaddr *remote_address, unsigned char *read_area, int length, int prev_seqno, unsigned int bundled)
static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
static struct ast_frame * red_t140_to_red(struct rtp_red *red)
static int ast_rtcp_generate_sdes(struct ast_rtp_instance *instance, unsigned char *rtcpheader, struct ast_rtp_rtcp_report *rtcp_report)
#define SEQNO_CYCLE_OVER
static double calc_media_experience_score(struct ast_rtp_instance *instance, double normdevrtt, double normdev_rxjitter, double stdev_rxjitter, double normdev_rxlost)
Calculate a "media experience score" based on given data.
static void update_reported_mes_stats(struct ast_rtp *rtp)
static int dtmftimeout
#define DEFAULT_STRICT_RTP
static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
generate comfort noice (CNG)
static char * handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
static void update_lost_stats(struct ast_rtp *rtp, unsigned int lost_packets)
static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
static const char * ast_rtp_get_cname(struct ast_rtp_instance *instance)
static void rtp_write_rtcp_psfb(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_frame *frame, struct ast_sockaddr *remote_address)
static int rtcpstats
static struct ast_frame * process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, int payloadtype, int mark)
#define RTP_SEQ_MOD
static struct ast_frame * create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
static void rtp_write_rtcp_fir(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *remote_address)
#define DEFAULT_TURN_PORT
#define MAXIMUM_RTP_SEND_BUFFER_SIZE
static int red_write(const void *data)
Write t140 redundancy frame.
#define DEFAULT_STUN_SOFTWARE_ATTRIBUTE
#define RTCP_LENGTH_MASK
#define DEFAULT_LEARNING_MIN_DURATION
static void update_local_mes_stats(struct ast_rtp *rtp)
static void rtp_transport_wide_cc_feedback_status_vector_append(unsigned char *rtcpheader, int *packet_len, int *status_vector_chunk_bits, uint16_t *status_vector_chunk, int status)
static int ast_rtp_extension_enable(struct ast_rtp_instance *instance, enum ast_rtp_extension extension)
static int ast_rtcp_write(const void *data)
Write a RTCP packet to the far end.
ast_srtp_suite
Definition res_srtp.h:56
@ AST_AES_CM_128_HMAC_SHA1_80
Definition res_srtp.h:58
@ AST_AES_CM_128_HMAC_SHA1_32
Definition res_srtp.h:59
static void cleanup(void)
Clean up any old apps that we don't need any more.
Definition res_stasis.c:327
#define NULL
Definition resample.c:96
Pluggable RTP Architecture.
ast_rtp_dtls_setup
DTLS setup types.
Definition rtp_engine.h:564
@ AST_RTP_DTLS_SETUP_PASSIVE
Definition rtp_engine.h:566
@ AST_RTP_DTLS_SETUP_HOLDCONN
Definition rtp_engine.h:568
@ AST_RTP_DTLS_SETUP_ACTPASS
Definition rtp_engine.h:567
@ AST_RTP_DTLS_SETUP_ACTIVE
Definition rtp_engine.h:565
#define AST_RTP_RTCP_PSFB
Definition rtp_engine.h:329
#define AST_DEBUG_CATEGORY_DTLS
#define ast_debug_rtcp_packet_is_allowed
ast_rtp_ice_role
ICE role during negotiation.
Definition rtp_engine.h:519
@ AST_RTP_ICE_ROLE_CONTROLLING
Definition rtp_engine.h:521
@ AST_RTP_ICE_ROLE_CONTROLLED
Definition rtp_engine.h:520
#define AST_RTP_RTCP_FMT_FIR
Definition rtp_engine.h:337
#define ast_debug_rtcp(sublevel,...)
Log debug level RTCP information.
struct ast_format * ast_rtp_codecs_get_preferred_format(struct ast_rtp_codecs *codecs)
Retrieve rx preferred format.
ast_rtp_ice_component_type
ICE component types.
Definition rtp_engine.h:513
@ AST_RTP_ICE_COMPONENT_RTCP
Definition rtp_engine.h:515
@ AST_RTP_ICE_COMPONENT_RTP
Definition rtp_engine.h:514
struct ast_rtp_rtcp_report * ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
Allocate an ao2 ref counted instance of ast_rtp_rtcp_report.
struct ast_rtp_payload_type * ast_rtp_codecs_get_payload(struct ast_rtp_codecs *codecs, int payload)
Retrieve rx payload mapped information by payload type.
int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
Get the value of an RTP instance property.
Definition rtp_engine.c:744
ast_rtp_dtls_hash
DTLS fingerprint hashes.
Definition rtp_engine.h:578
@ AST_RTP_DTLS_HASH_SHA1
Definition rtp_engine.h:580
@ AST_RTP_DTLS_HASH_SHA256
Definition rtp_engine.h:579
int ast_rtp_engine_srtp_is_registered(void)
ast_rtp_dtmf_mode
Definition rtp_engine.h:151
#define AST_RED_MAX_GENERATION
Definition rtp_engine.h:98
#define AST_RTP_DTMF
Definition rtp_engine.h:294
ast_rtp_instance_rtcp
Definition rtp_engine.h:283
@ AST_RTP_INSTANCE_RTCP_MUX
Definition rtp_engine.h:289
@ AST_RTP_INSTANCE_RTCP_STANDARD
Definition rtp_engine.h:287
void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp, struct stasis_message_type *message_type, struct ast_rtp_rtcp_report *report, struct ast_json *blob)
Publish an RTCP message to Stasis Message Bus API.
struct ast_srtp * ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance, int rtcp)
Obtain the SRTP instance associated with an RTP instance.
#define AST_RTP_STAT_TERMINATOR(combined)
Definition rtp_engine.h:500
#define AST_RTP_RTCP_RTPFB
Definition rtp_engine.h:327
struct ast_rtp_instance * ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
Get the other RTP instance that an instance is bridged to.
ast_rtp_dtls_verify
DTLS verification settings.
Definition rtp_engine.h:584
@ AST_RTP_DTLS_VERIFY_FINGERPRINT
Definition rtp_engine.h:586
@ AST_RTP_DTLS_VERIFY_CERTIFICATE
Definition rtp_engine.h:587
#define ast_debug_rtp_packet_is_allowed
#define AST_LOG_CATEGORY_RTCP_PACKET
ast_rtp_instance_stat
Definition rtp_engine.h:185
@ AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS
Definition rtp_engine.h:207
@ AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS
Definition rtp_engine.h:203
@ AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS
Definition rtp_engine.h:199
@ AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVMES
Definition rtp_engine.h:270
@ AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER
Definition rtp_engine.h:223
@ AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVMES
Definition rtp_engine.h:278
@ AST_RTP_INSTANCE_STAT_MIN_RTT
Definition rtp_engine.h:243
@ AST_RTP_INSTANCE_STAT_TXMES
Definition rtp_engine.h:262
@ AST_RTP_INSTANCE_STAT_CHANNEL_UNIQUEID
Definition rtp_engine.h:253
@ AST_RTP_INSTANCE_STAT_TXPLOSS
Definition rtp_engine.h:195
@ AST_RTP_INSTANCE_STAT_MAX_RTT
Definition rtp_engine.h:241
@ AST_RTP_INSTANCE_STAT_RXPLOSS
Definition rtp_engine.h:197
@ AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER
Definition rtp_engine.h:221
@ AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER
Definition rtp_engine.h:229
@ AST_RTP_INSTANCE_STAT_REMOTE_MINMES
Definition rtp_engine.h:268
@ AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER
Definition rtp_engine.h:227
@ AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS
Definition rtp_engine.h:201
@ AST_RTP_INSTANCE_STAT_LOCAL_MINMES
Definition rtp_engine.h:276
@ AST_RTP_INSTANCE_STAT_TXOCTETCOUNT
Definition rtp_engine.h:255
@ AST_RTP_INSTANCE_STAT_RXMES
Definition rtp_engine.h:264
@ AST_RTP_INSTANCE_STAT_REMOTE_STDEVMES
Definition rtp_engine.h:272
@ AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS
Definition rtp_engine.h:211
@ AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS
Definition rtp_engine.h:205
@ AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS
Definition rtp_engine.h:213
@ AST_RTP_INSTANCE_STAT_REMOTE_MAXMES
Definition rtp_engine.h:266
@ AST_RTP_INSTANCE_STAT_TXCOUNT
Definition rtp_engine.h:189
@ AST_RTP_INSTANCE_STAT_STDEVRTT
Definition rtp_engine.h:247
@ AST_RTP_INSTANCE_STAT_COMBINED_MES
Definition rtp_engine.h:260
@ AST_RTP_INSTANCE_STAT_LOCAL_MAXMES
Definition rtp_engine.h:274
@ AST_RTP_INSTANCE_STAT_RXJITTER
Definition rtp_engine.h:219
@ AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS
Definition rtp_engine.h:209
@ AST_RTP_INSTANCE_STAT_LOCAL_SSRC
Definition rtp_engine.h:249
@ AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER
Definition rtp_engine.h:225
@ AST_RTP_INSTANCE_STAT_COMBINED_JITTER
Definition rtp_engine.h:215
@ AST_RTP_INSTANCE_STAT_TXJITTER
Definition rtp_engine.h:217
@ AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER
Definition rtp_engine.h:231
@ AST_RTP_INSTANCE_STAT_COMBINED_LOSS
Definition rtp_engine.h:193
@ AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER
Definition rtp_engine.h:235
@ AST_RTP_INSTANCE_STAT_COMBINED_RTT
Definition rtp_engine.h:237
@ AST_RTP_INSTANCE_STAT_NORMDEVRTT
Definition rtp_engine.h:245
@ AST_RTP_INSTANCE_STAT_RTT
Definition rtp_engine.h:239
@ AST_RTP_INSTANCE_STAT_RXOCTETCOUNT
Definition rtp_engine.h:257
@ AST_RTP_INSTANCE_STAT_LOCAL_STDEVMES
Definition rtp_engine.h:280
@ AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER
Definition rtp_engine.h:233
@ AST_RTP_INSTANCE_STAT_RXCOUNT
Definition rtp_engine.h:191
@ AST_RTP_INSTANCE_STAT_REMOTE_SSRC
Definition rtp_engine.h:251
void * ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
Get the data portion of an RTP instance.
Definition rtp_engine.c:591
#define ast_rtp_instance_get_remote_address(instance, address)
Get the address of the remote endpoint that we are sending RTP to.
enum ast_media_type ast_rtp_codecs_get_stream_type(struct ast_rtp_codecs *codecs)
Determine the type of RTP stream media from the codecs mapped.
#define AST_RTP_RTCP_FMT_NACK
Definition rtp_engine.h:333
#define ast_debug_rtp(sublevel,...)
Log debug level RTP information.
void ast_rtp_instance_set_last_tx(struct ast_rtp_instance *rtp, time_t time)
Set the last RTP transmission time.
void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
Set the data portion of an RTP instance.
Definition rtp_engine.c:586
int ast_rtp_codecs_payload_code_tx_sample_rate(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code, unsigned int sample_rate)
Retrieve a tx mapped payload type based on whether it is an Asterisk format and the code.
void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
Set the value of an RTP instance property.
Definition rtp_engine.c:733
int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int payload)
Search for the tx payload type in the ast_rtp_codecs structure.
int ast_rtp_codecs_get_preferred_dtmf_format_rate(struct ast_rtp_codecs *codecs)
Retrieve rx preferred dtmf format sample rate.
void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance, struct ast_sockaddr *address)
Get the local address that we are expecting RTP on.
Definition rtp_engine.c:671
@ AST_RTP_ICE_CANDIDATE_TYPE_RELAYED
Definition rtp_engine.h:509
@ AST_RTP_ICE_CANDIDATE_TYPE_SRFLX
Definition rtp_engine.h:508
@ AST_RTP_ICE_CANDIDATE_TYPE_HOST
Definition rtp_engine.h:507
#define AST_DEBUG_CATEGORY_ICE
int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance, const struct ast_sockaddr *address)
Set the address that we are expecting to receive RTP on.
Definition rtp_engine.c:616
int ast_rtp_get_rate(const struct ast_format *format)
Retrieve the sample rate of a format according to RTP specifications.
int ast_rtp_codecs_payload_code_tx(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
Retrieve a tx mapped payload type based on whether it is an Asterisk format and the code.
ast_rtp_extension
Known RTP extensions.
Definition rtp_engine.h:593
@ AST_RTP_EXTENSION_TRANSPORT_WIDE_CC
Definition rtp_engine.h:599
@ AST_RTP_EXTENSION_ABS_SEND_TIME
Definition rtp_engine.h:597
int ast_rtp_payload_mapping_tx_is_present(struct ast_rtp_codecs *codecs, const struct ast_rtp_payload_type *to_match)
Determine if a type of payload is already present in mappings.
#define ast_rtp_instance_set_remote_address(instance, address)
Set the address of the remote endpoint that we are sending RTP to.
#define AST_RTP_RTCP_FMT_REMB
Definition rtp_engine.h:339
ast_rtp_dtls_connection
DTLS connection states.
Definition rtp_engine.h:572
@ AST_RTP_DTLS_CONNECTION_NEW
Definition rtp_engine.h:573
@ AST_RTP_DTLS_CONNECTION_EXISTING
Definition rtp_engine.h:574
#define ast_debug_dtls(sublevel,...)
Log debug level DTLS information.
ast_rtp_property
Definition rtp_engine.h:116
@ AST_RTP_PROPERTY_NAT
Definition rtp_engine.h:118
@ AST_RTP_PROPERTY_RETRANS_RECV
Definition rtp_engine.h:130
@ AST_RTP_PROPERTY_RETRANS_SEND
Definition rtp_engine.h:132
@ AST_RTP_PROPERTY_RTCP
Definition rtp_engine.h:126
@ AST_RTP_PROPERTY_ASYMMETRIC_CODEC
Definition rtp_engine.h:128
@ AST_RTP_PROPERTY_DTMF
Definition rtp_engine.h:120
@ AST_RTP_PROPERTY_DTMF_COMPENSATE
Definition rtp_engine.h:122
@ AST_RTP_PROPERTY_REMB
Definition rtp_engine.h:134
#define ast_debug_dtls_packet_is_allowed
#define AST_LOG_CATEGORY_RTP_PACKET
#define AST_RTP_STAT_STRCPY(current_stat, combined, placement, value)
Definition rtp_engine.h:492
#define ast_debug_ice(sublevel,...)
Log debug level ICE information.
void ast_rtp_instance_get_requested_target_address(struct ast_rtp_instance *instance, struct ast_sockaddr *address)
Get the requested target address of the remote endpoint.
Definition rtp_engine.c:701
int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance, const struct ast_sockaddr *address)
Set the incoming source address of the remote endpoint that we are sending RTP to.
Definition rtp_engine.c:634
int ast_rtp_instance_extmap_get_id(struct ast_rtp_instance *instance, enum ast_rtp_extension extension)
Retrieve the id for an RTP extension.
Definition rtp_engine.c:914
#define AST_RTP_CN
Definition rtp_engine.h:296
int ast_rtp_codecs_get_preferred_dtmf_format_pt(struct ast_rtp_codecs *codecs)
Retrieve rx preferred dtmf format payload type.
int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
Unregister an RTP engine.
Definition rtp_engine.c:370
#define AST_RTP_RTCP_FMT_TRANSPORT_WIDE_CC
Definition rtp_engine.h:341
struct ast_rtp_codecs * ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
Get the codecs structure of an RTP instance.
Definition rtp_engine.c:755
const char * ast_rtp_instance_get_channel_id(struct ast_rtp_instance *instance)
Get the unique ID of the channel that owns this RTP instance.
Definition rtp_engine.c:576
unsigned int ast_rtp_codecs_get_framing(struct ast_rtp_codecs *codecs)
Get the framing used for a set of codecs.
unsigned int ast_rtp_instance_get_ssrc(struct ast_rtp_instance *rtp)
Retrieve the local SSRC value that we will be using.
#define AST_RTP_STAT_SET(current_stat, combined, placement, value)
Definition rtp_engine.h:484
#define DEFAULT_DTMF_SAMPLE_RATE_MS
Definition rtp_engine.h:110
int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy, int rtcp)
Add or replace the SRTP policies for the given RTP instance.
#define AST_RTP_RTCP_FMT_PLI
Definition rtp_engine.h:335
#define ast_rtp_engine_register(engine)
Definition rtp_engine.h:852
#define AST_RTP_CISCO_DTMF
Definition rtp_engine.h:298
#define AST_SCHED_DEL_UNREF(sched, id, refcall)
schedule task to get deleted and call unref function
Definition sched.h:82
#define AST_SCHED_DEL(sched, id)
Remove a scheduler entry.
Definition sched.h:46
int ast_sched_del(struct ast_sched_context *con, int id) attribute_warn_unused_result
Deletes a scheduled event.
Definition sched.c:614
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
Definition sched.c:567
int ast_sched_add_variable(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data, int variable) attribute_warn_unused_result
Adds a scheduled event with rescheduling support.
Definition sched.c:526
int(* ast_sched_cb)(const void *data)
scheduler callback
Definition sched.h:178
Security Event Reporting API.
struct stasis_topic * ast_security_topic(void)
A stasis_topic which publishes messages for security related issues.
Asterisk internal frame definitions.
void ast_smoother_set_flags(struct ast_smoother *smoother, int flags)
Definition smoother.c:123
#define ast_smoother_feed_be(s, f)
Definition smoother.h:77
int ast_smoother_test_flag(struct ast_smoother *s, int flag)
Definition smoother.c:128
void ast_smoother_free(struct ast_smoother *s)
Definition smoother.c:220
#define AST_SMOOTHER_FLAG_FORCED
Definition smoother.h:36
struct ast_frame * ast_smoother_read(struct ast_smoother *s)
Definition smoother.c:169
#define ast_smoother_feed(s, f)
Definition smoother.h:75
struct ast_smoother * ast_smoother_new(int bytes)
Definition smoother.c:108
#define AST_SMOOTHER_FLAG_BE
Definition smoother.h:35
@ STASIS_SUBSCRIPTION_FILTER_SELECTIVE
Definition stasis.h:297
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
Definition stasis.c:1090
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
Definition stasis.c:1144
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
Definition stasis.c:1201
#define stasis_subscribe(topic, callback, data)
Definition stasis.h:649
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
Definition strings.h:80
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true"....
Definition utils.c:2235
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition strings.h:65
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is "false"....
Definition utils.c:2252
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition strings.h:425
char *attribute_pure ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
Definition strings.h:161
Generic container type.
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
Definition astobj2.h:1821
Wrapper for an ast_acl linked list.
Definition acl.h:76
Structure to describe a channel "technology", ie a channel driver See for examples:
Definition channel.h:648
Main Channel structure associated with a channel.
descriptor for a cli entry.
Definition cli.h:171
int args
This gets set in ast_cli_register()
Definition cli.h:185
char * command
Definition cli.h:186
const char * usage
Definition cli.h:177
Data buffer containing fixed number of data payloads.
Definition data_buffer.c:59
A recurring DNS query.
A DNS query.
For AST_LIST.
char data[0]
The raw DNS record.
int rr_type
Resource record type.
The result of a DNS query.
Structure used to handle boolean flags.
Definition utils.h:220
Definition of a media format.
Definition format.c:43
struct ast_codec * codec
Pointer to the codec in use for this format.
Definition format.c:47
struct ast_format * format
Data structure associated with a single frame of data.
struct ast_frame_subclass subclass
struct timeval delivery
enum ast_frame_type frametype
union ast_frame::@239 data
Abstract JSON element (object, array, string, int, ...).
Structure defining an RTCP session.
double reported_mes
unsigned int themrxlsr
unsigned int rxmes_count
unsigned int received_prior
unsigned int sr_count
unsigned char frame_buf[512+AST_FRIENDLY_OFFSET]
double reported_maxjitter
unsigned int reported_mes_count
double reported_normdev_lost
double reported_minlost
double normdevrtt
double reported_normdev_mes
double minrxjitter
unsigned int soc
unsigned int lastsrtxcount
double reported_maxmes
struct ast_sockaddr them
unsigned int reported_lost
double reported_stdev_jitter
unsigned int reported_jitter_count
double normdev_rxjitter
double accumulated_transit
double reported_stdev_lost
struct timeval txlsr
enum ast_rtp_instance_rtcp type
unsigned int spc
unsigned int rxjitter_count
unsigned int reported_lost_count
double normdev_rxlost
double reported_stdev_mes
unsigned int rtt_count
double normdev_rxmes
double maxrxjitter
double reported_normdev_jitter
double reported_maxlost
unsigned int rxlost_count
unsigned int rr_count
double stdev_rxjitter
double reported_jitter
double stdev_rxmes
double reported_minjitter
struct ast_sockaddr us
struct timeval rxlsr
char * local_addr_str
unsigned int expected_prior
double reported_minmes
double stdev_rxlost
DTLS configuration structure.
Definition rtp_engine.h:605
enum ast_rtp_dtls_setup default_setup
Definition rtp_engine.h:608
enum ast_rtp_dtls_verify verify
Definition rtp_engine.h:611
unsigned int rekey
Definition rtp_engine.h:607
enum ast_rtp_dtls_hash hash
Definition rtp_engine.h:610
unsigned int enabled
Definition rtp_engine.h:606
unsigned int ephemeral_cert
Definition rtp_engine.h:617
enum ast_srtp_suite suite
Definition rtp_engine.h:609
Structure that represents the optional DTLS SRTP support within an RTP engine.
Definition rtp_engine.h:621
int(* set_configuration)(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
Definition rtp_engine.h:623
Structure for an ICE candidate.
Definition rtp_engine.h:525
struct ast_sockaddr address
Definition rtp_engine.h:530
enum ast_rtp_ice_component_type id
Definition rtp_engine.h:527
struct ast_sockaddr relay_address
Definition rtp_engine.h:531
enum ast_rtp_ice_candidate_type type
Definition rtp_engine.h:532
Structure that represents the optional ICE support within an RTP engine.
Definition rtp_engine.h:536
void(* set_authentication)(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
Definition rtp_engine.h:538
void(* start)(struct ast_rtp_instance *instance)
Definition rtp_engine.h:542
const char * name
Definition rtp_engine.h:667
struct ast_rtp_engine_dtls * dtls
Definition rtp_engine.h:744
unsigned int remote_ssrc
Definition rtp_engine.h:454
unsigned int local_ssrc
Definition rtp_engine.h:452
unsigned int rxoctetcount
Definition rtp_engine.h:460
unsigned int txoctetcount
Definition rtp_engine.h:458
char channel_uniqueid[MAX_CHANNEL_ID]
Definition rtp_engine.h:456
An object that represents data received in a feedback report.
Definition rtp_engine.h:388
struct ast_rtp_rtcp_feedback_remb remb
Definition rtp_engine.h:391
Structure for storing RTP packets for retransmission.
A report block within a SR/RR report.
Definition rtp_engine.h:346
unsigned int highest_seq_no
Definition rtp_engine.h:352
struct ast_rtp_rtcp_report_block::@291 lost_count
unsigned short fraction
Definition rtp_engine.h:349
An object that represents data sent during a SR/RR RTCP report.
Definition rtp_engine.h:361
struct ast_rtp_rtcp_report::@292 sender_information
unsigned int type
Definition rtp_engine.h:364
unsigned short reception_report_count
Definition rtp_engine.h:362
unsigned int rtp_timestamp
Definition rtp_engine.h:367
struct ast_rtp_rtcp_report_block * report_block[0]
Definition rtp_engine.h:374
struct timeval ntp_timestamp
Definition rtp_engine.h:366
unsigned int octet_count
Definition rtp_engine.h:369
unsigned int ssrc
Definition rtp_engine.h:363
unsigned int packet_count
Definition rtp_engine.h:368
RTP session description.
unsigned int rxcount
unsigned int lastividtimestamp
unsigned int dtmf_duration
unsigned int dtmfsamples
unsigned int ssrc_orig
struct ast_format * lasttxformat
struct rtp_transport_wide_cc_statistics transport_wide_cc
unsigned int lastts
struct ast_smoother * smoother
struct ast_sched_context * sched
unsigned short seedrxseqno
struct timeval txcore
unsigned int remote_seed_rx_rtp_ts_stable
enum ast_rtp_dtmf_mode dtmfmode
struct ast_sockaddr strict_rtp_address
double rxstart_stable
enum strict_rtp_state strict_rtp_state
unsigned short seqno
unsigned int rxoctetcount
struct timeval rxcore
unsigned int last_seqno
struct ast_frame f
struct ast_rtcp * rtcp
unsigned int themssrc_valid
struct ast_rtp::@513 ssrc_mapping
double rxjitter
unsigned int dtmf_timeout
char cname[AST_UUID_STR_LEN]
unsigned int txcount
unsigned char rawdata[8192+AST_FRIENDLY_OFFSET]
unsigned int last_transit_time_samples
unsigned int cycles
unsigned int lastovidtimestamp
unsigned int ssrc
unsigned int asymmetric_codec
double rxjitter_samples
struct ast_rtp::@512 missing_seqno
struct ast_data_buffer * recv_buffer
optional_ts last_end_timestamp
unsigned int lastotexttimestamp
unsigned int flags
struct timeval dtmfmute
struct ast_sockaddr bind_address
unsigned char ssrc_saved
struct ast_data_buffer * send_buffer
struct rtp_learning_info rtp_source_learn
struct ast_rtp_instance * owner
The RTP instance owning us (used for debugging purposes) We don't hold a reference to the instance be...
unsigned int remote_seed_rx_rtp_ts
unsigned int lastitexttimestamp
unsigned int dtmf_samplerate_ms
unsigned int lastdigitts
unsigned int txoctetcount
struct ast_rtp_instance * bundled
struct rtp_red * red
struct ast_format * lastrxformat
unsigned int themssrc
Structure for rwlock and tracking information.
Definition lock.h:164
Socket address structure.
Definition netsock2.h:97
socklen_t len
Definition netsock2.h:99
void(* destroy)(struct ast_srtp_policy *policy)
Definition res_srtp.h:72
int(* set_master_key)(struct ast_srtp_policy *policy, const unsigned char *key, size_t key_len, const unsigned char *salt, size_t salt_len)
Definition res_srtp.h:74
void(* set_ssrc)(struct ast_srtp_policy *policy, unsigned long ssrc, int inbound)
Definition res_srtp.h:75
int(* set_suite)(struct ast_srtp_policy *policy, enum ast_srtp_suite suite)
Definition res_srtp.h:73
struct ast_srtp_policy *(* alloc)(void)
Definition res_srtp.h:71
int(* unprotect)(struct ast_srtp *srtp, void *buf, int *size, int rtcp)
Definition res_srtp.h:48
int(* change_source)(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc)
Definition res_srtp.h:44
int(* protect)(struct ast_srtp *srtp, void **buf, int *size, int rtcp)
Definition res_srtp.h:50
struct ast_rtp_instance * rtp
Definition res_srtp.c:93
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
structure to hold extensions
unsigned int ts
unsigned char is_set
RTP learning mode tracking information.
enum ast_media_type stream_type
struct timeval received
struct ast_sockaddr proposed_address
struct timeval start
struct ast_frame t140
unsigned char t140red_data[64000]
unsigned char ts[AST_RED_MAX_GENERATION]
unsigned char len[AST_RED_MAX_GENERATION]
unsigned char buf_data[64000]
unsigned char pt[AST_RED_MAX_GENERATION]
long int prev_ts
struct ast_frame t140red
Structure used for mapping an incoming SSRC to an RTP instance.
unsigned int ssrc
The received SSRC.
unsigned int ssrc_valid
struct ast_rtp_instance * instance
The RTP instance this SSRC belongs to.
Packet statistics (used for transport-cc)
Statistics information (used for transport-cc)
struct rtp_transport_wide_cc_statistics::@511 packet_statistics
Definition sched.c:76
STUN support.
int ast_stun_request(int s, struct sockaddr_in *dst, const char *username, struct sockaddr_in *answer)
Generic STUN request.
Definition stun.c:415
int ast_stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
handle an incoming STUN message.
Definition stun.c:293
#define ast_debug_stun(sublevel,...)
Log debug level STUN information.
Definition stun.h:54
#define AST_DEBUG_CATEGORY_STUN
Definition stun.h:45
static const int STANDARD_STUN_PORT
Definition stun.h:61
@ AST_STUN_ACCEPT
Definition stun.h:65
int value
Definition syslog.c:37
Test Framework API.
#define ast_test_suite_event_notify(s, f,...)
Definition test.h:189
static struct test_options options
static struct test_val b
static struct test_val a
static struct test_val d
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
#define AST_THREADSTORAGE(name)
Define a thread storage variable.
int64_t ast_tvdiff_us(struct timeval end, struct timeval start)
Computes the difference (in microseconds) between two struct timeval instances.
Definition time.h:87
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
Definition time.h:282
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
Definition time.h:117
@ TIME_UNIT_MICROSECOND
Definition time.h:341
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compress two struct timeval instances returning -1, 0, 1 if the first arg is smaller,...
Definition time.h:137
struct timeval ast_time_create_by_unit(unsigned long val, enum TIME_UNIT unit)
Convert the given unit value, and create a timeval object from it.
Definition time.c:113
double ast_samp2sec(unsigned int _nsamp, unsigned int _rate)
Returns the duration in seconds of _nsamp samples at rate _rate.
Definition time.h:316
unsigned int ast_sec2samp(double _seconds, int _rate)
Returns the number of samples at _rate in the duration in _seconds.
Definition time.h:333
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
Definition extconf.c:2280
struct timeval ast_time_create_by_unit_str(unsigned long val, const char *unit)
Convert the given unit value, and create a timeval object from it.
Definition time.c:143
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
Definition extconf.c:2295
double ast_tv2double(const struct timeval *tv)
Returns a double corresponding to the number of seconds in the timeval tv.
Definition time.h:270
ast_suseconds_t ast_time_tv_to_usec(const struct timeval *tv)
Convert a timeval structure to microseconds.
Definition time.c:90
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
Definition time.h:107
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition time.h:159
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
Definition time.h:235
static void destroy(struct ast_trans_pvt *pvt)
Definition translate.c:292
Handle unaligned data access.
static void put_unaligned_uint16(void *p, unsigned short datum)
Definition unaligned.h:65
static void put_unaligned_uint32(void *p, unsigned int datum)
Definition unaligned.h:58
FILE * out
Definition utils/frame.c:33
int error(const char *format,...)
static void statistics(void)
FILE * in
Definition utils/frame.c:33
Utility functions.
#define ast_test_flag(p, flag)
Definition utils.h:64
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition utils.h:981
#define ast_assert(a)
Definition utils.h:779
#define MIN(a, b)
Definition utils.h:252
#define ast_socket_nonblock(domain, type, protocol)
Create a non-blocking socket.
Definition utils.h:1113
#define ast_clear_flag(p, flag)
Definition utils.h:78
long int ast_random(void)
Definition utils.c:2348
#define ast_set_flag(p, flag)
Definition utils.h:71
#define ARRAY_LEN(a)
Definition utils.h:706
Universally unique identifier support.
#define AST_UUID_STR_LEN
Definition uuid.h:27
char * ast_uuid_generate_str(char *buf, size_t size)
Generate a UUID string.
Definition uuid.c:141
#define AST_VECTOR_RESET(vec, cleanup)
Reset vector.
Definition vector.h:636
#define AST_VECTOR_ELEM_CLEANUP_NOOP(elem)
Vector element cleanup that does nothing.
Definition vector.h:582
#define AST_VECTOR_SIZE(vec)
Get the number of elements in a vector.
Definition vector.h:620
#define AST_VECTOR_REMOVE_CMP_ORDERED(vec, value, cmp, cleanup)
Remove an element from a vector that matches the given comparison while maintaining order.
Definition vector.h:551
#define AST_VECTOR_FREE(vec)
Deallocates this vector.
Definition vector.h:185
#define AST_VECTOR_REMOVE_CMP_UNORDERED(vec, value, cmp, cleanup)
Remove an element from a vector that matches the given comparison.
Definition vector.h:499
#define AST_VECTOR_GET_CMP(vec, value, cmp)
Get an element from a vector that matches the given comparison.
Definition vector.h:742
#define AST_VECTOR_ADD_SORTED(vec, elem, cmp)
Add an element into a sorted vector.
Definition vector.h:382
#define AST_VECTOR_INIT(vec, size)
Initialize a vector.
Definition vector.h:124
#define AST_VECTOR_APPEND(vec, elem)
Append an element to a vector, growing the vector if needed.
Definition vector.h:267
#define AST_VECTOR(name, type)
Define a vector structure.
Definition vector.h:44
#define AST_VECTOR_GET_ADDR(vec, idx)
Get an address of element in a vector.
Definition vector.h:679