Skip to content

Commit ae00df1

Browse files
tomberganagl
authored andcommitted
crypto/tls: implement dynamic record sizing
Currently, if a client of crypto/tls (e.g., net/http, http2) calls tls.Conn.Write with a 33KB buffer, that ends up writing three TLS records: 16KB, 16KB, and 1KB. Slow clients (such as 2G phones) must download the first 16KB record before they can decrypt the first byte. To improve latency, it's better to send smaller TLS records. However, sending smaller records adds overhead (more overhead bytes and more crypto calls), which slightly hurts throughput. A simple heuristic, implemented in this change, is to send small records for new connections, then boost to large records after the first 1MB has been written on the connection. Fixes #14376 Change-Id: Ice0f6279325be6775aa55351809f88e07dd700cd Reviewed-on: https://go-review.googlesource.com/19591 TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Tom Bergan <[email protected]> Reviewed-by: Adam Langley <[email protected]>
1 parent 1220ac2 commit ae00df1

File tree

3 files changed

+213
-4
lines changed

3 files changed

+213
-4
lines changed

src/crypto/tls/common.go

+6
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,12 @@ type Config struct {
349349
// be used.
350350
CurvePreferences []CurveID
351351

352+
// DynamicRecordSizingDisabled disables adaptive sizing of TLS records.
353+
// When true, the largest possible TLS record size is always used. When
354+
// false, the size of TLS records may be adjusted in an attempt to
355+
// improve latency.
356+
DynamicRecordSizingDisabled bool
357+
352358
serverInitOnce sync.Once // guards calling (*Config).serverInit
353359

354360
// mutex protects sessionTicketKeys

src/crypto/tls/conn.go

+79-4
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ type Conn struct {
5757
input *block // application data waiting to be read
5858
hand bytes.Buffer // handshake data waiting to be read
5959

60+
// bytesSent counts the number of bytes of application data that have
61+
// been sent.
62+
bytesSent int64
63+
6064
// activeCall is an atomic int32; the low bit is whether Close has
6165
// been called. the rest of the bits are the number of goroutines
6266
// in Conn.Write.
@@ -712,6 +716,76 @@ func (c *Conn) sendAlert(err alert) error {
712716
return c.sendAlertLocked(err)
713717
}
714718

719+
const (
720+
// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
721+
// size (MSS). A constant is used, rather than querying the kernel for
722+
// the actual MSS, to avoid complexity. The value here is the IPv6
723+
// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
724+
// bytes) and a TCP header with timestamps (32 bytes).
725+
tcpMSSEstimate = 1208
726+
727+
// recordSizeBoostThreshold is the number of bytes of application data
728+
// sent after which the TLS record size will be increased to the
729+
// maximum.
730+
recordSizeBoostThreshold = 1 * 1024 * 1024
731+
)
732+
733+
// maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
734+
// next application data record. There is the following trade-off:
735+
//
736+
// - For latency-sensitive applications, such as web browsing, each TLS
737+
// record should fit in one TCP segment.
738+
// - For throughput-sensitive applications, such as large file transfers,
739+
// larger TLS records better amortize framing and encryption overheads.
740+
//
741+
// A simple heuristic that works well in practice is to use small records for
742+
// the first 1MB of data, then use larger records for subsequent data, and
743+
// reset back to smaller records after the connection becomes idle. See "High
744+
// Performance Web Networking", Chapter 4, or:
745+
// https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
746+
//
747+
// In the interests of simplicity and determinism, this code does not attempt
748+
// to reset the record size once the connection is idle, however.
749+
//
750+
// c.out.Mutex <= L.
751+
func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
752+
if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
753+
return maxPlaintext
754+
}
755+
756+
if c.bytesSent >= recordSizeBoostThreshold {
757+
return maxPlaintext
758+
}
759+
760+
// Subtract TLS overheads to get the maximum payload size.
761+
macSize := 0
762+
if c.out.mac != nil {
763+
macSize = c.out.mac.Size()
764+
}
765+
766+
payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
767+
if c.out.cipher != nil {
768+
switch ciph := c.out.cipher.(type) {
769+
case cipher.Stream:
770+
payloadBytes -= macSize
771+
case cipher.AEAD:
772+
payloadBytes -= ciph.Overhead()
773+
case cbcMode:
774+
blockSize := ciph.BlockSize()
775+
// The payload must fit in a multiple of blockSize, with
776+
// room for at least one padding byte.
777+
payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
778+
// The MAC is appended before padding so affects the
779+
// payload size directly.
780+
payloadBytes -= macSize
781+
default:
782+
panic("unknown cipher type")
783+
}
784+
}
785+
786+
return payloadBytes
787+
}
788+
715789
// writeRecord writes a TLS record with the given type and payload
716790
// to the connection and updates the record layer state.
717791
// c.out.Mutex <= L.
@@ -721,10 +795,6 @@ func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
721795

722796
var n int
723797
for len(data) > 0 {
724-
m := len(data)
725-
if m > maxPlaintext {
726-
m = maxPlaintext
727-
}
728798
explicitIVLen := 0
729799
explicitIVIsSeq := false
730800

@@ -747,6 +817,10 @@ func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
747817
explicitIVIsSeq = true
748818
}
749819
}
820+
m := len(data)
821+
if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
822+
m = maxPayload
823+
}
750824
b.resize(recordHeaderLen + explicitIVLen + m)
751825
b.data[0] = byte(typ)
752826
vers := c.vers
@@ -774,6 +848,7 @@ func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
774848
if _, err := c.conn.Write(b.data); err != nil {
775849
return n, err
776850
}
851+
c.bytesSent += int64(m)
777852
n += m
778853
data = data[m:]
779854
}

