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