diff --git a/conn.go b/conn.go index ecf404a..5febcfa 100644 --- a/conn.go +++ b/conn.go @@ -108,6 +108,14 @@ type Conn struct { 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) + rawInputBuf []byte + rawInputSmall []byte + rawInputPooled *[]byte + lastRecordLen int // payload length of the last record read + // bytesSent counts the bytes of application data sent. // packetsSent counts packets. bytesSent int64 @@ -616,7 +624,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 { @@ -641,6 +648,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]) @@ -688,6 +709,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 +861,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 +1463,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 +1638,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..a9a721c --- /dev/null +++ b/rawinput.go @@ -0,0 +1,147 @@ +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() +} + +// 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 new file mode 100644 index 0000000..47acb98 --- /dev/null +++ b/rawinput_test.go @@ -0,0 +1,175 @@ +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 + } + } +} + +// 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) + } +}