Skip to content

fix: don't drop or replay drained bytes on partial reads - #84

Open
ArniDagur wants to merge 1 commit into
rustls:mainfrom
ArniDagur:fix-drained-buf
Open

ArniDagur wants to merge 1 commit into
rustls:mainfrom
ArniDagur:fix-drained-buf

Conversation

@ArniDagur

@ArniDagur ArniDagur commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Replaces KtlsStream's bare Option<(usize, Vec<u8>)> drained field with a private DrainedBuf that enforces pos < buf.len() whenever a buffer is present.

This structurally eliminates three cursor bugs:

  1. Partial-read data loss in poll_read: let drained = &drained[*drain_index..]; shadowed the Vec<u8>, so *drain_index >= drained.len() compared against the remaining length instead of the full length and silently dropped tail bytes once reads passed the midpoint.
  2. Empty drained buffer in KtlsStream::new: passing Some(Vec::new()) left Some((0, vec![])), causing the first poll_read to return Poll::Ready(Ok(())) with 0 bytes (a spurious EOF) instead of polling the inner stream. Note: KtlsStream::new(io, Some(Vec::new())).into_raw().0 now returns None instead of Some(vec![]), matching drain().
  3. Replayed bytes in KtlsStream::into_raw: drain_index was ignored, returning bytes that had already been consumed by earlier poll_read calls.

Also drops the unnecessary cx.waker().wake_by_ref() on the drained path, which already returns Poll::Ready(Ok(())), and adds tests in ktls/tests/integration_test.rs covering all three bugs and boundary cases.

Replace `KtlsStream`'s bare `Option<(usize, Vec<u8>)>` drained field
with a private `DrainedBuf` type that maintains `pos < buf.len()`
whenever a buffer is present. This fixes three cursor bugs together:

- `poll_read` shadowed `drained` with `&drained[*drain_index..]` and
  compared `*drain_index >= drained.len()` against the remaining length,
  silently dropping tail bytes once partial reads passed the midpoint.
- `KtlsStream::new` accepted `Some(Vec::new())`, causing the first
  `poll_read` to return a spurious 0-byte read instead of polling the
  inner stream (`into_raw().0` now returns `None` in this case).
- `KtlsStream::into_raw` discarded `drain_index` and returned bytes that
  had already been read.

Also drop the unnecessary `cx.waker().wake_by_ref()` on the drained
path, which already returns `Poll::Ready(Ok(()))`.
@ArniDagur ArniDagur changed the title fix: encapsulate drained buffer cursor in DrainedBuf fix: don't drop or replay drained bytes on partial reads Dec 4, 2026
@ArniDagur
ArniDagur marked this pull request as ready for review December 4, 2026 00:08
@ArniDagur

Copy link
Copy Markdown
Contributor Author

@cpu could you take a look?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant