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