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