Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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])

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
147 changes: 147 additions & 0 deletions rawinput.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading