2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
28 * \ingroup rtp_engines
32 <use type="external">pjproject</use>
33 <support_level>core</support_level>
38 ASTERISK_REGISTER_FILE()
44 #ifdef HAVE_OPENSSL_SRTP
45 #include <openssl/ssl.h>
46 #include <openssl/err.h>
47 #include <openssl/bio.h>
52 #include <pjlib-util.h>
56 #include "asterisk/stun.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/frame.h"
59 #include "asterisk/format_cache.h"
60 #include "asterisk/channel.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/config.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/cli.h"
66 #include "asterisk/manager.h"
67 #include "asterisk/unaligned.h"
68 #include "asterisk/module.h"
69 #include "asterisk/rtp_engine.h"
70 #include "asterisk/smoother.h"
71 #include "asterisk/test.h"
73 #define MAX_TIMESTAMP_SKEW 640
75 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
76 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
77 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
78 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
80 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
81 #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
83 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
84 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
86 #define DEFAULT_TURN_PORT 3478
88 #define TURN_STATE_WAIT_TIME 2000
90 #define RTCP_PT_FUR 192
91 #define RTCP_PT_SR AST_RTP_RTCP_SR
92 #define RTCP_PT_RR AST_RTP_RTCP_RR
93 #define RTCP_PT_SDES 202
94 #define RTCP_PT_BYE 203
95 #define RTCP_PT_APP 204
96 /* VP8: RTCP Feedback */
97 #define RTCP_PT_PSFB 206
100 #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
102 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
104 #define ZFONE_PROFILE_ID 0x505a
106 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
108 #define SRTP_MASTER_KEY_LEN 16
109 #define SRTP_MASTER_SALT_LEN 14
110 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
112 enum strict_rtp_state {
113 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
114 STRICT_RTP_LEARN, /*! Accept next packet as source */
115 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
118 #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
119 #define DEFAULT_ICESUPPORT 1
121 extern struct ast_srtp_res *res_srtp;
122 extern struct ast_srtp_policy_res *res_srtp_policy;
124 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
126 static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
127 static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
128 static int rtpdebug; /*!< Are we debugging? */
129 static int rtcpdebug; /*!< Are we debugging RTCP? */
130 static int rtcpstats; /*!< Are we debugging RTCP? */
131 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
132 static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
133 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
134 static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
135 static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
137 static int nochecksums;
139 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. */
140 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. */
141 #ifdef HAVE_PJPROJECT
142 static int icesupport = DEFAULT_ICESUPPORT;
143 static struct sockaddr_in stunaddr;
144 static pj_str_t turnaddr;
145 static int turnport = DEFAULT_TURN_PORT;
146 static pj_str_t turnusername;
147 static pj_str_t turnpassword;
149 /*! \brief Pool factory used by pjlib to allocate memory. */
150 static pj_caching_pool cachingpool;
152 /*! \brief Global memory pool for configuration and timers */
153 static pj_pool_t *pool;
155 /*! \brief Global timer heap */
156 static pj_timer_heap_t *timer_heap;
158 /*! \brief Thread executing the timer heap */
159 static pj_thread_t *timer_thread;
161 /*! \brief Used to tell the timer thread to terminate */
162 static int timer_terminate;
164 /*! \brief Structure which contains ioqueue thread information */
165 struct ast_rtp_ioqueue_thread {
166 /*! \brief Pool used by the thread */
168 /*! \brief The thread handling the queue and timer heap */
170 /*! \brief Ioqueue which polls on sockets */
171 pj_ioqueue_t *ioqueue;
172 /*! \brief Timer heap for scheduled items */
173 pj_timer_heap_t *timerheap;
174 /*! \brief Termination request */
176 /*! \brief Current number of descriptors being waited on */
178 /*! \brief Linked list information */
179 AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
182 /*! \brief List of ioqueue threads */
183 static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
187 #define FLAG_3389_WARNING (1 << 0)
188 #define FLAG_NAT_ACTIVE (3 << 1)
189 #define FLAG_NAT_INACTIVE (0 << 1)
190 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
191 #define FLAG_NEED_MARKER_BIT (1 << 3)
192 #define FLAG_DTMF_COMPENSATE (1 << 4)
194 #define TRANSPORT_SOCKET_RTP 0
195 #define TRANSPORT_SOCKET_RTCP 1
196 #define TRANSPORT_TURN_RTP 2
197 #define TRANSPORT_TURN_RTCP 3
199 /*! \brief RTP learning mode tracking information */
200 struct rtp_learning_info {
201 int max_seq; /*!< The highest sequence number received */
202 int packets; /*!< The number of remaining packets before the source is accepted */
205 #ifdef HAVE_OPENSSL_SRTP
206 struct dtls_details {
207 ast_mutex_t lock; /*!< Lock for timeout timer synchronization */
208 SSL *ssl; /*!< SSL session */
209 BIO *read_bio; /*!< Memory buffer for reading */
210 BIO *write_bio; /*!< Memory buffer for writing */
211 enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
212 enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
213 int timeout_timer; /*!< Scheduler id for timeout timer */
217 /*! \brief RTP session description */
221 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
222 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
223 unsigned int themssrc; /*!< Their SSRC */
226 unsigned int lastrxts;
227 unsigned int lastividtimestamp;
228 unsigned int lastovidtimestamp;
229 unsigned int lastitexttimestamp;
230 unsigned int lastotexttimestamp;
231 unsigned int lasteventseqn;
232 int lastrxseqno; /*!< Last received sequence number */
233 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
234 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
235 unsigned int rxcount; /*!< How many packets have we received? */
236 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
237 unsigned int txcount; /*!< How many packets have we sent? */
238 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
239 unsigned int cycles; /*!< Shifted count of sequence number cycles */
240 double rxjitter; /*!< Interarrival jitter at the moment in seconds */
241 double rxtransit; /*!< Relative transit time for previous packet */
242 struct ast_format *lasttxformat;
243 struct ast_format *lastrxformat;
245 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
246 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
247 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
249 /* DTMF Reception Variables */
250 char resp; /*!< The current digit being processed */
251 unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
252 unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
253 unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
254 unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
255 unsigned int dtmfsamples;
256 enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
257 /* DTMF Transmission Variables */
258 unsigned int lastdigitts;
259 char sending_digit; /*!< boolean - are we sending digits */
260 char send_digit; /*!< digit we are sending */
264 struct timeval rxcore;
265 struct timeval txcore;
266 double drxcore; /*!< The double representation of the first received packet */
267 struct timeval lastrx; /*!< timeval when we last received a packet */
268 struct timeval dtmfmute;
269 struct ast_smoother *smoother;
271 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
272 unsigned short rxseqno;
273 struct ast_sched_context *sched;
274 struct io_context *io;
276 struct ast_rtcp *rtcp;
277 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
279 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
280 struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
283 * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
284 * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
286 struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
287 struct rtp_learning_info alt_source_learn; /* Learning mode tracking for a new RTP source after one has been chosen */
291 ast_mutex_t lock; /*!< Lock for synchronization purposes */
292 ast_cond_t cond; /*!< Condition for signaling */
294 #ifdef HAVE_PJPROJECT
295 pj_ice_sess *ice; /*!< ICE session */
296 pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
297 pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
298 pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
299 unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
300 unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
301 unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
302 unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
303 struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
304 struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
306 struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
308 char remote_ufrag[256]; /*!< The remote ICE username */
309 char remote_passwd[256]; /*!< The remote ICE password */
311 char local_ufrag[256]; /*!< The local ICE username */
312 char local_passwd[256]; /*!< The local ICE password */
314 struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
315 struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
316 struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
317 struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
320 #ifdef HAVE_OPENSSL_SRTP
321 SSL_CTX *ssl_ctx; /*!< SSL context */
322 enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
323 enum ast_srtp_suite suite; /*!< SRTP crypto suite */
324 enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
325 char local_fingerprint[160]; /*!< Fingerprint of our certificate */
326 enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
327 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
328 unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
329 int rekeyid; /*!< Scheduled item id for rekeying */
330 struct dtls_details dtls; /*!< DTLS state information */
335 * \brief Structure defining an RTCP session.
337 * The concept "RTCP session" is not defined in RFC 3550, but since
338 * this structure is analogous to ast_rtp, which tracks a RTP session,
339 * it is logical to think of this as a RTCP session.
341 * RTCP packet is defined on page 9 of RFC 3550.
346 int s; /*!< Socket */
347 struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
348 struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
349 unsigned int soc; /*!< What they told us */
350 unsigned int spc; /*!< What they told us */
351 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
352 struct timeval rxlsr; /*!< Time when we got their last SR */
353 struct timeval txlsr; /*!< Time when we sent or last SR*/
354 unsigned int expected_prior; /*!< no. packets in previous interval */
355 unsigned int received_prior; /*!< no. packets received in previous interval */
356 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
357 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
358 unsigned int sr_count; /*!< number of SRs we've sent */
359 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
360 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
361 double rtt; /*!< Last reported rtt */
362 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
363 unsigned int reported_lost; /*!< Reported lost packets in their RR */
365 double reported_maxjitter;
366 double reported_minjitter;
367 double reported_normdev_jitter;
368 double reported_stdev_jitter;
369 unsigned int reported_jitter_count;
371 double reported_maxlost;
372 double reported_minlost;
373 double reported_normdev_lost;
374 double reported_stdev_lost;
379 double normdev_rxlost;
381 unsigned int rxlost_count;
385 double normdev_rxjitter;
386 double stdev_rxjitter;
387 unsigned int rxjitter_count;
392 unsigned int rtt_count;
394 /* VP8: sequence number for the RTCP FIR FCI */
397 #ifdef HAVE_OPENSSL_SRTP
398 struct dtls_details dtls; /*!< DTLS state information */
403 struct ast_frame t140; /*!< Primary data */
404 struct ast_frame t140red; /*!< Redundant t140*/
405 unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
406 unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
407 unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
408 int num_gen; /*!< Number of generations */
409 int schedid; /*!< Timer id */
410 int ti; /*!< How long to buffer data before send */
411 unsigned char t140red_data[64000];
412 unsigned char buf_data[64000]; /*!< buffered primary data */
417 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
419 /* Forward Declarations */
420 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
421 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
422 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
423 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
424 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
425 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
426 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
427 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
428 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
429 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
430 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
431 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
432 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
433 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
434 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
435 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
436 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
437 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
438 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
439 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
440 static void ast_rtp_stop(struct ast_rtp_instance *instance);
441 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
442 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
444 #ifdef HAVE_OPENSSL_SRTP
445 static int ast_rtp_activate(struct ast_rtp_instance *instance);
446 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
447 static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
448 static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
451 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp);
453 #ifdef HAVE_PJPROJECT
454 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
455 static void update_address_with_ice_candidate(struct ast_rtp *rtp, enum ast_rtp_ice_component_type component,
456 struct ast_sockaddr *cand_address)
458 char address[PJ_INET6_ADDRSTRLEN];
460 if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
464 ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
465 ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
468 /*! \brief Destructor for locally created ICE candidates */
469 static void ast_rtp_ice_candidate_destroy(void *obj)
471 struct ast_rtp_engine_ice_candidate *candidate = obj;
473 if (candidate->foundation) {
474 ast_free(candidate->foundation);
477 if (candidate->transport) {
478 ast_free(candidate->transport);
482 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
484 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
486 if (!ast_strlen_zero(ufrag)) {
487 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
490 if (!ast_strlen_zero(password)) {
491 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
495 static int ice_candidate_cmp(void *obj, void *arg, int flags)
497 struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
499 if (strcmp(candidate1->foundation, candidate2->foundation) ||
500 candidate1->id != candidate2->id ||
501 ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
502 candidate1->type != candidate1->type) {
506 return CMP_MATCH | CMP_STOP;
509 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
511 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
512 struct ast_rtp_engine_ice_candidate *remote_candidate;
514 /* ICE sessions only support UDP candidates */
515 if (strcasecmp(candidate->transport, "udp")) {
519 if (!rtp->ice_proposed_remote_candidates &&
520 !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
524 /* If this is going to exceed the maximum number of ICE candidates don't even add it */
525 if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
529 if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
533 remote_candidate->foundation = ast_strdup(candidate->foundation);
534 remote_candidate->id = candidate->id;
535 remote_candidate->transport = ast_strdup(candidate->transport);
536 remote_candidate->priority = candidate->priority;
537 ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
538 ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
539 remote_candidate->type = candidate->type;
541 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
542 ao2_ref(remote_candidate, -1);
545 AST_THREADSTORAGE(pj_thread_storage);
547 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
548 static void pj_thread_register_check(void)
550 pj_thread_desc *desc;
553 if (pj_thread_is_registered() == PJ_TRUE) {
557 desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
559 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
562 pj_bzero(*desc, sizeof(*desc));
564 if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
565 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
570 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
571 int port, int replace);
573 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
575 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
581 pj_thread_register_check();
583 pj_ice_sess_destroy(rtp->ice);
587 static int ice_reset_session(struct ast_rtp_instance *instance)
589 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
590 pj_ice_sess_role role = rtp->ice->role;
593 if (!rtp->ice->is_nominating && !rtp->ice->is_complete) {
597 ast_rtp_ice_stop(instance);
599 res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
601 /* Preserve the role that the old ICE session used */
602 pj_ice_sess_change_role(rtp->ice, role);
608 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
610 struct ao2_iterator i;
611 struct ast_rtp_engine_ice_candidate *right_candidate;
613 if (ao2_container_count(left) != ao2_container_count(right)) {
617 i = ao2_iterator_init(right, 0);
618 while ((right_candidate = ao2_iterator_next(&i))) {
619 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
621 if (!left_candidate) {
622 ao2_ref(right_candidate, -1);
623 ao2_iterator_destroy(&i);
627 ao2_ref(left_candidate, -1);
628 ao2_ref(right_candidate, -1);
630 ao2_iterator_destroy(&i);
635 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
637 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
638 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
639 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
640 struct ao2_iterator i;
641 struct ast_rtp_engine_ice_candidate *candidate;
642 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
644 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
648 /* Check for equivalence in the lists */
649 if (rtp->ice_active_remote_candidates &&
650 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
651 ao2_cleanup(rtp->ice_proposed_remote_candidates);
652 rtp->ice_proposed_remote_candidates = NULL;
656 /* Out with the old, in with the new */
657 ao2_cleanup(rtp->ice_active_remote_candidates);
658 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
659 rtp->ice_proposed_remote_candidates = NULL;
661 /* Reset the ICE session. Is this going to work? */
662 if (ice_reset_session(instance)) {
663 ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
667 pj_thread_register_check();
669 i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
671 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
674 /* there needs to be at least one rtp and rtcp candidate in the list */
675 has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
676 has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
678 pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
679 candidates[cand_cnt].comp_id = candidate->id;
680 candidates[cand_cnt].prio = candidate->priority;
682 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
684 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
685 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
688 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
689 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
690 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
691 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
692 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
693 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
696 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
697 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
698 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
699 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
703 ao2_ref(candidate, -1);
706 ao2_iterator_destroy(&i);
708 if (has_rtp && has_rtcp &&
709 pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(
710 rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
711 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
712 pj_ice_sess_start_check(rtp->ice);
713 pj_timer_heap_poll(timer_heap, NULL);
714 rtp->strict_rtp_state = STRICT_RTP_OPEN;
718 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
720 /* even though create check list failed don't stop ice as
721 it might still work */
722 ast_debug(1, "Failed to create ICE session check list\n");
723 /* however we do need to reset remote candidates since
724 this function may be re-entered */
725 ao2_ref(rtp->ice_active_remote_candidates, -1);
726 rtp->ice_active_remote_candidates = NULL;
727 rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
730 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
732 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
734 return rtp->local_ufrag;
737 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
739 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
741 return rtp->local_passwd;
744 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
746 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
748 if (rtp->ice_local_candidates) {
749 ao2_ref(rtp->ice_local_candidates, +1);
752 return rtp->ice_local_candidates;
755 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
757 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
763 pj_thread_register_check();
765 pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
768 static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
770 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
776 pj_thread_register_check();
778 pj_ice_sess_change_role(rtp->ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
779 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
782 static void ast_rtp_ice_add_cand(struct ast_rtp *rtp, unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
783 const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
786 struct ast_rtp_engine_ice_candidate *candidate, *existing;
787 char address[PJ_INET6_ADDRSTRLEN];
789 pj_thread_register_check();
791 pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
793 if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
797 if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
801 candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
802 candidate->id = comp_id;
803 candidate->transport = ast_strdup("UDP");
805 ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
806 ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
809 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
810 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
813 if (type == PJ_ICE_CAND_TYPE_HOST) {
814 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
815 } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
816 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
817 } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
818 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
821 if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
822 ao2_ref(existing, -1);
823 ao2_ref(candidate, -1);
827 if (pj_ice_sess_add_cand(rtp->ice, comp_id, transport_id, type, local_pref, &foundation, addr, base_addr, rel_addr, addr_len, NULL) != PJ_SUCCESS) {
828 ao2_ref(candidate, -1);
832 /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
833 candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
835 ao2_link(rtp->ice_local_candidates, candidate);
836 ao2_ref(candidate, -1);
839 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)
841 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
842 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
845 status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTP, TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr,
847 if (status != PJ_SUCCESS) {
850 pj_strerror(status, buf, sizeof(buf));
851 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
855 if (!rtp->rtp_passthrough) {
858 rtp->rtp_passthrough = 0;
860 ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
863 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)
865 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
868 /* If this is a leftover from an already notified RTP instance just ignore the state change */
873 rtp = ast_rtp_instance_get_data(instance);
875 /* We store the new state so the other thread can actually handle it */
876 ast_mutex_lock(&rtp->lock);
877 rtp->turn_state = new_state;
878 ast_cond_signal(&rtp->cond);
880 if (new_state == PJ_TURN_STATE_DESTROYING) {
881 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
882 rtp->turn_rtp = NULL;
885 ast_mutex_unlock(&rtp->lock);
888 /* RTP TURN Socket interface declaration */
889 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
890 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
891 .on_state = ast_rtp_on_turn_rtp_state,
894 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)
896 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
897 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
900 status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr,
902 if (status != PJ_SUCCESS) {
905 pj_strerror(status, buf, sizeof(buf));
906 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
910 if (!rtp->rtcp_passthrough) {
913 rtp->rtcp_passthrough = 0;
915 ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
918 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)
920 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
921 struct ast_rtp *rtp = NULL;
923 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
928 rtp = ast_rtp_instance_get_data(instance);
930 /* We store the new state so the other thread can actually handle it */
931 ast_mutex_lock(&rtp->lock);
932 rtp->turn_state = new_state;
933 ast_cond_signal(&rtp->cond);
935 if (new_state == PJ_TURN_STATE_DESTROYING) {
936 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
937 rtp->turn_rtcp = NULL;
940 ast_mutex_unlock(&rtp->lock);
943 /* RTCP TURN Socket interface declaration */
944 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
945 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
946 .on_state = ast_rtp_on_turn_rtcp_state,
949 /*! \brief Worker thread for ioqueue and timerheap */
950 static int ioqueue_worker_thread(void *data)
952 struct ast_rtp_ioqueue_thread *ioqueue = data;
954 while (!ioqueue->terminate) {
955 const pj_time_val delay = {0, 10};
957 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
959 pj_timer_heap_poll(ioqueue->timerheap, NULL);
965 /*! \brief Destroyer for ioqueue thread */
966 static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
968 if (ioqueue->thread) {
969 ioqueue->terminate = 1;
970 pj_thread_join(ioqueue->thread);
971 pj_thread_destroy(ioqueue->thread);
974 pj_pool_release(ioqueue->pool);
978 /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
979 static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
983 /* If nothing is using this ioqueue thread destroy it */
984 AST_LIST_LOCK(&ioqueues);
985 if ((ioqueue->count - 2) == 0) {
987 AST_LIST_REMOVE(&ioqueues, ioqueue, next);
989 AST_LIST_UNLOCK(&ioqueues);
995 rtp_ioqueue_thread_destroy(ioqueue);
998 /*! \brief Finder and allocator for an ioqueue thread */
999 static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
1001 struct ast_rtp_ioqueue_thread *ioqueue;
1004 AST_LIST_LOCK(&ioqueues);
1006 /* See if an ioqueue thread exists that can handle more */
1007 AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1008 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1013 /* If we found one bump it up and return it */
1015 ioqueue->count += 2;
1019 ioqueue = ast_calloc(1, sizeof(*ioqueue));
1024 ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1026 /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1027 * on a session at the same time
1029 if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1033 if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1037 pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1039 if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1043 if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1047 AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1049 /* Since this is being returned to an active session the count always starts at 2 */
1055 rtp_ioqueue_thread_destroy(ioqueue);
1059 AST_LIST_UNLOCK(&ioqueues);
1063 static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1064 enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1066 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1067 pj_turn_sock **turn_sock;
1068 const pj_turn_sock_cb *turn_cb;
1069 pj_turn_tp_type conn_type;
1071 pj_stun_auth_cred cred = { 0, };
1073 struct ast_sockaddr addr = { { 0, } };
1074 pj_stun_config stun_config;
1075 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1076 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1077 pj_turn_session_info info;
1078 struct ast_sockaddr local, loop;
1080 ast_rtp_instance_get_local_address(instance, &local);
1081 if (ast_sockaddr_is_ipv4(&local)) {
1082 ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1084 ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
1087 /* Determine what component we are requesting a TURN session for */
1088 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1089 turn_sock = &rtp->turn_rtp;
1090 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1091 conn_transport = TRANSPORT_TURN_RTP;
1092 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
1093 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1094 turn_sock = &rtp->turn_rtcp;
1095 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1096 conn_transport = TRANSPORT_TURN_RTCP;
1097 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&rtp->rtcp->us));
1102 if (transport == AST_TRANSPORT_UDP) {
1103 conn_type = PJ_TURN_TP_UDP;
1104 } else if (transport == AST_TRANSPORT_TCP) {
1105 conn_type = PJ_TURN_TP_TCP;
1111 ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1113 ast_mutex_lock(&rtp->lock);
1115 pj_turn_sock_destroy(*turn_sock);
1116 rtp->turn_state = PJ_TURN_STATE_NULL;
1117 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1118 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1121 ast_mutex_unlock(&rtp->lock);
1123 if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1124 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1125 if (!rtp->ioqueue) {
1130 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1132 if (pj_turn_sock_create(&stun_config, ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1133 turn_cb, NULL, instance, turn_sock) != PJ_SUCCESS) {
1134 ast_log(LOG_WARNING, "Could not create a TURN client socket\n");
1138 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1139 pj_strset2(&cred.data.static_cred.username, (char*)username);
1140 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1141 pj_strset2(&cred.data.static_cred.data, (char*)password);
1143 /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
1144 ast_mutex_lock(&rtp->lock);
1145 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1146 while (rtp->turn_state < PJ_TURN_STATE_READY) {
1147 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1149 ast_mutex_unlock(&rtp->lock);
1151 /* If a TURN session was allocated add it as a candidate */
1152 if (rtp->turn_state != PJ_TURN_STATE_READY) {
1156 pj_turn_sock_get_info(*turn_sock, &info);
1158 ast_rtp_ice_add_cand(rtp, component, conn_transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr,
1159 &info.relay_addr, &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1161 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1162 ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1163 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1164 ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1168 static char *generate_random_string(char *buf, size_t size)
1173 for (x=0; x<4; x++) {
1174 val[x] = ast_random();
1176 snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1181 /* ICE RTP Engine interface declaration */
1182 static struct ast_rtp_engine_ice ast_rtp_ice = {
1183 .set_authentication = ast_rtp_ice_set_authentication,
1184 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1185 .start = ast_rtp_ice_start,
1186 .stop = ast_rtp_ice_stop,
1187 .get_ufrag = ast_rtp_ice_get_ufrag,
1188 .get_password = ast_rtp_ice_get_password,
1189 .get_local_candidates = ast_rtp_ice_get_local_candidates,
1190 .ice_lite = ast_rtp_ice_lite,
1191 .set_role = ast_rtp_ice_set_role,
1192 .turn_request = ast_rtp_ice_turn_request,
1196 #ifdef HAVE_OPENSSL_SRTP
1197 static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1199 /* We don't want to actually verify the certificate so just accept what they have provided */
1203 static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1204 enum ast_rtp_dtls_setup setup)
1206 dtls->dtls_setup = setup;
1208 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1209 ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1213 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1214 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1217 BIO_set_mem_eof_return(dtls->read_bio, -1);
1219 if (!(dtls->write_bio = BIO_new(BIO_s_mem()))) {
1220 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1223 BIO_set_mem_eof_return(dtls->write_bio, -1);
1225 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1227 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1228 SSL_set_accept_state(dtls->ssl);
1230 SSL_set_connect_state(dtls->ssl);
1232 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1234 ast_mutex_init(&dtls->lock);
1235 dtls->timeout_timer = -1;
1240 if (dtls->read_bio) {
1241 BIO_free(dtls->read_bio);
1242 dtls->read_bio = NULL;
1245 if (dtls->write_bio) {
1246 BIO_free(dtls->write_bio);
1247 dtls->write_bio = NULL;
1251 SSL_free(dtls->ssl);
1257 static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1259 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1261 if (!rtp->ssl_ctx || !rtp->rtcp) {
1265 return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup);
1268 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
1270 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1273 if (!dtls_cfg->enabled) {
1277 if (!ast_rtp_engine_srtp_is_registered()) {
1278 ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
1286 if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
1290 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
1292 rtp->dtls_verify = dtls_cfg->verify;
1294 SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1295 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1296 dtls_verify_callback : NULL);
1298 if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
1299 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
1300 } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
1301 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
1303 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
1307 rtp->local_hash = dtls_cfg->hash;
1309 if (!ast_strlen_zero(dtls_cfg->certfile)) {
1310 char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
1314 unsigned int size, i;
1315 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1316 char *local_fingerprint = rtp->local_fingerprint;
1318 if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
1319 ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
1320 dtls_cfg->certfile, instance);
1324 if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
1325 !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
1326 ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
1331 if (!(certbio = BIO_new(BIO_s_file()))) {
1332 ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
1337 if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
1339 } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
1340 type = EVP_sha256();
1342 ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
1347 if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
1348 !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
1349 !X509_digest(cert, type, fingerprint, &size) ||
1351 ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
1352 dtls_cfg->certfile, instance);
1353 BIO_free_all(certbio);
1357 for (i = 0; i < size; i++) {
1358 sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
1359 local_fingerprint += 3;
1362 *(local_fingerprint-1) = 0;
1364 BIO_free_all(certbio);
1367 if (!ast_strlen_zero(dtls_cfg->cipher)) {
1368 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
1369 ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
1370 dtls_cfg->cipher, instance);
1375 if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
1376 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
1377 ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
1378 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
1383 rtp->rekey = dtls_cfg->rekey;
1384 rtp->suite = dtls_cfg->suite;
1386 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup);
1388 dtls_setup_rtcp(instance);
1394 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
1396 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1398 return !rtp->ssl_ctx ? 0 : 1;
1401 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
1403 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1405 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
1408 SSL_CTX_free(rtp->ssl_ctx);
1409 rtp->ssl_ctx = NULL;
1412 if (rtp->dtls.ssl) {
1413 SSL_free(rtp->dtls.ssl);
1414 rtp->dtls.ssl = NULL;
1415 ast_mutex_destroy(&rtp->dtls.lock);
1419 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
1421 if (rtp->rtcp->dtls.ssl) {
1422 SSL_free(rtp->rtcp->dtls.ssl);
1423 rtp->rtcp->dtls.ssl = NULL;
1424 ast_mutex_destroy(&rtp->rtcp->dtls.lock);
1429 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
1431 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1433 if (SSL_is_init_finished(rtp->dtls.ssl)) {
1434 SSL_shutdown(rtp->dtls.ssl);
1435 rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1438 if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
1439 SSL_shutdown(rtp->rtcp->dtls.ssl);
1440 rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1444 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
1446 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1448 return rtp->dtls.connection;
1451 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
1453 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1455 return rtp->dtls.dtls_setup;
1458 static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
1460 enum ast_rtp_dtls_setup old = *dtls_setup;
1463 case AST_RTP_DTLS_SETUP_ACTIVE:
1464 *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1466 case AST_RTP_DTLS_SETUP_PASSIVE:
1467 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1469 case AST_RTP_DTLS_SETUP_ACTPASS:
1470 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
1471 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
1472 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1475 case AST_RTP_DTLS_SETUP_HOLDCONN:
1476 *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
1479 /* This should never occur... if it does exit early as we don't know what state things are in */
1483 /* If the setup state did not change we go on as if nothing happened */
1484 if (old == *dtls_setup) {
1488 /* If they don't want us to establish a connection wait until later */
1489 if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
1493 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1494 SSL_set_connect_state(ssl);
1495 } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1496 SSL_set_accept_state(ssl);
1502 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
1504 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1506 if (rtp->dtls.ssl) {
1507 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
1510 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1511 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
1515 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
1517 char *tmp = ast_strdupa(fingerprint), *value;
1519 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1521 if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
1525 rtp->remote_hash = hash;
1527 while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
1528 sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
1532 static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
1534 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1536 return rtp->local_hash;
1539 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
1541 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1543 return rtp->local_fingerprint;
1546 /* DTLS RTP Engine interface declaration */
1547 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
1548 .set_configuration = ast_rtp_dtls_set_configuration,
1549 .active = ast_rtp_dtls_active,
1550 .stop = ast_rtp_dtls_stop,
1551 .reset = ast_rtp_dtls_reset,
1552 .get_connection = ast_rtp_dtls_get_connection,
1553 .get_setup = ast_rtp_dtls_get_setup,
1554 .set_setup = ast_rtp_dtls_set_setup,
1555 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
1556 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
1557 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
1562 /* RTP Engine Declaration */
1563 static struct ast_rtp_engine asterisk_rtp_engine = {
1566 .destroy = ast_rtp_destroy,
1567 .dtmf_begin = ast_rtp_dtmf_begin,
1568 .dtmf_end = ast_rtp_dtmf_end,
1569 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
1570 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
1571 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
1572 .update_source = ast_rtp_update_source,
1573 .change_source = ast_rtp_change_source,
1574 .write = ast_rtp_write,
1575 .read = ast_rtp_read,
1576 .prop_set = ast_rtp_prop_set,
1578 .remote_address_set = ast_rtp_remote_address_set,
1579 .red_init = rtp_red_init,
1580 .red_buffer = rtp_red_buffer,
1581 .local_bridge = ast_rtp_local_bridge,
1582 .get_stat = ast_rtp_get_stat,
1583 .dtmf_compatible = ast_rtp_dtmf_compatible,
1584 .stun_request = ast_rtp_stun_request,
1585 .stop = ast_rtp_stop,
1586 .qos = ast_rtp_qos_set,
1587 .sendcng = ast_rtp_sendcng,
1588 #ifdef HAVE_PJPROJECT
1589 .ice = &ast_rtp_ice,
1591 #ifdef HAVE_OPENSSL_SRTP
1592 .dtls = &ast_rtp_dtls,
1593 .activate = ast_rtp_activate,
1597 #ifdef HAVE_OPENSSL_SRTP
1598 static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
1600 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1602 /* If we are not acting as a client connecting to the remote side then
1603 * don't start the handshake as it will accomplish nothing and would conflict
1604 * with the handshake we receive from the remote side.
1606 if (!dtls->ssl || (dtls->dtls_setup != AST_RTP_DTLS_SETUP_ACTIVE)) {
1610 SSL_do_handshake(dtls->ssl);
1612 /* Since the handshake is started in a thread outside of the channel thread it's possible
1613 * for the response to be handled in the channel thread before we start the timeout timer.
1614 * To ensure this doesn't actually happen we hold the DTLS lock. The channel thread will
1615 * block until we're done at which point the timeout timer will be immediately stopped.
1617 ast_mutex_lock(&dtls->lock);
1618 dtls_srtp_check_pending(instance, rtp, rtcp);
1619 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
1620 ast_mutex_unlock(&dtls->lock);
1624 #ifdef HAVE_PJPROJECT
1625 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
1627 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
1629 struct ast_rtp_instance *instance = ice->user_data;
1630 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1632 if (status == PJ_SUCCESS) {
1633 struct ast_sockaddr remote_address;
1635 /* Symmetric RTP must be disabled for the remote address to not get overwritten */
1636 ast_rtp_instance_set_prop(instance, AST_RTP_PROPERTY_NAT, 0);
1638 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
1639 ast_rtp_instance_set_remote_address(instance, &remote_address);
1642 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
1646 #ifdef HAVE_OPENSSL_SRTP
1647 dtls_perform_handshake(instance, &rtp->dtls, 0);
1650 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
1658 rtp->strict_rtp_state = STRICT_RTP_LEARN;
1659 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
1662 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)
1664 struct ast_rtp_instance *instance = ice->user_data;
1665 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1667 /* 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
1669 if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
1670 rtp->passthrough = 1;
1671 } else if (transport_id == TRANSPORT_TURN_RTP) {
1672 rtp->rtp_passthrough = 1;
1673 } else if (transport_id == TRANSPORT_TURN_RTCP) {
1674 rtp->rtcp_passthrough = 1;
1678 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)
1680 struct ast_rtp_instance *instance = ice->user_data;
1681 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1682 pj_status_t status = PJ_EINVALIDOP;
1683 pj_ssize_t _size = (pj_ssize_t)size;
1685 if (transport_id == TRANSPORT_SOCKET_RTP) {
1686 /* Traffic is destined to go right out the RTP socket we already have */
1687 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1688 /* sendto on a connectionless socket should send all the data, or none at all */
1689 ast_assert(_size == size || status != PJ_SUCCESS);
1690 } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
1691 /* Traffic is destined to go right out the RTCP socket we already have */
1693 status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1694 /* sendto on a connectionless socket should send all the data, or none at all */
1695 ast_assert(_size == size || status != PJ_SUCCESS);
1697 status = PJ_SUCCESS;
1699 } else if (transport_id == TRANSPORT_TURN_RTP) {
1700 /* Traffic is going through the RTP TURN relay */
1701 if (rtp->turn_rtp) {
1702 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
1704 } else if (transport_id == TRANSPORT_TURN_RTCP) {
1705 /* Traffic is going through the RTCP TURN relay */
1706 if (rtp->turn_rtcp) {
1707 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
1714 /* ICE Session interface declaration */
1715 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
1716 .on_ice_complete = ast_rtp_on_ice_complete,
1717 .on_rx_data = ast_rtp_on_ice_rx_data,
1718 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
1721 /*! \brief Worker thread for timerheap */
1722 static int timer_worker_thread(void *data)
1724 pj_ioqueue_t *ioqueue;
1726 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
1730 while (!timer_terminate) {
1731 const pj_time_val delay = {0, 10};
1733 pj_timer_heap_poll(timer_heap, NULL);
1734 pj_ioqueue_poll(ioqueue, &delay);
1741 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
1746 if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
1748 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
1750 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
1757 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
1762 if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
1763 if (rtcpdebugport) {
1764 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
1766 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
1773 #ifdef HAVE_OPENSSL_SRTP
1774 static int dtls_srtp_handle_timeout(struct ast_rtp_instance *instance, int rtcp)
1776 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1777 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1778 struct timeval dtls_timeout;
1780 DTLSv1_handle_timeout(dtls->ssl);
1781 dtls_srtp_check_pending(instance, rtp, rtcp);
1783 /* If a timeout can't be retrieved then this recurring scheduled item must stop */
1784 if (!DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
1785 dtls->timeout_timer = -1;
1789 return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
1792 static int dtls_srtp_handle_rtp_timeout(const void *data)
1794 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1797 reschedule = dtls_srtp_handle_timeout(instance, 0);
1800 ao2_ref(instance, -1);
1806 static int dtls_srtp_handle_rtcp_timeout(const void *data)
1808 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1811 reschedule = dtls_srtp_handle_timeout(instance, 1);
1814 ao2_ref(instance, -1);
1820 static void dtls_srtp_start_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
1822 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1823 struct timeval dtls_timeout;
1825 if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
1826 int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
1828 ast_assert(dtls->timeout_timer == -1);
1830 ao2_ref(instance, +1);
1831 if ((dtls->timeout_timer = ast_sched_add(rtp->sched, timeout,
1832 !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout, instance)) < 0) {
1833 ao2_ref(instance, -1);
1834 ast_log(LOG_WARNING, "Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
1835 !rtcp ? "RTP" : "RTCP", instance);
1840 static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
1842 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1844 AST_SCHED_DEL_UNREF(rtp->sched, dtls->timeout_timer, ao2_ref(instance, -1));
1847 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
1849 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1852 if (!dtls->ssl || !dtls->write_bio) {
1856 pending = BIO_ctrl_pending(dtls->write_bio);
1859 char outgoing[pending];
1861 struct ast_sockaddr remote_address = { {0, } };
1865 ast_rtp_instance_get_remote_address(instance, &remote_address);
1867 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
1870 /* If we do not yet know an address to send this to defer it until we do */
1871 if (ast_sockaddr_isnull(&remote_address)) {
1875 out = BIO_read(dtls->write_bio, outgoing, sizeof(outgoing));
1876 __rtp_sendto(instance, outgoing, out, 0, &remote_address, rtcp, &ice, 0);
1880 static int dtls_srtp_renegotiate(const void *data)
1882 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1883 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1885 SSL_renegotiate(rtp->dtls.ssl);
1886 SSL_do_handshake(rtp->dtls.ssl);
1887 dtls_srtp_check_pending(instance, rtp, 0);
1889 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1890 SSL_renegotiate(rtp->rtcp->dtls.ssl);
1891 SSL_do_handshake(rtp->rtcp->dtls.ssl);
1892 dtls_srtp_check_pending(instance, rtp, 1);
1896 ao2_ref(instance, -1);
1901 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
1903 unsigned char material[SRTP_MASTER_LEN * 2];
1904 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
1905 struct ast_srtp_policy *local_policy, *remote_policy = NULL;
1906 struct ast_rtp_instance_stats stats = { 0, };
1909 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1910 if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
1913 if (!(certificate = SSL_get_peer_certificate(rtp->dtls.ssl))) {
1914 ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
1918 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1919 if (rtp->remote_fingerprint[0]) {
1921 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1924 if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
1926 } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
1927 type = EVP_sha256();
1929 ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
1933 if (!X509_digest(certificate, type, fingerprint, &size) ||
1935 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
1936 X509_free(certificate);
1937 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
1943 X509_free(certificate);
1946 /* Ensure that certificate verification was successful */
1947 if ((rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) && SSL_get_verify_result(rtp->dtls.ssl) != X509_V_OK) {
1948 ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
1953 /* Produce key information and set up SRTP */
1954 if (!SSL_export_keying_material(rtp->dtls.ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
1955 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
1960 /* Whether we are acting as a server or client determines where the keys/salts are */
1961 if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1962 local_key = material;
1963 remote_key = local_key + SRTP_MASTER_KEY_LEN;
1964 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
1965 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
1967 remote_key = material;
1968 local_key = remote_key + SRTP_MASTER_KEY_LEN;
1969 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
1970 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
1973 if (!(local_policy = res_srtp_policy->alloc())) {
1977 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
1978 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
1982 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
1983 ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1987 if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
1991 res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
1993 if (!(remote_policy = res_srtp_policy->alloc())) {
1997 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
1998 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
2002 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
2003 ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
2007 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
2009 if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
2010 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
2015 ao2_ref(instance, +1);
2016 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
2017 ao2_ref(instance, -1);
2025 /* policy->destroy() called even on success to release local reference to these resources */
2026 res_srtp_policy->destroy(local_policy);
2028 if (remote_policy) {
2029 res_srtp_policy->destroy(remote_policy);
2036 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
2039 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2040 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2042 #ifdef HAVE_PJPROJECT
2043 struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
2046 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
2050 #ifdef HAVE_OPENSSL_SRTP
2051 /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
2052 * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
2053 if ((*in >= 20) && (*in <= 63)) {
2054 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2057 /* If no SSL session actually exists terminate things */
2059 ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
2064 /* This mutex is locked so that this thread blocks until the dtls_perform_handshake function
2067 ast_mutex_lock(&dtls->lock);
2068 ast_mutex_unlock(&dtls->lock);
2070 /* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
2071 dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
2073 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
2074 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2075 dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2076 SSL_set_accept_state(dtls->ssl);
2079 dtls_srtp_check_pending(instance, rtp, rtcp);
2081 BIO_write(dtls->read_bio, buf, len);
2083 len = SSL_read(dtls->ssl, buf, len);
2085 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
2086 unsigned long error = ERR_get_error();
2087 ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
2088 instance, ERR_reason_error_string(error));
2092 dtls_srtp_check_pending(instance, rtp, rtcp);
2094 if (SSL_is_init_finished(dtls->ssl)) {
2095 /* Any further connections will be existing since this is now established */
2096 dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
2098 /* Use the keying material to set up key/salt information */
2099 res = dtls_srtp_setup(rtp, srtp, instance);
2102 /* Since we've sent additional traffic start the timeout timer for retransmission */
2103 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
2110 #ifdef HAVE_PJPROJECT
2111 if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
2112 /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
2113 * so it reflects the actual source and not the loopback
2116 ast_sockaddr_copy(sa, &rtp->rtcp->them);
2118 ast_rtp_instance_get_remote_address(instance, sa);
2120 } else if (rtp->ice) {
2121 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
2122 pj_sockaddr address;
2125 pj_thread_register_check();
2127 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
2129 status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
2130 rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
2131 pj_sockaddr_get_len(&address));
2132 if (status != PJ_SUCCESS) {
2135 pj_strerror(status, buf, sizeof(buf));
2136 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
2140 if (!rtp->passthrough) {
2143 rtp->passthrough = 0;
2147 if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
2154 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2156 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
2159 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2161 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
2164 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp)
2168 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2169 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2173 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
2177 #ifdef HAVE_PJPROJECT
2179 pj_thread_register_check();
2181 if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
2188 return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
2191 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2193 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
2196 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2198 return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
2201 static int rtp_get_rate(struct ast_format *format)
2203 /* For those wondering: due to a fluke in RFC publication, G.722 is advertised
2204 * as having a sample rate of 8kHz, while implementations must know that its
2205 * real rate is 16kHz. Seriously.
2207 return (ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) ? 8000 : (int)ast_format_get_sample_rate(format);
2210 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
2212 unsigned int interval;
2213 /*! \todo XXX Do a more reasonable calculation on this one
2214 * Look in RFC 3550 Section A.7 for an example*/
2215 interval = rtcpinterval;
2219 /*! \brief Calculate normal deviation */
2220 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
2222 normdev = normdev * sample_count + sample;
2225 return normdev / sample_count;
2228 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
2231 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
2232 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
2233 we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
2236 #define SQUARE(x) ((x) * (x))
2238 stddev = sample_count * stddev;
2242 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
2243 ( SQUARE(sample - normdev_curent) / sample_count );
2248 static int create_new_socket(const char *type, int af)
2250 int sock = socket(af, SOCK_DGRAM, 0);
2256 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2258 long flags = fcntl(sock, F_GETFL);
2259 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
2262 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2272 * \brief Initializes sequence values and probation for learning mode.
2273 * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
2275 * \param info The learning information to track
2276 * \param seq sequence number read from the rtp header to initialize the information with
2278 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
2280 info->max_seq = seq - 1;
2281 info->packets = learning_min_sequential;
2286 * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
2287 * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
2289 * \param info Structure tracking the learning progress of some address
2290 * \param seq sequence number read from the rtp header
2291 * \retval 0 if probation mode should exit for this address
2292 * \retval non-zero if probation mode should continue
2294 static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
2296 if (seq == info->max_seq + 1) {
2297 /* packet is in sequence */
2300 /* Sequence discontinuity; reset */
2301 info->packets = learning_min_sequential - 1;
2303 info->max_seq = seq;
2305 return (info->packets == 0);
2308 #ifdef HAVE_PJPROJECT
2309 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
2312 pj_sockaddr address[16];
2313 unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
2315 /* Add all the local interface IP addresses */
2316 if (ast_sockaddr_is_ipv4(addr)) {
2317 pj_enum_ip_interface(pj_AF_INET(), &count, address);
2318 } else if (ast_sockaddr_is_any(addr)) {
2319 pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
2321 pj_enum_ip_interface(pj_AF_INET6(), &count, address);
2324 for (pos = 0; pos < count; pos++) {
2325 pj_sockaddr_set_port(&address[pos], port);
2326 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
2327 pj_sockaddr_get_len(&address[pos]));
2330 /* If configured to use a STUN server to get our external mapped address do so */
2331 if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
2332 struct sockaddr_in answer;
2334 if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
2336 pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
2338 /* Use the first local host candidate as the base */
2339 pj_sockaddr_cp(&base, &address[0]);
2341 pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
2343 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
2344 &base, pj_sockaddr_get_len(&address[0]));
2348 /* If configured to use a TURN relay create a session and allocate */
2349 if (pj_strlen(&turnaddr)) {
2350 ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
2351 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
2358 * \brief Calculates the elapsed time from issue of the first tx packet in an
2359 * rtp session and a specified time
2361 * \param rtp pointer to the rtp struct with the transmitted rtp packet
2362 * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
2364 * \return time elapsed in milliseconds
2366 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2371 if (ast_tvzero(rtp->txcore)) {
2372 rtp->txcore = ast_tvnow();
2373 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2376 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2377 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
2382 return (unsigned int) ms;
2385 #ifdef HAVE_PJPROJECT
2388 * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
2390 * \param instance RTP instance for which the ICE session is being replaced
2391 * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
2392 * \param port port to use for adding RTP candidates to the ICE session
2393 * \param replace 0 when creating a new session, 1 when replacing a destroyed session
2395 * \retval 0 on success
2396 * \retval -1 on failure
2398 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
2399 int port, int replace)
2401 pj_stun_config stun_config;
2402 pj_str_t ufrag, passwd;
2403 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2405 ao2_cleanup(rtp->ice_local_candidates);
2406 rtp->ice_local_candidates = NULL;
2408 pj_thread_register_check();
2410 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
2412 ufrag = pj_str(rtp->local_ufrag);
2413 passwd = pj_str(rtp->local_passwd);
2415 /* Create an ICE session for ICE negotiation */
2416 if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
2417 &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &rtp->ice) == PJ_SUCCESS) {
2418 /* Make this available for the callbacks */
2419 rtp->ice->user_data = instance;
2421 /* Add all of the available candidates to the ICE session */
2422 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
2423 TRANSPORT_SOCKET_RTP);
2425 /* Only add the RTCP candidates to ICE when replacing the session. New sessions
2426 * handle this in a separate part of the setup phase */
2427 if (replace && rtp->rtcp) {
2428 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
2429 ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
2430 TRANSPORT_SOCKET_RTCP);
2441 static int ast_rtp_new(struct ast_rtp_instance *instance,
2442 struct ast_sched_context *sched, struct ast_sockaddr *addr,
2445 struct ast_rtp *rtp = NULL;
2448 /* Create a new RTP structure to hold all of our data */
2449 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
2453 /* Initialize synchronization aspects */
2454 ast_mutex_init(&rtp->lock);
2455 ast_cond_init(&rtp->cond, NULL);
2457 /* Set default parameters on the newly created RTP structure */
2458 rtp->ssrc = ast_random();
2459 rtp->seqno = ast_random() & 0xffff;
2460 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2462 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
2463 rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
2466 /* Create a new socket for us to listen on and use */
2468 create_new_socket("RTP",
2469 ast_sockaddr_is_ipv4(addr) ? AF_INET :
2470 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
2471 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
2476 /* Now actually find a free RTP port to use */
2477 x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
2482 ast_sockaddr_set_port(addr, x);
2483 /* Try to bind, this will tell us whether the port is available or not */
2484 if (!ast_bind(rtp->s, addr)) {
2485 ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
2486 ast_rtp_instance_set_local_address(instance, addr);
2492 x = (rtpstart + 1) & ~1;
2495 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
2496 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
2497 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
2504 #ifdef HAVE_PJPROJECT
2505 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
2506 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
2508 ast_rtp_instance_set_data(instance, rtp);
2509 #ifdef HAVE_PJPROJECT
2510 /* Create an ICE session for ICE negotiation */
2512 if (ice_create(instance, addr, x, 0)) {
2513 ast_log(LOG_NOTICE, "Failed to start ICE session\n");
2516 ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
2521 /* Record any information we may need */
2524 #ifdef HAVE_OPENSSL_SRTP
2528 rtp->f.subclass.format = ao2_bump(ast_format_none);
2529 rtp->lastrxformat = ao2_bump(ast_format_none);
2530 rtp->lasttxformat = ao2_bump(ast_format_none);
2535 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
2537 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2538 #ifdef HAVE_PJPROJECT
2539 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
2540 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
2543 #ifdef HAVE_OPENSSL_SRTP
2544 ast_rtp_dtls_stop(instance);
2547 /* Destroy the smoother that was smoothing out audio if present */
2548 if (rtp->smoother) {
2549 ast_smoother_free(rtp->smoother);
2552 /* Close our own socket so we no longer get packets */
2557 /* Destroy RTCP if it was being used */
2560 * It is not possible for there to be an active RTCP scheduler
2561 * entry at this point since it holds a reference to the
2562 * RTP instance while it's active.
2564 close(rtp->rtcp->s);
2565 ast_free(rtp->rtcp);
2568 /* Destroy RED if it was being used */
2570 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2574 #ifdef HAVE_PJPROJECT
2575 pj_thread_register_check();
2577 /* Destroy the RTP TURN relay if being used */
2578 ast_mutex_lock(&rtp->lock);
2579 if (rtp->turn_rtp) {
2580 pj_turn_sock_destroy(rtp->turn_rtp);
2581 rtp->turn_state = PJ_TURN_STATE_NULL;
2582 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2583 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2587 /* Destroy the RTCP TURN relay if being used */
2588 if (rtp->turn_rtcp) {
2589 pj_turn_sock_destroy(rtp->turn_rtcp);
2590 rtp->turn_state = PJ_TURN_STATE_NULL;
2591 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2592 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2595 ast_mutex_unlock(&rtp->lock);
2598 rtp_ioqueue_thread_remove(rtp->ioqueue);
2601 /* Destroy the ICE session if being used */
2603 pj_ice_sess_destroy(rtp->ice);
2606 /* Destroy any candidates */
2607 if (rtp->ice_local_candidates) {
2608 ao2_ref(rtp->ice_local_candidates, -1);
2611 if (rtp->ice_active_remote_candidates) {
2612 ao2_ref(rtp->ice_active_remote_candidates, -1);
2616 ao2_cleanup(rtp->lasttxformat);
2617 ao2_cleanup(rtp->lastrxformat);
2618 ao2_cleanup(rtp->f.subclass.format);
2620 /* Destroy synchronization items */
2621 ast_mutex_destroy(&rtp->lock);
2622 ast_cond_destroy(&rtp->cond);
2624 /* Finally destroy ourselves */
2630 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
2632 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2633 rtp->dtmfmode = dtmf_mode;
2637 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
2639 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2640 return rtp->dtmfmode;
2643 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
2645 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2646 struct ast_sockaddr remote_address = { {0,} };
2647 int hdrlen = 12, res = 0, i = 0, payload = 101;
2649 unsigned int *rtpheader = (unsigned int*)data;
2651 ast_rtp_instance_get_remote_address(instance, &remote_address);
2653 /* If we have no remote address information bail out now */
2654 if (ast_sockaddr_isnull(&remote_address)) {
2658 /* Convert given digit into what we want to transmit */
2659 if ((digit <= '9') && (digit >= '0')) {
2661 } else if (digit == '*') {
2663 } else if (digit == '#') {
2665 } else if ((digit >= 'A') && (digit <= 'D')) {
2666 digit = digit - 'A' + 12;
2667 } else if ((digit >= 'a') && (digit <= 'd')) {
2668 digit = digit - 'a' + 12;
2670 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2674 /* Grab the payload that they expect the RFC2833 packet to be received in */
2675 payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
2677 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2678 rtp->send_duration = 160;
2679 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2680 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
2682 /* Create the actual packet that we will be sending */
2683 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2684 rtpheader[1] = htonl(rtp->lastdigitts);
2685 rtpheader[2] = htonl(rtp->ssrc);
2687 /* Actually send the packet */
2688 for (i = 0; i < 2; i++) {
2691 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2692 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2694 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2695 ast_sockaddr_stringify(&remote_address),
2698 if (rtp_debug_test_addr(&remote_address)) {
2699 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2700 ast_sockaddr_stringify(&remote_address),
2701 ice ? " (via ICE)" : "",
2702 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2705 rtp->send_duration += 160;
2706 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2709 /* Record that we are in the process of sending a digit and information needed to continue doing so */
2710 rtp->sending_digit = 1;
2711 rtp->send_digit = digit;
2712 rtp->send_payload = payload;
2717 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
2719 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2720 struct ast_sockaddr remote_address = { {0,} };
2721 int hdrlen = 12, res = 0;
2723 unsigned int *rtpheader = (unsigned int*)data;
2726 ast_rtp_instance_get_remote_address(instance, &remote_address);
2728 /* Make sure we know where the other side is so we can send them the packet */
2729 if (ast_sockaddr_isnull(&remote_address)) {
2733 /* Actually create the packet we will be sending */
2734 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2735 rtpheader[1] = htonl(rtp->lastdigitts);
2736 rtpheader[2] = htonl(rtp->ssrc);
2737 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2739 /* Boom, send it on out */
2740 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2742 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2743 ast_sockaddr_stringify(&remote_address),
2747 if (rtp_debug_test_addr(&remote_address)) {
2748 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2749 ast_sockaddr_stringify(&remote_address),
2750 ice ? " (via ICE)" : "",
2751 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2754 /* And now we increment some values for the next time we swing by */
2756 rtp->send_duration += 160;
2757 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2762 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
2764 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2765 struct ast_sockaddr remote_address = { {0,} };
2766 int hdrlen = 12, res = -1, i = 0;
2768 unsigned int *rtpheader = (unsigned int*)data;
2769 unsigned int measured_samples;
2771 ast_rtp_instance_get_remote_address(instance, &remote_address);
2773 /* Make sure we know where the remote side is so we can send them the packet we construct */
2774 if (ast_sockaddr_isnull(&remote_address)) {
2778 /* Convert the given digit to the one we are going to send */
2779 if ((digit <= '9') && (digit >= '0')) {
2781 } else if (digit == '*') {
2783 } else if (digit == '#') {
2785 } else if ((digit >= 'A') && (digit <= 'D')) {
2786 digit = digit - 'A' + 12;
2787 } else if ((digit >= 'a') && (digit <= 'd')) {
2788 digit = digit - 'a' + 12;
2790 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2794 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2796 if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
2797 ast_debug(2, "Adjusting final end duration from %d to %u\n", rtp->send_duration, measured_samples);
2798 rtp->send_duration = measured_samples;
2801 /* Construct the packet we are going to send */
2802 rtpheader[1] = htonl(rtp->lastdigitts);
2803 rtpheader[2] = htonl(rtp->ssrc);
2804 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2805 rtpheader[3] |= htonl((1 << 23));
2807 /* Send it 3 times, that's the magical number */
2808 for (i = 0; i < 3; i++) {
2811 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2813 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2816 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2817 ast_sockaddr_stringify(&remote_address),
2821 if (rtp_debug_test_addr(&remote_address)) {
2822 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2823 ast_sockaddr_stringify(&remote_address),
2824 ice ? " (via ICE)" : "",
2825 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2832 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
2833 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2835 rtp->sending_digit = 0;
2836 rtp->send_digit = 0;
2841 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
2843 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
2846 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
2848 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2850 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2851 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2852 ast_debug(3, "Setting the marker bit due to a source update\n");
2857 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
2859 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2860 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2861 unsigned int ssrc = ast_random();
2864 ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
2868 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2869 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2871 ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
2874 ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
2875 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
2883 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
2885 unsigned int sec, usec, frac;
2886 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
2888 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
2893 static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
2895 tv->tv_sec = msw - 2208988800u;
2896 tv->tv_usec = ((lsw << 6) / 3650) - (lsw >> 12) - (lsw >> 8);
2899 static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
2900 unsigned int *lost_packets,
2903 unsigned int extended_seq_no;
2904 unsigned int expected_packets;
2905 unsigned int expected_interval;
2906 unsigned int received_interval;
2907 double rxlost_current;
2910 /* Compute statistics */
2911 extended_seq_no = rtp->cycles + rtp->lastrxseqno;
2912 expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
2913 if (rtp->rxcount > expected_packets) {
2914 expected_packets += rtp->rxcount - expected_packets;
2916 *lost_packets = expected_packets - rtp->rxcount;
2917 expected_interval = expected_packets - rtp->rtcp->expected_prior;
2918 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2919 lost_interval = expected_interval - received_interval;
2920 if (expected_interval == 0 || lost_interval <= 0) {
2923 *fraction_lost = (lost_interval << 8) / expected_interval;
2926 /* Update RTCP statistics */
2927 rtp->rtcp->received_prior = rtp->rxcount;
2928 rtp->rtcp->expected_prior = expected_packets;
2929 if (lost_interval <= 0) {
2930 rtp->rtcp->rxlost = 0;
2932 rtp->rtcp->rxlost = lost_interval;
2934 if (rtp->rtcp->rxlost_count == 0) {
2935 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2937 if (lost_interval < rtp->rtcp->minrxlost) {
2938 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2940 if (lost_interval > rtp->rtcp->maxrxlost) {
2941 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
2943 rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
2945 rtp->rtcp->rxlost_count);
2946 rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
2948 rtp->rtcp->normdev_rxlost,
2950 rtp->rtcp->rxlost_count);
2951 rtp->rtcp->normdev_rxlost = rxlost_current;
2952 rtp->rtcp->rxlost_count++;
2955 /*! \brief Send RTCP SR or RR report */
2956 static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
2958 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2959 RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
2963 unsigned int now_lsw;
2964 unsigned int now_msw;
2965 unsigned int *rtcpheader;
2966 unsigned int lost_packets;
2968 struct timeval dlsr = { 0, };
2970 int rate = rtp_get_rate(rtp->f.subclass.format);
2972 int header_offset = 0;
2973 char *str_remote_address;
2974 char *str_local_address;
2975 struct ast_sockaddr remote_address = { { 0, } };
2976 struct ast_sockaddr local_address = { { 0, } };
2977 struct ast_sockaddr real_remote_address = { { 0, } };
2978 struct ast_sockaddr real_local_address = { { 0, } };
2979 struct ast_rtp_rtcp_report_block *report_block = NULL;
2980 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
2981 ast_rtp_rtcp_report_alloc(rtp->themssrc ? 1 : 0),
2984 if (!rtp || !rtp->rtcp) {
2988 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
2989 /* RTCP was stopped. */
2997 /* Compute statistics */
2998 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
3000 gettimeofday(&now, NULL);
3001 rtcp_report->reception_report_count = rtp->themssrc ? 1 : 0;
3002 rtcp_report->ssrc = rtp->ssrc;
3003 rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
3005 rtcp_report->sender_information.ntp_timestamp = now;
3006 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
3007 rtcp_report->sender_information.packet_count = rtp->txcount;
3008 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
3011 if (rtp->themssrc) {
3012 report_block = ast_calloc(1, sizeof(*report_block));
3013 if (!report_block) {
3017 rtcp_report->report_block[0] = report_block;
3018 report_block->source_ssrc = rtp->themssrc;
3019 report_block->lost_count.fraction = (fraction_lost & 0xff);
3020 report_block->lost_count.packets = (lost_packets & 0xffffff);
3021 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
3022 report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
3023 report_block->lsr = rtp->rtcp->themrxlsr;
3024 /* If we haven't received an SR report, DLSR should be 0 */
3025 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
3026 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
3027 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
3030 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
3031 rtcpheader = (unsigned int *)bdata;
3032 rtcpheader[1] = htonl(rtcp_report->ssrc); /* Our SSRC */
3036 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
3037 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
3038 rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
3039 rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
3040 rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
3044 rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc); /* Their SSRC */
3045 rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
3046 rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
3047 rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
3048 rtcpheader[6 + header_offset] = htonl(report_block->lsr);
3049 rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
3052 rtcpheader[0] = htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
3053 | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
3055 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
3056 /* it can change mid call, and SDES can't) */
3057 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
3058 rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
3059 rtcpheader[(len/4)+2] = htonl(0x01 << 24);
3062 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
3063 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
3065 ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
3067 ast_sockaddr_stringify(&rtp->rtcp->them),
3072 /* Update RTCP SR/RR statistics */
3074 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
3075 rtp->rtcp->sr_count++;
3076 rtp->rtcp->lastsrtxcount = rtp->txcount;
3078 rtp->rtcp->rr_count++;
3081 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
3082 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
3083 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
3084 ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
3086 ast_verbose(" Sent(NTP): %u.%010u\n",
3087 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
3088 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
3089 ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
3090 ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
3091 ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
3094 ast_verbose(" Report block:\n");
3095 ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
3096 ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
3097 ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
3098 ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
3099 ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
3100 ast_verbose(" Their last SR: %u\n", report_block->lsr);
3101 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
3105 ast_rtp_instance_get_local_address(instance, &local_address);
3106 if (!ast_find_ourip(&real_local_address, &local_address, 0)) {
3107 str_local_address = ast_strdupa(ast_sockaddr_stringify(&real_local_address));
3109 str_local_address = ast_strdupa(ast_sockaddr_stringify(&local_address));
3112 if (!ast_find_ourip(&real_remote_address, &remote_address, 0)) {
3113 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&real_remote_address));
3115 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&remote_address));
3118 message_blob = ast_json_pack("{s: s, s: s}",
3119 "to", str_remote_address,
3120 "from", str_local_address);
3121 ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
3127 /*! \brief Write and RTCP packet to the far end
3128 * \note Decide if we are going to send an SR (with Reception Block) or RR
3129 * RR is sent if we have not sent any rtp packets in the previous interval */
3130 static int ast_rtcp_write(const void *data)
3132 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
3133 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3136 if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
3137 ao2_ref(instance, -1);
3141 if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
3143 res = ast_rtcp_write_report(instance, 1);
3146 res = ast_rtcp_write_report(instance, 0);
3151 * Not being rescheduled.
3153 ao2_ref(instance, -1);
3154 rtp->rtcp->schedid = -1;
3160 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
3162 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3164 unsigned int ms = calc_txstamp(rtp, &frame->delivery);
3165 struct ast_sockaddr remote_address = { {0,} };
3166 int rate = rtp_get_rate(frame->subclass.format) / 1000;
3168 if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
3169 frame->samples /= 2;
3172 if (rtp->sending_digit) {
3176 if (frame->frametype == AST_FRAME_VOICE) {
3177 pred = rtp->lastts + frame->samples;
3179 /* Re-calculate last TS */
3180 rtp->lastts = rtp->lastts + ms * rate;
3181 if (ast_tvzero(frame->delivery)) {
3182 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3183 and if so, go with our prediction */
3184 if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
3187 ast_debug(3, "Difference is %d, ms is %u\n", abs((int)rtp->lastts - pred), ms);
3191 } else if (frame->frametype == AST_FRAME_VIDEO) {
3192 mark = frame->subclass.frame_ending;
3193 pred = rtp->lastovidtimestamp + frame->samples;
3194 /* Re-calculate last TS */
3195 rtp->lastts = rtp->lastts + ms * 90;
3196 /* If it's close to our prediction, go for it */
3197 if (ast_tvzero(frame->delivery)) {
3198 if (abs((int)rtp->lastts - pred) < 7200) {
3200 rtp->lastovidtimestamp += frame->samples;
3202 ast_debug(3, "Difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
3203 rtp->lastovidtimestamp = rtp->lastts;
3207 pred = rtp->lastotexttimestamp + frame->samples;
3208 /* Re-calculate last TS */
3209 rtp->lastts = rtp->lastts + ms;
3210 /* If it's close to our prediction, go for it */
3211 if (ast_tvzero(frame->delivery)) {
3212 if (abs((int)rtp->lastts - pred) < 7200) {
3214 rtp->lastotexttimestamp += frame->samples;
3216 ast_debug(3, "Difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
3217 rtp->lastotexttimestamp = rtp->lastts;
3222 /* If we have been explicitly told to set the marker bit then do so */
3223 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
3225 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
3228 /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
3229 if (rtp->lastts > rtp->lastdigitts) {
3230 rtp->lastdigitts = rtp->lastts;
3233 if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
3234 rtp->lastts = frame->ts * rate;
3237 ast_rtp_instance_get_remote_address(instance, &remote_address);
3239 /* If we know the remote address construct a packet and send it out */
3240 if (!ast_sockaddr_isnull(&remote_address)) {
3241 int hdrlen = 12, res, ice;
3242 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
3244 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3245 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3246 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3248 if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
3249 if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3250 ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
3252 ast_sockaddr_stringify(&remote_address),
3254 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3255 /* Only give this error message once if we are not RTP debugging */
3257 ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
3258 ast_sockaddr_stringify(&remote_address));
3259 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
3263 rtp->txoctetcount += (res - hdrlen);
3265 if (rtp->rtcp && rtp->rtcp->schedid < 1) {
3266 ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
3267 ao2_ref(instance, +1);
3268 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
3269 if (rtp->rtcp->schedid < 0) {
3270 ao2_ref(instance, -1);
3271 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
3276 if (rtp_debug_test_addr(&remote_address)) {
3277 ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
3278 ast_sockaddr_stringify(&remote_address),
3279 ice ? " (via ICE)" : "",
3280 codec, rtp->seqno, rtp->lastts, res - hdrlen);
3289 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
3290 unsigned char *data = red->t140red.data.ptr;
3294 /* replace most aged generation */
3296 for (i = 1; i < red->num_gen+1; i++)
3299 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
3302 /* Store length of each generation and primary data length*/
3303 for (i = 0; i < red->num_gen; i++)
3304 red->len[i] = red->len[i+1];
3305 red->len[i] = red->t140.datalen;
3307 /* write each generation length in red header */
3309 for (i = 0; i < red->num_gen; i++) {
3310 len += data[i*4+3] = red->len[i];
3313 /* add primary data to buffer */
3314 memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
3315 red->t140red.datalen = len + red->t140.datalen;
3317 /* no primary data and no generations to send */
3318 if (len == red->hdrlen && !red->t140.datalen) {
3322 /* reset t.140 buffer */
3323 red->t140.datalen = 0;
3325 return &red->t140red;
3328 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
3330 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3331 struct ast_sockaddr remote_address = { {0,} };
3332 struct ast_format *format;
3335 ast_rtp_instance_get_remote_address(instance, &remote_address);
3337 /* If we don't actually know the remote address don't even bother doing anything */
3338 if (ast_sockaddr_isnull(&remote_address)) {
3339 ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
3343 /* VP8: is this a request to send a RTCP FIR? */
3344 if (frame->frametype == AST_FRAME_CONTROL && frame->subclass.integer == AST_CONTROL_VIDUPDATE) {
3345 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3346 unsigned int *rtcpheader;
3352 if (!rtp || !rtp->rtcp) {
3356 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
3363 /* Prepare RTCP FIR (PT=206, FMT=4) */
3364 rtp->rtcp->firseq++;
3365 if(rtp->rtcp->firseq == 256) {
3366 rtp->rtcp->firseq = 0;
3369 rtcpheader = (unsigned int *)bdata;
3370 rtcpheader[0] = htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((len/4)-1));
3371 rtcpheader[1] = htonl(rtp->ssrc);
3372 rtcpheader[2] = htonl(rtp->themssrc);
3373 rtcpheader[3] = htonl(rtp->themssrc); /* FCI: SSRC */
3374 rtcpheader[4] = htonl(rtp->rtcp->firseq << 24); /* FCI: Sequence number */
3375 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them, &ice);
3377 ast_log(LOG_ERROR, "RTCP FIR transmission error: %s\n", strerror(errno));
3382 /* If there is no data length we can't very well send the packet */
3383 if (!frame->datalen) {
3384 ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
3388 /* If the packet is not one our RTP stack supports bail out */
3389 if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
3390 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
3396 /* no primary data or generations to send */
3397 if ((frame = red_t140_to_red(rtp->red)) == NULL)
3401 /* Grab the subclass and look up the payload we are going to use */
3402 codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance),
3404 frame->subclass.format,
3407 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n",
3408 ast_format_get_name(frame->subclass.format));
3412 /* Note that we do not increase the ref count here as this pointer
3413 * will not be held by any thing explicitly. The format variable is
3414 * merely a convenience reference to frame->subclass.format */
3415 format = frame->subclass.format;
3416 if (ast_format_cmp(rtp->lasttxformat, format) == AST_FORMAT_CMP_NOT_EQUAL) {
3417 /* Oh dear, if the format changed we will have to set up a new smoother */
3418 if (option_debug > 0) {
3419 ast_debug(1, "Ooh, format changed from %s to %s\n",
3420 ast_format_get_name(rtp->lasttxformat),
3421 ast_format_get_name(frame->subclass.format));
3423 ao2_replace(rtp->lasttxformat, format);
3424 if (rtp->smoother) {
3425 ast_smoother_free(rtp->smoother);
3426 rtp->smoother = NULL;
3430 /* If no smoother is present see if we have to set one up */
3431 if (!rtp->smoother && ast_format_can_be_smoothed(format)) {
3432 unsigned int framing_ms = ast_rtp_codecs_get_framing(ast_rtp_instance_get_codecs(instance));
3435 rtp->smoother = ast_smoother_new((framing_ms * ast_format_get_minimum_bytes(format)) / ast_format_get_minimum_ms(format));
3436 if (!rtp->smoother) {
3437 ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %u len: %u\n",
3438 ast_format_get_name(format), framing_ms, ast_format_get_minimum_bytes(format));
3444 /* Feed audio frames into the actual function that will create a frame and send it */
3445 if (rtp->smoother) {
3446 struct ast_frame *f;
3448 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
3449 ast_smoother_feed_be(rtp->smoother, frame);
3451 ast_smoother_feed(rtp->smoother, frame);
3454 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
3455 ast_rtp_raw_write(instance, f, codec);
3459 struct ast_frame *f = NULL;
3461 if (frame->offset < hdrlen) {
3462 f = ast_frdup(frame);
3467 ast_rtp_raw_write(instance, f, codec);
3478 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
3483 double current_time;
3487 int rate = rtp_get_rate(rtp->f.subclass.format);
3489 double normdev_rxjitter_current;
3490 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
3491 gettimeofday(&rtp->rxcore, NULL);
3492 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
3493 /* map timestamp to a real time */
3494 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
3495 tmp = ast_samp2tv(timestamp, rate);
3496 rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
3497 /* Round to 0.1ms for nice, pretty timestamps */
3498 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
3501 gettimeofday(&now,NULL);
3502 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
3503 tmp = ast_samp2tv(timestamp, rate);
3504 *tv = ast_tvadd(rtp->rxcore, tmp);
3506 prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
3507 dtv = (double)rtp->drxcore + (double)(prog);
3508 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
3509 transit = current_time - dtv;
3510 d = transit - rtp->rxtransit;
3511 rtp->rxtransit = transit;
3515 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
3517 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
3518 rtp->rtcp->maxrxjitter = rtp->rxjitter;
3519 if (rtp->rtcp->rxjitter_count == 1)
3520 rtp->rtcp->minrxjitter = rtp->rxjitter;
3521 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
3522 rtp->rtcp->minrxjitter = rtp->rxjitter;
3524 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
3525 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
3527 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
3528 rtp->rtcp->rxjitter_count++;
3532 static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
3534 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3535 struct ast_sockaddr remote_address = { {0,} };
3537 ast_rtp_instance_get_remote_address(instance, &remote_address);
3539 if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
3540 ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
3541 ast_sockaddr_stringify(&remote_address));
3543 rtp->dtmfsamples = 0;
3544 return &ast_null_frame;
3546 ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
3547 type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
3548 rtp->resp, rtp->resp,
3549 ast_sockaddr_stringify(&remote_address));
3550 if (rtp->resp == 'X') {
3551 rtp->f.frametype = AST_FRAME_CONTROL;
3552 rtp->f.subclass.integer = AST_CONTROL_FLASH;
3554 rtp->f.frametype = type;
3555 rtp->f.subclass.integer = rtp->resp;
3561 AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
3566 static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
3568 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3569 struct ast_sockaddr remote_address = { {0,} };
3570 unsigned int event, event_end, samples;
3572 struct ast_frame *f = NULL;
3574 ast_rtp_instance_get_remote_address(instance, &remote_address);
3576 /* Figure out event, event end, and samples */
3577 event = ntohl(*((unsigned int *)(data)));
3579 event_end = ntohl(*((unsigned int *)(data)));
3582 samples = ntohl(*((unsigned int *)(data)));
3585 if (rtp_debug_test_addr(&remote_address)) {
3586 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",
3587 ast_sockaddr_stringify(&remote_address),
3588 payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
3591 /* Print out debug if turned on */
3593 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
3595 /* Figure out what digit was pressed */
3598 } else if (event < 11) {
3600 } else if (event < 12) {
3602 } else if (event < 16) {
3603 resp = 'A' + (event - 12);
3604 } else if (event < 17) { /* Event 16: Hook flash */
3607 /* Not a supported event */
3608 ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
3612 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
3613 if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
3615 rtp->dtmf_timeout = 0;
3616 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
3618 rtp->last_end_timestamp = timestamp;
3619 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3622 /* The duration parameter measures the complete
3623 duration of the event (from the beginning) - RFC2833.
3624 Account for the fact that duration is only 16 bits long
3625 (about 8 seconds at 8000 Hz) and can wrap is digit
3626 is hold for too long. */
3627 unsigned int new_duration = rtp->dtmf_duration;
3628 unsigned int last_duration = new_duration & 0xFFFF;
3630 if (last_duration > 64000 && samples < last_duration) {
3631 new_duration += 0xFFFF + 1;
3633 new_duration = (new_duration & ~0xFFFF) | samples;
3635 if (event_end & 0x80) {
3637 if ((rtp->last_seqno != seqno) && (timestamp > rtp->last_end_timestamp)) {
3638 rtp->last_end_timestamp = timestamp;
3639 rtp->dtmf_duration = new_duration;
3641 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
3642 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
3644 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
3645 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3646 } else if (rtpdebug) {
3647 ast_debug(1, "Dropping duplicate or out of order DTMF END frame (seqno: %u, ts %u, digit %c)\n",
3648 seqno, timestamp, resp);
3651 /* Begin/continuation */
3653 /* The second portion of the seqno check is to not mistakenly
3654 * stop accepting DTMF if the seqno rolls over beyond
3657 if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
3658 || timestamp <= rtp->last_end_timestamp) {
3659 /* Out of order frame. Processing this can cause us to
3660 * improperly duplicate incoming DTMF, so just drop
3664 ast_debug(1, "Dropping out of order DTMF frame (seqno %u, ts %u, digit %c)\n",
3665 seqno, timestamp, resp);
3670 if (rtp->resp && rtp->resp != resp) {
3671 /* Another digit already began. End it */
3672 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
3673 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.format)), ast_tv(0, 0));
3675 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
3676 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3680 /* Digit continues */
3681 rtp->dtmf_duration = new_duration;