Linux bluetooth development
 help / color / mirror / Atom feed
* [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon
@ 2026-12-04 16:04 Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors Frédéric Danis
                   ` (5 more replies)
  0 siblings, 6 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

btmon currently hexdumps all OBEX traffic (RFCOMM and L2CAP GOEP), making
PBAP/MAP/BIP/OPP sessions hard to follow in a trace. This series adds a
dedicated OBEX dissector (monitor/obex.c) and wires it into the RFCOMM,
L2CAP and SDP monitors.

Patch 1 strips the trailing L2CAP FCS of ERTM/Streaming mode frames,
which was passed to the upper layer dissectors as payload.

Patch 2 adds the core decoder: opcodes, response codes, CONNECT/SETPATH
fixed fields, all generic header IDs, BIP's IMG-Handle/IMG-Descriptor
extension headers, and Target/Who UUID recognition for the well known
OBEX profiles.
It tracks sessions on both RFCOMM (learned from SDP
ProtocolDescriptorList) and L2CAP (a dynamically negotiated PSM
learned from the GoepL2capPsm SDP attribute), keyed
direction-independently so CONNECT requests and responses are correctly
matched to the same session.

Patch 3 adds per-profile Application Parameters (Tag/Len/Value) decoding
for PBAP, MAP and BIP, replacing the generic 'Tag 0xNN len N' hexdump with
named, typed values, using the profile learned from each session's
Target/Who header.

Patch 4 adds SDU reassembly for L2CAP ERTM/Streaming mode, since OBEX PDUs
routinely span multiple SAR fragments; without it, any segmented PDU
failed to parse ('frame too short'). Each SDU is decoded from the frame
completing it, so the output follows the capture order, while the
payload of fragments still being buffered is hexdumped so no bytes are
lost from the trace.

Patch 5 fixes the RFCOMM frame length and FCS handling.

Patch 6 reassembles OBEX PDUs split across several RFCOMM UIH frames.

Sample decode, a PBAP CONNECT followed by a GET with Application
Parameters:

OBEX: Connect (0x00) final 1 len 35
   Version: 1.0
   Flags: 0x00
   Max Packet Length: 8087
   Target: Phonebook Access (PBAP)
   Application Parameters: [len 6]
     Supported Features: 1023 (0x000003ff)
...
OBEX: Get (0x03) final 1 len 87
   Connection ID: 1 (0x00000001)
   Single Response Mode: 1 (0x01)
   Name: telecom/fav.vcf
   Type: x-bt/phonebook
   Application Parameters: [len 21]
     Format: 1 (0x01)
     Max List Count: 65535 (0xffff)
     Filter: 0x0000000018b111af
     List Start Offset: 0 (0x0000)

v1->v2: Fix commit title issue

v2->v3: Address review feedback:
  - Patch 2 (OBEX protocol decoder): fix a possible uint32_t overflow in
    the SDP element-length parsing, fix obex_de_uuid16() extracting the
    short value from the wrong half of a 32-bit UUID, and stop treating
    L2CAP PSM 0x1001 as always running OBEX.
  - Patch 3 (PBAP/MAP/BIP Application Parameters): clear the learned
    profile classification on session/channel/handle teardown and on a
    new CONNECT, so a later session can't inherit a stale profile.
  - Patch 4 (L2CAP SDU reassembly, retitled): track the expected TxSeq
    per direction to discard retransmitted/duplicate fragments and stop
    reassembling past a lost fragment, and fix l2cap_sdu_reassemble()
    reporting success on an End fragment with no buffered Start, which
    could free a borrowed packet buffer.
  - New patch 5: trim the trailing RFCOMM FCS byte from the payload
    handed to upper layer dissectors, and skip credit-only UIH frames.
  - New patch 6: reassemble OBEX PDUs split across several RFCOMM UIH
    frames, since the RFCOMM MTU is typically smaller than the maximum
    OBEX PDU length.

v3->v4: Address review feedback:
  - Patch 1 (L2CAP FCS): apply an FCS value requested by a Config
    Request on a successful, option-free Config Response too.
  - Patch 2 (OBEX protocol decoder): fix the disconnect handler's
    swapped SCID/DCID session resolution, stop obex_remove_channel()
    from dropping the SDP-learned channel mapping so a reconnect on
    the same ACL link doesn't need SDP repeated, validate 128-bit
    UUIDs against the Bluetooth Base UUID before treating them as
    16-bit assigned numbers, recognize OBEX running directly over a
    dedicated L2CAP PSM (e.g. BIP's AVRCP Cover Art), only trust a
    GOEP L2CAP PSM attribute once the record is confirmed to speak
    OBEX, and decode UTF-16 surrogate pairs correctly.
  - Patch 3 (PBAP/MAP/BIP Application Parameters): document why
    obex_remove_channel() keeps the channel mapping, and use a
    channel-zero check consistently to detect free profile slots.
  - Patch 6 (OBEX PDU reassembly over RFCOMM): free a handle's
    reassembly buffers when the ACL link itself is disconnected
    without a per-channel RFCOMM DISC/DM, and widen the reassembly
    length/position tracking to avoid truncating a malformed
    declared length's remaining byte count.

v4->v5: Address review feedback:
  - Patch 1 (L2CAP FCS): discard a pending requested FCS value when
    its Config Request is rejected with Unknown Options, so a later
    unrelated successful Config Response doesn't apply it.
  - Patch 2 (OBEX protocol decoder): use the processed frame's
    data/size, not the original pre-FCS-strip/pre-reassembly packet
    parameters, in the default-PSM hexdump fallback.
  - Patch 4 (L2CAP SDU reassembly): track the TxSeq of the Start
    fragment that began the in-progress SDU and compare a new Start
    fragment against it, so a retransmitted duplicate of that Start
    fragment doesn't needlessly discard the already-buffered
    Continuation fragments.
  - Patch 5 (RFCOMM UIH length/credit handling): bound the payload
    handed to uih_frame()/mcc_frame() by the UIH frame's own declared
    hdr.length, so an L2CAP PDU carrying more than one multiplexed
    RFCOMM frame doesn't leak the next frame's bytes into this
    frame's payload.
  - Patch 6 (OBEX PDU reassembly over RFCOMM): hexdump an
    incomplete, still-buffered PDU's own payload instead of showing
    nothing, key the reassembly buffer and OBEX session state on the
    full DLCI instead of just the server channel number, clear every
    data channel's OBEX state on a DLCI 0 (multiplexer) or RFCOMM
    L2CAP transport teardown, and bounds-check a chan_list[] index
    derived from an unresolved CID before dereferencing it.

v5->v6: Address review feedback:
  - Patch 1 (L2CAP FCS): only apply a Config Response's FCS option on
    a definitively successful result instead of on any response, and
    extend discarding a pending requested FCS value to any final
    failure result (not just Unknown Options), leaving it alone while
    the result is Pending or the response is a non-final fragment.
  - Patch 2 (OBEX protocol decoder): special-case the SDP Nil type to
    a zero data length in obex_de_next(), instead of the 1 byte it
    shares with 8-bit Int/UInt, so scanning a Nil-valued attribute
    doesn't desync.
  - Patch 4 (L2CAP SDU reassembly): replace the "only check the
    immediately preceding TxSeq" duplicate check with a
    wraparound-aware range check covering every already-received
    fragment, so a retransmission of an earlier (not just the most
    recent) fragment doesn't wrongly discard the buffered SDU.
  - Patch 6 (OBEX PDU reassembly over RFCOMM): track which device
    sent the DLCI 0 SABM establishing each ACL's RFCOMM multiplexer
    session, and have obex_channel()/obex_add_channel() skip a
    channel-number match whose stored role disagrees with the live
    session's, so a server channel number reused independently by
    each peer isn't confused between them; add l2cap_remove_handle()
    to release a handle's chan_list[] entries (and SAR reassembly
    buffers) on HCI Disconnection Complete without a per-channel
    L2CAP Disconnection Response.

v6->v7: Address review feedback:
  - Patch 1 (L2CAP FCS): compare the Config Response result against
    le16_to_cpu(pdu->result) instead of the raw wire value, so a
    big-endian host no longer misreads e.g. a Pending response as a
    final failure, and stage a Config Response's own FCS option
    instead of applying it as soon as a fragment's result reads
    Success, committing it only once the final fragment's result is
    known.
  - Patch 4 (L2CAP SDU reassembly): track the uncapped fragment count
    received since the Start segment and measure the duplicate/gap
    check as a window of that size ending at the last received
    sequence number, instead of a span reduced mod seq_mod, so the
    check no longer wraps to an ambiguous zero once a full window's
    worth of fragments has been received.
  - Patch 6 (OBEX PDU reassembly over RFCOMM): pass the DLCI into
    rfcomm_local_is_server() and derive the server role from both the
    mux initiator/responder tracking and the DLCI's direction bit,
    instead of always treating the mux responder as server.

v7->v8: Address review feedback:
  - Patch 1 (L2CAP FCS): track the FCS option per direction, and
    discard the staged FCS values once committed or on Unknown
    Options.
  - Patch 4 (L2CAP SDU reassembly): rework the reassembly to keep
    out-of-order fragments, so ERTM retransmissions complete the SDU,
    decode each SDU from the frame completing it, and bound the
    fragments kept per direction.
  - Patch 5 (RFCOMM UIH length/credit handling): read the FCS right
    after each frame's declared length, and decode all RFCOMM frames
    carried in the same L2CAP SDU.
  - Patch 6 (OBEX PDU reassembly over RFCOMM): fix the inverted server
    role derived from the DLCI direction bit, check the server role of
    L2CAP PSM mappings too, and keep the SDP mappings across ACL
    reconnection, matched by peer address.
  - All patches: trim comments and commit messages.

Frédéric Danis (6):
  monitor: Strip trailing L2CAP FCS before upper layer dissectors
  monitor: Add OBEX protocol decoder
  monitor: Decode PBAP/MAP/BIP Application Parameters tags
  monitor: Reassemble L2CAP ERTM/Streaming SDUs
  monitor: Fix RFCOMM UIH frame length and credit-only handling
  monitor: Reassemble OBEX PDUs split across RFCOMM UIH frames

 Makefile.tools   |    1 +
 monitor/l2cap.c  |  995 +++++++++++++++++++++++++++--
 monitor/l2cap.h  |    4 +
 monitor/obex.c   | 1549 ++++++++++++++++++++++++++++++++++++++++++++++
 monitor/obex.h   |  123 ++++
 monitor/packet.c |    7 +-
 monitor/rfcomm.c |  340 +++++++++-
 monitor/sdp.c    |   12 +-
 8 files changed, 2949 insertions(+), 82 deletions(-)
 create mode 100644 monitor/obex.c
 create mode 100644 monitor/obex.h

-- 
2.43.0


^ permalink raw reply	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  2026-12-04 17:12   ` monitor: Add an OBEX protocol decoder to btmon bluez.test.bot
  2026-12-04 16:04 ` [PATCH BlueZ v8 2/6] monitor: Add OBEX protocol decoder Frédéric Danis
                   ` (4 subsequent siblings)
  5 siblings, 1 reply; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

From: Frédéric Danis <frederic.danis.oss@gmail.com>

ERTM and Streaming mode frames end with a 2-byte FCS, which was passed
to the upper layer dissectors as part of the payload.

Track the FCS option negotiated for each channel and remove the FCS
from ERTM/Streaming mode frames before PSM dispatch. FCS is used unless
both directions negotiate "No FCS", so the option is tracked per
direction. An FCS option from a Config Request or Response only takes
effect once the final Config Response fragment reports success, and is
dropped on failure.

Convert the Config Response result to host byte order before comparing
it, as the comparisons were wrong on big-endian hosts.

Assisted-by: Claude:claude-sonnet-5
---
v3->v4:
  - Track the FCS value requested by a Config Request and apply it on
    a successful Config Response that doesn't repeat it (a successful
    response need not repeat accepted options), instead of only
    reading the FCS option when the response itself carries it.

v4->v5:
  - Discard a pending requested FCS value when its Config Request is
    rejected with Unknown Options (discard_req_fcs()), so a later,
    unrelated successful Config Response in the same renegotiation
    doesn't apply the rejected value.

v5->v6:
  - Extend discard_req_fcs() to any final failure result (Unacceptable
    Parameters, Rejected, Flow Spec Rejected), not just Unknown
    Options, leaving the pending value alone while the result is
    Pending or the response is a non-final fragment.
  - Only apply a Config Response's FCS option (print_config_options())
    on a definitively successful result, instead of on any response,
    so a failed negotiation doesn't change the channel's tracked FCS
    mode.

v6->v7:
  - Compare the Config Response result against le16_to_cpu(pdu->result)
    instead of the raw wire value, so a big-endian host no longer
    misreads e.g. a Pending (0x0004) response as a final failure.
  - Stage a Config Response's own FCS option (rsp_fcs) instead of
    applying it as soon as a fragment's result reads Success, and
    commit it with the rest of the response's final result handling,
    so a non-final fragment reading Success no longer changes the
    channel's FCS mode ahead of a later fragment that actually rejects
    the configuration.

v7->v8:
  - Track the FCS option per direction, as FCS is only disabled once
    both directions negotiate "No FCS".
  - Also discard the staged Config Response FCS option on Unknown
    Options, and discard both staged values once committed, so a later
    Config Response can't apply them again.
  - Trim comments and commit message.

 monitor/l2cap.c | 243 +++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 238 insertions(+), 5 deletions(-)

diff --git a/monitor/l2cap.c b/monitor/l2cap.c
index ddc2388d5..114037336 100644
--- a/monitor/l2cap.c
+++ b/monitor/l2cap.c
@@ -100,6 +100,10 @@ struct chan_data {
 	uint8_t  ext_ctrl;
 	uint8_t  seq_num;
 	uint16_t sdu;
+	uint8_t  fcs;
+	uint8_t  fcs_dir[2];
+	int8_t   req_fcs[2];
+	int8_t   rsp_fcs[2];
 	struct packet_latency tx_l;
 };
 
@@ -158,6 +162,15 @@ static void assign_scid(const struct l2cap_frame *frame, uint16_t scid,
 	chan_list[n].ctrlid = ctrlid;
 	chan_list[n].mode = mode;
 
+	/* FCS is used unless both directions negotiate "No FCS" */
+	chan_list[n].fcs = 1;
+	chan_list[n].fcs_dir[0] = 1;
+	chan_list[n].fcs_dir[1] = 1;
+	chan_list[n].req_fcs[0] = -1;
+	chan_list[n].req_fcs[1] = -1;
+	chan_list[n].rsp_fcs[0] = -1;
+	chan_list[n].rsp_fcs[1] = -1;
+
 	chan_list[n].seq_num = seq_num;
 }
 
@@ -255,6 +268,189 @@ static void assign_mode(const struct l2cap_frame *frame,
 	}
 }
 
+/* A successful Config Response doesn't need to repeat the FCS option of
+ * the Request, so keep it until the final response, per direction.
+ */
+static void assign_req_fcs(const struct l2cap_frame *frame,
+					uint8_t fcs, uint16_t dcid)
+{
+	int i;
+	int dir = frame->in ? 1 : 0;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == dcid) {
+				chan_list[i].req_fcs[dir] = fcs;
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == dcid) {
+				chan_list[i].req_fcs[dir] = fcs;
+				break;
+			}
+		}
+	}
+}
+
+/* Called with the Response frame, sent in the opposite direction of the
+ * Request.
+ */
+static void apply_req_fcs(const struct l2cap_frame *frame, uint16_t scid)
+{
+	int i;
+	int dir = frame->in ? 0 : 1;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == scid) {
+				if (chan_list[i].req_fcs[dir] >= 0)
+					chan_list[i].fcs_dir[dir] =
+						chan_list[i].req_fcs[dir];
+				chan_list[i].fcs = chan_list[i].fcs_dir[0] ||
+							chan_list[i].fcs_dir[1];
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == scid) {
+				if (chan_list[i].req_fcs[dir] >= 0)
+					chan_list[i].fcs_dir[dir] =
+						chan_list[i].req_fcs[dir];
+				chan_list[i].fcs = chan_list[i].fcs_dir[0] ||
+							chan_list[i].fcs_dir[1];
+				break;
+			}
+		}
+	}
+}
+
+static void discard_req_fcs(const struct l2cap_frame *frame, uint16_t scid)
+{
+	int i;
+	int dir = frame->in ? 0 : 1;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == scid) {
+				chan_list[i].req_fcs[dir] = -1;
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == scid) {
+				chan_list[i].req_fcs[dir] = -1;
+				break;
+			}
+		}
+	}
+}
+
+/* A Config Response option only takes effect once the final fragment
+ * reports success.
+ */
+static void assign_rsp_fcs(const struct l2cap_frame *frame,
+					uint8_t fcs, uint16_t dcid)
+{
+	int i;
+	int dir = frame->in ? 0 : 1;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == dcid) {
+				chan_list[i].rsp_fcs[dir] = fcs;
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == dcid) {
+				chan_list[i].rsp_fcs[dir] = fcs;
+				break;
+			}
+		}
+	}
+}
+
+static void apply_rsp_fcs(const struct l2cap_frame *frame, uint16_t scid)
+{
+	int i;
+	int dir = frame->in ? 0 : 1;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == scid) {
+				if (chan_list[i].rsp_fcs[dir] >= 0)
+					chan_list[i].fcs_dir[dir] =
+						chan_list[i].rsp_fcs[dir];
+				chan_list[i].fcs = chan_list[i].fcs_dir[0] ||
+							chan_list[i].fcs_dir[1];
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == scid) {
+				if (chan_list[i].rsp_fcs[dir] >= 0)
+					chan_list[i].fcs_dir[dir] =
+						chan_list[i].rsp_fcs[dir];
+				chan_list[i].fcs = chan_list[i].fcs_dir[0] ||
+							chan_list[i].fcs_dir[1];
+				break;
+			}
+		}
+	}
+}
+
+static void discard_rsp_fcs(const struct l2cap_frame *frame, uint16_t scid)
+{
+	int i;
+	int dir = frame->in ? 0 : 1;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != frame->index)
+			continue;
+
+		if (chan_list[i].handle != frame->handle)
+			continue;
+
+		if (frame->in) {
+			if (chan_list[i].scid == scid) {
+				chan_list[i].rsp_fcs[dir] = -1;
+				break;
+			}
+		} else {
+			if (chan_list[i].dcid == scid) {
+				chan_list[i].rsp_fcs[dir] = -1;
+				break;
+			}
+		}
+	}
+}
+
 static int get_chan_data_index(const struct l2cap_frame *frame)
 {
 	int i;
@@ -797,7 +993,8 @@ static void print_unknown_options(const struct l2cap_frame *source,
 }
 
 static void print_config_options(const struct l2cap_frame *frame,
-				uint8_t offset, uint16_t cid, bool response)
+				uint8_t offset, uint16_t cid, bool response,
+				bool success)
 {
 	const uint8_t *data = frame->data + offset;
 	uint16_t size = frame->size - offset;
@@ -882,6 +1079,14 @@ static void print_config_options(const struct l2cap_frame *frame,
 					get_le16(data + consumed + 9));
 			break;
 		case 0x05:
+			if (response) {
+				if (success)
+					assign_rsp_fcs(frame,
+							data[consumed + 2],
+									cid);
+			} else
+				assign_req_fcs(frame, data[consumed + 2], cid);
+
 			switch (data[consumed + 2]) {
 			case 0x00:
 				str = "No FCS";
@@ -1178,20 +1383,43 @@ static void sig_config_req(const struct l2cap_frame *frame)
 
 	print_cid("Destination", pdu->dcid);
 	print_config_flags(pdu->flags);
-	print_config_options(frame, 4, le16_to_cpu(pdu->dcid), false);
+	print_config_options(frame, 4, le16_to_cpu(pdu->dcid), false, false);
 }
 
 static void sig_config_rsp(const struct l2cap_frame *frame)
 {
 	const struct bt_l2cap_pdu_config_rsp *pdu = frame->data;
+	bool final = !(le16_to_cpu(pdu->flags) & 0x0001);
+	uint16_t result = le16_to_cpu(pdu->result);
+	bool success = result == 0x0000;
 
 	print_cid("Source", pdu->scid);
 	print_config_flags(pdu->flags);
 	print_config_result(pdu->result);
-	if (pdu->result == 0x0003)
+	if (result == 0x0003) {
+		if (final) {
+			discard_req_fcs(frame, le16_to_cpu(pdu->scid));
+			discard_rsp_fcs(frame, le16_to_cpu(pdu->scid));
+		}
 		print_unknown_options(frame, 6);
-	else
-		print_config_options(frame, 6, le16_to_cpu(pdu->scid), true);
+	} else {
+		print_config_options(frame, 6, le16_to_cpu(pdu->scid), true,
+								success);
+
+		/* Pending (0x0004) isn't final */
+		if (final) {
+			if (success) {
+				apply_req_fcs(frame, le16_to_cpu(pdu->scid));
+				apply_rsp_fcs(frame, le16_to_cpu(pdu->scid));
+
+				discard_req_fcs(frame, le16_to_cpu(pdu->scid));
+				discard_rsp_fcs(frame, le16_to_cpu(pdu->scid));
+			} else if (result != 0x0004) {
+				discard_req_fcs(frame, le16_to_cpu(pdu->scid));
+				discard_rsp_fcs(frame, le16_to_cpu(pdu->scid));
+			}
+		}
+	}
 }
 
 static void sig_disconn_req(const struct l2cap_frame *frame)
@@ -2740,6 +2968,11 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			}
 
 			display_printf("\n");
+
+			chan = get_chan(&frame);
+			if (chan && chan->fcs && frame.size >= 2)
+				frame.size -= 2;
+
 			break;
 		}
 
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 2/6] monitor: Add OBEX protocol decoder
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 3/6] monitor: Decode PBAP/MAP/BIP Application Parameters tags Frédéric Danis
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

From: Frédéric Danis <frederic.danis.oss@gmail.com>

Decode OBEX traffic instead of hexdumping it: opcodes, response codes,
CONNECT/SETPATH fields and headers, including the BIP IMG-Handle and
IMG-Descriptor headers, and the Target/Who UUIDs of PBAP, FTP, MAP, BIP
and IrMC/SyncML.

OBEX runs on RFCOMM channels and L2CAP PSMs which are only known from
SDP records, so scan SDP attribute responses, including continuations,
for OBEX service records and record their RFCOMM channel or
GoepL2capPsm. UIH frames on such a channel and L2CAP frames on such a
PSM are passed to the OBEX decoder. These mappings are dropped on ACL
disconnection.

Key L2CAP OBEX sessions on l2cap_chan_key(), so that a CONNECT request
and its response, sent on different CIDs, are matched and the fixed
fields of the response are decoded. The request state of a session is
cleared on RFCOMM DISC/DM and on L2CAP Disconnection Request.

Hexdump frame.data/frame.size instead of data/size for PSMs without a
dissector, so the ERTM/Streaming control fields and FCS are not
included.

Assisted-by: Claude:claude-sonnet-5
---
v2->v3:
  - Fix a possible uint32_t overflow in obex_de_next()'s SDP
    element-length arithmetic by computing it in 64-bit space before
    comparing it against the available buffer size.
  - Fix obex_de_uuid16() extracting the short value from the wrong half
    (high instead of low 16 bits) of a 32-bit SDP UUID.
  - Stop special-casing L2CAP PSM 0x1001: only dispatch to the OBEX
    decoder once a PSM has actually been learned from an SDP record via
    obex_add_psm()/obex_psm().

v3->v4:
  - Fix the disconnect handler's SCID/DCID resolution to the
    direction-independent session key: SCID is the sender's own CID so
    it matches the local chan_list entry on a locally-initiated
    disconnect, and DCID matches it on a peer-initiated one (the two
    were swapped).
  - Drop obex_remove_channel()'s clearing of the SDP-learned
    obex_chan_list mapping itself, so a peer can reopen the same
    RFCOMM service on the still-up ACL link without repeating SDP;
    only the per-session request/profile state is cleared on teardown
    now.
  - Use a channel/handle-zero check (!channel) instead of an explicit
    handle == 0x0000 comparison to detect free obex_req_list slots.
  - Validate a 128-bit UUID against the Bluetooth Base UUID suffix
    before treating it as a 16-bit assigned number, instead of
    assuming any 128-bit value in that attribute is Base UUID-derived.
  - Recognize OBEX running directly over a dedicated L2CAP PSM (e.g.
    BIP's AVRCP Cover Art) by also scanning the Protocol Descriptor
    List for an L2CAP PSM parameter, not just an RFCOMM channel
    number.
  - Only trust a record's attribute 0x0200 as a GOEP L2CAP PSM once
    the record has been confirmed to actually speak OBEX via its
    protocol descriptor list(s), since other profiles reuse the same
    attribute ID for unrelated UINT16 values; remember the candidate
    PSM and decide once the whole record has been scanned.
  - Decode UTF-16 surrogate pairs into their combined supplementary-
    plane code point instead of encoding each surrogate half as its
    own (invalid) UTF-8 sequence.

v4->v5:
  - Use the processed frame's data/size, not the original pre-FCS-
    strip/pre-reassembly packet parameters, in the default-PSM
    hexdump fallback.

v5->v6:
  - Special-case the SDP Nil type (size index 0) in obex_de_next() to
    a zero data length instead of 1, matching monitor/sdp.c's
    get_size(), so scanning a Nil-valued attribute doesn't desync by
    consuming one byte too many.

v7->v8:
  - Trim comments and commit message.

 Makefile.tools   |    1 +
 monitor/l2cap.c  |   15 +-
 monitor/obex.c   | 1063 ++++++++++++++++++++++++++++++++++++++++++++++
 monitor/obex.h   |  118 +++++
 monitor/packet.c |    5 +-
 monitor/rfcomm.c |   16 +-
 monitor/sdp.c    |   12 +-
 7 files changed, 1222 insertions(+), 8 deletions(-)
 create mode 100644 monitor/obex.c
 create mode 100644 monitor/obex.h

diff --git a/Makefile.tools b/Makefile.tools
index 3a376b3d0..f67a89085 100644
--- a/Makefile.tools
+++ b/Makefile.tools
@@ -49,6 +49,7 @@ monitor_btmon_SOURCES = monitor/main.c monitor/bt.h \
 				monitor/a2dp.h monitor/a2dp.c \
 				monitor/rfcomm.h monitor/rfcomm.c \
 				monitor/bnep.h monitor/bnep.c \
+				monitor/obex.h monitor/obex.c \
 				monitor/hwdb.h monitor/hwdb.c \
 				monitor/keys.h monitor/keys.c \
 				monitor/analyze.h monitor/analyze.c \
diff --git a/monitor/l2cap.c b/monitor/l2cap.c
index 114037336..d4714a9e6 100644
--- a/monitor/l2cap.c
+++ b/monitor/l2cap.c
@@ -35,6 +35,7 @@
 #include "rfcomm.h"
 #include "bnep.h"
 #include "att.h"
+#include "obex.h"
 
 #define L2CAP_MODE_BASIC		0x00
 #define L2CAP_MODE_RETRANS		0x01
@@ -1428,6 +1429,14 @@ static void sig_disconn_req(const struct l2cap_frame *frame)
 
 	print_cid("Destination", pdu->dcid);
 	print_cid("Source", pdu->scid);
+
+	/* SCID belongs to the sender and DCID to the recipient */
+	obex_remove_session(frame->index, frame->handle,
+			l2cap_chan_key(frame->index, !frame->in, frame->handle,
+						le16_to_cpu(pdu->scid)));
+	obex_remove_session(frame->index, frame->handle,
+			l2cap_chan_key(frame->index, frame->in, frame->handle,
+						le16_to_cpu(pdu->dcid)));
 }
 
 static void sig_disconn_rsp(const struct l2cap_frame *frame)
@@ -3000,7 +3009,11 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			avdtp_packet(&frame);
 			break;
 		default:
-			packet_hexdump(data, size);
+			if (obex_psm(index, handle, frame.psm))
+				obex_packet(&frame, l2cap_chan_key(index, in,
+								handle, cid));
+			else
+				packet_hexdump(frame.data, frame.size);
 			break;
 		}
 		break;