src/crypto/tls/conn_test.go

+128
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
package tls
66

77
import (
8+
"bytes"
9+
"io"
10+
"net"
811
"testing"
912
)
1013

@@ -116,3 +119,128 @@ func TestCertificateSelection(t *testing.T) {
116119
t.Errorf("foo.bar.baz.example.com returned certificate %d, not 0", n)
117120
}
118121
}
122+
123+
// Run with multiple crypto configs to test the logic for computing TLS record overheads.
124+
func runDynamicRecordSizingTest(t *testing.T, config *Config) {
125+
clientConn, serverConn := net.Pipe()
126+
127+
serverConfig := *config
128+
serverConfig.DynamicRecordSizingDisabled = false
129+
tlsConn := Server(serverConn, &serverConfig)
130+
131+
recordSizesChan := make(chan []int, 1)
132+
go func() {
133+
// This goroutine performs a TLS handshake over clientConn and
134+
// then reads TLS records until EOF. It writes a slice that
135+
// contains all the record sizes to recordSizesChan.
136+
defer close(recordSizesChan)
137+
defer clientConn.Close()
138+
139+
tlsConn := Client(clientConn, config)
140+
if err := tlsConn.Handshake(); err != nil {
141+
t.Errorf("Error from client handshake: %s", err)
142+
return
143+
}
144+
145+
var recordHeader [recordHeaderLen]byte
146+
var record []byte
147+
var recordSizes []int
148+
149+
for {
150+
n, err := clientConn.Read(recordHeader[:])
151+
if err == io.EOF {
152+
break
153+
}
154+
if err != nil || n != len(recordHeader) {
155+
t.Errorf("Error from client read: %s", err)
156+
return
157+
}
158+
159+
length := int(recordHeader[3])<<8 | int(recordHeader[4])
160+
if len(record) < length {
161+
record = make([]byte, length)
162+
}
163+
164+
n, err = clientConn.Read(record[:length])
165+
if err != nil || n != length {
166+
t.Errorf("Error from client read: %s", err)
167+
return
168+
}
169+
170+
// The last record will be a close_notify alert, which
171+
// we don't wish to record.
172+
if recordType(recordHeader[0]) == recordTypeApplicationData {
173+
recordSizes = append(recordSizes, recordHeaderLen+length)
174+
}
175+
}
176+
177+
recordSizesChan <- recordSizes
178+
}()
179+
180+
if err := tlsConn.Handshake(); err != nil {
181+
t.Fatalf("Error from server handshake: %s", err)
182+
}
183+
184+
// The server writes these plaintexts in order.
185+
plaintext := bytes.Join([][]byte{
186+
bytes.Repeat([]byte("x"), recordSizeBoostThreshold),
187+
bytes.Repeat([]byte("y"), maxPlaintext*2),
188+
bytes.Repeat([]byte("z"), maxPlaintext),
189+
}, nil)
190+
191+
if _, err := tlsConn.Write(plaintext); err != nil {
192+
t.Fatalf("Error from server write: %s", err)
193+
}
194+
if err := tlsConn.Close(); err != nil {
195+
t.Fatalf("Error from server close: %s", err)
196+
}
197+
198+
recordSizes := <-recordSizesChan
199+
if recordSizes == nil {
200+
t.Fatalf("Client encountered an error")
201+
}
202+
203+
// Drop the size of last record, which is likely to be truncated.
204+
recordSizes = recordSizes[:len(recordSizes)-1]
205+
206+
// recordSizes should contain a series of records smaller than
207+
// tcpMSSEstimate followed by some larger than maxPlaintext.
208+
seenLargeRecord := false
209+
for i, size := range recordSizes {
210+
if !seenLargeRecord {
211+
if size > tcpMSSEstimate {
212+
if i < 100 {
213+
t.Fatalf("Record #%d has size %d, which is too large too soon", i, size)
214+
}
215+
if size <= maxPlaintext {
216+
t.Fatalf("Record #%d has odd size %d", i, size)
217+
}
218+
seenLargeRecord = true
219+
}
220+
} else if size <= maxPlaintext {
221+
t.Fatalf("Record #%d has size %d but should be full sized", i, size)
222+
}
223+
}
224+
225+
if !seenLargeRecord {
226+
t.Fatalf("No large records observed")
227+
}
228+
}
229+
230+
func TestDynamicRecordSizingWithStreamCipher(t *testing.T) {
231+
config := *testConfig
232+
config.CipherSuites = []uint16{TLS_RSA_WITH_RC4_128_SHA}
233+
runDynamicRecordSizingTest(t, &config)
234+
}
235+
236+
func TestDynamicRecordSizingWithCBC(t *testing.T) {
237+
config := *testConfig
238+
config.CipherSuites = []uint16{TLS_RSA_WITH_AES_256_CBC_SHA}
239+
runDynamicRecordSizingTest(t, &config)
240+
}
241+
242+
func TestDynamicRecordSizingWithAEAD(t *testing.T) {
243+
config := *testConfig
244+
config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
245+
runDynamicRecordSizingTest(t, &config)
246+
}

0 commit comments

Comments
 (0)