Skip to content

Fix: buf.Compact dropping data when the buffer has no room after its end - #3869

Open
Dv2Corn wants to merge 1 commit into
v2fly:masterfrom
Dv2Corn:fix/buf-compact-room
Open

Dv2Corn wants to merge 1 commit into
v2fly:masterfrom
Dv2Corn:fix/buf-compact-room

Conversation

@Dv2Corn

@Dv2Corn Dv2Corn commented Nov 8, 2026

Copy link
Copy Markdown

buf.Compact can silently drop bytes. It is called on the write path of the TLS, WebSocket, HTTPUpgrade and QUIC transports (WriteMultiBuffer), so the dropped bytes are missing from the stream sent to the peer.

Compact merges the next buffer into the previous one when their total length fits in Size:

if last.Len()+curr.Len() > Size {
mb2 = append(mb2, last)
last = curr
} else {
common.Must2(last.ReadFrom(curr))
curr.Release()

The bytes are copied with Buffer.ReadFrom, which writes after end and copies at most the room left there in one Read:

func (b *Buffer) ReadFrom(reader io.Reader) (int64, error) {
n, err := reader.Read(b.v[b.end:])
b.end += int32(n)
return int64(n), err
}

Len() + curr.Len() <= Size does not mean the next buffer fits after end:

  • a buffer whose start is not 0 (after Advance, e.g. in SplitSize, a partial Read, or header stripping in a protocol reader) has only Size - end bytes of room;
  • a buffer made with FromBytes has no room at all.

In both cases only part of curr is copied, then curr is released, so the rest is lost. For example, a buffer with start=1000, end=1500 followed by a 1000-byte buffer: 500 + 1000 <= 2048, but only 548 bytes fit, so 452 bytes are dropped.

The fix checks the room after end (last.end+curr.Len() > last.Cap()) instead of the total length. For a fresh buffer (start == 0, capacity Size) the result is the same as before.

Tested with a new TestCompactBufferWithoutRoom (advanced buffer and FromBytes buffer):

  • before: unexpected Compact result length 1048, want 1500 and length 2, want 4
  • after: passes; go test ./common/... ./transport/internet/{tls,websocket,httpupgrade,quic}/... passes, golangci-lint with .github/linters/.golangci.yml reports nothing new.

Compact decided whether to merge the next buffer by comparing the total
length with Size, but the bytes are copied after the end of the previous
buffer. When that buffer had been advanced (SplitSize, partial Read,
header stripping) or wraps a byte slice (FromBytes), the room after its
end is smaller than Size - Len(), so ReadFrom copied only part of the
next buffer and the rest was released and lost.

Check the room after the end instead.
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