diff --git a/monitor/obex.c b/monitor/obex.c
new file mode 100644
index 000000000..770d375db
--- /dev/null
+++ b/monitor/obex.c
@@ -0,0 +1,1063 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright © 2025 Collabora Ltd.
+ *
+ *
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+#include "bluetooth/bluetooth.h"
+#include "bluetooth/uuid.h"
+
+#include "src/shared/util.h"
+#include "bt.h"
+#include "packet.h"
+#include "display.h"
+#include "l2cap.h"
+#include "obex.h"
+
+/* SDP Data Element types (see monitor/sdp.c type_table) */
+#define SDP_DE_UINT		1
+#define SDP_DE_UUID		3
+#define SDP_DE_SEQ		6
+
+#define SDP_ATTR_SVCLASS_ID_LIST	0x0001
+#define SDP_ATTR_PROTO_DESC_LIST	0x0004
+#define SDP_ATTR_ADD_PROTO_DESC_LISTS	0x000d
+#define SDP_ATTR_GOEP_L2CAP_PSM		0x0200
+
+#define MAX_OBEX_CHAN 64
+#define MAX_OBEX_REQ  32
+
+struct obex_chan_data {
+	uint16_t index;
+	uint16_t handle;
+	uint8_t channel;
+	char profile[32];
+};
+
+static struct obex_chan_data obex_chan_list[MAX_OBEX_CHAN];
+
+struct obex_req_data {
+	uint16_t index;
+	uint16_t handle;
+	uint16_t channel;
+	uint8_t opcode;
+};
+
+static struct obex_req_data obex_req_list[MAX_OBEX_REQ];
+
+void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
+							const char *profile)
+{
+	int i, n = -1;
+
+	if (!channel)
+		return;
+
+	for (i = 0; i < MAX_OBEX_CHAN; i++) {
+		if (!obex_chan_list[i].channel) {
+			if (n < 0)
+				n = i;
+			continue;
+		}
+
+		if (obex_chan_list[i].index == index &&
+				obex_chan_list[i].handle == handle &&
+				obex_chan_list[i].channel == channel) {
+			n = i;
+			break;
+		}
+	}
+
+	if (n < 0)
+		return;
+
+	obex_chan_list[n].index = index;
+	obex_chan_list[n].handle = handle;
+	obex_chan_list[n].channel = channel;
+
+	if (profile)
+		snprintf(obex_chan_list[n].profile,
+				sizeof(obex_chan_list[n].profile),
+							"%s", profile);
+	else
+		obex_chan_list[n].profile[0] = '\0';
+}
+
+bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
+							const char **profile)
+{
+	int i;
+
+	if (!channel)
+		return false;
+
+	for (i = 0; i < MAX_OBEX_CHAN; i++) {
+		if (!obex_chan_list[i].channel)
+			continue;
+
+		if (obex_chan_list[i].index == index &&
+				obex_chan_list[i].handle == handle &&
+				obex_chan_list[i].channel == channel) {
+			if (profile)
+				*profile = obex_chan_list[i].profile;
+			return true;
+		}
+	}
+
+	return false;
+}
+
+#define MAX_OBEX_PSM 16
+
+struct obex_psm_data {
+	uint16_t index;
+	uint16_t handle;
+	uint16_t psm;
+};
+
+static struct obex_psm_data obex_psm_list[MAX_OBEX_PSM];
+
+void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm)
+{
+	int i, n = -1;
+
+	if (!psm)
+		return;
+
+	for (i = 0; i < MAX_OBEX_PSM; i++) {
+		if (!obex_psm_list[i].psm) {
+			if (n < 0)
+				n = i;
+			continue;
+		}
+
+		if (obex_psm_list[i].index == index &&
+				obex_psm_list[i].handle == handle &&
+				obex_psm_list[i].psm == psm) {
+			n = i;
+			break;
+		}
+	}
+
+	if (n < 0)
+		return;
+
+	obex_psm_list[n].index = index;
+	obex_psm_list[n].handle = handle;
+	obex_psm_list[n].psm = psm;
+}
+
+bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm)
+{
+	int i;
+
+	if (!psm)
+		return false;
+
+	for (i = 0; i < MAX_OBEX_PSM; i++) {
+		if (!obex_psm_list[i].psm)
+			continue;
+
+		if (obex_psm_list[i].index == index &&
+				obex_psm_list[i].handle == handle &&
+				obex_psm_list[i].psm == psm)
+			return true;
+	}
+
+	return false;
+}
+
+static void obex_clear_request(uint16_t index, uint16_t handle,
+							uint16_t channel)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_REQ; i++) {
+		if (obex_req_list[i].index == index &&
+				obex_req_list[i].handle == handle &&
+				obex_req_list[i].channel == channel)
+			memset(&obex_req_list[i], 0, sizeof(obex_req_list[i]));
+	}
+}
+
+void obex_remove_channel(uint16_t index, uint16_t handle, uint8_t channel)
+{
+	if (!channel)
+		return;
+
+	obex_clear_request(index, handle, channel);
+}
+
+void obex_remove_session(uint16_t index, uint16_t handle, uint16_t channel)
+{
+	obex_clear_request(index, handle, channel);
+}
+
+void obex_disconnect_handle(uint16_t index, uint16_t handle)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_CHAN; i++) {
+		if (!obex_chan_list[i].channel)
+			continue;
+
+		if (obex_chan_list[i].index == index &&
+				obex_chan_list[i].handle == handle)
+			memset(&obex_chan_list[i], 0,
+						sizeof(obex_chan_list[i]));
+	}
+
+	for (i = 0; i < MAX_OBEX_REQ; i++) {
+		if (obex_req_list[i].index == index &&
+				obex_req_list[i].handle == handle)
+			memset(&obex_req_list[i], 0, sizeof(obex_req_list[i]));
+	}
+
+	for (i = 0; i < MAX_OBEX_PSM; i++) {
+		if (!obex_psm_list[i].psm)
+			continue;
+
+		if (obex_psm_list[i].index == index &&
+				obex_psm_list[i].handle == handle)
+			memset(&obex_psm_list[i], 0,
+						sizeof(obex_psm_list[i]));
+	}
+}
+
+static void obex_set_last_request(uint16_t index, uint16_t handle,
+					uint16_t channel, uint8_t opcode)
+{
+	int i, n = -1;
+
+	for (i = 0; i < MAX_OBEX_REQ; i++) {
+		if (!obex_req_list[i].channel && n < 0) {
+			n = i;
+			continue;
+		}
+
+		if (obex_req_list[i].index == index &&
+				obex_req_list[i].handle == handle &&
+				obex_req_list[i].channel == channel) {
+			n = i;
+			break;
+		}
+	}
+
+	if (n < 0)
+		return;
+
+	obex_req_list[n].index = index;
+	obex_req_list[n].handle = handle;
+	obex_req_list[n].channel = channel;
+	obex_req_list[n].opcode = opcode;
+}
+
+static bool obex_last_request_is(uint16_t index, uint16_t handle,
+					uint16_t channel, uint8_t opcode)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_REQ; i++) {
+		if (obex_req_list[i].handle != handle ||
+				obex_req_list[i].index != index ||
+				obex_req_list[i].channel != channel)
+			continue;
+
+		return obex_req_list[i].opcode == opcode;
+	}
+
+	return false;
+}
+
+/* Returns the size of the SDP Data Element at data, 0 if invalid */
+static uint32_t obex_de_next(const uint8_t *data, uint32_t size,
+				uint8_t *type, const uint8_t **value,
+				uint32_t *vsize)
+{
+	uint32_t extrabytes, datalen, elemlen;
+	uint64_t total;
+
+	if (size < 1)
+		return 0;
+
+	*type = (data[0] & 0xf8) >> 3;
+
+	switch (data[0] & 0x07) {
+	case 0:
+		extrabytes = 0;
+		/* Nil has no value */
+		datalen = (data[0] & 0xf8) == 0 ? 0 : 1;
+		break;
+	case 1:
+		extrabytes = 0;
+		datalen = 2;
+		break;
+	case 2:
+		extrabytes = 0;
+		datalen = 4;
+		break;
+	case 3:
+		extrabytes = 0;
+		datalen = 8;
+		break;
+	case 4:
+		extrabytes = 0;
+		datalen = 16;
+		break;
+	case 5:
+		extrabytes = 1;
+		if (size < 2)
+			return 0;
+		datalen = data[1];
+		break;
+	case 6:
+		extrabytes = 2;
+		if (size < 3)
+			return 0;
+		datalen = get_be16(data + 1);
+		break;
+	case 7:
+		extrabytes = 4;
+		if (size < 5)
+			return 0;
+		datalen = get_be32(data + 1);
+		break;
+	default:
+		return 0;
+	}
+
+	total = (uint64_t) 1 + extrabytes + datalen;
+
+	if (total > size)
+		return 0;
+
+	elemlen = (uint32_t) total;
+
+	*value = data + 1 + extrabytes;
+	*vsize = datalen;
+
+	return elemlen;
+}
+
+static uint16_t obex_de_uuid16(const uint8_t *data, uint32_t size)
+{
+	/* Bluetooth Base UUID */
+	static const uint8_t base_uuid_suffix[12] = {
+		0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80,
+		0x5f, 0x9b, 0x34, 0xfb
+	};
+
+	switch (size) {
+	case 2:
+		return get_be16(data);
+	case 4: {
+		uint32_t uuid32 = get_be32(data);
+
+		if (uuid32 & 0xffff0000)
+			return 0;
+
+		return (uint16_t) uuid32;
+	}
+	case 16:
+		if (memcmp(data + 4, base_uuid_suffix,
+						sizeof(base_uuid_suffix)))
+			return 0;
+
+		if (data[0] || data[1])
+			return 0;
+
+		return get_be16(data + 2);
+	default:
+		return 0;
+	}
+}
+
+/* Record the RFCOMM channel or L2CAP PSM of a Protocol Descriptor List
+ * carrying OBEX. Returns whether it carries OBEX.
+ */
+static bool obex_scan_proto_list(uint16_t index, uint16_t handle,
+				const uint8_t *data, uint32_t size,
+				const char *profile)
+{
+	uint32_t pos = 0;
+	uint8_t channel = 0;
+	uint16_t psm = 0;
+	bool have_obex = false;
+
+	while (pos < size) {
+		uint8_t type;
+		const uint8_t *entry;
+		uint32_t entry_size;
+		uint32_t elemlen = obex_de_next(data + pos, size - pos,
+							&type, &entry,
+							&entry_size);
+		uint32_t epos;
+		uint16_t uuid16 = 0;
+		bool have_uuid = false;
+
+		if (!elemlen)
+			break;
+
+		if (type != SDP_DE_SEQ)
+			goto next;
+
+		epos = 0;
+
+		while (epos < entry_size) {
+			uint8_t etype;
+			const uint8_t *eval;
+			uint32_t evsize;
+			uint32_t eelemlen = obex_de_next(entry + epos,
+							entry_size - epos,
+							&etype, &eval,
+							&evsize);
+
+			if (!eelemlen)
+				break;
+
+			if (!have_uuid) {
+				if (etype == SDP_DE_UUID) {
+					uuid16 = obex_de_uuid16(eval, evsize);
+					have_uuid = true;
+				}
+			} else if (uuid16 == 0x0003 && evsize >= 1) {
+				channel = eval[0];
+			} else if (uuid16 == 0x0100 && evsize >= 2) {
+				psm = get_be16(eval);
+			}
+
+			epos += eelemlen;
+		}
+
+		if (uuid16 == 0x0008)
+			have_obex = true;
+
+next:
+		pos += elemlen;
+	}
+
+	if (have_obex && channel)
+		obex_add_channel(index, handle, channel, profile);
+	else if (have_obex && psm)
+		obex_add_psm(index, handle, psm);
+
+	return have_obex;
+}
+
+static bool obex_scan_svclass(const uint8_t *data, uint32_t size,
+							char *buf, size_t len)
+{
+	uint8_t type;
+	const uint8_t *value;
+	uint32_t vsize;
+	uint16_t uuid16;
+
+	if (!obex_de_next(data, size, &type, &value, &vsize))
+		return false;
+
+	if (type != SDP_DE_UUID)
+		return false;
+
+	uuid16 = obex_de_uuid16(value, vsize);
+	if (!uuid16)
+		return false;
+
+	snprintf(buf, len, "%s", bt_uuid16_to_str(uuid16));
+
+	return true;
+}
+
+static void obex_scan_attr_list(uint16_t index, uint16_t handle,
+				const uint8_t *data, uint32_t size)
+{
+	uint32_t pos = 0;
+	char profile[32] = { 0 };
+	bool have_obex = false;
+	uint16_t goep_psm = 0;
+
+	while (pos < size) {
+		uint8_t type;
+		const uint8_t *id_val;
+		uint32_t id_size;
+		uint32_t idlen = obex_de_next(data + pos, size - pos, &type,
+							&id_val, &id_size);
+		uint16_t attr_id;
+		uint32_t vallen;
+		const uint8_t *attr_val;
+		uint32_t attr_size;
+
+		if (!idlen || id_size < 2)
+			break;
+
+		attr_id = get_be16(id_val);
+		pos += idlen;
+
+		vallen = obex_de_next(data + pos, size - pos, &type,
+						&attr_val, &attr_size);
+		if (!vallen)
+			break;
+
+		switch (attr_id) {
+		case SDP_ATTR_SVCLASS_ID_LIST:
+			obex_scan_svclass(attr_val, attr_size, profile,
+							sizeof(profile));
+			break;
+		case SDP_ATTR_PROTO_DESC_LIST:
+			if (obex_scan_proto_list(index, handle, attr_val,
+							attr_size, profile))
+				have_obex = true;
+			break;
+		case SDP_ATTR_ADD_PROTO_DESC_LISTS: {
+			uint32_t apos = 0;
+
+			while (apos < attr_size) {
+				uint8_t atype;
+				const uint8_t *aval;
+				uint32_t avsize;
+				uint32_t aelemlen = obex_de_next(
+						attr_val + apos,
+						attr_size - apos,
+						&atype, &aval, &avsize);
+
+				if (!aelemlen)
+					break;
+
+				if (atype == SDP_DE_SEQ &&
+						obex_scan_proto_list(index,
+								handle, aval,
+								avsize,
+								profile))
+					have_obex = true;
+
+				apos += aelemlen;
+			}
+			break;
+		}
+		case SDP_ATTR_GOEP_L2CAP_PSM:
+			/* Attribute 0x0200 is profile specific, only used
+			 * once the record is known to carry OBEX.
+			 */
+			if (type == SDP_DE_UINT && attr_size == 2)
+				goep_psm = get_be16(attr_val);
+			break;
+		}
+
+		pos += vallen;
+	}
+
+	if (have_obex && goep_psm)
+		obex_add_psm(index, handle, goep_psm);
+}
+
+/* nested is set for a Service Search Attribute Response, which holds a
+ * sequence of attribute lists.
+ */
+void obex_sdp_scan(const struct l2cap_frame *frame, const uint8_t *data,
+						uint32_t size, bool nested)
+{
+	uint8_t type;
+	const uint8_t *val;
+	uint32_t vsize;
+	uint32_t pos = 0;
+
+	if (!obex_de_next(data, size, &type, &val, &vsize) ||
+							type != SDP_DE_SEQ)
+		return;
+
+	if (!nested) {
+		obex_scan_attr_list(frame->index, frame->handle, val, vsize);
+		return;
+	}
+
+	while (pos < vsize) {
+		uint8_t rtype;
+		const uint8_t *rval;
+		uint32_t rvsize;
+		uint32_t relemlen = obex_de_next(val + pos, vsize - pos,
+							&rtype, &rval, &rvsize);
+
+		if (!relemlen)
+			break;
+
+		if (rtype == SDP_DE_SEQ)
+			obex_scan_attr_list(frame->index, frame->handle,
+							rval, rvsize);
+
+		pos += relemlen;
+	}
+}
+
+struct obex_opcode_data {
+	uint8_t code;
+	const char *str;
+};
+
+static const struct obex_opcode_data obex_req_table[] = {
+	{ OBEX_OP_CONNECT,	"Connect"		},
+	{ OBEX_OP_DISCONNECT,	"Disconnect"		},
+	{ OBEX_OP_PUT,		"Put"			},
+	{ OBEX_OP_GET,		"Get"			},
+	{ OBEX_OP_SETPATH,	"Set Path"		},
+	{ OBEX_OP_ACTION,	"Action"		},
+	{ OBEX_OP_SESSION,	"Session"		},
+	{ OBEX_OP_ABORT,	"Abort"			},
+	{ }
+};
+
+static const struct obex_opcode_data obex_rsp_table[] = {
+	{ OBEX_RSP_CONTINUE,			"Continue"		},
+	{ OBEX_RSP_SUCCESS,			"OK, Success"		},
+	{ OBEX_RSP_CREATED,			"Created"		},
+	{ OBEX_RSP_ACCEPTED,			"Accepted"		},
+	{ OBEX_RSP_NON_AUTHORITATIVE,		"Non-Authoritative"	},
+	{ OBEX_RSP_NO_CONTENT,			"No Content"		},
+	{ OBEX_RSP_RESET_CONTENT,		"Reset Content"		},
+	{ OBEX_RSP_PARTIAL_CONTENT,		"Partial Content"	},
+	{ OBEX_RSP_MULTIPLE_CHOICES,		"Multiple Choices"	},
+	{ OBEX_RSP_MOVED_PERMANENTLY,		"Moved Permanently"	},
+	{ OBEX_RSP_MOVED_TEMPORARILY,		"Moved Temporarily"	},
+	{ OBEX_RSP_SEE_OTHER,			"See Other"		},
+	{ OBEX_RSP_NOT_MODIFIED,		"Not Modified"		},
+	{ OBEX_RSP_USE_PROXY,			"Use Proxy"		},
+	{ OBEX_RSP_BAD_REQUEST,			"Bad Request"		},
+	{ OBEX_RSP_UNAUTHORIZED,		"Unauthorized"		},
+	{ OBEX_RSP_PAYMENT_REQUIRED,		"Payment Required"	},
+	{ OBEX_RSP_FORBIDDEN,			"Forbidden"		},
+	{ OBEX_RSP_NOT_FOUND,			"Not Found"		},
+	{ OBEX_RSP_METHOD_NOT_ALLOWED,		"Method Not Allowed"	},
+	{ OBEX_RSP_NOT_ACCEPTABLE,		"Not Acceptable"	},
+	{ OBEX_RSP_PROXY_AUTH_REQUIRED,
+					"Proxy Authentication Required" },
+	{ OBEX_RSP_REQUEST_TIME_OUT,		"Request Time Out"	},
+	{ OBEX_RSP_CONFLICT,			"Conflict"		},
+	{ OBEX_RSP_GONE,			"Gone"			},
+	{ OBEX_RSP_LENGTH_REQUIRED,		"Length Required"	},
+	{ OBEX_RSP_PRECONDITION_FAILED,		"Precondition Failed"	},
+	{ OBEX_RSP_REQ_ENTITY_TOO_LARGE,
+					"Requested Entity Too Large"	},
+	{ OBEX_RSP_REQ_URL_TOO_LARGE,		"Requested URL Too Large" },
+	{ OBEX_RSP_UNSUPPORTED_MEDIA_TYPE,	"Unsupported Media Type" },
+	{ OBEX_RSP_INTERNAL_SERVER_ERROR,	"Internal Server Error"	},
+	{ OBEX_RSP_NOT_IMPLEMENTED,		"Not Implemented"	},
+	{ OBEX_RSP_BAD_GATEWAY,			"Bad Gateway"		},
+	{ OBEX_RSP_SERVICE_UNAVAILABLE,		"Service Unavailable"	},
+	{ OBEX_RSP_GATEWAY_TIMEOUT,		"Gateway Timeout"	},
+	{ OBEX_RSP_VERSION_NOT_SUPPORTED,	"HTTP Version Not Supported" },
+	{ OBEX_RSP_DATABASE_FULL,		"Database Full"	},
+	{ OBEX_RSP_DATABASE_LOCKED,		"Database Locked"	},
+	{ }
+};
+
+static const char *obex_opcode_str(uint8_t code, bool *is_request)
+{
+	int i;
+
+	for (i = 0; obex_req_table[i].str; i++) {
+		if (obex_req_table[i].code == code) {
+			*is_request = true;
+			return obex_req_table[i].str;
+		}
+	}
+
+	for (i = 0; obex_rsp_table[i].str; i++) {
+		if (obex_rsp_table[i].code == code) {
+			*is_request = false;
+			return obex_rsp_table[i].str;
+		}
+	}
+
+	return NULL;
+}
+
+static const struct {
+	uint8_t id;
+	const char *str;
+} obex_hdr_table[] = {
+	{ OBEX_HDR_COUNT,		"Count"			},
+	{ OBEX_HDR_NAME,		"Name"			},
+	{ OBEX_HDR_TYPE,		"Type"			},
+	{ OBEX_HDR_LENGTH,		"Length"		},
+	{ OBEX_HDR_TIME,		"Time"			},
+	{ OBEX_HDR_DESCRIPTION,		"Description"		},
+	{ OBEX_HDR_TARGET,		"Target"		},
+	{ OBEX_HDR_HTTP,		"HTTP"			},
+	{ OBEX_HDR_BODY,		"Body"			},
+	{ OBEX_HDR_BODY_END,		"End of Body"		},
+	{ OBEX_HDR_WHO,			"Who"			},
+	{ OBEX_HDR_CONNECTION,		"Connection ID"		},
+	{ OBEX_HDR_APPARAM,		"Application Parameters" },
+	{ OBEX_HDR_AUTHCHAL,		"Authentication Challenge" },
+	{ OBEX_HDR_AUTHRESP,		"Authentication Response" },
+	{ OBEX_HDR_CREATOR,		"Creator ID"		},
+	{ OBEX_HDR_WANUUID,		"WAN UUID"		},
+	{ OBEX_HDR_OBJECTCLASS,		"Object Class"		},
+	{ OBEX_HDR_SESSIONPARAM,	"Session Parameters"	},
+	{ OBEX_HDR_SESSIONSEQ,		"Session Sequence Number" },
+	{ OBEX_HDR_ACTION,		"Action ID"		},
+	{ OBEX_HDR_DESTNAME,		"Destination Name"	},
+	{ OBEX_HDR_PERMISSIONS,		"Permissions"		},
+	{ OBEX_HDR_SRM,			"Single Response Mode"	},
+	{ OBEX_HDR_SRMP,		"SRM Parameters"	},
+	{ OBEX_HDR_IMG_HANDLE,		"Image Handle"		},
+	{ OBEX_HDR_IMG_DESC,		"Image Descriptor"	},
+	{ }
+};
+
+static const char *obex_hdr_str(uint8_t id)
+{
+	int i;
+
+	for (i = 0; obex_hdr_table[i].str; i++) {
+		if (obex_hdr_table[i].id == id)
+			return obex_hdr_table[i].str;
+	}
+
+	return "Unknown";
+}
+
+/* Target/Who header values, as used by obexd/client */
+static const struct {
+	const uint8_t uuid[16];
+	uint8_t len;
+	const char *str;
+} obex_target_table[] = {
+	{ { 0x79, 0x61, 0x35, 0xf0, 0xf0, 0xc5, 0x11, 0xd8,
+	    0x09, 0x66, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
+					"Phonebook Access (PBAP)" },
+	{ { 0xf9, 0xec, 0x7b, 0xc4, 0x95, 0x3c, 0x11, 0xd2,
+	    0x98, 0x4e, 0x52, 0x54, 0x00, 0xdc, 0x9e, 0x09 }, 16,
+					"File Transfer (FTP)" },
+	{ { 0xbb, 0x58, 0x2b, 0x40, 0x42, 0x0c, 0x11, 0xdb,
+	    0xb0, 0xde, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
+					"Message Access (MAP)" },
+	{ { 0xbb, 0x58, 0x2b, 0x41, 0x42, 0x0c, 0x11, 0xdb,
+	    0xb0, 0xde, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
+					"Message Notification (MNS)" },
+	{ { 0x71, 0x63, 0xdd, 0x54, 0x4a, 0x7e, 0x11, 0xe2,
+	    0xb4, 0x7c, 0x00, 0x50, 0xc2, 0x49, 0x00, 0x48 }, 16,
+				"Basic Imaging (BIP, AVRCP Cover Art)" },
+	{ { 'I', 'R', 'M', 'C', '-', 'S', 'Y', 'N', 'C' }, 9,
+					"Synchronization (IrMC/SyncML)" },
+	{ }
+};
+
+static const char *obex_target_str(const uint8_t *data, uint16_t len)
+{
+	int i;
+
+	for (i = 0; obex_target_table[i].len; i++) {
+		if (obex_target_table[i].len != len)
+			continue;
+
+		if (!memcmp(obex_target_table[i].uuid, data, len))
+			return obex_target_table[i].str;
+	}
+
+	return NULL;
+}
+
+static void print_unicode_header(const char *label, const uint8_t *data,
+						uint16_t len, uint8_t indent)
+{
+	char buf[256];
+	size_t n = 0;
+	uint16_t i;
+
+	for (i = 0; i + 1 < len && n + 4 < sizeof(buf); i += 2) {
+		uint16_t ch = get_be16(data + i);
+		uint32_t cp;
+
+		if (ch == 0x0000)
+			break;
+
+		if (ch >= 0xd800 && ch <= 0xdbff) {
+			/* High surrogate: combine with a following low
+			 * surrogate into a single supplementary-plane code
+			 * point, or fall back to the replacement character
+			 * if unpaired.
+			 */
+			uint16_t lo = 0;
+
+			if (i + 3 < len)
+				lo = get_be16(data + i + 2);
+
+			if (lo >= 0xdc00 && lo <= 0xdfff) {
+				cp = 0x10000 + (((uint32_t) ch - 0xd800) << 10)
+							+ (lo - 0xdc00);
+				i += 2;
+			} else {
+				cp = 0xfffd;
+			}
+		} else if (ch >= 0xdc00 && ch <= 0xdfff) {
+			/* Unpaired low surrogate. */
+			cp = 0xfffd;
+		} else {
+			cp = ch;
+		}
+
+		if (cp < 0x80) {
+			buf[n++] = (char) cp;
+		} else if (cp < 0x800) {
+			buf[n++] = 0xc0 | (cp >> 6);
+			buf[n++] = 0x80 | (cp & 0x3f);
+		} else if (cp < 0x10000) {
+			buf[n++] = 0xe0 | (cp >> 12);
+			buf[n++] = 0x80 | ((cp >> 6) & 0x3f);
+			buf[n++] = 0x80 | (cp & 0x3f);
+		} else {
+			buf[n++] = 0xf0 | (cp >> 18);
+			buf[n++] = 0x80 | ((cp >> 12) & 0x3f);
+			buf[n++] = 0x80 | ((cp >> 6) & 0x3f);
+			buf[n++] = 0x80 | (cp & 0x3f);
+		}
+	}
+
+	buf[n] = '\0';
+
+	print_field("%*c%s: %s", indent, ' ', label, buf);
+}
+
+static void obex_print_apparam(const uint8_t *data, uint16_t size,
+								uint8_t indent)
+{
+	uint16_t pos = 0;
+
+	while (pos + 2 <= size) {
+		uint8_t tag = data[pos];
+		uint8_t len = data[pos + 1];
+
+		if ((uint32_t) pos + 2 + len > size) {
+			print_text(COLOR_ERROR, "invalid app parameter length");
+			break;
+		}
+
+		print_field("%*cTag 0x%02x len %d", indent, ' ', tag, len);
+		if (len)
+			packet_hexdump(data + pos + 2, len);
+
+		pos += 2 + len;
+	}
+}
+
+static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent)
+{
+	while (frame->size > 0) {
+		uint8_t hdr_id;
+		const char *label;
+
+		if (!l2cap_frame_get_u8(frame, &hdr_id))
+			return false;
+
+		label = obex_hdr_str(hdr_id);
+
+		switch (hdr_id & OBEX_HDR_TYPE_MASK) {
+		case OBEX_HDR_TYPE_UNICODE:
+		case OBEX_HDR_TYPE_BYTES: {
+			uint16_t hlen, vlen;
+			const uint8_t *data;
+
+			if (!l2cap_frame_get_be16(frame, &hlen))
+				return false;
+
+			if (hlen < 3 || hlen - 3 > frame->size) {
+				print_text(COLOR_ERROR,
+						"invalid header length");
+				return false;
+			}
+
+			vlen = hlen - 3;
+			data = frame->data;
+
+			if ((hdr_id & OBEX_HDR_TYPE_MASK) ==
+							OBEX_HDR_TYPE_UNICODE) {
+				print_unicode_header(label, data, vlen,
+									indent);
+			} else if (hdr_id == OBEX_HDR_TARGET ||
+					hdr_id == OBEX_HDR_WHO) {
+				const char *profile =
+					obex_target_str(data, vlen);
+
+				if (profile) {
+					print_field("%*c%s: %s", indent, ' ',
+							label, profile);
+				} else {
+					print_field("%*c%s: [len %d]", indent,
+							' ', label, vlen);
+					if (vlen)
+						packet_hexdump(data, vlen);
+				}
+			} else if (hdr_id == OBEX_HDR_TYPE ||
+					hdr_id == OBEX_HDR_IMG_DESC) {
+				print_field("%*c%s: %.*s", indent, ' ',
+							label, vlen, data);
+			} else {
+				print_field("%*c%s: [len %d]", indent, ' ',
+								label, vlen);
+
+				if (hdr_id == OBEX_HDR_TIME)
+					print_field("%*c%.*s", indent + 2, ' ',
+								vlen, data);
+
+				if (hdr_id == OBEX_HDR_APPARAM)
+					obex_print_apparam(data, vlen,
+								indent + 2);
+				else if (vlen)
+					packet_hexdump(data, vlen);
+			}
+
+			l2cap_frame_pull(frame, frame, vlen);
+			break;
+		}
+		case OBEX_HDR_TYPE_UINT8: {
+			uint8_t value;
+
+			if (!l2cap_frame_get_u8(frame, &value))
+				return false;
+
+			print_field("%*c%s: %d (0x%02x)", indent, ' ', label,
+							value, value);
+			break;
+		}
+		case OBEX_HDR_TYPE_UINT32: {
+			uint32_t value;
+
+			if (!l2cap_frame_get_be32(frame, &value))
+				return false;
+
+			print_field("%*c%s: %u (0x%08x)", indent, ' ', label,
+							value, value);
+			break;
+		}
+		}
+	}
+
+	return true;
+}
+
+static bool obex_connect_fields(struct l2cap_frame *frame, uint8_t indent)
+{
+	uint8_t version, flags;
+	uint16_t mtu;
+
+	if (!l2cap_frame_get_u8(frame, &version) ||
+			!l2cap_frame_get_u8(frame, &flags) ||
+			!l2cap_frame_get_be16(frame, &mtu))
+		return false;
+
+	print_field("%*cVersion: %d.%d", indent, ' ', version >> 4,
+							version & 0x0f);
+	print_field("%*cFlags: 0x%02x", indent, ' ', flags);
+	print_field("%*cMax Packet Length: %d", indent, ' ', mtu);
+
+	return true;
+}
+
+static bool obex_setpath_fields(struct l2cap_frame *frame, uint8_t indent)
+{
+	uint8_t flags, constants;
+
+	if (!l2cap_frame_get_u8(frame, &flags) ||
+			!l2cap_frame_get_u8(frame, &constants))
+		return false;
+
+	print_field("%*cFlags: 0x%02x", indent, ' ', flags);
+	print_field("%*cConstants: 0x%02x", indent, ' ', constants);
+
+	return true;
+}
+
+void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
+{
+	struct l2cap_frame obex_frame;
+	struct l2cap_frame *f = &obex_frame;
+	uint8_t opcode, code, indent = 1;
+	uint16_t length, pdu_len;
+	const char *opcode_str;
+	const char *color;
+	bool is_request = false;
+	const uint8_t *trailer;
+	uint16_t trailer_len;
+
+	l2cap_frame_pull(f, frame, 0);
+
+	if (f->size < 3)
+		goto fail;
+
+	if (!l2cap_frame_get_u8(f, &opcode) ||
+			!l2cap_frame_get_be16(f, &length))
+		goto fail;
+
+	if (length < 3)
+		goto fail;
+
+	pdu_len = length - 3;
+
+	if (f->size < pdu_len)
+		goto fail;
+
+	trailer = (const uint8_t *) f->data + pdu_len;
+	trailer_len = f->size - pdu_len;
+
+	f->size = pdu_len;
+
+	code = opcode & ~OBEX_FINAL_BIT;
+
+	opcode_str = obex_opcode_str(code, &is_request);
+
+	if (opcode_str)
+		color = frame->in ? COLOR_MAGENTA : COLOR_BLUE;
+	else {
+		opcode_str = "Unknown";
+		color = COLOR_WHITE_BG;
+	}
+
+	print_indent(6, color, "OBEX: ", opcode_str, COLOR_OFF,
+			" (0x%2.2x) final %d len %d", code,
+			(opcode & OBEX_FINAL_BIT) ? 1 : 0, length);
+
+	if (is_request && code == OBEX_OP_CONNECT) {
+		if (!obex_connect_fields(f, indent))
+			goto fail;
+	} else if (!is_request && obex_last_request_is(frame->index,
+						frame->handle, channel,
+						OBEX_OP_CONNECT)) {
+		if (!obex_connect_fields(f, indent))
+			goto fail;
+	} else if (is_request && code == OBEX_OP_SETPATH) {
+		if (!obex_setpath_fields(f, indent))
+			goto fail;
+	}
+
+	if (!obex_print_headers(f, indent))
+		goto fail;
+
+	if (is_request)
+		obex_set_last_request(frame->index, frame->handle, channel,
+								code);
+
+	if (trailer_len) {
+		print_field("%*cTrailing data: [len %d]", indent, ' ',
+							trailer_len);
+		packet_hexdump(trailer, trailer_len);
+	}
+
+	return;
+
+fail:
+	print_text(COLOR_ERROR, "frame too short");
+	packet_hexdump(frame->data, frame->size);
+}
diff --git a/monitor/obex.h b/monitor/obex.h
new file mode 100644
index 000000000..5af28ea8b
--- /dev/null
+++ b/monitor/obex.h
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ *
+ *  BlueZ - Bluetooth protocol stack for Linux
+ *
+ *  Copyright (C) 2024  BlueZ project
+ *
+ *
+ */
+
+/* OBEX request opcodes (FINAL bit 0x80 is masked out before matching) */
+#define OBEX_OP_CONNECT		0x00
+#define OBEX_OP_DISCONNECT	0x01
+#define OBEX_OP_PUT		0x02
+#define OBEX_OP_GET		0x03
+#define OBEX_OP_SETPATH	0x05
+#define OBEX_OP_ACTION		0x06
+#define OBEX_OP_SESSION	0x07
+#define OBEX_OP_ABORT		0x7f
+
+#define OBEX_FINAL_BIT		0x80
+
+/* OBEX response codes */
+#define OBEX_RSP_CONTINUE			0x10
+#define OBEX_RSP_SUCCESS			0x20
+#define OBEX_RSP_CREATED			0x21
+#define OBEX_RSP_ACCEPTED			0x22
+#define OBEX_RSP_NON_AUTHORITATIVE		0x23
+#define OBEX_RSP_NO_CONTENT			0x24
+#define OBEX_RSP_RESET_CONTENT			0x25
+#define OBEX_RSP_PARTIAL_CONTENT		0x26
+#define OBEX_RSP_MULTIPLE_CHOICES		0x30
+#define OBEX_RSP_MOVED_PERMANENTLY		0x31
+#define OBEX_RSP_MOVED_TEMPORARILY		0x32
+#define OBEX_RSP_SEE_OTHER			0x33
+#define OBEX_RSP_NOT_MODIFIED			0x34
+#define OBEX_RSP_USE_PROXY			0x35
+#define OBEX_RSP_BAD_REQUEST			0x40
+#define OBEX_RSP_UNAUTHORIZED			0x41
+#define OBEX_RSP_PAYMENT_REQUIRED		0x42
+#define OBEX_RSP_FORBIDDEN			0x43
+#define OBEX_RSP_NOT_FOUND			0x44
+#define OBEX_RSP_METHOD_NOT_ALLOWED		0x45
+#define OBEX_RSP_NOT_ACCEPTABLE		0x46
+#define OBEX_RSP_PROXY_AUTH_REQUIRED		0x47
+#define OBEX_RSP_REQUEST_TIME_OUT		0x48
+#define OBEX_RSP_CONFLICT			0x49
+#define OBEX_RSP_GONE				0x4a
+#define OBEX_RSP_LENGTH_REQUIRED		0x4b
+#define OBEX_RSP_PRECONDITION_FAILED		0x4c
+#define OBEX_RSP_REQ_ENTITY_TOO_LARGE		0x4d
+#define OBEX_RSP_REQ_URL_TOO_LARGE		0x4e
+#define OBEX_RSP_UNSUPPORTED_MEDIA_TYPE	0x4f
+#define OBEX_RSP_INTERNAL_SERVER_ERROR		0x50
+#define OBEX_RSP_NOT_IMPLEMENTED		0x51
+#define OBEX_RSP_BAD_GATEWAY			0x52
+#define OBEX_RSP_SERVICE_UNAVAILABLE		0x53
+#define OBEX_RSP_GATEWAY_TIMEOUT		0x54
+#define OBEX_RSP_VERSION_NOT_SUPPORTED		0x55
+#define OBEX_RSP_DATABASE_FULL			0x60
+#define OBEX_RSP_DATABASE_LOCKED		0x61
+
+/* OBEX header identifiers */
+#define OBEX_HDR_COUNT		0xc0
+#define OBEX_HDR_NAME		0x01
+#define OBEX_HDR_TYPE		0x42
+#define OBEX_HDR_LENGTH	0xc3
+#define OBEX_HDR_TIME		0x44
+#define OBEX_HDR_DESCRIPTION	0x05
+#define OBEX_HDR_TARGET	0x46
+#define OBEX_HDR_HTTP		0x47
+#define OBEX_HDR_BODY		0x48
+#define OBEX_HDR_BODY_END	0x49
+#define OBEX_HDR_WHO		0x4a
+#define OBEX_HDR_CONNECTION	0xcb
+#define OBEX_HDR_APPARAM	0x4c
+#define OBEX_HDR_AUTHCHAL	0x4d
+#define OBEX_HDR_AUTHRESP	0x4e
+#define OBEX_HDR_CREATOR	0xcf
+#define OBEX_HDR_WANUUID	0x50
+#define OBEX_HDR_OBJECTCLASS	0x51
+#define OBEX_HDR_SESSIONPARAM	0x52
+#define OBEX_HDR_SESSIONSEQ	0x93
+#define OBEX_HDR_ACTION	0x94
+#define OBEX_HDR_DESTNAME	0x15
+#define OBEX_HDR_PERMISSIONS	0xd6
+#define OBEX_HDR_SRM		0x97
+#define OBEX_HDR_SRMP		0x98
+
+/* BIP (Basic Imaging Profile) specific headers, see BIP spec section
+ * 5.1. Only meaningful on a BIP channel, but the header IDs are not
+ * reused by any other known profile so they can be decoded generically.
+ */
+#define OBEX_HDR_IMG_HANDLE	0x30
+#define OBEX_HDR_IMG_DESC	0x71
+
+/* Header ID encoding (top 2 bits of the header ID byte) */
+#define OBEX_HDR_TYPE_MASK	0xc0
+#define OBEX_HDR_TYPE_UNICODE	0x00
+#define OBEX_HDR_TYPE_BYTES	0x40
+#define OBEX_HDR_TYPE_UINT8	0x80
+#define OBEX_HDR_TYPE_UINT32	0xc0
+
+void obex_packet(const struct l2cap_frame *frame, uint16_t channel);
+
+void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
+							const char *profile);
+bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
+							const char **profile);
+void obex_remove_channel(uint16_t index, uint16_t handle, uint8_t channel);
+void obex_remove_session(uint16_t index, uint16_t handle, uint16_t channel);
+void obex_disconnect_handle(uint16_t index, uint16_t handle);
+
+void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm);
+bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm);
+
+void obex_sdp_scan(const struct l2cap_frame *frame, const uint8_t *data,
+						uint32_t size, bool nested);
diff --git a/monitor/packet.c b/monitor/packet.c
index eddf8706a..7414910c7 100644
--- a/monitor/packet.c
+++ b/monitor/packet.c
@@ -47,6 +47,7 @@
 #include "keys.h"
 #include "packet.h"
 #include "l2cap.h"
+#include "obex.h"
 #include "control.h"
 #include "vendor.h"
 #include "msft.h"
@@ -12311,8 +12312,10 @@ static void disconnect_complete_evt(struct timeval *tv, uint16_t index,
 	print_handle(evt->handle);
 	print_reason(evt->reason);
 
-	if (evt->status == 0x00)
+	if (evt->status == 0x00) {
 		release_handle(le16_to_cpu(evt->handle));
+		obex_disconnect_handle(index, le16_to_cpu(evt->handle));
+	}
 }
 
 static void auth_complete_evt(struct timeval *tv, uint16_t index,
diff --git a/monitor/rfcomm.c b/monitor/rfcomm.c
index 419910127..9e01c8a96 100644
--- a/monitor/rfcomm.c
+++ b/monitor/rfcomm.c
@@ -31,6 +31,7 @@
 #include "keys.h"
 #include "sdp.h"
 #include "rfcomm.h"
+#include "obex.h"
 
 static const char *cr_str[] = {
 	"RSP",
@@ -390,8 +391,9 @@ static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 	uint8_t credits;
 	struct l2cap_frame *frame = &rfcomm_frame->l2cap_frame;
 	struct rfcomm_lhdr *hdr = &rfcomm_frame->hdr;
+	uint8_t channel = RFCOMM_GET_CHANNEL(hdr->address);
 
-	if (!RFCOMM_GET_CHANNEL(hdr->address))
+	if (!channel)
 		return mcc_frame(rfcomm_frame, indent);
 
 	/* fetching credits from UIH frame */
@@ -402,7 +404,11 @@ static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 		print_field("%*cCredits: %d", indent, ' ', hdr->credits);
 	}
 
-	packet_hexdump(frame->data, frame->size);
+	if (obex_channel(frame->index, frame->handle, channel, NULL))
+		obex_packet(frame, channel);
+	else
+		packet_hexdump(frame->data, frame->size);
+
 	return true;
 }
 
@@ -494,9 +500,13 @@ void rfcomm_packet(const struct l2cap_frame *frame)
 	print_rfcomm_hdr(&rfcomm_frame, indent);
 
 	/* UIH frame */
-	if (ctype == 0xef)
+	if (ctype == 0xef) {
 		if (!uih_frame(&rfcomm_frame, indent))
 			goto fail;
+	} else if (ctype == 0x43 || ctype == 0x0f) {
+		obex_remove_channel(frame->index, frame->handle,
+					RFCOMM_GET_CHANNEL(hdr.address));
+	}
 
 	return;
 
diff --git a/monitor/sdp.c b/monitor/sdp.c
index ce06b73ec..25a718be8 100644
--- a/monitor/sdp.c
+++ b/monitor/sdp.c
@@ -29,6 +29,7 @@
 #include "display.h"
 #include "l2cap.h"
 #include "sdp.h"
+#include "obex.h"
 
 #define MAX_TID 16
 #define MAX_CONT_SIZE 17
@@ -423,7 +424,8 @@ struct cont_data {
 
 static struct cont_data cont_list[MAX_CONT];
 
-static void handle_continuation(struct tid_data *tid, bool nested,
+static void handle_continuation(const struct l2cap_frame *frame,
+			struct tid_data *tid, bool nested,
 			uint16_t bytes, const uint8_t *data, uint16_t size)
 {
 	uint8_t *newdata;
@@ -437,6 +439,7 @@ static void handle_continuation(struct tid_data *tid, bool nested,
 	if (tid->cont[0] == 0x00 && data[bytes] == 0x00) {
 		decode_data_elements(0, 2, data, bytes,
 				nested ? print_attr_lists : print_attr_list);
+		obex_sdp_scan(frame, data, bytes, nested);
 
 		print_continuation(data + bytes, size - bytes);
 		return;
@@ -489,6 +492,8 @@ static void handle_continuation(struct tid_data *tid, bool nested,
 
 		decode_data_elements(0, 2, cont_list[n].data, cont_list[n].size,
 				nested ? print_attr_lists : print_attr_list);
+		obex_sdp_scan(frame, cont_list[n].data, cont_list[n].size,
+								nested);
 
 		free(cont_list[n].data);
 		cont_list[n].data = NULL;
@@ -641,7 +646,7 @@ static void attr_rsp(const struct l2cap_frame *frame, struct tid_data *tid)
 
 	bytes = common_rsp(frame, tid);
 
-	handle_continuation(tid, false, bytes,
+	handle_continuation(frame, tid, false, bytes,
 					frame->data + 2, frame->size - 2);
 
 	clear_tid(tid);
@@ -689,7 +694,8 @@ static void search_attr_rsp(const struct l2cap_frame *frame,
 
 	bytes = common_rsp(frame, tid);
 
-	handle_continuation(tid, true, bytes, frame->data + 2, frame->size - 2);
+	handle_continuation(frame, tid, true, bytes, frame->data + 2,
+							frame->size - 2);
 
 	clear_tid(tid);
 }
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 3/6] monitor: Decode PBAP/MAP/BIP Application Parameters tags
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 2/6] monitor: Add OBEX protocol decoder Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 4/6] monitor: Reassemble L2CAP ERTM/Streaming SDUs Frédéric Danis
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

From: Frédéric Danis <frederic.danis.oss@gmail.com>

Add the PBAP, MAP and BIP Application Parameters tag tables, so that
known tags are shown with their name and decoded value instead of a
generic Tag/Len hexdump.

Application Parameters headers don't identify the profile, so remember
the profile found in the CONNECT Target/Who header of each session. It
is cleared on each CONNECT request and from obex_remove_channel(),
obex_remove_session() and obex_disconnect_handle(). Sessions without a
known profile keep the generic dump.

Assisted-by: Claude:claude-sonnet-5
---
v2->v3:
  - Clear the learned profile classification from
    obex_remove_channel(), obex_remove_session() and
    obex_disconnect_handle() on session/channel/handle teardown, and
    also reset it on every CONNECT, so a later session reusing the same
    index/handle/channel triplet can't inherit a stale profile from an
    unrelated earlier session.

v3->v4:
  - Explain in a comment above obex_remove_channel() why the
    SDP-learned obex_chan_list mapping itself is kept across RFCOMM
    teardown (a reconnect on the same ACL link must still resolve the
    channel), and bail out early when called with a zero channel.
  - Use a channel-zero check (!channel) instead of an explicit
    handle == 0x0000 comparison to detect free obex_profile_list
    slots.

v7->v8:
  - Trim comments and commit message.

 monitor/obex.c | 337 +++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 324 insertions(+), 13 deletions(-)

diff --git a/monitor/obex.c b/monitor/obex.c
index 770d375db..779313352 100644
--- a/monitor/obex.c
+++ b/monitor/obex.c
@@ -41,6 +41,14 @@
 #define MAX_OBEX_CHAN 64
 #define MAX_OBEX_REQ  32
 
+/* Profiles with a known Application Parameters tag table */
+enum obex_profile {
+	OBEX_PROFILE_UNKNOWN,
+	OBEX_PROFILE_PBAP,
+	OBEX_PROFILE_MAP,
+	OBEX_PROFILE_BIP,
+};
+
 struct obex_chan_data {
 	uint16_t index;
 	uint16_t handle;
@@ -194,17 +202,48 @@ static void obex_clear_request(uint16_t index, uint16_t handle,
 	}
 }
 
+/* Profile from the CONNECT Target/Who header, used to decode the
+ * Application Parameters headers of the session.
+ */
+#define MAX_OBEX_PROFILE 32
+
+struct obex_profile_data {
+	uint16_t index;
+	uint16_t handle;
+	uint16_t channel;
+	enum obex_profile profile;
+};
+
+static struct obex_profile_data obex_profile_list[MAX_OBEX_PROFILE];
+
+static void obex_clear_profile(uint16_t index, uint16_t handle,
+							uint16_t channel)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
+		if (obex_profile_list[i].index == index &&
+				obex_profile_list[i].handle == handle &&
+				obex_profile_list[i].channel == channel)
+			memset(&obex_profile_list[i], 0,
+					sizeof(obex_profile_list[i]));
+	}
+}
+
+/* The SDP mapping is kept, the channel can be reopened without SDP */
 void obex_remove_channel(uint16_t index, uint16_t handle, uint8_t channel)
 {
 	if (!channel)
 		return;
 
 	obex_clear_request(index, handle, channel);
+	obex_clear_profile(index, handle, channel);
 }
 
 void obex_remove_session(uint16_t index, uint16_t handle, uint16_t channel)
 {
 	obex_clear_request(index, handle, channel);
+	obex_clear_profile(index, handle, channel);
 }
 
 void obex_disconnect_handle(uint16_t index, uint16_t handle)
@@ -236,6 +275,16 @@ void obex_disconnect_handle(uint16_t index, uint16_t handle)
 			memset(&obex_psm_list[i], 0,
 						sizeof(obex_psm_list[i]));
 	}
+
+	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
+		if (!obex_profile_list[i].channel)
+			continue;
+
+		if (obex_profile_list[i].index == index &&
+				obex_profile_list[i].handle == handle)
+			memset(&obex_profile_list[i], 0,
+					sizeof(obex_profile_list[i]));
+	}
 }
 
 static void obex_set_last_request(uint16_t index, uint16_t handle,
@@ -283,6 +332,52 @@ static bool obex_last_request_is(uint16_t index, uint16_t handle,
 	return false;
 }
 
+static void obex_set_profile(uint16_t index, uint16_t handle,
+					uint16_t channel,
+					enum obex_profile profile)
+{
+	int i, n = -1;
+
+	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
+		if (!obex_profile_list[i].channel && n < 0) {
+			n = i;
+			continue;
+		}
+
+		if (obex_profile_list[i].index == index &&
+				obex_profile_list[i].handle == handle &&
+				obex_profile_list[i].channel == channel) {
+			n = i;
+			break;
+		}
+	}
+
+	if (n < 0)
+		return;
+
+	obex_profile_list[n].index = index;
+	obex_profile_list[n].handle = handle;
+	obex_profile_list[n].channel = channel;
+	obex_profile_list[n].profile = profile;
+}
+
+static enum obex_profile obex_get_profile(uint16_t index, uint16_t handle,
+							uint16_t channel)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
+		if (obex_profile_list[i].handle != handle ||
+				obex_profile_list[i].index != index ||
+				obex_profile_list[i].channel != channel)
+			continue;
+
+		return obex_profile_list[i].profile;
+	}
+
+	return OBEX_PROFILE_UNKNOWN;
+}
+
 /* Returns the size of the SDP Data Element at data, 0 if invalid */
 static uint32_t obex_de_next(const uint8_t *data, uint32_t size,
 				uint8_t *type, const uint8_t **value,
@@ -734,24 +829,31 @@ static const struct {
 	const uint8_t uuid[16];
 	uint8_t len;
 	const char *str;
+	enum obex_profile profile;
 } obex_target_table[] = {
 	{ { 0x79, 0x61, 0x35, 0xf0, 0xf0, 0xc5, 0x11, 0xd8,
 	    0x09, 0x66, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
-					"Phonebook Access (PBAP)" },
+					"Phonebook Access (PBAP)",
+					OBEX_PROFILE_PBAP },
 	{ { 0xf9, 0xec, 0x7b, 0xc4, 0x95, 0x3c, 0x11, 0xd2,
 	    0x98, 0x4e, 0x52, 0x54, 0x00, 0xdc, 0x9e, 0x09 }, 16,
-					"File Transfer (FTP)" },
+					"File Transfer (FTP)",
+					OBEX_PROFILE_UNKNOWN },
 	{ { 0xbb, 0x58, 0x2b, 0x40, 0x42, 0x0c, 0x11, 0xdb,
 	    0xb0, 0xde, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
-					"Message Access (MAP)" },
+					"Message Access (MAP)",
+					OBEX_PROFILE_MAP },
 	{ { 0xbb, 0x58, 0x2b, 0x41, 0x42, 0x0c, 0x11, 0xdb,
 	    0xb0, 0xde, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }, 16,
-					"Message Notification (MNS)" },
+					"Message Notification (MNS)",
+					OBEX_PROFILE_MAP },
 	{ { 0x71, 0x63, 0xdd, 0x54, 0x4a, 0x7e, 0x11, 0xe2,
 	    0xb4, 0x7c, 0x00, 0x50, 0xc2, 0x49, 0x00, 0x48 }, 16,
-				"Basic Imaging (BIP, AVRCP Cover Art)" },
+				"Basic Imaging (BIP, AVRCP Cover Art)",
+					OBEX_PROFILE_BIP },
 	{ { 'I', 'R', 'M', 'C', '-', 'S', 'Y', 'N', 'C' }, 9,
-					"Synchronization (IrMC/SyncML)" },
+					"Synchronization (IrMC/SyncML)",
+					OBEX_PROFILE_UNKNOWN },
 	{ }
 };
 
@@ -770,6 +872,22 @@ static const char *obex_target_str(const uint8_t *data, uint16_t len)
 	return NULL;
 }
 
+static enum obex_profile obex_target_profile(const uint8_t *data,
+							uint16_t len)
+{
+	int i;
+
+	for (i = 0; obex_target_table[i].len; i++) {
+		if (obex_target_table[i].len != len)
+			continue;
+
+		if (!memcmp(obex_target_table[i].uuid, data, len))
+			return obex_target_table[i].profile;
+	}
+
+	return OBEX_PROFILE_UNKNOWN;
+}
+
 static void print_unicode_header(const char *label, const uint8_t *data,
 						uint16_t len, uint8_t indent)
 {
@@ -831,8 +949,192 @@ static void print_unicode_header(const char *label, const uint8_t *data,
 	print_field("%*c%s: %s", indent, ' ', label, buf);
 }
 
+/* Application Parameters tags from the PBAP/MAP/BIP specifications */
+enum obex_aparam_type {
+	OBEX_APARAM_U8,
+	OBEX_APARAM_U16,
+	OBEX_APARAM_U32,
+	OBEX_APARAM_U64,
+	OBEX_APARAM_U128,
+	OBEX_APARAM_STR,
+	OBEX_APARAM_BYTES,
+};
+
+struct obex_aparam_tag {
+	uint8_t tag;
+	const char *str;
+	enum obex_aparam_type type;
+};
+
+static const struct obex_aparam_tag obex_pbap_aparam_table[] = {
+	{ 0x01, "Order",			OBEX_APARAM_U8	},
+	{ 0x02, "Search Value",			OBEX_APARAM_STR	},
+	{ 0x03, "Search Attribute",		OBEX_APARAM_U8	},
+	{ 0x04, "Max List Count",		OBEX_APARAM_U16	},
+	{ 0x05, "List Start Offset",		OBEX_APARAM_U16	},
+	{ 0x06, "Filter",			OBEX_APARAM_U64	},
+	{ 0x07, "Format",			OBEX_APARAM_U8	},
+	{ 0x08, "Phonebook Size",		OBEX_APARAM_U16	},
+	{ 0x09, "New Missed Calls",		OBEX_APARAM_U8	},
+	{ 0x0a, "Primary Folder Version",	OBEX_APARAM_U128 },
+	{ 0x0b, "Secondary Folder Version",	OBEX_APARAM_U128 },
+	{ 0x0c, "vCard Selector",		OBEX_APARAM_U64	},
+	{ 0x0d, "Database Identifier",		OBEX_APARAM_U128 },
+	{ 0x0e, "vCard Selector Operator",	OBEX_APARAM_U8	},
+	{ 0x0f, "Reset New Missed Calls",	OBEX_APARAM_U8	},
+	{ 0x10, "Supported Features",		OBEX_APARAM_U32	},
+	{ }
+};
+
+static const struct obex_aparam_tag obex_map_aparam_table[] = {
+	{ 0x01, "Max List Count",			OBEX_APARAM_U16	},
+	{ 0x02, "List Start Offset",			OBEX_APARAM_U16	},
+	{ 0x03, "Filter Message Type",			OBEX_APARAM_U8	},
+	{ 0x04, "Filter Period Begin",			OBEX_APARAM_STR	},
+	{ 0x05, "Filter Period End",			OBEX_APARAM_STR	},
+	{ 0x06, "Filter Read Status",			OBEX_APARAM_U8	},
+	{ 0x07, "Filter Recipient",			OBEX_APARAM_STR	},
+	{ 0x08, "Filter Originator",			OBEX_APARAM_STR	},
+	{ 0x09, "Filter Priority",			OBEX_APARAM_U8	},
+	{ 0x0a, "Attachment",				OBEX_APARAM_U8	},
+	{ 0x0b, "Transparent",				OBEX_APARAM_U8	},
+	{ 0x0c, "Retry",				OBEX_APARAM_U8	},
+	{ 0x0d, "New Message",				OBEX_APARAM_U8	},
+	{ 0x0e, "Notification Status",			OBEX_APARAM_U8	},
+	{ 0x0f, "MAS Instance ID",			OBEX_APARAM_U8	},
+	{ 0x10, "Parameter Mask",			OBEX_APARAM_U32	},
+	{ 0x11, "Folder Listing Size",			OBEX_APARAM_U16	},
+	{ 0x12, "Listing Size",				OBEX_APARAM_U16	},
+	{ 0x13, "Subject Length",			OBEX_APARAM_U8	},
+	{ 0x14, "Charset",				OBEX_APARAM_U8	},
+	{ 0x15, "Fraction Request",			OBEX_APARAM_U8	},
+	{ 0x16, "Fraction Deliver",			OBEX_APARAM_U8	},
+	{ 0x17, "Status Indicator",			OBEX_APARAM_U8	},
+	{ 0x18, "Status Value",				OBEX_APARAM_U8	},
+	{ 0x19, "MSE Time",				OBEX_APARAM_STR	},
+	{ 0x1a, "Database Identifier",			OBEX_APARAM_BYTES },
+	{ 0x1b, "Conversation Listing Version Counter", OBEX_APARAM_BYTES },
+	{ 0x1c, "Presence Availability",		OBEX_APARAM_U8	},
+	{ 0x1d, "Presence Text",			OBEX_APARAM_STR	},
+	{ 0x1e, "Last Activity",			OBEX_APARAM_STR	},
+	{ 0x1f, "Filter Last Activity Begin",		OBEX_APARAM_STR	},
+	{ 0x20, "Filter Last Activity End",		OBEX_APARAM_STR	},
+	{ 0x21, "Chat State",				OBEX_APARAM_U8	},
+	{ 0x22, "Conversation ID",			OBEX_APARAM_BYTES },
+	{ 0x23, "Folder Version Counter",		OBEX_APARAM_BYTES },
+	{ 0x24, "Filter Message Handle",		OBEX_APARAM_STR	},
+	{ 0x25, "Notification Filter Mask",		OBEX_APARAM_U32	},
+	{ 0x26, "Conversation Parameter Mask",		OBEX_APARAM_U32	},
+	{ 0x27, "Filter Message Source Type",		OBEX_APARAM_U8	},
+	{ 0x29, "MAP Supported Features",		OBEX_APARAM_U32	},
+	{ }
+};
+
+static const struct obex_aparam_tag obex_bip_aparam_table[] = {
+	{ 0x01, "Number of Returned Handles",	OBEX_APARAM_U16	},
+	{ 0x02, "List Start Offset",		OBEX_APARAM_U16	},
+	{ 0x03, "Latest Captured Images",	OBEX_APARAM_U8	},
+	{ 0x04, "Partial File Length",		OBEX_APARAM_U32	},
+	{ 0x05, "Partial File Start Offset",	OBEX_APARAM_U32	},
+	{ 0x06, "Total File Size",		OBEX_APARAM_U32	},
+	{ 0x07, "End Flag",			OBEX_APARAM_U8	},
+	{ 0x08, "Remote Display",		OBEX_APARAM_U8	},
+	{ }
+};
+
+static void obex_print_apparam_tag(enum obex_profile profile, uint8_t tag,
+				const uint8_t *data, uint8_t len,
+				uint8_t indent)
+{
+	const struct obex_aparam_tag *table;
+	int i;
+
+	switch (profile) {
+	case OBEX_PROFILE_PBAP:
+		table = obex_pbap_aparam_table;
+		break;
+	case OBEX_PROFILE_MAP:
+		table = obex_map_aparam_table;
+		break;
+	case OBEX_PROFILE_BIP:
+		table = obex_bip_aparam_table;
+		break;
+	case OBEX_PROFILE_UNKNOWN:
+	default:
+		table = NULL;
+		break;
+	}
+
+	for (i = 0; table && table[i].str; i++) {
+		if (table[i].tag != tag)
+			continue;
+
+		switch (table[i].type) {
+		case OBEX_APARAM_U8:
+			if (len == 1) {
+				print_field("%*c%s: %d (0x%02x)", indent, ' ',
+						table[i].str, data[0],
+						data[0]);
+				return;
+			}
+			break;
+		case OBEX_APARAM_U16:
+			if (len == 2) {
+				uint16_t val = get_be16(data);
+
+				print_field("%*c%s: %u (0x%04x)", indent, ' ',
+						table[i].str, val, val);
+				return;
+			}
+			break;
+		case OBEX_APARAM_U32:
+			if (len == 4) {
+				uint32_t val = get_be32(data);
+
+				print_field("%*c%s: %u (0x%08x)", indent, ' ',
+						table[i].str, val, val);
+				return;
+			}
+			break;
+		case OBEX_APARAM_U64:
+			if (len == 8) {
+				print_field("%*c%s: 0x%016" PRIx64, indent,
+						' ', table[i].str,
+						get_be64(data));
+				return;
+			}
+			break;
+		case OBEX_APARAM_U128:
+			if (len == 16) {
+				print_field("%*c%s: 0x%016" PRIx64 "%016"
+						PRIx64, indent, ' ',
+						table[i].str, get_be64(data),
+						get_be64(data + 8));
+				return;
+			}
+			break;
+		case OBEX_APARAM_STR:
+			print_field("%*c%s: %.*s", indent, ' ', table[i].str,
+							len, data);
+			return;
+		case OBEX_APARAM_BYTES:
+			break;
+		}
+
+		print_field("%*c%s: [len %d]", indent, ' ', table[i].str,
+									len);
+		if (len)
+			packet_hexdump(data, len);
+		return;
+	}
+
+	print_field("%*cTag 0x%02x len %d", indent, ' ', tag, len);
+	if (len)
+		packet_hexdump(data, len);
+}
+
 static void obex_print_apparam(const uint8_t *data, uint16_t size,
-								uint8_t indent)
+				uint8_t indent, enum obex_profile profile)
 {
 	uint16_t pos = 0;
 
@@ -845,15 +1147,15 @@ static void obex_print_apparam(const uint8_t *data, uint16_t size,
 			break;
 		}
 
-		print_field("%*cTag 0x%02x len %d", indent, ' ', tag, len);
-		if (len)
-			packet_hexdump(data + pos + 2, len);
+		obex_print_apparam_tag(profile, tag, data + pos + 2, len,
+								indent);
 
 		pos += 2 + len;
 	}
 }
 
