[Asterisk-code-review] rtp engine/res rtp asterisk: Fix RTP struct reentrancy crashes. (asterisk[13])

Richard Mudgett asteriskteam at digium.com
Mon Mar 27 17:18:56 CDT 2017


Richard Mudgett has uploaded a new change for review. ( https://gerrit.asterisk.org/5341 )

Change subject: rtp_engine/res_rtp_asterisk: Fix RTP struct reentrancy crashes.
......................................................................

rtp_engine/res_rtp_asterisk: Fix RTP struct reentrancy crashes.

The struct ast_rtp_instance has historically been indirectly protected
from reentrancy issues by the channel lock because early channel drivers
held the lock for really long times.  Holding the channel lock for such a
long time has caused many deadlock problems in the past.  Along comes
chan_pjsip/res_pjsip which doesn't necessarily hold the channel lock
because sometimes there may not be an associated channel created yet or
the channel pointer isn't available.

In the case of ASTERISK-26835 a pjsip serializer thread was processing a
message's SDP body while another thread was reading a RTP packet from the
socket.  Both threads wound up changing the rtp->rtcp->local_addr_str
string and interfering with each other.  The classic reentrancy problem
resulted in a crash.

In the case of ASTERISK-26853 a pjsip serializer thread was processing a
message's SDP body while another thread was reading a RTP packet from the
socket.  Both threads wound up processing ICE candidates in pjproject and
interfering with each other.  The classic reentrancy problem resulted in a
crash.

* rtp_engine.c: Make the ast_rtp_instance_xxx() calls lock the RTP
instance struct.

* rtp_engine.c: Make ICE and DTLS wrapper functions to lock the RTP
instance struct for the API call.

* res_rtp_asterisk.c: Lock the RTP instance to prevent a reentrancy
problem with rtp->rtcp->local_addr_str in the scheduler thread running
ast_rtcp_write().

* res_rtp_asterisk.c: Avoid deadlock when local RTP bridging in
bridge_p2p_rtp_write() because there are two RTP instance structs
involved.

* res_rtp_asterisk.c: Avoid deadlock when trying to stop scheduler
callbacks.  We cannot hold the instance lock when trying to stop a
scheduler callback.

* res_rtp_asterisk.c: Remove the lock in struct dtls_details and use the
struct ast_rtp_instance ao2 object lock instead.  The lock was used to
synchronize two threads to prevent a race condition between starting and
stopping a timeout timer.  The race condition is no longer present between
dtls_perform_handshake() and __rtp_recvfrom() because the instance lock
prevents these functions from overlapping each other with regards to the
timeout timer.

* res_rtp_asterisk.c: Remove the lock in struct ast_rtp and use the struct
ast_rtp_instance ao2 object lock instead.  The lock was used to
synchronize two threads using a condition signal to know when TURN
negotiations complete.

ASTERISK-26835 #close
ASTERISK-26853 #close

Change-Id: I780b39ec935dcefcce880d50c1a7261744f1d1b4
---
M main/rtp_engine.c
M res/res_rtp_asterisk.c
2 files changed, 604 insertions(+), 90 deletions(-)


  git pull ssh://gerrit.asterisk.org:29418/asterisk refs/changes/41/5341/1

diff --git a/main/rtp_engine.c b/main/rtp_engine.c
index 0f09e2f..0214c78 100644
--- a/main/rtp_engine.c
+++ b/main/rtp_engine.c
@@ -376,9 +376,14 @@
 	struct ast_rtp_instance *instance = obj;
 
 	/* Pass us off to the engine to destroy */
-	if (instance->data && instance->engine->destroy(instance)) {
-		ast_debug(1, "Engine '%s' failed to destroy RTP instance '%p'\n", instance->engine->name, instance);
-		return;
+	if (instance->data) {
+		/*
+		 * Lock in case the RTP engine has other threads that
+		 * need synchronization with the destruction.
+		 */
+		ao2_lock(instance);
+		instance->engine->destroy(instance);
+		ao2_unlock(instance);
 	}
 
 	if (instance->srtp) {
@@ -453,12 +458,20 @@
 
 	ast_debug(1, "Using engine '%s' for RTP instance '%p'\n", engine->name, instance);
 
-	/* And pass it off to the engine to setup */
+	/*
+	 * And pass it off to the engine to setup
+	 *
+	 * Lock in case the RTP engine has other threads that
+	 * need synchronization with the construction.
+	 */
+	ao2_lock(instance);
 	if (instance->engine->new(instance, sched, &address, data)) {
 		ast_debug(1, "Engine '%s' failed to setup RTP instance '%p'\n", engine->name, instance);
+		ao2_unlock(instance);
 		ao2_ref(instance, -1);
 		return NULL;
 	}
+	ao2_unlock(instance);
 
 	ast_debug(1, "RTP instance '%p' is setup and ready to go\n", instance);
 
@@ -487,31 +500,48 @@
 
 int ast_rtp_instance_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
 {
-	return instance->engine->write(instance, frame);
+	int res;
+
+	ao2_lock(instance);
+	res = instance->engine->write(instance, frame);
+	ao2_unlock(instance);
+	return res;
 }
 
 struct ast_frame *ast_rtp_instance_read(struct ast_rtp_instance *instance, int rtcp)
 {
-	return instance->engine->read(instance, rtcp);
+	struct ast_frame *frame;
+
+	ao2_lock(instance);
+	frame = instance->engine->read(instance, rtcp);
+	ao2_unlock(instance);
+	return frame;
 }
 
 int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance,
 		const struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	ast_sockaddr_copy(&instance->local_address, address);
+	ao2_unlock(instance);
 	return 0;
 }
 
-int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance,
-						 const struct ast_sockaddr *address)
+static void rtp_instance_set_incoming_source_address_nolock(struct ast_rtp_instance *instance,
+	const struct ast_sockaddr *address)
 {
 	ast_sockaddr_copy(&instance->incoming_source_address, address);
-
-	/* moo */
-
 	if (instance->engine->remote_address_set) {
 		instance->engine->remote_address_set(instance, &instance->incoming_source_address);
 	}
+}
+
+int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance,
+	const struct ast_sockaddr *address)
+{
+	ao2_lock(instance);
+	rtp_instance_set_incoming_source_address_nolock(instance, address);
+	ao2_unlock(instance);
 
 	return 0;
 }
