From 2bd68ed82435d8ca64b5b6840c86d3805e8e5f46 Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Sun, 18 Oct 2026 02:45:02 +0300 Subject: [PATCH 1/4] crypto/tls: size the raw input buffer by what is moving, release it when drained rawInput grew with bytes.Buffer.Grow, which doubles it, and was kept for the life of the connection: a connection that once received a full record holds 16-40 KiB, and 2-4 KiB after the handshake alone (a large ClientHello), while it waits for its peer. A proxy that keeps thousands of mostly idle connections pays that for each of them. A read now takes a small buffer of its own (1 KiB) while the records are small and a pooled buffer that holds the largest record when one does not fit. Once Read has handed out everything that was read and the last record was a short one, the pooled buffer goes back to the pool and the small one takes over again. After a full record the pooled buffer stays, so a transfer keeps one read per record. The handshake message buffer is dropped once the handshake is complete. --- conn.go | 12 +++- rawinput.go | 120 +++++++++++++++++++++++++++++++++++++ rawinput_test.go | 150 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 rawinput.go create mode 100644 rawinput_test.go diff --git a/conn.go b/conn.go index ecf404a..6909ba5 100644 --- a/conn.go +++ b/conn.go @@ -103,6 +103,13 @@ type Conn struct { // input/output in, out halfConn rawInput bytes.Buffer // raw input, starting with a record header + // rawInputBuf is the whole buffer of rawInput: rawInputSmall, the + // connection's own small buffer, or *rawInputPooled, taken from + // rawInputPool for a large record (see rawinput.go) + rawInputBuf []byte + rawInputSmall []byte + rawInputPooled *[]byte + lastRecordLen int // payload length of the last record read input bytes.Reader // application data waiting to be read, from rawInput.Next hand bytes.Buffer // handshake data waiting to be read buffering bool // whether records are buffered in sendBuf @@ -688,6 +695,7 @@ func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { } // Process message. + c.lastRecordLen = n record := c.rawInput.Next(recordHeaderLen + n) data, typ, err := c.in.decrypt(record) if err != nil { @@ -839,7 +847,7 @@ func (c *Conn) readFromUntil(r io.Reader, n int) error { // There might be extra input waiting on the wire. Make a best effort // attempt to fetch it so that it can be used in (*Conn).Read to // "predict" closeNotify alerts. - c.rawInput.Grow(needs + bytes.MinRead) + c.reserveRawInput(needs + bytes.MinRead) _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) return err } @@ -1441,6 +1449,7 @@ func (c *Conn) Read(b []byte) (int, error) { c.in.Lock() defer c.in.Unlock() + defer c.releaseInput() for c.input.Len() == 0 { if err := c.readRecord(); err != nil { @@ -1615,6 +1624,7 @@ func (c *Conn) handshakeContext(ctx context.Context) (ret error) { c.handshakeErr = c.handshakeFn(handshakeCtx) if c.handshakeErr == nil { c.handshakes++ + c.releaseHandshakeBuffers() } else { // If an error occurred during the handshake try to flush the // alert that might be left in the buffer. diff --git a/rawinput.go b/rawinput.go new file mode 100644 index 0000000..d02f794 --- /dev/null +++ b/rawinput.go @@ -0,0 +1,120 @@ +package tls + +import ( + "bytes" + "sync" +) + +// The raw input buffer (Conn.rawInput) is sized by what is moving, not by the +// largest record the connection ever saw. +// +// Upstream grows rawInput with bytes.Buffer.Grow, which doubles it, and keeps +// it for the life of the connection: a connection that once received a full +// record, or only a large ClientHello, holds 16-40 KiB (2-4 KiB after a +// handshake alone) while it waits for its next record. A proxy that keeps +// thousands of mostly idle connections pays that for each of them. +// +// Here a read takes a small buffer of its own while the records are small, +// and a pooled buffer that holds the largest record when one does not fit. +// Once Read has handed out everything that was read (the raw input and the +// plaintext are both drained) and the last record was a short one, a pooled +// buffer goes back to the pool and the small one, which is kept, takes over +// again. A connection that waits for its peer after a short message (an +// answer, an acknowledgement, a keepalive) or right after the handshake +// holds rawInputSmallSize bytes; one that waits after a full record keeps +// the pooled buffer (upstream keeps a larger one); a transfer of full +// records runs on one pooled buffer, with one read per record as before. + +// rawInputSmallSize is the largest buffer a Conn allocates for itself: the +// record header and the read-ahead of readFromUntil (bytes.MinRead) with room +// for a short record. +const rawInputSmallSize = 1024 + +// rawInputPoolSize holds the largest record with its header and the +// read-ahead. +const rawInputPoolSize = recordHeaderLen + maxCiphertext + bytes.MinRead + +var rawInputPool = sync.Pool{New: func() any { + b := make([]byte, rawInputPoolSize) + return &b +}} + +// reserveRawInput makes room for n more bytes after the data in c.rawInput, +// keeping that data. +func (c *Conn) reserveRawInput(n int) { + data := c.rawInput.Bytes() + if cap(data)-len(data) >= n { + return + } + m := len(data) + if c.rawInputBuf != nil && m+n <= len(c.rawInputBuf) { + // The data was read from the front of the buffer: move it back. + k := copy(c.rawInputBuf, data) + c.rawInput = *bytes.NewBuffer(c.rawInputBuf[:k]) + return + } + var buf []byte + switch { + case m+n <= rawInputSmallSize: + if c.rawInputSmall == nil { + c.rawInputSmall = make([]byte, rawInputSmallSize) + } + buf = c.rawInputSmall + case m+n <= rawInputPoolSize: + c.rawInputPooled = rawInputPool.Get().(*[]byte) + buf = *c.rawInputPooled + default: + // Not reached by readFromUntil, whose records fit the pooled size. + buf = make([]byte, m+n) + } + k := copy(buf, data) + if c.rawInputPooled != nil && &buf[0] != &(*c.rawInputPooled)[0] { + c.putRawInput() + } + c.rawInput = *bytes.NewBuffer(buf[:k]) + c.rawInputBuf = buf +} + +// putRawInput returns a pooled raw input buffer to the pool. The caller +// replaces c.rawInput. +func (c *Conn) putRawInput() { + if c.rawInputPooled != nil { + rawInputPool.Put(c.rawInputPooled) + c.rawInputPooled = nil + } + c.rawInputBuf = nil +} + +// releaseInput lets go of the input buffers once everything read was handed +// out: a pooled raw input buffer goes back to the pool after a record that +// the small buffer holds, a small one is kept for the next record. c.in must +// be held. +// +// After a large record the pooled buffer stays: a transfer drains the conn +// after every record when its reader keeps up, and reading the next record's +// header into the small buffer would cost a second read per record. +func (c *Conn) releaseInput() { + if c.input.Len() != 0 || c.rawInput.Len() != 0 { + return + } + // c.input points into c.rawInput. + c.input.Reset(nil) + if c.rawInputPooled != nil && c.lastRecordLen+recordHeaderLen+bytes.MinRead <= rawInputSmallSize { + c.putRawInput() + // back to the small buffer, if there is one yet + c.rawInput = *bytes.NewBuffer(c.rawInputSmall[:0]) + c.rawInputBuf = c.rawInputSmall + } else { + c.rawInput.Reset() + } +} + +// releaseHandshakeBuffers drops what only the handshake needed once it is +// complete and nothing is left to read: the handshake message buffer and the +// raw input. c.in must be held. +func (c *Conn) releaseHandshakeBuffers() { + if c.hand.Len() == 0 { + c.hand = bytes.Buffer{} + } + c.releaseInput() +} diff --git a/rawinput_test.go b/rawinput_test.go new file mode 100644 index 0000000..ece1217 --- /dev/null +++ b/rawinput_test.go @@ -0,0 +1,150 @@ +package tls + +import ( + "bytes" + "io" + "testing" +) + +// rawInputPair returns a client and a server Conn with the handshake done. +func rawInputPair(t *testing.T) (*Conn, *Conn) { + t.Helper() + c, s := localPipe(t) + client := Client(c, testConfig.Clone()) + server := Server(s, testConfig.Clone()) + errc := make(chan error, 1) + go func() { errc <- server.Handshake() }() + if err := client.Handshake(); err != nil { + t.Fatal(err) + } + if err := <-errc; err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close(); server.Close() }) + return client, server +} + +func checkIdle(t *testing.T, conn *Conn, when string) { + t.Helper() + conn.in.Lock() + defer conn.in.Unlock() + if conn.rawInputPooled != nil { + t.Errorf("%s: a drained conn holds a pooled raw input buffer", when) + } + if n := cap(conn.rawInput.Bytes()); n > rawInputSmallSize { + t.Errorf("%s: a drained conn holds %d bytes of raw input, want at most %d", when, n, rawInputSmallSize) + } + if n := conn.hand.Cap(); n != 0 && when == "after the handshake" { + t.Errorf("%s: the handshake buffer keeps %d bytes", when, n) + } +} + +// TestRawInputIdle: a connection holds no more than a small raw input +// buffer after the handshake and after a transfer of full records, and the +// data arrives intact whatever the record sizes. +func TestRawInputIdle(t *testing.T) { + client, server := rawInputPair(t) + checkIdle(t, client, "after the handshake") + checkIdle(t, server, "after the handshake") + + sizes := []int{1, 100, 900, 2000, 16384, 70000, 5, 300000, 17} + var want bytes.Buffer + for i, n := range sizes { + p := make([]byte, n) + for j := range p { + p[j] = byte(i + j) + } + want.Write(p) + } + go func() { + for i, n := range sizes { + p := make([]byte, n) + for j := range p { + p[j] = byte(i + j) + } + if _, err := client.Write(p); err != nil { + return + } + } + }() + got := make([]byte, want.Len()) + // Reads of every size: whole records, parts of records. + for off, step := 0, 1; off < len(got); step = step*3 + 1 { + if step > 50000 { + step = 7 + } + end := off + step + if end > len(got) { + end = len(got) + } + n, err := io.ReadFull(server, got[off:end]) + if err != nil { + t.Fatal(err) + } + off += n + } + if !bytes.Equal(got, want.Bytes()) { + t.Fatal("the data was corrupted") + } + checkIdle(t, server, "after a transfer") + + // a short message back and forth keeps the small buffer + go client.Write([]byte("ping")) + p := make([]byte, 4) + if _, err := io.ReadFull(server, p); err != nil || string(p) != "ping" { + t.Fatalf("got %q, %v", p, err) + } + checkIdle(t, server, "after a short message") +} + +// TestRawInputCloseNotify: the close_notify read ahead with the last data +// still ends the stream with EOF. +func TestRawInputCloseNotify(t *testing.T) { + client, server := rawInputPair(t) + go func() { + client.Write(bytes.Repeat([]byte("x"), 20000)) + client.CloseWrite() + }() + got, err := io.ReadAll(server) + if err != nil { + t.Fatal(err) + } + if len(got) != 20000 { + t.Fatalf("read %d bytes, want 20000", len(got)) + } + checkIdle(t, server, "after close_notify") +} + +func BenchmarkRawInputThroughput(b *testing.B) { + c, s := localPipe(b) + client := Client(c, testConfig.Clone()) + server := Server(s, testConfig.Clone()) + go server.Handshake() + if err := client.Handshake(); err != nil { + b.Fatal(err) + } + defer client.Close() + defer server.Close() + const chunk = 1 << 20 + go func() { + p := make([]byte, chunk) + for { + if _, err := client.Write(p); err != nil { + return + } + } + }() + p := make([]byte, 32<<10) + b.SetBytes(chunk) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + for n := 0; n < chunk; { + m, err := server.Read(p) + if err != nil { + b.Fatal(err) + } + n += m + } + } +} From 1233c8175e90d6f7e74882e0c10153a7a273e3cf Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Sun, 18 Oct 2026 03:01:01 +0300 Subject: [PATCH 2/4] crypto/tls: wait for the next record in a small frame readRecordOrCCS blocks in the read of the record header with its whole frame (close to 500 bytes) on the stack. An idle connection's goroutine spends its life there, and the runtime shrinks a goroutine stack at GC only when less than a quarter of it is in use: every frame above that read counts towards keeping an idle connection at a 16 KiB stack instead of 8 KiB. The record processing after the header moves to readRecordBody. --- conn.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/conn.go b/conn.go index 6909ba5..4c410d6 100644 --- a/conn.go +++ b/conn.go @@ -623,7 +623,6 @@ func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { if c.in.err != nil { return c.in.err } - handshakeComplete := c.isHandshakeComplete.Load() // This function modifies c.rawInput, which owns the c.input memory. if c.input.Len() != 0 { @@ -648,6 +647,20 @@ func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { } return err } + return c.readRecordBody(expectChangeCipherSpec) +} + +// readRecordBody is the rest of readRecordOrCCS once a record header is in +// c.rawInput. +// +// It is a function of its own so that its frame is not on the stack while a +// connection waits for its next record: an idle connection's goroutine +// blocks in the header read above, and the runtime shrinks a goroutine stack +// at GC only when less than a quarter of it is in use. +// +//go:noinline +func (c *Conn) readRecordBody(expectChangeCipherSpec bool) error { + handshakeComplete := c.isHandshakeComplete.Load() hdr := c.rawInput.Bytes()[:recordHeaderLen] typ := recordType(hdr[0]) From badeaf7be37aac093737d6367b175d869153b8b3 Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Sun, 18 Oct 2026 03:06:05 +0300 Subject: [PATCH 3/4] crypto/tls: add Conn.WaitRead, to wait for data without a read buffer A proxy's relay keeps a read buffer for each connection while it waits in Read. WaitRead blocks until Read can return data without blocking (or until it would fail, with the same error), so that the caller takes its buffer only once data is there and a connection whose peer is silent holds none. --- rawinput.go | 27 +++++++++++++++++++++++++++ rawinput_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/rawinput.go b/rawinput.go index d02f794..a9a721c 100644 --- a/rawinput.go +++ b/rawinput.go @@ -118,3 +118,30 @@ func (c *Conn) releaseHandshakeBuffers() { } c.releaseInput() } + +// WaitRead blocks until Read can return data without blocking, or until the +// read would fail; the error is the one Read would return. It runs the +// handshake first, like Read. +// +// A caller that keeps a read buffer for every connection, such as a proxy's +// relay, waits here and takes its buffer only once data is there, so that a +// connection whose peer is silent holds no read buffer beyond the raw input +// (see rawinput.go). +func (c *Conn) WaitRead() error { + if err := c.Handshake(); err != nil { + return err + } + c.in.Lock() + defer c.in.Unlock() + for c.input.Len() == 0 { + if err := c.readRecord(); err != nil { + return err + } + for c.hand.Len() > 0 { + if err := c.handlePostHandshakeMessage(); err != nil { + return err + } + } + } + return nil +} diff --git a/rawinput_test.go b/rawinput_test.go index ece1217..47acb98 100644 --- a/rawinput_test.go +++ b/rawinput_test.go @@ -148,3 +148,28 @@ func BenchmarkRawInputThroughput(b *testing.B) { } } } + +// TestWaitRead: WaitRead returns once data can be read, consumes nothing, +// and reports the error Read would. +func TestWaitRead(t *testing.T) { + client, server := rawInputPair(t) + go client.Write([]byte("hello")) + if err := server.WaitRead(); err != nil { + t.Fatal(err) + } + if err := server.WaitRead(); err != nil { // data is waiting: returns at once + t.Fatal(err) + } + p := make([]byte, 5) + if _, err := io.ReadFull(server, p); err != nil || string(p) != "hello" { + t.Fatalf("got %q, %v", p, err) + } + checkIdle(t, server, "after WaitRead and Read") + client.Close() + if err := server.WaitRead(); err != io.EOF { + t.Fatalf("WaitRead after close_notify: %v, want EOF", err) + } + if _, err := server.Read(p); err != io.EOF { + t.Fatalf("Read after close_notify: %v, want EOF", err) + } +} From 0a54a49f00e8e93310be82633a1805736615eb90 Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Sun, 18 Oct 2026 04:24:58 +0300 Subject: [PATCH 4/4] crypto/tls: keep the raw input fields apart, gofmt --- conn.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/conn.go b/conn.go index 4c410d6..5febcfa 100644 --- a/conn.go +++ b/conn.go @@ -103,6 +103,11 @@ type Conn struct { // input/output in, out halfConn rawInput bytes.Buffer // raw input, starting with a record header + input bytes.Reader // application data waiting to be read, from rawInput.Next + hand bytes.Buffer // handshake data waiting to be read + buffering bool // whether records are buffered in sendBuf + sendBuf []byte // a buffer of records waiting to be sent + // rawInputBuf is the whole buffer of rawInput: rawInputSmall, the // connection's own small buffer, or *rawInputPooled, taken from // rawInputPool for a large record (see rawinput.go) @@ -110,10 +115,6 @@ type Conn struct { rawInputSmall []byte rawInputPooled *[]byte lastRecordLen int // payload length of the last record read - input bytes.Reader // application data waiting to be read, from rawInput.Next - hand bytes.Buffer // handshake data waiting to be read - buffering bool // whether records are buffered in sendBuf - sendBuf []byte // a buffer of records waiting to be sent // bytesSent counts the bytes of application data sent. // packetsSent counts packets.