-static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent)
+static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent,
+							uint16_t channel)
 {
 	while (frame->size > 0) {
 		uint8_t hdr_id;
@@ -894,6 +1196,10 @@ static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent)
 				if (profile) {
 					print_field("%*c%s: %s", indent, ' ',
 							label, profile);
+					obex_set_profile(frame->index,
+						frame->handle, channel,
+						obex_target_profile(data,
+								vlen));
 				} else {
 					print_field("%*c%s: [len %d]", indent,
 							' ', label, vlen);
@@ -914,7 +1220,10 @@ static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent)
 
 				if (hdr_id == OBEX_HDR_APPARAM)
 					obex_print_apparam(data, vlen,
-								indent + 2);
+						indent + 2,
+						obex_get_profile(frame->index,
+							frame->handle,
+							channel));
 				else if (vlen)
 					packet_hexdump(data, vlen);
 			}
@@ -1030,6 +1339,8 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
 			(opcode & OBEX_FINAL_BIT) ? 1 : 0, length);
 
 	if (is_request && code == OBEX_OP_CONNECT) {
+		obex_clear_profile(frame->index, frame->handle, channel);
+
 		if (!obex_connect_fields(f, indent))
 			goto fail;
 	} else if (!is_request && obex_last_request_is(frame->index,
@@ -1042,7 +1353,7 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
 			goto fail;
 	}
 
-	if (!obex_print_headers(f, indent))
+	if (!obex_print_headers(f, indent, channel))
 		goto fail;
 
 	if (is_request)
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 4/6] monitor: Reassemble L2CAP ERTM/Streaming SDUs
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
                   ` (2 preceding siblings ...)
  2026-12-04 16:04 ` [PATCH BlueZ v8 3/6] monitor: Decode PBAP/MAP/BIP Application Parameters tags Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 5/6] monitor: Fix RFCOMM UIH frame length and credit-only handling Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 6/6] monitor: Reassemble OBEX PDUs split across RFCOMM UIH frames Frédéric Danis
  5 siblings, 0 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

ERTM and Streaming mode can segment an SDU across several I-frames, but
each I-frame was dissected on its own, and S-frames were passed to the
upper layer dissectors as empty payloads.

Reassemble SDUs per channel and direction, and skip S-frames before PSM
dispatch. Fragments are kept until a contiguous Start..End TxSeq run is
available, and the SDU is dispatched from the frame completing it, so
that the output follows the capture order even when an ERTM
retransmission completes an SDU after a later one. Fragments still
being buffered are hexdumped.

TxSeq values are mapped to positions which don't wrap, using the
cumulative ReqSeq acknowledgements to tell retransmissions from new
frames, and the TxSeq values received within the last sequence cycle
are remembered to discard retransmitted duplicates. Streaming mode has
no retransmission, so a gap discards the SDU in progress. An SDU
exceeding its declared length is discarded, and the number and size of
the fragments kept per direction are bounded.

Add a frag_len argument to obex_packet(), the number of trailing bytes
not already hexdumped with earlier fragments, and use it to limit the
Body/End-of-Body hexdumps.

Pass frame.data/frame.size to the ATT/EATT dissector instead of the raw
data/size, so it gets the reassembled SDU, and skip it for an empty SDU
since att_packet() reads the opcode before checking the size.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Claude:claude-opus-5-5
---
v1->v2: Fix commit title issue

v2->v3:
  - Retitled from "monitor: Reassemble L2CAP ERTM/Streaming fragments
    before dissecting" (subject line was exceeding the mailing list's
    80-character limit with the series prefix).
  - Track the expected TxSeq per direction alongside each reassembly
    buffer: a fragment matching the previous TxSeq is a retransmitted
    duplicate and is discarded instead of being appended again, and a
    fragment whose TxSeq doesn't match the expected value means a prior
    fragment was lost, so the in-progress SDU is discarded rather than
    reassembled past the gap.

v4->v5:
  - Track the TxSeq of the Start fragment that began the in-progress
    SDU (start_seq) and compare a new Start fragment against it, so a
    retransmitted duplicate of that same Start fragment is recognized
    and discarded instead of needlessly dropping the already-buffered
    Continuation fragments.

v5->v6:
  - Replace the "only check the immediately preceding TxSeq"
    duplicate-fragment check with a wraparound-aware range check
    against the whole start_seq..next_seq-1 span of already-received
    fragments, so a retransmission of an earlier (not just the most
    recent) fragment doesn't wrongly discard the buffered SDU.

v6->v7:
  - Track the uncapped fragment count received since the Start segment
    (sdu->received) and measure the duplicate/gap check as a window of
    that size (capped at seq_mod - 1) ending at next_seq - 1, instead
    of a start_seq..next_seq-1 span reduced mod seq_mod, so the check
    no longer wraps to an ambiguous zero once a full window's worth of
    fragments has been received.

v7->v8:
  - Rework the reassembly to keep out-of-order fragments, so ERTM
    retransmissions after REJ/SREJ complete the SDU instead of
    discarding it. Each SDU is decoded from the frame completing it,
    so the output follows the capture order.
  - Map TxSeq to positions which don't wrap, using the ReqSeq
    acknowledgements to tell retransmissions from new frames, and
    discard duplicates received within the last sequence cycle.
  - Streaming mode: discard the SDU in progress on a gap.
  - Discard an SDU exceeding its declared length, and bound the number
    and size of the fragments kept per direction.
  - Pass the number of bytes carried by the completing fragment, which
    isn't necessarily the End one, to obex_packet().
  - Pass frame.data/frame.size to the ATT/EATT dissector, and skip it
    for an empty SDU.
  - Trim comments and commit message.

 monitor/l2cap.c  | 635 ++++++++++++++++++++++++++++++++++++++++++++---
 monitor/obex.c   |  46 +++-
 monitor/obex.h   |   3 +-
 monitor/rfcomm.c |   2 +-
 4 files changed, 643 insertions(+), 43 deletions(-)

diff --git a/monitor/l2cap.c b/monitor/l2cap.c
index d4714a9e6..76a16e22c 100644
--- a/monitor/l2cap.c
+++ b/monitor/l2cap.c
@@ -86,9 +86,57 @@
 #define L2CAP_SAR_START		0x01
 #define L2CAP_SAR_END		0x02
 #define L2CAP_SAR_CONTINUE	0x03
+#define L2CAP_SAR_NONE		0xff	/* S-frame, no SAR field */
 
 #define MAX_CHAN 64
 
+/* ERTM/Streaming mode SAR fragment (Start/Continuation/End) waiting for
+ * the rest of its SDU.
+ */
+struct l2cap_sdu_fragment {
+	struct l2cap_sdu_fragment *next;	/* all pending fragments */
+	struct l2cap_sdu_fragment *prev;
+	struct l2cap_sdu_fragment *slot_next;	/* same TxSeq */
+	uint32_t pos;		/* absolute TxSeq position, see l2cap_sdu */
+	uint8_t sar;
+	uint16_t sdu_len;	/* total SDU length, Start only */
+	uint16_t len;
+	uint8_t data[];
+};
+
+/* Per direction SAR reassembly state of an ERTM/Streaming mode channel.
+ *
+ * An SDU is decoded when the frame completing it is received, so that
+ * the output follows the capture order, even if ERTM retransmissions
+ * complete an SDU after a later one has already been decoded.
+ *
+ * TxSeq values are mapped to an absolute position which doesn't wrap,
+ * relative to the most advanced TxSeq received (high/high_pos). seen is
+ * a bitmap, indexed by TxSeq, of the frames received within the last
+ * seq_mod positions, used to detect retransmitted duplicates.
+ */
+struct l2cap_sdu {
+	bool valid;
+	uint16_t seq_mod;
+	uint16_t high;
+	uint32_t high_pos;
+	bool ack_valid;
+	bool ack_received;	/* ack received by the local host */
+	uint16_t ack;		/* last ReqSeq acknowledging this direction */
+	uint8_t *seen;
+	struct l2cap_sdu_fragment *fragments;
+	struct l2cap_sdu_fragment **slots;	/* indexed by TxSeq */
+	uint32_t pending_count;
+	uint32_t pending_bytes;
+};
+
+/* Bounds on fragments kept per direction while waiting for the rest of
+ * their SDU: room for an SDU of the maximum length plus out-of-order
+ * fragments of the following ones.
+ */
+#define MAX_SDU_PENDING_FRAGMENTS	8192
+#define MAX_SDU_PENDING_BYTES		(4 * 65536)
+
 struct chan_data {
 	uint16_t index;
 	uint16_t handle;
@@ -105,11 +153,32 @@ struct chan_data {
 	uint8_t  fcs_dir[2];
 	int8_t   req_fcs[2];
 	int8_t   rsp_fcs[2];
+	struct l2cap_sdu sdu_rx[2];
 	struct packet_latency tx_l;
 };
 
 static struct chan_data chan_list[MAX_CHAN];
 
+static void reset_sdu(struct l2cap_sdu *sdu)
+{
+	struct l2cap_sdu_fragment *fragment;
+
+	while ((fragment = sdu->fragments)) {
+		sdu->fragments = fragment->next;
+		free(fragment);
+	}
+
+	free(sdu->seen);
+	free(sdu->slots);
+	memset(sdu, 0, sizeof(*sdu));
+}
+
+static void reset_sdu_rx(struct chan_data *chan)
+{
+	reset_sdu(&chan->sdu_rx[0]);
+	reset_sdu(&chan->sdu_rx[1]);
+}
+
 static void assign_scid(const struct l2cap_frame *frame, uint16_t scid,
 			uint16_t psm, uint8_t mode, uint8_t ctrlid)
 {
@@ -149,6 +218,7 @@ static void assign_scid(const struct l2cap_frame *frame, uint16_t scid,
 	if (n < 0)
 		return;
 
+	reset_sdu_rx(&chan_list[n]);
 	memset(&chan_list[n], 0, sizeof(chan_list[n]));
 	chan_list[n].index = frame->index;
 	chan_list[n].handle = frame->handle;
@@ -188,11 +258,13 @@ static void release_scid(const struct l2cap_frame *frame, uint16_t scid)
 
 		if (frame->in) {
 			if (chan_list[i].scid == scid) {
+				reset_sdu_rx(&chan_list[i]);
 				chan_list[i].handle = 0;
 				break;
 			}
 		} else {
 			if (chan_list[i].dcid == scid) {
+				reset_sdu_rx(&chan_list[i]);
 				chan_list[i].handle = 0;
 				break;
 			}
@@ -638,76 +710,100 @@ static char *mode2str(uint8_t mode)
 	}
 }
 
-static void l2cap_ctrl_ext_parse(struct l2cap_frame *frame, uint32_t ctrl)
+static uint8_t l2cap_ctrl_ext_parse(struct l2cap_frame *frame, uint32_t ctrl,
+					uint16_t *sdu_len, uint16_t *txseq,
+					uint16_t *reqseq, bool *ack)
 {
+	uint8_t sar = L2CAP_SAR_NONE;
+
+	*reqseq = (ctrl & L2CAP_EXT_CTRL_REQSEQ_MASK) >>
+						L2CAP_EXT_CTRL_REQSEQ_SHIFT;
+
 	display_printf("      %s:",
 		ctrl & L2CAP_EXT_CTRL_FRAME_TYPE ? "S-frame" : "I-frame");
 
 	if (ctrl & L2CAP_EXT_CTRL_FRAME_TYPE) {
-		display_printf(" %s",
-		supervisory2str((ctrl & L2CAP_EXT_CTRL_SUPERVISE_MASK) >>
-						L2CAP_EXT_CTRL_SUPER_SHIFT));
+		uint8_t super = (ctrl & L2CAP_EXT_CTRL_SUPERVISE_MASK) >>
+						L2CAP_EXT_CTRL_SUPER_SHIFT;
+
+		display_printf(" %s", supervisory2str(super));
+
+		/* SREJ without P-bit requests a single retransmission,
+		 * its ReqSeq doesn't acknowledge the preceding frames.
+		 */
+		*ack = super != L2CAP_SUPER_SREJ ||
+					(ctrl & L2CAP_EXT_CTRL_POLL);
 
 		if (ctrl & L2CAP_EXT_CTRL_POLL)
 			display_printf(" P-bit");
 	} else {
-		uint8_t sar = (ctrl & L2CAP_EXT_CTRL_SAR_MASK) >>
+		sar = (ctrl & L2CAP_EXT_CTRL_SAR_MASK) >>
 						L2CAP_EXT_CTRL_SAR_SHIFT;
 		display_printf(" %s", sar2str(sar));
 		if (sar == L2CAP_SAR_START) {
-			uint16_t len;
-
-			if (!l2cap_frame_get_le16(frame, &len))
-				return;
+			if (!l2cap_frame_get_le16(frame, sdu_len))
+				return L2CAP_SAR_NONE;
 
-			display_printf(" (len %d)", len);
+			display_printf(" (len %d)", *sdu_len);
 		}
-		display_printf(" TxSeq %d",
-			(ctrl & L2CAP_EXT_CTRL_TXSEQ_MASK) >>
-						L2CAP_EXT_CTRL_TXSEQ_SHIFT);
+		*txseq = (ctrl & L2CAP_EXT_CTRL_TXSEQ_MASK) >>
+						L2CAP_EXT_CTRL_TXSEQ_SHIFT;
+		display_printf(" TxSeq %d", *txseq);
 	}
 
-	display_printf(" ReqSeq %d", (ctrl & L2CAP_EXT_CTRL_REQSEQ_MASK) >>
-						L2CAP_EXT_CTRL_REQSEQ_SHIFT);
+	display_printf(" ReqSeq %d", *reqseq);
 
 	if (ctrl & L2CAP_EXT_CTRL_FINAL)
 		display_printf(" F-bit");
+
+	return sar;
 }
 
-static void l2cap_ctrl_parse(struct l2cap_frame *frame, uint32_t ctrl)
+static uint8_t l2cap_ctrl_parse(struct l2cap_frame *frame, uint32_t ctrl,
+					uint16_t *sdu_len, uint16_t *txseq,
+					uint16_t *reqseq, bool *ack)
 {
+	uint8_t sar = L2CAP_SAR_NONE;
+
+	*reqseq = (ctrl & L2CAP_CTRL_REQSEQ_MASK) >>
+						L2CAP_CTRL_REQSEQ_SHIFT;
+
 	display_printf("      %s:",
 			ctrl & L2CAP_CTRL_FRAME_TYPE ? "S-frame" : "I-frame");
 
 	if (ctrl & 0x01) {
-		display_printf(" %s",
-			supervisory2str((ctrl & L2CAP_CTRL_SUPERVISE_MASK) >>
-						L2CAP_CTRL_SUPER_SHIFT));
+		uint8_t super = (ctrl & L2CAP_CTRL_SUPERVISE_MASK) >>
+						L2CAP_CTRL_SUPER_SHIFT;
+
+		display_printf(" %s", supervisory2str(super));
+
+		/* SREJ without P-bit requests a single retransmission,
+		 * its ReqSeq doesn't acknowledge the preceding frames.
+		 */
+		*ack = super != L2CAP_SUPER_SREJ || (ctrl & L2CAP_CTRL_POLL);
 
 		if (ctrl & L2CAP_CTRL_POLL)
 			display_printf(" P-bit");
 	} else {
-		uint8_t sar;
-
 		sar = (ctrl & L2CAP_CTRL_SAR_MASK) >> L2CAP_CTRL_SAR_SHIFT;
 		display_printf(" %s", sar2str(sar));
 		if (sar == L2CAP_SAR_START) {
-			uint16_t len;
-
-			if (!l2cap_frame_get_le16(frame, &len))
-				return;
+			if (!l2cap_frame_get_le16(frame, sdu_len))
+				return L2CAP_SAR_NONE;
 
-			display_printf(" (len %d)", len);
+			display_printf(" (len %d)", *sdu_len);
 		}
-		display_printf(" TxSeq %d", (ctrl & L2CAP_CTRL_TXSEQ_MASK) >>
-						L2CAP_CTRL_TXSEQ_SHIFT);
+		*txseq = (ctrl & L2CAP_CTRL_TXSEQ_MASK) >>
+						L2CAP_CTRL_TXSEQ_SHIFT;
+		display_printf(" TxSeq %d", *txseq);
 	}
 
-	display_printf(" ReqSeq %d", (ctrl & L2CAP_CTRL_REQSEQ_MASK) >>
-						L2CAP_CTRL_REQSEQ_SHIFT);
+	display_printf(" ReqSeq %d", *reqseq);
 
 	if (ctrl & L2CAP_CTRL_FINAL)
 		display_printf(" F-bit");
+
+	return sar;
 }
 
 #define MAX_INDEX 16
@@ -2886,6 +2982,427 @@ static void smp_packet(uint16_t index, bool in, uint16_t handle,
 	opcode_data->func(&frame);
 }
 
+static bool sdu_seen(const struct l2cap_sdu *sdu, uint16_t txseq)
+{
+	return sdu->seen[txseq / 8] & (1 << (txseq % 8));
+}
+
+static void sdu_set_seen(struct l2cap_sdu *sdu, uint16_t txseq, bool seen)
+{
+	if (seen)
+		sdu->seen[txseq / 8] |= 1 << (txseq % 8);
+	else
+		sdu->seen[txseq / 8] &= ~(1 << (txseq % 8));
+}
+
+static struct l2cap_sdu_fragment *sdu_find(const struct l2cap_sdu *sdu,
+								uint32_t pos)
+{
+	struct l2cap_sdu_fragment *fragment;
+
+	for (fragment = sdu->slots[pos % sdu->seq_mod]; fragment;
+					fragment = fragment->slot_next) {
+		if (fragment->pos == pos)
+			return fragment;
+	}
+
+	return NULL;
+}
+
+static void sdu_insert(struct l2cap_sdu *sdu,
+					struct l2cap_sdu_fragment *fragment)
+{
+	struct l2cap_sdu_fragment **slot;
+
+	slot = &sdu->slots[fragment->pos % sdu->seq_mod];
+	fragment->slot_next = *slot;
+	*slot = fragment;
+
+	fragment->prev = NULL;
+	fragment->next = sdu->fragments;
+	if (sdu->fragments)
+		sdu->fragments->prev = fragment;
+	sdu->fragments = fragment;
+
+	sdu->pending_count++;
+	sdu->pending_bytes += fragment->len;
+}
+
+static void sdu_remove(struct l2cap_sdu *sdu,
+					struct l2cap_sdu_fragment *fragment)
+{
+	struct l2cap_sdu_fragment **slot;
+
+	slot = &sdu->slots[fragment->pos % sdu->seq_mod];
+	while (*slot != fragment)
+		slot = &(*slot)->slot_next;
+	*slot = fragment->slot_next;
+
+	if (fragment->prev)
+		fragment->prev->next = fragment->next;
+	else
+		sdu->fragments = fragment->next;
+	if (fragment->next)
+		fragment->next->prev = fragment->prev;
+
+	sdu->pending_count--;
+	sdu->pending_bytes -= fragment->len;
+	free(fragment);
+}
+
+static void sdu_clear(struct l2cap_sdu *sdu)
+{
+	while (sdu->fragments)
+		sdu_remove(sdu, sdu->fragments);
+}
+
+/* Map txseq to its absolute position. ERTM only retransmits frames not
+ * yet acknowledged, so a TxSeq not before the last ReqSeq is a
+ * retransmission. When the local host received that ReqSeq, the peer
+ * did too and anything else is a new frame. When the local host sent
+ * it, it may have been lost, so a TxSeq at most half the sequence space
+ * behind the most advanced one is a retransmission too. Streaming mode
+ * has no retransmission at all.
+ */
+static uint32_t sdu_pos(const struct l2cap_sdu *sdu, uint16_t txseq,
+							bool streaming)
+{
+	uint16_t m = sdu->seq_mod;
+	uint16_t behind = (sdu->high - txseq + m) % m;
+
+	bool unacked;
+
+	if (streaming)
+		return sdu->high_pos + (behind ? m - behind : m);
+
+	unacked = sdu->ack_valid && (txseq - sdu->ack + m) % m <
+					(sdu->high + 1 - sdu->ack + m) % m;
+
+	if (unacked || (behind < m / 2 &&
+				!(sdu->ack_valid && sdu->ack_received)))
+		return sdu->high_pos - behind;
+
+	return sdu->high_pos + m - behind;
+}
+
+/* Move the most advanced position forward. Positions entering the
+ * window reuse the TxSeq of positions a full cycle back, which can no
+ * longer be retransmitted, so forget them for duplicate detection.
+ *
+ * A fragment at such an expired position is only still useful if its
+ * SDU has no gap there, i.e. if it belongs to the contiguous run going
+ * from a Start up to the last expired position, as an SDU can have
+ * more fragments than the sequence space. Any other one is behind a
+ * gap which can't be filled anymore.
+ */
+static void sdu_advance(struct l2cap_sdu *sdu, uint16_t txseq, uint32_t pos)
+{
+	struct l2cap_sdu_fragment *fragment, *next;
+	uint32_t p, first = 0, last = pos - sdu->seq_mod;
+	bool expired = false, live = false;
+
+	if (pos - sdu->high_pos >= sdu->seq_mod)
+		memset(sdu->seen, 0, (sdu->seq_mod + 7) / 8);
+	else
+		for (p = sdu->high_pos + 1; p != pos + 1; p++)
+			sdu_set_seen(sdu, p % sdu->seq_mod, false);
+
+	for (fragment = sdu->fragments; fragment; fragment = fragment->next) {
+		if (pos - fragment->pos >= sdu->seq_mod) {
+			expired = true;
+			break;
+		}
+	}
+
+	if (!expired)
+		goto done;
+
+	p = last;
+	while ((fragment = sdu_find(sdu, p)) &&
+				fragment->sar == L2CAP_SAR_CONTINUE)
+		p--;
+
+	if (fragment && fragment->sar == L2CAP_SAR_START) {
+		first = p;
+		live = true;
+	}
+
+	for (fragment = sdu->fragments; fragment; fragment = next) {
+		next = fragment->next;
+
+		if (pos - fragment->pos >= sdu->seq_mod && (!live ||
+				fragment->pos - first > last - first))
+			sdu_remove(sdu, fragment);
+	}
+
+done:
+	sdu->high = txseq;
+	sdu->high_pos = pos;
+}
+
+/* ReqSeq cumulatively acknowledges every frame up to ReqSeq - 1. When
+ * it covers more frames since the previous one than were captured as
+ * sent, the others were not captured: move the most advanced position
+ * past them so that the following new frames aren't taken for
+ * retransmissions.
+ */
+static void l2cap_sdu_ack(struct chan_data *chan, bool in, uint16_t reqseq)
+{
+	struct l2cap_sdu *sdu = &chan->sdu_rx[in ? 0 : 1];
+	uint16_t m, prev, acked, sent;
+	bool had_ack;
+
+	if (chan->mode != L2CAP_MODE_ERTM)
+		return;
+
+	prev = sdu->ack;
+	had_ack = sdu->ack_valid;
+
+	sdu->ack = reqseq;
+	sdu->ack_valid = true;
+	sdu->ack_received = in;
+
+	if (!sdu->valid || !had_ack)
+		return;
+
+	m = sdu->seq_mod;
+	acked = (reqseq - prev + m) % m;
+	sent = (sdu->high + 1 - prev + m) % m;
+
+	if (acked > sent && acked - sent < m / 2)
+		sdu_advance(sdu, (reqseq - 1 + m) % m,
+					sdu->high_pos + acked - sent);
+}
+
+/* A frame beginning an SDU (Start/Unsegmented) at pos means that an
+ * unfinished SDU ending right before it can never complete, and one
+ * ending an SDU (End/Unsegmented) means the same for Continuation/End
+ * fragments right after it, which lack a Start.
+ */
+static void sdu_drop_dead(struct l2cap_sdu *sdu, uint8_t sar, uint32_t pos)
+{
+	struct l2cap_sdu_fragment *fragment;
+	bool dropped = false;
+
+	if (sar == L2CAP_SAR_START || sar == L2CAP_SAR_UNSEGMENTED) {
+		uint32_t p = pos - 1;
+
+		while ((fragment = sdu_find(sdu, p)) &&
+				fragment->sar != L2CAP_SAR_END) {
+			bool start = fragment->sar == L2CAP_SAR_START;
+
+			sdu_remove(sdu, fragment);
+			dropped = true;
+			if (start)
+				break;
+			p--;
+		}
+	}
+
+	if (sar == L2CAP_SAR_END || sar == L2CAP_SAR_UNSEGMENTED) {
+		uint32_t p = pos + 1;
+
+		while ((fragment = sdu_find(sdu, p)) &&
+				fragment->sar != L2CAP_SAR_START) {
+			bool end = fragment->sar == L2CAP_SAR_END;
+
+			sdu_remove(sdu, fragment);
+			dropped = true;
+			if (end)
+				break;
+			p++;
+		}
+	}
+
+	if (dropped)
+		print_text(COLOR_ERROR, "incomplete SDU discarded");
+}
+
+/* Returns true when frame holds a payload to dispatch. *owned is set when
+ * frame->data was replaced by a reassembled SDU to be freed by the caller.
+ * *final_len is the number of trailing bytes of frame->data carried by
+ * this fragment, i.e. not already shown with an earlier one.
+ */
+static bool l2cap_sdu_reassemble(struct chan_data *chan, bool in,
+					uint8_t sar, uint16_t sdu_len,
+					uint16_t txseq, uint16_t seq_mod,
+					struct l2cap_frame *frame, bool *owned,
+					uint16_t *final_len)
+{
+	struct l2cap_sdu *sdu;
+	struct l2cap_sdu_fragment *fragment, *start, *end, *next;
+	bool streaming, mismatch = false;
+	uint32_t pos, len, total, offset = 0;
+	uint8_t *data;
+
+	*owned = false;
+	*final_len = frame->size;
+
+	if (!chan)
+		return true;
+
+	sdu = &chan->sdu_rx[in ? 1 : 0];
+	streaming = chan->mode == L2CAP_MODE_STREAMING;
+
+	if (sdu->valid && sdu->seq_mod != seq_mod)
+		reset_sdu(sdu);
+
+	if (!sdu->valid) {
+		sdu->seen = calloc(1, (seq_mod + 7) / 8);
+		sdu->slots = calloc(seq_mod, sizeof(*sdu->slots));
+		if (!sdu->seen || !sdu->slots) {
+			free(sdu->seen);
+			free(sdu->slots);
+			sdu->seen = NULL;
+			sdu->slots = NULL;
+			return sar == L2CAP_SAR_UNSEGMENTED;
+		}
+
+		sdu->valid = true;
+		sdu->seq_mod = seq_mod;
+		/* Keep positions congruent to TxSeq, which indexes seen */
+		sdu->high = txseq;
+		sdu->high_pos = txseq;
+		pos = txseq;
+
+		/* Until a ReqSeq is seen, the first frame captured is the
+		 * oldest one which may still be unacknowledged.
+		 */
+		if (!sdu->ack_valid) {
+			sdu->ack = txseq;
+			sdu->ack_valid = true;
+			sdu->ack_received = false;
+		}
+	} else {
+		pos = sdu_pos(sdu, txseq, streaming);
+
+		if (pos - sdu->high_pos - 1 < seq_mod) {
+			sdu_advance(sdu, txseq, pos);
+		} else if (sdu_seen(sdu, txseq)) {
+			print_text(COLOR_ERROR,
+				"duplicate segment TxSeq %u discarded", txseq);
+			return false;
+		}
+	}
+
+	sdu_set_seen(sdu, txseq, true);
+	sdu_drop_dead(sdu, sar, pos);
+
+	if (sar == L2CAP_SAR_UNSEGMENTED)
+		return true;
+
+	if (streaming && sar != L2CAP_SAR_START && !sdu_find(sdu, pos - 1)) {
+		print_text(COLOR_ERROR, "gap in reassembly, discarding SDU");
+		sdu_clear(sdu);
+		return false;
+	}
+
+	if (sdu->pending_count >= MAX_SDU_PENDING_FRAGMENTS ||
+			sdu->pending_bytes + frame->size >
+						MAX_SDU_PENDING_BYTES) {
+		print_text(COLOR_ERROR,
+			"reassembly limit exceeded, pending SDUs discarded");
+		sdu_clear(sdu);
+	}
+
+	fragment = malloc(sizeof(*fragment) + frame->size);
+	if (!fragment)
+		return false;
+
+	fragment->pos = pos;
+	fragment->sar = sar;
+	fragment->sdu_len = sdu_len;
+	fragment->len = frame->size;
+	if (frame->size)
+		memcpy(fragment->data, frame->data, frame->size);
+	sdu_insert(sdu, fragment);
+
+	/* Look for the contiguous run of fragments around this one */
+	len = fragment->len;
+
+	start = fragment;
+	while (start->sar != L2CAP_SAR_START) {
+		next = sdu_find(sdu, start->pos - 1);
+		if (!next || (next->sar != L2CAP_SAR_START &&
+					next->sar != L2CAP_SAR_CONTINUE))
+			break;
+		start = next;
+		len += next->len;
+	}
+
+	end = fragment;
+	while (end->sar != L2CAP_SAR_END) {
+		next = sdu_find(sdu, end->pos + 1);
+		if (!next || (next->sar != L2CAP_SAR_CONTINUE &&
+					next->sar != L2CAP_SAR_END))
+			break;
+		end = next;
+		len += next->len;
+	}
+
+	if (start->sar != L2CAP_SAR_START)
+		return false;
+
+	if (end->sar != L2CAP_SAR_END) {
+		uint32_t p, last;
+
+		if (len <= start->sdu_len)
+			return false;
+
+		/* Already longer than its declared length */
+		print_text(COLOR_ERROR,
+				"SDU length exceeded, discarding SDU");
+
+		last = end->pos;
+		for (p = start->pos; p != last + 1; p++)
+			sdu_remove(sdu, sdu_find(sdu, p));
+
+		return false;
+	}
+
+	total = start->sdu_len;
+	data = malloc(total ? total : 1);
+	if (!data)
+		return false;
+
+	len = 0;
+	next = start;
+
+	for (;;) {
+		uint32_t n = next->len;
+		uint32_t next_pos = next->pos + 1;
+		bool last = next == end;
+
+		if (next == fragment)
+			offset = len;
+
+		if (n > total - len) {
+			n = total - len;
+			mismatch = true;
+		}
+
+		if (n)
+			memcpy(data + len, next->data, n);
+		len += n;
+
+		sdu_remove(sdu, next);
+		if (last)
+			break;
+
+		next = sdu_find(sdu, next_pos);
+	}
+
+	if (mismatch || len != total)
+		print_text(COLOR_ERROR, "reassembled SDU length mismatch");
+
+	frame->data = data;
+	frame->size = len;
+	*owned = true;
+	*final_len = len - offset;
+
+	return true;
+}
+
 void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			uint16_t psm, const void *data, uint16_t size)
 {
@@ -2894,6 +3411,15 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 	uint32_t ctrl32 = 0;
 	uint16_t ctrl16 = 0;
 	uint8_t ext_ctrl;
+	uint8_t sar = L2CAP_SAR_UNSEGMENTED;
+	uint16_t sdu_len = 0;
+	uint16_t txseq = 0;
+	uint16_t reqseq = 0;
+	bool ack = true;
+	uint16_t seq_mod = 64;
+	uint16_t frag_len = size;
+	void *sdu_buf = NULL;
+	bool owned;
 
 	switch (cid) {
 	case 0x0001:
@@ -2960,7 +3486,10 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 						frame.psm, mode2str(frame.mode),
 						frame.mode, frame.chan);
 
-				l2cap_ctrl_ext_parse(&frame, ctrl32);
+				sar = l2cap_ctrl_ext_parse(&frame, ctrl32,
+							&sdu_len, &txseq,
+							&reqseq, &ack);
+				seq_mod = 16384;
 			} else {
 				if (!l2cap_frame_get_le16(&frame, &ctrl16))
 					return;
@@ -2973,15 +3502,44 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 						frame.psm, mode2str(frame.mode),
 						frame.mode, frame.chan);
 
-				l2cap_ctrl_parse(&frame, ctrl16);
+				sar = l2cap_ctrl_parse(&frame, ctrl16,
+							&sdu_len, &txseq,
+							&reqseq, &ack);
+				seq_mod = 64;
 			}
 
 			display_printf("\n");
 
 			chan = get_chan(&frame);
