Asterisk - The Open Source Telephony Project  GIT-master-a24979a
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"
41 #include "asterisk/dns_internal.h"
42 #include "asterisk/dns_recurring.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 #define OPENSSL_SUPPRESS_DEPRECATED 1
51 #include <openssl/opensslconf.h>
52 #include <openssl/opensslv.h>
53 #if !defined(OPENSSL_NO_SRTP) && (OPENSSL_VERSION_NUMBER >= 0x10001000L)
54 #include <openssl/ssl.h>
55 #include <openssl/err.h>
56 #include <openssl/bio.h>
57 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
58 #include <openssl/bn.h>
59 #endif
60 #ifndef OPENSSL_NO_DH
61 #include <openssl/dh.h>
62 #endif
63 #endif
64 #endif
65 
66 #ifdef HAVE_PJPROJECT
67 #include <pjlib.h>
68 #include <pjlib-util.h>
69 #include <pjnath.h>
70 #include <ifaddrs.h>
71 #endif
72 
73 #include "asterisk/conversions.h"
74 #include "asterisk/options.h"
76 #include "asterisk/stun.h"
77 #include "asterisk/pbx.h"
78 #include "asterisk/frame.h"
79 #include "asterisk/format_cache.h"
80 #include "asterisk/channel.h"
81 #include "asterisk/acl.h"
82 #include "asterisk/config.h"
83 #include "asterisk/lock.h"
84 #include "asterisk/utils.h"
85 #include "asterisk/cli.h"
86 #include "asterisk/manager.h"
87 #include "asterisk/unaligned.h"
88 #include "asterisk/module.h"
89 #include "asterisk/rtp_engine.h"
90 #include "asterisk/smoother.h"
91 #include "asterisk/uuid.h"
92 #include "asterisk/test.h"
93 #include "asterisk/data_buffer.h"
94 #ifdef HAVE_PJPROJECT
95 #include "asterisk/res_pjproject.h"
97 #endif
98 
99 #define MAX_TIMESTAMP_SKEW 640
100 
101 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
102 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
103 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
104 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
105 
106 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
107 #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
108 
109 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
110 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
111 
112 #define DEFAULT_TURN_PORT 3478
113 
114 #define TURN_STATE_WAIT_TIME 2000
115 
116 #define DEFAULT_RTP_SEND_BUFFER_SIZE 250 /*!< The initial size of the RTP send buffer */
117 #define MAXIMUM_RTP_SEND_BUFFER_SIZE (DEFAULT_RTP_SEND_BUFFER_SIZE + 200) /*!< Maximum RTP send buffer size */
118 #define DEFAULT_RTP_RECV_BUFFER_SIZE 20 /*!< The initial size of the RTP receiver buffer */
119 #define MAXIMUM_RTP_RECV_BUFFER_SIZE (DEFAULT_RTP_RECV_BUFFER_SIZE + 20) /*!< Maximum RTP receive buffer size */
120 #define OLD_PACKET_COUNT 1000 /*!< The number of previous packets that are considered old */
121 #define MISSING_SEQNOS_ADDED_TRIGGER 2 /*!< The number of immediate missing packets that will trigger an immediate NACK */
122 
123 #define SEQNO_CYCLE_OVER 65536 /*!< The number after the maximum allowed sequence number */
124 
125 /*! Full INTRA-frame Request / Fast Update Request (From RFC2032) */
126 #define RTCP_PT_FUR 192
127 /*! Sender Report (From RFC3550) */
128 #define RTCP_PT_SR AST_RTP_RTCP_SR
129 /*! Receiver Report (From RFC3550) */
130 #define RTCP_PT_RR AST_RTP_RTCP_RR
131 /*! Source Description (From RFC3550) */
132 #define RTCP_PT_SDES 202
133 /*! Goodbye (To remove SSRC's from tables) (From RFC3550) */
134 #define RTCP_PT_BYE 203
135 /*! Application defined (From RFC3550) */
136 #define RTCP_PT_APP 204
137 /* VP8: RTCP Feedback */
138 /*! Payload Specific Feed Back (From RFC4585 also RFC5104) */
139 #define RTCP_PT_PSFB AST_RTP_RTCP_PSFB
140 
141 #define RTP_MTU 1200
142 #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
143 
144 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
145 
146 #define ZFONE_PROFILE_ID 0x505a
147 
148 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
149 /*!
150  * \brief Calculate the min learning duration in ms.
151  *
152  * \details
153  * The min supported packet size represents 10 ms and we need to account
154  * for some jitter and fast clocks while learning. Some messed up devices
155  * have very bad jitter for a small packet sample size. Jitter can also
156  * be introduced by the network itself.
157  *
158  * So we'll allow packets to come in every 9ms on average for fast clocking
159  * with the last one coming in 5ms early for jitter.
160  */
161 #define CALC_LEARNING_MIN_DURATION(count) (((count) - 1) * 9 - 5)
162 #define DEFAULT_LEARNING_MIN_DURATION CALC_LEARNING_MIN_DURATION(DEFAULT_LEARNING_MIN_SEQUENTIAL)
163 
164 #define SRTP_MASTER_KEY_LEN 16
165 #define SRTP_MASTER_SALT_LEN 14
166 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
167 
168 #define RTP_DTLS_ESTABLISHED -37
169 
171  STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
172  STRICT_RTP_LEARN, /*! Accept next packet as source */
173  STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
174 };
175 
177  STRICT_RTP_NO = 0, /*! Don't adhere to any strict RTP rules */
178  STRICT_RTP_YES, /*! Strict RTP that restricts packets based on time and sequence number */
179  STRICT_RTP_SEQNO, /*! Strict RTP that restricts packets based on sequence number */
180 };
181 
182 /*!
183  * \brief Strict RTP learning timeout time in milliseconds
184  *
185  * \note Set to 5 seconds to allow reinvite chains for direct media
186  * to settle before media actually starts to arrive. There may be a
187  * reinvite collision involved on the other leg.
188  */
189 #define STRICT_RTP_LEARN_TIMEOUT 5000
190 
191 #define DEFAULT_STRICT_RTP STRICT_RTP_YES /*!< Enabled by default */
192 #define DEFAULT_SRTP_REPLAY_PROTECTION 1
193 #define DEFAULT_ICESUPPORT 1
194 #define DEFAULT_STUN_SOFTWARE_ATTRIBUTE 1
195 #define DEFAULT_DTLS_MTU 1200
196 
197 extern struct ast_srtp_res *res_srtp;
198 extern struct ast_srtp_policy_res *res_srtp_policy;
199 
201 
202 static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
203 static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
204 static int rtcpstats; /*!< Are we debugging RTCP? */
205 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
206 static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
207 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
208 static int rtpdebugport; /*!< Debug only RTP packets from IP or IP+Port if port is > 0 */
209 static int rtcpdebugport; /*!< Debug only RTCP packets from IP or IP+Port if port is > 0 */
210 #ifdef SO_NO_CHECK
211 static int nochecksums;
212 #endif
213 static 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. */
214 static 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. */
215 static int learning_min_duration = DEFAULT_LEARNING_MIN_DURATION; /*!< Lowest acceptable timeout between the first and the last sequential RTP frame. */
217 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
218 static int dtls_mtu = DEFAULT_DTLS_MTU;
219 #endif
220 #ifdef HAVE_PJPROJECT
221 static int icesupport = DEFAULT_ICESUPPORT;
222 static int stun_software_attribute = DEFAULT_STUN_SOFTWARE_ATTRIBUTE;
223 static struct sockaddr_in stunaddr;
224 static pj_str_t turnaddr;
225 static int turnport = DEFAULT_TURN_PORT;
226 static pj_str_t turnusername;
227 static pj_str_t turnpassword;
228 static struct stasis_subscription *acl_change_sub = NULL;
229 static struct ast_sockaddr lo6 = { .len = 0 };
230 
231 /*! ACL for ICE addresses */
232 static struct ast_acl_list *ice_acl = NULL;
233 static ast_rwlock_t ice_acl_lock = AST_RWLOCK_INIT_VALUE;
234 
235 /*! ACL for STUN requests */
236 static struct ast_acl_list *stun_acl = NULL;
237 static ast_rwlock_t stun_acl_lock = AST_RWLOCK_INIT_VALUE;
238 
239 /*! stunaddr recurring resolution */
240 static ast_rwlock_t stunaddr_lock = AST_RWLOCK_INIT_VALUE;
241 static struct ast_dns_query_recurring *stunaddr_resolver = NULL;
242 
243 /*! \brief Pool factory used by pjlib to allocate memory. */
244 static pj_caching_pool cachingpool;
245 
246 /*! \brief Global memory pool for configuration and timers */
247 static pj_pool_t *pool;
248 
249 /*! \brief Global timer heap */
250 static pj_timer_heap_t *timer_heap;
251 
252 /*! \brief Thread executing the timer heap */
253 static pj_thread_t *timer_thread;
254 
255 /*! \brief Used to tell the timer thread to terminate */
256 static int timer_terminate;
257 
258 /*! \brief Structure which contains ioqueue thread information */
259 struct ast_rtp_ioqueue_thread {
260  /*! \brief Pool used by the thread */
261  pj_pool_t *pool;
262  /*! \brief The thread handling the queue and timer heap */
263  pj_thread_t *thread;
264  /*! \brief Ioqueue which polls on sockets */
265  pj_ioqueue_t *ioqueue;
266  /*! \brief Timer heap for scheduled items */
267  pj_timer_heap_t *timerheap;
268  /*! \brief Termination request */
269  int terminate;
270  /*! \brief Current number of descriptors being waited on */
271  unsigned int count;
272  /*! \brief Linked list information */
273  AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
274 };
275 
276 /*! \brief List of ioqueue threads */
277 static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
278 
279 /*! \brief Structure which contains ICE host candidate mapping information */
280 struct ast_ice_host_candidate {
281  struct ast_sockaddr local;
282  struct ast_sockaddr advertised;
283  unsigned int include_local;
284  AST_RWLIST_ENTRY(ast_ice_host_candidate) next;
285 };
286 
287 /*! \brief List of ICE host candidate mappings */
288 static AST_RWLIST_HEAD_STATIC(host_candidates, ast_ice_host_candidate);
289 
290 static char *generate_random_string(char *buf, size_t size);
291 
292 #endif
293 
294 #define FLAG_3389_WARNING (1 << 0)
295 #define FLAG_NAT_ACTIVE (3 << 1)
296 #define FLAG_NAT_INACTIVE (0 << 1)
297 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
298 #define FLAG_NEED_MARKER_BIT (1 << 3)
299 #define FLAG_DTMF_COMPENSATE (1 << 4)
300 #define FLAG_REQ_LOCAL_BRIDGE_BIT (1 << 5)
301 
302 #define TRANSPORT_SOCKET_RTP 0
303 #define TRANSPORT_SOCKET_RTCP 1
304 #define TRANSPORT_TURN_RTP 2
305 #define TRANSPORT_TURN_RTCP 3
306 
307 /*! \brief RTP learning mode tracking information */
309  struct ast_sockaddr proposed_address; /*!< Proposed remote address for strict RTP */
310  struct timeval start; /*!< The time learning mode was started */
311  struct timeval received; /*!< The time of the first received packet */
312  int max_seq; /*!< The highest sequence number received */
313  int packets; /*!< The number of remaining packets before the source is accepted */
314  /*! Type of media stream carried by the RTP instance */
316 };
317 
318 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
319 struct dtls_details {
320  SSL *ssl; /*!< SSL session */
321  BIO *read_bio; /*!< Memory buffer for reading */
322  BIO *write_bio; /*!< Memory buffer for writing */
323  enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
324  enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
325  int timeout_timer; /*!< Scheduler id for timeout timer */
326 };
327 #endif
328 
329 #ifdef HAVE_PJPROJECT
330 /*! An ao2 wrapper protecting the PJPROJECT ice structure with ref counting. */
331 struct ice_wrap {
332  pj_ice_sess *real_ice; /*!< ICE session */
333 };
334 #endif
335 
336 /*! \brief Structure used for mapping an incoming SSRC to an RTP instance */
338  /*! \brief The received SSRC */
339  unsigned int ssrc;
340  /*! True if the SSRC is available. Otherwise, this is a placeholder mapping until the SSRC is set. */
341  unsigned int ssrc_valid;
342  /*! \brief The RTP instance this SSRC belongs to*/
344 };
345 
346 /*! \brief Packet statistics (used for transport-cc) */
348  /*! The transport specific sequence number */
349  unsigned int seqno;
350  /*! The time at which the packet was received */
351  struct timeval received;
352  /*! The delta between this packet and the previous */
353  int delta;
354 };
355 
356 /*! \brief Statistics information (used for transport-cc) */
358  /*! A vector of packet statistics */
359  AST_VECTOR(, struct rtp_transport_wide_cc_packet_statistics) packet_statistics; /*!< Packet statistics, used for transport-cc */
360  /*! The last sequence number received */
361  unsigned int last_seqno;
362  /*! The last extended sequence number */
363  unsigned int last_extended_seqno;
364  /*! How many feedback packets have gone out */
365  unsigned int feedback_count;
366  /*! How many cycles have occurred for the sequence numbers */
367  unsigned int cycles;
368  /*! Scheduler id for periodic feedback transmission */
369  int schedid;
370 };
371 
372 typedef struct {
373  unsigned int ts;
374  unsigned char is_set;
375 } optional_ts;
376 
377 /*! \brief RTP session description */
378 struct ast_rtp {
379  int s;
380  /*! \note The f.subclass.format holds a ref. */
381  struct ast_frame f;
382  unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
383  unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
384  unsigned int ssrc_orig; /*!< SSRC used before native bridge activated */
385  unsigned char ssrc_saved; /*!< indicates if ssrc_orig has a value */
386  char cname[AST_UUID_STR_LEN]; /*!< Our local CNAME */
387  unsigned int themssrc; /*!< Their SSRC */
388  unsigned int themssrc_valid; /*!< True if their SSRC is available. */
389  unsigned int lastts;
390  unsigned int lastividtimestamp;
391  unsigned int lastovidtimestamp;
392  unsigned int lastitexttimestamp;
393  unsigned int lastotexttimestamp;
394  int lastrxseqno; /*!< Last received sequence number, from the network */
395  int expectedrxseqno; /*!< Next expected sequence number, from the network */
396  AST_VECTOR(, int) missing_seqno; /*!< A vector of sequence numbers we never received */
397  int expectedseqno; /*!< Next expected sequence number, from the core */
398  unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
399  unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
400  unsigned int rxcount; /*!< How many packets have we received? */
401  unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
402  unsigned int txcount; /*!< How many packets have we sent? */
403  unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
404  unsigned int cycles; /*!< Shifted count of sequence number cycles */
405  double rxjitter; /*!< Interarrival jitter at the moment in seconds to be reported */
406  double rxtransit; /*!< Relative transit time for previous packet */
409 
410  /* DTMF Reception Variables */
411  char resp; /*!< The current digit being processed */
412  unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
413  optional_ts last_end_timestamp; /*!< The last known timestamp received from an END packet */
414  unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
415  unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
416  unsigned int dtmfsamples;
417  enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
418  /* DTMF Transmission Variables */
419  unsigned int lastdigitts;
420  char sending_digit; /*!< boolean - are we sending digits */
421  char send_digit; /*!< digit we are sending */
424  unsigned int flags;
425  struct timeval rxcore;
426  struct timeval txcore;
427  double drxcore; /*!< The double representation of the first received packet */
428  struct timeval dtmfmute;
430  unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
432  struct ast_rtcp *rtcp;
433  unsigned int asymmetric_codec; /*!< Indicate if asymmetric send/receive codecs are allowed */
434 
435  struct ast_rtp_instance *bundled; /*!< The RTP instance we are bundled to */
436  int stream_num; /*!< Stream num for this RTP instance */
437  AST_VECTOR(, struct rtp_ssrc_mapping) ssrc_mapping; /*!< Mappings of SSRC to RTP instances */
438  struct ast_sockaddr bind_address; /*!< Requested bind address for the sockets */
439 
440  enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
441  struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
442 
443  /*
444  * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
445  * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
446  */
447  struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
448 
449  struct rtp_red *red;
450 
451  struct ast_data_buffer *send_buffer; /*!< Buffer for storing sent packets for retransmission */
452  struct ast_data_buffer *recv_buffer; /*!< Buffer for storing received packets for retransmission */
453 
454  struct rtp_transport_wide_cc_statistics transport_wide_cc; /*!< Transport-cc statistics information */
455 
456 #ifdef HAVE_PJPROJECT
457  ast_cond_t cond; /*!< ICE/TURN condition for signaling */
458 
459  struct ice_wrap *ice; /*!< ao2 wrapped ICE session */
460  enum ast_rtp_ice_role role; /*!< Our role in ICE negotiation */
461  pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
462  pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
463  pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
464  unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
465  unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
466  unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
467  unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
468  struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
469  struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
470 
471  struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
472 
473  char remote_ufrag[256]; /*!< The remote ICE username */
474  char remote_passwd[256]; /*!< The remote ICE password */
475 
476  char local_ufrag[256]; /*!< The local ICE username */
477  char local_passwd[256]; /*!< The local ICE password */
478 
479  struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
480  struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
481  struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
482  struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
483  unsigned int ice_num_components; /*!< The number of ICE components */
484  unsigned int ice_media_started:1; /*!< ICE media has started, either on a valid pair or on ICE completion */
485 #endif
486 
487 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
488  SSL_CTX *ssl_ctx; /*!< SSL context */
489  enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
490  enum ast_srtp_suite suite; /*!< SRTP crypto suite */
491  enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
492  char local_fingerprint[160]; /*!< Fingerprint of our certificate */
493  enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
494  unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
495  unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
496  int rekeyid; /*!< Scheduled item id for rekeying */
497  struct dtls_details dtls; /*!< DTLS state information */
498 #endif
499 };
500 
501 /*!
502  * \brief Structure defining an RTCP session.
503  *
504  * The concept "RTCP session" is not defined in RFC 3550, but since
505  * this structure is analogous to ast_rtp, which tracks a RTP session,
506  * it is logical to think of this as a RTCP session.
507  *
508  * RTCP packet is defined on page 9 of RFC 3550.
509  *
510  */
511 struct ast_rtcp {
513  int s; /*!< Socket */
514  struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
515  struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
516  unsigned int soc; /*!< What they told us */
517  unsigned int spc; /*!< What they told us */
518  unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
519  struct timeval rxlsr; /*!< Time when we got their last SR */
520  struct timeval txlsr; /*!< Time when we sent or last SR*/
521  unsigned int expected_prior; /*!< no. packets in previous interval */
522  unsigned int received_prior; /*!< no. packets received in previous interval */
523  int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
524  unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
525  unsigned int sr_count; /*!< number of SRs we've sent */
526  unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
527  double accumulated_transit; /*!< accumulated a-dlsr-lsr */
528  double rtt; /*!< Last reported rtt */
529  unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
530  unsigned int reported_lost; /*!< Reported lost packets in their RR */
531 
532  double reported_maxjitter; /*!< Maximum reported interarrival jitter */
533  double reported_minjitter; /*!< Minimum reported interarrival jitter */
534  double reported_normdev_jitter; /*!< Mean of reported interarrival jitter */
535  double reported_stdev_jitter; /*!< Standard deviation of reported interarrival jitter */
536  unsigned int reported_jitter_count; /*!< Reported interarrival jitter count */
537 
538  double reported_maxlost; /*!< Maximum reported packets lost */
539  double reported_minlost; /*!< Minimum reported packets lost */
540  double reported_normdev_lost; /*!< Mean of reported packets lost */
541  double reported_stdev_lost; /*!< Standard deviation of reported packets lost */
542  unsigned int reported_lost_count; /*!< Reported packets lost count */
543 
544  double rxlost; /*!< Calculated number of lost packets since last report */
545  double maxrxlost; /*!< Maximum calculated lost number of packets between reports */
546  double minrxlost; /*!< Minimum calculated lost number of packets between reports */
547  double normdev_rxlost; /*!< Mean of calculated lost packets between reports */
548  double stdev_rxlost; /*!< Standard deviation of calculated lost packets between reports */
549  unsigned int rxlost_count; /*!< Calculated lost packets sample count */
550 
551  double maxrxjitter; /*!< Maximum of calculated interarrival jitter */
552  double minrxjitter; /*!< Minimum of calculated interarrival jitter */
553  double normdev_rxjitter; /*!< Mean of calculated interarrival jitter */
554  double stdev_rxjitter; /*!< Standard deviation of calculated interarrival jitter */
555  unsigned int rxjitter_count; /*!< Calculated interarrival jitter count */
556 
557  double maxrtt; /*!< Maximum of calculated round trip time */
558  double minrtt; /*!< Minimum of calculated round trip time */
559  double normdevrtt; /*!< Mean of calculated round trip time */
560  double stdevrtt; /*!< Standard deviation of calculated round trip time */
561  unsigned int rtt_count; /*!< Calculated round trip time count */
562 
563  /* VP8: sequence number for the RTCP FIR FCI */
564  int firseq;
565 
566 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
567  struct dtls_details dtls; /*!< DTLS state information */
568 #endif
569 
570  /* Cached local address string allows us to generate
571  * RTCP stasis messages without having to look up our
572  * own address every time
573  */
576  /* Buffer for frames created during RTCP interpretation */
577  unsigned char frame_buf[512 + AST_FRIENDLY_OFFSET];
578 };
579 
580 struct rtp_red {
581  struct ast_frame t140; /*!< Primary data */
582  struct ast_frame t140red; /*!< Redundant t140*/
583  unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
584  unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
585  unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
586  int num_gen; /*!< Number of generations */
587  int schedid; /*!< Timer id */
588  int ti; /*!< How long to buffer data before send */
589  unsigned char t140red_data[64000];
590  unsigned char buf_data[64000]; /*!< buffered primary data */
591  int hdrlen;
592  long int prev_ts;
593 };
594 
595 /*! \brief Structure for storing RTP packets for retransmission */
597  size_t size; /*!< The size of the payload */
598  unsigned char buf[0]; /*!< The payload data */
599 };
600 
602 
603 /* Forward Declarations */
604 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
605 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
606 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
607 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
608 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
609 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
610 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
611 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
612 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
613 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
614 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
615 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
616 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
617 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
618 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
619 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
620 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
621 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
622 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
623 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
624 static void ast_rtp_stop(struct ast_rtp_instance *instance);
625 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
626 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
627 static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance);
628 static const char *ast_rtp_get_cname(struct ast_rtp_instance *instance);
629 static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc);
630 static void ast_rtp_set_stream_num(struct ast_rtp_instance *instance, int stream_num);
631 static int ast_rtp_extension_enable(struct ast_rtp_instance *instance, enum ast_rtp_extension extension);
632 static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent);
633 
634 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
635 static int ast_rtp_activate(struct ast_rtp_instance *instance);
636 static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
637 static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
638 static int dtls_bio_write(BIO *bio, const char *buf, int len);
639 static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2);
640 static int dtls_bio_new(BIO *bio);
641 static int dtls_bio_free(BIO *bio);
642 
643 #ifndef HAVE_OPENSSL_BIO_METHOD
644 static BIO_METHOD dtls_bio_methods = {
645  .type = BIO_TYPE_BIO,
646  .name = "rtp write",
647  .bwrite = dtls_bio_write,
648  .ctrl = dtls_bio_ctrl,
649  .create = dtls_bio_new,
650  .destroy = dtls_bio_free,
651 };
652 #else
653 static BIO_METHOD *dtls_bio_methods;
654 #endif
655 #endif
656 
657 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp);
658 
659 #ifdef HAVE_PJPROJECT
660 static void stunaddr_resolve_callback(const struct ast_dns_query *query);
661 static int store_stunaddr_resolved(const struct ast_dns_query *query);
662 #endif
663 
664 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
665 static int dtls_bio_new(BIO *bio)
666 {
667 #ifdef HAVE_OPENSSL_BIO_METHOD
668  BIO_set_init(bio, 1);
669  BIO_set_data(bio, NULL);
670  BIO_set_shutdown(bio, 0);
671 #else
672  bio->init = 1;
673  bio->ptr = NULL;
674  bio->flags = 0;
675 #endif
676  return 1;
677 }
678 
679 static int dtls_bio_free(BIO *bio)
680 {
681  /* The pointer on the BIO is that of the RTP instance. It is not reference counted as the BIO
682  * lifetime is tied to the instance, and actions on the BIO are taken by the thread handling
683  * the RTP instance - not another thread.
684  */
685 #ifdef HAVE_OPENSSL_BIO_METHOD
686  BIO_set_data(bio, NULL);
687 #else
688  bio->ptr = NULL;
689 #endif
690  return 1;
691 }
692 
693 static int dtls_bio_write(BIO *bio, const char *buf, int len)
694 {
695 #ifdef HAVE_OPENSSL_BIO_METHOD
696  struct ast_rtp_instance *instance = BIO_get_data(bio);
697 #else
698  struct ast_rtp_instance *instance = bio->ptr;
699 #endif
700  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
701  int rtcp = 0;
702  struct ast_sockaddr remote_address = { {0, } };
703  int ice;
704  int bytes_sent;
705 
706  /* OpenSSL can't tolerate a packet not being sent, so we always state that
707  * we sent the packet. If it isn't then retransmission will occur.
708  */
709 
710  if (rtp->rtcp && rtp->rtcp->dtls.write_bio == bio) {
711  rtcp = 1;
712  ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
713  } else {
714  ast_rtp_instance_get_remote_address(instance, &remote_address);
715  }
716 
717  if (ast_sockaddr_isnull(&remote_address)) {
718  return len;
719  }
720 
721  bytes_sent = __rtp_sendto(instance, (char *)buf, len, 0, &remote_address, rtcp, &ice, 0);
722 
723  if (bytes_sent > 0 && ast_debug_dtls_packet_is_allowed) {
724  ast_debug(0, "(%p) DTLS - sent %s packet to %s%s (len %-6.6d)\n",
725  instance, rtcp ? "RTCP" : "RTP", ast_sockaddr_stringify(&remote_address),
726  ice ? " (via ICE)" : "", bytes_sent);
727  }
728 
729  return len;
730 }
731 
732 static long dtls_bio_ctrl(BIO *bio, int cmd, long arg1, void *arg2)
733 {
734  switch (cmd) {
735  case BIO_CTRL_FLUSH:
736  return 1;
737  case BIO_CTRL_DGRAM_QUERY_MTU:
738  return dtls_mtu;
739  case BIO_CTRL_WPENDING:
740  case BIO_CTRL_PENDING:
741  return 0L;
742  default:
743  return 0;
744  }
745 }
746 
747 #endif
748 
749 #ifdef HAVE_PJPROJECT
750 /*! \brief Helper function which clears the ICE host candidate mapping */
751 static void host_candidate_overrides_clear(void)
752 {
753  struct ast_ice_host_candidate *candidate;
754 
755  AST_RWLIST_WRLOCK(&host_candidates);
756  AST_RWLIST_TRAVERSE_SAFE_BEGIN(&host_candidates, candidate, next) {
758  ast_free(candidate);
759  }
761  AST_RWLIST_UNLOCK(&host_candidates);
762 }
763 
764 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
765 static void update_address_with_ice_candidate(pj_ice_sess *ice, enum ast_rtp_ice_component_type component,
766  struct ast_sockaddr *cand_address)
767 {
768  char address[PJ_INET6_ADDRSTRLEN];
769 
770  if (component < 1 || !ice->comp[component - 1].valid_check) {
771  return;
772  }
773 
774  ast_sockaddr_parse(cand_address,
775  pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr, address,
776  sizeof(address), 0), 0);
777  ast_sockaddr_set_port(cand_address,
778  pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
779 }
780 
781 /*! \brief Destructor for locally created ICE candidates */
782 static void ast_rtp_ice_candidate_destroy(void *obj)
783 {
784  struct ast_rtp_engine_ice_candidate *candidate = obj;
785 
786  if (candidate->foundation) {
787  ast_free(candidate->foundation);
788  }
789 
790  if (candidate->transport) {
791  ast_free(candidate->transport);
792  }
793 }
794 
795 /*! \pre instance is locked */
796 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
797 {
798  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
799  int ice_attrb_reset = 0;
800 
801  if (!ast_strlen_zero(ufrag)) {
802  if (!ast_strlen_zero(rtp->remote_ufrag) && strcmp(ufrag, rtp->remote_ufrag)) {
803  ice_attrb_reset = 1;
804  }
805  ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
806  }
807 
808  if (!ast_strlen_zero(password)) {
809  if (!ast_strlen_zero(rtp->remote_passwd) && strcmp(password, rtp->remote_passwd)) {
810  ice_attrb_reset = 1;
811  }
812  ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
813  }
814 
815  /* If the remote ufrag or passwd changed, local ufrag and passwd need to regenerate */
816  if (ice_attrb_reset) {
817  generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
818  generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
819  }
820 }
821 
822 static int ice_candidate_cmp(void *obj, void *arg, int flags)
823 {
824  struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
825 
826  if (strcmp(candidate1->foundation, candidate2->foundation) ||
827  candidate1->id != candidate2->id ||
828  candidate1->type != candidate2->type ||
829  ast_sockaddr_cmp(&candidate1->address, &candidate2->address)) {
830  return 0;
831  }
832 
833  return CMP_MATCH | CMP_STOP;
834 }
835 
836 /*! \pre instance is locked */
837 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
838 {
839  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
840  struct ast_rtp_engine_ice_candidate *remote_candidate;
841 
842  /* ICE sessions only support UDP candidates */
843  if (strcasecmp(candidate->transport, "udp")) {
844  return;
845  }
846 
847  if (!rtp->ice_proposed_remote_candidates) {
848  rtp->ice_proposed_remote_candidates = ao2_container_alloc_list(
849  AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, ice_candidate_cmp);
850  if (!rtp->ice_proposed_remote_candidates) {
851  return;
852  }
853  }
854 
855  /* If this is going to exceed the maximum number of ICE candidates don't even add it */
856  if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
857  return;
858  }
859 
860  if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
861  return;
862  }
863 
864  remote_candidate->foundation = ast_strdup(candidate->foundation);
865  remote_candidate->id = candidate->id;
866  remote_candidate->transport = ast_strdup(candidate->transport);
867  remote_candidate->priority = candidate->priority;
868  ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
869  ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
870  remote_candidate->type = candidate->type;
871 
872  ast_debug_ice(2, "(%p) ICE add remote candidate\n", instance);
873 
874  ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
875  ao2_ref(remote_candidate, -1);
876 }
877 
879 
880 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
881 static void pj_thread_register_check(void)
882 {
883  pj_thread_desc *desc;
884  pj_thread_t *thread;
885 
886  if (pj_thread_is_registered() == PJ_TRUE) {
887  return;
888  }
889 
890  desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
891  if (!desc) {
892  ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
893  return;
894  }
895  pj_bzero(*desc, sizeof(*desc));
896 
897  if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
898  ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
899  }
900  return;
901 }
902 
903 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
904  int port, int replace);
905 
906 /*! \pre instance is locked */
907 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
908 {
909  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
910  struct ice_wrap *ice;
911 
912  ice = rtp->ice;
913  rtp->ice = NULL;
914  if (ice) {
915  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
916  ao2_unlock(instance);
917  ao2_ref(ice, -1);
918  ao2_lock(instance);
919  ast_debug_ice(2, "(%p) ICE stopped\n", instance);
920  }
921 }
922 
923 /*!
924  * \brief ao2 ICE wrapper object destructor.
925  *
926  * \param vdoomed Object being destroyed.
927  *
928  * \note The associated struct ast_rtp_instance object must not
929  * be locked when unreffing the object. Otherwise we could
930  * deadlock trying to destroy the PJPROJECT ICE structure.
931  */
932 static void ice_wrap_dtor(void *vdoomed)
933 {
934  struct ice_wrap *ice = vdoomed;
935 
936  if (ice->real_ice) {
937  pj_thread_register_check();
938 
939  pj_ice_sess_destroy(ice->real_ice);
940  }
941 }
942 
943 static void ast2pj_rtp_ice_role(enum ast_rtp_ice_role ast_role, enum pj_ice_sess_role *pj_role)
944 {
945  switch (ast_role) {
947  *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
948  break;
950  *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
951  break;
952  }
953 }
954 
955 static void pj2ast_rtp_ice_role(enum pj_ice_sess_role pj_role, enum ast_rtp_ice_role *ast_role)
956 {
957  switch (pj_role) {
958  case PJ_ICE_SESS_ROLE_CONTROLLED:
959  *ast_role = AST_RTP_ICE_ROLE_CONTROLLED;
960  return;
961  case PJ_ICE_SESS_ROLE_CONTROLLING:
962  *ast_role = AST_RTP_ICE_ROLE_CONTROLLING;
963  return;
964  case PJ_ICE_SESS_ROLE_UNKNOWN:
965  /* Don't change anything */
966  return;
967  default:
968  /* If we aren't explicitly handling something, it's a bug */
969  ast_assert(0);
970  return;
971  }
972 }
973 
974 /*! \pre instance is locked */
975 static int ice_reset_session(struct ast_rtp_instance *instance)
976 {
977  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
978  int res;
979 
980  ast_debug_ice(3, "(%p) ICE resetting\n", instance);
981  if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
982  ast_debug_ice(3, " (%p) ICE nevermind, not ready for a reset\n", instance);
983  return 0;
984  }
985 
986  ast_debug_ice(3, "(%p) ICE recreating ICE session %s (%d)\n",
987  instance, ast_sockaddr_stringify(&rtp->ice_original_rtp_addr), rtp->ice_port);
988  res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
989  if (!res) {
990  /* Use the current expected role for the ICE session */
991  enum pj_ice_sess_role role = PJ_ICE_SESS_ROLE_UNKNOWN;
992  ast2pj_rtp_ice_role(rtp->role, &role);
993  pj_ice_sess_change_role(rtp->ice->real_ice, role);
994  }
995 
996  /* If we only have one component now, and we previously set up TURN for RTCP,
997  * we need to destroy that TURN socket.
998  */
999  if (rtp->ice_num_components == 1 && rtp->turn_rtcp) {
1000  struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1001  struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1002 
1003  rtp->turn_state = PJ_TURN_STATE_NULL;
1004 
1005  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1006  ao2_unlock(instance);
1007  pj_turn_sock_destroy(rtp->turn_rtcp);
1008  ao2_lock(instance);
1009  while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1010  ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1011  }
1012  }
1013 
1014  rtp->ice_media_started = 0;
1015 
1016  return res;
1017 }
1018 
1019 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
1020 {
1021  struct ao2_iterator i;
1022  struct ast_rtp_engine_ice_candidate *right_candidate;
1023 
1024  if (ao2_container_count(left) != ao2_container_count(right)) {
1025  return -1;
1026  }
1027 
1028  i = ao2_iterator_init(right, 0);
1029  while ((right_candidate = ao2_iterator_next(&i))) {
1030  struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
1031 
1032  if (!left_candidate) {
1033  ao2_ref(right_candidate, -1);
1035  return -1;
1036  }
1037 
1038  ao2_ref(left_candidate, -1);
1039  ao2_ref(right_candidate, -1);
1040  }
1042 
1043  return 0;
1044 }
1045 
1046 /*! \pre instance is locked */
1047 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
1048 {
1049  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1050  pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
1051  pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
1052  struct ao2_iterator i;
1053  struct ast_rtp_engine_ice_candidate *candidate;
1054  int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
1055 
1056  if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
1057  return;
1058  }
1059 
1060  /* Check for equivalence in the lists */
1061  if (rtp->ice_active_remote_candidates &&
1062  !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
1063  ast_debug_ice(2, "(%p) ICE proposed equals active candidates\n", instance);
1064  ao2_cleanup(rtp->ice_proposed_remote_candidates);
1065  rtp->ice_proposed_remote_candidates = NULL;
1066  /* If this ICE session is being preserved then go back to the role it currently is */
1067  pj2ast_rtp_ice_role(rtp->ice->real_ice->role, &rtp->role);
1068  return;
1069  }
1070 
1071  /* Out with the old, in with the new */
1072  ao2_cleanup(rtp->ice_active_remote_candidates);
1073  rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
1074  rtp->ice_proposed_remote_candidates = NULL;
1075 
1076  ast_debug_ice(2, "(%p) ICE start\n", instance);
1077 
1078  /* Reset the ICE session. Is this going to work? */
1079  if (ice_reset_session(instance)) {
1080  ast_log(LOG_NOTICE, "(%p) ICE failed to create replacement session\n", instance);
1081  return;
1082  }
1083 
1084  pj_thread_register_check();
1085 
1086  i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
1087 
1088  while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
1089  pj_str_t address;
1090 
1091  /* there needs to be at least one rtp and rtcp candidate in the list */
1092  has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
1093  has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
1094 
1095  pj_strdup2(rtp->ice->real_ice->pool, &candidates[cand_cnt].foundation,
1096  candidate->foundation);
1097  candidates[cand_cnt].comp_id = candidate->id;
1098  candidates[cand_cnt].prio = candidate->priority;
1099 
1100  pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
1101 
1102  if (!ast_sockaddr_isnull(&candidate->relay_address)) {
1103  pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
1104  }
1105 
1106  if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
1107  candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
1108  } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
1109  candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
1110  } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
1111  candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
1112  }
1113 
1114  if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
1115  ast_debug_ice(2, "(%p) ICE RTP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1116  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1117  ao2_unlock(instance);
1118  pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
1119  ao2_lock(instance);
1120  } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
1121  ast_debug_ice(2, "(%p) ICE RTCP candidate %s\n", instance, ast_sockaddr_stringify(&candidate->address));
1122  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1123  ao2_unlock(instance);
1124  pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
1125  ao2_lock(instance);
1126  }
1127 
1128  cand_cnt++;
1129  ao2_ref(candidate, -1);
1130  }
1131 
1133 
1134  if (cand_cnt < ao2_container_count(rtp->ice_active_remote_candidates)) {
1135  ast_log(LOG_WARNING, "(%p) ICE lost %d candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP\n",
1136  instance, ao2_container_count(rtp->ice_active_remote_candidates) - cand_cnt);
1137  }
1138 
1139  if (!has_rtp) {
1140  ast_log(LOG_WARNING, "(%p) ICE no RTP candidates; skipping checklist\n", instance);
1141  }
1142 
1143  /* If we're only dealing with one ICE component, then we don't care about the lack of RTCP candidates */
1144  if (!has_rtcp && rtp->ice_num_components > 1) {
1145  ast_log(LOG_WARNING, "(%p) ICE no RTCP candidates; skipping checklist\n", instance);
1146  }
1147 
1148  if (rtp->ice && has_rtp && (has_rtcp || rtp->ice_num_components == 1)) {
1149  pj_status_t res;
1150  char reason[80];
1151  struct ice_wrap *ice;
1152 
1153  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1154  ice = rtp->ice;
1155  ao2_ref(ice, +1);
1156  ao2_unlock(instance);
1157  res = pj_ice_sess_create_check_list(ice->real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
1158  if (res == PJ_SUCCESS) {
1159  ast_debug_ice(2, "(%p) ICE successfully created checklist\n", instance);
1160  ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
1161  pj_ice_sess_start_check(ice->real_ice);
1162  pj_timer_heap_poll(timer_heap, NULL);
1163  ao2_ref(ice, -1);
1164  ao2_lock(instance);
1166  return;
1167  }
1168  ao2_ref(ice, -1);
1169  ao2_lock(instance);
1170 
1171  pj_strerror(res, reason, sizeof(reason));
1172  ast_log(LOG_WARNING, "(%p) ICE failed to create session check list: %s\n", instance, reason);
1173  }
1174 
1175  ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
1176 
1177  /* even though create check list failed don't stop ice as
1178  it might still work */
1179  /* however we do need to reset remote candidates since
1180  this function may be re-entered */
1181  ao2_ref(rtp->ice_active_remote_candidates, -1);
1182  rtp->ice_active_remote_candidates = NULL;
1183  if (rtp->ice) {
1184  rtp->ice->real_ice->rcand_cnt = rtp->ice->real_ice->clist.count = 0;
1185  }
1186 }
1187 
1188 /*! \pre instance is locked */
1189 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
1190 {
1191  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1192 
1193  return rtp->local_ufrag;
1194 }
1195 
1196 /*! \pre instance is locked */
1197 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
1198 {
1199  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1200 
1201  return rtp->local_passwd;
1202 }
1203 
1204 /*! \pre instance is locked */
1205 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
1206 {
1207  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1208 
1209  if (rtp->ice_local_candidates) {
1210  ao2_ref(rtp->ice_local_candidates, +1);
1211  }
1212 
1213  return rtp->ice_local_candidates;
1214 }
1215 
1216 /*! \pre instance is locked */
1217 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
1218 {
1219  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1220 
1221  if (!rtp->ice) {
1222  return;
1223  }
1224 
1225  pj_thread_register_check();
1226 
1227  pj_ice_sess_change_role(rtp->ice->real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
1228 }
1229 
1230 /*! \pre instance is locked */
1231 static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
1232 {
1233  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1234 
1235  if (!rtp->ice) {
1236  ast_debug_ice(3, "(%p) ICE set role failed; no ice instance\n", instance);
1237  return;
1238  }
1239 
1240  rtp->role = role;
1241 
1242  if (!rtp->ice->real_ice->is_nominating && !rtp->ice->real_ice->is_complete) {
1243  pj_thread_register_check();
1244  ast_debug_ice(2, "(%p) ICE set role to %s\n",
1245  instance, role == AST_RTP_ICE_ROLE_CONTROLLED ? "CONTROLLED" : "CONTROLLING");
1246  pj_ice_sess_change_role(rtp->ice->real_ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
1247  PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
1248  } else {
1249  ast_debug_ice(2, "(%p) ICE not setting role because state is %s\n",
1250  instance, rtp->ice->real_ice->is_nominating ? "nominating" : "complete");
1251  }
1252 }
1253 
1254 /*! \pre instance is locked */
1255 static void ast_rtp_ice_add_cand(struct ast_rtp_instance *instance, struct ast_rtp *rtp,
1256  unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
1257  const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr,
1258  int addr_len)
1259 {
1260  pj_str_t foundation;
1261  struct ast_rtp_engine_ice_candidate *candidate, *existing;
1262  struct ice_wrap *ice;
1263  char address[PJ_INET6_ADDRSTRLEN];
1264  pj_status_t status;
1265 
1266  if (!rtp->ice) {
1267  return;
1268  }
1269 
1270  pj_thread_register_check();
1271 
1272  pj_ice_calc_foundation(rtp->ice->real_ice->pool, &foundation, type, addr);
1273 
1274  if (!rtp->ice_local_candidates) {
1275  rtp->ice_local_candidates = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1276  NULL, ice_candidate_cmp);
1277  if (!rtp->ice_local_candidates) {
1278  return;
1279  }
1280  }
1281 
1282  if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
1283  return;
1284  }
1285 
1286  candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
1287  candidate->id = comp_id;
1288  candidate->transport = ast_strdup("UDP");
1289 
1290  ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
1291  ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
1292 
1293  if (rel_addr) {
1294  ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
1295  ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
1296  }
1297 
1298  if (type == PJ_ICE_CAND_TYPE_HOST) {
1300  } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
1302  } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
1304  }
1305 
1306  if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
1307  ao2_ref(existing, -1);
1308  ao2_ref(candidate, -1);
1309  return;
1310  }
1311 
1312  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1313  ice = rtp->ice;
1314  ao2_ref(ice, +1);
1315  ao2_unlock(instance);
1316  status = pj_ice_sess_add_cand(ice->real_ice, comp_id, transport_id, type, local_pref,
1317  &foundation, addr, base_addr, rel_addr, addr_len, NULL);
1318  ao2_ref(ice, -1);
1319  ao2_lock(instance);
1320  if (!rtp->ice || status != PJ_SUCCESS) {
1321  ast_debug_ice(2, "(%p) ICE unable to add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1322  &candidate->address), candidate->priority);
1323  ao2_ref(candidate, -1);
1324  return;
1325  }
1326 
1327  /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
1328  candidate->priority = rtp->ice->real_ice->lcand[rtp->ice->real_ice->lcand_cnt - 1].prio;
1329 
1330  ast_debug_ice(2, "(%p) ICE add candidate: %s, %d\n", instance, ast_sockaddr_stringify(
1331  &candidate->address), candidate->priority);
1332 
1333  ao2_link(rtp->ice_local_candidates, candidate);
1334  ao2_ref(candidate, -1);
1335 }
1336 
1337 /* PJPROJECT TURN callback */
1338 static 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)
1339 {
1340  struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1341  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1342  struct ice_wrap *ice;
1343  pj_status_t status;
1344 
1345  ao2_lock(instance);
1346  ice = ao2_bump(rtp->ice);
1347  ao2_unlock(instance);
1348 
1349  if (ice) {
1350  status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTP,
1351  TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr, addr_len);
1352  ao2_ref(ice, -1);
1353  if (status != PJ_SUCCESS) {
1354  char buf[100];
1355 
1356  pj_strerror(status, buf, sizeof(buf));
1357  ast_log(LOG_WARNING, "(%p) ICE PJ Rx error status code: %d '%s'.\n",
1358  instance, (int)status, buf);
1359  return;
1360  }
1361  if (!rtp->rtp_passthrough) {
1362  return;
1363  }
1364  rtp->rtp_passthrough = 0;
1365  }
1366 
1367  ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
1368 }
1369 
1370 /* PJPROJECT TURN callback */
1371 static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1372 {
1373  struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1374  struct ast_rtp *rtp;
1375 
1376  /* If this is a leftover from an already notified RTP instance just ignore the state change */
1377  if (!instance) {
1378  return;
1379  }
1380 
1381  rtp = ast_rtp_instance_get_data(instance);
1382 
1383  ao2_lock(instance);
1384 
1385  /* We store the new state so the other thread can actually handle it */
1386  rtp->turn_state = new_state;
1387  ast_cond_signal(&rtp->cond);
1388 
1389  if (new_state == PJ_TURN_STATE_DESTROYING) {
1390  pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
1391  rtp->turn_rtp = NULL;
1392  }
1393 
1394  ao2_unlock(instance);
1395 }
1396 
1397 /* RTP TURN Socket interface declaration */
1398 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1399  .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1400  .on_state = ast_rtp_on_turn_rtp_state,
1401 };
1402 
1403 /* PJPROJECT TURN callback */
1404 static 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)
1405 {
1406  struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1407  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1408  struct ice_wrap *ice;
1409  pj_status_t status;
1410 
1411  ao2_lock(instance);
1412  ice = ao2_bump(rtp->ice);
1413  ao2_unlock(instance);
1414 
1415  if (ice) {
1416  status = pj_ice_sess_on_rx_pkt(ice->real_ice, AST_RTP_ICE_COMPONENT_RTCP,
1417  TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr, addr_len);
1418  ao2_ref(ice, -1);
1419  if (status != PJ_SUCCESS) {
1420  char buf[100];
1421 
1422  pj_strerror(status, buf, sizeof(buf));
1423  ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
1424  (int)status, buf);
1425  return;
1426  }
1427  if (!rtp->rtcp_passthrough) {
1428  return;
1429  }
1430  rtp->rtcp_passthrough = 0;
1431  }
1432 
1433  ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
1434 }
1435 
1436 /* PJPROJECT TURN callback */
1437 static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
1438 {
1439  struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1440  struct ast_rtp *rtp;
1441 
1442  /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
1443  if (!instance) {
1444  return;
1445  }
1446 
1447  rtp = ast_rtp_instance_get_data(instance);
1448 
1449  ao2_lock(instance);
1450 
1451  /* We store the new state so the other thread can actually handle it */
1452  rtp->turn_state = new_state;
1453  ast_cond_signal(&rtp->cond);
1454 
1455  if (new_state == PJ_TURN_STATE_DESTROYING) {
1456  pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
1457  rtp->turn_rtcp = NULL;
1458  }
1459 
1460  ao2_unlock(instance);
1461 }
1462 
1463 /* RTCP TURN Socket interface declaration */
1464 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1465  .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1466  .on_state = ast_rtp_on_turn_rtcp_state,
1467 };
1468 
1469 /*! \brief Worker thread for ioqueue and timerheap */
1470 static int ioqueue_worker_thread(void *data)
1471 {
1472  struct ast_rtp_ioqueue_thread *ioqueue = data;
1473 
1474  while (!ioqueue->terminate) {
1475  const pj_time_val delay = {0, 10};
1476 
1477  pj_ioqueue_poll(ioqueue->ioqueue, &delay);
1478 
1479  pj_timer_heap_poll(ioqueue->timerheap, NULL);
1480  }
1481 
1482  return 0;
1483 }
1484 
1485 /*! \brief Destroyer for ioqueue thread */
1486 static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
1487 {
1488  if (ioqueue->thread) {
1489  ioqueue->terminate = 1;
1490  pj_thread_join(ioqueue->thread);
1491  pj_thread_destroy(ioqueue->thread);
1492  }
1493 
1494  if (ioqueue->pool) {
1495  /* This mimics the behavior of pj_pool_safe_release
1496  * which was introduced in pjproject 2.6.
1497  */
1498  pj_pool_t *temp_pool = ioqueue->pool;
1499 
1500  ioqueue->pool = NULL;
1501  pj_pool_release(temp_pool);
1502  }
1503 
1504  ast_free(ioqueue);
1505 }
1506 
1507 /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
1508 static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
1509 {
1510  int destroy = 0;
1511 
1512  /* If nothing is using this ioqueue thread destroy it */
1513  AST_LIST_LOCK(&ioqueues);
1514  if ((ioqueue->count - 2) == 0) {
1515  destroy = 1;
1516  AST_LIST_REMOVE(&ioqueues, ioqueue, next);
1517  }
1518  AST_LIST_UNLOCK(&ioqueues);
1519 
1520  if (!destroy) {
1521  return;
1522  }
1523 
1524  rtp_ioqueue_thread_destroy(ioqueue);
1525 }
1526 
1527 /*! \brief Finder and allocator for an ioqueue thread */
1528 static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
1529 {
1530  struct ast_rtp_ioqueue_thread *ioqueue;
1531  pj_lock_t *lock;
1532 
1533  AST_LIST_LOCK(&ioqueues);
1534 
1535  /* See if an ioqueue thread exists that can handle more */
1536  AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1537  if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1538  break;
1539  }
1540  }
1541 
1542  /* If we found one bump it up and return it */
1543  if (ioqueue) {
1544  ioqueue->count += 2;
1545  goto end;
1546  }
1547 
1548  ioqueue = ast_calloc(1, sizeof(*ioqueue));
1549  if (!ioqueue) {
1550  goto end;
1551  }
1552 
1553  ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1554 
1555  /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1556  * on a session at the same time
1557  */
1558  if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1559  goto fatal;
1560  }
1561 
1562  if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1563  goto fatal;
1564  }
1565 
1566  pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1567 
1568  if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1569  goto fatal;
1570  }
1571 
1572  if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1573  goto fatal;
1574  }
1575 
1576  AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1577 
1578  /* Since this is being returned to an active session the count always starts at 2 */
1579  ioqueue->count = 2;
1580 
1581  goto end;
1582 
1583 fatal:
1584  rtp_ioqueue_thread_destroy(ioqueue);
1585  ioqueue = NULL;
1586 
1587 end:
1588  AST_LIST_UNLOCK(&ioqueues);
1589  return ioqueue;
1590 }
1591 
1592 /*! \pre instance is locked */
1593 static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1594  enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1595 {
1596  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1597  pj_turn_sock **turn_sock;
1598  const pj_turn_sock_cb *turn_cb;
1599  pj_turn_tp_type conn_type;
1600  int conn_transport;
1601  pj_stun_auth_cred cred = { 0, };
1602  pj_str_t turn_addr;
1603  struct ast_sockaddr addr = { { 0, } };
1604  pj_stun_config stun_config;
1605  struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1606  struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1607  pj_turn_session_info info;
1608  struct ast_sockaddr local, loop;
1609  pj_status_t status;
1610  pj_turn_sock_cfg turn_sock_cfg;
1611  struct ice_wrap *ice;
1612 
1613  ast_rtp_instance_get_local_address(instance, &local);
1614  if (ast_sockaddr_is_ipv4(&local)) {
1615  ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1616  } else {
1617  ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
1618  }
1619 
1620  /* Determine what component we are requesting a TURN session for */
1621  if (component == AST_RTP_ICE_COMPONENT_RTP) {
1622  turn_sock = &rtp->turn_rtp;
1623  turn_cb = &ast_rtp_turn_rtp_sock_cb;
1624  conn_transport = TRANSPORT_TURN_RTP;
1625  ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
1626  } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1627  turn_sock = &rtp->turn_rtcp;
1628  turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1629  conn_transport = TRANSPORT_TURN_RTCP;
1631  } else {
1632  return;
1633  }
1634 
1635  if (transport == AST_TRANSPORT_UDP) {
1636  conn_type = PJ_TURN_TP_UDP;
1637  } else if (transport == AST_TRANSPORT_TCP) {
1638  conn_type = PJ_TURN_TP_TCP;
1639  } else {
1640  ast_assert(0);
1641  return;
1642  }
1643 
1644  ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1645 
1646  if (*turn_sock) {
1647  rtp->turn_state = PJ_TURN_STATE_NULL;
1648 
1649  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1650  ao2_unlock(instance);
1651  pj_turn_sock_destroy(*turn_sock);
1652  ao2_lock(instance);
1653  while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1654  ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1655  }
1656  }
1657 
1658  if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1659  /*
1660  * We cannot hold the instance lock because we could wait
1661  * for the ioqueue thread to die and we might deadlock as
1662  * a result.
1663  */
1664  ao2_unlock(instance);
1665  rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1666  ao2_lock(instance);
1667  if (!rtp->ioqueue) {
1668  return;
1669  }
1670  }
1671 
1672  pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1673  if (!stun_software_attribute) {
1674  stun_config.software_name = pj_str(NULL);
1675  }
1676 
1677  /* Use ICE session group lock for TURN session to avoid deadlock */
1678  pj_turn_sock_cfg_default(&turn_sock_cfg);
1679  ice = rtp->ice;
1680  if (ice) {
1681  turn_sock_cfg.grp_lock = ice->real_ice->grp_lock;
1682  ao2_ref(ice, +1);
1683  }
1684 
1685  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
1686  ao2_unlock(instance);
1687  status = pj_turn_sock_create(&stun_config,
1688  ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1689  turn_cb, &turn_sock_cfg, instance, turn_sock);
1690  ao2_cleanup(ice);
1691  if (status != PJ_SUCCESS) {
1692  ast_log(LOG_WARNING, "(%p) Could not create a TURN client socket\n", instance);
1693  ao2_lock(instance);
1694  return;
1695  }
1696 
1697  cred.type = PJ_STUN_AUTH_CRED_STATIC;
1698  pj_strset2(&cred.data.static_cred.username, (char*)username);
1699  cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1700  pj_strset2(&cred.data.static_cred.data, (char*)password);
1701 
1702  pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1703 
1704  ast_debug_ice(2, "(%p) ICE request TURN %s %s candidate\n", instance,
1705  transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
1706  component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
1707 
1708  ao2_lock(instance);
1709 
1710  /*
1711  * Because the TURN socket is asynchronous and we are synchronous we need to
1712  * wait until it is done
1713  */
1714  while (rtp->turn_state < PJ_TURN_STATE_READY) {
1715  ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
1716  }
1717 
1718  /* If a TURN session was allocated add it as a candidate */
1719  if (rtp->turn_state != PJ_TURN_STATE_READY) {
1720  return;
1721  }
1722 
1723  pj_turn_sock_get_info(*turn_sock, &info);
1724 
1725  ast_rtp_ice_add_cand(instance, rtp, component, conn_transport,
1726  PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
1727  &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1728 
1729  if (component == AST_RTP_ICE_COMPONENT_RTP) {
1730  ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1731  } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1732  ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1733  }
1734 }
1735 
1736 static char *generate_random_string(char *buf, size_t size)
1737 {
1738  long val[4];
1739  int x;
1740 
1741  for (x=0; x<4; x++) {
1742  val[x] = ast_random();
1743  }
1744  snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1745 
1746  return buf;
1747 }
1748 
1749 /*! \pre instance is locked */
1750 static void ast_rtp_ice_change_components(struct ast_rtp_instance *instance, int num_components)
1751 {
1752  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1753 
1754  /* Don't do anything if ICE is unsupported or if we're not changing the
1755  * number of components
1756  */
1757  if (!icesupport || !rtp->ice || rtp->ice_num_components == num_components) {
1758  return;
1759  }
1760 
1761  ast_debug_ice(2, "(%p) ICE change number of components %u -> %u\n", instance,
1762  rtp->ice_num_components, num_components);
1763 
1764  rtp->ice_num_components = num_components;
1765  ice_reset_session(instance);
1766 }
1767 
1768 /* ICE RTP Engine interface declaration */
1769 static struct ast_rtp_engine_ice ast_rtp_ice = {
1770  .set_authentication = ast_rtp_ice_set_authentication,
1771  .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1772  .start = ast_rtp_ice_start,
1773  .stop = ast_rtp_ice_stop,
1774  .get_ufrag = ast_rtp_ice_get_ufrag,
1775  .get_password = ast_rtp_ice_get_password,
1776  .get_local_candidates = ast_rtp_ice_get_local_candidates,
1777  .ice_lite = ast_rtp_ice_lite,
1778  .set_role = ast_rtp_ice_set_role,
1779  .turn_request = ast_rtp_ice_turn_request,
1780  .change_components = ast_rtp_ice_change_components,
1781 };
1782 #endif
1783 
1784 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
1785 static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1786 {
1787  /* We don't want to actually verify the certificate so just accept what they have provided */
1788  return 1;
1789 }
1790 
1791 static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1792  enum ast_rtp_dtls_setup setup, struct ast_rtp_instance *instance)
1793 {
1794  dtls->dtls_setup = setup;
1795 
1796  if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1797  ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1798  goto error;
1799  }
1800 
1801  if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1802  ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1803  goto error;
1804  }
1805  BIO_set_mem_eof_return(dtls->read_bio, -1);
1806 
1807 #ifdef HAVE_OPENSSL_BIO_METHOD
1808  if (!(dtls->write_bio = BIO_new(dtls_bio_methods))) {
1809  ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1810  goto error;
1811  }
1812 
1813  BIO_set_data(dtls->write_bio, instance);
1814 #else
1815  if (!(dtls->write_bio = BIO_new(&dtls_bio_methods))) {
1816  ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1817  goto error;
1818  }
1819  dtls->write_bio->ptr = instance;
1820 #endif
1821  SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1822 
1823  if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1824  SSL_set_accept_state(dtls->ssl);
1825  } else {
1826  SSL_set_connect_state(dtls->ssl);
1827  }
1828  dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1829 
1830  return 0;
1831 
1832 error:
1833  if (dtls->read_bio) {
1834  BIO_free(dtls->read_bio);
1835  dtls->read_bio = NULL;
1836  }
1837 
1838  if (dtls->write_bio) {
1839  BIO_free(dtls->write_bio);
1840  dtls->write_bio = NULL;
1841  }
1842 
1843  if (dtls->ssl) {
1844  SSL_free(dtls->ssl);
1845  dtls->ssl = NULL;
1846  }
1847  return -1;
1848 }
1849 
1850 static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1851 {
1852  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1853 
1854  if (!rtp->ssl_ctx || !rtp->rtcp) {
1855  return 0;
1856  }
1857 
1858  ast_debug_dtls(3, "(%p) DTLS RTCP setup\n", instance);
1859  return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup, instance);
1860 }
1861 
1862 static const SSL_METHOD *get_dtls_method(void)
1863 {
1864 #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
1865  return DTLSv1_method();
1866 #else
1867  return DTLS_method();
1868 #endif
1869 }
1870 
1871 struct dtls_cert_info {
1872  EVP_PKEY *private_key;
1873  X509 *certificate;
1874 };
1875 
1876 static void configure_dhparams(const struct ast_rtp *rtp, const struct ast_rtp_dtls_cfg *dtls_cfg)
1877 {
1878 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1879  EC_KEY *ecdh;
1880 #endif
1881 
1882 #ifndef OPENSSL_NO_DH
1883  if (!ast_strlen_zero(dtls_cfg->pvtfile)) {
1884  BIO *bio = BIO_new_file(dtls_cfg->pvtfile, "r");
1885  if (bio) {
1886  DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1887  if (dh) {
1888  if (SSL_CTX_set_tmp_dh(rtp->ssl_ctx, dh)) {
1889  long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
1890  SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
1891  options = SSL_CTX_set_options(rtp->ssl_ctx, options);
1892  ast_verb(2, "DTLS DH initialized, PFS enabled\n");
1893  }
1894  DH_free(dh);
1895  }
1896  BIO_free(bio);
1897  }
1898  }
1899 #endif /* !OPENSSL_NO_DH */
1900 
1901 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1902  /* enables AES-128 ciphers, to get AES-256 use NID_secp384r1 */
1903  ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1904  if (ecdh) {
1905  if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
1906  #ifndef SSL_CTRL_SET_ECDH_AUTO
1907  #define SSL_CTRL_SET_ECDH_AUTO 94
1908  #endif
1909  /* SSL_CTX_set_ecdh_auto(rtp->ssl_ctx, on); requires OpenSSL 1.0.2 which wraps: */
1910  if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
1911  ast_verb(2, "DTLS ECDH initialized (automatic), faster PFS enabled\n");
1912  } else {
1913  ast_verb(2, "DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
1914  }
1915  }
1916  EC_KEY_free(ecdh);
1917  }
1918 #endif /* !OPENSSL_NO_ECDH */
1919 }
1920 
1921 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
1922 
1923 static int create_ephemeral_ec_keypair(EVP_PKEY **keypair)
1924 {
1925  EC_KEY *eckey = NULL;
1926  EC_GROUP *group = NULL;
1927 
1928  group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1929  if (!group) {
1930  goto error;
1931  }
1932 
1933  EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
1934  EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED);
1935 
1936  eckey = EC_KEY_new();
1937  if (!eckey) {
1938  goto error;
1939  }
1940 
1941  if (!EC_KEY_set_group(eckey, group)) {
1942  goto error;
1943  }
1944 
1945  if (!EC_KEY_generate_key(eckey)) {
1946  goto error;
1947  }
1948 
1949  *keypair = EVP_PKEY_new();
1950  if (!*keypair) {
1951  goto error;
1952  }
1953 
1954  EVP_PKEY_assign_EC_KEY(*keypair, eckey);
1955  EC_GROUP_free(group);
1956 
1957  return 0;
1958 
1959 error:
1960  EC_KEY_free(eckey);
1961  EC_GROUP_free(group);
1962 
1963  return -1;
1964 }
1965 
1966 /* From OpenSSL's x509 command */
1967 #define SERIAL_RAND_BITS 159
1968 
1969 static int create_ephemeral_certificate(EVP_PKEY *keypair, X509 **certificate)
1970 {
1971  X509 *cert = NULL;
1972  BIGNUM *serial = NULL;
1973  X509_NAME *name = NULL;
1974 
1975  cert = X509_new();
1976  if (!cert) {
1977  goto error;
1978  }
1979 
1980  if (!X509_set_version(cert, 2)) {
1981  goto error;
1982  }
1983 
1984  /* Set the public key */
1985  X509_set_pubkey(cert, keypair);
1986 
1987  /* Generate a random serial number */
1988  if (!(serial = BN_new())
1989  || !BN_rand(serial, SERIAL_RAND_BITS, -1, 0)
1990  || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) {
1991  goto error;
1992  }
1993 
1994  /*
1995  * Validity period - Current Chrome & Firefox make it 31 days starting
1996  * with yesterday at the current time, so we will do the same.
1997  */
1998 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1999  if (!X509_time_adj_ex(X509_get_notBefore(cert), -1, 0, NULL)
2000  || !X509_time_adj_ex(X509_get_notAfter(cert), 30, 0, NULL)) {
2001  goto error;
2002  }
2003 #else
2004  if (!X509_time_adj_ex(X509_getm_notBefore(cert), -1, 0, NULL)
2005  || !X509_time_adj_ex(X509_getm_notAfter(cert), 30, 0, NULL)) {
2006  goto error;
2007  }
2008 #endif
2009 
2010  /* Set the name and issuer */
2011  if (!(name = X509_get_subject_name(cert))
2012  || !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC,
2013  (unsigned char *) "asterisk", -1, -1, 0)
2014  || !X509_set_issuer_name(cert, name)) {
2015  goto error;
2016  }
2017 
2018  /* Sign it */
2019  if (!X509_sign(cert, keypair, EVP_sha256())) {
2020  goto error;
2021  }
2022 
2023  *certificate = cert;
2024 
2025  return 0;
2026 
2027 error:
2028  BN_free(serial);
2029  X509_free(cert);
2030 
2031  return -1;
2032 }
2033 
2034 static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2035  const struct ast_rtp_dtls_cfg *dtls_cfg,
2036  struct dtls_cert_info *cert_info)
2037 {
2038  /* Make sure these are initialized */
2039  cert_info->private_key = NULL;
2040  cert_info->certificate = NULL;
2041 
2042  if (create_ephemeral_ec_keypair(&cert_info->private_key)) {
2043  ast_log(LOG_ERROR, "Failed to create ephemeral ECDSA keypair\n");
2044  goto error;
2045  }
2046 
2047  if (create_ephemeral_certificate(cert_info->private_key, &cert_info->certificate)) {
2048  ast_log(LOG_ERROR, "Failed to create ephemeral X509 certificate\n");
2049  goto error;
2050  }
2051 
2052  return 0;
2053 
2054  error:
2055  X509_free(cert_info->certificate);
2056  EVP_PKEY_free(cert_info->private_key);
2057 
2058  return -1;
2059 }
2060 
2061 #else
2062 
2063 static int create_certificate_ephemeral(struct ast_rtp_instance *instance,
2064  const struct ast_rtp_dtls_cfg *dtls_cfg,
2065  struct dtls_cert_info *cert_info)
2066 {
2067  ast_log(LOG_ERROR, "Your version of OpenSSL does not support ECDSA keys\n");
2068  return -1;
2069 }
2070 
2071 #endif /* !OPENSSL_NO_ECDH */
2072 
2073 static int create_certificate_from_file(struct ast_rtp_instance *instance,
2074  const struct ast_rtp_dtls_cfg *dtls_cfg,
2075  struct dtls_cert_info *cert_info)
2076 {
2077  FILE *fp;
2078  BIO *certbio = NULL;
2079  EVP_PKEY *private_key = NULL;
2080  X509 *cert = NULL;
2081  char *private_key_file = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
2082 
2083  fp = fopen(private_key_file, "r");
2084  if (!fp) {
2085  ast_log(LOG_ERROR, "Failed to read private key from file '%s': %s\n", private_key_file, strerror(errno));
2086  goto error;
2087  }
2088 
2089  if (!PEM_read_PrivateKey(fp, &private_key, NULL, NULL)) {
2090  ast_log(LOG_ERROR, "Failed to read private key from PEM file '%s'\n", private_key_file);
2091  fclose(fp);
2092  goto error;
2093  }
2094 
2095  if (fclose(fp)) {
2096  ast_log(LOG_ERROR, "Failed to close private key file '%s': %s\n", private_key_file, strerror(errno));
2097  goto error;
2098  }
2099 
2100  certbio = BIO_new(BIO_s_file());
2101  if (!certbio) {
2102  ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
2103  instance);
2104  goto error;
2105  }
2106 
2107  if (!BIO_read_filename(certbio, dtls_cfg->certfile)
2108  || !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
2109  ast_log(LOG_ERROR, "Failed to read certificate from file '%s'\n", dtls_cfg->certfile);
2110  goto error;
2111  }
2112 
2113  cert_info->private_key = private_key;
2114  cert_info->certificate = cert;
2115 
2116  BIO_free_all(certbio);
2117 
2118  return 0;
2119 
2120 error:
2121  X509_free(cert);
2122  BIO_free_all(certbio);
2123  EVP_PKEY_free(private_key);
2124 
2125  return -1;
2126 }
2127 
2128 static int load_dtls_certificate(struct ast_rtp_instance *instance,
2129  const struct ast_rtp_dtls_cfg *dtls_cfg,
2130  struct dtls_cert_info *cert_info)
2131 {
2132  if (dtls_cfg->ephemeral_cert) {
2133  return create_certificate_ephemeral(instance, dtls_cfg, cert_info);
2134  } else if (!ast_strlen_zero(dtls_cfg->certfile)) {
2135  return create_certificate_from_file(instance, dtls_cfg, cert_info);
2136  } else {
2137  return -1;
2138  }
2139 }
2140 
2141 /*! \pre instance is locked */
2142 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
2143 {
2144  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2145  struct dtls_cert_info cert_info = { 0 };
2146  int res;
2147 
2148  if (!dtls_cfg->enabled) {
2149  return 0;
2150  }
2151 
2152  ast_debug_dtls(3, "(%p) DTLS RTP setup\n", instance);
2153 
2155  ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
2156  return -1;
2157  }
2158 
2159  if (rtp->ssl_ctx) {
2160  return 0;
2161  }
2162 
2163  rtp->ssl_ctx = SSL_CTX_new(get_dtls_method());
2164  if (!rtp->ssl_ctx) {
2165  return -1;
2166  }
2167 
2168  SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
2169 
2170  configure_dhparams(rtp, dtls_cfg);
2171 
2172  rtp->dtls_verify = dtls_cfg->verify;
2173 
2174  SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2175  SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
2176  dtls_verify_callback : NULL);
2177 
2178  if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
2179  SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
2180  } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
2181  SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
2182  } else {
2183  ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
2184  return -1;
2185  }
2186 
2187  rtp->local_hash = dtls_cfg->hash;
2188 
2189  if (!load_dtls_certificate(instance, dtls_cfg, &cert_info)) {
2190  const EVP_MD *type;
2191  unsigned int size, i;
2192  unsigned char fingerprint[EVP_MAX_MD_SIZE];
2193  char *local_fingerprint = rtp->local_fingerprint;
2194 
2195  if (!SSL_CTX_use_certificate(rtp->ssl_ctx, cert_info.certificate)) {
2196  ast_log(LOG_ERROR, "Specified certificate for RTP instance '%p' could not be used\n",
2197  instance);
2198  return -1;
2199  }
2200 
2201  if (!SSL_CTX_use_PrivateKey(rtp->ssl_ctx, cert_info.private_key)
2202  || !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
2203  ast_log(LOG_ERROR, "Specified private key for RTP instance '%p' could not be used\n",
2204  instance);
2205  return -1;
2206  }
2207 
2208  if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
2209  type = EVP_sha1();
2210  } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
2211  type = EVP_sha256();
2212  } else {
2213  ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
2214  instance);
2215  return -1;
2216  }
2217 
2218  if (!X509_digest(cert_info.certificate, type, fingerprint, &size) || !size) {
2219  ast_log(LOG_ERROR, "Could not produce fingerprint from certificate for RTP instance '%p'\n",
2220  instance);
2221  return -1;
2222  }
2223 
2224  for (i = 0; i < size; i++) {
2225  sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
2226  local_fingerprint += 3;
2227  }
2228 
2229  *(local_fingerprint - 1) = 0;
2230 
2231  EVP_PKEY_free(cert_info.private_key);
2232  X509_free(cert_info.certificate);
2233  }
2234 
2235  if (!ast_strlen_zero(dtls_cfg->cipher)) {
2236  if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
2237  ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
2238  dtls_cfg->cipher, instance);
2239  return -1;
2240  }
2241  }
2242 
2243  if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
2244  if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
2245  ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
2246  S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
2247  return -1;
2248  }
2249  }
2250 
2251  rtp->rekey = dtls_cfg->rekey;
2252  rtp->suite = dtls_cfg->suite;
2253 
2254  res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup, instance);
2255  if (!res) {
2256  dtls_setup_rtcp(instance);
2257  }
2258 
2259  return res;
2260 }
2261 
2262 /*! \pre instance is locked */
2263 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
2264 {
2265  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2266 
2267  return !rtp->ssl_ctx ? 0 : 1;
2268 }
2269 
2270 /*! \pre instance is locked */
2271 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
2272 {
2273  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2274  SSL *ssl = rtp->dtls.ssl;
2275 
2276  ast_debug_dtls(3, "(%p) DTLS stop\n", instance);
2277  ao2_unlock(instance);
2278  dtls_srtp_stop_timeout_timer(instance, rtp, 0);
2279  ao2_lock(instance);
2280 
2281  if (rtp->ssl_ctx) {
2282  SSL_CTX_free(rtp->ssl_ctx);
2283  rtp->ssl_ctx = NULL;
2284  }
2285 
2286  if (rtp->dtls.ssl) {
2287  SSL_free(rtp->dtls.ssl);
2288  rtp->dtls.ssl = NULL;
2289  }
2290 
2291  if (rtp->rtcp) {
2292  ao2_unlock(instance);
2293  dtls_srtp_stop_timeout_timer(instance, rtp, 1);
2294  ao2_lock(instance);
2295 
2296  if (rtp->rtcp->dtls.ssl) {
2297  if (rtp->rtcp->dtls.ssl != ssl) {
2298  SSL_free(rtp->rtcp->dtls.ssl);
2299  }
2300  rtp->rtcp->dtls.ssl = NULL;
2301  }
2302  }
2303 }
2304 
2305 /*! \pre instance is locked */
2306 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
2307 {
2308  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2309 
2310  if (SSL_is_init_finished(rtp->dtls.ssl)) {
2311  SSL_shutdown(rtp->dtls.ssl);
2312  rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2313  }
2314 
2315  if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
2316  SSL_shutdown(rtp->rtcp->dtls.ssl);
2317  rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
2318  }
2319 }
2320 
2321 /*! \pre instance is locked */
2322 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
2323 {
2324  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2325 
2326  return rtp->dtls.connection;
2327 }
2328 
2329 /*! \pre instance is locked */
2330 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
2331 {
2332  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2333 
2334  return rtp->dtls.dtls_setup;
2335 }
2336 
2337 static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
2338 {
2339  enum ast_rtp_dtls_setup old = *dtls_setup;
2340 
2341  switch (setup) {
2343  *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2344  break;
2346  *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2347  break;
2349  /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
2350  if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2351  *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
2352  }
2353  break;
2355  *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
2356  break;
2357  default:
2358  /* This should never occur... if it does exit early as we don't know what state things are in */
2359  return;
2360  }
2361 
2362  /* If the setup state did not change we go on as if nothing happened */
2363  if (old == *dtls_setup) {
2364  return;
2365  }
2366 
2367  /* If they don't want us to establish a connection wait until later */
2368  if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
2369  return;
2370  }
2371 
2372  if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
2373  SSL_set_connect_state(ssl);
2374  } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2375  SSL_set_accept_state(ssl);
2376  } else {
2377  return;
2378  }
2379 }
2380 
2381 /*! \pre instance is locked */
2382 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
2383 {
2384  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2385 
2386  if (rtp->dtls.ssl) {
2387  dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
2388  }
2389 
2390  if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
2391  dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
2392  }
2393 }
2394 
2395 /*! \pre instance is locked */
2396 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
2397 {
2398  char *tmp = ast_strdupa(fingerprint), *value;
2399  int pos = 0;
2400  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2401 
2402  if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
2403  return;
2404  }
2405 
2406  rtp->remote_hash = hash;
2407 
2408  while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
2409  sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
2410  }
2411 }
2412 
2413 /*! \pre instance is locked */
2414 static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
2415 {
2416  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2417 
2418  return rtp->local_hash;
2419 }
2420 
2421 /*! \pre instance is locked */
2422 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
2423 {
2424  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2425 
2426  return rtp->local_fingerprint;
2427 }
2428 
2429 /* DTLS RTP Engine interface declaration */
2430 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
2431  .set_configuration = ast_rtp_dtls_set_configuration,
2432  .active = ast_rtp_dtls_active,
2433  .stop = ast_rtp_dtls_stop,
2434  .reset = ast_rtp_dtls_reset,
2435  .get_connection = ast_rtp_dtls_get_connection,
2436  .get_setup = ast_rtp_dtls_get_setup,
2437  .set_setup = ast_rtp_dtls_set_setup,
2438  .set_fingerprint = ast_rtp_dtls_set_fingerprint,
2439  .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
2440  .get_fingerprint = ast_rtp_dtls_get_fingerprint,
2441 };
2442 
2443 #endif
2444 
2445 #ifdef TEST_FRAMEWORK
2446 static size_t get_recv_buffer_count(struct ast_rtp_instance *instance)
2447 {
2448  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2449 
2450  if (rtp && rtp->recv_buffer) {
2451  return ast_data_buffer_count(rtp->recv_buffer);
2452  }
2453 
2454  return 0;
2455 }
2456 
2457 static size_t get_recv_buffer_max(struct ast_rtp_instance *instance)
2458 {
2459  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2460 
2461  if (rtp && rtp->recv_buffer) {
2462  return ast_data_buffer_max(rtp->recv_buffer);
2463  }
2464 
2465  return 0;
2466 }
2467 
2468 static size_t get_send_buffer_count(struct ast_rtp_instance *instance)
2469 {
2470  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2471 
2472  if (rtp && rtp->send_buffer) {
2473  return ast_data_buffer_count(rtp->send_buffer);
2474  }
2475 
2476  return 0;
2477 }
2478 
2479 static void set_rtp_rtcp_schedid(struct ast_rtp_instance *instance, int id)
2480 {
2481  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2482 
2483  if (rtp && rtp->rtcp) {
2484  rtp->rtcp->schedid = id;
2485  }
2486 }
2487 
2488 static struct ast_rtp_engine_test ast_rtp_test = {
2489  .packets_to_drop = 0,
2490  .send_report = 0,
2491  .sdes_received = 0,
2492  .recv_buffer_count = get_recv_buffer_count,
2493  .recv_buffer_max = get_recv_buffer_max,
2494  .send_buffer_count = get_send_buffer_count,
2495  .set_schedid = set_rtp_rtcp_schedid,
2496 };
2497 #endif
2498 
2499 /* RTP Engine Declaration */
2500 static struct ast_rtp_engine asterisk_rtp_engine = {
2501  .name = "asterisk",
2502  .new = ast_rtp_new,
2503  .destroy = ast_rtp_destroy,
2504  .dtmf_begin = ast_rtp_dtmf_begin,
2505  .dtmf_end = ast_rtp_dtmf_end,
2506  .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
2507  .dtmf_mode_set = ast_rtp_dtmf_mode_set,
2508  .dtmf_mode_get = ast_rtp_dtmf_mode_get,
2509  .update_source = ast_rtp_update_source,
2510  .change_source = ast_rtp_change_source,
2511  .write = ast_rtp_write,
2512  .read = ast_rtp_read,
2513  .prop_set = ast_rtp_prop_set,
2514  .fd = ast_rtp_fd,
2515  .remote_address_set = ast_rtp_remote_address_set,
2516  .red_init = rtp_red_init,
2517  .red_buffer = rtp_red_buffer,
2518  .local_bridge = ast_rtp_local_bridge,
2519  .get_stat = ast_rtp_get_stat,
2520  .dtmf_compatible = ast_rtp_dtmf_compatible,
2521  .stun_request = ast_rtp_stun_request,
2522  .stop = ast_rtp_stop,
2523  .qos = ast_rtp_qos_set,
2524  .sendcng = ast_rtp_sendcng,
2525 #ifdef HAVE_PJPROJECT
2526  .ice = &ast_rtp_ice,
2527 #endif
2528 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2529  .dtls = &ast_rtp_dtls,
2530  .activate = ast_rtp_activate,
2531 #endif
2532  .ssrc_get = ast_rtp_get_ssrc,
2533  .cname_get = ast_rtp_get_cname,
2534  .set_remote_ssrc = ast_rtp_set_remote_ssrc,
2535  .set_stream_num = ast_rtp_set_stream_num,
2536  .extension_enable = ast_rtp_extension_enable,
2537  .bundle = ast_rtp_bundle,
2538 #ifdef TEST_FRAMEWORK
2539  .test = &ast_rtp_test,
2540 #endif
2541 };
2542 
2543 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2544 /*! \pre instance is locked */
2545 static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
2546 {
2547  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2548 
2549  ast_debug_dtls(3, "(%p) DTLS perform handshake - ssl = %p, setup = %d\n",
2550  rtp, dtls->ssl, dtls->dtls_setup);
2551 
2552  /* If we are not acting as a client connecting to the remote side then
2553  * don't start the handshake as it will accomplish nothing and would conflict
2554  * with the handshake we receive from the remote side.
2555  */
2556  if (!dtls->ssl || (dtls->dtls_setup != AST_RTP_DTLS_SETUP_ACTIVE)) {
2557  return;
2558  }
2559 
2560  SSL_do_handshake(dtls->ssl);
2561 
2562  /*
2563  * A race condition is prevented between this function and __rtp_recvfrom()
2564  * because both functions have to get the instance lock before they can do
2565  * anything. Without holding the instance lock, this function could start
2566  * the SSL handshake above in one thread and the __rtp_recvfrom() function
2567  * called by the channel thread could read the response and stop the timeout
2568  * timer before we have a chance to even start it.
2569  */
2570  dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
2571 }
2572 #endif
2573 
2574 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2575 static void dtls_perform_setup(struct dtls_details *dtls)
2576 {
2577  if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
2578  return;
2579  }
2580 
2581  SSL_clear(dtls->ssl);
2582  if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
2583  SSL_set_accept_state(dtls->ssl);
2584  } else {
2585  SSL_set_connect_state(dtls->ssl);
2586  }
2587  dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
2588 
2589  ast_debug_dtls(3, "DTLS perform setup - connection reset\n");
2590 }
2591 #endif
2592 
2593 #ifdef HAVE_PJPROJECT
2594 static void rtp_learning_start(struct ast_rtp *rtp);
2595 
2596 /* Handles start of media during ICE negotiation or completion */
2597 static void ast_rtp_ice_start_media(pj_ice_sess *ice, pj_status_t status)
2598 {
2599  struct ast_rtp_instance *instance = ice->user_data;
2600  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2601 
2602  ao2_lock(instance);
2603 
2604  if (status == PJ_SUCCESS) {
2605  struct ast_sockaddr remote_address;
2606 
2607  ast_sockaddr_setnull(&remote_address);
2608  update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2609  if (!ast_sockaddr_isnull(&remote_address)) {
2610  /* Symmetric RTP must be disabled for the remote address to not get overwritten */
2612 
2613  ast_rtp_instance_set_remote_address(instance, &remote_address);
2614  }
2615 
2616  if (rtp->rtcp) {
2617  update_address_with_ice_candidate(ice, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
2618  }
2619  }
2620 
2621 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2622  /* If we've already started media, no need to do all of this again */
2623  if (rtp->ice_media_started) {
2624  ao2_unlock(instance);
2625  return;
2626  }
2627 
2629  "(%p) ICE starting media - perform DTLS - (%p)\n", instance, rtp);
2630 
2631  /*
2632  * Seemingly no reason to call dtls_perform_setup here. Currently we'll do a full
2633  * protocol level renegotiation if things do change. And if bundled is being used
2634  * then ICE is reused when a stream is added.
2635  *
2636  * Note, if for some reason in the future dtls_perform_setup does need to done here
2637  * be aware that creates a race condition between the call here (on ice completion)
2638  * and potential DTLS handshaking when receiving RTP. What happens is the ssl object
2639  * can get cleared (SSL_clear) during that handshaking process (DTLS init). If that
2640  * happens then Asterisk won't complete DTLS initialization. RTP packets are still
2641  * sent/received but won't be encrypted/decrypted.
2642  */
2643  dtls_perform_handshake(instance, &rtp->dtls, 0);
2644 
2645  if (rtp->rtcp && rtp->rtcp->type == AST_RTP_INSTANCE_RTCP_STANDARD) {
2646  dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
2647  }
2648 #endif
2649 
2650  rtp->ice_media_started = 1;
2651 
2652  if (!strictrtp) {
2653  ao2_unlock(instance);
2654  return;
2655  }
2656 
2657  ast_verb(4, "%p -- Strict RTP learning after ICE completion\n", rtp);
2658  rtp_learning_start(rtp);
2659  ao2_unlock(instance);
2660 }
2661 
2662 #ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2663 /* PJPROJECT ICE optional callback */
2664 static void ast_rtp_on_valid_pair(pj_ice_sess *ice)
2665 {
2666  ast_debug_ice(2, "(%p) ICE valid pair, start media\n", ice->user_data);
2667  ast_rtp_ice_start_media(ice, PJ_SUCCESS);
2668 }
2669 #endif
2670 
2671 /* PJPROJECT ICE callback */
2672 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
2673 {
2674  ast_debug_ice(2, "(%p) ICE complete, start media\n", ice->user_data);
2675  ast_rtp_ice_start_media(ice, status);
2676 }
2677 
2678 /* PJPROJECT ICE callback */
2679 static 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)
2680 {
2681  struct ast_rtp_instance *instance = ice->user_data;
2682  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2683 
2684  /* 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
2685  * returns */
2686  if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
2687  rtp->passthrough = 1;
2688  } else if (transport_id == TRANSPORT_TURN_RTP) {
2689  rtp->rtp_passthrough = 1;
2690  } else if (transport_id == TRANSPORT_TURN_RTCP) {
2691  rtp->rtcp_passthrough = 1;
2692  }
2693 }
2694 
2695 /* PJPROJECT ICE callback */
2696 static 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)
2697 {
2698  struct ast_rtp_instance *instance = ice->user_data;
2699  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2700  pj_status_t status = PJ_EINVALIDOP;
2701  pj_ssize_t _size = (pj_ssize_t)size;
2702 
2703  if (transport_id == TRANSPORT_SOCKET_RTP) {
2704  /* Traffic is destined to go right out the RTP socket we already have */
2705  status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2706  /* sendto on a connectionless socket should send all the data, or none at all */
2707  ast_assert(_size == size || status != PJ_SUCCESS);
2708  } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
2709  /* Traffic is destined to go right out the RTCP socket we already have */
2710  if (rtp->rtcp) {
2711  status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2712  /* sendto on a connectionless socket should send all the data, or none at all */
2713  ast_assert(_size == size || status != PJ_SUCCESS);
2714  } else {
2715  status = PJ_SUCCESS;
2716  }
2717  } else if (transport_id == TRANSPORT_TURN_RTP) {
2718  /* Traffic is going through the RTP TURN relay */
2719  if (rtp->turn_rtp) {
2720  status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
2721  }
2722  } else if (transport_id == TRANSPORT_TURN_RTCP) {
2723  /* Traffic is going through the RTCP TURN relay */
2724  if (rtp->turn_rtcp) {
2725  status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
2726  }
2727  }
2728 
2729  return status;
2730 }
2731 
2732 /* ICE Session interface declaration */
2733 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
2734 #ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2735  .on_valid_pair = ast_rtp_on_valid_pair,
2736 #endif
2737  .on_ice_complete = ast_rtp_on_ice_complete,
2738  .on_rx_data = ast_rtp_on_ice_rx_data,
2739  .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
2740 };
2741 
2742 /*! \brief Worker thread for timerheap */
2743 static int timer_worker_thread(void *data)
2744 {
2745  pj_ioqueue_t *ioqueue;
2746 
2747  if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
2748  return -1;
2749  }
2750 
2751  while (!timer_terminate) {
2752  const pj_time_val delay = {0, 10};
2753 
2754  pj_timer_heap_poll(timer_heap, NULL);
2755  pj_ioqueue_poll(ioqueue, &delay);
2756  }
2757 
2758  return 0;
2759 }
2760 #endif
2761 
2762 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
2763 {
2765  return 0;
2766  }
2768  if (rtpdebugport) {
2769  return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
2770  } else {
2771  return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
2772  }
2773  }
2774 
2775  return 1;
2776 }
2777 
2778 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
2779 {
2781  return 0;
2782  }
2784  if (rtcpdebugport) {
2785  return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
2786  } else {
2787  return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
2788  }
2789  }
2790 
2791  return 1;
2792 }
2793 
2794 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2795 /*! \pre instance is locked */
2796 static int dtls_srtp_handle_timeout(struct ast_rtp_instance *instance, int rtcp)
2797 {
2798  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2799  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2800  struct timeval dtls_timeout;
2801 
2802  ast_debug_dtls(3, "(%p) DTLS srtp - handle timeout - rtcp=%d\n", instance, rtcp);
2803  DTLSv1_handle_timeout(dtls->ssl);
2804 
2805  /* If a timeout can't be retrieved then this recurring scheduled item must stop */
2806  if (!DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2807  dtls->timeout_timer = -1;
2808  return 0;
2809  }
2810 
2811  return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2812 }
2813 
2814 /* Scheduler callback */
2815 static int dtls_srtp_handle_rtp_timeout(const void *data)
2816 {
2817  struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2818  int reschedule;
2819 
2820  ao2_lock(instance);
2821  reschedule = dtls_srtp_handle_timeout(instance, 0);
2822  ao2_unlock(instance);
2823  if (!reschedule) {
2824  ao2_ref(instance, -1);
2825  }
2826 
2827  return reschedule;
2828 }
2829 
2830 /* Scheduler callback */
2831 static int dtls_srtp_handle_rtcp_timeout(const void *data)
2832 {
2833  struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2834  int reschedule;
2835 
2836  ao2_lock(instance);
2837  reschedule = dtls_srtp_handle_timeout(instance, 1);
2838  ao2_unlock(instance);
2839  if (!reschedule) {
2840  ao2_ref(instance, -1);
2841  }
2842 
2843  return reschedule;
2844 }
2845 
2846 static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
2847 {
2848  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2849  struct timeval dtls_timeout;
2850 
2851  if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2852  int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2853 
2854  ast_assert(dtls->timeout_timer == -1);
2855 
2856  ao2_ref(instance, +1);
2857  if ((dtls->timeout_timer = ast_sched_add(rtp->sched, timeout,
2858  !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout, instance)) < 0) {
2859  ao2_ref(instance, -1);
2860  ast_log(LOG_WARNING, "Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
2861  !rtcp ? "RTP" : "RTCP", instance);
2862  } else {
2863  ast_debug_dtls(3, "(%p) DTLS srtp - scheduled timeout timer for '%d'\n", instance, timeout);
2864  }
2865  }
2866 }
2867 
2868 /*! \pre Must not be called with the instance locked. */
2869 static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
2870 {
2871  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2872 
2873  AST_SCHED_DEL_UNREF(rtp->sched, dtls->timeout_timer, ao2_ref(instance, -1));
2874  ast_debug_dtls(3, "(%p) DTLS srtp - stopped timeout timer'\n", instance);
2875 }
2876 
2877 /* Scheduler callback */
2878 static int dtls_srtp_renegotiate(const void *data)
2879 {
2880  struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
2881  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2882 
2883  ao2_lock(instance);
2884 
2885  ast_debug_dtls(3, "(%p) DTLS srtp - renegotiate'\n", instance);
2886  SSL_renegotiate(rtp->dtls.ssl);
2887  SSL_do_handshake(rtp->dtls.ssl);
2888 
2889  if (rtp->rtcp && rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
2890  SSL_renegotiate(rtp->rtcp->dtls.ssl);
2891  SSL_do_handshake(rtp->rtcp->dtls.ssl);
2892  }
2893 
2894  rtp->rekeyid = -1;
2895 
2896  ao2_unlock(instance);
2897  ao2_ref(instance, -1);
2898 
2899  return 0;
2900 }
2901 
2902 static int dtls_srtp_add_local_ssrc(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp, unsigned int ssrc, int set_remote_policy)
2903 {
2904  unsigned char material[SRTP_MASTER_LEN * 2];
2905  unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
2906  struct ast_srtp_policy *local_policy, *remote_policy = NULL;
2907  int res = -1;
2908  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2909 
2910  ast_debug_dtls(3, "(%p) DTLS srtp - add local ssrc - rtcp=%d, set_remote_policy=%d'\n",
2911  instance, rtcp, set_remote_policy);
2912 
2913  /* Produce key information and set up SRTP */
2914  if (!SSL_export_keying_material(dtls->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
2915  ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
2916  instance);
2917  return -1;
2918  }
2919 
2920  /* Whether we are acting as a server or client determines where the keys/salts are */
2921  if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
2922  local_key = material;
2923  remote_key = local_key + SRTP_MASTER_KEY_LEN;
2924  local_salt = remote_key + SRTP_MASTER_KEY_LEN;
2925  remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
2926  } else {
2927  remote_key = material;
2928  local_key = remote_key + SRTP_MASTER_KEY_LEN;
2929  remote_salt = local_key + SRTP_MASTER_KEY_LEN;
2930  local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
2931  }
2932 
2933  if (!(local_policy = res_srtp_policy->alloc())) {
2934  return -1;
2935  }
2936 
2937  if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
2938  ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
2939  goto error;
2940  }
2941 
2942  if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
2943  ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
2944  goto error;
2945  }
2946 
2947  res_srtp_policy->set_ssrc(local_policy, ssrc, 0);
2948 
2949  if (set_remote_policy) {
2950  if (!(remote_policy = res_srtp_policy->alloc())) {
2951  goto error;
2952  }
2953 
2954  if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
2955  ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
2956  goto error;
2957  }
2958 
2959  if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
2960  ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
2961  goto error;
2962  }
2963 
2964  res_srtp_policy->set_ssrc(remote_policy, 0, 1);
2965  }
2966 
2967  if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy, rtcp)) {
2968  ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
2969  goto error;
2970  }
2971 
2972  res = 0;
2973 
2974 error:
2975  /* policy->destroy() called even on success to release local reference to these resources */
2976  res_srtp_policy->destroy(local_policy);
2977 
2978  if (remote_policy) {
2979  res_srtp_policy->destroy(remote_policy);
2980  }
2981 
2982  return res;
2983 }
2984 
2985 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_rtp_instance *instance, int rtcp)
2986 {
2987  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2988  int index;
2989 
2990  ast_debug_dtls(3, "(%p) DTLS setup SRTP rtp=%p'\n", instance, rtp);
2991 
2992  /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
2993  if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
2994  X509 *certificate;
2995 
2996  if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
2997  ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
2998  return -1;
2999  }
3000 
3001  /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
3002  if (rtp->remote_fingerprint[0]) {
3003  const EVP_MD *type;
3004  unsigned char fingerprint[EVP_MAX_MD_SIZE];
3005  unsigned int size;
3006 
3007  if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
3008  type = EVP_sha1();
3009  } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
3010  type = EVP_sha256();
3011  } else {
3012  ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
3013  return -1;
3014  }
3015 
3016  if (!X509_digest(certificate, type, fingerprint, &size) ||
3017  !size ||
3018  memcmp(fingerprint, rtp->remote_fingerprint, size)) {
3019  X509_free(certificate);
3020  ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
3021  instance);
3022  return -1;
3023  }
3024  }
3025 
3026  X509_free(certificate);
3027  }
3028 
3029  if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(instance), 1)) {
3030  ast_log(LOG_ERROR, "Failed to add local source '%p'\n", rtp);
3031  return -1;
3032  }
3033 
3034  for (index = 0; index < AST_VECTOR_SIZE(&rtp->ssrc_mapping); ++index) {
3035  struct rtp_ssrc_mapping *mapping = AST_VECTOR_GET_ADDR(&rtp->ssrc_mapping, index);
3036 
3037  if (dtls_srtp_add_local_ssrc(rtp, instance, rtcp, ast_rtp_instance_get_ssrc(mapping->instance), 0)) {
3038  return -1;
3039  }
3040  }
3041 
3042  if (rtp->rekey) {
3043  ao2_ref(instance, +1);
3044  if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
3045  ao2_ref(instance, -1);
3046  return -1;
3047  }
3048  }
3049 
3050  return 0;
3051 }
3052 #endif
3053 
3054 /*! \brief Helper function to compare an elem in a vector by value */
3055 static int compare_by_value(int elem, int value)
3056 {
3057  return elem - value;
3058 }
3059 
3060 /*! \brief Helper function to find an elem in a vector by value */
3061 static int find_by_value(int elem, int value)
3062 {
3063  return elem == value;
3064 }
3065 
3066 static int rtcp_mux(struct ast_rtp *rtp, const unsigned char *packet)
3067 {
3068  uint8_t version;
3069  uint8_t pt;
3070  uint8_t m;
3071 
3072  if (!rtp->rtcp || rtp->rtcp->type != AST_RTP_INSTANCE_RTCP_MUX) {
3073  return 0;
3074  }
3075 
3076  version = (packet[0] & 0XC0) >> 6;
3077  if (version == 0) {
3078  /* version 0 indicates this is a STUN packet and shouldn't
3079  * be interpreted as a possible RTCP packet
3080  */
3081  return 0;
3082  }
3083 
3084  /* The second octet of a packet will be one of the following:
3085  * For RTP: The marker bit (1 bit) and the RTP payload type (7 bits)
3086  * For RTCP: The payload type (8)
3087  *
3088  * RTP has a forbidden range of payload types (64-95) since these
3089  * will conflict with RTCP payload numbers if the marker bit is set.
3090  */
3091  m = packet[1] & 0x80;
3092  pt = packet[1] & 0x7F;
3093  if (m && pt >= 64 && pt <= 95) {
3094  return 1;
3095  }
3096  return 0;
3097 }
3098 
3099 /*! \pre instance is locked */
3100 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
3101 {
3102  int len;
3103  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3104 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3105  char *in = buf;
3106 #endif
3107 #ifdef HAVE_PJPROJECT
3108  struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
3109 #endif
3110 #ifdef TEST_FRAMEWORK
3111  struct ast_rtp_engine_test *test = ast_rtp_instance_get_test(instance);
3112 #endif
3113 
3114  if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
3115  return len;
3116  }
3117 
3118 #ifdef TEST_FRAMEWORK
3119  if (test && test->packets_to_drop > 0) {
3120  test->packets_to_drop--;
3121  return 0;
3122  }
3123 #endif
3124 
3125 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3126  /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
3127  * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
3128  if ((*in >= 20) && (*in <= 63)) {
3129  struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3130  int res = 0;
3131 
3132  /* If no SSL session actually exists terminate things */
3133  if (!dtls->ssl) {
3134  ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
3135  instance);
3136  return -1;
3137  }
3138 
3139  ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - Got SSL packet '%d'\n", instance, rtp, *in);
3140 
3141  /*
3142  * A race condition is prevented between dtls_perform_handshake()
3143  * and this function because both functions have to get the
3144  * instance lock before they can do anything. The
3145  * dtls_perform_handshake() function needs to start the timer
3146  * before we stop it below.
3147  */
3148 
3149  /* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
3150  ao2_unlock(instance);
3151  dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
3152  ao2_lock(instance);
3153 
3154  /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
3155  if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
3156  dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
3157  SSL_set_accept_state(dtls->ssl);
3158  }
3159 
3160  BIO_write(dtls->read_bio, buf, len);
3161 
3162  len = SSL_read(dtls->ssl, buf, len);
3163 
3164  if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
3165  unsigned long error = ERR_get_error();
3166  ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
3167  instance, ERR_reason_error_string(error));
3168  return -1;
3169  }
3170 
3171  if (SSL_is_init_finished(dtls->ssl)) {
3172  /* Any further connections will be existing since this is now established */
3173  dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
3174  /* Use the keying material to set up key/salt information */
3175  if ((res = dtls_srtp_setup(rtp, instance, rtcp))) {
3176  return res;
3177  }
3178  /* Notify that dtls has been established */
3179  res = RTP_DTLS_ESTABLISHED;
3180 
3181  ast_debug_dtls(3, "(%p) DTLS - __rtp_recvfrom rtp=%p - established'\n", instance, rtp);
3182  } else {
3183  /* Since we've sent additional traffic start the timeout timer for retransmission */
3184  dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
3185  }
3186 
3187  return res;
3188  }
3189 #endif
3190 
3191 #ifdef HAVE_PJPROJECT
3192  if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
3193  /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
3194  * so it reflects the actual source and not the loopback
3195  */
3196  if (rtcp) {
3197  ast_sockaddr_copy(sa, &rtp->rtcp->them);
3198  } else {
3200  }
3201  } else if (rtp->ice) {
3202  pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
3203  pj_sockaddr address;
3204  pj_status_t status;
3205  struct ice_wrap *ice;
3206 
3207  pj_thread_register_check();
3208 
3209  pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
3210 
3211  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3212  ice = rtp->ice;
3213  ao2_ref(ice, +1);
3214  ao2_unlock(instance);
3215  status = pj_ice_sess_on_rx_pkt(ice->real_ice,
3218  pj_sockaddr_get_len(&address));
3219  ao2_ref(ice, -1);
3220  ao2_lock(instance);
3221  if (status != PJ_SUCCESS) {
3222  char err_buf[100];
3223 
3224  pj_strerror(status, err_buf, sizeof(err_buf));
3225  ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
3226  (int)status, err_buf);
3227  return -1;
3228  }
3229  if (!rtp->passthrough) {
3230  /* If a unidirectional ICE negotiation occurs then lock on to the source of the
3231  * ICE traffic and use it as the target. This will occur if the remote side only
3232  * wants to receive media but never send to us.
3233  */
3234  if (!rtp->ice_active_remote_candidates && !rtp->ice_proposed_remote_candidates) {
3235  if (rtcp) {
3236  ast_sockaddr_copy(&rtp->rtcp->them, sa);
3237  } else {
3239  }
3240  }
3241  return 0;
3242  }
3243  rtp->passthrough = 0;
3244  }
3245 #endif
3246 
3247  return len;
3248 }
3249 
3250 /*! \pre instance is locked */
3251 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3252 {
3253  return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
3254 }
3255 
3256 /*! \pre instance is locked */
3257 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
3258 {
3259  return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
3260 }
3261 
3262 /*! \pre instance is locked */
3263 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp)
3264 {
3265  int len = size;
3266  void *temp = buf;
3267  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3268  struct ast_rtp_instance *transport = rtp->bundled ? rtp->bundled : instance;
3269  struct ast_rtp *transport_rtp = ast_rtp_instance_get_data(transport);
3270  struct ast_srtp *srtp = ast_rtp_instance_get_srtp(transport, rtcp);
3271  int res;
3272 
3273  *via_ice = 0;
3274 
3275  if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
3276  return -1;
3277  }
3278 
3279 #ifdef HAVE_PJPROJECT
3280  if (transport_rtp->ice) {
3282  pj_status_t status;
3283  struct ice_wrap *ice;
3284 
3285  /* If RTCP is sharing the same socket then use the same component */
3286  if (rtcp && rtp->rtcp->s == rtp->s) {
3287  component = AST_RTP_ICE_COMPONENT_RTP;
3288  }
3289 
3290  pj_thread_register_check();
3291 
3292  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3293  ice = transport_rtp->ice;
3294  ao2_ref(ice, +1);
3295  if (instance == transport) {
3296  ao2_unlock(instance);
3297  }
3298  status = pj_ice_sess_send_data(ice->real_ice, component, temp, len);
3299  ao2_ref(ice, -1);
3300  if (instance == transport) {
3301  ao2_lock(instance);
3302  }
3303  if (status == PJ_SUCCESS) {
3304  *via_ice = 1;
3305  return len;
3306  }
3307  }
3308 #endif
3309 
3310  res = ast_sendto(rtcp ? transport_rtp->rtcp->s : transport_rtp->s, temp, len, flags, sa);
3311  if (res > 0) {
3312  ast_rtp_instance_set_last_tx(instance, time(NULL));
3313  }
3314 
3315  return res;
3316 }
3317 
3318 /*! \pre instance is locked */
3319 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3320 {
3321  return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
3322 }
3323 
3324 /*! \pre instance is locked */
3325 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
3326 {
3327  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3328  int hdrlen = 12;
3329  int res;
3330 
3331  if ((res = __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1)) > 0) {
3332  rtp->txcount++;
3333  rtp->txoctetcount += (res - hdrlen);
3334  }
3335 
3336  return res;
3337 }
3338 
3339 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
3340 {
3341  unsigned int interval;
3342  /*! \todo XXX Do a more reasonable calculation on this one
3343  * Look in RFC 3550 Section A.7 for an example*/
3344  interval = rtcpinterval;
3345  return interval;
3346 }
3347 
3348 static void calc_mean_and_standard_deviation(double new_sample, double *mean, double *std_dev, unsigned int *count)
3349 {
3350  double delta1;
3351  double delta2;
3352 
3353  /* First convert the standard deviation back into a sum of squares. */
3354  double last_sum_of_squares = (*std_dev) * (*std_dev) * (*count ?: 1);
3355 
3356  if (++(*count) == 0) {
3357  /* Avoid potential divide by zero on an overflow */
3358  *count = 1;
3359  }
3360 
3361  /*
3362  * Below is an implementation of Welford's online algorithm [1] for calculating
3363  * mean and variance in a single pass.
3364  *
3365  * [1] https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
3366  */
3367 
3368  delta1 = new_sample - *mean;
3369  *mean += (delta1 / *count);
3370  delta2 = new_sample - *mean;
3371 
3372  /* Now calculate the new variance, and subsequent standard deviation */
3373  *std_dev = sqrt((last_sum_of_squares + (delta1 * delta2)) / *count);
3374 }
3375 
3376 static int create_new_socket(const char *type, int af)
3377 {
3378  int sock = ast_socket_nonblock(af, SOCK_DGRAM, 0);
3379 
3380  if (sock < 0) {
3381  ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
3382  return sock;
3383  }
3384 
3385 #ifdef SO_NO_CHECK
3386  if (nochecksums) {
3387  setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3388  }
3389 #endif
3390 
3391  return sock;
3392 }
3393 
3394 /*!
3395  * \internal
3396  * \brief Initializes sequence values and probation for learning mode.
3397  * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
3398  *
3399  * \param info The learning information to track
3400  * \param seq sequence number read from the rtp header to initialize the information with
3401  */
3402 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
3403 {
3404  info->max_seq = seq;
3405  info->packets = learning_min_sequential;
3406  memset(&info->received, 0, sizeof(info->received));
3407 }
3408 
3409 /*!
3410  * \internal
3411  * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
3412  * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
3413  *
3414  * \param info Structure tracking the learning progress of some address
3415  * \param seq sequence number read from the rtp header
3416  * \retval 0 if probation mode should exit for this address
3417  * \retval non-zero if probation mode should continue
3418  */
3420 {
3421  if (seq == (uint16_t) (info->max_seq + 1)) {
3422  /* packet is in sequence */
3423  info->packets--;
3424  } else {
3425  /* Sequence discontinuity; reset */
3426  info->packets = learning_min_sequential - 1;
3427  info->received = ast_tvnow();
3428  }
3429 
3430  /* Only check time if strictrtp is set to yes. Otherwise, we only needed to check seqno */
3431  if (strictrtp == STRICT_RTP_YES) {
3432  switch (info->stream_type) {
3434  case AST_MEDIA_TYPE_AUDIO:
3435  /*
3436  * Protect against packet floods by checking that we
3437  * received the packet sequence in at least the minimum
3438  * allowed time.
3439  */
3440  if (ast_tvzero(info->received)) {
3441  info->received = ast_tvnow();
3442  } else if (!info->packets
3443  && ast_tvdiff_ms(ast_tvnow(), info->received) < learning_min_duration) {
3444  /* Packet flood; reset */
3445  info->packets = learning_min_sequential - 1;
3446  info->received = ast_tvnow();
3447  }
3448  break;
3449  case AST_MEDIA_TYPE_VIDEO:
3450  case AST_MEDIA_TYPE_IMAGE:
3451  case AST_MEDIA_TYPE_TEXT:
3452  case AST_MEDIA_TYPE_END:
3453  break;
3454  }
3455  }
3456 
3457  info->max_seq = seq;
3458 
3459  return info->packets;
3460 }
3461 
3462 /*!
3463  * \brief Start the strictrtp learning mode.
3464  *
3465  * \param rtp RTP session description
3466  */
3467 static void rtp_learning_start(struct ast_rtp *rtp)
3468 {
3470  memset(&rtp->rtp_source_learn.proposed_address, 0,
3471  sizeof(rtp->rtp_source_learn.proposed_address));
3472  rtp->rtp_source_learn.start = ast_tvnow();
3473  rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t) rtp->lastrxseqno);
3474 }
3475 
3476 #ifdef HAVE_PJPROJECT
3477 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
3478 
3479 /*!
3480  * \internal
3481  * \brief Resets and ACL to empty state.
3482  */
3483 static void rtp_unload_acl(ast_rwlock_t *lock, struct ast_acl_list **acl)
3484 {
3486  *acl = ast_free_acl_list(*acl);
3488 }
3489 
3490 /*!
3491  * \internal
3492  * \brief Checks an address against the ICE blacklist
3493  * \note If there is no ice_blacklist list, always returns 0
3494  *
3495  * \param address The address to consider
3496  * \retval 0 if address is not ICE blacklisted
3497  * \retval 1 if address is ICE blacklisted
3498  */
3499 static int rtp_address_is_ice_blacklisted(const struct ast_sockaddr *address)
3500 {
3501  int result = 0;
3502 
3503  ast_rwlock_rdlock(&ice_acl_lock);
3505  ast_rwlock_unlock(&ice_acl_lock);
3506 
3507  return result;
3508 }
3509 
3510 /*!
3511  * \internal
3512  * \brief Checks an address against the STUN blacklist
3513  * \since 13.16.0
3514  *
3515  * \note If there is no stun_blacklist list, always returns 0
3516  *
3517  * \param addr The address to consider
3518  *
3519  * \retval 0 if address is not STUN blacklisted
3520  * \retval 1 if address is STUN blacklisted
3521  */
3522 static int stun_address_is_blacklisted(const struct ast_sockaddr *addr)
3523 {
3524  int result = 0;
3525 
3526  ast_rwlock_rdlock(&stun_acl_lock);
3527  result |= ast_apply_acl_nolog(stun_acl, addr) == AST_SENSE_DENY;
3528  ast_rwlock_unlock(&stun_acl_lock);
3529 
3530  return result;
3531 }
3532 
3533 /*! \pre instance is locked */
3534 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
3535  int transport)
3536 {
3537  unsigned int count = 0;
3538  struct ifaddrs *ifa, *ia;
3539  struct ast_sockaddr tmp;
3540  pj_sockaddr pjtmp;
3541  struct ast_ice_host_candidate *candidate;
3542  int af_inet_ok = 0, af_inet6_ok = 0;
3543  struct sockaddr_in stunaddr_copy;
3544 
3545  if (ast_sockaddr_is_ipv4(addr)) {
3546  af_inet_ok = 1;
3547  } else if (ast_sockaddr_is_any(addr)) {
3548  af_inet_ok = af_inet6_ok = 1;
3549  } else {
3550  af_inet6_ok = 1;
3551  }
3552 
3553  if (getifaddrs(&ifa) < 0) {
3554  /* If we can't get addresses, we can't load ICE candidates */
3555  ast_log(LOG_ERROR, "(%p) ICE Error obtaining list of local addresses: %s\n",
3556  instance, strerror(errno));
3557  } else {
3558  ast_debug_ice(2, "(%p) ICE add system candidates\n", instance);
3559  /* Iterate through the list of addresses obtained from the system,
3560  * until we've iterated through all of them, or accepted
3561  * PJ_ICE_MAX_CAND candidates */
3562  for (ia = ifa; ia && count < PJ_ICE_MAX_CAND; ia = ia->ifa_next) {
3563  /* Interface is either not UP or doesn't have an address assigned,
3564  * eg, a ppp that just completed LCP but no IPCP yet */
3565  if (!ia->ifa_addr || (ia->ifa_flags & IFF_UP) == 0) {
3566  continue;
3567  }
3568 
3569  /* Filter out non-IPvX addresses, eg, link-layer */
3570  if (ia->ifa_addr->sa_family != AF_INET && ia->ifa_addr->sa_family != AF_INET6) {
3571  continue;
3572  }
3573 
3574  ast_sockaddr_from_sockaddr(&tmp, ia->ifa_addr);
3575 
3576  if (ia->ifa_addr->sa_family == AF_INET) {
3577  const struct sockaddr_in *sa_in = (struct sockaddr_in*)ia->ifa_addr;
3578  if (!af_inet_ok) {
3579  continue;
3580  }
3581 
3582  /* Skip 127.0.0.0/8 (loopback) */
3583  /* Don't use IFF_LOOPBACK check since one could assign usable
3584  * publics to the loopback */
3585  if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) {
3586  continue;
3587  }
3588 
3589  /* Skip 0.0.0.0/8 based on RFC1122, and from pjproject */
3590  if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == 0) {
3591  continue;
3592  }
3593  } else { /* ia->ifa_addr->sa_family == AF_INET6 */
3594  if (!af_inet6_ok) {
3595  continue;
3596  }
3597 
3598  /* Filter ::1 */
3599  if (!ast_sockaddr_cmp_addr(&lo6, &tmp)) {
3600  continue;
3601  }
3602  }
3603 
3604  /* Pull in the host candidates from [ice_host_candidates] */
3605  AST_RWLIST_RDLOCK(&host_candidates);
3606  AST_LIST_TRAVERSE(&host_candidates, candidate, next) {
3607  if (!ast_sockaddr_cmp(&candidate->local, &tmp)) {
3608  /* candidate->local matches actual assigned, so check if
3609  * advertised is blacklisted, if not, add it to the
3610  * advertised list. Not that it would make sense to remap
3611  * a local address to a blacklisted address, but honour it
3612  * anyway. */
3613  if (!rtp_address_is_ice_blacklisted(&candidate->advertised)) {
3614  ast_sockaddr_to_pj_sockaddr(&candidate->advertised, &pjtmp);
3615  pj_sockaddr_set_port(&pjtmp, port);
3616  ast_rtp_ice_add_cand(instance, rtp, component, transport,
3617  PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3618  pj_sockaddr_get_len(&pjtmp));
3619  ++count;
3620  }
3621 
3622  if (!candidate->include_local) {
3623  /* We don't want to advertise the actual address */
3625  }
3626 
3627  break;
3628  }
3629  }
3630  AST_RWLIST_UNLOCK(&host_candidates);
3631 
3632  /* we had an entry in [ice_host_candidates] that matched, and
3633  * didn't have include_local_address set. Alternatively, adding
3634  * that match resulted in us going to PJ_ICE_MAX_CAND */
3635  if (ast_sockaddr_isnull(&tmp) || count == PJ_ICE_MAX_CAND) {
3636  continue;
3637  }
3638 
3639  if (rtp_address_is_ice_blacklisted(&tmp)) {
3640  continue;
3641  }
3642 
3643  ast_sockaddr_to_pj_sockaddr(&tmp, &pjtmp);
3644  pj_sockaddr_set_port(&pjtmp, port);
3645  ast_rtp_ice_add_cand(instance, rtp, component, transport,
3646  PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3647  pj_sockaddr_get_len(&pjtmp));
3648  ++count;
3649  }
3650  freeifaddrs(ifa);
3651  }
3652 
3653  ast_rwlock_rdlock(&stunaddr_lock);
3654  memcpy(&stunaddr_copy, &stunaddr, sizeof(stunaddr));
3655  ast_rwlock_unlock(&stunaddr_lock);
3656 
3657  /* If configured to use a STUN server to get our external mapped address do so */
3658  if (stunaddr_copy.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
3659  (ast_sockaddr_is_ipv4(addr) || ast_sockaddr_is_any(addr)) &&
3660  count < PJ_ICE_MAX_CAND) {
3661  struct sockaddr_in answer;
3662  int rsp;
3663 
3665  "(%p) ICE request STUN %s %s candidate\n", instance,
3666  transport == AST_TRANSPORT_UDP ? "UDP" : "TCP",
3667  component == AST_RTP_ICE_COMPONENT_RTP ? "RTP" : "RTCP");
3668 
3669  /*
3670  * The instance should not be locked because we can block
3671  * waiting for a STUN respone.
3672  */
3673  ao2_unlock(instance);
3674  rsp = ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP
3675  ? rtp->rtcp->s : rtp->s, &stunaddr_copy, NULL, &answer);
3676  ao2_lock(instance);
3677  if (!rsp) {
3678  struct ast_rtp_engine_ice_candidate *candidate;
3679  pj_sockaddr ext, base;
3680  pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
3681  int srflx = 1, baseset = 0;
3682  struct ao2_iterator i;
3683 
3684  pj_sockaddr_init(pj_AF_INET(), &ext, &mapped, ntohs(answer.sin_port));
3685 
3686  /*
3687  * If the returned address is the same as one of our host
3688  * candidates, don't send the srflx. At the same time,
3689  * we need to set the base address (raddr).
3690  */
3691  i = ao2_iterator_init(rtp->ice_local_candidates, 0);
3692  while (srflx && (candidate = ao2_iterator_next(&i))) {
3693  if (!baseset && ast_sockaddr_is_ipv4(&candidate->address)) {
3694  baseset = 1;
3695  ast_sockaddr_to_pj_sockaddr(&candidate->address, &base);
3696  }
3697 
3698  if (!pj_sockaddr_cmp(&candidate->address, &ext)) {
3699  srflx = 0;
3700  }
3701 
3702  ao2_ref(candidate, -1);
3703  }
3705 
3706  if (srflx && baseset) {
3707  pj_sockaddr_set_port(&base, port);
3708  ast_rtp_ice_add_cand(instance, rtp, component, transport,
3709  PJ_ICE_CAND_TYPE_SRFLX, 65535, &ext, &base, &base,
3710  pj_sockaddr_get_len(&ext));
3711  }
3712  }
3713  }
3714 
3715  /* If configured to use a TURN relay create a session and allocate */
3716  if (pj_strlen(&turnaddr)) {
3717  ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
3718  pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
3719  }
3720 }
3721 #endif
3722 
3723 /*!
3724  * \internal
3725  * \brief Calculates the elapsed time from issue of the first tx packet in an
3726  * rtp session and a specified time
3727  *
3728  * \param rtp pointer to the rtp struct with the transmitted rtp packet
3729  * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
3730  *
3731  * \return time elapsed in milliseconds
3732  */
3733 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
3734 {
3735  struct timeval t;
3736  long ms;
3737 
3738  if (ast_tvzero(rtp->txcore)) {
3739  rtp->txcore = ast_tvnow();
3740  rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
3741  }
3742 
3743  t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
3744  if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
3745  ms = 0;
3746  }
3747  rtp->txcore = t;
3748 
3749  return (unsigned int) ms;
3750 }
3751 
3752 #ifdef HAVE_PJPROJECT
3753 /*!
3754  * \internal
3755  * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
3756  *
3757  * \param instance RTP instance for which the ICE session is being replaced
3758  * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
3759  * \param port port to use for adding RTP candidates to the ICE session
3760  * \param replace 0 when creating a new session, 1 when replacing a destroyed session
3761  *
3762  * \pre instance is locked
3763  *
3764  * \retval 0 on success
3765  * \retval -1 on failure
3766  */
3767 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
3768  int port, int replace)
3769 {
3770  pj_stun_config stun_config;
3771  pj_str_t ufrag, passwd;
3772  pj_status_t status;
3773  struct ice_wrap *ice_old;
3774  struct ice_wrap *ice;
3775  pj_ice_sess *real_ice = NULL;
3776  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3777 
3778  ao2_cleanup(rtp->ice_local_candidates);
3779  rtp->ice_local_candidates = NULL;
3780 
3781  ast_debug_ice(2, "(%p) ICE create%s\n", instance, replace ? " and replace" : "");
3782 
3783  ice = ao2_alloc_options(sizeof(*ice), ice_wrap_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
3784  if (!ice) {
3785  ast_rtp_ice_stop(instance);
3786  return -1;
3787  }
3788 
3789  pj_thread_register_check();
3790 
3791  pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
3792  if (!stun_software_attribute) {
3793  stun_config.software_name = pj_str(NULL);
3794  }
3795 
3796  ufrag = pj_str(rtp->local_ufrag);
3797  passwd = pj_str(rtp->local_passwd);
3798 
3799  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3800  ao2_unlock(instance);
3801  /* Create an ICE session for ICE negotiation */
3802  status = pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
3803  rtp->ice_num_components, &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &real_ice);
3804  ao2_lock(instance);
3805  if (status == PJ_SUCCESS) {
3806  /* Safely complete linking the ICE session into the instance */
3807  real_ice->user_data = instance;
3808  ice->real_ice = real_ice;
3809  ice_old = rtp->ice;
3810  rtp->ice = ice;
3811  if (ice_old) {
3812  ao2_unlock(instance);
3813  ao2_ref(ice_old, -1);
3814  ao2_lock(instance);
3815  }
3816 
3817  /* Add all of the available candidates to the ICE session */
3818  rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
3820 
3821  /* Only add the RTCP candidates to ICE when replacing the session and if
3822  * the ICE session contains more than just an RTP component. New sessions
3823  * handle this in a separate part of the setup phase */
3824  if (replace && rtp->rtcp && rtp->ice_num_components > 1) {
3825  rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
3828  }
3829 
3830  return 0;
3831  }
3832 
3833  /*
3834  * It is safe to unref this while instance is locked here.
3835  * It was not initialized with a real_ice pointer.
3836  */
3837  ao2_ref(ice, -1);
3838 
3839  ast_rtp_ice_stop(instance);
3840  return -1;
3841 
3842 }
3843 #endif
3844 
3845 static int rtp_allocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
3846 {
3847  int x, startplace, i, maxloops;
3848 
3850 
3851  /* Create a new socket for us to listen on and use */
3852  if ((rtp->s =
3853  create_new_socket("RTP",
3854  ast_sockaddr_is_ipv4(&rtp->bind_address) ? AF_INET :
3855  ast_sockaddr_is_ipv6(&rtp->bind_address) ? AF_INET6 : -1)) < 0) {
3856  ast_log(LOG_WARNING, "Failed to create a new socket for RTP instance '%p'\n", instance);
3857  return -1;
3858  }
3859 
3860  /* Now actually find a free RTP port to use */
3861  x = (ast_random() % (rtpend - rtpstart)) + rtpstart;
3862  x = x & ~1;
3863  startplace = x;
3864 
3865  /* Protection against infinite loops in the case there is a potential case where the loop is not broken such as an odd
3866  start port sneaking in (even though this condition is checked at load.) */
3867  maxloops = rtpend - rtpstart;
3868  for (i = 0; i <= maxloops; i++) {
3870  /* Try to bind, this will tell us whether the port is available or not */
3871  if (!ast_bind(rtp->s, &rtp->bind_address)) {
3872  ast_debug_rtp(1, "(%p) RTP allocated port %d\n", instance, x);
3874  ast_test_suite_event_notify("RTP_PORT_ALLOCATED", "Port: %d", x);
3875  break;
3876  }
3877 
3878  x += 2;
3879  if (x > rtpend) {
3880  x = (rtpstart + 1) & ~1;
3881  }
3882 
3883  /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
3884  if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
3885  ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
3886  close(rtp->s);
3887  rtp->s = -1;
3888  return -1;
3889  }
3890  }
3891 
3892 #ifdef HAVE_PJPROJECT
3893  /* Initialize synchronization aspects */
3894  ast_cond_init(&rtp->cond, NULL);
3895 
3896  generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
3897  generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
3898 
3899  /* Create an ICE session for ICE negotiation */
3900  if (icesupport) {
3901  rtp->ice_num_components = 2;
3902  ast_debug_ice(2, "(%p) ICE creating session %s (%d)\n", instance,
3904  if (ice_create(instance, &rtp->bind_address, x, 0)) {
3905  ast_log(LOG_NOTICE, "(%p) ICE failed to create session\n", instance);
3906  } else {
3907  rtp->ice_port = x;
3908  ast_sockaddr_copy(&rtp->ice_original_rtp_addr, &rtp->bind_address);
3909  }
3910  }
3911 #endif
3912 
3913 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3914  rtp->rekeyid = -1;
3915  rtp->dtls.timeout_timer = -1;
3916 #endif
3917 
3918  return 0;
3919 }
3920 
3921 static void rtp_deallocate_transport(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
3922 {
3923  int saved_rtp_s = rtp->s;
3924 #ifdef HAVE_PJPROJECT
3925  struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
3926  struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
3927 #endif
3928 
3929 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3930  ast_rtp_dtls_stop(instance);
3931 #endif
3932 
3933  /* Close our own socket so we no longer get packets */
3934  if (rtp->s > -1) {
3935  close(rtp->s);
3936  rtp->s = -1;
3937  }
3938 
3939  /* Destroy RTCP if it was being used */
3940  if (rtp->rtcp && rtp->rtcp->s > -1) {
3941  if (saved_rtp_s != rtp->rtcp->s) {
3942  close(rtp->rtcp->s);
3943  }
3944  rtp->rtcp->s = -1;
3945  }
3946 
3947 #ifdef HAVE_PJPROJECT
3948  pj_thread_register_check();
3949 
3950  /*
3951  * The instance lock is already held.
3952  *
3953  * Destroy the RTP TURN relay if being used
3954  */
3955  if (rtp->turn_rtp) {
3956  rtp->turn_state = PJ_TURN_STATE_NULL;
3957 
3958  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3959  ao2_unlock(instance);
3960  pj_turn_sock_destroy(rtp->turn_rtp);
3961  ao2_lock(instance);
3962  while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
3963  ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
3964  }
3965  rtp->turn_rtp = NULL;
3966  }
3967 
3968  /* Destroy the RTCP TURN relay if being used */
3969  if (rtp->turn_rtcp) {
3970  rtp->turn_state = PJ_TURN_STATE_NULL;
3971 
3972  /* Release the instance lock to avoid deadlock with PJPROJECT group lock */
3973  ao2_unlock(instance);
3974  pj_turn_sock_destroy(rtp->turn_rtcp);
3975  ao2_lock(instance);
3976  while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
3977  ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
3978  }
3979  rtp->turn_rtcp = NULL;
3980  }
3981 
3982  ast_debug_ice(2, "(%p) ICE RTP transport deallocating\n", instance);
3983  /* Destroy any ICE session */
3984  ast_rtp_ice_stop(instance);
3985 
3986  /* Destroy any candidates */
3987  if (rtp->ice_local_candidates) {
3988  ao2_ref(rtp->ice_local_candidates, -1);
3989  rtp->ice_local_candidates = NULL;
3990  }
3991 
3992  if (rtp->ice_active_remote_candidates) {
3993  ao2_ref(rtp->ice_active_remote_candidates, -1);
3994  rtp->ice_active_remote_candidates = NULL;
3995  }
3996 
3997  if (rtp->ice_proposed_remote_candidates) {
3998  ao2_ref(rtp->ice_proposed_remote_candidates, -1);
3999  rtp->ice_proposed_remote_candidates = NULL;
4000  }
4001 
4002  if (rtp->ioqueue) {
4003  /*
4004  * We cannot hold the instance lock because we could wait
4005  * for the ioqueue thread to die and we might deadlock as
4006  * a result.
4007  */
4008  ao2_unlock(instance);
4009  rtp_ioqueue_thread_remove(rtp->ioqueue);
4010  ao2_lock(instance);
4011  rtp->ioqueue = NULL;
4012  }
4013 #endif
4014 }
4015 
4016 /*! \pre instance is locked */
4017 static int ast_rtp_new(struct ast_rtp_instance *instance,
4018  struct ast_sched_context *sched, struct ast_sockaddr *addr,
4019  void *data)
4020 {
4021  struct ast_rtp *rtp = NULL;
4022 
4023  /* Create a new RTP structure to hold all of our data */
4024  if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
4025  return -1;
4026  }
4027 
4028  /* Set default parameters on the newly created RTP structure */
4029  rtp->ssrc = ast_random();
4030  ast_uuid_generate_str(rtp->cname, sizeof(rtp->cname));
4031  rtp->seqno = ast_random() & 0x7fff;
4032  rtp->expectedrxseqno = -1;
4033  rtp->expectedseqno = -1;
4034  rtp->sched = sched;
4035  ast_sockaddr_copy(&rtp->bind_address, addr);
4036 
4037  /* Transport creation operations can grab the RTP data from the instance, so set it */
4038  ast_rtp_instance_set_data(instance, rtp);
4039 
4040  if (rtp_allocate_transport(instance, rtp)) {
4041  return -1;
4042  }
4043 
4044  if (AST_VECTOR_INIT(&rtp->ssrc_mapping, 1)) {
4045  return -1;
4046  }
4047 
4049  return -1;
4050  }
4051  rtp->transport_wide_cc.schedid = -1;
4052 
4056  rtp->stream_num = -1;
4057 
4058  return 0;
4059 }
4060 
4061 /*!
4062  * \brief SSRC mapping comparator for AST_VECTOR_REMOVE_CMP_UNORDERED()
4063  *
4064  * \param elem Element to compare against
4065  * \param value Value to compare with the vector element.
4066  *
4067  * \retval 0 if element does not match.
4068  * \retval Non-zero if element matches.
4069  */
4070 #define SSRC_MAPPING_ELEM_CMP(elem, value) ((elem).instance == (value))
4071 
4072 /*! \pre instance is locked */
4073 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
4074 {
4075  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4076 
4077  if (rtp->bundled) {
4078  struct ast_rtp *bundled_rtp;
4079 
4080  /* We can't hold our instance lock while removing ourselves from the parent */
4081  ao2_unlock(instance);
4082 
4083  ao2_lock(rtp->bundled);
4084  bundled_rtp = ast_rtp_instance_get_data(rtp->bundled);
4086  ao2_unlock(rtp->bundled);
4087 
4088  ao2_lock(instance);
4089  ao2_ref(rtp->bundled, -1);
4090  }
4091 
4092  rtp_deallocate_transport(instance, rtp);
4093 
4094  /* Destroy the smoother that was smoothing out audio if present */
4095  if (rtp->smoother) {
4097  }
4098 
4099  /* Destroy RTCP if it was being used */
4100  if (rtp->rtcp) {
4101  /*
4102  * It is not possible for there to be an active RTCP scheduler
4103  * entry at this point since it holds a reference to the
4104  * RTP instance while it's active.
4105  */
4106  ast_free(rtp->rtcp->local_addr_str);
4107  ast_free(rtp->rtcp);
4108  }
4109 
4110  /* Destroy RED if it was being used */
4111  if (rtp->red) {
4112  ao2_unlock(instance);
4113  AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
4114  ao2_lock(instance);
4115  ast_free(rtp->red);
4116  rtp->red = NULL;
4117  }
4118 
4119  /* Destroy the send buffer if it was being used */
4120  if (rtp->send_buffer) {
4122  }
4123 
4124  /* Destroy the recv buffer if it was being used */
4125  if (rtp->recv_buffer) {
4127  }
4128 
4130 
4131  ao2_cleanup(rtp->lasttxformat);
4132  ao2_cleanup(rtp->lastrxformat);
4133  ao2_cleanup(rtp->f.subclass.format);
4136 
4137  /* Finally destroy ourselves */
4138  ast_free(rtp);
4139 
4140  return 0;
4141 }
4142 
4143 /*! \pre instance is locked */
4144 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
4145 {
4146  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4147  rtp->dtmfmode = dtmf_mode;
4148  return 0;
4149 }
4150 
4151 /*! \pre instance is locked */
4152 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
4153 {
4154  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4155  return rtp->dtmfmode;
4156 }
4157 
4158 /*! \pre instance is locked */
4159 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
4160 {
4161  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4162  struct ast_sockaddr remote_address = { {0,} };
4163  int hdrlen = 12, res = 0, i = 0, payload = 101;
4164  char data[256];
4165  unsigned int *rtpheader = (unsigned int*)data;
4166 
4167  ast_rtp_instance_get_remote_address(instance, &remote_address);
4168 
4169  /* If we have no remote address information bail out now */
4170  if (ast_sockaddr_isnull(&remote_address)) {
4171  return -1;
4172  }
4173 
4174  /* Convert given digit into what we want to transmit */
4175  if ((digit <= '9') && (digit >= '0')) {
4176  digit -= '0';
4177  } else if (digit == '*') {
4178  digit = 10;
4179  } else if (digit == '#') {
4180  digit = 11;
4181  } else if ((digit >= 'A') && (digit <= 'D')) {
4182  digit = digit - 'A' + 12;
4183  } else if ((digit >= 'a') && (digit <= 'd')) {
4184  digit = digit - 'a' + 12;
4185  } else {
4186  ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4187  return -1;
4188  }
4189 
4190  /* Grab the payload that they expect the RFC2833 packet to be received in */
4192 
4193  rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4194  rtp->send_duration = 160;
4195  rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
4196  rtp->lastdigitts = rtp->lastts + rtp->send_duration;
4197 
4198  /* Create the actual packet that we will be sending */
4199  rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
4200  rtpheader[1] = htonl(rtp->lastdigitts);
4201  rtpheader[2] = htonl(rtp->ssrc);
4202 
4203  /* Actually send the packet */
4204  for (i = 0; i < 2; i++) {
4205  int ice;
4206 
4207  rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4208  res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4209  if (res < 0) {
4210  ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4211  ast_sockaddr_stringify(&remote_address),
4212  strerror(errno));
4213  }
4214  if (rtp_debug_test_addr(&remote_address)) {
4215  ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4216  ast_sockaddr_stringify(&remote_address),
4217  ice ? " (via ICE)" : "",
4218  payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4219  }
4220  rtp->seqno++;
4221  rtp->send_duration += 160;
4222  rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
4223  }
4224 
4225  /* Record that we are in the process of sending a digit and information needed to continue doing so */
4226  rtp->sending_digit = 1;
4227  rtp->send_digit = digit;
4228  rtp->send_payload = payload;
4229 
4230  return 0;
4231 }
4232 
4233 /*! \pre instance is locked */
4234 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
4235 {
4236  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4237  struct ast_sockaddr remote_address = { {0,} };
4238  int hdrlen = 12, res = 0;
4239  char data[256];
4240  unsigned int *rtpheader = (unsigned int*)data;
4241  int ice;
4242 
4243  ast_rtp_instance_get_remote_address(instance, &remote_address);
4244 
4245  /* Make sure we know where the other side is so we can send them the packet */
4246  if (ast_sockaddr_isnull(&remote_address)) {
4247  return -1;
4248  }
4249 
4250  /* Actually create the packet we will be sending */
4251  rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4252  rtpheader[1] = htonl(rtp->lastdigitts);
4253  rtpheader[2] = htonl(rtp->ssrc);
4254  rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
4255 
4256  /* Boom, send it on out */
4257  res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4258  if (res < 0) {
4259  ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4260  ast_sockaddr_stringify(&remote_address),
4261  strerror(errno));
4262  }
4263 
4264  if (rtp_debug_test_addr(&remote_address)) {
4265  ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4266  ast_sockaddr_stringify(&remote_address),
4267  ice ? " (via ICE)" : "",
4268  rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4269  }
4270 
4271  /* And now we increment some values for the next time we swing by */
4272  rtp->seqno++;
4273  rtp->send_duration += 160;
4274  rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
4275 
4276  return 0;
4277 }
4278 
4279 /*! \pre instance is locked */
4280 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
4281 {
4282  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4283  struct ast_sockaddr remote_address = { {0,} };
4284  int hdrlen = 12, res = -1, i = 0;
4285  char data[256];
4286  unsigned int *rtpheader = (unsigned int*)data;
4287  unsigned int measured_samples;
4288 
4289  ast_rtp_instance_get_remote_address(instance, &remote_address);
4290 
4291  /* Make sure we know where the remote side is so we can send them the packet we construct */
4292  if (ast_sockaddr_isnull(&remote_address)) {
4293  goto cleanup;
4294  }
4295 
4296  /* Convert the given digit to the one we are going to send */
4297  if ((digit <= '9') && (digit >= '0')) {
4298  digit -= '0';
4299  } else if (digit == '*') {
4300  digit = 10;
4301  } else if (digit == '#') {
4302  digit = 11;
4303  } else if ((digit >= 'A') && (digit <= 'D')) {
4304  digit = digit - 'A' + 12;
4305  } else if ((digit >= 'a') && (digit <= 'd')) {
4306  digit = digit - 'a' + 12;
4307  } else {
4308  ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
4309  goto cleanup;
4310  }
4311 
4312  rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
4313 
4314  if (duration > 0 && (measured_samples = duration * ast_rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
4315  ast_debug_rtp(2, "(%p) RTP adjusting final end duration from %d to %u\n",
4316  instance, rtp->send_duration, measured_samples);
4317  rtp->send_duration = measured_samples;
4318  }
4319 
4320  /* Construct the packet we are going to send */
4321  rtpheader[1] = htonl(rtp->lastdigitts);
4322  rtpheader[2] = htonl(rtp->ssrc);
4323  rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4324  rtpheader[3] |= htonl((1 << 23));
4325 
4326  /* Send it 3 times, that's the magical number */
4327  for (i = 0; i < 3; i++) {
4328  int ice;
4329 
4330  rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
4331 
4332  res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4333 
4334  if (res < 0) {
4335  ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
4336  ast_sockaddr_stringify(&remote_address),
4337  strerror(errno));
4338  }
4339 
4340  if (rtp_debug_test_addr(&remote_address)) {
4341  ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4342  ast_sockaddr_stringify(&remote_address),
4343  ice ? " (via ICE)" : "",
4344  rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
4345  }
4346 
4347  rtp->seqno++;
4348  }
4349  res = 0;
4350 
4351  /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
4352  rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
4353 
4354  /* Reset the smoother as the delivery time stored in it is now out of date */
4355  if (rtp->smoother) {
4357  rtp->smoother = NULL;
4358  }
4359 cleanup:
4360  rtp->sending_digit = 0;
4361  rtp->send_digit = 0;
4362 
4363  /* Re-Learn expected seqno */
4364  rtp->expectedseqno = -1;
4365 
4366  return res;
4367 }
4368 
4369 /*! \pre instance is locked */
4370 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
4371 {
4372  return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
4373 }
4374 
4375 /*! \pre instance is locked */
4376 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
4377 {
4378  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4379 
4380  /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4382  ast_debug_rtp(3, "(%p) RTP setting the marker bit due to a source update\n", instance);
4383 
4384  return;
4385 }
4386 
4387 /*! \pre instance is locked */
4388 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
4389 {
4390  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4391  struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance, 0);
4392  struct ast_srtp *rtcp_srtp = ast_rtp_instance_get_srtp(instance, 1);
4393  unsigned int ssrc = ast_random();
4394 
4395  if (rtp->lastts) {
4396  /* We simply set this bit so that the next packet sent will have the marker bit turned on */
4398  }
4399 
4400  ast_debug_rtp(3, "(%p) RTP changing ssrc from %u to %u due to a source change\n",
4401  instance, rtp->ssrc, ssrc);
4402 
4403  if (srtp) {
4404  ast_debug_rtp(3, "(%p) RTP changing ssrc for SRTP from %u to %u\n",
4405  instance, rtp->ssrc, ssrc);
4406  res_srtp->change_source(srtp, rtp->ssrc, ssrc);
4407  if (rtcp_srtp != srtp) {
4408  res_srtp->change_source(rtcp_srtp, rtp->ssrc, ssrc);
4409  }
4410  }
4411 
4412  rtp->ssrc = ssrc;
4413 
4414  /* Since the source is changing, we don't know what sequence number to expect next */
4415  rtp->expectedrxseqno = -1;
4416 
4417  return;
4418 }
4419 
4420 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
4421 {
4422  unsigned int sec, usec, frac;
4423  sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
4424  usec = tv.tv_usec;
4425  /*
4426  * Convert usec to 0.32 bit fixed point without overflow.
4427  *
4428  * = usec * 2^32 / 10^6
4429  * = usec * 2^32 / (2^6 * 5^6)
4430  * = usec * 2^26 / 5^6
4431  *
4432  * The usec value needs 20 bits to represent 999999 usec. So
4433  * splitting the 2^26 to get the most precision using 32 bit
4434  * values gives:
4435  *
4436  * = ((usec * 2^12) / 5^6) * 2^14
4437  *
4438  * Splitting the division into two stages preserves all the
4439  * available significant bits of usec over doing the division
4440  * all at once.
4441  *
4442  * = ((((usec * 2^12) / 5^3) * 2^7) / 5^3) * 2^7
4443  */
4444  frac = ((((usec << 12) / 125) << 7) / 125) << 7;
4445  *msw = sec;
4446  *lsw = frac;
4447 }
4448 
4449 static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
4450 {
4451  tv->tv_sec = msw - 2208988800u;
4452  /* Reverse the sequence in timeval2ntp() */
4453  tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
4454 }
4455 
4457  unsigned int *lost_packets,
4458  int *fraction_lost)
4459 {
4460  unsigned int extended_seq_no;
4461  unsigned int expected_packets;
4462  unsigned int expected_interval;
4463  unsigned int received_interval;
4464  int lost_interval;
4465 
4466  /* Compute statistics */
4467  extended_seq_no = rtp->cycles + rtp->lastrxseqno;
4468  expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
4469  if (rtp->rxcount > expected_packets) {
4470  expected_packets += rtp->rxcount - expected_packets;
4471  }
4472  *lost_packets = expected_packets - rtp->rxcount;
4473  expected_interval = expected_packets - rtp->rtcp->expected_prior;
4474  received_interval = rtp->rxcount - rtp->rtcp->received_prior;
4475  if (received_interval > expected_interval) {
4476  /* If we receive some late packets it is possible for the packets
4477  * we received in this interval to exceed the number we expected.
4478  * We update the expected so that the packet loss calculations
4479  * show that no packets are lost.
4480  */
4481  expected_interval = received_interval;
4482  }
4483  lost_interval = expected_interval - received_interval;
4484  if (expected_interval == 0 || lost_interval <= 0) {
4485  *fraction_lost = 0;
4486  } else {
4487  *fraction_lost = (lost_interval << 8) / expected_interval;
4488  }
4489 
4490  /* Update RTCP statistics */
4491  rtp->rtcp->received_prior = rtp->rxcount;
4492  rtp->rtcp->expected_prior = expected_packets;
4493 
4494  /*
4495  * While rxlost represents the number of packets lost since the last report was sent, for
4496  * the calculations below it should be thought of as a single sample. Thus min/max are the
4497  * lowest/highest sample value seen, and the mean is the average number of packets lost
4498  * between each report. As such rxlost_count only needs to be incremented per report.
4499  */
4500  if (lost_interval <= 0) {
4501  rtp->rtcp->rxlost = 0;
4502  } else {
4503  rtp->rtcp->rxlost = lost_interval;
4504  }
4505  if (rtp->rtcp->rxlost_count == 0) {
4506  rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4507  }
4508  if (lost_interval && lost_interval < rtp->rtcp->minrxlost) {
4509  rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
4510  }
4511  if (lost_interval > rtp->rtcp->maxrxlost) {
4512  rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
4513  }
4514 
4515  calc_mean_and_standard_deviation(rtp->rtcp->rxlost, &rtp->rtcp->normdev_rxlost,
4516  &rtp->rtcp->stdev_rxlost, &rtp->rtcp->rxlost_count);
4517 }
4518 
4519 static int ast_rtcp_generate_report(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4520  struct ast_rtp_rtcp_report *rtcp_report, int *sr)
4521 {
4522  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4523  int len = 0;
4524  struct timeval now;
4525  unsigned int now_lsw;
4526  unsigned int now_msw;
4527  unsigned int lost_packets;
4528  int fraction_lost;
4529  struct timeval dlsr = { 0, };
4530  struct ast_rtp_rtcp_report_block *report_block = NULL;
4531 
4532  if (!rtp || !rtp->rtcp) {
4533  return 0;
4534  }
4535 
4536  if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
4537  /* RTCP was stopped. */
4538  return 0;
4539  }
4540 
4541  if (!rtcp_report) {
4542  return 1;
4543  }
4544 
4545  *sr = rtp->txcount > rtp->rtcp->lastsrtxcount ? 1 : 0;
4546 
4547  /* Compute statistics */
4548  calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
4549 
4550  gettimeofday(&now, NULL);
4551  rtcp_report->reception_report_count = rtp->themssrc_valid ? 1 : 0;
4552  rtcp_report->ssrc = rtp->ssrc;
4553  rtcp_report->type = *sr ? RTCP_PT_SR : RTCP_PT_RR;
4554  if (*sr) {
4555  rtcp_report->sender_information.ntp_timestamp = now;
4556  rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
4557  rtcp_report->sender_information.packet_count = rtp->txcount;
4558  rtcp_report->sender_information.octet_count = rtp->txoctetcount;
4559  }
4560 
4561  if (rtp->themssrc_valid) {
4562  report_block = ast_calloc(1, sizeof(*report_block));
4563  if (!report_block) {
4564  return 1;
4565  }
4566 
4567  rtcp_report->report_block[0] = report_block;
4568  report_block->source_ssrc = rtp->themssrc;
4569  report_block->lost_count.fraction = (fraction_lost & 0xff);
4570  report_block->lost_count.packets = (lost_packets & 0xffffff);
4571  report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
4572  report_block->ia_jitter = (unsigned int)(rtp->rxjitter * ast_rtp_get_rate(rtp->f.subclass.format));
4573  report_block->lsr = rtp->rtcp->themrxlsr;
4574  /* If we haven't received an SR report, DLSR should be 0 */
4575  if (!ast_tvzero(rtp->rtcp->rxlsr)) {
4576  timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
4577  report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
4578  }
4579  }
4580  timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
4581  put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc)); /* Our SSRC */
4582  len += 8;
4583  if (*sr) {
4584  put_unaligned_uint32(rtcpheader + len, htonl(now_msw)); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970 */
4585  put_unaligned_uint32(rtcpheader + len + 4, htonl(now_lsw)); /* now, LSW */
4586  put_unaligned_uint32(rtcpheader + len + 8, htonl(rtcp_report->sender_information.rtp_timestamp));
4587  put_unaligned_uint32(rtcpheader + len + 12, htonl(rtcp_report->sender_information.packet_count));
4588  put_unaligned_uint32(rtcpheader + len + 16, htonl(rtcp_report->sender_information.octet_count));
4589  len += 20;
4590  }
4591  if (report_block) {
4592  put_unaligned_uint32(rtcpheader + len, htonl(report_block->source_ssrc)); /* Their SSRC */
4593  put_unaligned_uint32(rtcpheader + len + 4, htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets));
4594  put_unaligned_uint32(rtcpheader + len + 8, htonl(report_block->highest_seq_no));
4595  put_unaligned_uint32(rtcpheader + len + 12, htonl(report_block->ia_jitter));
4596  put_unaligned_uint32(rtcpheader + len + 16, htonl(report_block->lsr));
4597  put_unaligned_uint32(rtcpheader + len + 20, htonl(report_block->dlsr));
4598  len += 24;
4599  }
4600 
4601  put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
4602  | ((*sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1)));
4603 
4604  return len;
4605 }
4606 
4608  struct ast_rtp_rtcp_report *rtcp_report, struct ast_sockaddr remote_address, int ice, int sr)
4609 {
4610  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4611  struct ast_rtp_rtcp_report_block *report_block = NULL;
4612  RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
4613 
4614  if (!rtp || !rtp->rtcp) {
4615  return 0;
4616  }
4617 
4618  if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4619  return 0;
4620  }
4621 
4622  if (!rtcp_report) {
4623  return -1;
4624  }
4625 
4626  report_block = rtcp_report->report_block[0];
4627 
4628  if (sr) {
4629  rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
4630  rtp->rtcp->sr_count++;
4631  rtp->rtcp->lastsrtxcount = rtp->txcount;
4632  } else {
4633  rtp->rtcp->rr_count++;
4634  }
4635 
4636  if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
4637  ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
4638  ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
4639  ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
4640  if (sr) {
4641  ast_verbose(" Sent(NTP): %u.%06u\n",
4642  (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
4643  (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
4644  ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
4645  ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
4646  ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
4647  }
4648  if (report_block) {
4649  ast_verbose(" Report block:\n");
4650  ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
4651  ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
4652  ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
4653  ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
4654  ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / ast_rtp_get_rate(rtp->f.subclass.format));
4655  ast_verbose(" Their last SR: %u\n", report_block->lsr);
4656  ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
4657  }
4658  }
4659 
4660  message_blob = ast_json_pack("{s: s, s: s}",
4661  "to", ast_sockaddr_stringify(&remote_address),
4662  "from", rtp->rtcp->local_addr_str);
4664  rtcp_report, message_blob);
4665 
4666  return 1;
4667 }
4668 
4669 static int ast_rtcp_generate_sdes(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4670  struct ast_rtp_rtcp_report *rtcp_report)
4671 {
4672  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4673  int len = 0;
4674  uint16_t sdes_packet_len_bytes;
4675  uint16_t sdes_packet_len_rounded;
4676 
4677  if (!rtp || !rtp->rtcp) {
4678  return 0;
4679  }
4680 
4681  if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4682  return 0;
4683  }
4684 
4685  if (!rtcp_report) {
4686  return -1;
4687  }
4688 
4689  sdes_packet_len_bytes =
4690  4 + /* RTCP Header */
4691  4 + /* SSRC */
4692  1 + /* Type (CNAME) */
4693  1 + /* Text Length */
4694  AST_UUID_STR_LEN /* Text and NULL terminator */
4695  ;
4696 
4697  /* Round to 32 bit boundary */
4698  sdes_packet_len_rounded = (sdes_packet_len_bytes + 3) & ~0x3;
4699 
4700  put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | ((sdes_packet_len_rounded / 4) - 1)));
4701  put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc));
4702  rtcpheader[8] = 0x01; /* CNAME */
4703  rtcpheader[9] = AST_UUID_STR_LEN - 1; /* Number of bytes of text */
4704  memcpy(rtcpheader + 10, rtp->cname, AST_UUID_STR_LEN);
4705  len += 10 + AST_UUID_STR_LEN;
4706 
4707  /* Padding - Note that we don't set the padded bit on the packet. From
4708  * RFC 3550 Section 6.5:
4709  *
4710  * No length octet follows the null item type octet, but additional null
4711  * octets MUST be included if needd to pad until the next 32-bit
4712  * boundary. Note that this padding is separate from that indicated by
4713  * the P bit in the RTCP header.
4714  *
4715  * These bytes will already be zeroed out during array initialization.
4716  */
4717  len += (sdes_packet_len_rounded - sdes_packet_len_bytes);
4718 
4719  return len;
4720 }
4721 
4722 /* Lock instance before calling this if it isn't already
4723  *
4724  * If successful, the overall packet length is returned
4725  * If not, then 0 is returned
4726  */
4727 static int ast_rtcp_generate_compound_prefix(struct ast_rtp_instance *instance, unsigned char *rtcpheader,
4728  struct ast_rtp_rtcp_report *report, int *sr)
4729 {
4730  int packet_len = 0;
4731  int res;
4732 
4733  /* Every RTCP packet needs to be sent out with a SR/RR and SDES prefixing it.
4734  * At the end of this function, rtcpheader should contain both of those packets,
4735  * and will return the length of the overall packet. This can be used to determine
4736  * where further packets can be inserted in the compound packet.
4737  */
4738  res = ast_rtcp_generate_report(instance, rtcpheader, report, sr);
4739 
4740  if (res == 0 || res == 1) {
4741  ast_debug_rtcp(1, "(%p) RTCP failed to generate %s report!\n", instance, sr ? "SR" : "RR");
4742  return 0;
4743  }
4744 
4745  packet_len += res;
4746 
4747  res = ast_rtcp_generate_sdes(instance, rtcpheader + packet_len, report);
4748 
4749  if (res == 0 || res == 1) {
4750  ast_debug_rtcp(1, "(%p) RTCP failed to generate SDES!\n", instance);
4751  return 0;
4752  }
4753 
4754  return packet_len + res;
4755 }
4756 
4757 static int ast_rtcp_generate_nack(struct ast_rtp_instance *instance, unsigned char *rtcpheader)
4758 {
4759  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4760  int packet_len;
4761  int blp_index = -1;
4762  int current_seqno;
4763  unsigned int fci = 0;
4764  size_t remaining_missing_seqno;
4765 
4766  if (!rtp || !rtp->rtcp) {
4767  return 0;
4768  }
4769 
4770  if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
4771  return 0;
4772  }
4773 
4774  current_seqno = rtp->expectedrxseqno;
4775  remaining_missing_seqno = AST_VECTOR_SIZE(&rtp->missing_seqno);
4776  packet_len = 12; /* The header length is 12 (version line, packet source SSRC, media source SSRC) */
4777 
4778  /* If there are no missing sequence numbers then don't bother sending a NACK needlessly */
4779  if (!remaining_missing_seqno) {
4780  return 0;
4781  }
4782 
4783  /* This iterates through the possible forward sequence numbers seeing which ones we
4784  * have no packet for, adding it to the NACK until we are out of missing packets.
4785  */
4786  while (remaining_missing_seqno) {
4787  int *missing_seqno;
4788 
4789  /* On the first entry to this loop blp_index will be -1, so this will become 0
4790  * and the sequence number will be placed into the packet as the PID.
4791  */
4792  blp_index++;
4793 
4794  missing_seqno = AST_VECTOR_GET_CMP(&rtp->missing_seqno, current_seqno,
4795  find_by_value);
4796  if (missing_seqno) {
4797  /* We hit the max blp size, reset */
4798  if (blp_index >= 17) {
4799  put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
4800  fci = 0;
4801  blp_index = 0;
4802  packet_len += 4;
4803  }
4804 
4805  if (blp_index == 0) {
4806  fci |= (current_seqno << 16);
4807  } else {
4808  fci |= (1 << (blp_index - 1));
4809  }
4810 
4811  /* Since we've used a missing sequence number, we're down one */
4812  remaining_missing_seqno--;
4813  }
4814 
4815  /* Handle cycling of the sequence number */
4816  current_seqno++;
4817  if (current_seqno == SEQNO_CYCLE_OVER) {
4818  current_seqno = 0;
4819  }
4820  }
4821 
4822  put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
4823  packet_len += 4;
4824 
4825  /* Length MUST be 2+n, where n is the number of NACKs. Same as length in words minus 1 */
4826  put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (AST_RTP_RTCP_FMT_NACK << 24)
4827  | (AST_RTP_RTCP_RTPFB << 16) | ((packet_len / 4) - 1)));
4828  put_unaligned_uint32(rtcpheader + 4, htonl(rtp->ssrc));
4829  put_unaligned_uint32(rtcpheader + 8, htonl(rtp->themssrc));
4830 
4831  return packet_len;
4832 }
4833 
4834 /*!
4835  * \brief Write a RTCP packet to the far end
4836  *
4837  * \note Decide if we are going to send an SR (with Reception Block) or RR
4838  * RR is sent if we have not sent any rtp packets in the previous interval
4839  *
4840  * Scheduler callback
4841  */
4842 static int ast_rtcp_write(const void *data)
4843 {
4844  struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
4845  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4846  int res;
4847  int sr = 0;
4848  int packet_len = 0;
4849  int ice;
4850  struct ast_sockaddr remote_address = { { 0, } };
4851  unsigned char *rtcpheader;
4852  unsigned char bdata[AST_UUID_STR_LEN + 128] = ""; /* More than enough */
4853  RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
4855  ao2_cleanup);
4856 
4857  if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
4858  ao2_ref(instance, -1);
4859  return 0;
4860  }
4861 
4862  ao2_lock(instance);
4863  rtcpheader = bdata;
4864 
4865  res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
4866 
4867  if (res == 0 || res == 1) {
4868  goto cleanup;
4869  }
4870 
4871  packet_len += res;
4872 
4873  if (rtp->bundled) {
4874  ast_rtp_instance_get_remote_address(instance, &remote_address);
4875  } else {
4876  ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
4877  }
4878 
4879  res = rtcp_sendto(instance, (unsigned int *)rtcpheader, packet_len, 0, &remote_address, &ice);
4880  if (res < 0) {
4881  ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
4882  sr ? "SR" : "RR",
4884  strerror(errno));
4885  res = 0;
4886  } else {
4887  ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, remote_address, ice, sr);
4888  }
4889 
4890 cleanup:
4891  ao2_unlock(instance);
4892 
4893  if (!res) {
4894  /*
4895  * Not being rescheduled.
4896  */
4897  rtp->rtcp->schedid = -1;
4898  ao2_ref(instance, -1);
4899  }
4900 
4901  return res;
4902 }
4903 
4904 static void put_unaligned_time24(void *p, uint32_t time_msw, uint32_t time_lsw)
4905 {
4906  unsigned char *cp = p;
4907  uint32_t datum;
4908 
4909  /* Convert the time to 6.18 format */
4910  datum = (time_msw << 18) & 0x00fc0000;
4911  datum |= (time_lsw >> 14) & 0x0003ffff;
4912 
4913  cp[0] = datum >> 16;
4914  cp[1] = datum >> 8;
4915  cp[2] = datum;
4916 }
4917 
4918 /*! \pre instance is locked */
4919 static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
4920 {
4921  struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
4922  int pred, mark = 0;
4923  unsigned int ms = calc_txstamp(rtp, &frame->delivery);
4924  struct ast_sockaddr remote_address = { {0,} };
4925  int rate = ast_rtp_get_rate(frame->subclass.format) / 1000;
4926  unsigned int seqno;
4927 #ifdef TEST_FRAMEWORK
4928  struct ast_rtp_engine_test *test = ast_rtp_instance_get_test(instance);
4929 #endif
4930 
4932  frame->samples /= 2;
4933  }
4934 
4935  if (rtp->sending_digit) {
4936  return 0;
4937  }
4938 
4939 #ifdef TEST_FRAMEWORK
4940  if (test && test->send_report) {
4941  test->send_report = 0;
4942  ast_rtcp_write(instance);
4943  return 0;
4944  }
4945 #endif
4946 
4947  if (frame->frametype == AST_FRAME_VOICE) {
4948  pred = rtp->lastts + frame->samples;
4949 
4950  /* Re-calculate last TS */
4951  rtp->lastts = rtp->lastts + ms * rate;
4952  if (ast_tvzero(frame->delivery)) {
4953  /* If this isn't an absolute delivery time, Check if it is close to our prediction,
4954  and if so, go with our prediction */
4955  if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
4956  rtp->lastts = pred;
4957  } else {
4958  ast_debug_rtp(3, "(%p) RTP audio difference is %d, ms is %u\n",
4959  instance, abs((int)rtp->lastts - pred), ms);
4960  mark = 1;
4961  }
4962  }
4963  } else if (frame->frametype == AST_FRAME_VIDEO) {
4964  mark = frame->subclass.frame_ending;
4965  pred = rtp->lastovidtimestamp + frame->samples;
4966  /* Re-calculate last TS */
4967  rtp->lastts = rtp->lastts + ms * 90;
4968  /* If it's close to our prediction, go for it */
4969  if (ast_tvzero(frame->delivery)) {
4970  if (abs((int)rtp->lastts - pred) < 7200) {
4971  rtp->lastts = pred;
4972  rtp->lastovidtimestamp += frame->samples;
4973  } else {
4974  ast_debug_rtp(3, "(%p) RTP video difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n",
4975  instance, abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
4976  rtp->lastovidtimestamp = rtp->lastts;
4977  }
4978  }
4979  } else {
4980  pred = rtp->lastotexttimestamp + frame->samples;
4981  /* Re-calculate last TS */
4982  rtp->lastts = rtp->lastts + ms;
4983  /* If it's close to our prediction, go for it */
4984  if (ast_tvzero(frame->delivery)) {
4985  if (abs((int)rtp->lastts - pred) < 7200) {
4986  rtp->lastts = pred;
4987  rtp->lastotexttimestamp += frame->samples;
4988  } else {
4989  ast_debug_rtp(3, "(%p) RTP other difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n",
4990  instance, abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
4991  rtp->lastotexttimestamp = rtp->lastts;
4992  }
4993  }
4994  }
4995 
4996  /* If we have been explicitly told to set the marker bit then do so */
4997  if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
4998  mark = 1;
5000  }
5001 
5002  /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
5003  if (rtp->lastts > rtp->lastdigitts) {
5004  rtp->lastdigitts = rtp->lastts;
5005  }
5006 
5007  /* Assume that the sequence number we expect to use is what will be used until proven otherwise */
5008  seqno = rtp->seqno;
5009 
5010  /* If the frame contains sequence number information use it to influence our sequence number */
5012  if (rtp->expectedseqno != -1) {
5013  /* Determine where the frame from the core is in relation to where we expected */
5014  int difference = frame->seqno - rtp->expectedseqno;
5015 
5016  /* If there is a substantial difference then we've either got packets really out
5017  * of order, or the source is RTP and it has cycled. If this happens we resync
5018  * the sequence number adjustments to this frame. If we also have packet loss
5019  * things won't be reflected correctly but it will sort itself out after a bit.
5020  */
5021  if (abs(difference) > 100) {
5022  difference = 0;
5023  }
5024 
5025  /* Adjust the sequence number being used for this packet accordingly */
5026  seqno += difference;
5027 
5028  if (difference >= 0) {
5029  /* This frame is on time or in the future */
5030  rtp->expectedseqno = frame->seqno + 1;
5031  rtp->seqno += difference;
5032  }
5033  } else {
5034  /* This is the first frame with sequence number we've seen, so start keeping track */
5035  rtp->expectedseqno = frame->seqno + 1;
5036  }
5037  } else {
5038  rtp->expectedseqno = -1;
5039  }
5040 
5042  rtp->lastts = frame->ts * rate;
5043  }
5044 
5045  ast_rtp_instance_get_remote_address(instance, &remote_address);
5046 
5047  /* If we know the remote address construct a packet and send it out */
5048  if (!ast_sockaddr_isnull(&remote_address)) {
5049  int hdrlen = 12;
5050  int res;
5051  int ice;
5052  int ext = 0;
5053  int abs_send_time_id;
5054  int packet_len;
5055  unsigned char *rtpheader;
5056 
5057  /* If the abs-send-time extension has been negotiated determine how much space we need */
5059  if (abs_send_time_id != -1) {
5060  /* 4 bytes for the shared information, 1 byte for identifier, 3 bytes for abs-send-time */
5061  hdrlen += 8;
5062  ext = 1;
5063  }
5064 
5065  packet_len = frame->datalen + hdrlen;
5066  rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
5067 
5068  put_unaligned_uint32(rtpheader, htonl((2 << 30) | (ext << 28) | (codec << 16) | (seqno) | (mark << 23)));
5069  put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
5070  put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
5071 
5072  /* We assume right now that we will only ever have the abs-send-time extension in the packet
5073  * which simplifies things a bit.
5074  */
5075  if (abs_send_time_id != -1) {
5076  unsigned int now_msw;
5077  unsigned int now_lsw;
5078 
5079  /* This happens before being placed into the retransmission buffer so that when we
5080  * retransmit we only have to update the timestamp, not everything else.
5081  */
5082  put_unaligned_uint32(rtpheader + 12, htonl((0xBEDE << 16) | 1));
5083  rtpheader[16] = (abs_send_time_id << 4) | 2;
5084 
5085  timeval2ntp(ast_tvnow(), &now_msw, &now_lsw);
5086  put_unaligned_time24(rtpheader + 17, now_msw, now_lsw);
5087  }
5088 
5089  /* If retransmissions are enabled, we need to store this packet for future use */
5090  if (rtp->send_buffer) {
5091  struct ast_rtp_rtcp_nack_payload *payload;
5092 
5093  payload = ast_malloc(sizeof(*payload) + packet_len);
5094  if (payload) {
5095  payload->size = packet_len;
5096  memcpy(payload->buf, rtpheader, packet_len);
5097  if (ast_data_buffer_put(rtp->send_buffer, rtp->seqno, payload) == -1) {
5098  ast_free(payload);
5099  }
5100  }
5101  }
5102 
5103  res = rtp_sendto(instance, (void *)rtpheader, packet_len, 0, &remote_address, &ice);
5104  if (res < 0) {
5106  ast_debug_rtp(1, "(%p) RTP transmission error of packet %d to %s: %s\n",
5107  instance, rtp->seqno,
5108  ast_sockaddr_stringify(&remote_address),
5109  strerror(errno));
5111  /* Only give this error message once if we are not RTP debugging */
5113  ast_debug(0, "(%p) RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
5114  instance, ast_sockaddr_stringify(&remote_address));
5116  }
5117  } else {
5118  if (rtp->rtcp && rtp->rtcp->schedid < 0) {
5119  ast_debug_rtcp(1, "(%p) RTCP starting transmission\n", instance);
5120  ao2_ref(instance, +1);
5121  rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
5122  if (rtp->rtcp->schedid < 0) {
5123  ao2_ref(instance, -1);
5124  ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
5125  }
5126  }
5127  }
5128 
5129  if (rtp_debug_test_addr(&remote_address)) {
5130  ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
5131  ast_sockaddr_stringify(&remote_address),
5132  ice ? " (via ICE)" : "",
5133  codec, rtp->seqno, rtp->lastts, res - hdrlen);
5134  }
5135  }
5136 
5137  /* If the sequence number that has been used doesn't match what we expected then this is an out of
5138  * order late packet, so we don't need to increment as we haven't yet gotten the expected frame from
5139  * the core.
5140  */
5141  if (seqno == rtp->seqno) {
5142  rtp->seqno++;
5143  }
5144 
5145  return 0;
5146 }
5147 
5148 static struct ast_frame *red_t140_to_red(struct rtp_red *red)
5149 {
5150  unsigned char *data = red->t140red.data.ptr;
5151  int len = 0;
5152  int i;
5153 
5154  /* replace most aged generation */
5155  if (red->len[0]) {
5156  for (i = 1; i < red->num_gen+1; i++)
5157  len += red->len[i];
5158 
5159  memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
5160  }
5161 
5162  /* Store length of each generation and primary data length*/
5163  for (i = 0; i < red->num_gen; i++)
5164  red->len[i] = red->len[i+1];
5165  red->len[i] = red->t140.datalen;
5166 
5167  /* write each generation length in red header */
5168  len = red->hdrlen;
5169  for (i = 0; i < red->num_gen; i++) {
5170  len += data[i*4+3] = red->len[i];
5171  }
5172 
5173  /* add primary data to buffer */
5174  memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
5175  red->t140red.datalen = len + red->t140.datalen;
5176 
5177  /* no primary data and no generations to send */
5178  if (len == red->hdrlen && !red->t140.datalen) {
5179  return NULL;
5180  }
5181 
5182  /* reset t.140 buffer */
5183  red->t140.datalen = 0;
5184 
5185  return &red->t140red;
5186 }
5187 
5188 static void rtp_write_rtcp_fir(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *remote_address)
5189 {
5190  unsigned char *rtcpheader;
5191  unsigned char bdata[1024];
5192  int packet_len = 0;
5193  int fir_len = 20;
5194  int ice;
5195  int res;
5196  int sr;
5197  RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
5199  ao2_cleanup);
5200 
5201  if (!rtp || !rtp->rtcp) {
5202  return;
5203  }
5204 
5205  if (ast_sockaddr_isnull(&rtp->rtcp->them) || rtp->rtcp->schedid < 0) {
5206  /*
5207  * RTCP was stopped.
5208  */
5209  return;
5210  }
5211 
5212  if (!rtp->themssrc_valid) {
5213  /* We don't know their SSRC value so we don't know who to update. */
5214  return;
5215  }
5216 
5217  /* Prepare RTCP FIR (PT=206, FMT=4) */
5218  rtp->rtcp->firseq++;
5219  if(rtp->rtcp->firseq == 256) {
5220  rtp->rtcp->firseq = 0;
5221  }
5222 
5223  rtcpheader = bdata;
5224 
5225  ao2_lock(instance);
5226  res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5227 
5228  if (res == 0 || res == 1) {
5229  ao2_unlock(instance);
5230  return;
5231  }
5232 
5233  packet_len += res;
5234 
5235  put_unaligned_uint32(rtcpheader + packet_len + 0, htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((fir_len/4)-1)));
5236  put_unaligned_uint32(rtcpheader + packet_len + 4, htonl(rtp->ssrc));
5237