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