+			if (chan && ack)
+				l2cap_sdu_ack(chan, frame.in, reqseq);
 			if (chan && chan->fcs && frame.size >= 2)
 				frame.size -= 2;
 
+			frag_len = frame.size;
+
+			if (sar != L2CAP_SAR_NONE) {
+				if (!l2cap_sdu_reassemble(chan, frame.in, sar,
+								sdu_len, txseq,
+								seq_mod,
+								&frame,
+								&owned,
+								&frag_len)) {
+					if (frame.size)
+						packet_hexdump(frame.data,
+								frame.size);
+					return;
+				}
+
+				if (owned)
+					sdu_buf = (void *) frame.data;
+			}
+
+			break;
+		}
+
+		if (sar == L2CAP_SAR_NONE) {
+			free(sdu_buf);
 			break;
 		}
 
@@ -2996,10 +3554,13 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			bnep_packet(&frame);
 			break;
 		case 0x001f:
-			att_packet(index, in, handle, cid, data, size);
-			break;
 		case 0x0027:
-			att_packet(index, in, handle, cid, data + 2, size - 2);
+			/* att_packet() reads the opcode before checking the
+			 * size.
+			 */
+			if (frame.size)
+				att_packet(index, in, handle, cid, frame.data,
+								frame.size);
 			break;
 		case 0x0017:
 		case 0x001B:
@@ -3011,11 +3572,13 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 		default:
 			if (obex_psm(index, handle, frame.psm))
 				obex_packet(&frame, l2cap_chan_key(index, in,
-								handle, cid));
+							handle, cid), frag_len);
 			else
 				packet_hexdump(frame.data, frame.size);
 			break;
 		}
+
+		free(sdu_buf);
 		break;
 	}
 }
diff --git a/monitor/obex.c b/monitor/obex.c
index 779313352..d48706feb 100644
--- a/monitor/obex.c
+++ b/monitor/obex.c
@@ -949,6 +949,30 @@ static void print_unicode_header(const char *label, const uint8_t *data,
 	print_field("%*c%s: %s", indent, ' ', label, buf);
 }
 
+/* Bytes of a reassembled PDU before offset from of base have already
+ * been hexdumped with earlier fragments.
+ */
+static void obex_hexdump(const uint8_t *base, uint16_t from,
+					const uint8_t *data, uint16_t len)
+{
+	uint32_t offset;
+
+	if (!len)
+		return;
+
+	offset = data - base;
+
+	if (offset + len <= from)
+		return;
+
+	if (offset < from) {
+		len -= from - offset;
+		data += from - offset;
+	}
+
+	packet_hexdump(data, len);
+}
+
 /* Application Parameters tags from the PBAP/MAP/BIP specifications */
 enum obex_aparam_type {
 	OBEX_APARAM_U8,
@@ -1155,7 +1179,8 @@ static void obex_print_apparam(const uint8_t *data, uint16_t size,
 }
 
 static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent,
-							uint16_t channel)
+					uint16_t channel, const uint8_t *base,
+					uint16_t dump_from)
 {
 	while (frame->size > 0) {
 		uint8_t hdr_id;
@@ -1224,6 +1249,10 @@ static bool obex_print_headers(struct l2cap_frame *frame, uint8_t indent,
 						obex_get_profile(frame->index,
 							frame->handle,
 							channel));
+				else if (vlen && (hdr_id == OBEX_HDR_BODY ||
+						hdr_id == OBEX_HDR_BODY_END))
+					obex_hexdump(base, dump_from, data,
+									vlen);
 				else if (vlen)
 					packet_hexdump(data, vlen);
 			}
@@ -1289,7 +1318,8 @@ static bool obex_setpath_fields(struct l2cap_frame *frame, uint8_t indent)
 	return true;
 }
 
-void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
+void obex_packet(const struct l2cap_frame *frame, uint16_t channel,
+							uint16_t frag_len)
 {
 	struct l2cap_frame obex_frame;
 	struct l2cap_frame *f = &obex_frame;
@@ -1300,9 +1330,15 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
 	bool is_request = false;
 	const uint8_t *trailer;
 	uint16_t trailer_len;
+	const uint8_t *dump_base;
+	uint16_t dump_from;
 
 	l2cap_frame_pull(f, frame, 0);
 
+	dump_base = frame->data;
+	dump_from = (frag_len < frame->size) ?
+					frame->size - frag_len : 0;
+
 	if (f->size < 3)
 		goto fail;
 
@@ -1353,7 +1389,7 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
 			goto fail;
 	}
 
-	if (!obex_print_headers(f, indent, channel))
+	if (!obex_print_headers(f, indent, channel, dump_base, dump_from))
 		goto fail;
 
 	if (is_request)
@@ -1363,12 +1399,12 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel)
 	if (trailer_len) {
 		print_field("%*cTrailing data: [len %d]", indent, ' ',
 							trailer_len);
-		packet_hexdump(trailer, trailer_len);
+		obex_hexdump(dump_base, dump_from, trailer, trailer_len);
 	}
 
 	return;
 
 fail:
 	print_text(COLOR_ERROR, "frame too short");
-	packet_hexdump(frame->data, frame->size);
+	obex_hexdump(dump_base, dump_from, frame->data, frame->size);
 }
diff --git a/monitor/obex.h b/monitor/obex.h
index 5af28ea8b..019ed6174 100644
--- a/monitor/obex.h
+++ b/monitor/obex.h
@@ -101,7 +101,8 @@
 #define OBEX_HDR_TYPE_UINT8	0x80
 #define OBEX_HDR_TYPE_UINT32	0xc0
 
-void obex_packet(const struct l2cap_frame *frame, uint16_t channel);
+void obex_packet(const struct l2cap_frame *frame, uint16_t channel,
+							uint16_t frag_len);
 
 void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
 							const char *profile);
diff --git a/monitor/rfcomm.c b/monitor/rfcomm.c
index 9e01c8a96..747c771fa 100644
--- a/monitor/rfcomm.c
+++ b/monitor/rfcomm.c
@@ -405,7 +405,7 @@ static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 	}
 
 	if (obex_channel(frame->index, frame->handle, channel, NULL))
-		obex_packet(frame, channel);
+		obex_packet(frame, channel, frame->size);
 	else
 		packet_hexdump(frame->data, frame->size);
 
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 5/6] monitor: Fix RFCOMM UIH frame length and credit-only handling
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
                   ` (3 preceding siblings ...)
  2026-12-04 16:04 ` [PATCH BlueZ v8 4/6] monitor: Reassemble L2CAP ERTM/Streaming SDUs Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  2026-12-04 16:04 ` [PATCH BlueZ v8 6/6] monitor: Reassemble OBEX PDUs split across RFCOMM UIH frames Frédéric Danis
  5 siblings, 0 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

The RFCOMM FCS byte was read but left in the payload passed to
uih_frame()/mcc_frame(); remove it, and adjust the mcc_test() and
mcc_msc() size checks which accounted for it.

Bound the payload of each RFCOMM frame by its declared length (plus the
credit octet), read its FCS right after it, and decode the following
RFCOMM frames carried in the same L2CAP SDU, instead of treating them as
part of the payload of the first one.

Don't pass credit-only UIH frames, which have no payload, to the OBEX
decoder.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Claude:claude-opus-5-5
---
v2->v3: New in v3.

v4->v5:
  - Bound rfcomm_packet()'s payload by the UIH frame's own declared
    hdr.length (plus the leading credit octet, when present), instead
    of handing uih_frame()/mcc_frame() the whole remaining L2CAP PDU,
    so an L2CAP PDU carrying more than one multiplexed RFCOMM frame
    doesn't leak the next frame's bytes into this frame's payload.

v7->v8:
  - Read the FCS right after the frame's declared length instead of
    from the last byte of the L2CAP SDU, and decode all RFCOMM frames
    carried in the same L2CAP SDU.
  - Adjust the mcc_test() and mcc_msc() size checks, which still
    accounted for the FCS byte.
  - Trim commit message.

 monitor/rfcomm.c | 63 ++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 50 insertions(+), 13 deletions(-)

diff --git a/monitor/rfcomm.c b/monitor/rfcomm.c
index 747c771fa..ca5deeba2 100644
--- a/monitor/rfcomm.c
+++ b/monitor/rfcomm.c
@@ -142,7 +142,7 @@ static inline bool mcc_test(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 
 	display_printf("%*cTest Data: 0x ", indent, ' ');
 
-	while (frame->size > 1) {
+	while (frame->size > 0) {
 		if (!l2cap_frame_get_u8(frame, &data))
 			return false;
 		display_printf("%2.2x ", data);
@@ -171,7 +171,7 @@ static inline bool mcc_msc(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 		GET_V24_RTR(msc.v24_sig), GET_V24_IC(msc.v24_sig),
 					GET_V24_DV(msc.v24_sig));
 
-	if (frame->size < 2)
+	if (frame->size < 1)
 		goto done;
 
 	/*
@@ -404,6 +404,9 @@ static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 		print_field("%*cCredits: %d", indent, ' ', hdr->credits);
 	}
 
+	if (!frame->size)
+		return true;
+
 	if (obex_channel(frame->index, frame->handle, channel, NULL))
 		obex_packet(frame, channel, frame->size);
 	else
@@ -426,14 +429,17 @@ static const struct rfcomm_data rfcomm_table[] = {
 	{ }
 };
 
-void rfcomm_packet(const struct l2cap_frame *frame)
+/* Decode the RFCOMM frame at the start of frame and return its size */
+static uint16_t rfcomm_frame_packet(const struct l2cap_frame *frame)
 {
 	uint8_t ctype, length, ex_length, indent = 1;
 	const char *frame_str, *frame_color;
-	struct l2cap_frame *l2cap_frame, tmp_frame;
+	struct l2cap_frame *l2cap_frame;
 	struct rfcomm_frame rfcomm_frame;
 	struct rfcomm_lhdr hdr;
 	const struct rfcomm_data *rfcomm_data = NULL;
+	uint32_t max_size, hdr_len;
+	uint16_t consumed;
 	int i;
 
 	l2cap_frame_pull(&rfcomm_frame.l2cap_frame, frame, 0);
@@ -462,14 +468,29 @@ void rfcomm_packet(const struct l2cap_frame *frame)
 	if (!l2cap_frame->size)
 		goto fail;
 
-	l2cap_frame_pull(&tmp_frame, l2cap_frame, l2cap_frame->size-1);
-
-	if (!l2cap_frame_get_u8(&tmp_frame, &hdr.fcs))
-		goto fail;
+	hdr_len = frame->size - l2cap_frame->size;
 
 	/* Decoding frame type */
 	ctype = RFCOMM_GET_TYPE(hdr.control);
 
+	/* Credit octet */
+	if (ctype == 0xef && GET_PF(hdr.control))
+		max_size = (uint32_t) hdr.length + 1;
+	else
+		max_size = hdr.length;
+
+	/* An L2CAP SDU may carry several RFCOMM frames */
+	if (hdr_len + max_size + 1 <= frame->size) {
+		hdr.fcs = ((const uint8_t *) l2cap_frame->data)[max_size];
+		l2cap_frame->size = max_size;
+		consumed = hdr_len + max_size + 1;
+	} else {
+		hdr.fcs = ((const uint8_t *) l2cap_frame->data)
+						[l2cap_frame->size - 1];
+		l2cap_frame->size -= 1;
+		consumed = frame->size;
+	}
+
 	for (i = 0; rfcomm_table[i].str; i++) {
 		if (rfcomm_table[i].frame == ctype) {
 			rfcomm_data = &rfcomm_table[i];
@@ -489,8 +510,8 @@ void rfcomm_packet(const struct l2cap_frame *frame)
 	}
 
 	if (!rfcomm_data) {
-		packet_hexdump(frame->data, frame->size);
-		return;
+		packet_hexdump(frame->data, consumed);
+		return consumed;
 	}
 
 	print_indent(6, frame_color, "RFCOMM: ", frame_str, COLOR_OFF,
@@ -502,16 +523,32 @@ void rfcomm_packet(const struct l2cap_frame *frame)
 	/* UIH frame */
 	if (ctype == 0xef) {
 		if (!uih_frame(&rfcomm_frame, indent))
-			goto fail;
+			goto fail_frame;
 	} else if (ctype == 0x43 || ctype == 0x0f) {
 		obex_remove_channel(frame->index, frame->handle,
 					RFCOMM_GET_CHANNEL(hdr.address));
 	}
 
-	return;
+	return consumed;
+
+fail_frame:
+	print_text(COLOR_ERROR, "Frame too short");
+	packet_hexdump(frame->data, consumed);
+	return consumed;
 
 fail:
 	print_text(COLOR_ERROR, "Frame too short");
 	packet_hexdump(frame->data, frame->size);
-	return;
+	return frame->size;
+}
+
+void rfcomm_packet(const struct l2cap_frame *frame)
+{
+	struct l2cap_frame rfcomm;
+
+	l2cap_frame_pull(&rfcomm, frame, 0);
+
+	while (rfcomm.size)
+		l2cap_frame_pull(&rfcomm, &rfcomm,
+					rfcomm_frame_packet(&rfcomm));
 }
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH BlueZ v8 6/6] monitor: Reassemble OBEX PDUs split across RFCOMM UIH frames
  2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
                   ` (4 preceding siblings ...)
  2026-12-04 16:04 ` [PATCH BlueZ v8 5/6] monitor: Fix RFCOMM UIH frame length and credit-only handling Frédéric Danis
@ 2026-12-04 16:04 ` Frédéric Danis
  5 siblings, 0 replies; 8+ messages in thread