@@ -519,18 +549,26 @@
 int ast_rtp_instance_set_requested_target_address(struct ast_rtp_instance *instance,
 						  const struct ast_sockaddr *address)
 {
-	ast_sockaddr_copy(&instance->requested_target_address, address);
+	ao2_lock(instance);
 
-	return ast_rtp_instance_set_incoming_source_address(instance, address);
+	ast_sockaddr_copy(&instance->requested_target_address, address);
+	rtp_instance_set_incoming_source_address_nolock(instance, address);
+
+	ao2_unlock(instance);
+
+	return 0;
 }
 
 int ast_rtp_instance_get_and_cmp_local_address(struct ast_rtp_instance *instance,
 		struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	if (ast_sockaddr_cmp(address, &instance->local_address) != 0) {
 		ast_sockaddr_copy(address, &instance->local_address);
+		ao2_unlock(instance);
 		return 1;
 	}
+	ao2_unlock(instance);
 
 	return 0;
 }
@@ -538,16 +576,21 @@
 void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance,
 		struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	ast_sockaddr_copy(address, &instance->local_address);
+	ao2_unlock(instance);
 }
 
 int ast_rtp_instance_get_and_cmp_requested_target_address(struct ast_rtp_instance *instance,
 		struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	if (ast_sockaddr_cmp(address, &instance->requested_target_address) != 0) {
 		ast_sockaddr_copy(address, &instance->requested_target_address);
+		ao2_unlock(instance);
 		return 1;
 	}
+	ao2_unlock(instance);
 
 	return 0;
 }
@@ -555,43 +598,63 @@
 void ast_rtp_instance_get_incoming_source_address(struct ast_rtp_instance *instance,
 						  struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	ast_sockaddr_copy(address, &instance->incoming_source_address);
+	ao2_unlock(instance);
 }
 
 void ast_rtp_instance_get_requested_target_address(struct ast_rtp_instance *instance,
 						   struct ast_sockaddr *address)
 {
+	ao2_lock(instance);
 	ast_sockaddr_copy(address, &instance->requested_target_address);
+	ao2_unlock(instance);
 }
 
 void ast_rtp_instance_set_extended_prop(struct ast_rtp_instance *instance, int property, void *value)
 {
 	if (instance->engine->extended_prop_set) {
+		ao2_lock(instance);
 		instance->engine->extended_prop_set(instance, property, value);
+		ao2_unlock(instance);
 	}
 }
 
 void *ast_rtp_instance_get_extended_prop(struct ast_rtp_instance *instance, int property)
 {
+	void *prop;
+
 	if (instance->engine->extended_prop_get) {
-		return instance->engine->extended_prop_get(instance, property);
+		ao2_lock(instance);
+		prop = instance->engine->extended_prop_get(instance, property);
+		ao2_unlock(instance);
+	} else {
+		prop = NULL;
 	}
 
-	return NULL;
+	return prop;
 }
 
 void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
 {
+	ao2_lock(instance);
 	instance->properties[property] = value;
 
 	if (instance->engine->prop_set) {
 		instance->engine->prop_set(instance, property, value);
 	}
+	ao2_unlock(instance);
 }
 
 int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
 {
-	return instance->properties[property];
+	int prop;
+
+	ao2_lock(instance);
+	prop = instance->properties[property];
+	ao2_unlock(instance);
+
+	return prop;
 }
 
 struct ast_rtp_codecs *ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
@@ -632,9 +695,12 @@
 
 	if (instance && instance->engine && instance->engine->payload_set) {
 		int i;
+
+		ao2_lock(instance);
 		for (i = 0; i < AST_RTP_MAX_PT; i++) {
 			instance->engine->payload_set(instance, i, 0, NULL, 0);
 		}
+		ao2_unlock(instance);
 	}
 }
 
@@ -660,7 +726,9 @@
 		AST_VECTOR_REPLACE(&dest->payloads, i, type);
 
 		if (instance && instance->engine && instance->engine->payload_set) {
+			ao2_lock(instance);
 			instance->engine->payload_set(instance, i, type->asterisk_format, type->format, type->rtp_code);
+			ao2_unlock(instance);
 		}
 	}
 	dest->framing = src->framing;
@@ -696,7 +764,9 @@
 	AST_VECTOR_REPLACE(&codecs->payloads, payload, new_type);
 
 	if (instance && instance->engine && instance->engine->payload_set) {
+		ao2_lock(instance);
 		instance->engine->payload_set(instance, payload, new_type->asterisk_format, new_type->format, new_type->rtp_code);
+		ao2_unlock(instance);
 	}
 
 	ast_rwlock_unlock(&codecs->codecs_lock);
@@ -764,7 +834,9 @@
 		AST_VECTOR_REPLACE(&codecs->payloads, pt, new_type);
 
 		if (instance && instance->engine && instance->engine->payload_set) {
+			ao2_lock(instance);
 			instance->engine->payload_set(instance, pt, new_type->asterisk_format, new_type->format, new_type->rtp_code);
+			ao2_unlock(instance);
 		}
 
 		break;
@@ -798,7 +870,9 @@
 	}
 
 	if (instance && instance->engine && instance->engine->payload_set) {
+		ao2_lock(instance);
 		instance->engine->payload_set(instance, payload, 0, NULL, 0);
+		ao2_unlock(instance);
 	}
 
 	ast_rwlock_unlock(&codecs->codecs_lock);
