From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=148.251.105.195 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796400265; b=bFm0Z9eHGzxU0f8DDxF8HauMmx8Q1RJ70dFWgUIJFo0kZq42iDNG6px1lWJ9/0009b3d 6lpdcGJ/2uL/s99k9enRnRLzSeFTTUo4oLoiJwvSf2oJG0pD8h1duh1strq8Cudr49cuH 77KdTtVhjPZtLzWbZI437RiSZYqmCytbSIQ1wbvCALETB4jNu3rMa7hUzpxpcmnLgN2LF srUrKMm0Kp+J62QrS3HsWEYx4n5VqoxyhVxOSrrQI4RDBA9v5glPXF4+XweKz1DtH4n2p WGFgXcqHKFmIQGiyldmMY4cwNq9ek9DjmbTv/3F1pJfSoBddB97ugw+DPMHifzyO0wQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796400265; h=DMARC-Filter:DKIM-Signature:Received:From:To:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version:Content-Type: Content-Transfer-Encoding; bh=7L2qH+saQt1NM9OlVeHLk5hLW0CrpYIakUbyZzF/p0M=; b=OO+nUfvjKi4jeXPNu6yXrPixA/Aw81e7EFK+Cuo3FDNm0T7wDdvj9nXqx2PLghYPbQBs qTdaNbwh3Vz+TJ+hEH+idcEjXT82a06317Q9Bv7MYqMk6jysWK61nJcfXKoUlORKfwfpj ECWe23UMjVbEs8t6jQmkGCcSS5xNHNn51EPcNmB+S2dbEtFEPrhfAJf06QrZele1v8yt4 lV2we7Fe7Gy1smrqlL8GpW0TBzJesybh+i85NP8BW8+RnC+T8Xh92r1XAoKkgTVKnkAbO Ir8Pwt6bniIamkmqYcG5K+B8SfQRQTqBb1/rpEE1mSRZv/SJtNBpDOosACH1S0vj/9Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass header.d=collabora.com header.i=@collabora.com header.a=rsa-sha256 header.s=mail header.b=LWlkF772; arc=none smtp.remote-ip=148.251.105.195 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DCBCE606A330 for ; Fri, 4 Dec 2026 16:04:23 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org DCBCE606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.a=rsa-sha256 header.s=mail header.b=LWlkF772 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1796400262; bh=+R0LDnfjb7xoj/HFHRpo3lvY+v/q22SvE3PDSfOfBS8=; h=From:To:Subject:Date:In-Reply-To:References:From; b=LWlkF772nAZFxKQlbEO+T1p9hwhG5vA6h5u48VkKOeXSrNZ5cYBbgMsjAqDZH65IT va5zV6VBd1Zs04i8ByqAUCXsx61XFEky908P6SDcxlqDeU6FrPTrPHZojrbOCjWNbQ Pxu5jZctBAQFmEo60J9hB0EHncB0Uc0ix3142eJsH7XPAc4jKs6a4O+S+98qu+FJZC Qcnig1dmBgjhse+/jBSQeb0khS2kawWatbbYGRD/QW9LYUFYRVct5k+IT3ITwDeiLy ko4+cjyQVVVfmBZff5VLkIICUvETUPwhuAcOob/ADlZ1N1NBpMpQPasrI9GBKG5X27 R3hVkVStZBlrw== Received: from fdanis-ThinkPad-X1.. (unknown [100.64.1.5]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: fdanis) by bali.collaboradmins.com (Postfix) with ESMTPSA id 497DA17E11E0 for ; Fri, 04 Dec 2026 17:04:22 +0100 (CET) From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Danis?= To: linux-bluetooth@vger.kernel.org Subject: [PATCH BlueZ v8 4/6] monitor: Reassemble L2CAP ERTM/Streaming SDUs Date: Fri, 4 Dec 2026 17:04:14 +0100 Message-ID: <20261204160416.1254097-5-frederic.danis@collabora.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20261204160416.1254097-1-frederic.danis@collabora.com> References: <20261204160416.1254097-1-frederic.danis@collabora.com> X-Mailing-List: linux-bluetooth@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit 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