From: Frédéric Danis @ 2026-12-04 16:04 UTC (permalink / raw)
  To: linux-bluetooth

An OBEX PDU can be split across several UIH frames, which were decoded
independently.

Buffer the UIH payload per index/handle/DLCI/direction until a complete
PDU is available, hexdumping the payload of the frames still being
buffered, and limit OBEX hexdumps to the bytes carried by the current
frame. Key this buffer and the OBEX session state on the DLCI rather
than the server channel, as two connections can use the same server
channel.

Drop them on DISC/DM of the DLCI, and for all DLCIs of the multiplexer
on DISC/DM of DLCI 0 or disconnection of its L2CAP channel. On ACL
disconnection, also release the L2CAP channels still tracked for the
handle (l2cap_remove_handle()).

RFCOMM server channels and dynamic PSMs are allocated by each device
independently, so a channel or PSM learned from the SDP record of one
device must not match a session served by the other one. Record the
server role with each mapping learned from SDP, i.e. the device
answering the query, and reject a session with the other role. The
role of an RFCOMM session is derived from the device sending the SABM
on DLCI 0 and from the DLCI direction bit, and the role of an L2CAP
channel from the direction of its Connection Request, now also looked
up for Basic mode. The check is skipped while the role isn't known.

SDP isn't necessarily repeated after an ACL reconnection, so keep the
channel and PSM mappings across ACL disconnection and match them by
peer address on the new handle.

Assisted-by: Claude:claude-sonnet-5
Assisted-by: Claude:claude-opus-5-5
---
v2->v3: New in v3.

v3->v4:
  - Add rfcomm_remove_handle(), called from the HCI disconnect
    complete handler, to free every fragment buffer still tracked for
    an ACL handle that goes away without an RFCOMM DISC/DM on each of
    its channels.
  - Widen the reassembly buffer's length/position tracking from
    uint16_t to uint32_t, and clamp the amount handed to obex_packet()
    on a malformed declared length to l2cap_frame.size's uint16_t
    range, keeping any excess buffered for the next call instead of
    reporting an incorrect remaining size.

v4->v5:
  - While a PDU is still incomplete and buffered, hexdump the UIH
    frame's own payload instead of showing nothing, mirroring the
    L2CAP SAR reassembly path, so partial OBEX data isn't silently
    dropped from the trace.
  - Key the reassembly buffer and its OBEX session/request state on
    the full DLCI (server channel plus direction bit) instead of just
    the server channel number, since two concurrent connections can
    share a server channel while using distinct DLCIs.
  - Treat a DISC/DM on DLCI 0 as closing the whole RFCOMM multiplexer,
    clearing every data channel's OBEX state via the new
    obex_remove_rfcomm_sessions() and rfcomm_remove_handle(), since no
    per-channel DISC/DM is seen for each of them, while keeping the
    SDP-learned channel mappings for a future reconnect.
  - Detect the RFCOMM L2CAP transport (PSM 0x0003) itself closing
    while the ACL link stays up, in sig_disconn_req(), and clear the
    same per-DLCI state in that case too.
  - Add is_rfcomm_chan_key(), bounds-checking the chan_list[] index
    against MAX_CHAN before dereferencing it in sig_disconn_req():
    l2cap_chan_key() only sets the 0x8000 bit when it resolves to a
    chan_list[] entry, but falls back to the raw CID otherwise, which
    isn't restricted to below 0x8000, risking a read past the end of
    chan_list[].

v5->v6:
  - Track which device sent the DLCI 0 SABM establishing each ACL's
    RFCOMM multiplexer session, and have obex_channel()/
    obex_add_channel() skip a channel-number match whose stored role
    disagrees with the live session's, so a server channel number
    that happens to be reused independently by each peer is no longer
    confused between them; still falls back to matching on channel
    number alone when the session's initiator hasn't been observed
    yet.
  - Add l2cap_remove_handle(), mirroring release_scid(), to release
    every chan_list[] entry (and its SAR reassembly buffers) still
    tracked for a handle torn down by HCI Disconnection Complete
    without an L2CAP Disconnection Response for each of its channels.

v6->v7:
  - Pass the DLCI into rfcomm_local_is_server() and derive the server
    role from both the mux initiator/responder tracking and the
    DLCI's direction bit, instead of always treating the mux responder
    as server: the direction bit only identifies which side opened
    that particular data channel as client, so the server is the
    other side, not unconditionally the responder.

v7->v8:
  - Fix the server role derived from the DLCI direction bit, which was
    inverted.
  - Mark used multiplexer slots with in_use, as handle 0 is valid.
  - Record the server role with the PSM mappings too, and reject an
    L2CAP channel with the other role. The role comes from the
    Connection Request direction, and is also looked up for Basic
    mode.
  - Keep the channel and PSM mappings across ACL disconnection and
    match them by peer address on the new handle, as SDP isn't
    necessarily repeated after a reconnection.
  - Look up the L2CAP channel to detect the RFCOMM transport on
    Disconnection Request, instead of decoding the l2cap_chan_key()
    value, which can be a raw CID with bit 15 set.
  - Limit OBEX hexdumps to the bytes carried by the current UIH frame,
    and only hexdump the bytes of a buffered frame not decoded yet.
  - Trim comments and commit message.

 monitor/l2cap.c  | 142 ++++++++++++++++++-------
 monitor/l2cap.h  |   4 +
 monitor/obex.c   | 237 ++++++++++++++++++++++++++++++++---------
 monitor/obex.h   |  12 ++-
 monitor/packet.c |   2 +
 monitor/rfcomm.c | 271 ++++++++++++++++++++++++++++++++++++++++++++++-
 6 files changed, 570 insertions(+), 98 deletions(-)

diff --git a/monitor/l2cap.c b/monitor/l2cap.c
index 76a16e22c..ddca385ac 100644
--- a/monitor/l2cap.c
+++ b/monitor/l2cap.c
@@ -153,6 +153,7 @@ struct chan_data {
 	uint8_t  fcs_dir[2];
 	int8_t   req_fcs[2];
 	int8_t   rsp_fcs[2];
+	int8_t   local_is_server;
 	struct l2cap_sdu sdu_rx[2];
 	struct packet_latency tx_l;
 };
@@ -233,6 +234,9 @@ static void assign_scid(const struct l2cap_frame *frame, uint16_t scid,
 	chan_list[n].ctrlid = ctrlid;
 	chan_list[n].mode = mode;
 
+	/* Called for a Connection Request, sent by the client */
+	chan_list[n].local_is_server = frame->in ? 1 : 0;
+
 	/* FCS is used unless both directions negotiate "No FCS" */
 	chan_list[n].fcs = 1;
 	chan_list[n].fcs_dir[0] = 1;
@@ -272,6 +276,25 @@ static void release_scid(const struct l2cap_frame *frame, uint16_t scid)
 	}
 }
 
+/* Channels of a disconnected ACL link may not have seen a Disconnection
+ * Response.
+ */
+void l2cap_remove_handle(uint16_t index, uint16_t handle)
+{
+	int i;
+
+	for (i = 0; i < MAX_CHAN; i++) {
+		if (chan_list[i].index != index)
+			continue;
+
+		if (chan_list[i].handle != handle)
+			continue;
+
+		reset_sdu_rx(&chan_list[i]);
+		chan_list[i].handle = 0;
+	}
+}
+
 static void assign_dcid(const struct l2cap_frame *frame, uint16_t dcid,
 								uint16_t scid)
 {
@@ -576,6 +599,23 @@ uint16_t l2cap_chan_key(uint16_t index, bool in, uint16_t handle, uint16_t cid)
 	return cid;
 }
 
+static bool is_rfcomm_chan(uint16_t index, bool in, uint16_t handle,
+							uint16_t cid)
+{
+	struct l2cap_frame frame;
+	int i;
+
+	memset(&frame, 0, sizeof(frame));
+	frame.index = index;
+	frame.in = in;
+	frame.handle = handle;
+	frame.cid = cid;
+
+	i = get_chan_data_index(&frame);
+
+	return i >= 0 && chan_list[i].psm == 0x0003;
+}
+
 static struct chan_data *get_chan(const struct l2cap_frame *frame)
 {
 	int i;
@@ -1522,17 +1562,26 @@ static void sig_config_rsp(const struct l2cap_frame *frame)
 static void sig_disconn_req(const struct l2cap_frame *frame)
 {
 	const struct bt_l2cap_pdu_disconn_req *pdu = frame->data;
+	uint16_t scid_key, dcid_key;
 
 	print_cid("Destination", pdu->dcid);
 	print_cid("Source", pdu->scid);
 
 	/* SCID belongs to the sender and DCID to the recipient */
-	obex_remove_session(frame->index, frame->handle,
-			l2cap_chan_key(frame->index, !frame->in, frame->handle,
-						le16_to_cpu(pdu->scid)));
-	obex_remove_session(frame->index, frame->handle,
-			l2cap_chan_key(frame->index, frame->in, frame->handle,
-						le16_to_cpu(pdu->dcid)));
+	scid_key = l2cap_chan_key(frame->index, !frame->in, frame->handle,
+						le16_to_cpu(pdu->scid));
+	dcid_key = l2cap_chan_key(frame->index, frame->in, frame->handle,
+						le16_to_cpu(pdu->dcid));
+	obex_remove_session(frame->index, frame->handle, scid_key);
+	obex_remove_session(frame->index, frame->handle, dcid_key);
+
+	if (is_rfcomm_chan(frame->index, !frame->in, frame->handle,
+					le16_to_cpu(pdu->scid)) ||
+			is_rfcomm_chan(frame->index, frame->in, frame->handle,
+					le16_to_cpu(pdu->dcid))) {
+		obex_remove_rfcomm_sessions(frame->index, frame->handle);
+		rfcomm_remove_handle(frame->index, frame->handle);
+	}
 }
 
 static void sig_disconn_rsp(const struct l2cap_frame *frame)
@@ -3403,6 +3452,48 @@ static bool l2cap_sdu_reassemble(struct chan_data *chan, bool in,
 	return true;
 }
 
+/* frag_len is the number of trailing bytes of frame->data carried by the
+ * fragment completing the SDU.
+ */
+static void l2cap_sdu_dispatch(uint16_t index, bool in, uint16_t handle,
+				uint16_t cid, struct l2cap_frame *frame,
+				struct chan_data *chan, uint16_t frag_len)
+{
+	switch (frame->psm) {
+	case 0x0001:
+		sdp_packet(frame);
+		break;
+	case 0x0003:
+		rfcomm_packet(frame);
+		break;
+	case 0x000f:
+		bnep_packet(frame);
+		break;
+	case 0x001f:
+	case 0x0027:
+		/* att_packet() reads the opcode before checking the size */
+		if (frame->size)
+			att_packet(index, in, handle, cid, frame->data,
+							frame->size);
+		break;
+	case 0x0017:
+	case 0x001B:
+		avctp_packet(frame);
+		break;
+	case 0x0019:
+		avdtp_packet(frame);
+		break;
+	default:
+		if (obex_psm(index, handle, frame->psm,
+				chan ? chan->local_is_server : -1))
+			obex_packet(frame, l2cap_chan_key(index, in,
+						handle, cid), frag_len);
+		else
+			packet_hexdump(frame->data, frame->size);
+		break;
+	}
+}
+
 void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			uint16_t psm, const void *data, uint16_t size)
 {
@@ -3470,6 +3561,8 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 					"{chan %d}", cid, size, frame.psm,
 					mode2str(frame.mode), frame.mode,
 					frame.chan);
+			/* For the OBEX PSM role check */
+			chan = get_chan(&frame);
 			break;
 		default:
 			ext_ctrl = get_ext_ctrl(&frame);
@@ -3543,42 +3636,11 @@ void l2cap_frame(uint16_t index, bool in, uint16_t handle, uint16_t cid,
 			break;
 		}
 
-		switch (frame.psm) {
-		case 0x0001:
-			sdp_packet(&frame);
-			break;
-		case 0x0003:
-			rfcomm_packet(&frame);
-			break;
-		case 0x000f:
-			bnep_packet(&frame);
-			break;
-		case 0x001f:
-		case 0x0027:
-			/* att_packet() reads the opcode before checking the
-			 * size.
-			 */
-			if (frame.size)
-				att_packet(index, in, handle, cid, frame.data,
-								frame.size);
-			break;
-		case 0x0017:
-		case 0x001B:
-			avctp_packet(&frame);
-			break;
-		case 0x0019:
-			avdtp_packet(&frame);
-			break;
-		default:
-			if (obex_psm(index, handle, frame.psm))
-				obex_packet(&frame, l2cap_chan_key(index, in,
-							handle, cid), frag_len);
-			else
-				packet_hexdump(frame.data, frame.size);
-			break;
-		}
+		l2cap_sdu_dispatch(index, in, handle, cid, &frame, chan,
+								frag_len);
 
 		free(sdu_buf);
+
 		break;
 	}
 }
diff --git a/monitor/l2cap.h b/monitor/l2cap.h
index 1c1f7e609..18b8d2f88 100644
--- a/monitor/l2cap.h
+++ b/monitor/l2cap.h
@@ -364,4 +364,8 @@ void l2cap_packet(uint16_t index, bool in, uint16_t handle, uint8_t flags,
 
 void rfcomm_packet(const struct l2cap_frame *frame);
 
+void rfcomm_remove_handle(uint16_t index, uint16_t handle);
+
+void l2cap_remove_handle(uint16_t index, uint16_t handle);
+
 void l2cap_dequeue_frame(struct timeval *delta, struct packet_conn_data *conn);
diff --git a/monitor/obex.c b/monitor/obex.c
index d48706feb..54f142e43 100644
--- a/monitor/obex.c
+++ b/monitor/obex.c
@@ -49,10 +49,74 @@ enum obex_profile {
 	OBEX_PROFILE_BIP,
 };
 
-struct obex_chan_data {
+/* SDP isn't necessarily repeated after an ACL reconnection, so the peer
+ * address is kept to match the new handle.
+ */
+struct obex_link {
 	uint16_t index;
 	uint16_t handle;
+	bool connected;
+	bool has_bdaddr;
+	uint8_t bdaddr[6];
+};
+
+static void obex_link_set(struct obex_link *link, uint16_t index,
+							uint16_t handle)
+{
+	struct packet_conn_data *conn = packet_get_conn_data(handle);
+
+	link->index = index;
+	link->handle = handle;
+	link->connected = true;
+	link->has_bdaddr = conn && conn->index == index;
+	if (link->has_bdaddr)
+		memcpy(link->bdaddr, conn->dst, sizeof(link->bdaddr));
+}
+
+static bool obex_link_match(struct obex_link *link, uint16_t index,
+							uint16_t handle)
+{
+	struct packet_conn_data *conn;
+
+	if (link->index != index)
+		return false;
+
+	if (link->connected && link->handle == handle)
+		return true;
+
+	if (!link->has_bdaddr)
+		return false;
+
+	conn = packet_get_conn_data(handle);
+	if (!conn || conn->index != index)
+		return false;
+
+	if (memcmp(link->bdaddr, conn->dst, sizeof(link->bdaddr)))
+		return false;
+
+	link->handle = handle;
+	link->connected = true;
+
+	return true;
+}
+
+/* Returns whether the entry should be released */
+static bool obex_link_disconnect(struct obex_link *link, uint16_t index,
+							uint16_t handle)
+{
+	if (link->index != index || !link->connected ||
+						link->handle != handle)
+		return false;
+
+	link->connected = false;
+
+	return !link->has_bdaddr;
+}
+
+struct obex_chan_data {
+	struct obex_link link;
 	uint8_t channel;
+	bool local_is_server;
 	char profile[32];
 };
 
@@ -68,9 +132,9 @@ struct obex_req_data {
 static struct obex_req_data obex_req_list[MAX_OBEX_REQ];
 
 void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
-							const char *profile)
+				bool local_is_server, const char *profile)
 {
-	int i, n = -1;
+	int i, n = -1, stale = -1;
 
 	if (!channel)
 		return;
@@ -82,20 +146,27 @@ void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
 			continue;
 		}
 
-		if (obex_chan_list[i].index == index &&
-				obex_chan_list[i].handle == handle &&
-				obex_chan_list[i].channel == channel) {
+		if (obex_link_match(&obex_chan_list[i].link, index, handle) &&
+				obex_chan_list[i].channel == channel &&
+				obex_chan_list[i].local_is_server ==
+							local_is_server) {
 			n = i;
 			break;
 		}
+
+		if (stale < 0 && !obex_chan_list[i].link.connected)
+			stale = i;
 	}
 
+	if (n < 0)
+		n = stale;
+
 	if (n < 0)
 		return;
 
-	obex_chan_list[n].index = index;
-	obex_chan_list[n].handle = handle;
+	obex_link_set(&obex_chan_list[n].link, index, handle);
 	obex_chan_list[n].channel = channel;
+	obex_chan_list[n].local_is_server = local_is_server;
 
 	if (profile)
 		snprintf(obex_chan_list[n].profile,
@@ -105,8 +176,11 @@ void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
 		obex_chan_list[n].profile[0] = '\0';
 }
 
+/* local_is_server is 1 if the local host is the server, 0 if the peer
+ * is, or -1 if unknown, in which case the role isn't checked.
+ */
 bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
-							const char **profile)
+				int local_is_server, const char **profile)
 {
 	int i;
 
@@ -117,9 +191,13 @@ bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
 		if (!obex_chan_list[i].channel)
 			continue;
 
-		if (obex_chan_list[i].index == index &&
-				obex_chan_list[i].handle == handle &&
+		if (obex_link_match(&obex_chan_list[i].link, index, handle) &&
 				obex_chan_list[i].channel == channel) {
+			if (local_is_server >= 0 &&
+					!!obex_chan_list[i].local_is_server !=
+							!!local_is_server)
+				continue;
+
 			if (profile)
 				*profile = obex_chan_list[i].profile;
 			return true;
@@ -132,16 +210,17 @@ bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
 #define MAX_OBEX_PSM 16
 
 struct obex_psm_data {
-	uint16_t index;
-	uint16_t handle;
+	struct obex_link link;
 	uint16_t psm;
+	bool local_is_server;
 };
 
 static struct obex_psm_data obex_psm_list[MAX_OBEX_PSM];
 
-void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm)
+void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm,
+						bool local_is_server)
 {
-	int i, n = -1;
+	int i, n = -1, stale = -1;
 
 	if (!psm)
 		return;
@@ -153,23 +232,32 @@ void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm)
 			continue;
 		}
 
-		if (obex_psm_list[i].index == index &&
-				obex_psm_list[i].handle == handle &&
-				obex_psm_list[i].psm == psm) {
+		if (obex_link_match(&obex_psm_list[i].link, index, handle) &&
+				obex_psm_list[i].psm == psm &&
+				obex_psm_list[i].local_is_server ==
+							local_is_server) {
 			n = i;
 			break;
 		}
+
+		if (stale < 0 && !obex_psm_list[i].link.connected)
+			stale = i;
 	}
 
+	if (n < 0)
+		n = stale;
+
 	if (n < 0)
 		return;
 
-	obex_psm_list[n].index = index;
-	obex_psm_list[n].handle = handle;
+	obex_link_set(&obex_psm_list[n].link, index, handle);
 	obex_psm_list[n].psm = psm;