@@ -1077,57 +1151,127 @@
 
 int ast_rtp_instance_dtmf_begin(struct ast_rtp_instance *instance, char digit)
 {
-	return instance->engine->dtmf_begin ? instance->engine->dtmf_begin(instance, digit) : -1;
+	int res;
+
+	if (instance->engine->dtmf_begin) {
+		ao2_lock(instance);
+		res = instance->engine->dtmf_begin(instance, digit);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 int ast_rtp_instance_dtmf_end(struct ast_rtp_instance *instance, char digit)
 {
-	return instance->engine->dtmf_end ? instance->engine->dtmf_end(instance, digit) : -1;
+	int res;
+
+	if (instance->engine->dtmf_end) {
+		ao2_lock(instance);
+		res = instance->engine->dtmf_end(instance, digit);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
+
 int ast_rtp_instance_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
 {
-	return instance->engine->dtmf_end_with_duration ? instance->engine->dtmf_end_with_duration(instance, digit, duration) : -1;
+	int res;
+
+	if (instance->engine->dtmf_end_with_duration) {
+		ao2_lock(instance);
+		res = instance->engine->dtmf_end_with_duration(instance, digit, duration);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 int ast_rtp_instance_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
 {
-	return (!instance->engine->dtmf_mode_set || instance->engine->dtmf_mode_set(instance, dtmf_mode)) ? -1 : 0;
+	int res;
+
+	if (instance->engine->dtmf_mode_set) {
+		ao2_lock(instance);
+		res = instance->engine->dtmf_mode_set(instance, dtmf_mode);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 enum ast_rtp_dtmf_mode ast_rtp_instance_dtmf_mode_get(struct ast_rtp_instance *instance)
 {
-	return instance->engine->dtmf_mode_get ? instance->engine->dtmf_mode_get(instance) : 0;
+	int res;
+
+	if (instance->engine->dtmf_mode_get) {
+		ao2_lock(instance);
+		res = instance->engine->dtmf_mode_get(instance);
+		ao2_unlock(instance);
+	} else {
+		res = 0;
+	}
+	return res;
 }
 
 void ast_rtp_instance_update_source(struct ast_rtp_instance *instance)
 {
 	if (instance->engine->update_source) {
+		ao2_lock(instance);
 		instance->engine->update_source(instance);
+		ao2_unlock(instance);
 	}
 }
 
 void ast_rtp_instance_change_source(struct ast_rtp_instance *instance)
 {
 	if (instance->engine->change_source) {
+		ao2_lock(instance);
 		instance->engine->change_source(instance);
+		ao2_unlock(instance);
 	}
 }
 
 int ast_rtp_instance_set_qos(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
 {
-	return instance->engine->qos ? instance->engine->qos(instance, tos, cos, desc) : -1;
+	int res;
+
+	if (instance->engine->qos) {
+		ao2_lock(instance);
+		res = instance->engine->qos(instance, tos, cos, desc);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 void ast_rtp_instance_stop(struct ast_rtp_instance *instance)
 {
 	if (instance->engine->stop) {
+		ao2_lock(instance);
 		instance->engine->stop(instance);
+		ao2_unlock(instance);
 	}
 }
 
 int ast_rtp_instance_fd(struct ast_rtp_instance *instance, int rtcp)
 {
-	return instance->engine->fd ? instance->engine->fd(instance, rtcp) : -1;
+	int res;
+
+	if (instance->engine->fd) {
+		ao2_lock(instance);
+		res = instance->engine->fd(instance, rtcp);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 struct ast_rtp_glue *ast_rtp_instance_get_glue(const char *type)
@@ -1160,12 +1304,19 @@
 
 struct ast_rtp_instance *ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
 {
-	return instance->bridged;
+	struct ast_rtp_instance *bridged;
+
+	ao2_lock(instance);
+	bridged = instance->bridged;
+	ao2_unlock(instance);
+	return bridged;
 }
 
 void ast_rtp_instance_set_bridged(struct ast_rtp_instance *instance, struct ast_rtp_instance *bridged)
 {
+	ao2_lock(instance);
 	instance->bridged = bridged;
+	ao2_unlock(instance);
 }
 
 void ast_rtp_instance_early_bridge_make_compatible(struct ast_channel *c_dst, struct ast_channel *c_src)
@@ -1337,17 +1488,44 @@
 
 int ast_rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
 {
-	return instance->engine->red_init ? instance->engine->red_init(instance, buffer_time, payloads, generations) : -1;
+	int res;
+
+	if (instance->engine->red_init) {
+		ao2_lock(instance);
+		res = instance->engine->red_init(instance, buffer_time, payloads, generations);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 int ast_rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
 {
-	return instance->engine->red_buffer ? instance->engine->red_buffer(instance, frame) : -1;
+	int res;
+
+	if (instance->engine->red_buffer) {
+		ao2_lock(instance);
+		res = instance->engine->red_buffer(instance, frame);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 int ast_rtp_instance_get_stats(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
 {
-	return instance->engine->get_stat ? instance->engine->get_stat(instance, stats, stat) : -1;
+	int res;
+
+	if (instance->engine->get_stat) {
+		ao2_lock(instance);
+		res = instance->engine->get_stat(instance, stats, stat);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 char *ast_rtp_instance_get_quality(struct ast_rtp_instance *instance, enum ast_rtp_instance_stat_field field, char *buf, size_t size)
@@ -1452,14 +1630,33 @@
 
 int ast_rtp_instance_set_read_format(struct ast_rtp_instance *instance, struct ast_format *format)
 {
-	return instance->engine->set_read_format ? instance->engine->set_read_format(instance, format) : -1;
+	int res;
+
+	if (instance->engine->set_read_format) {
+		ao2_lock(instance);
+		res = instance->engine->set_read_format(instance, format);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
 int ast_rtp_instance_set_write_format(struct ast_rtp_instance *instance, struct ast_format *format)
 {
-	return instance->engine->set_write_format ? instance->engine->set_write_format(instance, format) : -1;
+	int res;
+
+	if (instance->engine->set_read_format) {
+		ao2_lock(instance);
+		res = instance->engine->set_write_format(instance, format);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
 
+/* XXX Nothing calls this */
 int ast_rtp_instance_make_compatible(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_channel *peer)
 {
 	struct ast_rtp_glue *glue;
@@ -1490,6 +1687,10 @@
 		return -1;
 	}
 
+	/*
+	 * XXX Good thing nothing calls this function because we would need
+	 * deadlock avoidance to get the two instance locks.
+	 */
 	res = instance->engine->make_compatible(chan, instance, peer, peer_instance);
 
 	ast_channel_unlock(peer);
@@ -1503,7 +1704,9 @@
 void ast_rtp_instance_available_formats(struct ast_rtp_instance *instance, struct ast_format_cap *to_endpoint, struct ast_format_cap *to_asterisk, struct ast_format_cap *result)
 {
 	if (instance->engine->available_formats) {
+		ao2_lock(instance);
 		instance->engine->available_formats(instance, to_endpoint, to_asterisk, result);
+		ao2_unlock(instance);
 		if (ast_format_cap_count(result)) {
 			return;
 		}
@@ -1514,7 +1717,16 @@
 
 int ast_rtp_instance_activate(struct ast_rtp_instance *instance)
 {
-	return instance->engine->activate ? instance->engine->activate(instance) : 0;
+	int res;
+
+	if (instance->engine->activate) {
+		ao2_lock(instance);
+		res = instance->engine->activate(instance);
+		ao2_unlock(instance);
+	} else {
+		res = 0;
+	}
+	return res;
 }
 
 void ast_rtp_instance_stun_request(struct ast_rtp_instance *instance,
@@ -1522,7 +1734,9 @@
 				   const char *username)
 {
 	if (instance->engine->stun_request) {
+		ao2_lock(instance);
 		instance->engine->stun_request(instance, suggestion, username);
+		ao2_unlock(instance);
 	}
 }
 
@@ -1620,29 +1834,250 @@
 {
 	if (rtcp && instance->rtcp_srtp) {
 		return instance->rtcp_srtp;
-	}
-	else {
+	} else {
 		return instance->srtp;
 	}
 }
 
 int ast_rtp_instance_sendcng(struct ast_rtp_instance *instance, int level)
 {
-	if (instance->engine->sendcng) {
-		return instance->engine->sendcng(instance, level);
-	}
+	int res;
 
-	return -1;
+	if (instance->engine->sendcng) {
+		ao2_lock(instance);
+		res = instance->engine->sendcng(instance, level);
+		ao2_unlock(instance);
+	} else {
+		res = -1;
+	}
+	return res;
 }
+
+static void rtp_ice_wrap_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
+{
+	ao2_lock(instance);
+	instance->engine->ice->set_authentication(instance, ufrag, password);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
+{
+	ao2_lock(instance);
+	instance->engine->ice->add_remote_candidate(instance, candidate);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_start(struct ast_rtp_instance *instance)
+{
+	ao2_lock(instance);
+	instance->engine->ice->start(instance);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_stop(struct ast_rtp_instance *instance)
+{
+	ao2_lock(instance);
+	instance->engine->ice->stop(instance);
+	ao2_unlock(instance);
+}
+
+static const char *rtp_ice_wrap_get_ufrag(struct ast_rtp_instance *instance)
+{
+	const char *ufrag;
+
+	ao2_lock(instance);
+	ufrag = instance->engine->ice->get_ufrag(instance);
+	ao2_unlock(instance);
+	return ufrag;
+}
+
+static const char *rtp_ice_wrap_get_password(struct ast_rtp_instance *instance)
+{
+	const char *password;
+
+	ao2_lock(instance);
+	password = instance->engine->ice->get_password(instance);
+	ao2_unlock(instance);
+	return password;
+}
+
+static struct ao2_container *rtp_ice_wrap_get_local_candidates(struct ast_rtp_instance *instance)
+{
+	struct ao2_container *local_candidates;
+
+	ao2_lock(instance);
+	local_candidates = instance->engine->ice->get_local_candidates(instance);
+	ao2_unlock(instance);
+	return local_candidates;
+}
+
+static void rtp_ice_wrap_ice_lite(struct ast_rtp_instance *instance)
+{
+	ao2_lock(instance);
+	instance->engine->ice->ice_lite(instance);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_set_role(struct ast_rtp_instance *instance,
+	enum ast_rtp_ice_role role)
+{
+	ao2_lock(instance);
+	instance->engine->ice->set_role(instance, role);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_turn_request(struct ast_rtp_instance *instance,
+	enum ast_rtp_ice_component_type component, enum ast_transport transport,
+	const char *server, unsigned int port, const char *username, const char *password)
+{
+	ao2_lock(instance);
+	instance->engine->ice->turn_request(instance, component, transport, server, port,
+		username, password);
+	ao2_unlock(instance);
+}
+
+static void rtp_ice_wrap_change_components(struct ast_rtp_instance *instance,
+	int num_components)
+{
+	ao2_lock(instance);
+	instance->engine->ice->change_components(instance, num_components);
+	ao2_unlock(instance);
+}
+
+static struct ast_rtp_engine_ice rtp_ice_wrappers = {
+	.set_authentication = rtp_ice_wrap_set_authentication,
+	.add_remote_candidate = rtp_ice_wrap_add_remote_candidate,
+	.start = rtp_ice_wrap_start,
+	.stop = rtp_ice_wrap_stop,
+	.get_ufrag = rtp_ice_wrap_get_ufrag,
+	.get_password = rtp_ice_wrap_get_password,
+	.get_local_candidates = rtp_ice_wrap_get_local_candidates,
+	.ice_lite = rtp_ice_wrap_ice_lite,
+	.set_role = rtp_ice_wrap_set_role,
+	.turn_request = rtp_ice_wrap_turn_request,
+	.change_components = rtp_ice_wrap_change_components,
+};
 
 struct ast_rtp_engine_ice *ast_rtp_instance_get_ice(struct ast_rtp_instance *instance)
 {
-	return instance->engine->ice;
+	if (instance->engine->ice) {
+		return &rtp_ice_wrappers;
+	}
+	/* ICE not available */
+	return NULL;
 }
+
+static int rtp_dtls_wrap_set_configuration(struct ast_rtp_instance *instance,
+	const struct ast_rtp_dtls_cfg *dtls_cfg)
+{
+	int set_configuration;
+
+	ao2_lock(instance);
+	set_configuration = instance->engine->dtls->set_configuration(instance, dtls_cfg);
+	ao2_unlock(instance);
+	return set_configuration;
+}
+
+static int rtp_dtls_wrap_active(struct ast_rtp_instance *instance)
+{
+	int active;
+
+	ao2_lock(instance);
+	active = instance->engine->dtls->active(instance);
+	ao2_unlock(instance);
+	return active;
+}
+
+static void rtp_dtls_wrap_stop(struct ast_rtp_instance *instance)
+{
+	ao2_lock(instance);
+	instance->engine->dtls->stop(instance);
+	ao2_unlock(instance);
+}
+
+static void rtp_dtls_wrap_reset(struct ast_rtp_instance *instance)
+{
+	ao2_lock(instance);
+	instance->engine->dtls->reset(instance);
+	ao2_unlock(instance);
+}
+
+static enum ast_rtp_dtls_connection rtp_dtls_wrap_get_connection(struct ast_rtp_instance *instance)
+{
+	enum ast_rtp_dtls_connection get_connection;
+
+	ao2_lock(instance);
+	get_connection = instance->engine->dtls->get_connection(instance);
+	ao2_unlock(instance);
+	return get_connection;
+}
+
+static enum ast_rtp_dtls_setup rtp_dtls_wrap_get_setup(struct ast_rtp_instance *instance)
+{
+	enum ast_rtp_dtls_setup get_setup;
+
+	ao2_lock(instance);
+	get_setup = instance->engine->dtls->get_setup(instance);
+	ao2_unlock(instance);
+	return get_setup;
+}
+
+static void rtp_dtls_wrap_set_setup(struct ast_rtp_instance *instance,
+	enum ast_rtp_dtls_setup setup)
+{
+	ao2_lock(instance);
+	instance->engine->dtls->set_setup(instance, setup);
+	ao2_unlock(instance);
+}
+
+static void rtp_dtls_wrap_set_fingerprint(struct ast_rtp_instance *instance,
+	enum ast_rtp_dtls_hash hash, const char *fingerprint)
+{
+	ao2_lock(instance);
+	instance->engine->dtls->set_fingerprint(instance, hash, fingerprint);
+	ao2_unlock(instance);
+}
+
+static enum ast_rtp_dtls_hash rtp_dtls_wrap_get_fingerprint_hash(struct ast_rtp_instance *instance)
+{
+	enum ast_rtp_dtls_hash get_fingerprint_hash;
+
+	ao2_lock(instance);
+	get_fingerprint_hash = instance->engine->dtls->get_fingerprint_hash(instance);
+	ao2_unlock(instance);
+	return get_fingerprint_hash;
+}
+
+static const char *rtp_dtls_wrap_get_fingerprint(struct ast_rtp_instance *instance)
+{
+	const char *get_fingerprint;
+
+	ao2_lock(instance);
+	get_fingerprint = instance->engine->dtls->get_fingerprint(instance);
+	ao2_unlock(instance);
+	return get_fingerprint;
+}
+
+static struct ast_rtp_engine_dtls rtp_dtls_wrappers = {
+	.set_configuration = rtp_dtls_wrap_set_configuration,
+	.active = rtp_dtls_wrap_active,
+	.stop = rtp_dtls_wrap_stop,
+	.reset = rtp_dtls_wrap_reset,
+	.get_connection = rtp_dtls_wrap_get_connection,
+	.get_setup = rtp_dtls_wrap_get_setup,
+	.set_setup = rtp_dtls_wrap_set_setup,
+	.set_fingerprint = rtp_dtls_wrap_set_fingerprint,
+	.get_fingerprint_hash = rtp_dtls_wrap_get_fingerprint_hash,
+	.get_fingerprint = rtp_dtls_wrap_get_fingerprint,
+};
 
 struct ast_rtp_engine_dtls *ast_rtp_instance_get_dtls(struct ast_rtp_instance *instance)
 {
-	return instance->engine->dtls;
+	if (instance->engine->dtls) {
+		return &rtp_dtls_wrappers;
+	}
+	/* DTLS not available */
+	return NULL;
 }
 
 int ast_rtp_dtls_cfg_parse(struct ast_rtp_dtls_cfg *dtls_cfg, const char *name, const char *value)
diff --git a/res/res_rtp_asterisk.c b/res/res_rtp_asterisk.c
index d681fea..6d6b281 100644
--- a/res/res_rtp_asterisk.c
+++ b/res/res_rtp_asterisk.c
@@ -219,7 +219,6 @@
 
 #ifdef HAVE_OPENSSL_SRTP
 struct dtls_details {
-	ast_mutex_t lock; /*!< Lock for timeout timer synchronization */
 	SSL *ssl;         /*!< SSL session */
 	BIO *read_bio;    /*!< Memory buffer for reading */
 	BIO *write_bio;   /*!< Memory buffer for writing */
@@ -304,10 +303,9 @@
 
 	struct rtp_red *red;
 
-	ast_mutex_t lock;           /*!< Lock for synchronization purposes */
-	ast_cond_t cond;            /*!< Condition for signaling */
-
 #ifdef HAVE_PJPROJECT
+	ast_cond_t cond;            /*!< ICE/TURN condition for signaling */
+
 	pj_ice_sess *ice;           /*!< ICE session */
 	pj_turn_sock *turn_rtp;     /*!< RTP TURN relay */
 	pj_turn_sock *turn_rtcp;    /*!< RTCP TURN relay */
@@ -669,13 +667,12 @@
 		struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
 		struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
 
-		ast_mutex_lock(&rtp->lock);
+		/* The instance lock is already held. */
 		pj_turn_sock_destroy(rtp->turn_rtcp);
 		rtp->turn_state = PJ_TURN_STATE_NULL;
 		while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
-			ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
+			ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
 		}
-		ast_mutex_unlock(&rtp->lock);
 	}
 
 	return res;
@@ -939,6 +936,7 @@
 	ao2_ref(candidate, -1);
 }
 
+/* PJPROJECT TURN callback */
 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)
 {
 	struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
@@ -963,6 +961,7 @@
 	ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
 }
 
+/* PJPROJECT TURN callback */
 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)
 {
 	struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
@@ -975,8 +974,9 @@
 
 	rtp = ast_rtp_instance_get_data(instance);
 
+	ao2_lock(instance);
+
 	/* We store the new state so the other thread can actually handle it */
-	ast_mutex_lock(&rtp->lock);
 	rtp->turn_state = new_state;
 	ast_cond_signal(&rtp->cond);
 
@@ -985,7 +985,7 @@
 		rtp->turn_rtp = NULL;
 	}
 
-	ast_mutex_unlock(&rtp->lock);
+	ao2_unlock(instance);
 }
 
 /* RTP TURN Socket interface declaration */
@@ -994,6 +994,7 @@
 	.on_state = ast_rtp_on_turn_rtp_state,
 };
 
+/* PJPROJECT TURN callback */
 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)
 {
 	struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
@@ -1018,10 +1019,11 @@
 	ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
 }
 
+/* PJPROJECT TURN callback */
 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)
 {
 	struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
-	struct ast_rtp *rtp = NULL;
+	struct ast_rtp *rtp;
 
 	/* If this is a leftover from an already destroyed RTP instance just ignore the state change */
 	if (!instance) {
@@ -1030,8 +1032,9 @@
 
 	rtp = ast_rtp_instance_get_data(instance);
 
+	ao2_lock(instance);
+
 	/* We store the new state so the other thread can actually handle it */
-	ast_mutex_lock(&rtp->lock);
 	rtp->turn_state = new_state;
 	ast_cond_signal(&rtp->cond);
 
@@ -1040,7 +1043,7 @@
 		rtp->turn_rtcp = NULL;
 	}
 
-	ast_mutex_unlock(&rtp->lock);
+	ao2_unlock(instance);
 }
 
 /* RTCP TURN Socket interface declaration */
@@ -1222,15 +1225,14 @@
 
 	ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
 
-	ast_mutex_lock(&rtp->lock);
 	if (*turn_sock) {
+		/* The instance lock is already held. */
 		pj_turn_sock_destroy(*turn_sock);
 		rtp->turn_state = PJ_TURN_STATE_NULL;
 		while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
-			ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
+			ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
 		}
 	}
-	ast_mutex_unlock(&rtp->lock);
 
 	if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
 		rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
@@ -1252,13 +1254,16 @@
 	cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
 	pj_strset2(&cred.data.static_cred.data, (char*)password);
 
-	/* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
-	ast_mutex_lock(&rtp->lock);
+	/*
+	 * Because the TURN socket is asynchronous but we are synchronous we need to
+	 * wait until it is done
+	 *
+	 * The instance lock is already held.
+	 */
 	pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
 	while (rtp->turn_state < PJ_TURN_STATE_READY) {
-		ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
+		ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
 	}
-	ast_mutex_unlock(&rtp->lock);
 
 	/* If a TURN session was allocated add it as a candidate */
 	if (rtp->turn_state != PJ_TURN_STATE_READY) {
@@ -1358,8 +1363,6 @@
 		SSL_set_connect_state(dtls->ssl);
 	}
 	dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
-
-	ast_mutex_init(&dtls->lock);
 
 	return 0;
 
@@ -1579,7 +1582,9 @@
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
 	SSL *ssl = rtp->dtls.ssl;
 
+	ao2_unlock(instance);
 	dtls_srtp_stop_timeout_timer(instance, rtp, 0);
+	ao2_lock(instance);
 
 	if (rtp->ssl_ctx) {
 		SSL_CTX_free(rtp->ssl_ctx);
@@ -1589,16 +1594,16 @@
 	if (rtp->dtls.ssl) {
 		SSL_free(rtp->dtls.ssl);
 		rtp->dtls.ssl = NULL;
-		ast_mutex_destroy(&rtp->dtls.lock);
 	}
 
 	if (rtp->rtcp) {
+		ao2_unlock(instance);
 		dtls_srtp_stop_timeout_timer(instance, rtp, 1);
+		ao2_lock(instance);
 
 		if (rtp->rtcp->dtls.ssl && (rtp->rtcp->dtls.ssl != ssl)) {
 			SSL_free(rtp->rtcp->dtls.ssl);
 			rtp->rtcp->dtls.ssl = NULL;
-			ast_mutex_destroy(&rtp->rtcp->dtls.lock);
 		}
 	}
 }
@@ -1786,26 +1791,29 @@
 
 	SSL_do_handshake(dtls->ssl);
 
-	/* Since the handshake is started in a thread outside of the channel thread it's possible
-	 * for the response to be handled in the channel thread before we start the timeout timer.
-	 * To ensure this doesn't actually happen we hold the DTLS lock. The channel thread will
-	 * block until we're done at which point the timeout timer will be immediately stopped.
+	/*
+	 * A race condition is prevented between this function and __rtp_recvfrom()
+	 * because both functions have to get the instance lock before they can do
+	 * anything.  Without holding the instance lock, this function could start
+	 * the SSL handshake above in one thread and the __rtp_recvfrom() function
+	 * called by the channel thread could read the response and stop the timeout
+	 * timer before we have a chance to even start it.
 	 */
-	ast_mutex_lock(&dtls->lock);
 	dtls_srtp_check_pending(instance, rtp, rtcp);
 	dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
-	ast_mutex_unlock(&dtls->lock);
 }
 #endif
 
 #ifdef HAVE_PJPROJECT
 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
 
+/* PJPROJECT ICE callback */
 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
 {
 	struct ast_rtp_instance *instance = ice->user_data;
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
 
+	ao2_lock(instance);
 	if (status == PJ_SUCCESS) {
 		struct ast_sockaddr remote_address;
 
@@ -1829,13 +1837,16 @@
 #endif
 
 	if (!strictrtp) {
+		ao2_unlock(instance);
 		return;
 	}
 
 	rtp->strict_rtp_state = STRICT_RTP_LEARN;
 	rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
+	ao2_unlock(instance);
 }
 
+/* PJPROJECT ICE callback */
 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)
 {
 	struct ast_rtp_instance *instance = ice->user_data;
@@ -1852,6 +1863,7 @@
 	}
 }
 
+/* PJPROJECT ICE callback */
 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)
 {
 	struct ast_rtp_instance *instance = ice->user_data;
@@ -1966,13 +1978,15 @@
 	return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
 }
 
+/* Scheduler callback */
 static int dtls_srtp_handle_rtp_timeout(const void *data)
 {
 	struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
 	int reschedule;
 
+	ao2_lock(instance);
 	reschedule = dtls_srtp_handle_timeout(instance, 0);
-
+	ao2_unlock(instance);
 	if (!reschedule) {
 		ao2_ref(instance, -1);
 	}
@@ -1980,13 +1994,15 @@
 	return reschedule;
 }
 
+/* Scheduler callback */
 static int dtls_srtp_handle_rtcp_timeout(const void *data)
 {
 	struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
 	int reschedule;
 
+	ao2_lock(instance);
 	reschedule = dtls_srtp_handle_timeout(instance, 1);
-
+	ao2_unlock(instance);
 	if (!reschedule) {
 		ao2_ref(instance, -1);
 	}
@@ -2014,6 +2030,7 @@
 	}
 }
 
+/*! \pre Must not be called with the instance locked. */
 static void dtls_srtp_stop_timeout_timer(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
 {
 	struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
@@ -2054,10 +2071,13 @@
 	}
 }
 
+/* Scheduler callback */
 static int dtls_srtp_renegotiate(const void *data)
 {
 	struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
+
+	ao2_lock(instance);
 
 	SSL_renegotiate(rtp->dtls.ssl);
 	SSL_do_handshake(rtp->dtls.ssl);
@@ -2070,6 +2090,8 @@
 	}
 
 	rtp->rekeyid = -1;
+
+	ao2_unlock(instance);
 	ao2_ref(instance, -1);
 
 	return 0;
@@ -2239,14 +2261,18 @@
 			return -1;
 		}
 
-		/* This mutex is locked so that this thread blocks until the dtls_perform_handshake function
-		 * completes.
+		/*
+		 * A race condition is prevented between dtls_perform_handshake()
+		 * and this function because both functions have to get the
+		 * instance lock before they can do anything.  The
+		 * dtls_perform_handshake() function needs to start the timer
+		 * before we stop it below.
 		 */
-		ast_mutex_lock(&dtls->lock);
-		ast_mutex_unlock(&dtls->lock);
 
 		/* Before we feed data into OpenSSL ensure that the timeout timer is either stopped or completed */
+		ao2_unlock(instance);
 		dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
+		ao2_lock(instance);
 
 		/* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
 		if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
@@ -2692,10 +2718,6 @@
 		return -1;
 	}
 
-	/* Initialize synchronization aspects */
-	ast_mutex_init(&rtp->lock);
-	ast_cond_init(&rtp->cond, NULL);
-
 	/* Set default parameters on the newly created RTP structure */
 	rtp->ssrc = ast_random();
 	rtp->seqno = ast_random() & 0x7fff;
@@ -2744,6 +2766,9 @@
 	}
 
 #ifdef HAVE_PJPROJECT
+	/* Initialize synchronization aspects */
+	ast_cond_init(&rtp->cond, NULL);
+
 	generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
 	generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
 #endif
@@ -2812,7 +2837,9 @@
 
 	/* Destroy RED if it was being used */
 	if (rtp->red) {
+		ao2_unlock(instance);
 		AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
+		ao2_lock(instance);
 		ast_free(rtp->red);
 		rtp->red = NULL;
 	}
@@ -2820,13 +2847,16 @@
 #ifdef HAVE_PJPROJECT
 	pj_thread_register_check();
 
-	/* Destroy the RTP TURN relay if being used */
-	ast_mutex_lock(&rtp->lock);
+	/*
+	 * The instance lock is already held.
+	 *
+	 * Destroy the RTP TURN relay if being used
+	 */
 	if (rtp->turn_rtp) {
 		pj_turn_sock_destroy(rtp->turn_rtp);
 		rtp->turn_state = PJ_TURN_STATE_NULL;
 		while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
-			ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
+			ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
 		}
 	}
 
@@ -2835,10 +2865,9 @@
 		pj_turn_sock_destroy(rtp->turn_rtcp);
 		rtp->turn_state = PJ_TURN_STATE_NULL;
 		while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
-			ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
+			ast_cond_timedwait(&rtp->cond, ao2_object_get_lockaddr(instance), &ts);
 		}
 	}
-	ast_mutex_unlock(&rtp->lock);
 
 	if (rtp->ioqueue) {
 		rtp_ioqueue_thread_remove(rtp->ioqueue);
@@ -2863,9 +2892,10 @@
 	ao2_cleanup(rtp->lastrxformat);
 	ao2_cleanup(rtp->f.subclass.format);
 
+#ifdef HAVE_PJPROJECT
 	/* Destroy synchronization items */
-	ast_mutex_destroy(&rtp->lock);
 	ast_cond_destroy(&rtp->cond);
+#endif
 
 	/* Finally destroy ourselves */
 	ast_free(rtp);
@@ -3376,9 +3406,14 @@
 	return res;
 }
 
-/*! \brief Write and RTCP packet to the far end
+/*!
+ * \brief Write and RTCP packet to the far end
+ *
  * \note Decide if we are going to send an SR (with Reception Block) or RR
- * RR is sent if we have not sent any rtp packets in the previous interval */
+ * RR is sent if we have not sent any rtp packets in the previous interval
+ *
+ * Scheduler callback
+ */
 static int ast_rtcp_write(const void *data)
 {
 	struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
@@ -3390,6 +3425,7 @@
 		return 0;
 	}
 
+	ao2_lock(instance);
 	if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
 		/* Send an SR */
 		res = ast_rtcp_write_report(instance, 1);
@@ -3397,6 +3433,7 @@
 		/* Send an RR */
 		res = ast_rtcp_write_report(instance, 0);
 	}
+	ao2_unlock(instance);
 
 	if (!res) {
 		/*
@@ -4430,10 +4467,11 @@
 	return ast_rtcp_interpret(instance, read_area, res, &addr);
 }
 
-static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
+static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance,
+	struct ast_rtp_instance *instance1, unsigned int *rtpheader, int len, int hdrlen)
 {
-	struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
-	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
+	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
+	struct ast_rtp *bridged = ast_rtp_instance_get_data(instance1);
 	int res = 0, payload = 0, bridged_payload = 0, mark;
 	RAII_VAR(struct ast_rtp_payload_type *, payload_type, NULL, ao2_cleanup);
 	int reconstruct = ntohl(rtpheader[0]);
@@ -4496,10 +4534,27 @@
 	reconstruct |= (mark << 23);
 	rtpheader[0] = htonl(reconstruct);
 
+	/*
+	 * We have now determined that we need to send the RTP packet
+	 * out the bridged instance to do local bridging so we must unlock
+	 * the receiving instance to prevent deadlock with the bridged
+	 * instance.
+	 *
+	 * Technically we should grab a ref to instance1 so it won't go
+	 * away on us.  However, we should be safe because the bridged
+	 * instance won't change without both channels involved being
+	 * locked and we currently have the channel lock for the receiving
+	 * instance.
+	 */
+	ao2_unlock(instance);
+	ao2_lock(instance1);
+
 	ast_rtp_instance_get_remote_address(instance1, &remote_address);
 
 	if (ast_sockaddr_isnull(&remote_address)) {
 		ast_debug(5, "Remote address is null, most likely RTP has been stopped\n");
+		ao2_unlock(instance1);
+		ao2_lock(instance);
 		return 0;
 	}
 
@@ -4521,6 +4576,8 @@
 			}
 			ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
 		}
+		ao2_unlock(instance1);
+		ao2_lock(instance);
 		return 0;
 	}
 
@@ -4531,6 +4588,8 @@
 			    bridged_payload, len - hdrlen);
 	}
 
+	ao2_unlock(instance1);
+	ao2_lock(instance);
 	return 0;
 }
 
@@ -4570,6 +4629,7 @@
 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
 {
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
+	struct ast_rtp_instance *instance1;
 	struct ast_sockaddr addr;
 	int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
 	unsigned char *read_area = rtp->rawdata + AST_FRIENDLY_OFFSET;
@@ -4708,7 +4768,9 @@
 	}
 
 	/* If we are directly bridged to another instance send the audio directly out */
-	if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
+	instance1 = ast_rtp_instance_get_bridged(instance);
+	if (instance1
+		&& !bridge_p2p_rtp_write(instance, instance1, rtpheader, res, hdrlen)) {
 		return &ast_null_frame;
 	}
 
@@ -5114,14 +5176,17 @@
 		} else {
 			if (rtp->rtcp) {
 				if (rtp->rtcp->schedid > -1) {
+					ao2_unlock(instance);
 					if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
 						/* Successfully cancelled scheduler entry. */
 						ao2_ref(instance, -1);
 					} else {
 						/* Unable to cancel scheduler entry */
 						ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
+						ao2_lock(instance);
 						return;
 					}
+					ao2_lock(instance);
 					rtp->rtcp->schedid = -1;
 				}
 				if (rtp->rtcp->s > -1 && rtp->rtcp->s != rtp->s) {
@@ -5191,15 +5256,21 @@
 	}
 }
 
-/*! \brief Write t140 redundacy frame
+/*!
+ * \brief Write t140 redundacy frame
+ *
  * \param data primary data to be buffered
+ *
+ * Scheduler callback
  */
 static int red_write(const void *data)
 {
 	struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
 
+	ao2_lock(instance);
 	ast_rtp_write(instance, &rtp->red->t140);
+	ao2_unlock(instance);
 
 	return 1;
 }
@@ -5254,7 +5325,9 @@
 {
 	struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
 
+	ao2_lock(instance0);
 	ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
+	ao2_unlock(instance0);
 
 	return 0;
 }
@@ -5342,24 +5415,30 @@
 	struct ast_sockaddr addr = { {0,} };
 
 #ifdef HAVE_OPENSSL_SRTP
+	ao2_unlock(instance);
 	AST_SCHED_DEL_UNREF(rtp->sched, rtp->rekeyid, ao2_ref(instance, -1));
 
 	dtls_srtp_stop_timeout_timer(instance, rtp, 0);
 	if (rtp->rtcp) {
 		dtls_srtp_stop_timeout_timer(instance, rtp, 1);
 	}
+	ao2_lock(instance);
 #endif
 
 	if (rtp->rtcp && rtp->rtcp->schedid > -1) {
+		ao2_unlock(instance);
 		if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
 			/* successfully cancelled scheduler entry. */
 			ao2_ref(instance, -1);
 		}
+		ao2_lock(instance);
 		rtp->rtcp->schedid = -1;
 	}
 
 	if (rtp->red) {
+		ao2_unlock(instance);
 		AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
+		ao2_lock(instance);
 		ast_free(rtp->red);
 		rtp->red = NULL;
 	}

-- 
To view, visit https://gerrit.asterisk.org/5341
To unsubscribe, visit https://gerrit.asterisk.org/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I780b39ec935dcefcce880d50c1a7261744f1d1b4
Gerrit-PatchSet: 1
Gerrit-Project: asterisk
Gerrit-Branch: 13
Gerrit-Owner: Richard Mudgett <rmudgett at digium.com>



More information about the asterisk-code-review mailing list