All of lore.kernel.org
 help / color / mirror / Atom feed
From: "Frédéric Danis" <frederic.danis.oss@gmail.com>
To: linux-bluetooth@vger.kernel.org
Subject: [PATCH BlueZ v3] audio/hfp-hf: Destroy MediaTransport1 on codec change/disconnect
Date: Thu,  3 Dec 2026 15:55:44 +0100	[thread overview]
Message-ID: <20261203145544.153561-1-frederic.danis.oss@gmail.com> (raw)

- hfp_hf_clear_configuration() (mirrors a2dp's clear_config()) destroys
  a codec's MediaTransport1. Call it from hfp_hf_select_codec() on
  codec change (previous codec) and from device_destroy() (current
  codec), via new find_server_endpoint() helper. Previously the
  transport was only left IDLE, so it stayed in e.g. `bluetoothctl
  transport.list` after a call ended or the device disconnected.

- Fix use-after-free: transport_hfp_cancel() called g_source_remove()
  on the id from hfp_hf_sco_start(), but that id is dev->resume_id, an
  internal counter, not a GLib source id, so it never detached the
  in-flight SCO connect/codec negotiation from its owner. Clearing a
  previous codec's transport could then free that owner while the
  connect was still pending, leaving a dangling pointer for the
  completion callback to dereference.

  Track dev->pending_connect across all hfp_hf_sco_start() paths and
  add hfp_hf_sco_cancel() to detach the callback from it when the id
  matches. transport_hfp_cancel() tries this first, then falls back to
  g_source_remove() for the suspend-path id.

- sco_start_cb() now always frees connect_data, not only when its
  callback is set, fixing a leak the above introduces.

- dev->resume_id/pending_connect are shared by every codec's transport
  of a device, so a pending resume's id can collide with an unrelated
  sibling transport's suspend id. hfp_hf_sco_start()/hfp_hf_sco_cancel()
  take a resume_token (the transport pointer) to disambiguate; the
  transport pointer is used instead of transport->owner because
  media_transport_remove_owner() clears transport->owner before
  freeing the owner.

- Guard find_server_endpoint() against a NULL server, and make
  hfp_hf_select_codec() bail out with an error if find_server() finds
  none.

Assisted-by: Copilot:claude-sonnet-5
---
v1->v2:
 - Fix use-after-free on codec change: cancelling a pending SCO Acquire
   only removed a GLib source for an id that was never one, so the
   in-flight connect's callback could dereference a freed owner. Track
   dev->pending_connect and add hfp_hf_sco_cancel() to detach it instead.
 - Disambiguate cancellation with a resume_token (the transport pointer),
   since dev->resume_id/pending_connect are shared by every codec
   transport of a device.
 - Fix sco_start_cb() to always free connect_data.
 - Guard find_server_endpoint() and hfp_hf_select_codec() against a NULL
   server.

v2->v3:
 - Refcount connect_data (connect_data_ref()/connect_data_unref()) and
   add a completed flag, instead of relying on hfp_hf_sco_cancel() alone
   to make a cancelled connect/codec negotiation a no-op: bt_io_connect(),
   bt_io_accept() and the idle source now each hold their own reference
   via a GDestroyNotify, so connect_data stays valid for as long as any
   of them can still call back into it.
 - sco_connect_cb() now checks connect_data->completed and shuts down io
   instead of completing again, guarding against the callback firing
   after cancellation or disconnect.
 - device_destroy() now actively tears down a pending connect instead of
   just marking it done: it removes the idle source_id and shuts down io
   before calling sco_connect_complete(), so bt_io_connect()/the idle
   source cannot run after the device is gone.
 - confirm_cb() creates connect_data up front (if none is pending yet)
   so bt_io_accept()'s own reference/destroy-notify can track it the
   same way as the other paths.
 - hfp_hf_sco_cancel() also clears resume_token, so a stale cancelled
   connect_data cannot later be matched against a reused resume_token.

 profiles/audio/hfp-hf.c    | 194 ++++++++++++++++++++++++++++++++-----
 profiles/audio/hfp-hf.h    |   4 +-
 profiles/audio/media.c     |  15 +++
 profiles/audio/media.h     |   2 +
 profiles/audio/transport.c |  32 ++++--
 5 files changed, 214 insertions(+), 33 deletions(-)

diff --git a/profiles/audio/hfp-hf.c b/profiles/audio/hfp-hf.c
index bc6d7229f..02f114363 100644
--- a/profiles/audio/hfp-hf.c
+++ b/profiles/audio/hfp-hf.c
@@ -76,6 +76,11 @@ struct connect_data {
 	struct hfp_device *dev;
 	void (*cb)(int status, void *data);
 	void *cb_user_data;
+	const void *resume_token;
+	GIOChannel *io;
+	guint source_id;
+	unsigned int ref_count;
+	bool completed;
 };
 
 struct hfp_device {
@@ -138,6 +143,22 @@ static struct hfp_server *find_server(GSList *list, struct btd_adapter *a)
 	return NULL;
 }
 
+static struct media_endpoint *find_server_endpoint(struct hfp_server *server,
+							uint8_t codec)
+{
+	GSList *l;
+
+	if (!server)
+		return NULL;
+
+	for (l = server->endpoints; l; l = l->next) {
+		if (media_endpoint_get_codec(l->data) == codec)
+			return l->data;
+	}
+
+	return NULL;
+}
+
 static void unregister_endpoint(gpointer data, gpointer user_data)
 {
 	struct media_endpoint *ep = data;
@@ -179,18 +200,42 @@ static bool call_id_cmp(const void *data, const void *match_data)
 	return call->idx == id;
 }
 
+static struct connect_data *connect_data_ref(struct connect_data *connect_data)
+{
+	connect_data->ref_count++;
+
+	return connect_data;
+}
+
+static void connect_data_unref(gpointer data)
+{
+	struct connect_data *connect_data = data;
+
+	if (--connect_data->ref_count)
+		return;
+
+	g_free(connect_data);
+}
+
 static void sco_connect_complete(struct connect_data *connect_data, int status)
 {
-	if (!connect_data)
+	if (!connect_data || connect_data->completed)
 		return;
 
+	connect_data->completed = true;
+
 	if (connect_data->dev->pending_connect == connect_data)
 		connect_data->dev->pending_connect = NULL;
 
+	if (connect_data->io) {
+		g_io_channel_unref(connect_data->io);
+		connect_data->io = NULL;
+	}
+
 	if (connect_data->cb)
 		connect_data->cb(status, connect_data->cb_user_data);
 
-	g_free(connect_data);
+	connect_data_unref(connect_data);
 }
 
 static void dial_complete(enum hfp_result res, enum hfp_error cme_err,
@@ -228,8 +273,19 @@ static void device_destroy(struct hfp_device *dev)
 		dial_complete(HFP_RESULT_ERROR,
 				HFP_ERROR_NO_CONNECTION_TO_PHONE, dev);
 
-	if (dev->pending_connect)
-		sco_connect_complete(dev->pending_connect, -ENOTCONN);
+	if (dev->pending_connect) {
+		struct connect_data *connect_data = dev->pending_connect;
+
+		if (connect_data->source_id) {
+			g_source_remove(connect_data->source_id);
+			connect_data->source_id = 0;
+		}
+
+		if (connect_data->io)
+			g_io_channel_shutdown(connect_data->io, TRUE, NULL);
+
+		sco_connect_complete(connect_data, -ENOTCONN);
+	}
 
 	if (dev->hf) {
 		hfp_hf_unref(dev->hf);
@@ -248,9 +304,21 @@ static void device_destroy(struct hfp_device *dev)
 
 	server = find_server(servers,
 		device_get_adapter(telephony_get_device(dev->telephony)));
-	if (server)
+	if (server) {
+		struct media_endpoint *ep;
+
+		/* Destroy the MediaTransport1 created for this device's SCO
+		 * audio, if any, so it does not linger after the device is
+		 * gone.
+		 */
+		ep = find_server_endpoint(server, dev->codec);
+		if (ep)
+			hfp_hf_clear_configuration(ep,
+					telephony_get_device(dev->telephony));
+
 		g_slist_foreach(server->endpoints, unregister_endpoint,
 					dev->telephony);
+	}
 
 	telephony_unregister_interface(dev->telephony);
 }
@@ -422,21 +490,38 @@ static bool hfp_hf_select_codec(uint8_t codec, void *user_data)
 	struct hfp_device *dev = user_data;
 	struct btd_adapter *adapter;
 	struct hfp_server *server;
-	GSList *l;
+	struct media_endpoint *ep;
 
 	DBG("Selecting codec: %u", codec);
 	adapter = device_get_adapter(telephony_get_device(dev->telephony));
 	server = find_server(servers, adapter);
+	if (!server) {
+		error("No server found for adapter");
+		return false;
+	}
 
-	for (l = server->endpoints; l; l = l->next) {
-		if (media_endpoint_get_codec(l->data) == codec) {
-			dev->codec = codec;
-			return true;
-		}
+	ep = find_server_endpoint(server, codec);
+	if (!ep) {
+		DBG("Unsupported codec: %u", codec);
+		return false;
 	}
 
-	DBG("Unsupported codec: %u", codec);
-	return false;
+	if (dev->codec != codec) {
+		/* A device only ever has one SCO connection at a time, so
+		 * the previous codec's transport, if any, is no longer
+		 * valid.
+		 */
+		struct media_endpoint *prev;
+
+		prev = find_server_endpoint(server, dev->codec);
+		if (prev)
+			hfp_hf_clear_configuration(prev,
+					telephony_get_device(dev->telephony));
+	}
+
+	dev->codec = codec;
+
+	return true;
 }
 
 static struct hfp_hf_callbacks hf_session_callbacks = {
@@ -1123,6 +1208,12 @@ static void sco_connect_cb(GIOChannel *io, GError *err, gpointer user_data)
 	char *path = NULL;
 	uint16_t imtu, omtu;
 
+	if (connect_data->completed) {
+		if (io)
+			g_io_channel_shutdown(io, TRUE, NULL);
+		return;
+	}
+
 	if (err) {
 		error("Connecting failed: %s\n", err->message);
 		sco_connect_complete(connect_data, -EIO);
@@ -1215,6 +1306,7 @@ static void confirm_cb(GIOChannel *io, gpointer user_data)
 	struct btd_device *device;
 	struct btd_service *service;
 	struct hfp_device *dev = NULL;
+	struct connect_data *connect_data;
 	int voice;
 	GError *err = NULL;
 
@@ -1240,6 +1332,15 @@ static void confirm_cb(GIOChannel *io, gpointer user_data)
 		goto drop;
 
 	dev = btd_service_get_user_data(service);
+	connect_data = dev->pending_connect;
+
+	if (!connect_data) {
+		connect_data = g_new0(struct connect_data, 1);
+		connect_data->dev = dev;
+		connect_data->ref_count = 1;
+		dev->pending_connect = connect_data;
+	}
+
 	voice = dev->codec == 1 ? BT_VOICE_CVSD_16BIT : BT_VOICE_TRANSPARENT;
 
 	if (!bt_io_set(io, &err, BT_IO_OPT_VOICE, voice, BT_IO_OPT_INVALID)) {
@@ -1249,8 +1350,9 @@ static void confirm_cb(GIOChannel *io, gpointer user_data)
 		goto drop;
 	}
 
-	if (!bt_io_accept(io, sco_connect_cb, dev->pending_connect, NULL,
-								&err)) {
+	if (!bt_io_accept(io, sco_connect_cb, connect_data_ref(connect_data),
+						connect_data_unref, &err)) {
+		connect_data_unref(connect_data);
 		error("bt_io_accept() failed: %s", err->message);
 		g_error_free(err);
 		goto drop;
@@ -1359,15 +1461,14 @@ static gboolean sco_start_cb(gpointer data)
 {
 	struct connect_data *connect_data = data;
 
-	if (connect_data && connect_data->cb) {
-		connect_data->cb(0, connect_data->cb_user_data);
-		g_free(connect_data);
-	}
+	connect_data->source_id = 0;
+	sco_connect_complete(connect_data, 0);
 
 	return FALSE;
 }
 
-unsigned int hfp_hf_sco_start(struct hfp_device *dev, void *cb, void *user_data)
+unsigned int hfp_hf_sco_start(struct hfp_device *dev, void *cb,
+				void *user_data, const void *resume_token)
 {
 	bdaddr_t src, dst;
 	struct connect_data *connect_data;
@@ -1385,18 +1486,21 @@ unsigned int hfp_hf_sco_start(struct hfp_device *dev, void *cb, void *user_data)
 	connect_data->dev = dev;
 	connect_data->cb = cb;
 	connect_data->cb_user_data = user_data;
+	connect_data->resume_token = resume_token;
+	connect_data->ref_count = 1;
+	dev->pending_connect = connect_data;
 
 	src = telephony_get_src(dev->telephony);
 	dst = telephony_get_dst(dev->telephony);
 	if (!dev->sco_io) {
 		if (hfp_hf_request_codec_connection(dev->hf,
 						req_codec_connection_complete,
-						connect_data)) {
-			dev->pending_connect = connect_data;
+						connect_data))
 			goto done;
-		}
 
-		io = bt_io_connect(sco_connect_cb, connect_data, NULL, &err,
+		connect_data_ref(connect_data);
+		io = bt_io_connect(sco_connect_cb, connect_data,
+			connect_data_unref, &err,
 			BT_IO_OPT_SOURCE_BDADDR, &src,
 			BT_IO_OPT_DEST_BDADDR, &dst,
 			BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
@@ -1404,17 +1508,55 @@ unsigned int hfp_hf_sco_start(struct hfp_device *dev, void *cb, void *user_data)
 		if (!io) {
 			error("%s", err->message);
 			g_error_free(err);
-			g_free(connect_data);
+			dev->pending_connect = NULL;
+			connect_data_unref(connect_data);
+			connect_data_unref(connect_data);
 			return 0;
 		}
+
+		connect_data->io = io;
 	} else {
-		g_idle_add(sco_start_cb, connect_data);
+		connect_data->source_id = g_idle_add_full(
+					G_PRIORITY_DEFAULT_IDLE, sco_start_cb,
+					connect_data_ref(connect_data),
+					connect_data_unref);
 	}
 
 done:
 	return (++dev->resume_id);
 }
 
+bool hfp_hf_sco_cancel(struct hfp_device *dev, unsigned int id,
+						const void *resume_token)
+{
+	if (!dev->pending_connect || dev->resume_id != id)
+		return false;
+
+	/*
+	 * dev->resume_id is a device-wide counter shared by every codec's
+	 * transport, while id may also be an unrelated g_idle_add() source
+	 * id from a sibling transport's pending suspend. Require the caller
+	 * to also present the same resume_token that was passed to
+	 * hfp_hf_sco_start(), so a numeric collision between the two id
+	 * spaces can never cause this resume to be mistaken for that
+	 * suspend (or vice versa).
+	 */
+	if (dev->pending_connect->resume_token != resume_token)
+		return false;
+
+	/*
+	 * The underlying SCO connect/codec negotiation cannot be aborted
+	 * cleanly, so just detach the callback: the operation still runs
+	 * to completion, but will no longer touch the (about to be freed)
+	 * owner once hfp_hf_sco_start() handed out this id.
+	 */
+	dev->pending_connect->cb = NULL;
+	dev->pending_connect->cb_user_data = NULL;
+	dev->pending_connect->resume_token = NULL;
+
+	return true;
+}
+
 unsigned int hfp_hf_sco_stop(struct hfp_device *dev)
 {
 	if (!dev->sco_io)
diff --git a/profiles/audio/hfp-hf.h b/profiles/audio/hfp-hf.h
index 6dfa3b12f..b4daa9b21 100644
--- a/profiles/audio/hfp-hf.h
+++ b/profiles/audio/hfp-hf.h
@@ -15,8 +15,10 @@ typedef void (*hfp_hf_sco_closed_cb) (struct hfp_device *dev, void *user_data);
 bool hfp_hf_sco_listen(struct btd_adapter *adapter, void *endpoint);
 void hfp_hf_sco_remove(struct btd_adapter *adapter, void *endpoint);
 unsigned int hfp_hf_sco_start(struct hfp_device *dev, void *cb,
-							void *user_data);
+				void *user_data, const void *resume_token);
 unsigned int hfp_hf_sco_stop(struct hfp_device *dev);
+bool hfp_hf_sco_cancel(struct hfp_device *dev, unsigned int id,
+						const void *resume_token);
 void hfp_hf_set_sco_closed_cb(struct hfp_device *dev,
 				hfp_hf_sco_closed_cb cb, void *user_data);
 
diff --git a/profiles/audio/media.c b/profiles/audio/media.c
index 13fead886..f1c8906e4 100644
--- a/profiles/audio/media.c
+++ b/profiles/audio/media.c
@@ -1501,6 +1501,21 @@ gboolean hfp_hf_set_configuration(struct media_endpoint *endpoint,
 						cb, user_data, destroy, -1);
 }
 
+void hfp_hf_clear_configuration(struct media_endpoint *endpoint,
+					struct btd_device *device)
+{
+	struct media_transport *transport;
+
+	if (!endpoint)
+		return;
+
+	transport = find_device_transport(endpoint, device);
+	if (!transport)
+		return;
+
+	clear_configuration(endpoint, transport);
+}
+
 static bool endpoint_init_sco(struct media_endpoint *endpoint,
 						int *err)
 {
diff --git a/profiles/audio/media.h b/profiles/audio/media.h
index eb95a8b06..c20238f1a 100644
--- a/profiles/audio/media.h
+++ b/profiles/audio/media.h
@@ -89,3 +89,5 @@ gboolean hfp_hf_set_configuration(struct media_endpoint *endpoint,
 					media_endpoint_cb_t cb,
 					void *user_data,
 					GDestroyNotify destroy);
+void hfp_hf_clear_configuration(struct media_endpoint *endpoint,
+					struct btd_device *device);
diff --git a/profiles/audio/transport.c b/profiles/audio/transport.c
index de8dbd7a6..77bc5929d 100644
--- a/profiles/audio/transport.c
+++ b/profiles/audio/transport.c
@@ -2898,7 +2898,8 @@ static guint transport_hfp_resume(struct media_transport *transport,
 {
 	struct hfp_device *hfp_dev = transport->data;
 
-	return hfp_hf_sco_start(hfp_dev, hfp_transport_resume_cb, owner);
+	return hfp_hf_sco_start(hfp_dev, hfp_transport_resume_cb, owner,
+								transport);
 }
 
 static gboolean hfp_transport_suspend_cb(void *user_data)
@@ -2948,12 +2949,31 @@ static guint transport_hfp_suspend(struct media_transport *transport,
 
 static void transport_hfp_cancel(struct media_transport *transport, guint id)
 {
-	/* id is the g_idle_add() source id returned by transport_hfp_suspend()
-	 * for its still-pending hfp_transport_suspend_cb() callback. Cancel it
-	 * so it can never fire with a dangling owner pointer if owner is torn
-	 * down through another path first.
+	struct hfp_device *hfp_dev = transport->data;
+
+	/*
+	 * id can be either a dev->resume_id handed out by hfp_hf_sco_start()
+	 * for a still-pending resume, or the g_idle_add() source id returned
+	 * by transport_hfp_suspend() for its still-pending
+	 * hfp_transport_suspend_cb() callback. Since dev->resume_id is
+	 * shared by every codec transport of this device, it can collide
+	 * numerically with an unrelated sibling transport's suspend id;
+	 * hfp_hf_sco_cancel() also checks that the resume_token matches
+	 * this transport (the token hfp_hf_sco_start() was given when the
+	 * pending resume was started) before treating it as a match. transport
+	 * is always the transport whose owner is being cancelled (passed
+	 * down fresh from media_owner_remove()'s owner->transport), unlike
+	 * transport->owner, which may already have been cleared by the time
+	 * this runs (e.g. via media_transport_remove_owner()). Try the
+	 * resume case first; hfp_hf_sco_cancel() only detaches the callback
+	 * (the id space isn't a GLib source id, and the in-flight SCO
+	 * connect/codec negotiation cannot be aborted), so the owner can be
+	 * freed safely afterwards. Otherwise fall back to cancelling the
+	 * suspend idle source, so it never fires with a dangling owner
+	 * pointer if owner is torn down through another path first.
 	 */
-	g_source_remove(id);
+	if (!hfp_hf_sco_cancel(hfp_dev, id, transport))
+		g_source_remove(id);
 }
 #endif /* HAVE_HFP */
 
-- 
2.56.1


             reply	other threads:[~2026-12-03 14:55 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 14:55 Frédéric Danis [this message]
2026-12-03 17:43 ` [BlueZ,v3] audio/hfp-hf: Destroy MediaTransport1 on codec change/disconnect bluez.test.bot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261203145544.153561-1-frederic.danis.oss@gmail.com \
    --to=frederic.danis.oss@gmail.com \
    --cc=linux-bluetooth@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.