+	obex_psm_list[n].local_is_server = local_is_server;
 }
 
-bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm)
+/* local_is_server as for obex_channel() */
+bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm,
+						int local_is_server)
 {
 	int i;
 
@@ -180,9 +268,14 @@ bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm)
 		if (!obex_psm_list[i].psm)
 			continue;
 
-		if (obex_psm_list[i].index == index &&
-				obex_psm_list[i].handle == handle &&
-				obex_psm_list[i].psm == psm)
+		if (obex_psm_list[i].psm != psm ||
+				!obex_link_match(&obex_psm_list[i].link, index,
+								handle))
+			continue;
+
+		if (local_is_server < 0 ||
+				!!obex_psm_list[i].local_is_server ==
+							!!local_is_server)
 			return true;
 	}
 
@@ -246,38 +339,47 @@ void obex_remove_session(uint16_t index, uint16_t handle, uint16_t channel)
 	obex_clear_profile(index, handle, channel);
 }
 
-void obex_disconnect_handle(uint16_t index, uint16_t handle)
+void obex_remove_all_sessions(uint16_t index, uint16_t handle)
 {
 	int i;
 
-	for (i = 0; i < MAX_OBEX_CHAN; i++) {
-		if (!obex_chan_list[i].channel)
-			continue;
-
-		if (obex_chan_list[i].index == index &&
-				obex_chan_list[i].handle == handle)
-			memset(&obex_chan_list[i], 0,
-						sizeof(obex_chan_list[i]));
-	}
-
 	for (i = 0; i < MAX_OBEX_REQ; i++) {
 		if (obex_req_list[i].index == index &&
 				obex_req_list[i].handle == handle)
 			memset(&obex_req_list[i], 0, sizeof(obex_req_list[i]));
 	}
 
-	for (i = 0; i < MAX_OBEX_PSM; i++) {
-		if (!obex_psm_list[i].psm)
+	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
+		if (!obex_profile_list[i].channel)
 			continue;
 
-		if (obex_psm_list[i].index == index &&
-				obex_psm_list[i].handle == handle)
-			memset(&obex_psm_list[i], 0,
-						sizeof(obex_psm_list[i]));
+		if (obex_profile_list[i].index == index &&
+				obex_profile_list[i].handle == handle)
+			memset(&obex_profile_list[i], 0,
+					sizeof(obex_profile_list[i]));
+	}
+}
+
+/* Session keys above it are L2CAP ones, see l2cap_chan_key() */
+#define MAX_RFCOMM_DLCI 0x3f
+
+void obex_remove_rfcomm_sessions(uint16_t index, uint16_t handle)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_REQ; i++) {
+		if (obex_req_list[i].channel > MAX_RFCOMM_DLCI)
+			continue;
+
+		if (obex_req_list[i].index == index &&
+				obex_req_list[i].handle == handle)
+			memset(&obex_req_list[i], 0, sizeof(obex_req_list[i]));
 	}
 
 	for (i = 0; i < MAX_OBEX_PROFILE; i++) {
-		if (!obex_profile_list[i].channel)
+		if (!obex_profile_list[i].channel ||
+				obex_profile_list[i].channel >
+							MAX_RFCOMM_DLCI)
 			continue;
 
 		if (obex_profile_list[i].index == index &&
@@ -287,6 +389,33 @@ void obex_disconnect_handle(uint16_t index, uint16_t handle)
 	}
 }
 
+void obex_disconnect_handle(uint16_t index, uint16_t handle)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_CHAN; i++) {
+		if (!obex_chan_list[i].channel)
+			continue;
+
+		if (obex_link_disconnect(&obex_chan_list[i].link, index,
+								handle))
+			memset(&obex_chan_list[i], 0,
+						sizeof(obex_chan_list[i]));
+	}
+
+	obex_remove_all_sessions(index, handle);
+
+	for (i = 0; i < MAX_OBEX_PSM; i++) {
+		if (!obex_psm_list[i].psm)
+			continue;
+
+		if (obex_link_disconnect(&obex_psm_list[i].link, index,
+								handle))
+			memset(&obex_psm_list[i], 0,
+						sizeof(obex_psm_list[i]));
+	}
+}
+
 static void obex_set_last_request(uint16_t index, uint16_t handle,
 					uint16_t channel, uint8_t opcode)
 {
@@ -485,6 +614,7 @@ static uint16_t obex_de_uuid16(const uint8_t *data, uint32_t size)
  * carrying OBEX. Returns whether it carries OBEX.
  */
 static bool obex_scan_proto_list(uint16_t index, uint16_t handle,
+				bool local_is_server,
 				const uint8_t *data, uint32_t size,
 				const char *profile)
 {
@@ -546,9 +676,10 @@ next:
 	}
 
 	if (have_obex && channel)
-		obex_add_channel(index, handle, channel, profile);
+		obex_add_channel(index, handle, channel, local_is_server,
+								profile);
 	else if (have_obex && psm)
-		obex_add_psm(index, handle, psm);
+		obex_add_psm(index, handle, psm, local_is_server);
 
 	return have_obex;
 }
@@ -577,6 +708,7 @@ static bool obex_scan_svclass(const uint8_t *data, uint32_t size,
 }
 
 static void obex_scan_attr_list(uint16_t index, uint16_t handle,
+				bool local_is_server,
 				const uint8_t *data, uint32_t size)
 {
 	uint32_t pos = 0;
@@ -612,7 +744,9 @@ static void obex_scan_attr_list(uint16_t index, uint16_t handle,
 							sizeof(profile));
 			break;
 		case SDP_ATTR_PROTO_DESC_LIST:
-			if (obex_scan_proto_list(index, handle, attr_val,
+			if (obex_scan_proto_list(index, handle,
+							local_is_server,
+							attr_val,
 							attr_size, profile))
 				have_obex = true;
 			break;
@@ -633,7 +767,9 @@ static void obex_scan_attr_list(uint16_t index, uint16_t handle,
 
 				if (atype == SDP_DE_SEQ &&
 						obex_scan_proto_list(index,
-								handle, aval,
+								handle,
+								local_is_server,
+								aval,
 								avsize,
 								profile))
 					have_obex = true;
@@ -655,7 +791,7 @@ static void obex_scan_attr_list(uint16_t index, uint16_t handle,
 	}
 
 	if (have_obex && goep_psm)
-		obex_add_psm(index, handle, goep_psm);
+		obex_add_psm(index, handle, goep_psm, local_is_server);
 }
 
 /* nested is set for a Service Search Attribute Response, which holds a
@@ -668,13 +804,16 @@ void obex_sdp_scan(const struct l2cap_frame *frame, const uint8_t *data,
 	const uint8_t *val;
 	uint32_t vsize;
 	uint32_t pos = 0;
+	/* The device sending the record is the server */
+	bool local_is_server = !frame->in;
 
 	if (!obex_de_next(data, size, &type, &val, &vsize) ||
 							type != SDP_DE_SEQ)
 		return;
 
 	if (!nested) {
-		obex_scan_attr_list(frame->index, frame->handle, val, vsize);
+		obex_scan_attr_list(frame->index, frame->handle,
+						local_is_server, val, vsize);
 		return;
 	}
 
@@ -690,7 +829,7 @@ void obex_sdp_scan(const struct l2cap_frame *frame, const uint8_t *data,
 
 		if (rtype == SDP_DE_SEQ)
 			obex_scan_attr_list(frame->index, frame->handle,
-							rval, rvsize);
+						local_is_server, rval, rvsize);
 
 		pos += relemlen;
 	}
diff --git a/monitor/obex.h b/monitor/obex.h
index 019ed6174..c911766b5 100644
--- a/monitor/obex.h
+++ b/monitor/obex.h
@@ -105,15 +105,19 @@ void obex_packet(const struct l2cap_frame *frame, uint16_t channel,
 							uint16_t frag_len);
 
 void obex_add_channel(uint16_t index, uint16_t handle, uint8_t channel,
-							const char *profile);
+				bool local_is_server, const char *profile);
 bool obex_channel(uint16_t index, uint16_t handle, uint8_t channel,
-							const char **profile);
+				int local_is_server, const char **profile);
 void obex_remove_channel(uint16_t index, uint16_t handle, uint8_t channel);
 void obex_remove_session(uint16_t index, uint16_t handle, uint16_t channel);
+void obex_remove_all_sessions(uint16_t index, uint16_t handle);
+void obex_remove_rfcomm_sessions(uint16_t index, uint16_t handle);
 void obex_disconnect_handle(uint16_t index, uint16_t handle);
 
-void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm);
-bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm);
+void obex_add_psm(uint16_t index, uint16_t handle, uint16_t psm,
+						bool local_is_server);
+bool obex_psm(uint16_t index, uint16_t handle, uint16_t psm,
+						int local_is_server);
 
 void obex_sdp_scan(const struct l2cap_frame *frame, const uint8_t *data,
 						uint32_t size, bool nested);
diff --git a/monitor/packet.c b/monitor/packet.c
index 7414910c7..badf6b6f1 100644
--- a/monitor/packet.c
+++ b/monitor/packet.c
@@ -12315,6 +12315,8 @@ static void disconnect_complete_evt(struct timeval *tv, uint16_t index,
 	if (evt->status == 0x00) {
 		release_handle(le16_to_cpu(evt->handle));
 		obex_disconnect_handle(index, le16_to_cpu(evt->handle));
+		rfcomm_remove_handle(index, le16_to_cpu(evt->handle));
+		l2cap_remove_handle(index, le16_to_cpu(evt->handle));
 	}
 }
 
diff --git a/monitor/rfcomm.c b/monitor/rfcomm.c
index ca5deeba2..be4a3333e 100644
--- a/monitor/rfcomm.c
+++ b/monitor/rfcomm.c
@@ -386,12 +386,191 @@ static inline bool mcc_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 	return true;
 }
 
+/* OBEX PDUs split across UIH frames, keyed on the DLCI as two
+ * connections can use the same server channel.
+ */
+#define MAX_OBEX_FRAG 64
+
+struct obex_frag_data {
+	uint16_t index;
+	uint16_t handle;
+	uint8_t dlci;
+	bool in;
+	uint8_t *buf;
+	uint32_t len;
+};
+
+static struct obex_frag_data obex_frag_list[MAX_OBEX_FRAG];
+
+static struct obex_frag_data *obex_frag_get(uint16_t index, uint16_t handle,
+						uint8_t dlci, bool in)
+{
+	int i, n = -1;
+
+	for (i = 0; i < MAX_OBEX_FRAG; i++) {
+		if (!obex_frag_list[i].dlci) {
+			if (n < 0)
+				n = i;
+			continue;
+		}
+
+		if (obex_frag_list[i].index == index &&
+				obex_frag_list[i].handle == handle &&
+				obex_frag_list[i].dlci == dlci &&
+				obex_frag_list[i].in == in)
+			return &obex_frag_list[i];
+	}
+
+	if (n < 0)
+		return NULL;
+
+	obex_frag_list[n].index = index;
+	obex_frag_list[n].handle = handle;
+	obex_frag_list[n].dlci = dlci;
+	obex_frag_list[n].in = in;
+	obex_frag_list[n].buf = NULL;
+	obex_frag_list[n].len = 0;
+
+	return &obex_frag_list[n];
+}
+
+static void obex_frag_reset(struct obex_frag_data *frag)
+{
+	free(frag->buf);
+	frag->buf = NULL;
+	frag->len = 0;
+}
+
+/* Multiplexer initiator, from the SABM on DLCI 0 */
+#define MAX_RFCOMM_MUX 16
+
+struct rfcomm_mux_data {
+	bool in_use;
+	uint16_t index;
+	uint16_t handle;
+	bool local_is_initiator;
+};
+
+static struct rfcomm_mux_data rfcomm_mux_list[MAX_RFCOMM_MUX];
+
+static void rfcomm_set_mux_initiator(uint16_t index, uint16_t handle,
+						bool local_is_initiator)
+{
+	int i, n = -1;
+
+	for (i = 0; i < MAX_RFCOMM_MUX; i++) {
+		if (!rfcomm_mux_list[i].in_use) {
+			if (n < 0)
+				n = i;
+			continue;
+		}
+
+		if (rfcomm_mux_list[i].index == index &&
+				rfcomm_mux_list[i].handle == handle) {
+			n = i;
+			break;
+		}
+	}
+
+	if (n < 0)
+		return;
+
+	rfcomm_mux_list[n].in_use = true;
+	rfcomm_mux_list[n].index = index;
+	rfcomm_mux_list[n].handle = handle;
+	rfcomm_mux_list[n].local_is_initiator = local_is_initiator;
+}
+
+/* Returns 1 if the local host is the server of dlci, 0 if the peer is,
+ * or -1 if the multiplexer initiator is unknown.
+ */
+static int rfcomm_local_is_server(uint16_t index, uint16_t handle,
+							uint8_t dlci)
+{
+	int i;
+
+	for (i = 0; i < MAX_RFCOMM_MUX; i++) {
+		if (rfcomm_mux_list[i].in_use &&
+				rfcomm_mux_list[i].index == index &&
+				rfcomm_mux_list[i].handle == handle) {
+			bool local_is_initiator =
+					rfcomm_mux_list[i].local_is_initiator;
+
+			if (dlci & 1)
+				return local_is_initiator ? 1 : 0;
+
+			return local_is_initiator ? 0 : 1;
+		}
+	}
+
+	return -1;
+}
+
+static void rfcomm_remove_channel(uint16_t index, uint16_t handle,
+							uint8_t dlci)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_FRAG; i++) {
+		if (obex_frag_list[i].dlci == dlci &&
+				obex_frag_list[i].index == index &&
+				obex_frag_list[i].handle == handle) {
+			obex_frag_reset(&obex_frag_list[i]);
+			memset(&obex_frag_list[i], 0,
+					sizeof(obex_frag_list[i]));
+		}
+	}
+}
+
+void rfcomm_remove_handle(uint16_t index, uint16_t handle)
+{
+	int i;
+
+	for (i = 0; i < MAX_OBEX_FRAG; i++) {
+		if (!obex_frag_list[i].dlci)
+			continue;
+
+		if (obex_frag_list[i].index == index &&
+				obex_frag_list[i].handle == handle) {
+			obex_frag_reset(&obex_frag_list[i]);
+			memset(&obex_frag_list[i], 0,
+					sizeof(obex_frag_list[i]));
+		}
+	}
+
+	for (i = 0; i < MAX_RFCOMM_MUX; i++) {
+		if (rfcomm_mux_list[i].in_use &&
+				rfcomm_mux_list[i].index == index &&
+				rfcomm_mux_list[i].handle == handle)
+			memset(&rfcomm_mux_list[i], 0,
+					sizeof(rfcomm_mux_list[i]));
+	}
+}
+
+/* Number of bytes of the PDU at pos/len within a reassembly buffer
+ * which come from the frame appended at cur, i.e. not shown yet.
+ */
+static uint16_t obex_frag_new(uint32_t pos, uint16_t len, uint32_t cur)
+{
+	if (pos >= cur)
+		return len;
+
+	if (pos + len <= cur)
+		return 0;
+
+	return pos + len - cur;
+}
+
 static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 {
 	uint8_t credits;
 	struct l2cap_frame *frame = &rfcomm_frame->l2cap_frame;
 	struct rfcomm_lhdr *hdr = &rfcomm_frame->hdr;
 	uint8_t channel = RFCOMM_GET_CHANNEL(hdr->address);
+	uint8_t dlci = RFCOMM_GET_DLCI(hdr->address);
+	struct obex_frag_data *frag;
+	uint8_t *buf;
+	uint32_t pos, cur;
 
 	if (!channel)
 		return mcc_frame(rfcomm_frame, indent);
@@ -407,10 +586,78 @@ static bool uih_frame(struct rfcomm_frame *rfcomm_frame, uint8_t indent)
 	if (!frame->size)
 		return true;
 
-	if (obex_channel(frame->index, frame->handle, channel, NULL))
-		obex_packet(frame, channel, frame->size);
-	else
+	if (!obex_channel(frame->index, frame->handle, channel,
+			rfcomm_local_is_server(frame->index, frame->handle,
+								dlci),
+			NULL)) {
 		packet_hexdump(frame->data, frame->size);
+		return true;
+	}
+
+	frag = obex_frag_get(frame->index, frame->handle, dlci, frame->in);
+	if (!frag) {
+		obex_packet(frame, dlci, frame->size);
+		return true;
+	}
+
+	buf = realloc(frag->buf, frag->len + frame->size);
+	if (!buf) {
+		obex_frag_reset(frag);
+		obex_packet(frame, dlci, frame->size);
+		return true;
+	}
+
+	memcpy(buf + frag->len, frame->data, frame->size);
+	frag->buf = buf;
+	cur = frag->len;
+	frag->len += frame->size;
+
+	/* Bytes before cur were already shown with earlier frames */
+	pos = 0;
+
+	while (frag->len - pos >= 3) {
+		struct l2cap_frame pdu_frame = *frame;
+		uint16_t pdu_len = get_be16(frag->buf + pos + 1);
+
+		if (pdu_len < 3) {
+			/* Let obex_packet() report the invalid length */
+			uint32_t remaining = frag->len - pos;
+
+			if (remaining > UINT16_MAX)
+				remaining = UINT16_MAX;
+
+			pdu_frame.data = frag->buf + pos;
+			pdu_frame.size = remaining;
+			obex_packet(&pdu_frame, dlci,
+					obex_frag_new(pos, remaining, cur));
+			pos += remaining;
+			break;
+		}
+
+		if (frag->len - pos < pdu_len)
+			break;
+
+		pdu_frame.data = frag->buf + pos;
+		pdu_frame.size = pdu_len;
+		obex_packet(&pdu_frame, dlci,
+					obex_frag_new(pos, pdu_len, cur));
+
+		pos += pdu_len;
+	}
+
+	if (pos == frag->len) {
+		obex_frag_reset(frag);
+	} else {
+		if (pos > cur)
+			packet_hexdump(frag->buf + pos, frag->len - pos);
+		else
+			packet_hexdump(frame->data, frame->size);
+
+		if (pos) {
+			memmove(frag->buf, frag->buf + pos, frag->len - pos);
+			frag->len -= pos;
+		}
+	}
 
 	return true;
 }
@@ -524,9 +771,23 @@ static uint16_t rfcomm_frame_packet(const struct l2cap_frame *frame)
 	if (ctype == 0xef) {
 		if (!uih_frame(&rfcomm_frame, indent))
 			goto fail_frame;
+	} else if (ctype == 0x2f) {
+		if (!RFCOMM_GET_DLCI(hdr.address))
+			rfcomm_set_mux_initiator(frame->index, frame->handle,
+								!frame->in);
 	} else if (ctype == 0x43 || ctype == 0x0f) {
-		obex_remove_channel(frame->index, frame->handle,
-					RFCOMM_GET_CHANNEL(hdr.address));
+		uint8_t dlci = RFCOMM_GET_DLCI(hdr.address);
+
+		if (!dlci) {
+			obex_remove_rfcomm_sessions(frame->index,
+								frame->handle);
+			rfcomm_remove_handle(frame->index, frame->handle);
+		} else {
+			obex_remove_channel(frame->index, frame->handle,
+									dlci);
+			rfcomm_remove_channel(frame->index, frame->handle,
+									dlci);
+		}
 	}
 
 	return consumed;
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* RE: monitor: Add an OBEX protocol decoder to btmon
  2026-12-04 16:04 ` [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors Frédéric Danis
@ 2026-12-04 17:12   ` bluez.test.bot
  0 siblings, 0 replies; 8+ messages in thread
From: bluez.test.bot @ 2026-12-04 17:12 UTC (permalink / raw)
  To: linux-bluetooth, frederic.danis

[-- Attachment #1: Type: text/plain, Size: 1579 bytes --]

This is automated email and please do not reply to this email!

Dear submitter,

Thank you for submitting the patches to the linux bluetooth mailing list.
This is a CI test results with your patch series:
PW Link:https://patchwork.kernel.org/series/1232220/

---Test result---

Test Summary:
CheckPatch                    PASS      3.17 seconds
GitLint                       PASS      1.09 seconds
BuildEll                      PASS      16.85 seconds
BluezMake                     PASS      240.85 seconds
MakeCheck                     PASS      13.92 seconds
MakeDistcheck                 PASS      126.08 seconds
CheckValgrind                 PASS      297.44 seconds
CheckSmatch                   WARNING   247.30 seconds
bluezmakeextell               PASS      79.96 seconds
TestFunctional                PASS      1056.61 seconds
IncrementalBuild              PASS      299.61 seconds
ScanBuild                     PASS      894.58 seconds

Details
##############################
Test: CheckSmatch - WARNING
Desc: Run smatch tool with source
Output:
monitor/packet.c:2293:26: warning: Variable length array is used.monitor/packet.c: note: in included file:monitor/bt.h:4220:52: warning: array of flexible structuresmonitor/bt.h:4208:40: warning: array of flexible structuresmonitor/packet.c:2293:26: warning: Variable length array is used.monitor/packet.c: note: in included file:monitor/bt.h:4220:52: warning: array of flexible structuresmonitor/bt.h:4208:40: warning: array of flexible structures


https://github.com/bluez/bluez/pull/2982

---
Regards,
Linux Bluetooth


^ permalink raw reply	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2026-12-04 17:12 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 16:04 [PATCH BlueZ v8 0/6] monitor: Add an OBEX protocol decoder to btmon Frédéric Danis
2026-12-04 16:04 ` [PATCH BlueZ v8 1/6] monitor: Strip trailing L2CAP FCS before upper layer dissectors Frédéric Danis
2026-12-04 17:12   ` monitor: Add an OBEX protocol decoder to btmon bluez.test.bot
2026-12-04 16:04 ` [PATCH BlueZ v8 2/6] monitor: Add OBEX protocol decoder Frédéric Danis
2026-12-04 16:04 ` [PATCH BlueZ v8 3/6] monitor: Decode PBAP/MAP/BIP Application Parameters tags Frédéric Danis
2026-12-04 16:04 ` [PATCH BlueZ v8 4/6] monitor: Reassemble L2CAP ERTM/Streaming SDUs Frédéric Danis
2026-12-04 16:04 ` [PATCH BlueZ v8 5/6] monitor: Fix RFCOMM UIH frame length and credit-only handling Frédéric Danis
2026-12-04 16:04 ` [PATCH BlueZ v8 6/6] monitor: Reassemble OBEX PDUs split across RFCOMM UIH frames Frédéric Danis

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox