Asterisk - The Open Source Telephony Project GIT-master-3dee037
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[256]; /*!< The remote ICE username */
499 char remote_passwd[256]; /*!< The remote ICE password */
500
501 char local_ufrag[256]; /*!< The local ICE username */
502 char local_passwd[256]; /*!< 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 int ti; /*!< How long to buffer data before send */
627 unsigned char t140red_data[64000];
628 unsigned char buf_data[64000]; /*!< buffered primary data */
630 long int prev_ts;
631};
632
633/*! \brief Structure for storing RTP packets for retransmission */
635 size_t size; /*!< The size of the payload */
636 unsigned char buf[0]; /*!< The payload data */
637};
638
640
641/* Forward Declarations */
642static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
643static int ast_rtp_destroy(struct ast_rtp_instance *instance);
644static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
645static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
646static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
647static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
648static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
649static void ast_rtp_update_source(struct ast_rtp_instance *instance);
650static void ast_rtp_change_source(struct ast_rtp_instance *instance);
651static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
652static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
653static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
654static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
655static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
656static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
657static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
658static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
659static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
660static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
661static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
662static void ast_rtp_stop(struct ast_rtp_instance *instance);
663static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
664static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
665static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance);
666static const char *ast_rtp_get_cname(struct ast_rtp_instance *instance);
667static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc);
668static void ast_rtp_set_stream_num(struct ast_rtp_instance *instance, int stream_num);
670static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent);
671static void update_reported_mes_stats(struct ast_rtp *rtp);
672static void update_local_mes_stats(struct ast_rtp *rtp);
673
674#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
675static int ast_rtp_activate(struct ast_rtp_instance *instance);
676static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
677static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
678static int dtls_bio_write(BIO *bio, const char *buf, int len);
679static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2);
680static int dtls_bio_new(BIO *bio);
681static int dtls_bio_free(BIO *bio);
682
683#ifndef HAVE_OPENSSL_BIO_METHOD
684static BIO_METHOD dtls_bio_methods = {
685 .type = BIO_TYPE_BIO,
686 .name = "rtp write",
687 .bwrite = dtls_bio_write,
688 .ctrl = dtls_bio_ctrl,
689 .create = dtls_bio_new,
690 .destroy = dtls_bio_free,
691};
692#else
693static BIO_METHOD *dtls_bio_methods;
694#endif
695#endif
696
697static 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);
698
699#ifdef HAVE_PJPROJECT
700static void stunaddr_resolve_callback(const struct ast_dns_query *query);
701static int store_stunaddr_resolved(const struct ast_dns_query *query);
702#endif
703
704#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
705static int dtls_bio_new(BIO *bio)
706{
707#ifdef HAVE_OPENSSL_BIO_METHOD
708 BIO_set_init(bio, 1);
709 BIO_set_data(bio, NULL);
710 BIO_set_shutdown(bio, 0);
711#else
712 bio->init = 1;
713 bio->ptr = NULL;
714 bio->flags = 0;
715#endif
716 return 1;
717}
718
719static int dtls_bio_free(BIO *bio)
720{
721 /* The pointer on the BIO is that of the RTP instance. It is not reference counted as the BIO
722 * lifetime is tied to the instance, and actions on the BIO are taken by the thread handling
723 * the RTP instance - not another thread.
724 */
725#ifdef HAVE_OPENSSL_BIO_METHOD
726 BIO_set_data(bio, NULL);
727#else
728 bio->ptr = NULL;
729#endif
730 return 1;
731}
732
733static int dtls_bio_write(BIO *bio, const char *buf, int len)
734{
735#ifdef HAVE_OPENSSL_BIO_METHOD
736 struct ast_rtp_instance *instance = BIO_get_data(bio);
737#else
738 struct ast_rtp_instance *instance = bio->ptr;
739#endif
740 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
741 int rtcp = 0;
742 struct ast_sockaddr remote_address = { {0, } };
743 int ice;
744 int bytes_sent;
745
746 /* OpenSSL can't tolerate a packet not being sent, so we always state that
747 * we sent the packet. If it isn't then retransmission will occur.
748 */
749
750 if (rtp->rtcp && rtp->rtcp->dtls.write_bio == bio) {
751 rtcp = 1;
752 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
753 } else {
754 ast_rtp_instance_get_remote_address(instance, &remote_address);
755 }
756
757 if (ast_sockaddr_isnull(&remote_address)) {
758 return len;
759 }
760
761 bytes_sent = __rtp_sendto(instance, (char *)buf, len, 0, &remote_address, rtcp, &ice, 0);
762
763 if (bytes_sent > 0 && ast_debug_dtls_packet_is_allowed) {
764 ast_debug(0, "(%p) DTLS - sent %s packet to %s%s (len %-6.6d)\n",
765 instance, rtcp ? "RTCP" : "RTP", ast_sockaddr_stringify(&remote_address),
766 ice ? " (via ICE)" : "", bytes_sent);
767 }
768
769 return len;
770}
771
772static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2)
773{
774 switch (cmd) {
775 case BIO_CTRL_FLUSH:
776 return 1;
777 case BIO_CTRL_DGRAM_QUERY_MTU:
778 return dtls_mtu;
779 case BIO_CTRL_WPENDING:
780 case BIO_CTRL_PENDING:
781 return 0L;
782 default:
783 return 0;
784 }
785}
786
787#endif
788
789#ifdef HAVE_PJPROJECT
790/*! \brief Helper function which clears the ICE host candidate mapping */
791static void host_candidate_overrides_clear(void)
792{
793 struct ast_ice_host_candidate *candidate;
794
795 AST_RWLIST_WRLOCK(&host_candidates);
796 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&host_candidates, candidate, next) {
798 ast_free(candidate);
799 }
801 AST_RWLIST_UNLOCK(&host_candidates);
802}
803
804/*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
805static void update_address_with_ice_candidate(pj_ice_sess *ice, enum ast_rtp_ice_component_type component,
806 struct ast_sockaddr *cand_address)
807{
808 char address[PJ_INET6_ADDRSTRLEN];
809
810 if (component < 1 || !ice->comp[component - 1].valid_check) {
811 return;
812 }
813
814 ast_sockaddr_parse(cand_address,
815 pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr, address,
816 sizeof(address), 0), 0);
817 ast_sockaddr_set_port(cand_address,
818 pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
819}
820
821/*! \brief Destructor for locally created ICE candidates */
822static void ast_rtp_ice_candidate_destroy(void *obj)
823{
824 struct ast_rtp_engine_ice_candidate *candidate = obj;
825
826 if (candidate->foundation) {
827 ast_free(candidate->foundation);
828 }
829
830 if (candidate->transport) {
831 ast_free(candidate->transport);
832 }
833}
834
835/*! \pre instance is locked */
836static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
837{
838 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
839 int ice_attrb_reset = 0;
840
841 if (!ast_strlen_zero(ufrag)) {
842 if (!ast_strlen_zero(rtp->remote_ufrag) && strcmp(ufrag, rtp->remote_ufrag)) {
843 ice_attrb_reset = 1;
844 }
845 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
846 }
847
848 if (!ast_strlen_zero(password)) {
849 if (!ast_strlen_zero(rtp->remote_passwd) && strcmp(password, rtp->remote_passwd)) {
850 ice_attrb_reset = 1;
851 }
852 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
853 }
854
855 /* If the remote ufrag or passwd changed, local ufrag and passwd need to regenerate */
856 if (ice_attrb_reset) {
857 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
858 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
859 }
860}
861
862static int ice_candidate_cmp(void *obj, void *arg, int flags)
863{
864 struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
865
866 if (strcmp(candidate1->foundation, candidate2->foundation) ||
867 candidate1->id != candidate2->id ||
868 candidate1->type != candidate2->type ||
869 ast_sockaddr_cmp(&candidate1->address, &candidate2->address)) {
870 return 0;
871 }
872
873 return CMP_MATCH | CMP_STOP;
874}
875
876/*! \pre instance is locked */
877static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
878{
879 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
880 struct ast_rtp_engine_ice_candidate *remote_candidate;
881
882 /* ICE sessions only support UDP candidates */
883 if (strcasecmp(candidate->transport, "udp")) {
884 return;
885 }
886
887 if (!rtp->ice_proposed_remote_candidates) {
888 rtp->ice_proposed_remote_candidates = ao2_container_alloc_list(
889 AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, ice_candidate_cmp);
890 if (!rtp->ice_proposed_remote_candidates) {
891 return;
892 }
893 }
894
895 /* If this is going to exceed the maximum number of ICE candidates don't even add it */
896 if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
897 return;
898 }
899
900 if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
901 return;
902 }
903
904 remote_candidate->foundation = ast_strdup(candidate->foundation);
905 remote_candidate->id = candidate->id;
906 remote_candidate->transport = ast_strdup(candidate->transport);
907 remote_candidate->priority = candidate->priority;
908 ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
909 ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
910 remote_candidate->type = candidate->type;
911
912 ast_debug_ice(2, "(%p) ICE add remote candidate\n", instance);
913
914 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
915 ao2_ref(remote_candidate, -1);
916}
917
919
920/*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
921static void pj_thread_register_check(void)
922{
923 pj_thread_desc *desc;
924 pj_thread_t *thread;
925
926 if (pj_thread_is_registered() == PJ_TRUE) {
927 return;
928 }
929
930 desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
931 if (!desc) {
932 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
933 return;
934 }
935 pj_bzero(*desc, sizeof(*desc));
936
937 if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
938 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
939 }
940 return;
941}
942
943static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
944 int port, int replace);
945
946/*! \pre instance is locked */
947static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
948{
949 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
950 struct ice_wrap *ice;
951
952 ice = rtp->ice;
953 rtp->ice = NULL;
954 if (ice) {
955 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
956 ao2_unlock(instance);
957 ao2_ref(ice, -1);
958 ao2_lock(instance);
959 ast_debug_ice(2, "(%p) ICE stopped\n", instance);
960 }
961}
962
963/*!
964 * \brief ao2 ICE wrapper object destructor.
965 *
966 * \param vdoomed Object being destroyed.
967 *
968 * \note The associated struct ast_rtp_instance object must not
969 * be locked when unreffing the object. Otherwise we could
970 * deadlock trying to destroy the PJPROJECT ICE structure.
971 */
972static void ice_wrap_dtor(void *vdoomed)
973{
974 struct ice_wrap *ice = vdoomed;
975
976 if (ice->real_ice) {
977 pj_thread_register_check();
978
979 pj_ice_sess_destroy(ice->real_ice);
980 }
981}
982
983static void ast2pj_rtp_ice_role(enum ast_rtp_ice_role ast_role, enum pj_ice_sess_role *pj_role)
984{
985 switch (ast_role) {
987 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
988 break;
990 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
991 break;
992 }
993}
994
995static void pj2ast_rtp_ice_role(enum pj_ice_sess_role pj_role, enum ast_rtp_ice_role *ast_role)
996{
997 switch (pj_role) {
998 case PJ_ICE_SESS_ROLE_CONTROLLED:
999 *ast_role = AST_RTP_ICE_ROLE_CONTROLLED;
1000 return;
1001 case PJ_ICE_SESS_ROLE_CONTROLLING:
1002 *ast_role = AST_RTP_ICE_ROLE_CONTROLLING;
1003 return;
1004 case PJ_ICE_SESS_ROLE_UNKNOWN:
1005 /* Don't change anything */
1006 return;
1007 default:
1008 /* If we aren't explicitly handling something, it's a bug */
1009 ast_assert(0);
1010 return;
1011 }
1012}
1013
1014/*! \pre instance is locked */
1015static int ice_reset_session(struct ast_rtp_instance *instance)
1016{
1017 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1018 int res;
1019
1020 ast_debug_ice(3, "(%p) ICE resetting\n", instance);
1021 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1022 ast_debug_ice(3, " (%p) ICE nevermind, not ready for a reset\n", instance);
1023 return 0;
1024 }
1025
1026 ast_debug_ice(3, "(%p) ICE recreating ICE session %s (%d)\n",
1027 instance, ast_sockaddr_stringify(&rtp->ice_original_rtp_addr), rtp->ice_port);
1028 res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
1029 if (!res) {
1030 /* Use the current expected role for the ICE session */
1031 enum pj_ice_sess_role role = PJ_ICE_SESS_ROLE_UNKNOWN;
1032 ast2pj_rtp_ice_role(rtp->role, &role);
1033 pj_ice_sess_change_role(rtp->ice->real_ice, role);
1034 }
1035
1036 /* If we only have one component now, and we previously set up TURN for RTCP,
1037 * we need to destroy that TURN socket.
1038 */
1039 if (rtp->ice_num_components == 1 && rtp->turn_rtcp) {
1040 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1041 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1042
1043 rtp->turn_state = PJ_TURN_STATE_NULL;
1044
1045 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1046 ao2_unlock(instance);
1047 pj_turn_sock_destroy(rtp->turn_rtcp);
1048 ao2_lock(instance);
1049 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1050 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1051 }
1052 }
1053
1054 rtp->ice_media_started = 0;
1055
1056 return res;
1057}
1058
1059static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
1060{
1061 struct ao2_iterator i;
1062 struct ast_rtp_engine_ice_candidate *right_candidate;
1063
1064 if (ao2_container_count(left) != ao2_container_count(right)) {
1065 return -1;
1066 }
1067
1068 i = ao2_iterator_init(right, 0);
1069 while ((right_candidate = ao2_iterator_next(&i))) {
1070 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
1071
1072 if (!left_candidate) {
1073 ao2_ref(right_candidate, -1);
1075 return -1;
1076 }
1077
1078 ao2_ref(left_candidate, -1);
1079 ao2_ref(right_candidate, -1);
1080 }
1082
1083 return 0;
1084}
1085
1086/*! \pre instance is locked */
1087static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
1088{
1089 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1090 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
1091 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
1092 struct ao2_iterator i;
1093 struct ast_rtp_engine_ice_candidate *candidate;
1094 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
1095
1096 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
1097 return;
1098 }
1099
1100 /* Check for equivalence in the lists */
1101 if (rtp->ice_active_remote_candidates &&
1102 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
1103 ast_debug_ice(2, "(%p) ICE proposed equals active candidates\n", instance);
1104 ao2_cleanup(rtp->ice_proposed_remote_candidates);
1105 rtp->ice_proposed_remote_candidates = NULL;
1106 /* If this ICE session is being preserved then go back to the role it currently is */
1107 pj2ast_rtp_ice_role(rtp->ice->real_ice->role, &rtp->role);
1108 return;
1109 }
1110
1111 /* Out with the old, in with the new */
1112 ao2_cleanup(rtp->ice_active_remote_candidates);
1113 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
1114 rtp->ice_proposed_remote_candidates = NULL;
1115
1116 ast_debug_ice(2, "(%p) ICE start\n", instance);
1117
1118 /* Reset the ICE session. Is this going to work? */
1119 if (ice_reset_session(instance)) {
1120 ast_log(LOG_NOTICE, "(%p) ICE failed to create replacement session\n", instance);
1121 return;
1122 }
1123
1124 pj_thread_register_check();
1125
1126 i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
1127
1128 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
1129 pj_str_t address;
1130
1131 /* there needs to be at least one rtp and rtcp candidate in the list */
1132 has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
1133 has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
1134
1135 pj_strdup2(rtp->ice->real_ice->pool, &candidates[cand_cnt].foundation,
1136 candidate->foundation);
1137 candidates[cand_cnt].comp_id = candidate->id;
1138 candidates[cand_cnt].prio = candidate->priority;
1139
1140 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
1141
1142 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
1143 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
1144 }
1145
1146 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
1147 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
1148 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
1149 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
1150 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
1151 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
1152 }
1153
1154 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
1155 ast_debug_ice(2, "(%p) ICE RTP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1156 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1157 ao2_unlock(instance);
1158 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
1159 ao2_lock(instance);
1160 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
1161 ast_debug_ice(2, "(%p) ICE RTCP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1162 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1163 ao2_unlock(instance);
1164 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
1165 ao2_lock(instance);
1166 }
1167
1168 cand_cnt++;
1169 ao2_ref(candidate, -1);
1170 }
1171
1173
1174 if (cand_cnt < ao2_container_count(rtp->ice_active_remote_candidates)) {
1175 ast_log(LOG_WARNING, "(%p) ICE lost %d candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP\n",
1176 instance, ao2_container_count(rtp->ice_active_remote_candidates) - cand_cnt);
1177 }
1178
1179 if (!has_rtp) {
1180 ast_log(LOG_WARNING, "(%p) ICE no RTP candidates; skipping checklist\n", instance);
1181 }
1182
1183 /* If we're only dealing with one ICE component, then we don't care about the lack of RTCP candidates */
1184 if (!has_rtcp && rtp->ice_num_components > 1) {
1185 ast_log(LOG_WARNING, "(%p) ICE no RTCP candidates; skipping checklist\n", instance);
1186 }
1187
1188 if (rtp->ice && has_rtp && (has_rtcp || rtp->ice_num_components == 1)) {
1189 pj_status_t res;
1190 char reason[80];
1191 struct ice_wrap *ice;
1192
1193 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1194 ice = rtp->ice;
1195 ao2_ref(ice, +1);
1196 ao2_unlock(instance);
1197 res = pj_ice_sess_create_check_list(ice->real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
1198 if (res == PJ_SUCCESS) {
1199 ast_debug_ice(2, "(%p) ICE successfully created checklist\n", instance);
1200 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
1201 pj_ice_sess_start_check(ice->real_ice);
1202 pj_timer_heap_poll(timer_heap, NULL);
1203 ao2_ref(ice, -1);
1204 ao2_lock(instance);
1206 return;
1207 }
1208 ao2_ref(ice, -1);
1209 ao2_lock(instance);
1210
1211 pj_strerror(res, reason, sizeof(reason));
1212 ast_log(LOG_WARNING, "(%p) ICE failed to create session check list: %s\n", instance, reason);
1213 }
1214
1215 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
1216
1217 /* even though create check list failed don't stop ice as
1218 it might still work */
1219 /* however we do need to reset remote candidates since
1220 this function may be re-entered */
1221 ao2_ref(rtp->ice_active_remote_candidates, -1);
1222 rtp->ice_active_remote_candidates = NULL;
1223 if (rtp->ice) {
1224 rtp->ice->real_ice->rcand_cnt = rtp->ice->real_ice->clist.count = 0;
1225 }
1226}
1227
1228/*! \pre instance is locked */
1229static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
1230{
1231 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1232
1233 return rtp->local_ufrag;
1234}
1235
1236/*! \pre instance is locked */
1237static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
1238{
1239 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1240
1241 return rtp->local_passwd;
1242}
1243
1244/*! \pre instance is locked */
1245static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
1246{
1247 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1248
1249 if (rtp->ice_local_candidates) {
1250 ao2_ref(rtp->ice_local_candidates, +1);
1251 }
1252
1253 return rtp->ice_local_candidates;
1254}
1255
1256/*! \pre instance is locked */
1257static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
1258{
1259 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1260
1261 if (!rtp->ice) {
1262 return;
1263 }
1264
1265 pj_thread_register_check();
1266
1267 pj_ice_sess_change_role(rtp->ice->real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
1268}
1269
1270/*! \pre instance is locked */
1271static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
1272{
1273 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1274
1275 if (!rtp->ice) {
1276 ast_debug_ice(3, "(%p) ICE set role failed; no ice instance\n", instance);
1277 return;
1278 }
1279
1280 rtp->role = role;
1281
1282 if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1283 pj_thread_register_check();
1284 ast_debug_ice(2, "(%p) ICE set role to %s\n",
1285 instance, role == AST_RTP_ICE_ROLE_CONTROLLED ? "CONTROLLED" : "CONTROLLING");
1286 pj_ice_sess_change_role(rtp->ice->real_ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
1287 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
1288 } else {
1289 ast_debug_ice(2, "(%p) ICE not setting role because state is %s\n",
1290 instance, rtp->ice->real_ice->is_nominating ? "nominating" : "complete");
1291 }
1292}
1293
1294/*! \pre instance is locked */
1295static void ast_rtp_ice_add_cand(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
1296 unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
1297 const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr,
1298 int addr_len)
1299{
1300 pj_str_t foundation;
1301 struct ast_rtp_engine_ice_candidate *candidate, *existing;
1302 struct ice_wrap *ice;
1303 char address[PJ_INET6_ADDRSTRLEN];
1304 pj_status_t status;
1305
1306 if (!rtp->ice) {
1307 return;
1308 }
1309
1310 pj_thread_register_check();
1311
1312 pj_ice_calc_foundation(rtp->ice->real_ice->pool, &foundation, type, addr);
1313
1314 if (!rtp->ice_local_candidates) {
1315 rtp->ice_local_candidates = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1316 NULL, ice_candidate_cmp);
1317 if (!rtp->ice_local_candidates) {
1318 return;
1319 }
1320 }
1321
1322 if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
1323 return;
1324 }
1325
1326 candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
1327 candidate->id = comp_id;
1328 candidate->transport = ast_strdup("UDP");
1329
1330 ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
1331 ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
1332
1333 if (rel_addr) {
1334 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
1335 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
1336 }
1337
1338 if (type == PJ_ICE_CAND_TYPE_HOST) {
1340 } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
1342 } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
1344 }
1345
1346 if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
1347 ao2_ref(existing, -1);
1348 ao2_ref(candidate, -1);
1349 return;
1350 }
1351
1352 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1353 ice = rtp->ice;
1354 ao2_ref(ice, +1);
1355 ao2_unlock(instance);
1356 status = pj_ice_sess_add_cand(ice->real_ice, comp_id, transport_id, type, local_pref,
1357 &foundation, addr, base_addr, rel_addr, addr_len, NULL);
1358 ao2_ref(ice, -1);
1359 ao2_lock(instance);
1360 if (!rtp->ice || status != PJ_SUCCESS) {
1361 ast_debug_ice(2, "(%p) ICE unable to add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1362 &candidate->address), candidate->priority);
1363 ao2_ref(candidate, -1);
1364 return;
1365 }
1366
1367 /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
1368 candidate->priority = rtp->ice->real_ice->lcand[rtp->ice->real_ice->lcand_cnt - 1].prio;
1369
1370 ast_debug_ice(2, "(%p) ICE add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1371 &candidate->address), candidate->priority);
1372
1373 ao2_link(rtp->ice_local_candidates, candidate);
1374 ao2_ref(candidate, -1);
1375}
1376
1377/* PJPROJECT TURN callback */
1378static 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)
1379{
1380 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1381 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1382 struct ice_wrap *ice;
1383 pj_status_t status;
1384
1385 ao2_lock(instance);
1386 ice = ao2_bump(rtp->ice);
1387 ao2_unlock(instance);
1388
1389 if (ice) {
1390 status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTP,
1391 TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr, addr_len);
1392 ao2_ref(ice, -1);
1393 if (status != PJ_SUCCESS) {
1394 char buf[100];
1395
1396 pj_strerror(status, buf, sizeof(buf));
1397 ast_log(LOG_WARNING, "(%p) ICE PJ Rx error status code: %d '%s'.\n",
1398 instance, (int)status, buf);
1399 return;
1400 }
1401 if (!rtp->rtp_passthrough) {
1402 return;
1403 }
1404 rtp->rtp_passthrough = 0;
1405 }
1406
1407 ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
1408}
1409
1410/* PJPROJECT TURN callback */
1411static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1412{
1413 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1414 struct ast_rtp *rtp;
1415
1416 /* If this is a leftover from an already notified RTP instance just ignore the state change */
1417 if (!instance) {
1418 return;
1419 }
1420
1421 rtp = ast_rtp_instance_get_data(instance);
1422
1423 ao2_lock(instance);
1424
1425 /* We store the new state so the other thread can actually handle it */
1426 rtp->turn_state = new_state;
1427 ast_cond_signal(&rtp->cond);
1428
1429 if (new_state == PJ_TURN_STATE_DESTROYING) {
1430 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
1431 rtp->turn_rtp = NULL;
1432 }
1433
1434 ao2_unlock(instance);
1435}
1436
1437/* RTP TURN Socket interface declaration */
1438static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1439 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1440 .on_state = ast_rtp_on_turn_rtp_state,
1441};
1442
1443/* PJPROJECT TURN callback */
1444static 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)
1445{
1446 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1447 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1448 struct ice_wrap *ice;
1449 pj_status_t status;
1450
1451 ao2_lock(instance);
1452 ice = ao2_bump(rtp->ice);
1453 ao2_unlock(instance);
1454
1455 if (ice) {
1456 status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTCP,
1457 TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr, addr_len);
1458 ao2_ref(ice, -1);
1459 if (status != PJ_SUCCESS) {
1460 char buf[100];
1461
1462 pj_strerror(status, buf, sizeof(buf));
1463 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
1464 (int)status, buf);
1465 return;
1466 }
1467 if (!rtp->rtcp_passthrough) {
1468 return;
1469 }
1470 rtp->rtcp_passthrough = 0;
1471 }
1472
1473 ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
1474}
1475
1476/* PJPROJECT TURN callback */
1477static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1478{
1479 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1480 struct ast_rtp *rtp;
1481
1482 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
1483 if (!instance) {
1484 return;
1485 }
1486
1487 rtp = ast_rtp_instance_get_data(instance);
1488
1489 ao2_lock(instance);
1490
1491 /* We store the new state so the other thread can actually handle it */
1492 rtp->turn_state = new_state;
1493 ast_cond_signal(&rtp->cond);
1494
1495 if (new_state == PJ_TURN_STATE_DESTROYING) {
1496 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
1497 rtp->turn_rtcp = NULL;
1498 }
1499
1500 ao2_unlock(instance);
1501}
1502
1503/* RTCP TURN Socket interface declaration */
1504static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1505 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1506 .on_state = ast_rtp_on_turn_rtcp_state,
1507};
1508
1509/*! \brief Worker thread for ioqueue and timerheap */
1510static int ioqueue_worker_thread(void *data)
1511{
1512 struct ast_rtp_ioqueue_thread *ioqueue = data;
1513
1514 while (!ioqueue->terminate) {
1515 const pj_time_val delay = {0, 10};
1516
1517 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
1518
1519 pj_timer_heap_poll(ioqueue->timerheap, NULL);
1520 }
1521
1522 return 0;
1523}
1524
1525/*! \brief Destroyer for ioqueue thread */
1526static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
1527{
1528 if (ioqueue->thread) {
1529 ioqueue->terminate = 1;
1530 pj_thread_join(ioqueue->thread);
1531 pj_thread_destroy(ioqueue->thread);
1532 }
1533
1534 if (ioqueue->pool) {
1535 /* This mimics the behavior of pj_pool_safe_release
1536 * which was introduced in pjproject 2.6.
1537 */
1538 pj_pool_t *temp_pool = ioqueue->pool;
1539
1540 ioqueue->pool = NULL;
1541 pj_pool_release(temp_pool);
1542 }
1543
1544 ast_free(ioqueue);
1545}
1546
1547/*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
1548static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
1549{
1550 int destroy = 0;
1551
1552 /* If nothing is using this ioqueue thread destroy it */
1553 AST_LIST_LOCK(&ioqueues);
1554 if ((ioqueue->count -= 2) == 0) {
1555 destroy = 1;
1556 AST_LIST_REMOVE(&ioqueues, ioqueue, next);
1557 }
1558 AST_LIST_UNLOCK(&ioqueues);
1559
1560 if (!destroy) {
1561 return;
1562 }
1563
1564 rtp_ioqueue_thread_destroy(ioqueue);
1565}
1566
1567/*! \brief Finder and allocator for an ioqueue thread */
1568static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
1569{
1570 struct ast_rtp_ioqueue_thread *ioqueue;
1571 pj_lock_t *lock;
1572
1573 AST_LIST_LOCK(&ioqueues);
1574
1575 /* See if an ioqueue thread exists that can handle more */
1576 AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1577 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1578 break;
1579 }
1580 }
1581
1582 /* If we found one bump it up and return it */
1583 if (ioqueue) {
1584 ioqueue->count += 2;
1585 goto end;
1586 }
1587
1588 ioqueue = ast_calloc(1, sizeof(*ioqueue));
1589 if (!ioqueue) {
1590 goto end;
1591 }
1592
1593 ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1594
1595 /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1596 * on a session at the same time
1597 */
1598 if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1599 goto fatal;
1600 }
1601
1602 if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1603 goto fatal;
1604 }
1605
1606 pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1607
1608 if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1609 goto fatal;
1610 }
1611
1612 if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1613 goto fatal;
1614 }
1615
1616 AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1617
1618 /* Since this is being returned to an active session the count always starts at 2 */
1619 ioqueue->count = 2;
1620
1621 goto end;
1622
1623fatal:
1624 rtp_ioqueue_thread_destroy(ioqueue);
1625 ioqueue = NULL;
1626
1627end:
1628 AST_LIST_UNLOCK(&ioqueues);
1629 return ioqueue;
1630}
1631
1632/*! \pre instance is locked */
1633static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1634 enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1635{
1636 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1637 pj_turn_sock **turn_sock;
1638 const pj_turn_sock_cb *turn_cb;
1639 pj_turn_tp_type conn_type;
1640 int conn_transport;
1641 pj_stun_auth_cred cred = { 0, };
1642 pj_str_t turn_addr;
1643 struct ast_sockaddr addr = { { 0, } };
1644 pj_stun_config stun_config;
1645 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1646 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1647 pj_turn_session_info info;
1648 struct ast_sockaddr local, loop;
1649 pj_status_t status;
1650 pj_turn_sock_cfg turn_sock_cfg;
1651 struct ice_wrap *ice;
1652
1653 ast_rtp_instance_get_local_address(instance, &local);
1654 if (ast_sockaddr_is_ipv4(&local)) {
1655 ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1656 } else {
1658 }
1659
1660 /* Determine what component we are requesting a TURN session for */
1661 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1662 turn_sock = &rtp->turn_rtp;
1663 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1664 conn_transport = TRANSPORT_TURN_RTP;
1666 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1667 turn_sock = &rtp->turn_rtcp;
1668 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1669 conn_transport = TRANSPORT_TURN_RTCP;
1671 } else {
1672 return;
1673 }
1674
1675 if (transport == AST_TRANSPORT_UDP) {
1676 conn_type = PJ_TURN_TP_UDP;
1677 } else if (transport == AST_TRANSPORT_TCP) {
1678 conn_type = PJ_TURN_TP_TCP;
1679 } else {
1680 ast_assert(0);
1681 return;
1682 }
1683
1684 ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1685
1686 if (*turn_sock) {
1687 rtp->turn_state = PJ_TURN_STATE_NULL;
1688
1689 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1690 ao2_unlock(instance);
1691 pj_turn_sock_destroy(*turn_sock);
1692 ao2_lock(instance);
1693 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1694 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1695 }
1696 }
1697
1698 if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1699 /*
1700 * We cannot hold the instance lock because we could wait
1701 * for the ioqueue thread to die and we might deadlock as
1702 * a result.
1703 */
1704 ao2_unlock(instance);
1705 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1706 ao2_lock(instance);
1707 if (!rtp->ioqueue) {
1708 return;
1709 }
1710 }
1711
1712 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1713 if (!stun_software_attribute) {
1714 stun_config.software_name = pj_str(NULL);
1715 }
1716
1717 /* Use ICE session group lock for TURN session to avoid deadlock */
1718 pj_turn_sock_cfg_default(&turn_sock_cfg);
1719 ice = rtp->ice;
1720 if (ice) {
1721 turn_sock_cfg.grp_lock = ice->real_ice->grp_lock;
1722 ao2_ref(ice, +1);
1723 }
1724
1725 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1726 ao2_unlock(instance);
1727 status = pj_turn_sock_create(&stun_config,
1728 ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1729 turn_cb, &turn_sock_cfg, instance, turn_sock);
1730 ao2_cleanup(ice);
1731 if (status != PJ_SUCCESS) {
1732 ast_log(LOG_WARNING, "(%p) Could not create a TURN client socket\n", instance);
1733 ao2_lock(instance);
1734 return;
1735 }
1736
1737 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1738 pj_strset2(&cred.data.static_cred.username, (char*)username);
1739 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1740 pj_strset2(&cred.data.static_cred.data, (char*)password);
1741
1742 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1743
1744 ast_debug_ice(2, "(%p) ICE request TURN %s %s candidate\n", instance,
1745 transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
1746 component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
1747
1748 ao2_lock(instance);
1749
1750 /*
1751 * Because the TURN socket is asynchronous and we are synchronous we need to
1752 * wait until it is done
1753 */
1754 while (rtp->turn_state < PJ_TURN_STATE_READY) {
1755 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1756 }
1757
1758 /* If a TURN session was allocated add it as a candidate */
1759 if (rtp->turn_state != PJ_TURN_STATE_READY) {
1760 return;
1761 }
1762
1763 pj_turn_sock_get_info(*turn_sock, &info);
1764
1765 ast_rtp_ice_add_cand(instance, rtp, component, conn_transport,
1766 PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
1767 &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1768
1769 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1770 ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1771 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1772 ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1773 }
1774}
1775
1776static char *generate_random_string(char *buf, size_t size)
1777{
1778 long val[4];
1779 int x;
1780
1781 for (x=0; x<4; x++) {
1782 val[x] = ast_random();
1783 }
1784 snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1785
1786 return buf;
1787}
1788
1789/*! \pre instance is locked */
1790static void ast_rtp_ice_change_components(struct ast_rtp_instance *instance, int num_components)
1791{
1792 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1793
1794 /* Don't do anything if ICE is unsupported or if we're not changing the
1795 * number of components
1796 */
1797 if (!icesupport || !rtp->ice || rtp->ice_num_components == num_components) {
1798 return;
1799 }
1800
1801 ast_debug_ice(2, "(%p) ICE change number of components %u -> %u\n", instance,
1802 rtp->ice_num_components, num_components);
1803
1804 rtp->ice_num_components = num_components;
1805 ice_reset_session(instance);
1806}
1807
1808/* ICE RTP Engine interface declaration */
1809static struct ast_rtp_engine_ice ast_rtp_ice = {
1810 .set_authentication = ast_rtp_ice_set_authentication,
1811 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1812 .start = ast_rtp_ice_start,
1813 .stop = ast_rtp_ice_stop,
1814 .get_ufrag = ast_rtp_ice_get_ufrag,
1815 .get_password = ast_rtp_ice_get_password,
1816 .get_local_candidates = ast_rtp_ice_get_local_candidates,
1817 .ice_lite = ast_rtp_ice_lite,
1818 .set_role = ast_rtp_ice_set_role,
1819 .turn_request = ast_rtp_ice_turn_request,
1820 .change_components = ast_rtp_ice_change_components,
1821};
1822#endif
1823
1824#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
1825static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1826{
1827 /* We don't want to actually verify the certificate so just accept what they have provided */
1828 return 1;
1829}
1830
1831static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1832 enum ast_rtp_dtls_setup setup, struct ast_rtp_instance *instance)
1833{
1834 dtls->dtls_setup = setup;
1835
1836 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1837 ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1838 goto error;
1839 }
1840
1841 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1842 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1843 goto error;
1844 }
1845 BIO_set_mem_eof_return(dtls->read_bio, -1);
1846
1847#ifdef HAVE_OPENSSL_BIO_METHOD
1848 if (!(dtls->write_bio = BIO_new(dtls_bio_methods))) {
1849 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1850 goto error;
1851 }
1852
1853 BIO_set_data(dtls->write_bio, instance);
1854#else
1855 if (!(dtls->write_bio = BIO_new(&dtls_bio_methods))) {
1856 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1857 goto error;
1858 }
1859 dtls->write_bio->ptr = instance;
1860#endif
1861 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1862
1863 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1864 SSL_set_accept_state(dtls->ssl);
1865 } else {
1866 SSL_set_connect_state(dtls->ssl);
1867 }
1868 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1869
1870 return 0;
1871
1872error:
1873 if (dtls->read_bio) {
1874 BIO_free(dtls->read_bio);
1875 dtls->read_bio = NULL;
1876 }
1877
1878 if (dtls->write_bio) {
1879 BIO_free(dtls->write_bio);
1880 dtls->write_bio = NULL;
1881 }
1882
1883 if (dtls->ssl) {
1884 SSL_free(dtls->ssl);
1885 dtls->ssl = NULL;
1886 }
1887 return -1;
1888}
1889
1890static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1891{
1892 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1893
1894 if (!rtp->ssl_ctx || !rtp->rtcp) {
1895 return 0;
1896 }
1897
1898 ast_debug_dtls(3, "(%p) DTLS RTCP setup\n", instance);
1899 return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup, instance);
1900}
1901
1902static const SSL_METHOD *get_dtls_method(void)
1903{
1904#if OPENSSL_VERSION_NUMBER < 0x10002000L
1905 return DTLSv1_method();
1906#else
1907 return DTLS_method();
1908#endif
1909}
1910
1911struct dtls_cert_info {
1912 EVP_PKEY *private_key;
1913 X509 *certificate;
1914};
1915
1916static int apply_dh_params(SSL_CTX *ctx, BIO *bio)
1917{
1918 int res = 0;
1919
1920#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1921 EVP_PKEY *dhpkey = PEM_read_bio_Parameters(bio, NULL);
1922 if (dhpkey && EVP_PKEY_is_a(dhpkey, "DH")) {
1923 res = SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey);
1924 }
1925 if (!res) {
1926 /* A successful call to SSL_CTX_set0_tmp_dh_pkey() means
1927 that we lost ownership of dhpkey and should not free
1928 it ourselves */
1929 EVP_PKEY_free(dhpkey);
1930 }
1931#else
1932 DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1933 if (dh) {
1934 res = SSL_CTX_set_tmp_dh(ctx, dh);
1935 }
1936 DH_free(dh);
1937#endif
1938
1939 return res;
1940}
1941
1942static void configure_dhparams(const struct ast_rtp *rtp, const struct ast_rtp_dtls_cfg *dtls_cfg)
1943{
1944#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1945 EC_KEY *ecdh;
1946#endif
1947
1948#ifndef OPENSSL_NO_DH
1949 if (!ast_strlen_zero(dtls_cfg->pvtfile)) {
1950 BIO *bio = BIO_new_file(dtls_cfg->pvtfile, "r");
1951 if (bio) {
1952 if (apply_dh_params(rtp->ssl_ctx, bio)) {
1953 long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
1954 SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
1955 options = SSL_CTX_set_options(rtp->ssl_ctx, options);
1956 ast_verb(2, "DTLS DH initialized, PFS enabled\n");
1957 }
1958 BIO_free(bio);
1959 }
1960 }
1961#endif /* !OPENSSL_NO_DH */
1962
1963#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1964 /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
1965 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1966 if (ecdh) {
1967 if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
1968 #ifndef SSL_CTRL_SET_ECDH_AUTO
1969 #define SSL_CTRL_SET_ECDH_AUTO 94
1970 #endif
1971 /* SSL_CTX_set_ecdh_auto(rtp->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
1972 if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
1973 ast_verb(2, "DTLS ECDH initialized (automatic), faster PFS enabled\n");
1974 } else {
1975 ast_verb(2, "DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
1976 }
1977 }
1978 EC_KEY_free(ecdh);
1979 }
1980#endif /* !OPENSSL_NO_ECDH */
1981}
1982
1983#if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
1984
1985static int create_ephemeral_ec_keypair(EVP_PKEY **keypair)
1986{
1987#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1988 *keypair = EVP_EC_gen(SN_X9_62_prime256v1);
1989 return *keypair ? 0 : -1;
1990#else
1991 EC_KEY *eckey = NULL;
1992 EC_GROUP *group = NULL;
1993
1994 group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1995 if (!group) {
1996 goto error;
1997 }
1998
1999 EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
2000 EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED);
2001
2002 eckey = EC_KEY_new();
2003 if (!eckey) {
2004 goto error;
2005 }
2006
2007 if (!EC_KEY_set_group(eckey, group)) {
2008 goto error;
2009 }
2010
2011 if (!EC_KEY_generate_key(eckey)) {
2012 goto error;
2013 }
2014
2015 *keypair = EVP_PKEY_new();
2016 if (!*keypair) {
2017 goto error;
2018 }
2019
2020 EVP_PKEY_assign_EC_KEY(*keypair, eckey);
2021 EC_GROUP_free(group);
2022
2023 return 0;
2024
2025error:
2026 EC_KEY_free(eckey);
2027 EC_GROUP_free(group);
2028
2029 return -1;
2030#endif
2031}
2032
2033/* From OpenSSL's x509 command */
2034#define SERIAL_RAND_BITS 159
2035
2036static int create_ephemeral_certificate(EVP_PKEY *keypair, X509 **certificate)
2037{
2038 X509 *cert = NULL;
2039 BIGNUM *serial = NULL;
2040 X509_NAME *name = NULL;
2041
2042 cert = X509_new();
2043 if (!cert) {
2044 goto error;
2045 }
2046
2047 if (!X509_set_version(cert, 2)) {
2048 goto error;
2049 }
2050
2051 /* Set the public key */
2052 X509_set_pubkey(cert, keypair);
2053
2054 /* Generate a random serial number */
2055 if (!(serial = BN_new())
2056 || !BN_rand(serial, SERIAL_RAND_BITS, -1, 0)
2057 || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) {
2058 BN_free(serial);
2059 goto error;
2060 }
2061
2062 BN_free(serial);
2063
2064 /*
2065 * Validity period - Current Chrome & Firefox make it 31 days starting
2066 * with yesterday at the current time, so we will do the same.
2067 */
2068#if OPENSSL_VERSION_NUMBER < 0x10100000L
2069 if (!X509_time_adj_ex(X509_get_notBefore(cert), -1, 0, NULL)
2070 || !X509_time_adj_ex(X509_get_notAfter(cert), 30, 0, NULL)) {
2071 goto error;
2072 }
2073#else
2074 if (!X509_time_adj_ex(X509_getm_notBefore(cert), -1, 0, NULL)
2075 || !X509_time_adj_ex(X509_getm_notAfter(cert), 30, 0, NULL)) {
2076 goto error;
2077 }
2078#endif
2079
2080 /* Set the name and issuer */
2081 if (!(name = X509_get_subject_name(cert))
2082 || !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC,
2083 (unsigned char *) "asterisk", -1, -1, 0)
2084 || !X509_set_issuer_name(cert, name)) {
2085 goto error;
2086 }
2087
2088 /* Sign it */
2089 if (!X509_sign(cert, keypair, EVP_sha256())) {
2090 goto error;
2091 }
2092
2093 *certificate = cert;
2094
2095 return 0;
2096
2097error:
2098 X509_free(cert);
2099
2100 return -1;
2101}
2102
2103static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2104 const struct ast_rtp_dtls_cfg *dtls_cfg,
2105 struct dtls_cert_info *cert_info)
2106{
2107 /* Make sure these are initialized */
2108 cert_info->private_key = NULL;
2109 cert_info->certificate = NULL;
2110
2111 if (create_ephemeral_ec_keypair(&cert_info->private_key)) {
2112 ast_log(LOG_ERROR, "Failed to create ephemeral ECDSA keypair\n");
2113 goto error;
2114 }
2115
2116 if (create_ephemeral_certificate(cert_info->private_key, &cert_info->certificate)) {
2117 ast_log(LOG_ERROR, "Failed to create ephemeral X509 certificate\n");
2118 goto error;
2119 }
2120
2121 return 0;
2122
2123 error:
2124 X509_free(cert_info->certificate);
2125 EVP_PKEY_free(cert_info->private_key);
2126
2127 return -1;
2128}
2129
2130#else
2131
2132static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2133 const struct ast_rtp_dtls_cfg *dtls_cfg,
2134 struct dtls_cert_info *cert_info)
2135{
2136 ast_log(LOG_ERROR, "Your version of OpenSSL does not support ECDSA keys\n");
2137 return -1;
2138}
2139
2140#endif /* !OPENSSL_NO_ECDH */
2141
2142static int create_certificate_from_file(struct ast_rtp_instance *instance,
2143 const struct ast_rtp_dtls_cfg *dtls_cfg,
2144 struct dtls_cert_info *cert_info)
2145{
2146 FILE *fp;
2147 BIO *certbio = NULL;
2148 EVP_PKEY *private_key = NULL;
2149 X509 *cert = NULL;
2150 char *private_key_file = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
2151
2152 fp = fopen(private_key_file, "r");
2153 if (!fp) {
2154 ast_log(LOG_ERROR, "Failed to read private key from file '%s': %s\n", private_key_file, strerror(errno));
2155 goto error;
2156 }
2157
2158 if (!PEM_read_PrivateKey(fp, &private_key, NULL, NULL)) {
2159 ast_log(LOG_ERROR, "Failed to read private key from PEM file '%s'\n", private_key_file);
2160 fclose(fp);
2161 goto error;
2162 }
2163
2164 if (fclose(fp)) {
2165 ast_log(LOG_ERROR, "Failed to close private key file '%s': %s\n", private_key_file, strerror(errno));
2166 goto error;
2167 }
2168
2169 certbio = BIO_new(BIO_s_file());
2170 if (!certbio) {
2171 ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
2172 instance);
2173 goto error;
2174 }
2175
2176 if (!BIO_read_filename(certbio, dtls_cfg->certfile)
2177 || !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
2178 ast_log(LOG_ERROR, "Failed to read certificate from file '%s'\n", dtls_cfg->certfile);
2179 goto error;
2180 }
2181
2182 cert_info->private_key = private_key;
2183 cert_info->certificate = cert;
2184
2185 BIO_free_all(certbio);
2186
2187 return 0;
2188
2189error:
2190 X509_free(cert);
2191 BIO_free_all(certbio);
2192 EVP_PKEY_free(private_key);
2193
2194 return -1;
2195}
2196
2197static int load_dtls_certificate(struct ast_rtp_instance *instance,
2198 const struct ast_rtp_dtls_cfg *dtls_cfg,
2199 struct dtls_cert_info *cert_info)
2200{
2201 if (dtls_cfg->ephemeral_cert) {
2202 return create_certificate_ephemeral(instance, dtls_cfg, cert_info);
2203 } else if (!ast_strlen_zero(dtls_cfg->certfile)) {
2204 return create_certificate_from_file(instance, dtls_cfg, cert_info);
2205 } else {
2206 return -1;
2207 }
2208}
2209
2210/*! \pre instance is locked */
2211static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
2212{
2213 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2214 struct dtls_cert_info cert_info = { 0 };
2215 int res;
2216
2217 if (!dtls_cfg->enabled) {
2218 return 0;
2219 }
2220
2221 ast_debug_dtls(3, "(%p) DTLS RTP setup\n", instance);
2222
2224 ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
2225 return -1;
2226 }
2227
2228 if (rtp->ssl_ctx) {
2229 return 0;
2230 }
2231
2232 rtp->ssl_ctx = SSL_CTX_new(get_dtls_method());
2233 if (!rtp->ssl_ctx) {
2234 return -1;
2235 }
2236
2237 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
2238
2239 configure_dhparams(rtp, dtls_cfg);
2240
2241 rtp->dtls_verify = dtls_cfg->verify;
2242
2243 SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2244 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2245 dtls_verify_callback : NULL);
2246
2247 if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
2248 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
2249 } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
2250 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
2251 } else {
2252 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
2253 return -1;
2254 }
2255
2256 rtp->local_hash = dtls_cfg->hash;
2257
2258 if (!load_dtls_certificate(instance, dtls_cfg, &cert_info)) {
2259 const EVP_MD *type;
2260 unsigned int size, i;
2261 unsigned char fingerprint[EVP_MAX_MD_SIZE];
2262 char *local_fingerprint = rtp->local_fingerprint;
2263
2264 if (!SSL_CTX_use_certificate(rtp->ssl_ctx, cert_info.certificate)) {
2265 ast_log(LOG_ERROR, "Specified certificate for RTP instance '%p' could not be used\n",
2266 instance);
2267 return -1;
2268 }
2269
2270 if (!SSL_CTX_use_PrivateKey(rtp->ssl_ctx, cert_info.private_key)
2271 || !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
2272 ast_log(LOG_ERROR, "Specified private key for RTP instance '%p' could not be used\n",
2273 instance);
2274 return -1;
2275 }
2276
2277 if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
2278 type = EVP_sha1();
2279 } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
2280 type = EVP_sha256();
2281 } else {
2282 ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
2283 instance);
2284 return -1;
2285 }
2286
2287 if (!X509_digest(cert_info.certificate, type, fingerprint, &size) || !size) {
2288 ast_log(LOG_ERROR, "Could not produce fingerprint from certificate for RTP instance '%p'\n",
2289 instance);
2290 return -1;
2291 }
2292
2293 for (i = 0; i < size; i++) {
2294 sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
2295 local_fingerprint += 3;
2296 }
2297
2298 *(local_fingerprint - 1) = 0;
2299
2300 EVP_PKEY_free(cert_info.private_key);
2301 X509_free(cert_info.certificate);
2302 }
2303
2304 if (!ast_strlen_zero(dtls_cfg->cipher)) {
2305 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
2306 ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
2307 dtls_cfg->cipher, instance);
2308 return -1;
2309 }
2310 }
2311
2312 if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
2313 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
2314 ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
2315 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
2316 return -1;
2317 }
2318 }
2319
2320 rtp->rekey = dtls_cfg->rekey;
2321 rtp->suite = dtls_cfg->suite;
2322
2323 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup, instance);
2324 if (!res) {
2325 dtls_setup_rtcp(instance);
2326 }
2327
2328 return res;
2329}
2330
2331/*! \pre instance is locked */
2332static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
2333{
2334 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2335
2336 return !rtp->ssl_ctx ? 0 : 1;
2337}
2338
2339/*! \pre instance is locked */
2340static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
2341{
2342 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2343 SSL *ssl = rtp->dtls.ssl;
2344
2345 ast_debug_dtls(3, "(%p) DTLS stop\n", instance);
2346 ao2_unlock(instance);
2347 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
2348 ao2_lock(instance);
2349
2350 if (rtp->ssl_ctx) {
2351 SSL_CTX_free(rtp->ssl_ctx);
2352 rtp->ssl_ctx = NULL;
2353 }
2354
2355 if (rtp->dtls.ssl) {
2356 SSL_free(rtp->dtls.ssl);
2357 rtp->dtls.ssl = NULL;
2358 }
2359
2360 if (rtp->rtcp) {
2361 ao2_unlock(instance);
2362 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
2363 ao2_lock(instance);
2364
2365 if (rtp->rtcp->dtls.ssl) {
2366 if (rtp->rtcp->dtls.ssl != ssl) {
2367 SSL_free(rtp->rtcp->dtls.ssl);
2368 }
2369 rtp->rtcp->dtls.ssl = NULL;
2370 }
2371 }
2372}
2373
2374/*! \pre instance is locked */
2375static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
2376{
2377 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2378
2379 if (SSL_is_init_finished(rtp->dtls.ssl)) {
2380 SSL_shutdown(rtp->dtls.ssl);
2381 rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2382 }
2383
2384 if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
2385 SSL_shutdown(rtp->rtcp->dtls.ssl);
2386 rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2387 }
2388}
2389
2390/*! \pre instance is locked */
2391static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
2392{
2393 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2394
2395 return rtp->dtls.connection;
2396}
2397
2398/*! \pre instance is locked */
2399static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
2400{
2401 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2402
2403 return rtp->dtls.dtls_setup;
2404}
2405
2406static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
2407{
2408 enum ast_rtp_dtls_setup old = *dtls_setup;
2409
2410 switch (setup) {
2412 *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2413 break;
2415 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2416 break;
2418 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
2419 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2420 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2421 }
2422 break;
2424 *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
2425 break;
2426 default:
2427 /* This should never occur... if it does exit early as we don't know what state things are in */
2428 return;
2429 }
2430
2431 /* If the setup state did not change we go on as if nothing happened */
2432 if (old == *dtls_setup) {
2433 return;
2434 }
2435
2436 /* If they don't want us to establish a connection wait until later */
2437 if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
2438 return;
2439 }
2440
2441 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
2442 SSL_set_connect_state(ssl);
2443 } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2444 SSL_set_accept_state(ssl);
2445 } else {
2446 return;
2447 }
2448}
2449
2450/*! \pre instance is locked */
2451static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
2452{
2453 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2454
2455 if (rtp->dtls.ssl) {
2456 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
2457 }
2458
2459 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
2460 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
2461 }
2462}
2463
2464/*! \pre instance is locked */
2465static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
2466{
2467 char *tmp = ast_strdupa(fingerprint), *value;
2468 int pos = 0;
2469 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2470
2471 if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
2472 return;
2473 }
2474
2475 rtp->remote_hash = hash;
2476
2477 while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
2478 sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
2479 }
2480}
2481
2482/*! \pre instance is locked */
2483static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
2484{
2485 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2486
2487 return rtp->local_hash;
2488}
2489
2490/*! \pre instance is locked */
2491static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
2492{
2493 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2494
2495 return rtp->local_fingerprint;
2496}
2497
2498/* DTLS RTP Engine interface declaration */
2499static struct ast_rtp_engine_dtls ast_rtp_dtls = {
2500 .set_configuration = ast_rtp_dtls_set_configuration,
2501 .active = ast_rtp_dtls_active,
2502 .stop = ast_rtp_dtls_stop,
2503 .reset = ast_rtp_dtls_reset,
2504 .get_connection = ast_rtp_dtls_get_connection,
2505 .get_setup = ast_rtp_dtls_get_setup,
2506 .set_setup = ast_rtp_dtls_set_setup,
2507 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
2508 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
2509 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
2510};
2511
2512#endif
2513
2514#ifdef TEST_FRAMEWORK
2515static size_t get_recv_buffer_count(struct ast_rtp_instance *instance)
2516{
2517 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2518
2519 if (rtp && rtp->recv_buffer) {
2521 }
2522
2523 return 0;
2524}
2525
2526static size_t get_recv_buffer_max(struct ast_rtp_instance *instance)
2527{
2528 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2529
2530 if (rtp && rtp->recv_buffer) {
2531 return ast_data_buffer_max(rtp->recv_buffer);
2532 }
2533
2534 return 0;
2535}
2536
2537static size_t get_send_buffer_count(struct ast_rtp_instance *instance)
2538{
2539 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2540
2541 if (rtp && rtp->send_buffer) {
2543 }
2544
2545 return 0;
2546}
2547
2548static void set_rtp_rtcp_schedid(struct ast_rtp_instance *instance, int id)
2549{
2550 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2551
2552 if (rtp && rtp->rtcp) {
2553 rtp->rtcp->schedid = id;
2554 }
2555}
2556
2557static struct ast_rtp_engine_test ast_rtp_test = {
2558 .packets_to_drop = 0,
2559 .send_report = 0,
2560 .sdes_received = 0,
2561 .recv_buffer_count = get_recv_buffer_count,
2562 .recv_buffer_max = get_recv_buffer_max,
2563 .send_buffer_count = get_send_buffer_count,
2564 .set_schedid = set_rtp_rtcp_schedid,
2565};
2566#endif
2567
2568/* RTP Engine Declaration */
2570 .name = "asterisk",
2571 .new = ast_rtp_new,
2572 .destroy = ast_rtp_destroy,
2573 .dtmf_begin = ast_rtp_dtmf_begin,
2574 .dtmf_end = ast_rtp_dtmf_end,
2575 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
2576 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
2577 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
2578 .update_source = ast_rtp_update_source,
2579 .change_source = ast_rtp_change_source,
2580 .write = ast_rtp_write,
2581 .read = ast_rtp_read,
2582 .prop_set = ast_rtp_prop_set,
2583 .fd = ast_rtp_fd,
2584 .remote_address_set = ast_rtp_remote_address_set,
2585 .red_init = rtp_red_init,
2586 .red_buffer = rtp_red_buffer,
2587 .local_bridge = ast_rtp_local_bridge,
2588 .get_stat = ast_rtp_get_stat,
2589 .dtmf_compatible = ast_rtp_dtmf_compatible,
2590 .stun_request = ast_rtp_stun_request,
2591 .stop = ast_rtp_stop,
2592 .qos = ast_rtp_qos_set,
2593 .sendcng = ast_rtp_sendcng,
2594#ifdef HAVE_PJPROJECT
2595 .ice = &ast_rtp_ice,
2596#endif
2597#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2598 .dtls = &ast_rtp_dtls,
2599 .activate = ast_rtp_activate,
2600#endif
2601 .ssrc_get = ast_rtp_get_ssrc,
2602 .cname_get = ast_rtp_get_cname,
2603 .set_remote_ssrc = ast_rtp_set_remote_ssrc,
2604 .set_stream_num = ast_rtp_set_stream_num,
2605 .extension_enable = ast_rtp_extension_enable,
2606 .bundle = ast_rtp_bundle,
2607#ifdef TEST_FRAMEWORK
2608 .test = &ast_rtp_test,
2609#endif
2610};
2611
2612#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2613/*! \pre instance is locked */
2614static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
2615{
2616 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2617
2618 ast_debug_dtls(3, "(%p) DTLS perform handshake - ssl = %p, setup = %d\n",
2619 rtp, dtls->ssl, dtls->dtls_setup);
2620
2621 /* If we are not acting as a client connecting to the remote side then
2622 * don't start the handshake as it will accomplish nothing and would conflict
2623 * with the handshake we receive from the remote side.
2624 */
2625 if (!dtls->ssl || (dtls->dtls_setup != AST_RTP_DTLS_SETUP_ACTIVE)) {
2626 return;
2627 }
2628
2629 SSL_do_handshake(dtls->ssl);
2630
2631 /*
2632 * A race condition is prevented between this function and __rtp_recvfrom()
2633 * because both functions have to get the instance lock before they can do
2634 * anything. Without holding the instance lock, this function could start
2635 * the SSL handshake above in one thread and the __rtp_recvfrom() function
2636 * called by the channel thread could read the response and stop the timeout
2637 * timer before we have a chance to even start it.
2638 */
2639 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
2640}
2641#endif
2642
2643#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2644static void dtls_perform_setup(struct dtls_details *dtls)
2645{
2646 if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
2647 return;
2648 }
2649
2650 SSL_clear(dtls->ssl);
2651 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2652 SSL_set_accept_state(dtls->ssl);
2653 } else {
2654 SSL_set_connect_state(dtls->ssl);
2655 }
2656 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
2657
2658 ast_debug_dtls(3, "DTLS perform setup - connection reset\n");
2659}
2660#endif
2661
2662#ifdef HAVE_PJPROJECT
2663static void rtp_learning_start(struct ast_rtp *rtp);
2664
2665/* Handles start of media during ICE negotiation or completion */
2666static void ast_rtp_ice_start_media(pj_ice_sess *ice, pj_status_t status)
2667{
2668 struct ast_rtp_instance *instance = ice->user_data;
2669 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2670
2671 ao2_lock(instance);
2672
2673 if (status == PJ_SUCCESS) {
2674 struct ast_sockaddr remote_address;
2675
2676 ast_sockaddr_setnull(&remote_address);
2677 update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2678 if (!ast_sockaddr_isnull(&remote_address)) {
2679 /* Symmetric RTP must be disabled for the remote address to not get overwritten */
2681
2682 ast_rtp_instance_set_remote_address(instance, &remote_address);
2683 }
2684
2685 if (rtp->rtcp) {
2686 update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
2687 }
2688 }
2689
2690#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2691 /* If we've already started media, no need to do all of this again */
2692 if (rtp->ice_media_started) {
2693 ao2_unlock(instance);
2694 return;
2695 }
2696
2698 "(%p) ICE starting media - perform DTLS - (%p)\n", instance, rtp);
2699
2700 /*
2701 * Seemingly no reason to call dtls_perform_setup here. Currently we'll do a full
2702 * protocol level renegotiation if things do change. And if bundled is being used
2703 * then ICE is reused when a stream is added.
2704 *
2705 * Note, if for some reason in the future dtls_perform_setup does need to done here
2706 * be aware that creates a race condition between the call here (on ice completion)
2707 * and potential DTLS handshaking when receiving RTP. What happens is the ssl object
2708 * can get cleared (SSL_clear) during that handshaking process (DTLS init). If that
2709 * happens then Asterisk won't complete DTLS initialization. RTP packets are still
2710 * sent/received but won't be encrypted/decrypted.
2711 */
2712 dtls_perform_handshake(instance, &rtp->dtls, 0);
2713
2714 if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
2715 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
2716 }
2717#endif
2718
2719 rtp->ice_media_started = 1;
2720
2721 if (!strictrtp) {
2722 ao2_unlock(instance);
2723 return;
2724 }
2725
2726 ast_verb(4, "%p -- Strict RTP learning after ICE completion\n", rtp);
2727 rtp_learning_start(rtp);
2728 ao2_unlock(instance);
2729}
2730
2731#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2732/* PJPROJECT ICE optional callback */
2733static void ast_rtp_on_valid_pair(pj_ice_sess *ice)
2734{
2735 ast_debug_ice(2, "(%p) ICE valid pair, start media\n", ice->user_data);
2736 ast_rtp_ice_start_media(ice, PJ_SUCCESS);
2737}
2738#endif
2739
2740/* PJPROJECT ICE callback */
2741static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
2742{
2743 ast_debug_ice(2, "(%p) ICE complete, start media\n", ice->user_data);
2744 ast_rtp_ice_start_media(ice, status);
2745}
2746
2747/* PJPROJECT ICE callback */
2748static 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)
2749{
2750 struct ast_rtp_instance *instance = ice->user_data;
2751 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2752
2753 /* 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
2754 * returns */
2755 if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
2756 rtp->passthrough = 1;
2757 } else if (transport_id == TRANSPORT_TURN_RTP) {
2758 rtp->rtp_passthrough = 1;
2759 } else if (transport_id == TRANSPORT_TURN_RTCP) {
2760 rtp->rtcp_passthrough = 1;
2761 }
2762}
2763
2764/* PJPROJECT ICE callback */
2765static 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)
2766{
2767 struct ast_rtp_instance *instance = ice->user_data;
2768 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2769 pj_status_t status = PJ_EINVALIDOP;
2770 pj_ssize_t _size = (pj_ssize_t)size;
2771
2772 if (transport_id == TRANSPORT_SOCKET_RTP) {
2773 /* Traffic is destined to go right out the RTP socket we already have */
2774 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2775 /* sendto on a connectionless socket should send all the data, or none at all */
2776 ast_assert(_size == size || status != PJ_SUCCESS);
2777 } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
2778 /* Traffic is destined to go right out the RTCP socket we already have */
2779 if (rtp->rtcp) {
2780 status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2781 /* sendto on a connectionless socket should send all the data, or none at all */
2782 ast_assert(_size == size || status != PJ_SUCCESS);
2783 } else {
2784 status = PJ_SUCCESS;
2785 }
2786 } else if (transport_id == TRANSPORT_TURN_RTP) {
2787 /* Traffic is going through the RTP TURN relay */
2788 if (rtp->turn_rtp) {
2789 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
2790 }
2791 } else if (transport_id == TRANSPORT_TURN_RTCP) {
2792 /* Traffic is going through the RTCP TURN relay */
2793 if (rtp->turn_rtcp) {
2794 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
2795 }
2796 }
2797
2798 return status;
2799}
2800
2801/* ICE Session interface declaration */
2802static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
2803#ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2804 .on_valid_pair = ast_rtp_on_valid_pair,
2805#endif
2806 .on_ice_complete = ast_rtp_on_ice_complete,
2807 .on_rx_data = ast_rtp_on_ice_rx_data,
2808 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
2809};
2810
2811/*! \brief Worker thread for timerheap */
2812static int timer_worker_thread(void *data)
2813{
2814 pj_ioqueue_t *ioqueue;
2815
2816 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
2817 return -1;
2818 }
2819
2820 while (!timer_terminate) {
2821 const pj_time_val delay = {0, 10};
2822
2823 pj_timer_heap_poll(timer_heap, NULL);
2824 pj_ioqueue_poll(ioqueue, &delay);
2825 }
2826
2827 return 0;
2828}
2829#endif
2830
2831static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
2832{
2834 return 0;
2835 }
2837 if (rtpdebugport) {
2838 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
2839 } else {
2840 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
2841 }
2842 }
2843
2844 return 1;
2845}
2846
2847static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
2848{
2850 return 0;
2851 }
2853 if (rtcpdebugport) {
2854 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
2855 } else {
2856 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
2857 }
2858 }
2859
2860 return 1;
2861}
2862
2863#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2864/*!
2865 * \brief Handles DTLS timer expiration
2866 *
2867 * \param instance
2868 * \param timeout
2869 * \param rtcp
2870 *
2871 * If DTLSv1_get_timeout() returns 0, it's an error or no timeout was set.
2872 * We need to unref instance and stop the timer in this case. Otherwise,
2873 * new timeout may be a number of milliseconds or 0. If it's 0, OpenSSL
2874 * is telling us to call DTLSv1_handle_timeout() immediately so we'll set
2875 * timeout to 1ms so we get rescheduled almost immediately.
2876 *
2877 * \retval 0 - success
2878 * \retval -1 - failure
2879 */
2880static int dtls_srtp_handle_timeout(struct ast_rtp_instance *instance, int *timeout, int rtcp)
2881{
2882 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2883 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2884 struct timeval dtls_timeout;
2885 int res = 0;
2886
2887 res = DTLSv1_handle_timeout(dtls->ssl);
2888 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d result: %d\n", instance, rtcp, res);
2889
2890 /* If a timeout can't be retrieved then this recurring scheduled item must stop */
2891 res = DTLSv1_get_timeout(dtls->ssl, &dtls_timeout);
2892 if (!res) {
2893 /* Make sure we don't try to stop the timer later if it's already been stopped */
2894 dtls->timeout_timer = -1;
2895 ao2_ref(instance, -1);
2896 *timeout = 0;
2897 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d get timeout failure\n", instance, rtcp);
2898 return -1;
2899 }
2900 *timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2901 if (*timeout == 0) {
2902 /*
2903 * If DTLSv1_get_timeout() succeeded with a timeout of 0, OpenSSL
2904 * is telling us to call DTLSv1_handle_timeout() again now HOWEVER...
2905 * Do NOT be tempted to call DTLSv1_handle_timeout() and
2906 * DTLSv1_get_timeout() in a loop while the timeout is 0. There is only
2907 * 1 thread running the scheduler for all PJSIP related RTP instances
2908 * so we don't want to delay here any more than necessary. It's also
2909 * possible that an OpenSSL bug or change in behavior could cause
2910 * DTLSv1_get_timeout() to return 0 forever. If that happens, we'll
2911 * be stuck here and no other RTP instances will get serviced.
2912 * This RTP instance is also locked while this callback runs so we
2913 * don't want to delay other threads that may need to lock this
2914 * RTP instance for their own purpose.
2915 *
2916 * Just set the timeout to 1ms and let the scheduler reschedule us
2917 * as quickly as possible.
2918 */
2919 *timeout = 1;
2920 }
2921 ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d timeout=%d\n", instance, rtcp, *timeout);
2922
2923 return 0;
2924}
2925
2926/* Scheduler callback */
2927static int dtls_srtp_handle_rtp_timeout(const void *data)
2928{
2929 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2930 int timeout = 0;
2931 int res = 0;
2932
2933 ao2_lock(instance);
2934 res = dtls_srtp_handle_timeout(instance, &timeout, 0);
2935 ao2_unlock(instance);
2936 if (res < 0) {
2937 /* Tells the scheduler to stop rescheduling */
2938 return 0;
2939 }
2940
2941 /* Reschedule based on the timeout value */
2942 return timeout;
2943}
2944
2945/* Scheduler callback */
2946static int dtls_srtp_handle_rtcp_timeout(const void *data)
2947{
2948 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2949 int timeout = 0;
2950 int res = 0;
2951
2952 ao2_lock(instance);
2953 res = dtls_srtp_handle_timeout(instance, &timeout, 1);
2954 ao2_unlock(instance);
2955 if (res < 0) {
2956 /* Tells the scheduler to stop rescheduling */
2957 return 0;
2958 }
2959
2960 /* Reschedule based on the timeout value */
2961 return timeout;
2962}
2963
2964static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
2965{
2966 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2967 ast_sched_cb cb = !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout;
2968 struct timeval dtls_timeout;
2969 int res = 0;
2970 int timeout = 0;
2971
2972 ast_assert(dtls->timeout_timer == -1);
2973
2974 res = DTLSv1_get_timeout(dtls->ssl, &dtls_timeout);
2975 if (res == 0) {
2976 ast_debug_dtls(3, "(%p) DTLS srtp - DTLSv1_get_timeout return an error or there was no timeout set for %s\n",
2977 instance, rtcp ? "RTCP" : "RTP");
2978 return;
2979 }
2980
2981 timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2982
2983 ao2_ref(instance, +1);
2984 /*
2985 * We want the timer to fire again based on calling DTLSv1_get_timeout()
2986 * inside the callback, not at a fixed interval.
2987 */
2988 if ((dtls->timeout_timer = ast_sched_add_variable(rtp->sched, timeout, cb, instance, 1)) < 0) {
2989 ao2_ref(instance, -1);
2990 ast_log(LOG_WARNING, "Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
2991 !rtcp ? "RTP" : "RTCP", instance);
2992 } else {
2993 ast_debug_dtls(3, "(%p) DTLS srtp - scheduled timeout timer for '%d' %s\n",
2994 instance, timeout, rtcp ? "RTCP" : "RTP");
2995 }
2996}
2997
2998/*! \pre Must not be called with the instance locked. */
2999static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
3000{
3001 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3002
3003 AST_SCHED_DEL_UNREF(rtp->sched, dtls->timeout_timer, ao2_ref(instance, -1));
3004 ast_debug_dtls(3, "(%p) DTLS srtp - stopped timeout timer'\n", instance);
3005}
3006
3007/* Scheduler callback */
3008static int dtls_srtp_renegotiate(const void *data)
3009{
3010 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
3011 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3012
3013 ao2_lock(instance);
3014
3015 ast_debug_dtls(3, "(%p) DTLS srtp - renegotiate'\n", instance);
3016 SSL_renegotiate(rtp->dtls.ssl);
3017 SSL_do_handshake(rtp->dtls.ssl);
3018
3019 if (rtp->rtcp && rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
3020 SSL_renegotiate(rtp->rtcp->dtls.ssl);
3021 SSL_do_handshake(rtp->rtcp->dtls.ssl);
3022 }
3023
3024 rtp->rekeyid = -1;
3025
3026 ao2_unlock(instance);
3027 ao2_ref(instance, -1);
3028
3029 return 0;
3030}
3031
3032static int dtls_srtp_add_local_ssrc(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp, unsigned int ssrc, int set_remote_policy)
3033{
3034 unsigned char material[SRTP_MASTER_LEN * 2];
3035 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
3036 struct ast_srtp_policy *local_policy, *remote_policy = NULL;
3037 int res = -1;
3038 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3039
3040 ast_debug_dtls(3, "(%p) DTLS srtp - add local ssrc - rtcp=%d, set_remote_policy=%d'\n",
3041 instance, rtcp, set_remote_policy);
3042
3043 /* Produce key information and set up SRTP */
3044 if (!SSL_export_keying_material(dtls->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
3045 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
3046 instance);
3047 return -1;
3048 }
3049
3050 /* Whether we are acting as a server or client determines where the keys/salts are */
3051 if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
3052 local_key = material;
3053 remote_key = local_key + SRTP_MASTER_KEY_LEN;
3054 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
3055 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
3056 } else {
3057 remote_key = material;
3058 local_key = remote_key + SRTP_MASTER_KEY_LEN;
3059 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
3060 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
3061 }
3062
3063 if (!(local_policy = res_srtp_policy->alloc())) {
3064 return -1;
3065 }
3066
3067 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
3068 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
3069 goto error;
3070 }
3071
3072 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
3073 ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3074 goto error;
3075 }
3076
3077 res_srtp_policy->set_ssrc(local_policy, ssrc, 0);
3078
3079 if (set_remote_policy) {
3080 if (!(remote_policy = res_srtp_policy->alloc())) {
3081 goto error;
3082 }
3083
3084 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
3085 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
3086 goto error;
3087 }
3088
3089 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
3090 ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3091 goto error;
3092 }
3093
3094 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
3095 }
3096
3097 if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy, rtcp)) {
3098 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
3099 goto error;
3100 }
3101
3102 res = 0;
3103
3104error:
3105 /* policy->destroy() called even on success to release local reference to these resources */
3106 res_srtp_policy->destroy(local_policy);
3107
3108 if (remote_policy) {
3109 res_srtp_policy->destroy(remote_policy);
3110 }
3111
3112 return res;
3113}
3114
3115static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp)
3116{
3117 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3118 int index;
3119
3120 ast_debug_dtls(3, "(%p) DTLS setup SRTP rtp=%p'\n", instance, rtp);
3121
3122 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
3123 if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
3124 X509 *certificate;
3125
3126 if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
3127 ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
3128 return -1;
3129 }
3130
3131 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
3132 if (rtp->remote_fingerprint[0]) {
3133 const EVP_MD *type;
3134 unsigned char fingerprint[EVP_MAX_MD_SIZE];
3135 unsigned int size;
3136
3137 if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
3138 type = EVP_sha1();
3139 } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
3140 type = EVP_sha256();
3141 } else {
3142 ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
3143 return -1;
3144 }
3145
3146 if (!X509_digest(certificate, type, fingerprint, &size) ||
3147 !size ||
3148 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
3149 X509_free(certificate);
3150 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
3151 instance);
3152 return -1;
3153 }
3154 }
3155
3156 X509_free(certificate);
3157 }
3158
3159 if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(instance), 1)) {
3160 ast_log(LOG_ERROR, "Failed to add local source '%p'\n", rtp);
3161 return -1;
3162 }
3163
3164 for (index = 0; index < AST_VECTOR_SIZE(&rtp->ssrc_mapping); ++index) {
3165 struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&rtp->ssrc_mapping, index);
3166
3167 if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(mapping->instance), 0)) {
3168 return -1;
3169 }
3170 }
3171
3172 if (rtp->rekey) {
3173 ao2_ref(instance, +1);
3174 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
3175 ao2_ref(instance, -1);
3176 return -1;
3177 }
3178 }
3179
3180 return 0;
3181}
3182#endif
3183
3184/*! \brief Helper function to compare an elem in a vector by value */
3185static int compare_by_value(int elem, int value)
3186{
3187 return elem - value;
3188}
3189
3190/*! \brief Helper function to find an elem in a vector by value */
3191static int find_by_value(int elem, int value)
3192{
3193 return elem == value;
3194}
3195
3196static int rtcp_mux(struct ast_rtp *rtp, const unsigned char *packet)
3197{
3198 uint8_t version;
3199 uint8_t pt;
3200 uint8_t m;
3201
3202 if (!rtp->rtcp || rtp->rtcp->type != AST_RTP_INSTANCE_RTCP_MUX) {
3203 return 0;
3204 }
3205
3206 version = (packet[0] & 0XC0) >> 6;
3207 if (version == 0) {
3208 /* version 0 indicates this is a STUN packet and shouldn't
3209 * be interpreted as a possible RTCP packet
3210 */
3211 return 0;
3212 }
3213
3214 /* The second octet of a packet will be one of the following:
3215 * For RTP: The marker bit (1 bit) and the RTP payload type (7 bits)
3216 * For RTCP: The payload type (8)
3217 *
3218 * RTP has a forbidden range of payload types (64-95) since these
3219 * will conflict with RTCP payload numbers if the marker bit is set.
3220 */
3221 m = packet[1] & 0x80;
3222 pt = packet[1] & 0x7F;
3223 if (m && pt >= 64 && pt <= 95) {
3224 return 1;
3225 }
3226 return 0;
3227}
3228
3229/*! \pre instance is locked */
3230static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
3231{
3232 int len;
3233 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3234#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3235 char *in = buf;
3236#endif
3237#ifdef HAVE_PJPROJECT
3238 struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
3239#endif
3240#ifdef TEST_FRAMEWORK
3241 struct ast_rtp_engine_test *test = ast_rtp_instance_get_test(instance);
3242#endif
3243
3244 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
3245 return len;
3246 }
3247
3248#ifdef TEST_FRAMEWORK
3249 if (test && test->packets_to_drop > 0) {
3250 test->packets_to_drop--;
3251 return 0;
3252 }
3253#endif
3254
3255#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3256 /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
3257 * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
3258 if ((*in >= 20) && (*in <= 63)) {
3259 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3260 int res = 0;
3261
3262 /* If no SSL session actually exists terminate things */
3263 if (!dtls->ssl) {
3264 ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
3265 instance);
3266 return -1;
3267 }
3268
3269 ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - Got SSL packet '%d'\n", instance, rtp, *in);
3270
3271 /*
3272 * If ICE is in use, we can prevent a possible DOS attack
3273 * by allowing DTLS protocol messages (client hello, etc)
3274 * only from sources that are in the active remote
3275 * candidates list.
3276 */
3277
3278#ifdef HAVE_PJPROJECT
3279 if (rtp->ice) {
3280 int pass_src_check = 0;
3281 int ix = 0;
3282
3283 /*
3284 * You'd think that this check would cause a "deadlock"
3285 * because ast_rtp_ice_start_media calls dtls_perform_handshake
3286 * before it sets ice_media_started = 1 so how can we do a
3287 * handshake if we're dropping packets before we send them
3288 * to openssl. Fortunately, dtls_perform_handshake just sets
3289 * up openssl to do the handshake and doesn't actually perform it
3290 * itself and the locking prevents __rtp_recvfrom from
3291 * running before the ice_media_started flag is set. So only
3292 * unexpected DTLS packets can get dropped here.
3293 */
3294 if (!rtp->ice_media_started) {
3295 ast_log(LOG_WARNING, "%s: DTLS packet from %s dropped. ICE not completed yet.\n",
3298 return 0;
3299 }
3300
3301 /*
3302 * If we got this far, then there have to be candidates.
3303 * We have to use pjproject's rcands because they may have
3304 * peer reflexive candidates that our ice_active_remote_candidates
3305 * won't.
3306 */
3307 for (ix = 0; ix < rtp->ice->real_ice->rcand_cnt; ix++) {
3308 pj_ice_sess_cand *rcand = &rtp->ice->real_ice->rcand[ix];
3309 if (ast_sockaddr_pj_sockaddr_cmp(sa, &rcand->addr) == 0) {
3310 pass_src_check = 1;
3311 break;
3312 }
3313 }
3314
3315 if (!pass_src_check) {
3316 ast_log(LOG_WARNING, "%s: DTLS packet from %s dropped. Source not in ICE active candidate list.\n",
3319 return 0;
3320 }
3321 }
3322#endif
3323
3324 /*
3325 * A race condition is prevented between dtls_perform_handshake()
3326 * and this function because both functions have to get the
3327 * instance lock before they can do anything. The
3328 * dtls_perform_handshake() function needs to start the timer
3329 * before we stop it below.
3330 */
3331
3332 /* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
3333 ao2_unlock(instance);
3334 dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
3335 ao2_lock(instance);
3336
3337 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
3338 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
3339 dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
3340 SSL_set_accept_state(dtls->ssl);
3341 }
3342
3343 BIO_write(dtls->read_bio, buf, len);
3344
3345 len = SSL_read(dtls->ssl, buf, len);
3346
3347 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
3348 unsigned long error = ERR_get_error();
3349 ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
3350 instance, ERR_reason_error_string(error));
3351 return -1;
3352 }
3353
3354 if (SSL_is_init_finished(dtls->ssl)) {
3355 /* Any further connections will be existing since this is now established */
3356 dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
3357 /* Use the keying material to set up key/salt information */
3358 if ((res = dtls_srtp_setup(rtp, instance, rtcp))) {
3359 return res;
3360 }
3361 /* Notify that dtls has been established */
3363
3364 ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - established'\n", instance, rtp);
3365 } else {
3366 /* Since we've sent additional traffic start the timeout timer for retransmission */
3367 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
3368 }
3369
3370 return res;
3371 }
3372#endif
3373
3374#ifdef HAVE_PJPROJECT
3375 if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
3376 /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
3377 * so it reflects the actual source and not the loopback
3378 */
3379 if (rtcp) {
3380 ast_sockaddr_copy(sa, &rtp->rtcp->them);
3381 } else {
3383 }
3384 } else if (rtp->ice) {
3385 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
3386 pj_sockaddr address;
3387 pj_status_t status;
3388 struct ice_wrap *ice;
3389
3390 pj_thread_register_check();
3391
3392 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
3393
3394 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3395 ice = rtp->ice;
3396 ao2_ref(ice, +1);
3397 ao2_unlock(instance);
3398 status = pj_ice_sess_on_rx_pkt(ice->real_ice,
3401 pj_sockaddr_get_len(&address));
3402 ao2_ref(ice, -1);
3403 ao2_lock(instance);
3404 if (status != PJ_SUCCESS) {
3405 char err_buf[100];
3406
3407 pj_strerror(status, err_buf, sizeof(err_buf));
3408 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
3409 (int)status, err_buf);
3410 return -1;
3411 }
3412 if (!rtp->passthrough) {
3413 /* If a unidirectional ICE negotiation occurs then lock on to the source of the
3414 * ICE traffic and use it as the target. This will occur if the remote side only
3415 * wants to receive media but never send to us.
3416 */
3417 if (!rtp->ice_active_remote_candidates && !rtp->ice_proposed_remote_candidates) {
3418 if (rtcp) {
3419 ast_sockaddr_copy(&rtp->rtcp->them, sa);
3420 } else {
3422 }
3423 }
3424 return 0;
3425 }
3426 rtp->passthrough = 0;
3427 }
3428#endif
3429
3430 return len;
3431}
3432
3433/*! \pre instance is locked */
3434static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3435{
3436 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
3437}
3438
3439/*! \pre instance is locked */
3440static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3441{
3442 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
3443}
3444
3445/*! \pre instance is locked */
3446static 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)
3447{
3448 int len = size;
3449 void *temp = buf;
3450 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3451 struct ast_rtp_instance *transport = rtp->bundled ? rtp->bundled : instance;
3452 struct ast_rtp *transport_rtp = ast_rtp_instance_get_data(transport);
3453 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(transport, rtcp);
3454 int res;
3455
3456 *via_ice = 0;
3457
3458 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
3459 return -1;
3460 }
3461
3462#ifdef HAVE_PJPROJECT
3463 if (transport_rtp->ice) {
3465 pj_status_t status;
3466 struct ice_wrap *ice;
3467
3468 /* If RTCP is sharing the same socket then use the same component */
3469 if (rtcp && rtp->rtcp->s == rtp->s) {
3470 component = AST_RTP_ICE_COMPONENT_RTP;
3471 }
3472
3473 pj_thread_register_check();
3474
3475 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3476 ice = transport_rtp->ice;
3477 ao2_ref(ice, +1);
3478 if (instance == transport) {
3479 ao2_unlock(instance);
3480 }
3481 status = pj_ice_sess_send_data(ice->real_ice, component, temp, len);
3482 ao2_ref(ice, -1);
3483 if (instance == transport) {
3484 ao2_lock(instance);
3485 }
3486 if (status == PJ_SUCCESS) {
3487 *via_ice = 1;
3488 return len;
3489 }
3490 }
3491#endif
3492
3493 res = ast_sendto(rtcp ? transport_rtp->rtcp->s : transport_rtp->s, temp, len, flags, sa);
3494 if (res > 0) {
3495 ast_rtp_instance_set_last_tx(instance, time(NULL));
3496 }
3497
3498 return res;
3499}
3500
3501/*! \pre instance is locked */
3502static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3503{
3504 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
3505}
3506
3507/*! \pre instance is locked */
3508static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3509{
3510 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3511 int hdrlen = 12;
3512 int res;
3513
3514 if ((res = __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1)) > 0) {
3515 rtp->txcount++;
3516 rtp->txoctetcount += (res - hdrlen);
3517 }
3518
3519 return res;
3520}
3521
3522static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
3523{
3524 unsigned int interval;
3525 /*! \todo XXX Do a more reasonable calculation on this one
3526 * Look in RFC 3550 Section A.7 for an example*/
3527 interval = rtcpinterval;
3528 return interval;
3529}
3530
3531static void calc_mean_and_standard_deviation(double new_sample, double *mean, double *std_dev, unsigned int *count)
3532{
3533 double delta1;
3534 double delta2;
3535
3536 /* First convert the standard deviation back into a sum of squares. */
3537 double last_sum_of_squares = (*std_dev) * (*std_dev) * (*count ?: 1);
3538
3539 if (++(*count) == 0) {
3540 /* Avoid potential divide by zero on an overflow */
3541 *count = 1;
3542 }
3543
3544 /*
3545 * Below is an implementation of Welford's online algorithm [1] for calculating
3546 * mean and variance in a single pass.
3547 *
3548 * [1] https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
3549 */
3550
3551 delta1 = new_sample - *mean;
3552 *mean += (delta1 / *count);
3553 delta2 = new_sample - *mean;
3554
3555 /* Now calculate the new variance, and subsequent standard deviation */
3556 *std_dev = sqrt((last_sum_of_squares + (delta1 * delta2)) / *count);
3557}
3558
3559static int create_new_socket(const char *type, int af)
3560{
3561 int sock = ast_socket_nonblock(af, SOCK_DGRAM, 0);
3562
3563 if (sock < 0) {
3564 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
3565 return sock;
3566 }
3567
3568#ifdef SO_NO_CHECK
3569 if (nochecksums) {
3570 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3571 }
3572#endif
3573
3574 return sock;
3575}
3576
3577/*!
3578 * \internal
3579 * \brief Initializes sequence values and probation for learning mode.
3580 * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
3581 *
3582 * \param info The learning information to track
3583 * \param seq sequence number read from the rtp header to initialize the information with
3584 */
3585static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
3586{
3587 info->max_seq = seq;
3588 info->packets = learning_min_sequential;
3589 memset(&info->received, 0, sizeof(info->received));
3590}
3591
3592/*!
3593 * \internal
3594 * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
3595 * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
3596 *
3597 * \param info Structure tracking the learning progress of some address
3598 * \param seq sequence number read from the rtp header
3599 * \retval 0 if probation mode should exit for this address
3600 * \retval non-zero if probation mode should continue
3601 */
3603{
3604 if (seq == (uint16_t) (info->max_seq + 1)) {
3605 /* packet is in sequence */
3606 info->packets--;
3607 } else {
3608 /* Sequence discontinuity; reset */
3609 info->packets = learning_min_sequential - 1;
3610 info->received = ast_tvnow();
3611 }
3612
3613 /* Only check time if strictrtp is set to yes. Otherwise, we only needed to check seqno */
3614 if (strictrtp == STRICT_RTP_YES) {
3615 switch (info->stream_type) {
3618 /*
3619 * Protect against packet floods by checking that we
3620 * received the packet sequence in at least the minimum
3621 * allowed time.
3622 */
3623 if (ast_tvzero(info->received)) {
3624 info->received = ast_tvnow();
3625 } else if (!info->packets
3627 /* Packet flood; reset */
3628 info->packets = learning_min_sequential - 1;
3629 info->received = ast_tvnow();
3630 }
3631 break;
3635 case AST_MEDIA_TYPE_END:
3636 break;
3637 }
3638 }
3639
3640 info->max_seq = seq;
3641
3642 return info->packets;
3643}
3644
3645/*!
3646 * \brief Start the strictrtp learning mode.
3647 *
3648 * \param rtp RTP session description
3649 */
3650static void rtp_learning_start(struct ast_rtp *rtp)
3651{
3653 memset(&rtp->rtp_source_learn.proposed_address, 0,
3654 sizeof(rtp->rtp_source_learn.proposed_address));
3656 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t) rtp->lastrxseqno);
3657}
3658
3659#ifdef HAVE_PJPROJECT
3660static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
3661
3662/*!
3663 * \internal
3664 * \brief Resets and ACL to empty state.
3665 */
3666static void rtp_unload_acl(ast_rwlock_t *lock, struct ast_acl_list **acl)
3667{
3671}
3672
3673/*!
3674 * \internal
3675 * \brief Checks an address against the ICE blacklist
3676 * \note If there is no ice_blacklist list, always returns 0
3677 *
3678 * \param address The address to consider
3679 * \retval 0 if address is not ICE blacklisted
3680 * \retval 1 if address is ICE blacklisted
3681 */
3682static int rtp_address_is_ice_blacklisted(const struct ast_sockaddr *address)
3683{
3684 int result = 0;
3685
3686 ast_rwlock_rdlock(&ice_acl_lock);
3688 ast_rwlock_unlock(&ice_acl_lock);
3689
3690 return result;
3691}
3692
3693/*!
3694 * \internal
3695 * \brief Checks an address against the STUN blacklist
3696 * \since 13.16.0
3697 *
3698 * \note If there is no stun_blacklist list, always returns 0
3699 *
3700 * \param addr The address to consider
3701 *
3702 * \retval 0 if address is not STUN blacklisted
3703 * \retval 1 if address is STUN blacklisted
3704 */
3705static int stun_address_is_blacklisted(const struct ast_sockaddr *addr)
3706{
3707 int result = 0;
3708
3709 ast_rwlock_rdlock(&stun_acl_lock);
3710 result |= ast_apply_acl_nolog(stun_acl, addr) == AST_SENSE_DENY;
3711 ast_rwlock_unlock(&stun_acl_lock);
3712
3713 return result;
3714}
3715
3716/*! \pre instance is locked */
3717static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
3718 int transport)
3719{
3720 unsigned int count = 0;
3721 struct ifaddrs *ifa, *ia;
3722 struct ast_sockaddr tmp;
3723 pj_sockaddr pjtmp;
3724 struct ast_ice_host_candidate *candidate;
3725 int af_inet_ok = 0, af_inet6_ok = 0;
3726 struct sockaddr_in stunaddr_copy;
3727
3728 if (ast_sockaddr_is_ipv4(addr)) {
3729 af_inet_ok = 1;
3730 } else if (ast_sockaddr_is_any(addr)) {
3731 af_inet_ok = af_inet6_ok = 1;
3732 } else {
3733 af_inet6_ok = 1;
3734 }
3735
3736 if (getifaddrs(&ifa) < 0) {
3737 /* If we can't get addresses, we can't load ICE candidates */
3738 ast_log(LOG_ERROR, "(%p) ICE Error obtaining list of local addresses: %s\n",
3739 instance, strerror(errno));
3740 } else {
3741 ast_debug_ice(2, "(%p) ICE add system candidates\n", instance);
3742 /* Iterate through the list of addresses obtained from the system,
3743 * until we've iterated through all of them, or accepted
3744 * PJ_ICE_MAX_CAND candidates */
3745 for (ia = ifa; ia && count < PJ_ICE_MAX_CAND; ia = ia->ifa_next) {
3746 /* Interface is either not UP or doesn't have an address assigned,
3747 * eg, a ppp that just completed LCP but no IPCP yet */
3748 if (!ia->ifa_addr || (ia->ifa_flags & IFF_UP) == 0) {
3749 continue;
3750 }
3751
3752 /* Filter out non-IPvX addresses, eg, link-layer */
3753 if (ia->ifa_addr->sa_family != AF_INET && ia->ifa_addr->sa_family != AF_INET6) {
3754 continue;
3755 }
3756
3757 ast_sockaddr_from_sockaddr(&tmp, ia->ifa_addr);
3758
3759 if (ia->ifa_addr->sa_family == AF_INET) {
3760 const struct sockaddr_in *sa_in = (struct sockaddr_in*)ia->ifa_addr;
3761 if (!af_inet_ok) {
3762 continue;
3763 }
3764
3765 /* Skip 127.0.0.0/8 (loopback) */
3766 /* Don't use IFF_LOOPBACK check since one could assign usable
3767 * publics to the loopback */
3768 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) {
3769 continue;
3770 }
3771
3772 /* Skip 0.0.0.0/8 based on RFC1122, and from pjproject */
3773 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == 0) {
3774 continue;
3775 }
3776 } else { /* ia->ifa_addr->sa_family == AF_INET6 */
3777 if (!af_inet6_ok) {
3778 continue;
3779 }
3780
3781 /* Filter ::1 */
3782 if (!ast_sockaddr_cmp_addr(&lo6, &tmp)) {
3783 continue;
3784 }
3785 }
3786
3787 /* Pull in the host candidates from [ice_host_candidates] */
3788 AST_RWLIST_RDLOCK(&host_candidates);
3789 AST_LIST_TRAVERSE(&host_candidates, candidate, next) {
3790 if (!ast_sockaddr_cmp(&candidate->local, &tmp)) {
3791 /* candidate->local matches actual assigned, so check if
3792 * advertised is blacklisted, if not, add it to the
3793 * advertised list. Not that it would make sense to remap
3794 * a local address to a blacklisted address, but honour it
3795 * anyway. */
3796 if (!rtp_address_is_ice_blacklisted(&candidate->advertised)) {
3797 ast_sockaddr_to_pj_sockaddr(&candidate->advertised, &pjtmp);
3798 pj_sockaddr_set_port(&pjtmp, port);
3799 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3800 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3801 pj_sockaddr_get_len(&pjtmp));
3802 ++count;
3803 }
3804
3805 if (!candidate->include_local) {
3806 /* We don't want to advertise the actual address */
3808 }
3809
3810 break;
3811 }
3812 }
3813 AST_RWLIST_UNLOCK(&host_candidates);
3814
3815 /* we had an entry in [ice_host_candidates] that matched, and
3816 * didn't have include_local_address set. Alternatively, adding
3817 * that match resulted in us going to PJ_ICE_MAX_CAND */
3818 if (ast_sockaddr_isnull(&tmp) || count == PJ_ICE_MAX_CAND) {
3819 continue;
3820 }
3821
3822 if (rtp_address_is_ice_blacklisted(&tmp)) {
3823 continue;
3824 }
3825
3827 pj_sockaddr_set_port(&pjtmp, port);
3828 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3829 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3830 pj_sockaddr_get_len(&pjtmp));
3831 ++count;
3832 }
3833 freeifaddrs(ifa);
3834 }
3835
3836 ast_rwlock_rdlock(&stunaddr_lock);
3837 memcpy(&stunaddr_copy, &stunaddr, sizeof(stunaddr));
3838 ast_rwlock_unlock(&stunaddr_lock);
3839
3840 /* If configured to use a STUN server to get our external mapped address do so */
3841 if (stunaddr_copy.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
3842 (ast_sockaddr_is_ipv4(addr) || ast_sockaddr_is_any(addr)) &&
3843 count < PJ_ICE_MAX_CAND) {
3844 struct sockaddr_in answer;
3845 int rsp;
3846
3848 "(%p) ICE request STUN %s %s candidate\n", instance,
3849 transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
3850 component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
3851
3852 /*
3853 * The instance should not be locked because we can block
3854 * waiting for a STUN respone.
3855 */
3856 ao2_unlock(instance);
3858 ? rtp->rtcp->s : rtp->s, &stunaddr_copy, NULL, &answer);
3859 ao2_lock(instance);
3860 if (!rsp) {
3861 struct ast_rtp_engine_ice_candidate *candidate;
3862 pj_sockaddr ext, base;
3863 pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
3864 int srflx = 1, baseset = 0;
3865 struct ao2_iterator i;
3866
3867 pj_sockaddr_init(pj_AF_INET(), &ext, &mapped, ntohs(answer.sin_port));
3868
3869 /*
3870 * If the returned address is the same as one of our host
3871 * candidates, don't send the srflx. At the same time,
3872 * we need to set the base address (raddr).
3873 */
3874 i = ao2_iterator_init(rtp->ice_local_candidates, 0);
3875 while (srflx && (candidate = ao2_iterator_next(&i))) {
3876 if (!baseset && ast_sockaddr_is_ipv4(&candidate->address)) {
3877 baseset = 1;
3878 ast_sockaddr_to_pj_sockaddr(&candidate->address, &base);
3879 }
3880
3881 if (!pj_sockaddr_cmp(&candidate->address, &ext)) {
3882 srflx = 0;
3883 }
3884
3885 ao2_ref(candidate, -1);
3886 }
3888
3889 if (srflx && baseset) {
3890 pj_sockaddr_set_port(&base, port);
3891 ast_rtp_ice_add_cand(instance, rtp, component, transport,
3892 PJ_ICE_CAND_TYPE_SRFLX, 65535, &ext, &base, &base,
3893 pj_sockaddr_get_len(&ext));
3894 }
3895 }
3896 }
3897
3898 /* If configured to use a TURN relay create a session and allocate */
3899 if (pj_strlen(&turnaddr)) {
3900 ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
3901 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
3902 }
3903}
3904#endif
3905
3906/*!
3907 * \internal
3908 * \brief Calculates the elapsed time from issue of the first tx packet in an
3909 * rtp session and a specified time
3910 *
3911 * \param rtp pointer to the rtp struct with the transmitted rtp packet
3912 * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
3913 *
3914 * \return time elapsed in milliseconds
3915 */
3916static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
3917{
3918 struct timeval t;
3919 long ms;
3920
3921 if (ast_tvzero(rtp->txcore)) {
3922 rtp->txcore = ast_tvnow();
3923 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
3924 }
3925
3926 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
3927 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
3928 ms = 0;
3929 }
3930 rtp->txcore = t;
3931
3932 return (unsigned int) ms;
3933}
3934
3935#ifdef HAVE_PJPROJECT
3936/*!
3937 * \internal
3938 * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
3939 *
3940 * \param instance RTP instance for which the ICE session is being replaced
3941 * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
3942 * \param port port to use for adding RTP candidates to the ICE session
3943 * \param replace 0 when creating a new session, 1 when replacing a destroyed session
3944 *
3945 * \pre instance is locked
3946 *
3947 * \retval 0 on success
3948 * \retval -1 on failure
3949 */
3950static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
3951 int port, int replace)
3952{
3953 pj_stun_config stun_config;
3954 pj_str_t ufrag, passwd;
3955 pj_status_t status;
3956 struct ice_wrap *ice_old;
3957 struct ice_wrap *ice;
3958 pj_ice_sess *real_ice = NULL;
3959 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3960
3961 ao2_cleanup(rtp->ice_local_candidates);
3962 rtp->ice_local_candidates = NULL;
3963
3964 ast_debug_ice(2, "(%p) ICE create%s\n", instance, replace ? " and replace" : "");
3965
3966 ice = ao2_alloc_options(sizeof(*ice), ice_wrap_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
3967 if (!ice) {
3968 ast_rtp_ice_stop(instance);
3969 return -1;
3970 }
3971
3972 pj_thread_register_check();
3973
3974 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
3975 if (!stun_software_attribute) {
3976 stun_config.software_name = pj_str(NULL);
3977 }
3978
3979 ufrag = pj_str(rtp->local_ufrag);
3980 passwd = pj_str(rtp->local_passwd);
3981
3982 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3983 ao2_unlock(instance);
3984 /* Create an ICE session for ICE negotiation */
3985 status = pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
3986 rtp->ice_num_components, &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &real_ice);
3987 ao2_lock(instance);
3988 if (status == PJ_SUCCESS) {
3989 /* Safely complete linking the ICE session into the instance */
3990 real_ice->user_data = instance;
3991 ice->real_ice = real_ice;
3992 ice_old = rtp->ice;
3993 rtp->ice = ice;
3994 if (ice_old) {
3995 ao2_unlock(instance);
3996 ao2_ref(ice_old, -1);
3997 ao2_lock(instance);
3998 }
3999
4000 /* Add all of the available candidates to the ICE session */
4001 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
4003
4004 /* Only add the RTCP candidates to ICE when replacing the session and if
4005 * the ICE session contains more than just an RTP component. New sessions
4006 * handle this in a separate part of the setup phase */
4007 if (replace && rtp->rtcp && rtp->ice_num_components > 1) {
4008 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
4011 }
4012
4013 return 0;
4014 }
4015
4016 /*
4017 * It is safe to unref this while instance is locked here.
4018 * It was not initialized with a real_ice pointer.
4019 */
4020 ao2_ref(ice, -1);
4021
4022 ast_rtp_ice_stop(instance);
4023 return -1;
4024
4025}
4026#endif
4027
4028static int rtp_allocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
4029{
4030 int x, startplace, i, maxloops;
4031
4033
4034 /* Create a new socket for us to listen on and use */
4035 if ((rtp->s =
4036 create_new_socket("RTP",
4037 ast_sockaddr_is_ipv4(&rtp->bind_address) ? AF_INET :
4038 ast_sockaddr_is_ipv6(&rtp->bind_address) ? AF_INET6 : -1)) < 0) {
4039 ast_log(LOG_WARNING, "Failed to create a new socket for RTP instance '%p'\n", instance);
4040 return -1;
4041 }
4042
4043 /* Now actually find a free RTP port to use */
4044 x = (ast_random() % (rtpend - rtpstart)) + rtpstart;
4045 x = x & ~1;
4046 startplace = x;
4047
4048 /* Protection against infinite loops in the case there is a potential case where the loop is not broken such as an odd
4049 start port sneaking in (even though this condition is checked at load.) */
4050 maxloops = rtpend - rtpstart;
4051 for (i = 0; i <= maxloops; i++) {
4053 /* Try to bind, this will tell us whether the port is available or not */
4054 if (!ast_bind(rtp->s, &rtp->bind_address)) {
4055 ast_debug_rtp(1, "(%p) RTP allocated port %d\n", instance, x);
4057 ast_test_suite_event_notify("RTP_PORT_ALLOCATED", "Port: %d", x);
4058 break;
4059 }
4060
4061 x += 2;
4062 if (x > rtpend) {
4063 x = (rtpstart + 1) & ~1;
4064 }
4065
4066 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
4067 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
4068 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
4069 close(rtp->s);
4070 rtp->s = -1;
4071 return -1;
4072 }
4073 }
4074
4075#ifdef HAVE_PJPROJECT
4076 /* Initialize synchronization aspects */
4077 ast_cond_init(&rtp->cond, NULL);
4078
4079 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
4080 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
4081
4082 /* Create an ICE session for ICE negotiation */
4083 if (icesupport) {
4084 rtp->ice_num_components = 2;
4085 ast_debug_ice(2, "(%p) ICE creating session %s (%d)\n", instance,
4087 if (ice_create(instance, &rtp->bind_address, x, 0)) {
4088 ast_log(LOG_NOTICE, "(%p) ICE failed to create session\n", instance);
4089 } else {
4090 rtp->ice_port = x;
4091 ast_sockaddr_copy(&rtp->ice_original_rtp_addr, &rtp->bind_address);
4092 }
4093 }
4094#endif
4095
4096#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4097 rtp->rekeyid = -1;
4098 rtp->dtls.timeout_timer = -1;
4099#endif
4100
4101 return 0;
4102}
4103
4104static void rtp_deallocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
4105{
4106 int saved_rtp_s = rtp->s;
4107#ifdef HAVE_PJPROJECT
4108 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
4109 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
4110#endif
4111
4112#if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4113 ast_rtp_dtls_stop(instance);
4114#endif
4115
4116 /* Close our own socket so we no longer get packets */
4117 if (rtp->s > -1) {
4118 close(rtp->s);
4119 rtp->s = -1;
4120 }
4121
4122 /* Destroy RTCP if it was being used */
4123 if (rtp->rtcp && rtp->rtcp->s > -1) {
4124 if (saved_rtp_s != rtp->rtcp->s) {
4125 close(rtp->rtcp->s);
4126 }
4127 rtp->rtcp->s = -1;
4128 }
4129
4130#ifdef HAVE_PJPROJECT
4131 pj_thread_register_check();
4132
4133 /*
4134 * The instance lock is already held.
4135 *
4136 * Destroy the RTP TURN relay if being used
4137 */
4138 if (rtp->turn_rtp) {
4139 rtp->turn_state = PJ_TURN_STATE_NULL;
4140
4141 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
4142 ao2_unlock(instance);
4143 pj_turn_sock_destroy(rtp->turn_rtp);
4144 ao2_lock(instance);
4145 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4146 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
4147 }
4148 rtp->turn_rtp = NULL;
4149 }
4150
4151 /* Destroy the RTCP TURN relay if being used */
4152 if (rtp->turn_rtcp) {
4153 rtp->turn_state = PJ_TURN_STATE_NULL;
4154
4155 /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
4156 ao2_unlock(instance);
4157 pj_turn_sock_destroy(rtp->turn_rtcp);
4158 ao2_lock(instance);
4159 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
4160 ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
4161 }
4162 rtp->turn_rtcp = NULL;
4163 }
4164
4165 ast_debug_ice(2, "(%p) ICE RTP transport deallocating\n", instance);
4166 /* Destroy any ICE session */
4167 ast_rtp_ice_stop(instance);
4168
4169 /* Destroy any candidates */
4170 if (rtp->ice_local_candidates) {
4171 ao2_ref(rtp->ice_local_candidates, -1);
4172 rtp->ice_local_candidates = NULL;
4173 }
4174
4175 if (rtp->ice_active_remote_candidates) {
4176 ao2_ref(rtp->ice_active_remote_candidates, -1);
4177 rtp->ice_active_remote_candidates = NULL;
4178 }
4179
4180 if (rtp->ice_proposed_remote_candidates) {
4181 ao2_ref(rtp->ice_proposed_remote_candidates, -1);
4182 rtp->ice_proposed_remote_candidates = NULL;
4183 }
4184
4185 if (rtp->ioqueue) {
4186 /*
4187 * We cannot hold the instance lock because we could wait
4188 * for the ioqueue thread to die and we might deadlock as
4189 * a result.
4190 */
4191 ao2_unlock(instance);
4192 rtp_ioqueue_thread_remove(rtp->ioqueue);
4193 ao2_lock(instance);
4194 rtp->ioqueue = NULL;
4195 }
4196#endif
4197}
4198
4199/*! \pre instance is locked */
4200static int ast_rtp_new(struct ast_rtp_instance *instance,
4201 struct ast_sched_context *sched, struct ast_sockaddr *addr,
4202 void *data)
4203{
4204 struct ast_rtp *rtp = NULL;
4205
4206 /* Create a new RTP structure to hold all of our data */
4207 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
4208 return -1;
4209 }
4210 rtp->owner = instance;
4211 /* Set default parameters on the newly created RTP structure */
4212 rtp->ssrc = ast_random();
4213 ast_uuid_generate_str(rtp->cname, sizeof(rtp->cname));
4214 rtp->seqno = ast_random() & 0xffff;
4215 rtp->expectedrxseqno = -1;
4216 rtp->expectedseqno = -1;
4217 rtp->rxstart = -1;
4218 rtp->sched = sched;
4219 ast_sockaddr_copy(&rtp->bind_address, addr);
4220 /* Transport creation operations can grab the RTP data from the instance, so set it */
4221 ast_rtp_instance_set_data(instance, rtp);
4222
4223 if (rtp_allocate_transport(instance, rtp)) {
4224 return -1;
4225 }
4226
4227 if (AST_VECTOR_INIT(&rtp->ssrc_mapping, 1)) {
4228 return -1;
4229 }
4230
4232 return -1;
4233 }
4234 rtp->transport_wide_cc.schedid = -1;
4235
4239 rtp->stream_num = -1;
4240
4241 return 0;
4242}
4243
4244/*!
4245 * \brief SSRC mapping comparator for AST_VECTOR_REMOVE_CMP_UNORDERED()
4246 *
4247 * \param elem Element to compare against
4248 * \param value Value to compare with the vector element.
4249 *
4250 * \retval 0 if element does not match.
4251 * \retval Non-zero if element matches.
4252 */
4253#define SSRC_MAPPING_ELEM_CMP(elem, value) ((elem).instance == (value))
4254
4255/*! \pre instance is locked */
4256static int ast_rtp_destroy(struct ast_rtp_instance *instance)
4257{
4258 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4259
4260 if (rtp->bundled) {
4261 struct ast_rtp *bundled_rtp;
4262
4263 /* We can't hold our instance lock while removing ourselves from the parent */
4264 ao2_unlock(instance);
4265
4266 ao2_lock(rtp->bundled);
4267 bundled_rtp = ast_rtp_instance_get_data(rtp->bundled);
4269 ao2_unlock(rtp->bundled);
4270
4271 ao2_lock(instance);
4272 ao2_ref(rtp->bundled, -1);
4273 }
4274
4275 rtp_deallocate_transport(instance, rtp);
4276
4277 /* Destroy the smoother that was smoothing out audio if present */
4278 if (rtp->smoother) {
4280 }
4281
4282 /* Destroy RTCP if it was being used */
4283 if (rtp->rtcp) {
4284 /*
4285 * It is not possible for there to be an active RTCP scheduler
4286 * entry at this point since it holds a reference to the
4287 * RTP instance while it's active.
4288 */
4290 ast_free(rtp->rtcp);
4291 }
4292
4293 /* Destroy RED if it was being used */
4294 if (rtp->red) {
4295 ao2_unlock(instance);
4296 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
4297 ao2_lock(instance);
4298 ast_free(rtp->red);
4299 rtp->red = NULL;
4300 }
4301
4302 /* Destroy the send buffer if it was being used */
4303 if (rtp->send_buffer) {
4305 }
4306
4307 /* Destroy the recv buffer if it was being used */
4308 if (rtp->recv_buffer) {
4310 }
4311
4313
4319
4320 /* Finally destroy ourselves */
4321 rtp->owner = NULL;
4322 ast_free(rtp);
4323
4324 return 0;
4325}
4326
4327/*! \pre instance is locked */
4328static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
4329{
4330 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4331 rtp->dtmfmode = dtmf_mode;
4332 return 0;
4333}
4334
4335/*! \pre instance is locked */
4337{
4338 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4339 return rtp->dtmfmode;
4340}
4341
4342/*! \pre instance is locked */
4343static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
4344{
4345 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4346 struct ast_sockaddr remote_address = { {0,} };
4347 int hdrlen = 12, res = 0, i = 0, payload = -1, sample_rate = -1;
4348 char data[256];
4349 unsigned int *rtpheader = (unsigned int*)data;
4350 RAII_VAR(struct ast_format *, payload_format, NULL, ao2_cleanup);
4351
4352 ast_rtp_instance_get_remote_address(instance, &remote_address);
4353
4354 /* If we have no remote address information bail out now */
4355 if (ast_sockaddr_isnull(&remote_address)) {
4356 return -1;
4357 }
4358
4359 /* Convert given digit into what we want to transmit */
4360 if ((digit <= '9') && (digit >= '0')) {
4361 digit -= '0';
4362 } else if (digit == '*') {
4363 digit = 10;
4364 } else if (digit == '#') {
4365 digit = 11;
4366 } else if ((digit >= 'A') && (digit <= 'D')) {
4367 digit = digit - 'A' + 12;
4368 } else if ((digit >= 'a') && (digit <= 'd')) {
4369 digit = digit - 'a' + 12;
4370 } else {
4371 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4372 return -1;
4373 }
4374
4375 if (rtp->lasttxformat == ast_format_none) {
4376 /* No audio frames have been written yet so we have to lookup both the preferred payload type and bitrate. */
4378 if (payload_format) {
4379 /* If we have a preferred type, use that. Otherwise default to 8K. */
4380 sample_rate = ast_format_get_sample_rate(payload_format);
4381 }
4382 } else {
4383 sample_rate = ast_format_get_sample_rate(rtp->lasttxformat);
4384 }
4385
4386 if (sample_rate != -1) {
4388 }
4389
4390 if (payload == -1 ||
4393 /* Fall back to the preferred DTMF payload type and sample rate as either we couldn't find an audio codec to try and match
4394 sample rates with or we could, but a telephone-event matching that audio codec's sample rate was not included in the
4395 sdp negotiated by the far end. */
4398 }
4399
4400 /* The sdp negotiation has not yeilded a usable RFC 2833/4733 format. Try a default-rate one as a last resort. */
4401 if (payload == -1 || sample_rate == -1) {
4402 sample_rate = DEFAULT_DTMF_SAMPLE_RATE_MS;
4404 }
4405 /* Even trying a default payload has failed. We are trying to send a digit outside of what was negotiated for. */
4406 if (payload == -1) {
4407 return -1;
4408 }
4409
4410 ast_test_suite_event_notify("DTMF_BEGIN", "Digit: %d\r\nPayload: %d\r\nRate: %d\r\n", digit, payload, sample_rate);
4411 ast_debug(1, "Sending digit '%d' at rate %d with payload %d\n", digit, sample_rate, payload);
4412
4413 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4414 rtp->send_duration = 160;
4415 rtp->dtmf_samplerate_ms = (sample_rate / 1000);
4416 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4417 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
4418
4419 /* Create the actual packet that we will be sending */
4420 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
4421 rtpheader[1] = htonl(rtp->lastdigitts);
4422 rtpheader[2] = htonl(rtp->ssrc);
4423
4424 /* Actually send the packet */
4425 for (i = 0; i < 2; i++) {
4426 int ice;
4427
4428 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4429 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4430 if (res < 0) {
4431 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4432 ast_sockaddr_stringify(&remote_address),
4433 strerror(errno));
4434 }
4435 if (rtp_debug_test_addr(&remote_address)) {
4436 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4437 ast_sockaddr_stringify(&remote_address),
4438 ice ? " (via ICE)" : "",
4439 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4440 }
4441 rtp->seqno++;
4442 rtp->send_duration += 160;
4443 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
4444 }
4445
4446 /* Record that we are in the process of sending a digit and information needed to continue doing so */
4447 rtp->sending_digit = 1;
4448 rtp->send_digit = digit;
4449 rtp->send_payload = payload;
4450
4451 return 0;
4452}
4453
4454/*! \pre instance is locked */
4456{
4457 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4458 struct ast_sockaddr remote_address = { {0,} };
4459 int hdrlen = 12, res = 0;
4460 char data[256];
4461 unsigned int *rtpheader = (unsigned int*)data;
4462 int ice;
4463
4464 ast_rtp_instance_get_remote_address(instance, &remote_address);
4465
4466 /* Make sure we know where the other side is so we can send them the packet */
4467 if (ast_sockaddr_isnull(&remote_address)) {
4468 return -1;
4469 }
4470
4471 /* Actually create the packet we will be sending */
4472 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4473 rtpheader[1] = htonl(rtp->lastdigitts);
4474 rtpheader[2] = htonl(rtp->ssrc);
4475 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
4476
4477 /* Boom, send it on out */
4478 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4479 if (res < 0) {
4480 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4481 ast_sockaddr_stringify(&remote_address),
4482 strerror(errno));
4483 }
4484
4485 if (rtp_debug_test_addr(&remote_address)) {
4486 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4487 ast_sockaddr_stringify(&remote_address),
4488 ice ? " (via ICE)" : "",
4489 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4490 }
4491
4492 /* And now we increment some values for the next time we swing by */
4493 rtp->seqno++;
4494 rtp->send_duration += 160;
4495 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4496
4497 return 0;
4498}
4499
4500/*! \pre instance is locked */
4501static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
4502{
4503 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4504 struct ast_sockaddr remote_address = { {0,} };
4505 int hdrlen = 12, res = -1, i = 0;
4506 char data[256];
4507 unsigned int *rtpheader = (unsigned int*)data;
4508 unsigned int measured_samples;
4509
4510 ast_rtp_instance_get_remote_address(instance, &remote_address);
4511
4512 /* Make sure we know where the remote side is so we can send them the packet we construct */
4513 if (ast_sockaddr_isnull(&remote_address)) {
4514 goto cleanup;
4515 }
4516
4517 /* Convert the given digit to the one we are going to send */
4518 if ((digit <= '9') && (digit >= '0')) {
4519 digit -= '0';
4520 } else if (digit == '*') {
4521 digit = 10;
4522 } else if (digit == '#') {
4523 digit = 11;
4524 } else if ((digit >= 'A') && (digit <= 'D')) {
4525 digit = digit - 'A' + 12;
4526 } else if ((digit >= 'a') && (digit <= 'd')) {
4527 digit = digit - 'a' + 12;
4528 } else {
4529 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4530 goto cleanup;
4531 }
4532
4533 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4534
4535 if (duration > 0 && (measured_samples = duration * ast_rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
4536 ast_debug_rtp(2, "(%p) RTP adjusting final end duration from %d to %u\n",
4537 instance, rtp->send_duration, measured_samples);
4538 rtp->send_duration = measured_samples;
4539 }
4540
4541 /* Construct the packet we are going to send */
4542 rtpheader[1] = htonl(rtp->lastdigitts);
4543 rtpheader[2] = htonl(rtp->ssrc);
4544 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4545 rtpheader[3] |= htonl((1 << 23));
4546
4547 /* Send it 3 times, that's the magical number */
4548 for (i = 0; i < 3; i++) {
4549 int ice;
4550
4551 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4552
4553 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4554
4555 if (res < 0) {
4556 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4557 ast_sockaddr_stringify(&remote_address),
4558 strerror(errno));
4559 }
4560
4561 if (rtp_debug_test_addr(&remote_address)) {
4562 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4563 ast_sockaddr_stringify(&remote_address),
4564 ice ? " (via ICE)" : "",
4565 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4566 }
4567
4568 rtp->seqno++;
4569 }
4570 res = 0;
4571
4572 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
4573 rtp->lastts += calc_txstamp(rtp, NULL) * rtp->dtmf_samplerate_ms;
4574
4575 /* Reset the smoother as the delivery time stored in it is now out of date */
4576 if (rtp->smoother) {
4578 rtp->smoother = NULL;
4579 }
4580cleanup:
4581 rtp->sending_digit = 0;
4582 rtp->send_digit = 0;
4583
4584 /* Re-Learn expected seqno */
4585 rtp->expectedseqno = -1;
4586
4587 return res;
4588}
4589
4590/*! \pre instance is locked */
4591static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
4592{
4593 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
4594}
4595
4596/*! \pre instance is locked */
4597static void ast_rtp_update_source(struct ast_rtp_instance *instance)
4598{
4599 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4600
4601 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4603 ast_debug_rtp(3, "(%p) RTP setting the marker bit due to a source update\n", instance);
4604
4605 return;
4606}
4607
4608/*! \pre instance is locked */
4609static void ast_rtp_change_source(struct ast_rtp_instance *instance)
4610{
4611 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4612 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, 0);
4613 struct ast_srtp *rtcp_srtp = ast_rtp_instance_get_srtp(instance, 1);
4614 unsigned int ssrc = ast_random();
4615
4616 if (rtp->lastts) {
4617 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4619 }
4620
4621 ast_debug_rtp(3, "(%p) RTP changing ssrc from %u to %u due to a source change\n",
4622 instance, rtp->ssrc, ssrc);
4623
4624 if (srtp) {
4625 ast_debug_rtp(3, "(%p) RTP changing ssrc for SRTP from %u to %u\n",
4626 instance, rtp->ssrc, ssrc);
4627 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
4628 if (rtcp_srtp != srtp) {
4629 res_srtp->change_source(rtcp_srtp, rtp->ssrc, ssrc);
4630 }
4631 }
4632
4633 rtp->ssrc = ssrc;
4634
4635 /* Since the source is changing, we don't know what sequence number to expect next */
4636 rtp->expectedrxseqno = -1;
4637
4638 return;
4639}
4640
4641static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
4642{
4643 unsigned int sec, usec, frac;
4644 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
4645 usec = tv.tv_usec;
4646 /*
4647 * Convert usec to 0.32 bit fixed point without overflow.
4648 *
4649 * = usec * 2^32 / 10^6
4650 * = usec * 2^32 / (2^6 * 5^6)
4651 * = usec * 2^26 / 5^6
4652 *
4653 * The usec value needs 20 bits to represent 999999 usec. So
4654 * splitting the 2^26 to get the most precision using 32 bit
4655 * values gives:
4656 *
4657 * = ((usec * 2^12) / 5^6) * 2^14
4658 *
4659 * Splitting the division into two stages preserves all the
4660 * available significant bits of usec over doing the division
4661 * all at once.
4662 *
4663 * = ((((usec * 2^12) / 5^3) * 2^7) / 5^3) * 2^7
4664 */
4665 frac = ((((usec << 12) / 125) << 7) / 125) << 7;
4666 *msw = sec;
4667 *lsw = frac;
4668}
4669
4670static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
4671{
4672 tv->tv_sec = msw - 2208988800u;
4673 /* Reverse the sequence in timeval2ntp() */
4674 tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
4675}
4676
4678 unsigned int *lost_packets,
4679 int *fraction_lost)
4680{
4681 unsigned int extended_seq_no;
4682 unsigned int expected_packets;
4683 unsigned int expected_interval;
4684 unsigned int received_interval;
4685 int lost_interval;
4686
4687 /* Compute statistics */
4688 extended_seq_no = rtp->cycles + rtp->lastrxseqno;
4689 expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
4690 if (rtp->rxcount > expected_packets) {
4691 expected_packets += rtp->rxcount - expected_packets;
4692 }
4693 *lost_packets = expected_packets - rtp->rxcount;
4694 expected_interval = expected_packets - rtp->rtcp->expected_prior;
4695 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
4696 if (received_interval > expected_interval) {
4697 /* If we receive some late packets it is possible for the packets
4698 * we received in this interval to exceed the number we expected.
4699 * We update the expected so that the packet loss calculations
4700 * show that no packets are lost.
4701 */
4702 expected_interval = received_interval;
4703 }
4704 lost_interval = expected_interval - received_interval;
4705 if (expected_interval == 0 || lost_interval <= 0) {
4706 *fraction_lost = 0;
4707 } else {
4708 *fraction_lost = (lost_interval << 8) / expected_interval;
4709 }
4710
4711 /* Update RTCP statistics */
4712 rtp->rtcp->received_prior = rtp->rxcount;
4713 rtp->rtcp->expected_prior = expected_packets;
4714
4715 /*
4716 * While rxlost represents the number of packets lost since the last report was sent, for
4717 * the calculations below it should be thought of as a single sample. Thus min/max are the
4718 * lowest/highest sample value seen, and the mean is the average number of packets lost
4719 * between each report. As such rxlost_count only needs to be incremented per report.
4720 */
4721 if (lost_interval <= 0) {
4722 rtp->rtcp->rxlost = 0;
4723 } else {
4724 rtp->rtcp->rxlost = lost_interval;
4725 }
4726 if (rtp->rtcp->rxlost_count == 0) {
4727 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4728 }
4729 if (lost_interval && lost_interval < rtp->rtcp->minrxlost) {
4730 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4731 }
4732 if (lost_interval > rtp->rtcp->maxrxlost) {
4733 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
4734 }
4735
4736 calc_mean_and_standard_deviation(rtp->rtcp->rxlost, &rtp->rtcp->normdev_rxlost,
4737 &rtp->rtcp->stdev_rxlost, &rtp->rtcp->rxlost_count);
4738}
4739
4740static int ast_rtcp_generate_report(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4741 struct ast_rtp_rtcp_report *rtcp_report, int *sr)
4742{
4743 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4744 int len = 0;
4745 struct timeval now;
4746 unsigned int now_lsw;
4747 unsigned int now_msw;
4748 unsigned int lost_packets;
4749 int fraction_lost;
4750 struct timeval dlsr = { 0, };
4751 struct ast_rtp_rtcp_report_block *report_block = NULL;
4752
4753 if (!rtp || !rtp->rtcp) {
4754 return 0;
4755 }
4756
4757 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
4758 /* RTCP was stopped. */
4759 return 0;
4760 }
4761
4762 if (!rtcp_report) {
4763 return 1;
4764 }
4765
4766 *sr = rtp->txcount > rtp->rtcp->lastsrtxcount ? 1 : 0;
4767
4768 /* Compute statistics */
4769 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
4770 /*
4771 * update_local_mes_stats must be called AFTER
4772 * calculate_lost_packet_statistics
4773 */
4775
4776 gettimeofday(&now, NULL);
4777 rtcp_report->reception_report_count = rtp->themssrc_valid ? 1 : 0;
4778 rtcp_report->ssrc = rtp->ssrc;
4779 rtcp_report->type = *sr ? RTCP_PT_SR : RTCP_PT_RR;
4780 if (*sr) {
4781 rtcp_report->sender_information.ntp_timestamp = now;
4782 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
4783 rtcp_report->sender_information.packet_count = rtp->txcount;
4784 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
4785 }
4786
4787 if (rtp->themssrc_valid) {
4788 report_block = ast_calloc(1, sizeof(*report_block));
4789 if (!report_block) {
4790 return 1;
4791 }
4792
4793 rtcp_report->report_block[0] = report_block;
4794 report_block->source_ssrc = rtp->themssrc;
4795 report_block->lost_count.fraction = (fraction_lost & 0xff);
4796 report_block->lost_count.packets = (lost_packets & 0xffffff);
4797 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
4798 report_block->ia_jitter = (unsigned int)rtp->rxjitter_samples;
4799 report_block->lsr = rtp->rtcp->themrxlsr;
4800 /* If we haven't received an SR report, DLSR should be 0 */
4801 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
4802 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
4803 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
4804 }
4805 }
4806 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
4807 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc)); /* Our SSRC */
4808 len += 8;
4809 if (*sr) {
4810 put_unaligned_uint32(rtcpheader + len, htonl(now_msw)); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970 */
4811 put_unaligned_uint32(rtcpheader + len + 4, htonl(now_lsw)); /* now, LSW */
4812 put_unaligned_uint32(rtcpheader + len + 8, htonl(rtcp_report->sender_information.rtp_timestamp));
4813 put_unaligned_uint32(rtcpheader + len + 12, htonl(rtcp_report->sender_information.packet_count));
4814 put_unaligned_uint32(rtcpheader + len + 16, htonl(rtcp_report->sender_information.octet_count));
4815 len += 20;
4816 }
4817 if (report_block) {
4818 put_unaligned_uint32(rtcpheader + len, htonl(report_block->source_ssrc)); /* Their SSRC */
4819 put_unaligned_uint32(rtcpheader + len + 4, htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets));
4820 put_unaligned_uint32(rtcpheader + len + 8, htonl(report_block->highest_seq_no));
4821 put_unaligned_uint32(rtcpheader + len + 12, htonl(report_block->ia_jitter));
4822 put_unaligned_uint32(rtcpheader + len + 16, htonl(report_block->lsr));
4823 put_unaligned_uint32(rtcpheader + len + 20, htonl(report_block->dlsr));
4824 len += 24;
4825 }
4826
4827 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
4828 | ((*sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1)));
4829
4830 return len;
4831}
4832
4834 struct ast_rtp_rtcp_report *rtcp_report, struct ast_sockaddr remote_address, int ice, int sr)
4835{
4836 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4837 struct ast_rtp_rtcp_report_block *report_block = NULL;
4838 RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
4839
4840 if (!rtp || !rtp->rtcp) {
4841 return 0;
4842 }
4843
4844 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4845 return 0;
4846 }
4847
4848 if (!rtcp_report) {
4849 return -1;
4850 }
4851
4852 report_block = rtcp_report->report_block[0];
4853
4854 if (sr) {
4855 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
4856 rtp->rtcp->sr_count++;
4857 rtp->rtcp->lastsrtxcount = rtp->txcount;
4858 } else {
4859 rtp->rtcp->rr_count++;
4860 }
4861
4862 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
4863 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
4864 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
4865 ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
4866 if (sr) {
4867 ast_verbose(" Sent(NTP): %u.%06u\n",
4868 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
4869 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
4870 ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
4871 ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
4872 ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
4873 }
4874 if (report_block) {
4875 int rate = ast_rtp_get_rate(rtp->f.subclass.format);
4876 ast_verbose(" Report block:\n");
4877 ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
4878 ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
4879 ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
4880 ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
4881 ast_verbose(" IA jitter (samp): %u\n", report_block->ia_jitter);
4882 ast_verbose(" IA jitter (secs): %.6f\n", ast_samp2sec(report_block->ia_jitter, rate));
4883 ast_verbose(" Their last SR: %u\n", report_block->lsr);
4884 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
4885 }
4886 }
4887
4888 message_blob = ast_json_pack("{s: s, s: s, s: f}",
4889 "to", ast_sockaddr_stringify(&remote_address),
4890 "from", rtp->rtcp->local_addr_str,
4891 "mes", rtp->rxmes);
4892
4894 rtcp_report, message_blob);
4895
4896 return 1;
4897}
4898
4899static int ast_rtcp_generate_sdes(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4900 struct ast_rtp_rtcp_report *rtcp_report)
4901{
4902 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4903 int len = 0;
4904 uint16_t sdes_packet_len_bytes;
4905 uint16_t sdes_packet_len_rounded;
4906
4907 if (!rtp || !rtp->rtcp) {
4908 return 0;
4909 }
4910
4911 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4912 return 0;
4913 }
4914
4915 if (!rtcp_report) {
4916 return -1;
4917 }
4918
4919 sdes_packet_len_bytes =
4920 4 + /* RTCP Header */
4921 4 + /* SSRC */
4922 1 + /* Type (CNAME) */
4923 1 + /* Text Length */
4924 AST_UUID_STR_LEN /* Text and NULL terminator */
4925 ;
4926
4927 /* Round to 32 bit boundary */
4928 sdes_packet_len_rounded = (sdes_packet_len_bytes + 3) & ~0x3;
4929
4930 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | ((sdes_packet_len_rounded / 4) - 1)));
4931 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc));
4932 rtcpheader[8] = 0x01; /* CNAME */
4933 rtcpheader[9] = AST_UUID_STR_LEN - 1; /* Number of bytes of text */
4934 memcpy(rtcpheader + 10, rtp->cname, AST_UUID_STR_LEN);
4935 len += 10 + AST_UUID_STR_LEN;
4936
4937 /* Padding - Note t