Home | History | Annotate | Download | only in runner
      1 // Copyright 2009 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package runner
      6 
      7 import (
      8 	"bytes"
      9 	"encoding/binary"
     10 	"fmt"
     11 )
     12 
     13 func writeLen(buf []byte, v, size int) {
     14 	for i := 0; i < size; i++ {
     15 		buf[size-i-1] = byte(v)
     16 		v >>= 8
     17 	}
     18 	if v != 0 {
     19 		panic("length is too long")
     20 	}
     21 }
     22 
     23 type byteBuilder struct {
     24 	buf       *[]byte
     25 	start     int
     26 	prefixLen int
     27 	child     *byteBuilder
     28 }
     29 
     30 func newByteBuilder() *byteBuilder {
     31 	buf := make([]byte, 0, 32)
     32 	return &byteBuilder{buf: &buf}
     33 }
     34 
     35 func (bb *byteBuilder) len() int {
     36 	return len(*bb.buf) - bb.start - bb.prefixLen
     37 }
     38 
     39 func (bb *byteBuilder) data() []byte {
     40 	bb.flush()
     41 	return (*bb.buf)[bb.start+bb.prefixLen:]
     42 }
     43 
     44 func (bb *byteBuilder) flush() {
     45 	if bb.child == nil {
     46 		return
     47 	}
     48 	bb.child.flush()
     49 	writeLen((*bb.buf)[bb.child.start:], bb.child.len(), bb.child.prefixLen)
     50 	bb.child = nil
     51 	return
     52 }
     53 
     54 func (bb *byteBuilder) finish() []byte {
     55 	bb.flush()
     56 	return *bb.buf
     57 }
     58 
     59 func (bb *byteBuilder) addU8(u uint8) {
     60 	bb.flush()
     61 	*bb.buf = append(*bb.buf, u)
     62 }
     63 
     64 func (bb *byteBuilder) addU16(u uint16) {
     65 	bb.flush()
     66 	*bb.buf = append(*bb.buf, byte(u>>8), byte(u))
     67 }
     68 
     69 func (bb *byteBuilder) addU24(u int) {
     70 	bb.flush()
     71 	*bb.buf = append(*bb.buf, byte(u>>16), byte(u>>8), byte(u))
     72 }
     73 
     74 func (bb *byteBuilder) addU32(u uint32) {
     75 	bb.flush()
     76 	*bb.buf = append(*bb.buf, byte(u>>24), byte(u>>16), byte(u>>8), byte(u))
     77 }
     78 
     79 func (bb *byteBuilder) addU64(u uint64) {
     80 	bb.flush()
     81 	var b [8]byte
     82 	binary.BigEndian.PutUint64(b[:], u)
     83 	*bb.buf = append(*bb.buf, b[:]...)
     84 }
     85 
     86 func (bb *byteBuilder) addU8LengthPrefixed() *byteBuilder {
     87 	return bb.createChild(1)
     88 }
     89 
     90 func (bb *byteBuilder) addU16LengthPrefixed() *byteBuilder {
     91 	return bb.createChild(2)
     92 }
     93 
     94 func (bb *byteBuilder) addU24LengthPrefixed() *byteBuilder {
     95 	return bb.createChild(3)
     96 }
     97 
     98 func (bb *byteBuilder) addU32LengthPrefixed() *byteBuilder {
     99 	return bb.createChild(4)
    100 }
    101 
    102 func (bb *byteBuilder) addBytes(b []byte) {
    103 	bb.flush()
    104 	*bb.buf = append(*bb.buf, b...)
    105 }
    106 
    107 func (bb *byteBuilder) createChild(lengthPrefixSize int) *byteBuilder {
    108 	bb.flush()
    109 	bb.child = &byteBuilder{
    110 		buf:       bb.buf,
    111 		start:     len(*bb.buf),
    112 		prefixLen: lengthPrefixSize,
    113 	}
    114 	for i := 0; i < lengthPrefixSize; i++ {
    115 		*bb.buf = append(*bb.buf, 0)
    116 	}
    117 	return bb.child
    118 }
    119 
    120 func (bb *byteBuilder) discardChild() {
    121 	if bb.child == nil {
    122 		return
    123 	}
    124 	*bb.buf = (*bb.buf)[:bb.child.start]
    125 	bb.child = nil
    126 }
    127 
    128 type byteReader []byte
    129 
    130 func (br *byteReader) readInternal(out *byteReader, n int) bool {
    131 	if len(*br) < n {
    132 		return false
    133 	}
    134 	*out = (*br)[:n]
    135 	*br = (*br)[n:]
    136 	return true
    137 }
    138 
    139 func (br *byteReader) readBytes(out *[]byte, n int) bool {
    140 	var child byteReader
    141 	if !br.readInternal(&child, n) {
    142 		return false
    143 	}
    144 	*out = []byte(child)
    145 	return true
    146 }
    147 
    148 func (br *byteReader) readUint(out *uint64, n int) bool {
    149 	var b []byte
    150 	if !br.readBytes(&b, n) {
    151 		return false
    152 	}
    153 	*out = 0
    154 	for _, v := range b {
    155 		*out <<= 8
    156 		*out |= uint64(v)
    157 	}
    158 	return true
    159 }
    160 
    161 func (br *byteReader) readU8(out *uint8) bool {
    162 	var b []byte
    163 	if !br.readBytes(&b, 1) {
    164 		return false
    165 	}
    166 	*out = b[0]
    167 	return true
    168 }
    169 
    170 func (br *byteReader) readU16(out *uint16) bool {
    171 	var v uint64
    172 	if !br.readUint(&v, 2) {
    173 		return false
    174 	}
    175 	*out = uint16(v)
    176 	return true
    177 }
    178 
    179 func (br *byteReader) readU24(out *uint32) bool {
    180 	var v uint64
    181 	if !br.readUint(&v, 3) {
    182 		return false
    183 	}
    184 	*out = uint32(v)
    185 	return true
    186 }
    187 
    188 func (br *byteReader) readU32(out *uint32) bool {
    189 	var v uint64
    190 	if !br.readUint(&v, 4) {
    191 		return false
    192 	}
    193 	*out = uint32(v)
    194 	return true
    195 }
    196 
    197 func (br *byteReader) readU64(out *uint64) bool {
    198 	return br.readUint(out, 8)
    199 }
    200 
    201 func (br *byteReader) readLengthPrefixed(out *byteReader, n int) bool {
    202 	var length uint64
    203 	return br.readUint(&length, n) &&
    204 		uint64(len(*br)) >= length &&
    205 		br.readInternal(out, int(length))
    206 }
    207 
    208 func (br *byteReader) readLengthPrefixedBytes(out *[]byte, n int) bool {
    209 	var length uint64
    210 	return br.readUint(&length, n) &&
    211 		uint64(len(*br)) >= length &&
    212 		br.readBytes(out, int(length))
    213 }
    214 
    215 func (br *byteReader) readU8LengthPrefixed(out *byteReader) bool {
    216 	return br.readLengthPrefixed(out, 1)
    217 }
    218 func (br *byteReader) readU8LengthPrefixedBytes(out *[]byte) bool {
    219 	return br.readLengthPrefixedBytes(out, 1)
    220 }
    221 
    222 func (br *byteReader) readU16LengthPrefixed(out *byteReader) bool {
    223 	return br.readLengthPrefixed(out, 2)
    224 }
    225 func (br *byteReader) readU16LengthPrefixedBytes(out *[]byte) bool {
    226 	return br.readLengthPrefixedBytes(out, 2)
    227 }
    228 
    229 func (br *byteReader) readU24LengthPrefixed(out *byteReader) bool {
    230 	return br.readLengthPrefixed(out, 3)
    231 }
    232 func (br *byteReader) readU24LengthPrefixedBytes(out *[]byte) bool {
    233 	return br.readLengthPrefixedBytes(out, 3)
    234 }
    235 
    236 func (br *byteReader) readU32LengthPrefixed(out *byteReader) bool {
    237 	return br.readLengthPrefixed(out, 4)
    238 }
    239 func (br *byteReader) readU32LengthPrefixedBytes(out *[]byte) bool {
    240 	return br.readLengthPrefixedBytes(out, 4)
    241 }
    242 
    243 type keyShareEntry struct {
    244 	group       CurveID
    245 	keyExchange []byte
    246 }
    247 
    248 type pskIdentity struct {
    249 	ticket              []uint8
    250 	obfuscatedTicketAge uint32
    251 }
    252 
    253 type clientHelloMsg struct {
    254 	raw                     []byte
    255 	isDTLS                  bool
    256 	vers                    uint16
    257 	random                  []byte
    258 	sessionId               []byte
    259 	cookie                  []byte
    260 	cipherSuites            []uint16
    261 	compressionMethods      []uint8
    262 	nextProtoNeg            bool
    263 	serverName              string
    264 	ocspStapling            bool
    265 	supportedCurves         []CurveID
    266 	supportedPoints         []uint8
    267 	hasKeyShares            bool
    268 	keyShares               []keyShareEntry
    269 	keySharesRaw            []byte
    270 	trailingKeyShareData    bool
    271 	pskIdentities           []pskIdentity
    272 	pskKEModes              []byte
    273 	pskBinders              [][]uint8
    274 	hasEarlyData            bool
    275 	tls13Cookie             []byte
    276 	ticketSupported         bool
    277 	sessionTicket           []uint8
    278 	signatureAlgorithms     []signatureAlgorithm
    279 	signatureAlgorithmsCert []signatureAlgorithm
    280 	supportedVersions       []uint16
    281 	secureRenegotiation     []byte
    282 	alpnProtocols           []string
    283 	quicTransportParams     []byte
    284 	duplicateExtension      bool
    285 	channelIDSupported      bool
    286 	tokenBindingParams      []byte
    287 	tokenBindingVersion     uint16
    288 	npnAfterAlpn            bool
    289 	extendedMasterSecret    bool
    290 	srtpProtectionProfiles  []uint16
    291 	srtpMasterKeyIdentifier string
    292 	sctListSupported        bool
    293 	customExtension         string
    294 	hasGREASEExtension      bool
    295 	pskBinderFirst          bool
    296 	omitExtensions          bool
    297 	emptyExtensions         bool
    298 	pad                     int
    299 	compressedCertAlgs      []uint16
    300 	delegatedCredentials    bool
    301 }
    302 
    303 func (m *clientHelloMsg) equal(i interface{}) bool {
    304 	m1, ok := i.(*clientHelloMsg)
    305 	if !ok {
    306 		return false
    307 	}
    308 
    309 	return bytes.Equal(m.raw, m1.raw) &&
    310 		m.isDTLS == m1.isDTLS &&
    311 		m.vers == m1.vers &&
    312 		bytes.Equal(m.random, m1.random) &&
    313 		bytes.Equal(m.sessionId, m1.sessionId) &&
    314 		bytes.Equal(m.cookie, m1.cookie) &&
    315 		eqUint16s(m.cipherSuites, m1.cipherSuites) &&
    316 		bytes.Equal(m.compressionMethods, m1.compressionMethods) &&
    317 		m.nextProtoNeg == m1.nextProtoNeg &&
    318 		m.serverName == m1.serverName &&
    319 		m.ocspStapling == m1.ocspStapling &&
    320 		eqCurveIDs(m.supportedCurves, m1.supportedCurves) &&
    321 		bytes.Equal(m.supportedPoints, m1.supportedPoints) &&
    322 		m.hasKeyShares == m1.hasKeyShares &&
    323 		eqKeyShareEntryLists(m.keyShares, m1.keyShares) &&
    324 		m.trailingKeyShareData == m1.trailingKeyShareData &&
    325 		eqPSKIdentityLists(m.pskIdentities, m1.pskIdentities) &&
    326 		bytes.Equal(m.pskKEModes, m1.pskKEModes) &&
    327 		eqByteSlices(m.pskBinders, m1.pskBinders) &&
    328 		m.hasEarlyData == m1.hasEarlyData &&
    329 		bytes.Equal(m.tls13Cookie, m1.tls13Cookie) &&
    330 		m.ticketSupported == m1.ticketSupported &&
    331 		bytes.Equal(m.sessionTicket, m1.sessionTicket) &&
    332 		eqSignatureAlgorithms(m.signatureAlgorithms, m1.signatureAlgorithms) &&
    333 		eqSignatureAlgorithms(m.signatureAlgorithmsCert, m1.signatureAlgorithmsCert) &&
    334 		eqUint16s(m.supportedVersions, m1.supportedVersions) &&
    335 		bytes.Equal(m.secureRenegotiation, m1.secureRenegotiation) &&
    336 		(m.secureRenegotiation == nil) == (m1.secureRenegotiation == nil) &&
    337 		eqStrings(m.alpnProtocols, m1.alpnProtocols) &&
    338 		bytes.Equal(m.quicTransportParams, m1.quicTransportParams) &&
    339 		m.duplicateExtension == m1.duplicateExtension &&
    340 		m.channelIDSupported == m1.channelIDSupported &&
    341 		bytes.Equal(m.tokenBindingParams, m1.tokenBindingParams) &&
    342 		m.tokenBindingVersion == m1.tokenBindingVersion &&
    343 		m.npnAfterAlpn == m1.npnAfterAlpn &&
    344 		m.extendedMasterSecret == m1.extendedMasterSecret &&
    345 		eqUint16s(m.srtpProtectionProfiles, m1.srtpProtectionProfiles) &&
    346 		m.srtpMasterKeyIdentifier == m1.srtpMasterKeyIdentifier &&
    347 		m.sctListSupported == m1.sctListSupported &&
    348 		m.customExtension == m1.customExtension &&
    349 		m.hasGREASEExtension == m1.hasGREASEExtension &&
    350 		m.pskBinderFirst == m1.pskBinderFirst &&
    351 		m.omitExtensions == m1.omitExtensions &&
    352 		m.emptyExtensions == m1.emptyExtensions &&
    353 		m.pad == m1.pad &&
    354 		eqUint16s(m.compressedCertAlgs, m1.compressedCertAlgs) &&
    355 		m.delegatedCredentials == m1.delegatedCredentials
    356 }
    357 
    358 func (m *clientHelloMsg) marshalKeyShares(bb *byteBuilder) {
    359 	keyShares := bb.addU16LengthPrefixed()
    360 	for _, keyShare := range m.keyShares {
    361 		keyShares.addU16(uint16(keyShare.group))
    362 		keyExchange := keyShares.addU16LengthPrefixed()
    363 		keyExchange.addBytes(keyShare.keyExchange)
    364 	}
    365 	if m.trailingKeyShareData {
    366 		keyShares.addU8(0)
    367 	}
    368 }
    369 
    370 func (m *clientHelloMsg) marshal() []byte {
    371 	if m.raw != nil {
    372 		return m.raw
    373 	}
    374 
    375 	handshakeMsg := newByteBuilder()
    376 	handshakeMsg.addU8(typeClientHello)
    377 	hello := handshakeMsg.addU24LengthPrefixed()
    378 	hello.addU16(m.vers)
    379 	hello.addBytes(m.random)
    380 	sessionId := hello.addU8LengthPrefixed()
    381 	sessionId.addBytes(m.sessionId)
    382 	if m.isDTLS {
    383 		cookie := hello.addU8LengthPrefixed()
    384 		cookie.addBytes(m.cookie)
    385 	}
    386 	cipherSuites := hello.addU16LengthPrefixed()
    387 	for _, suite := range m.cipherSuites {
    388 		cipherSuites.addU16(suite)
    389 	}
    390 	compressionMethods := hello.addU8LengthPrefixed()
    391 	compressionMethods.addBytes(m.compressionMethods)
    392 
    393 	extensions := hello.addU16LengthPrefixed()
    394 	if len(m.pskIdentities) > 0 && m.pskBinderFirst {
    395 		extensions.addU16(extensionPreSharedKey)
    396 		pskExtension := extensions.addU16LengthPrefixed()
    397 
    398 		pskIdentities := pskExtension.addU16LengthPrefixed()
    399 		for _, psk := range m.pskIdentities {
    400 			pskIdentities.addU16LengthPrefixed().addBytes(psk.ticket)
    401 			pskIdentities.addU32(psk.obfuscatedTicketAge)
    402 		}
    403 		pskBinders := pskExtension.addU16LengthPrefixed()
    404 		for _, binder := range m.pskBinders {
    405 			pskBinders.addU8LengthPrefixed().addBytes(binder)
    406 		}
    407 	}
    408 	if m.duplicateExtension {
    409 		// Add a duplicate bogus extension at the beginning and end.
    410 		extensions.addU16(0xffff)
    411 		extensions.addU16(0) // 0-length for empty extension
    412 	}
    413 	if m.nextProtoNeg && !m.npnAfterAlpn {
    414 		extensions.addU16(extensionNextProtoNeg)
    415 		extensions.addU16(0) // The length is always 0
    416 	}
    417 	if len(m.serverName) > 0 {
    418 		extensions.addU16(extensionServerName)
    419 		serverNameList := extensions.addU16LengthPrefixed()
    420 
    421 		// RFC 3546, section 3.1
    422 		//
    423 		// struct {
    424 		//     NameType name_type;
    425 		//     select (name_type) {
    426 		//         case host_name: HostName;
    427 		//     } name;
    428 		// } ServerName;
    429 		//
    430 		// enum {
    431 		//     host_name(0), (255)
    432 		// } NameType;
    433 		//
    434 		// opaque HostName<1..2^16-1>;
    435 		//
    436 		// struct {
    437 		//     ServerName server_name_list<1..2^16-1>
    438 		// } ServerNameList;
    439 
    440 		serverName := serverNameList.addU16LengthPrefixed()
    441 		serverName.addU8(0) // NameType host_name(0)
    442 		hostName := serverName.addU16LengthPrefixed()
    443 		hostName.addBytes([]byte(m.serverName))
    444 	}
    445 	if m.ocspStapling {
    446 		extensions.addU16(extensionStatusRequest)
    447 		certificateStatusRequest := extensions.addU16LengthPrefixed()
    448 
    449 		// RFC 4366, section 3.6
    450 		certificateStatusRequest.addU8(1) // OCSP type
    451 		// Two zero valued uint16s for the two lengths.
    452 		certificateStatusRequest.addU16(0) // ResponderID length
    453 		certificateStatusRequest.addU16(0) // Extensions length
    454 	}
    455 	if len(m.supportedCurves) > 0 {
    456 		// http://tools.ietf.org/html/rfc4492#section-5.1.1
    457 		extensions.addU16(extensionSupportedCurves)
    458 		supportedCurvesList := extensions.addU16LengthPrefixed()
    459 		supportedCurves := supportedCurvesList.addU16LengthPrefixed()
    460 		for _, curve := range m.supportedCurves {
    461 			supportedCurves.addU16(uint16(curve))
    462 		}
    463 	}
    464 	if len(m.supportedPoints) > 0 {
    465 		// http://tools.ietf.org/html/rfc4492#section-5.1.2
    466 		extensions.addU16(extensionSupportedPoints)
    467 		supportedPointsList := extensions.addU16LengthPrefixed()
    468 		supportedPoints := supportedPointsList.addU8LengthPrefixed()
    469 		supportedPoints.addBytes(m.supportedPoints)
    470 	}
    471 	if m.hasKeyShares {
    472 		extensions.addU16(extensionKeyShare)
    473 		keyShareList := extensions.addU16LengthPrefixed()
    474 		m.marshalKeyShares(keyShareList)
    475 	}
    476 	if len(m.pskKEModes) > 0 {
    477 		extensions.addU16(extensionPSKKeyExchangeModes)
    478 		pskModesExtension := extensions.addU16LengthPrefixed()
    479 		pskModesExtension.addU8LengthPrefixed().addBytes(m.pskKEModes)
    480 	}
    481 	if m.hasEarlyData {
    482 		extensions.addU16(extensionEarlyData)
    483 		extensions.addU16(0) // The length is zero.
    484 	}
    485 	if len(m.tls13Cookie) > 0 {
    486 		extensions.addU16(extensionCookie)
    487 		body := extensions.addU16LengthPrefixed()
    488 		body.addU16LengthPrefixed().addBytes(m.tls13Cookie)
    489 	}
    490 	if m.ticketSupported {
    491 		// http://tools.ietf.org/html/rfc5077#section-3.2
    492 		extensions.addU16(extensionSessionTicket)
    493 		sessionTicketExtension := extensions.addU16LengthPrefixed()
    494 		sessionTicketExtension.addBytes(m.sessionTicket)
    495 	}
    496 	if len(m.signatureAlgorithms) > 0 {
    497 		// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
    498 		extensions.addU16(extensionSignatureAlgorithms)
    499 		signatureAlgorithmsExtension := extensions.addU16LengthPrefixed()
    500 		signatureAlgorithms := signatureAlgorithmsExtension.addU16LengthPrefixed()
    501 		for _, sigAlg := range m.signatureAlgorithms {
    502 			signatureAlgorithms.addU16(uint16(sigAlg))
    503 		}
    504 	}
    505 	if len(m.signatureAlgorithmsCert) > 0 {
    506 		extensions.addU16(extensionSignatureAlgorithmsCert)
    507 		signatureAlgorithmsCertExtension := extensions.addU16LengthPrefixed()
    508 		signatureAlgorithmsCert := signatureAlgorithmsCertExtension.addU16LengthPrefixed()
    509 		for _, sigAlg := range m.signatureAlgorithmsCert {
    510 			signatureAlgorithmsCert.addU16(uint16(sigAlg))
    511 		}
    512 	}
    513 	if len(m.supportedVersions) > 0 {
    514 		extensions.addU16(extensionSupportedVersions)
    515 		supportedVersionsExtension := extensions.addU16LengthPrefixed()
    516 		supportedVersions := supportedVersionsExtension.addU8LengthPrefixed()
    517 		for _, version := range m.supportedVersions {
    518 			supportedVersions.addU16(uint16(version))
    519 		}
    520 	}
    521 	if m.secureRenegotiation != nil {
    522 		extensions.addU16(extensionRenegotiationInfo)
    523 		secureRenegoExt := extensions.addU16LengthPrefixed()
    524 		secureRenego := secureRenegoExt.addU8LengthPrefixed()
    525 		secureRenego.addBytes(m.secureRenegotiation)
    526 	}
    527 	if len(m.alpnProtocols) > 0 {
    528 		// https://tools.ietf.org/html/rfc7301#section-3.1
    529 		extensions.addU16(extensionALPN)
    530 		alpnExtension := extensions.addU16LengthPrefixed()
    531 
    532 		protocolNameList := alpnExtension.addU16LengthPrefixed()
    533 		for _, s := range m.alpnProtocols {
    534 			protocolName := protocolNameList.addU8LengthPrefixed()
    535 			protocolName.addBytes([]byte(s))
    536 		}
    537 	}
    538 	if len(m.quicTransportParams) > 0 {
    539 		extensions.addU16(extensionQUICTransportParams)
    540 		params := extensions.addU16LengthPrefixed()
    541 		params.addBytes(m.quicTransportParams)
    542 	}
    543 	if m.channelIDSupported {
    544 		extensions.addU16(extensionChannelID)
    545 		extensions.addU16(0) // Length is always 0
    546 	}
    547 	if m.tokenBindingParams != nil {
    548 		extensions.addU16(extensionTokenBinding)
    549 		tokbindExtension := extensions.addU16LengthPrefixed()
    550 		tokbindExtension.addU16(m.tokenBindingVersion)
    551 		tokbindParams := tokbindExtension.addU8LengthPrefixed()
    552 		tokbindParams.addBytes(m.tokenBindingParams)
    553 	}
    554 	if m.nextProtoNeg && m.npnAfterAlpn {
    555 		extensions.addU16(extensionNextProtoNeg)
    556 		extensions.addU16(0) // Length is always 0
    557 	}
    558 	if m.duplicateExtension {
    559 		// Add a duplicate bogus extension at the beginning and end.
    560 		extensions.addU16(0xffff)
    561 		extensions.addU16(0)
    562 	}
    563 	if m.extendedMasterSecret {
    564 		// https://tools.ietf.org/html/rfc7627
    565 		extensions.addU16(extensionExtendedMasterSecret)
    566 		extensions.addU16(0) // Length is always 0
    567 	}
    568 	if len(m.srtpProtectionProfiles) > 0 {
    569 		// https://tools.ietf.org/html/rfc5764#section-4.1.1
    570 		extensions.addU16(extensionUseSRTP)
    571 		useSrtpExt := extensions.addU16LengthPrefixed()
    572 
    573 		srtpProtectionProfiles := useSrtpExt.addU16LengthPrefixed()
    574 		for _, p := range m.srtpProtectionProfiles {
    575 			srtpProtectionProfiles.addU16(p)
    576 		}
    577 		srtpMki := useSrtpExt.addU8LengthPrefixed()
    578 		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
    579 	}
    580 	if m.sctListSupported {
    581 		extensions.addU16(extensionSignedCertificateTimestamp)
    582 		extensions.addU16(0) // Length is always 0
    583 	}
    584 	if l := len(m.customExtension); l > 0 {
    585 		extensions.addU16(extensionCustom)
    586 		customExt := extensions.addU16LengthPrefixed()
    587 		customExt.addBytes([]byte(m.customExtension))
    588 	}
    589 	if len(m.compressedCertAlgs) > 0 {
    590 		extensions.addU16(extensionCompressedCertAlgs)
    591 		body := extensions.addU16LengthPrefixed()
    592 		algIDs := body.addU8LengthPrefixed()
    593 		for _, v := range m.compressedCertAlgs {
    594 			algIDs.addU16(v)
    595 		}
    596 	}
    597 	if m.delegatedCredentials {
    598 		extensions.addU16(extensionDelegatedCredentials)
    599 		extensions.addU16(0) // Length is always 0
    600 	}
    601 	// The PSK extension must be last. See https://tools.ietf.org/html/rfc8446#section-4.2.11
    602 	if len(m.pskIdentities) > 0 && !m.pskBinderFirst {
    603 		extensions.addU16(extensionPreSharedKey)
    604 		pskExtension := extensions.addU16LengthPrefixed()
    605 
    606 		pskIdentities := pskExtension.addU16LengthPrefixed()
    607 		for _, psk := range m.pskIdentities {
    608 			pskIdentities.addU16LengthPrefixed().addBytes(psk.ticket)
    609 			pskIdentities.addU32(psk.obfuscatedTicketAge)
    610 		}
    611 		pskBinders := pskExtension.addU16LengthPrefixed()
    612 		for _, binder := range m.pskBinders {
    613 			pskBinders.addU8LengthPrefixed().addBytes(binder)
    614 		}
    615 	}
    616 
    617 	if m.pad != 0 && hello.len()%m.pad != 0 {
    618 		extensions.addU16(extensionPadding)
    619 		padding := extensions.addU16LengthPrefixed()
    620 		// Note hello.len() has changed at this point from the length
    621 		// prefix.
    622 		if l := hello.len() % m.pad; l != 0 {
    623 			padding.addBytes(make([]byte, m.pad-l))
    624 		}
    625 	}
    626 
    627 	if m.omitExtensions || m.emptyExtensions {
    628 		// Silently erase any extensions which were sent.
    629 		hello.discardChild()
    630 		if m.emptyExtensions {
    631 			hello.addU16(0)
    632 		}
    633 	}
    634 
    635 	m.raw = handshakeMsg.finish()
    636 	// Sanity-check padding.
    637 	if m.pad != 0 && (len(m.raw)-4)%m.pad != 0 {
    638 		panic(fmt.Sprintf("%d is not a multiple of %d", len(m.raw)-4, m.pad))
    639 	}
    640 	return m.raw
    641 }
    642 
    643 func parseSignatureAlgorithms(reader *byteReader, out *[]signatureAlgorithm, allowEmpty bool) bool {
    644 	var sigAlgs byteReader
    645 	if !reader.readU16LengthPrefixed(&sigAlgs) {
    646 		return false
    647 	}
    648 	if !allowEmpty && len(sigAlgs) == 0 {
    649 		return false
    650 	}
    651 	*out = make([]signatureAlgorithm, 0, len(sigAlgs)/2)
    652 	for len(sigAlgs) > 0 {
    653 		var v uint16
    654 		if !sigAlgs.readU16(&v) {
    655 			return false
    656 		}
    657 		*out = append(*out, signatureAlgorithm(v))
    658 	}
    659 	return true
    660 }
    661 
    662 func checkDuplicateExtensions(extensions byteReader) bool {
    663 	seen := make(map[uint16]struct{})
    664 	for len(extensions) > 0 {
    665 		var extension uint16
    666 		var body byteReader
    667 		if !extensions.readU16(&extension) ||
    668 			!extensions.readU16LengthPrefixed(&body) {
    669 			return false
    670 		}
    671 		if _, ok := seen[extension]; ok {
    672 			return false
    673 		}
    674 		seen[extension] = struct{}{}
    675 	}
    676 	return true
    677 }
    678 
    679 func (m *clientHelloMsg) unmarshal(data []byte) bool {
    680 	m.raw = data
    681 	reader := byteReader(data[4:])
    682 	if !reader.readU16(&m.vers) ||
    683 		!reader.readBytes(&m.random, 32) ||
    684 		!reader.readU8LengthPrefixedBytes(&m.sessionId) ||
    685 		len(m.sessionId) > 32 {
    686 		return false
    687 	}
    688 	if m.isDTLS {
    689 		if !reader.readU8LengthPrefixedBytes(&m.cookie) ||
    690 			len(m.cookie) > 32 {
    691 			return false
    692 		}
    693 	}
    694 	var cipherSuites byteReader
    695 	if !reader.readU16LengthPrefixed(&cipherSuites) ||
    696 		!reader.readU8LengthPrefixedBytes(&m.compressionMethods) {
    697 		return false
    698 	}
    699 
    700 	m.cipherSuites = make([]uint16, 0, len(cipherSuites)/2)
    701 	for len(cipherSuites) > 0 {
    702 		var v uint16
    703 		if !cipherSuites.readU16(&v) {
    704 			return false
    705 		}
    706 		m.cipherSuites = append(m.cipherSuites, v)
    707 		if v == scsvRenegotiation {
    708 			m.secureRenegotiation = []byte{}
    709 		}
    710 	}
    711 
    712 	m.nextProtoNeg = false
    713 	m.serverName = ""
    714 	m.ocspStapling = false
    715 	m.keyShares = nil
    716 	m.pskIdentities = nil
    717 	m.hasEarlyData = false
    718 	m.ticketSupported = false
    719 	m.sessionTicket = nil
    720 	m.signatureAlgorithms = nil
    721 	m.signatureAlgorithmsCert = nil
    722 	m.supportedVersions = nil
    723 	m.alpnProtocols = nil
    724 	m.extendedMasterSecret = false
    725 	m.customExtension = ""
    726 	m.delegatedCredentials = false
    727 
    728 	if len(reader) == 0 {
    729 		// ClientHello is optionally followed by extension data
    730 		return true
    731 	}
    732 
    733 	var extensions byteReader
    734 	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 || !checkDuplicateExtensions(extensions) {
    735 		return false
    736 	}
    737 	for len(extensions) > 0 {
    738 		var extension uint16
    739 		var body byteReader
    740 		if !extensions.readU16(&extension) ||
    741 			!extensions.readU16LengthPrefixed(&body) {
    742 			return false
    743 		}
    744 		switch extension {
    745 		case extensionServerName:
    746 			var names byteReader
    747 			if !body.readU16LengthPrefixed(&names) || len(body) != 0 {
    748 				return false
    749 			}
    750 			for len(names) > 0 {
    751 				var nameType byte
    752 				var name []byte
    753 				if !names.readU8(&nameType) ||
    754 					!names.readU16LengthPrefixedBytes(&name) {
    755 					return false
    756 				}
    757 				if nameType == 0 {
    758 					m.serverName = string(name)
    759 				}
    760 			}
    761 		case extensionNextProtoNeg:
    762 			if len(body) != 0 {
    763 				return false
    764 			}
    765 			m.nextProtoNeg = true
    766 		case extensionStatusRequest:
    767 			m.ocspStapling = len(body) > 0 && body[0] == statusTypeOCSP
    768 		case extensionSupportedCurves:
    769 			// http://tools.ietf.org/html/rfc4492#section-5.5.1
    770 			var curves byteReader
    771 			if !body.readU16LengthPrefixed(&curves) || len(body) != 0 {
    772 				return false
    773 			}
    774 			m.supportedCurves = make([]CurveID, 0, len(curves)/2)
    775 			for len(curves) > 0 {
    776 				var v uint16
    777 				if !curves.readU16(&v) {
    778 					return false
    779 				}
    780 				m.supportedCurves = append(m.supportedCurves, CurveID(v))
    781 			}
    782 		case extensionSupportedPoints:
    783 			// http://tools.ietf.org/html/rfc4492#section-5.5.2
    784 			if !body.readU8LengthPrefixedBytes(&m.supportedPoints) || len(body) != 0 {
    785 				return false
    786 			}
    787 		case extensionSessionTicket:
    788 			// http://tools.ietf.org/html/rfc5077#section-3.2
    789 			m.ticketSupported = true
    790 			m.sessionTicket = []byte(body)
    791 		case extensionKeyShare:
    792 			// https://tools.ietf.org/html/rfc8446#section-4.2.8
    793 			m.hasKeyShares = true
    794 			m.keySharesRaw = body
    795 			var keyShares byteReader
    796 			if !body.readU16LengthPrefixed(&keyShares) || len(body) != 0 {
    797 				return false
    798 			}
    799 			for len(keyShares) > 0 {
    800 				var entry keyShareEntry
    801 				var group uint16
    802 				if !keyShares.readU16(&group) ||
    803 					!keyShares.readU16LengthPrefixedBytes(&entry.keyExchange) {
    804 					return false
    805 				}
    806 				entry.group = CurveID(group)
    807 				m.keyShares = append(m.keyShares, entry)
    808 			}
    809 		case extensionPreSharedKey:
    810 			// https://tools.ietf.org/html/rfc8446#section-4.2.11
    811 			var psks, binders byteReader
    812 			if !body.readU16LengthPrefixed(&psks) ||
    813 				!body.readU16LengthPrefixed(&binders) ||
    814 				len(body) != 0 {
    815 				return false
    816 			}
    817 			for len(psks) > 0 {
    818 				var psk pskIdentity
    819 				if !psks.readU16LengthPrefixedBytes(&psk.ticket) ||
    820 					!psks.readU32(&psk.obfuscatedTicketAge) {
    821 					return false
    822 				}
    823 				m.pskIdentities = append(m.pskIdentities, psk)
    824 			}
    825 			for len(binders) > 0 {
    826 				var binder []byte
    827 				if !binders.readU8LengthPrefixedBytes(&binder) {
    828 					return false
    829 				}
    830 				m.pskBinders = append(m.pskBinders, binder)
    831 			}
    832 
    833 			// There must be the same number of identities as binders.
    834 			if len(m.pskIdentities) != len(m.pskBinders) {
    835 				return false
    836 			}
    837 		case extensionPSKKeyExchangeModes:
    838 			// https://tools.ietf.org/html/rfc8446#section-4.2.9
    839 			if !body.readU8LengthPrefixedBytes(&m.pskKEModes) || len(body) != 0 {
    840 				return false
    841 			}
    842 		case extensionEarlyData:
    843 			// https://tools.ietf.org/html/rfc8446#section-4.2.10
    844 			if len(body) != 0 {
    845 				return false
    846 			}
    847 			m.hasEarlyData = true
    848 		case extensionCookie:
    849 			if !body.readU16LengthPrefixedBytes(&m.tls13Cookie) || len(body) != 0 {
    850 				return false
    851 			}
    852 		case extensionSignatureAlgorithms:
    853 			// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
    854 			if !parseSignatureAlgorithms(&body, &m.signatureAlgorithms, false) || len(body) != 0 {
    855 				return false
    856 			}
    857 		case extensionSignatureAlgorithmsCert:
    858 			if !parseSignatureAlgorithms(&body, &m.signatureAlgorithmsCert, false) || len(body) != 0 {
    859 				return false
    860 			}
    861 		case extensionSupportedVersions:
    862 			var versions byteReader
    863 			if !body.readU8LengthPrefixed(&versions) || len(body) != 0 {
    864 				return false
    865 			}
    866 			m.supportedVersions = make([]uint16, 0, len(versions)/2)
    867 			for len(versions) > 0 {
    868 				var v uint16
    869 				if !versions.readU16(&v) {
    870 					return false
    871 				}
    872 				m.supportedVersions = append(m.supportedVersions, v)
    873 			}
    874 		case extensionRenegotiationInfo:
    875 			if !body.readU8LengthPrefixedBytes(&m.secureRenegotiation) || len(body) != 0 {
    876 				return false
    877 			}
    878 		case extensionALPN:
    879 			var protocols byteReader
    880 			if !body.readU16LengthPrefixed(&protocols) || len(body) != 0 {
    881 				return false
    882 			}
    883 			for len(protocols) > 0 {
    884 				var protocol []byte
    885 				if !protocols.readU8LengthPrefixedBytes(&protocol) {
    886 					return false
    887 				}
    888 				m.alpnProtocols = append(m.alpnProtocols, string(protocol))
    889 			}
    890 		case extensionQUICTransportParams:
    891 			m.quicTransportParams = body
    892 		case extensionChannelID:
    893 			if len(body) != 0 {
    894 				return false
    895 			}
    896 			m.channelIDSupported = true
    897 		case extensionTokenBinding:
    898 			if !body.readU16(&m.tokenBindingVersion) ||
    899 				!body.readU8LengthPrefixedBytes(&m.tokenBindingParams) ||
    900 				len(body) != 0 {
    901 				return false
    902 			}
    903 		case extensionExtendedMasterSecret:
    904 			if len(body) != 0 {
    905 				return false
    906 			}
    907 			m.extendedMasterSecret = true
    908 		case extensionUseSRTP:
    909 			var profiles byteReader
    910 			var mki []byte
    911 			if !body.readU16LengthPrefixed(&profiles) ||
    912 				!body.readU8LengthPrefixedBytes(&mki) ||
    913 				len(body) != 0 {
    914 				return false
    915 			}
    916 			m.srtpProtectionProfiles = make([]uint16, 0, len(profiles)/2)
    917 			for len(profiles) > 0 {
    918 				var v uint16
    919 				if !profiles.readU16(&v) {
    920 					return false
    921 				}
    922 				m.srtpProtectionProfiles = append(m.srtpProtectionProfiles, v)
    923 			}
    924 			m.srtpMasterKeyIdentifier = string(mki)
    925 		case extensionSignedCertificateTimestamp:
    926 			if len(body) != 0 {
    927 				return false
    928 			}
    929 			m.sctListSupported = true
    930 		case extensionCustom:
    931 			m.customExtension = string(body)
    932 		case extensionCompressedCertAlgs:
    933 			var algIDs byteReader
    934 			if !body.readU8LengthPrefixed(&algIDs) {
    935 				return false
    936 			}
    937 
    938 			seen := make(map[uint16]struct{})
    939 			for len(algIDs) > 0 {
    940 				var algID uint16
    941 				if !algIDs.readU16(&algID) {
    942 					return false
    943 				}
    944 				if _, ok := seen[algID]; ok {
    945 					return false
    946 				}
    947 				seen[algID] = struct{}{}
    948 				m.compressedCertAlgs = append(m.compressedCertAlgs, algID)
    949 			}
    950 		case extensionPadding:
    951 			// Padding bytes must be all zero.
    952 			for _, b := range body {
    953 				if b != 0 {
    954 					return false
    955 				}
    956 			}
    957 		case extensionDelegatedCredentials:
    958 			if len(body) != 0 {
    959 				return false
    960 			}
    961 			m.delegatedCredentials = true
    962 		}
    963 
    964 		if isGREASEValue(extension) {
    965 			m.hasGREASEExtension = true
    966 		}
    967 	}
    968 
    969 	return true
    970 }
    971 
    972 type serverHelloMsg struct {
    973 	raw                   []byte
    974 	isDTLS                bool
    975 	vers                  uint16
    976 	versOverride          uint16
    977 	supportedVersOverride uint16
    978 	omitSupportedVers     bool
    979 	random                []byte
    980 	sessionId             []byte
    981 	cipherSuite           uint16
    982 	hasKeyShare           bool
    983 	keyShare              keyShareEntry
    984 	hasPSKIdentity        bool
    985 	pskIdentity           uint16
    986 	compressionMethod     uint8
    987 	customExtension       string
    988 	unencryptedALPN       string
    989 	omitExtensions        bool
    990 	emptyExtensions       bool
    991 	extensions            serverExtensions
    992 }
    993 
    994 func (m *serverHelloMsg) marshal() []byte {
    995 	if m.raw != nil {
    996 		return m.raw
    997 	}
    998 
    999 	handshakeMsg := newByteBuilder()
   1000 	handshakeMsg.addU8(typeServerHello)
   1001 	hello := handshakeMsg.addU24LengthPrefixed()
   1002 
   1003 	// m.vers is used both to determine the format of the rest of the
   1004 	// ServerHello and to override the value, so include a second version
   1005 	// field.
   1006 	vers, ok := wireToVersion(m.vers, m.isDTLS)
   1007 	if !ok {
   1008 		panic("unknown version")
   1009 	}
   1010 	if m.versOverride != 0 {
   1011 		hello.addU16(m.versOverride)
   1012 	} else if vers >= VersionTLS13 {
   1013 		hello.addU16(VersionTLS12)
   1014 	} else {
   1015 		hello.addU16(m.vers)
   1016 	}
   1017 
   1018 	hello.addBytes(m.random)
   1019 	sessionId := hello.addU8LengthPrefixed()
   1020 	sessionId.addBytes(m.sessionId)
   1021 	hello.addU16(m.cipherSuite)
   1022 	hello.addU8(m.compressionMethod)
   1023 
   1024 	extensions := hello.addU16LengthPrefixed()
   1025 
   1026 	if vers >= VersionTLS13 {
   1027 		if m.hasKeyShare {
   1028 			extensions.addU16(extensionKeyShare)
   1029 			keyShare := extensions.addU16LengthPrefixed()
   1030 			keyShare.addU16(uint16(m.keyShare.group))
   1031 			keyExchange := keyShare.addU16LengthPrefixed()
   1032 			keyExchange.addBytes(m.keyShare.keyExchange)
   1033 		}
   1034 		if m.hasPSKIdentity {
   1035 			extensions.addU16(extensionPreSharedKey)
   1036 			extensions.addU16(2) // Length
   1037 			extensions.addU16(m.pskIdentity)
   1038 		}
   1039 		if !m.omitSupportedVers {
   1040 			extensions.addU16(extensionSupportedVersions)
   1041 			extensions.addU16(2) // Length
   1042 			if m.supportedVersOverride != 0 {
   1043 				extensions.addU16(m.supportedVersOverride)
   1044 			} else {
   1045 				extensions.addU16(m.vers)
   1046 			}
   1047 		}
   1048 		if len(m.customExtension) > 0 {
   1049 			extensions.addU16(extensionCustom)
   1050 			customExt := extensions.addU16LengthPrefixed()
   1051 			customExt.addBytes([]byte(m.customExtension))
   1052 		}
   1053 		if len(m.unencryptedALPN) > 0 {
   1054 			extensions.addU16(extensionALPN)
   1055 			extension := extensions.addU16LengthPrefixed()
   1056 
   1057 			protocolNameList := extension.addU16LengthPrefixed()
   1058 			protocolName := protocolNameList.addU8LengthPrefixed()
   1059 			protocolName.addBytes([]byte(m.unencryptedALPN))
   1060 		}
   1061 	} else {
   1062 		m.extensions.marshal(extensions)
   1063 		if m.omitExtensions || m.emptyExtensions {
   1064 			// Silently erasing server extensions will break the handshake. Instead,
   1065 			// assert that tests which use this field also disable all features which
   1066 			// would write an extension.
   1067 			if extensions.len() != 0 {
   1068 				panic(fmt.Sprintf("ServerHello unexpectedly contained extensions: %x, %+v", extensions.data(), m))
   1069 			}
   1070 			hello.discardChild()
   1071 			if m.emptyExtensions {
   1072 				hello.addU16(0)
   1073 			}
   1074 		}
   1075 	}
   1076 
   1077 	m.raw = handshakeMsg.finish()
   1078 	return m.raw
   1079 }
   1080 
   1081 func (m *serverHelloMsg) unmarshal(data []byte) bool {
   1082 	m.raw = data
   1083 	reader := byteReader(data[4:])
   1084 	if !reader.readU16(&m.vers) ||
   1085 		!reader.readBytes(&m.random, 32) {
   1086 		return false
   1087 	}
   1088 	vers, ok := wireToVersion(m.vers, m.isDTLS)
   1089 	if !ok {
   1090 		return false
   1091 	}
   1092 	if !reader.readU8LengthPrefixedBytes(&m.sessionId) ||
   1093 		!reader.readU16(&m.cipherSuite) ||
   1094 		!reader.readU8(&m.compressionMethod) {
   1095 		return false
   1096 	}
   1097 
   1098 	if len(reader) == 0 && m.vers < VersionTLS13 {
   1099 		// Extension data is optional before TLS 1.3.
   1100 		m.extensions = serverExtensions{}
   1101 		m.omitExtensions = true
   1102 		return true
   1103 	}
   1104 
   1105 	var extensions byteReader
   1106 	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 || !checkDuplicateExtensions(extensions) {
   1107 		return false
   1108 	}
   1109 
   1110 	// Parse out the version from supported_versions if available.
   1111 	if m.vers == VersionTLS12 {
   1112 		extensionsCopy := extensions
   1113 		for len(extensionsCopy) > 0 {
   1114 			var extension uint16
   1115 			var body byteReader
   1116 			if !extensionsCopy.readU16(&extension) ||
   1117 				!extensionsCopy.readU16LengthPrefixed(&body) {
   1118 				return false
   1119 			}
   1120 			if extension == extensionSupportedVersions {
   1121 				if !body.readU16(&m.vers) || len(body) != 0 {
   1122 					return false
   1123 				}
   1124 				vers, ok = wireToVersion(m.vers, m.isDTLS)
   1125 				if !ok {
   1126 					return false
   1127 				}
   1128 			}
   1129 		}
   1130 	}
   1131 
   1132 	if vers >= VersionTLS13 {
   1133 		for len(extensions) > 0 {
   1134 			var extension uint16
   1135 			var body byteReader
   1136 			if !extensions.readU16(&extension) ||
   1137 				!extensions.readU16LengthPrefixed(&body) {
   1138 				return false
   1139 			}
   1140 			switch extension {
   1141 			case extensionKeyShare:
   1142 				m.hasKeyShare = true
   1143 				var group uint16
   1144 				if !body.readU16(&group) ||
   1145 					!body.readU16LengthPrefixedBytes(&m.keyShare.keyExchange) ||
   1146 					len(body) != 0 {
   1147 					return false
   1148 				}
   1149 				m.keyShare.group = CurveID(group)
   1150 			case extensionPreSharedKey:
   1151 				if !body.readU16(&m.pskIdentity) || len(body) != 0 {
   1152 					return false
   1153 				}
   1154 				m.hasPSKIdentity = true
   1155 			case extensionSupportedVersions:
   1156 				// Parsed above.
   1157 			default:
   1158 				// Only allow the 3 extensions that are sent in
   1159 				// the clear in TLS 1.3.
   1160 				return false
   1161 			}
   1162 		}
   1163 	} else if !m.extensions.unmarshal(extensions, vers) {
   1164 		return false
   1165 	}
   1166 
   1167 	return true
   1168 }
   1169 
   1170 type encryptedExtensionsMsg struct {
   1171 	raw        []byte
   1172 	extensions serverExtensions
   1173 	empty      bool
   1174 }
   1175 
   1176 func (m *encryptedExtensionsMsg) marshal() []byte {
   1177 	if m.raw != nil {
   1178 		return m.raw
   1179 	}
   1180 
   1181 	encryptedExtensionsMsg := newByteBuilder()
   1182 	encryptedExtensionsMsg.addU8(typeEncryptedExtensions)
   1183 	encryptedExtensions := encryptedExtensionsMsg.addU24LengthPrefixed()
   1184 	if !m.empty {
   1185 		extensions := encryptedExtensions.addU16LengthPrefixed()
   1186 		m.extensions.marshal(extensions)
   1187 	}
   1188 
   1189 	m.raw = encryptedExtensionsMsg.finish()
   1190 	return m.raw
   1191 }
   1192 
   1193 func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool {
   1194 	m.raw = data
   1195 	reader := byteReader(data[4:])
   1196 	var extensions byteReader
   1197 	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 {
   1198 		return false
   1199 	}
   1200 	return m.extensions.unmarshal(extensions, VersionTLS13)
   1201 }
   1202 
   1203 type serverExtensions struct {
   1204 	nextProtoNeg            bool
   1205 	nextProtos              []string
   1206 	ocspStapling            bool
   1207 	ticketSupported         bool
   1208 	secureRenegotiation     []byte
   1209 	alpnProtocol            string
   1210 	alpnProtocolEmpty       bool
   1211 	duplicateExtension      bool
   1212 	channelIDRequested      bool
   1213 	tokenBindingParams      []byte
   1214 	tokenBindingVersion     uint16
   1215 	extendedMasterSecret    bool
   1216 	srtpProtectionProfile   uint16
   1217 	srtpMasterKeyIdentifier string
   1218 	sctList                 []byte
   1219 	customExtension         string
   1220 	npnAfterAlpn            bool
   1221 	hasKeyShare             bool
   1222 	hasEarlyData            bool
   1223 	keyShare                keyShareEntry
   1224 	supportedVersion        uint16
   1225 	supportedPoints         []uint8
   1226 	supportedCurves         []CurveID
   1227 	quicTransportParams     []byte
   1228 	serverNameAck           bool
   1229 }
   1230 
   1231 func (m *serverExtensions) marshal(extensions *byteBuilder) {
   1232 	if m.duplicateExtension {
   1233 		// Add a duplicate bogus extension at the beginning and end.
   1234 		extensions.addU16(0xffff)
   1235 		extensions.addU16(0) // length = 0 for empty extension
   1236 	}
   1237 	if m.nextProtoNeg && !m.npnAfterAlpn {
   1238 		extensions.addU16(extensionNextProtoNeg)
   1239 		extension := extensions.addU16LengthPrefixed()
   1240 
   1241 		for _, v := range m.nextProtos {
   1242 			if len(v) > 255 {
   1243 				v = v[:255]
   1244 			}
   1245 			npn := extension.addU8LengthPrefixed()
   1246 			npn.addBytes([]byte(v))
   1247 		}
   1248 	}
   1249 	if m.ocspStapling {
   1250 		extensions.addU16(extensionStatusRequest)
   1251 		extensions.addU16(0)
   1252 	}
   1253 	if m.ticketSupported {
   1254 		extensions.addU16(extensionSessionTicket)
   1255 		extensions.addU16(0)
   1256 	}
   1257 	if m.secureRenegotiation != nil {
   1258 		extensions.addU16(extensionRenegotiationInfo)
   1259 		extension := extensions.addU16LengthPrefixed()
   1260 		secureRenego := extension.addU8LengthPrefixed()
   1261 		secureRenego.addBytes(m.secureRenegotiation)
   1262 	}
   1263 	if len(m.alpnProtocol) > 0 || m.alpnProtocolEmpty {
   1264 		extensions.addU16(extensionALPN)
   1265 		extension := extensions.addU16LengthPrefixed()
   1266 
   1267 		protocolNameList := extension.addU16LengthPrefixed()
   1268 		protocolName := protocolNameList.addU8LengthPrefixed()
   1269 		protocolName.addBytes([]byte(m.alpnProtocol))
   1270 	}
   1271 	if m.channelIDRequested {
   1272 		extensions.addU16(extensionChannelID)
   1273 		extensions.addU16(0)
   1274 	}
   1275 	if m.tokenBindingParams != nil {
   1276 		extensions.addU16(extensionTokenBinding)
   1277 		tokbindExtension := extensions.addU16LengthPrefixed()
   1278 		tokbindExtension.addU16(m.tokenBindingVersion)
   1279 		tokbindParams := tokbindExtension.addU8LengthPrefixed()
   1280 		tokbindParams.addBytes(m.tokenBindingParams)
   1281 	}
   1282 	if m.duplicateExtension {
   1283 		// Add a duplicate bogus extension at the beginning and end.
   1284 		extensions.addU16(0xffff)
   1285 		extensions.addU16(0)
   1286 	}
   1287 	if m.extendedMasterSecret {
   1288 		extensions.addU16(extensionExtendedMasterSecret)
   1289 		extensions.addU16(0)
   1290 	}
   1291 	if m.srtpProtectionProfile != 0 {
   1292 		extensions.addU16(extensionUseSRTP)
   1293 		extension := extensions.addU16LengthPrefixed()
   1294 
   1295 		srtpProtectionProfiles := extension.addU16LengthPrefixed()
   1296 		srtpProtectionProfiles.addU16(m.srtpProtectionProfile)
   1297 		srtpMki := extension.addU8LengthPrefixed()
   1298 		srtpMki.addBytes([]byte(m.srtpMasterKeyIdentifier))
   1299 	}
   1300 	if m.sctList != nil {
   1301 		extensions.addU16(extensionSignedCertificateTimestamp)
   1302 		extension := extensions.addU16LengthPrefixed()
   1303 		extension.addBytes(m.sctList)
   1304 	}
   1305 	if l := len(m.customExtension); l > 0 {
   1306 		extensions.addU16(extensionCustom)
   1307 		customExt := extensions.addU16LengthPrefixed()
   1308 		customExt.addBytes([]byte(m.customExtension))
   1309 	}
   1310 	if m.nextProtoNeg && m.npnAfterAlpn {
   1311 		extensions.addU16(extensionNextProtoNeg)
   1312 		extension := extensions.addU16LengthPrefixed()
   1313 
   1314 		for _, v := range m.nextProtos {
   1315 			if len(v) > 255 {
   1316 				v = v[0:255]
   1317 			}
   1318 			npn := extension.addU8LengthPrefixed()
   1319 			npn.addBytes([]byte(v))
   1320 		}
   1321 	}
   1322 	if m.hasKeyShare {
   1323 		extensions.addU16(extensionKeyShare)
   1324 		keyShare := extensions.addU16LengthPrefixed()
   1325 		keyShare.addU16(uint16(m.keyShare.group))
   1326 		keyExchange := keyShare.addU16LengthPrefixed()
   1327 		keyExchange.addBytes(m.keyShare.keyExchange)
   1328 	}
   1329 	if m.supportedVersion != 0 {
   1330 		extensions.addU16(extensionSupportedVersions)
   1331 		extensions.addU16(2) // Length
   1332 		extensions.addU16(m.supportedVersion)
   1333 	}
   1334 	if len(m.supportedPoints) > 0 {
   1335 		// http://tools.ietf.org/html/rfc4492#section-5.1.2
   1336 		extensions.addU16(extensionSupportedPoints)
   1337 		supportedPointsList := extensions.addU16LengthPrefixed()
   1338 		supportedPoints := supportedPointsList.addU8LengthPrefixed()
   1339 		supportedPoints.addBytes(m.supportedPoints)
   1340 	}
   1341 	if len(m.supportedCurves) > 0 {
   1342 		// https://tools.ietf.org/html/rfc8446#section-4.2.7
   1343 		extensions.addU16(extensionSupportedCurves)
   1344 		supportedCurvesList := extensions.addU16LengthPrefixed()
   1345 		supportedCurves := supportedCurvesList.addU16LengthPrefixed()
   1346 		for _, curve := range m.supportedCurves {
   1347 			supportedCurves.addU16(uint16(curve))
   1348 		}
   1349 	}
   1350 	if len(m.quicTransportParams) > 0 {
   1351 		extensions.addU16(extensionQUICTransportParams)
   1352 		params := extensions.addU16LengthPrefixed()
   1353 		params.addBytes(m.quicTransportParams)
   1354 	}
   1355 	if m.hasEarlyData {
   1356 		extensions.addU16(extensionEarlyData)
   1357 		extensions.addBytes([]byte{0, 0})
   1358 	}
   1359 	if m.serverNameAck {
   1360 		extensions.addU16(extensionServerName)
   1361 		extensions.addU16(0) // zero length
   1362 	}
   1363 }
   1364 
   1365 func (m *serverExtensions) unmarshal(data byteReader, version uint16) bool {
   1366 	// Reset all fields.
   1367 	*m = serverExtensions{}
   1368 
   1369 	if !checkDuplicateExtensions(data) {
   1370 		return false
   1371 	}
   1372 
   1373 	for len(data) > 0 {
   1374 		var extension uint16
   1375 		var body byteReader
   1376 		if !data.readU16(&extension) ||
   1377 			!data.readU16LengthPrefixed(&body) {
   1378 			return false
   1379 		}
   1380 		switch extension {
   1381 		case extensionNextProtoNeg:
   1382 			m.nextProtoNeg = true
   1383 			for len(body) > 0 {
   1384 				var protocol []byte
   1385 				if !body.readU8LengthPrefixedBytes(&protocol) {
   1386 					return false
   1387 				}
   1388 				m.nextProtos = append(m.nextProtos, string(protocol))
   1389 			}
   1390 		case extensionStatusRequest:
   1391 			if len(body) != 0 {
   1392 				return false
   1393 			}
   1394 			m.ocspStapling = true
   1395 		case extensionSessionTicket:
   1396 			if len(body) != 0 {
   1397 				return false
   1398 			}
   1399 			m.ticketSupported = true
   1400 		case extensionRenegotiationInfo:
   1401 			if !body.readU8LengthPrefixedBytes(&m.secureRenegotiation) || len(body) != 0 {
   1402 				return false
   1403 			}
   1404 		case extensionALPN:
   1405 			var protocols, protocol byteReader
   1406 			if !body.readU16LengthPrefixed(&protocols) ||
   1407 				len(body) != 0 ||
   1408 				!protocols.readU8LengthPrefixed(&protocol) ||
   1409 				len(protocols) != 0 {
   1410 				return false
   1411 			}
   1412 			m.alpnProtocol = string(protocol)
   1413 			m.alpnProtocolEmpty = len(protocol) == 0
   1414 		case extensionChannelID:
   1415 			if len(body) != 0 {
   1416 				return false
   1417 			}
   1418 			m.channelIDRequested = true
   1419 		case extensionTokenBinding:
   1420 			if !body.readU16(&m.tokenBindingVersion) ||
   1421 				!body.readU8LengthPrefixedBytes(&m.tokenBindingParams) ||
   1422 				len(m.tokenBindingParams) != 1 ||
   1423 				len(body) != 0 {
   1424 				return false
   1425 			}
   1426 		case extensionExtendedMasterSecret:
   1427 			if len(body) != 0 {
   1428 				return false
   1429 			}
   1430 			m.extendedMasterSecret = true
   1431 		case extensionUseSRTP:
   1432 			var profiles, mki byteReader
   1433 			if !body.readU16LengthPrefixed(&profiles) ||
   1434 				!profiles.readU16(&m.srtpProtectionProfile) ||
   1435 				len(profiles) != 0 ||
   1436 				!body.readU8LengthPrefixed(&mki) ||
   1437 				len(body) != 0 {
   1438 				return false
   1439 			}
   1440 			m.srtpMasterKeyIdentifier = string(mki)
   1441 		case extensionSignedCertificateTimestamp:
   1442 			m.sctList = []byte(body)
   1443 		case extensionCustom:
   1444 			m.customExtension = string(body)
   1445 		case extensionServerName:
   1446 			if len(body) != 0 {
   1447 				return false
   1448 			}
   1449 			m.serverNameAck = true
   1450 		case extensionSupportedPoints:
   1451 			// supported_points is illegal in TLS 1.3.
   1452 			if version >= VersionTLS13 {
   1453 				return false
   1454 			}
   1455 			// http://tools.ietf.org/html/rfc4492#section-5.5.2
   1456 			if !body.readU8LengthPrefixedBytes(&m.supportedPoints) || len(body) != 0 {
   1457 				return false
   1458 			}
   1459 		case extensionSupportedCurves:
   1460 			// The server can only send supported_curves in TLS 1.3.
   1461 			if version < VersionTLS13 {
   1462 				return false
   1463 			}
   1464 		case extensionQUICTransportParams:
   1465 			m.quicTransportParams = body
   1466 		case extensionEarlyData:
   1467 			if version < VersionTLS13 || len(body) != 0 {
   1468 				return false
   1469 			}
   1470 			m.hasEarlyData = true
   1471 		default:
   1472 			// Unknown extensions are illegal from the server.
   1473 			return false
   1474 		}
   1475 	}
   1476 
   1477 	return true
   1478 }
   1479 
   1480 type helloRetryRequestMsg struct {
   1481 	raw                 []byte
   1482 	vers                uint16
   1483 	isServerHello       bool
   1484 	sessionId           []byte
   1485 	cipherSuite         uint16
   1486 	compressionMethod   uint8
   1487 	hasSelectedGroup    bool
   1488 	selectedGroup       CurveID
   1489 	cookie              []byte
   1490 	customExtension     string
   1491 	duplicateExtensions bool
   1492 }
   1493 
   1494 func (m *helloRetryRequestMsg) marshal() []byte {
   1495 	if m.raw != nil {
   1496 		return m.raw
   1497 	}
   1498 
   1499 	retryRequestMsg := newByteBuilder()
   1500 	retryRequestMsg.addU8(typeServerHello)
   1501 	retryRequest := retryRequestMsg.addU24LengthPrefixed()
   1502 	retryRequest.addU16(VersionTLS12)
   1503 	retryRequest.addBytes(tls13HelloRetryRequest)
   1504 	sessionId := retryRequest.addU8LengthPrefixed()
   1505 	sessionId.addBytes(m.sessionId)
   1506 	retryRequest.addU16(m.cipherSuite)
   1507 	retryRequest.addU8(m.compressionMethod)
   1508 
   1509 	extensions := retryRequest.addU16LengthPrefixed()
   1510 
   1511 	count := 1
   1512 	if m.duplicateExtensions {
   1513 		count = 2
   1514 	}
   1515 
   1516 	for i := 0; i < count; i++ {
   1517 		extensions.addU16(extensionSupportedVersions)
   1518 		extensions.addU16(2) // Length
   1519 		extensions.addU16(m.vers)
   1520 		if m.hasSelectedGroup {
   1521 			extensions.addU16(extensionKeyShare)
   1522 			extensions.addU16(2) // length
   1523 			extensions.addU16(uint16(m.selectedGroup))
   1524 		}
   1525 		// m.cookie may be a non-nil empty slice for empty cookie tests.
   1526 		if m.cookie != nil {
   1527 			extensions.addU16(extensionCookie)
   1528 			body := extensions.addU16LengthPrefixed()
   1529 			body.addU16LengthPrefixed().addBytes(m.cookie)
   1530 		}
   1531 		if len(m.customExtension) > 0 {
   1532 			extensions.addU16(extensionCustom)
   1533 			extensions.addU16LengthPrefixed().addBytes([]byte(m.customExtension))
   1534 		}
   1535 	}
   1536 
   1537 	m.raw = retryRequestMsg.finish()
   1538 	return m.raw
   1539 }
   1540 
   1541 func (m *helloRetryRequestMsg) unmarshal(data []byte) bool {
   1542 	m.raw = data
   1543 	reader := byteReader(data[4:])
   1544 	if !reader.readU16(&m.vers) {
   1545 		return false
   1546 	}
   1547 	if m.isServerHello {
   1548 		var random []byte
   1549 		var compressionMethod byte
   1550 		if !reader.readBytes(&random, 32) ||
   1551 			!reader.readU8LengthPrefixedBytes(&m.sessionId) ||
   1552 			!reader.readU16(&m.cipherSuite) ||
   1553 			!reader.readU8(&compressionMethod) ||
   1554 			compressionMethod != 0 {
   1555 			return false
   1556 		}
   1557 	} else if !reader.readU16(&m.cipherSuite) {
   1558 		return false
   1559 	}
   1560 	var extensions byteReader
   1561 	if !reader.readU16LengthPrefixed(&extensions) || len(reader) != 0 {
   1562 		return false
   1563 	}
   1564 	extensionsCopy := extensions
   1565 	for len(extensionsCopy) > 0 {
   1566 		var extension uint16
   1567 		var body byteReader
   1568 		if !extensionsCopy.readU16(&extension) ||
   1569 			!extensionsCopy.readU16LengthPrefixed(&body) {
   1570 			return false
   1571 		}
   1572 		switch extension {
   1573 		case extensionSupportedVersions:
   1574 			if !m.isServerHello ||
   1575 				!body.readU16(&m.vers) ||
   1576 				len(body) != 0 {
   1577 				return false
   1578 			}
   1579 		default:
   1580 		}
   1581 	}
   1582 	for len(extensions) > 0 {
   1583 		var extension uint16
   1584 		var body byteReader
   1585 		if !extensions.readU16(&extension) ||
   1586 			!extensions.readU16LengthPrefixed(&body) {
   1587 			return false
   1588 		}
   1589 		switch extension {
   1590 		case extensionSupportedVersions:
   1591 			// Parsed above.
   1592 		case extensionKeyShare:
   1593 			var v uint16
   1594 			if !body.readU16(&v) || len(body) != 0 {
   1595 				return false
   1596 			}
   1597 			m.hasSelectedGroup = true
   1598 			m.selectedGroup = CurveID(v)
   1599 		case extensionCookie:
   1600 			if !body.readU16LengthPrefixedBytes(&m.cookie) || len(body) != 0 {
   1601 				return false
   1602 			}
   1603 		default:
   1604 			// Unknown extensions are illegal from the server.
   1605 			return false
   1606 		}
   1607 	}
   1608 	return true
   1609 }
   1610 
   1611 type certificateEntry struct {
   1612 	data                []byte
   1613 	ocspResponse        []byte
   1614 	sctList             []byte
   1615 	duplicateExtensions bool
   1616 	extraExtension      []byte
   1617 	delegatedCredential *delegatedCredential
   1618 }
   1619 
   1620 type delegatedCredential struct {
   1621 	// https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3
   1622 	signedBytes            []byte
   1623 	lifetimeSecs           uint32
   1624 	expectedCertVerifyAlgo signatureAlgorithm
   1625 	pkixPublicKey          []byte
   1626 	algorithm              signatureAlgorithm
   1627 	signature              []byte
   1628 }
   1629 
   1630 type certificateMsg struct {
   1631 	raw               []byte
   1632 	hasRequestContext bool
   1633 	requestContext    []byte
   1634 	certificates      []certificateEntry
   1635 }
   1636 
   1637 func (m *certificateMsg) marshal() (x []byte) {
   1638 	if m.raw != nil {
   1639 		return m.raw
   1640 	}
   1641 
   1642 	certMsg := newByteBuilder()
   1643 	certMsg.addU8(typeCertificate)
   1644 	certificate := certMsg.addU24LengthPrefixed()
   1645 	if m.hasRequestContext {
   1646 		context := certificate.addU8LengthPrefixed()
   1647 		context.addBytes(m.requestContext)
   1648 	}
   1649 	certificateList := certificate.addU24LengthPrefixed()
   1650 	for _, cert := range m.certificates {
   1651 		certEntry := certificateList.addU24LengthPrefixed()
   1652 		certEntry.addBytes(cert.data)
   1653 		if m.hasRequestContext {
   1654 			extensions := certificateList.addU16LengthPrefixed()
   1655 			count := 1
   1656 			if cert.duplicateExtensions {
   1657 				count = 2
   1658 			}
   1659 
   1660 			for i := 0; i < count; i++ {
   1661 				if cert.ocspResponse != nil {
   1662 					extensions.addU16(extensionStatusRequest)
   1663 					body := extensions.addU16LengthPrefixed()
   1664 					body.addU8(statusTypeOCSP)
   1665 					response := body.addU24LengthPrefixed()
   1666 					response.addBytes(cert.ocspResponse)
   1667 				}
   1668 
   1669 				if cert.sctList != nil {
   1670 					extensions.addU16(extensionSignedCertificateTimestamp)
   1671 					extension := extensions.addU16LengthPrefixed()
   1672 					extension.addBytes(cert.sctList)
   1673 				}
   1674 			}
   1675 			if cert.extraExtension != nil {
   1676 				extensions.addBytes(cert.extraExtension)
   1677 			}
   1678 		}
   1679 	}
   1680 
   1681 	m.raw = certMsg.finish()
   1682 	return m.raw
   1683 }
   1684 
   1685 func (m *certificateMsg) unmarshal(data []byte) bool {
   1686 	m.raw = data
   1687 	reader := byteReader(data[4:])
   1688 
   1689 	if m.hasRequestContext && !reader.readU8LengthPrefixedBytes(&m.requestContext) {
   1690 		return false
   1691 	}
   1692 
   1693 	var certs byteReader
   1694 	if !reader.readU24LengthPrefixed(&certs) || len(reader) != 0 {
   1695 		return false
   1696 	}
   1697 	m.certificates = nil
   1698 	for len(certs) > 0 {
   1699 		var cert certificateEntry
   1700 		if !certs.readU24LengthPrefixedBytes(&cert.data) {
   1701 			return false
   1702 		}
   1703 		if m.hasRequestContext {
   1704 			var extensions byteReader
   1705 			if !certs.readU16LengthPrefixed(&extensions) || !checkDuplicateExtensions(extensions) {
   1706 				return false
   1707 			}
   1708 			for len(extensions) > 0 {
   1709 				var extension uint16
   1710 				var body byteReader
   1711 				if !extensions.readU16(&extension) ||
   1712 					!extensions.readU16LengthPrefixed(&body) {
   1713 					return false
   1714 				}
   1715 				switch extension {
   1716 				case extensionStatusRequest:
   1717 					var statusType byte
   1718 					if !body.readU8(&statusType) ||
   1719 						statusType != statusTypeOCSP ||
   1720 						!body.readU24LengthPrefixedBytes(&cert.ocspResponse) ||
   1721 						len(body) != 0 {
   1722 						return false
   1723 					}
   1724 				case extensionSignedCertificateTimestamp:
   1725 					cert.sctList = []byte(body)
   1726 				case extensionDelegatedCredentials:
   1727 					// https://tools.ietf.org/html/draft-ietf-tls-subcerts-03#section-3
   1728 					if cert.delegatedCredential != nil {
   1729 						return false
   1730 					}
   1731 
   1732 					dc := new(delegatedCredential)
   1733 					origBody := body
   1734 					var expectedCertVerifyAlgo, algorithm uint16
   1735 
   1736 					if !body.readU32(&dc.lifetimeSecs) ||
   1737 						!body.readU16(&expectedCertVerifyAlgo) ||
   1738 						!body.readU24LengthPrefixedBytes(&dc.pkixPublicKey) ||
   1739 						!body.readU16(&algorithm) ||
   1740 						!body.readU16LengthPrefixedBytes(&dc.signature) ||
   1741 						len(body) != 0 {
   1742 						return false
   1743 					}
   1744 
   1745 					dc.expectedCertVerifyAlgo = signatureAlgorithm(expectedCertVerifyAlgo)
   1746 					dc.algorithm = signatureAlgorithm(algorithm)
   1747 					dc.signedBytes = []byte(origBody)[:4+2+3+len(dc.pkixPublicKey)]
   1748 					cert.delegatedCredential = dc
   1749 				default:
   1750 					return false
   1751 				}
   1752 			}
   1753 		}
   1754 		m.certificates = append(m.certificates, cert)
   1755 	}
   1756 
   1757 	return true
   1758 }
   1759 
   1760 type compressedCertificateMsg struct {
   1761 	raw                []byte
   1762 	algID              uint16
   1763 	uncompressedLength uint32
   1764 	compressed         []byte
   1765 }
   1766 
   1767 func (m *compressedCertificateMsg) marshal() (x []byte) {
   1768 	if m.raw != nil {
   1769 		return m.raw
   1770 	}
   1771 
   1772 	certMsg := newByteBuilder()
   1773 	certMsg.addU8(typeCompressedCertificate)
   1774 	certificate := certMsg.addU24LengthPrefixed()
   1775 	certificate.addU16(m.algID)
   1776 	certificate.addU24(int(m.uncompressedLength))
   1777 	compressed := certificate.addU24LengthPrefixed()
   1778 	compressed.addBytes(m.compressed)
   1779 
   1780 	m.raw = certMsg.finish()
   1781 	return m.raw
   1782 }
   1783 
   1784 func (m *compressedCertificateMsg) unmarshal(data []byte) bool {
   1785 	m.raw = data
   1786 	reader := byteReader(data[4:])
   1787 
   1788 	if !reader.readU16(&m.algID) ||
   1789 		!reader.readU24(&m.uncompressedLength) ||
   1790 		!reader.readU24LengthPrefixedBytes(&m.compressed) ||
   1791 		len(reader) != 0 {
   1792 		return false
   1793 	}
   1794 
   1795 	if m.uncompressedLength >= 1<<17 {
   1796 		return false
   1797 	}
   1798 
   1799 	return true
   1800 }
   1801 
   1802 type serverKeyExchangeMsg struct {
   1803 	raw []byte
   1804 	key []byte
   1805 }
   1806 
   1807 func (m *serverKeyExchangeMsg) marshal() []byte {
   1808 	if m.raw != nil {
   1809 		return m.raw
   1810 	}
   1811 	msg := newByteBuilder()
   1812 	msg.addU8(typeServerKeyExchange)
   1813 	msg.addU24LengthPrefixed().addBytes(m.key)
   1814 	m.raw = msg.finish()
   1815 	return m.raw
   1816 }
   1817 
   1818 func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool {
   1819 	m.raw = data
   1820 	if len(data) < 4 {
   1821 		return false
   1822 	}
   1823 	m.key = data[4:]
   1824 	return true
   1825 }
   1826 
   1827 type certificateStatusMsg struct {
   1828 	raw        []byte
   1829 	statusType uint8
   1830 	response   []byte
   1831 }
   1832 
   1833 func (m *certificateStatusMsg) marshal() []byte {
   1834 	if m.raw != nil {
   1835 		return m.raw
   1836 	}
   1837 
   1838 	var x []byte
   1839 	if m.statusType == statusTypeOCSP {
   1840 		msg := newByteBuilder()
   1841 		msg.addU8(typeCertificateStatus)
   1842 		body := msg.addU24LengthPrefixed()
   1843 		body.addU8(statusTypeOCSP)
   1844 		body.addU24LengthPrefixed().addBytes(m.response)
   1845 		x = msg.finish()
   1846 	} else {
   1847 		x = []byte{typeCertificateStatus, 0, 0, 1, m.statusType}
   1848 	}
   1849 
   1850 	m.raw = x
   1851 	return x
   1852 }
   1853 
   1854 func (m *certificateStatusMsg) unmarshal(data []byte) bool {
   1855 	m.raw = data
   1856 	reader := byteReader(data[4:])
   1857 	if !reader.readU8(&m.statusType) ||
   1858 		m.statusType != statusTypeOCSP ||
   1859 		!reader.readU24LengthPrefixedBytes(&m.response) ||
   1860 		len(reader) != 0 {
   1861 		return false
   1862 	}
   1863 	return true
   1864 }
   1865 
   1866 type serverHelloDoneMsg struct{}
   1867 
   1868 func (m *serverHelloDoneMsg) marshal() []byte {
   1869 	x := make([]byte, 4)
   1870 	x[0] = typeServerHelloDone
   1871 	return x
   1872 }
   1873 
   1874 func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
   1875 	return len(data) == 4
   1876 }
   1877 
   1878 type clientKeyExchangeMsg struct {
   1879 	raw        []byte
   1880 	ciphertext []byte
   1881 }
   1882 
   1883 func (m *clientKeyExchangeMsg) marshal() []byte {
   1884 	if m.raw != nil {
   1885 		return m.raw
   1886 	}
   1887 	msg := newByteBuilder()
   1888 	msg.addU8(typeClientKeyExchange)
   1889 	msg.addU24LengthPrefixed().addBytes(m.ciphertext)
   1890 	m.raw = msg.finish()
   1891 	return m.raw
   1892 }
   1893 
   1894 func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
   1895 	m.raw = data
   1896 	if len(data) < 4 {
   1897 		return false
   1898 	}
   1899 	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
   1900 	if l != len(data)-4 {
   1901 		return false
   1902 	}
   1903 	m.ciphertext = data[4:]
   1904 	return true
   1905 }
   1906 
   1907 type finishedMsg struct {
   1908 	raw        []byte
   1909 	verifyData []byte
   1910 }
   1911 
   1912 func (m *finishedMsg) marshal() []byte {
   1913 	if m.raw != nil {
   1914 		return m.raw
   1915 	}
   1916 
   1917 	msg := newByteBuilder()
   1918 	msg.addU8(typeFinished)
   1919 	msg.addU24LengthPrefixed().addBytes(m.verifyData)
   1920 	m.raw = msg.finish()
   1921 	return m.raw
   1922 }
   1923 
   1924 func (m *finishedMsg) unmarshal(data []byte) bool {
   1925 	m.raw = data
   1926 	if len(data) < 4 {
   1927 		return false
   1928 	}
   1929 	m.verifyData = data[4:]
   1930 	return true
   1931 }
   1932 
   1933 type nextProtoMsg struct {
   1934 	raw   []byte
   1935 	proto string
   1936 }
   1937 
   1938 func (m *nextProtoMsg) marshal() []byte {
   1939 	if m.raw != nil {
   1940 		return m.raw
   1941 	}
   1942 
   1943 	padding := 32 - (len(m.proto)+2)%32
   1944 
   1945 	msg := newByteBuilder()
   1946 	msg.addU8(typeNextProtocol)
   1947 	body := msg.addU24LengthPrefixed()
   1948 	body.addU8LengthPrefixed().addBytes([]byte(m.proto))
   1949 	body.addU8LengthPrefixed().addBytes(make([]byte, padding))
   1950 	m.raw = msg.finish()
   1951 	return m.raw
   1952 }
   1953 
   1954 func (m *nextProtoMsg) unmarshal(data []byte) bool {
   1955 	m.raw = data
   1956 	reader := byteReader(data[4:])
   1957 	var proto, padding []byte
   1958 	if !reader.readU8LengthPrefixedBytes(&proto) ||
   1959 		!reader.readU8LengthPrefixedBytes(&padding) ||
   1960 		len(reader) != 0 {
   1961 		return false
   1962 	}
   1963 	m.proto = string(proto)
   1964 
   1965 	// Padding is not meant to be checked normally, but as this is a testing
   1966 	// implementation, we check the padding is as expected.
   1967 	if len(padding) != 32-(len(m.proto)+2)%32 {
   1968 		return false
   1969 	}
   1970 	for _, v := range padding {
   1971 		if v != 0 {
   1972 			return false
   1973 		}
   1974 	}
   1975 
   1976 	return true
   1977 }
   1978 
   1979 type certificateRequestMsg struct {
   1980 	raw  []byte
   1981 	vers uint16
   1982 	// hasSignatureAlgorithm indicates whether this message includes a list
   1983 	// of signature and hash functions. This change was introduced with TLS
   1984 	// 1.2.
   1985 	hasSignatureAlgorithm bool
   1986 	// hasRequestContext indicates whether this message includes a context
   1987 	// field instead of certificateTypes. This change was introduced with
   1988 	// TLS 1.3.
   1989 	hasRequestContext bool
   1990 
   1991 	certificateTypes        []byte
   1992 	requestContext          []byte
   1993 	signatureAlgorithms     []signatureAlgorithm
   1994 	signatureAlgorithmsCert []signatureAlgorithm
   1995 	certificateAuthorities  [][]byte
   1996 	hasCAExtension          bool
   1997 	customExtension         uint16
   1998 }
   1999 
   2000 func (m *certificateRequestMsg) marshal() []byte {
   2001 	if m.raw != nil {
   2002 		return m.raw
   2003 	}
   2004 
   2005 	// See http://tools.ietf.org/html/rfc4346#section-7.4.4
   2006 	builder := newByteBuilder()
   2007 	builder.addU8(typeCertificateRequest)
   2008 	body := builder.addU24LengthPrefixed()
   2009 
   2010 	if m.hasRequestContext {
   2011 		requestContext := body.addU8LengthPrefixed()
   2012 		requestContext.addBytes(m.requestContext)
   2013 		extensions := newByteBuilder()
   2014 		extensions = body.addU16LengthPrefixed()
   2015 		if m.hasSignatureAlgorithm {
   2016 			extensions.addU16(extensionSignatureAlgorithms)
   2017 			signatureAlgorithms := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
   2018 			for _, sigAlg := range m.signatureAlgorithms {
   2019 				signatureAlgorithms.addU16(uint16(sigAlg))
   2020 			}
   2021 		}
   2022 		if len(m.signatureAlgorithmsCert) > 0 {
   2023 			extensions.addU16(extensionSignatureAlgorithmsCert)
   2024 			signatureAlgorithmsCert := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
   2025 			for _, sigAlg := range m.signatureAlgorithmsCert {
   2026 				signatureAlgorithmsCert.addU16(uint16(sigAlg))
   2027 			}
   2028 		}
   2029 		if len(m.certificateAuthorities) > 0 {
   2030 			extensions.addU16(extensionCertificateAuthorities)
   2031 			certificateAuthorities := extensions.addU16LengthPrefixed().addU16LengthPrefixed()
   2032 			for _, ca := range m.certificateAuthorities {
   2033 				caEntry := certificateAuthorities.addU16LengthPrefixed()
   2034 				caEntry.addBytes(ca)
   2035 			}
   2036 		}
   2037 
   2038 		if m.customExtension > 0 {
   2039 			extensions.addU16(m.customExtension)
   2040 			extensions.addU16LengthPrefixed()
   2041 		}
   2042 	} else {
   2043 		certificateTypes := body.addU8LengthPrefixed()
   2044 		certificateTypes.addBytes(m.certificateTypes)
   2045 
   2046 		if m.hasSignatureAlgorithm {
   2047 			signatureAlgorithms := body.addU16LengthPrefixed()
   2048 			for _, sigAlg := range m.signatureAlgorithms {
   2049 				signatureAlgorithms.addU16(uint16(sigAlg))
   2050 			}
   2051 		}
   2052 
   2053 		certificateAuthorities := body.addU16LengthPrefixed()
   2054 		for _, ca := range m.certificateAuthorities {
   2055 			caEntry := certificateAuthorities.addU16LengthPrefixed()
   2056 			caEntry.addBytes(ca)
   2057 		}
   2058 	}
   2059 
   2060 	m.raw = builder.finish()
   2061 	return m.raw
   2062 }
   2063 
   2064 func parseCAs(reader *byteReader, out *[][]byte) bool {
   2065 	var cas byteReader
   2066 	if !reader.readU16LengthPrefixed(&cas) {
   2067 		return false
   2068 	}
   2069 	for len(cas) > 0 {
   2070 		var ca []byte
   2071 		if !cas.readU16LengthPrefixedBytes(&ca) {
   2072 			return false
   2073 		}
   2074 		*out = append(*out, ca)
   2075 	}
   2076 	return true
   2077 }
   2078 
   2079 func (m *certificateRequestMsg) unmarshal(data []byte) bool {
   2080 	m.raw = data
   2081 	reader := byteReader(data[4:])
   2082 
   2083 	if m.hasRequestContext {
   2084 		var extensions byteReader
   2085 		if !reader.readU8LengthPrefixedBytes(&m.requestContext) ||
   2086 			!reader.readU16LengthPrefixed(&extensions) ||
   2087 			len(reader) != 0 ||
   2088 			!checkDuplicateExtensions(extensions) {
   2089 			return false
   2090 		}
   2091 		for len(extensions) > 0 {
   2092 			var extension uint16
   2093 			var body byteReader
   2094 			if !extensions.readU16(&extension) ||
   2095 				!extensions.readU16LengthPrefixed(&body) {
   2096 				return false
   2097 			}
   2098 			switch extension {
   2099 			case extensionSignatureAlgorithms:
   2100 				if !parseSignatureAlgorithms(&body, &m.signatureAlgorithms, false) || len(body) != 0 {
   2101 					return false
   2102 				}
   2103 			case extensionSignatureAlgorithmsCert:
   2104 				if !parseSignatureAlgorithms(&body, &m.signatureAlgorithmsCert, false) || len(body) != 0 {
   2105 					return false
   2106 				}
   2107 			case extensionCertificateAuthorities:
   2108 				if !parseCAs(&body, &m.certificateAuthorities) || len(body) != 0 {
   2109 					return false
   2110 				}
   2111 				m.hasCAExtension = true
   2112 			}
   2113 		}
   2114 	} else {
   2115 		if !reader.readU8LengthPrefixedBytes(&m.certificateTypes) {
   2116 			return false
   2117 		}
   2118 		// In TLS 1.2, the supported_signature_algorithms field in
   2119 		// CertificateRequest may be empty.
   2120 		if m.hasSignatureAlgorithm && !parseSignatureAlgorithms(&reader, &m.signatureAlgorithms, true) {
   2121 			return false
   2122 		}
   2123 		if !parseCAs(&reader, &m.certificateAuthorities) ||
   2124 			len(reader) != 0 {
   2125 			return false
   2126 		}
   2127 	}
   2128 
   2129 	return true
   2130 }
   2131 
   2132 type certificateVerifyMsg struct {
   2133 	raw                   []byte
   2134 	hasSignatureAlgorithm bool
   2135 	signatureAlgorithm    signatureAlgorithm
   2136 	signature             []byte
   2137 }
   2138 
   2139 func (m *certificateVerifyMsg) marshal() (x []byte) {
   2140 	if m.raw != nil {
   2141 		return m.raw
   2142 	}
   2143 
   2144 	// See http://tools.ietf.org/html/rfc4346#section-7.4.8
   2145 	siglength := len(m.signature)
   2146 	length := 2 + siglength
   2147 	if m.hasSignatureAlgorithm {
   2148 		length += 2
   2149 	}
   2150 	x = make([]byte, 4+length)
   2151 	x[0] = typeCertificateVerify
   2152 	x[1] = uint8(length >> 16)
   2153 	x[2] = uint8(length >> 8)
   2154 	x[3] = uint8(length)
   2155 	y := x[4:]
   2156 	if m.hasSignatureAlgorithm {
   2157 		y[0] = byte(m.signatureAlgorithm >> 8)
   2158 		y[1] = byte(m.signatureAlgorithm)
   2159 		y = y[2:]
   2160 	}
   2161 	y[0] = uint8(siglength >> 8)
   2162 	y[1] = uint8(siglength)
   2163 	copy(y[2:], m.signature)
   2164 
   2165 	m.raw = x
   2166 
   2167 	return
   2168 }
   2169 
   2170 func (m *certificateVerifyMsg) unmarshal(data []byte) bool {
   2171 	m.raw = data
   2172 
   2173 	if len(data) < 6 {
   2174 		return false
   2175 	}
   2176 
   2177 	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
   2178 	if uint32(len(data))-4 != length {
   2179 		return false
   2180 	}
   2181 
   2182 	data = data[4:]
   2183 	if m.hasSignatureAlgorithm {
   2184 		m.signatureAlgorithm = signatureAlgorithm(data[0])<<8 | signatureAlgorithm(data[1])
   2185 		data = data[2:]
   2186 	}
   2187 
   2188 	if len(data) < 2 {
   2189 		return false
   2190 	}
   2191 	siglength := int(data[0])<<8 + int(data[1])
   2192 	data = data[2:]
   2193 	if len(data) != siglength {
   2194 		return false
   2195 	}
   2196 
   2197 	m.signature = data
   2198 
   2199 	return true
   2200 }
   2201 
   2202 type newSessionTicketMsg struct {
   2203 	raw                         []byte
   2204 	vers                        uint16
   2205 	isDTLS                      bool
   2206 	ticketLifetime              uint32
   2207 	ticketAgeAdd                uint32
   2208 	ticketNonce                 []byte
   2209 	ticket                      []byte
   2210 	maxEarlyDataSize            uint32
   2211 	customExtension             string
   2212 	duplicateEarlyDataExtension bool
   2213 	hasGREASEExtension          bool
   2214 }
   2215 
   2216 func (m *newSessionTicketMsg) marshal() []byte {
   2217 	if m.raw != nil {
   2218 		return m.raw
   2219 	}
   2220 
   2221 	version, ok := wireToVersion(m.vers, m.isDTLS)
   2222 	if !ok {
   2223 		panic("unknown version")
   2224 	}
   2225 
   2226 	// See http://tools.ietf.org/html/rfc5077#section-3.3
   2227 	ticketMsg := newByteBuilder()
   2228 	ticketMsg.addU8(typeNewSessionTicket)
   2229 	body := ticketMsg.addU24LengthPrefixed()
   2230 	body.addU32(m.ticketLifetime)
   2231 	if version >= VersionTLS13 {
   2232 		body.addU32(m.ticketAgeAdd)
   2233 		body.addU8LengthPrefixed().addBytes(m.ticketNonce)
   2234 	}
   2235 
   2236 	ticket := body.addU16LengthPrefixed()
   2237 	ticket.addBytes(m.ticket)
   2238 
   2239 	if version >= VersionTLS13 {
   2240 		extensions := body.addU16LengthPrefixed()
   2241 		if m.maxEarlyDataSize > 0 {
   2242 			extensions.addU16(extensionEarlyData)
   2243 			extensions.addU16LengthPrefixed().addU32(m.maxEarlyDataSize)
   2244 			if m.duplicateEarlyDataExtension {
   2245 				extensions.addU16(extensionEarlyData)
   2246 				extensions.addU16LengthPrefixed().addU32(m.maxEarlyDataSize)
   2247 			}
   2248 		}
   2249 		if len(m.customExtension) > 0 {
   2250 			extensions.addU16(extensionCustom)
   2251 			extensions.addU16LengthPrefixed().addBytes([]byte(m.customExtension))
   2252 		}
   2253 	}
   2254 
   2255 	m.raw = ticketMsg.finish()
   2256 	return m.raw
   2257 }
   2258 
   2259 func (m *newSessionTicketMsg) unmarshal(data []byte) bool {
   2260 	m.raw = data
   2261 
   2262 	version, ok := wireToVersion(m.vers, m.isDTLS)
   2263 	if !ok {
   2264 		panic("unknown version")
   2265 	}
   2266 
   2267 	if len(data) < 8 {
   2268 		return false
   2269 	}
   2270 	m.ticketLifetime = uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
   2271 	data = data[8:]
   2272 
   2273 	if version >= VersionTLS13 {
   2274 		if len(data) < 4 {
   2275 			return false
   2276 		}
   2277 		m.ticketAgeAdd = uint32(data[0])<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
   2278 		data = data[4:]
   2279 		nonceLen := int(data[0])
   2280 		data = data[1:]
   2281 		if len(data) < nonceLen {
   2282 			return false
   2283 		}
   2284 		m.ticketNonce = data[:nonceLen]
   2285 		data = data[nonceLen:]
   2286 	}
   2287 
   2288 	if len(data) < 2 {
   2289 		return false
   2290 	}
   2291 	ticketLen := int(data[0])<<8 + int(data[1])
   2292 	data = data[2:]
   2293 	if len(data) < ticketLen {
   2294 		return false
   2295 	}
   2296 
   2297 	if version >= VersionTLS13 && ticketLen == 0 {
   2298 		return false
   2299 	}
   2300 
   2301 	m.ticket = data[:ticketLen]
   2302 	data = data[ticketLen:]
   2303 
   2304 	if version >= VersionTLS13 {
   2305 		if len(data) < 2 {
   2306 			return false
   2307 		}
   2308 
   2309 		extensionsLength := int(data[0])<<8 | int(data[1])
   2310 		data = data[2:]
   2311 		if extensionsLength != len(data) {
   2312 			return false
   2313 		}
   2314 
   2315 		for len(data) != 0 {
   2316 			if len(data) < 4 {
   2317 				return false
   2318 			}
   2319 			extension := uint16(data[0])<<8 | uint16(data[1])
   2320 			length := int(data[2])<<8 | int(data[3])
   2321 			data = data[4:]
   2322 			if len(data) < length {
   2323 				return false
   2324 			}
   2325 
   2326 			switch extension {
   2327 			case extensionEarlyData:
   2328 				if length != 4 {
   2329 					return false
   2330 				}
   2331 				m.maxEarlyDataSize = uint32(data[0])<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
   2332 			default:
   2333 				if isGREASEValue(extension) {
   2334 					m.hasGREASEExtension = true
   2335 				}
   2336 			}
   2337 
   2338 			data = data[length:]
   2339 		}
   2340 	}
   2341 
   2342 	if len(data) > 0 {
   2343 		return false
   2344 	}
   2345 
   2346 	return true
   2347 }
   2348 
   2349 type v2ClientHelloMsg struct {
   2350 	raw          []byte
   2351 	vers         uint16
   2352 	cipherSuites []uint16
   2353 	sessionId    []byte
   2354 	challenge    []byte
   2355 }
   2356 
   2357 func (m *v2ClientHelloMsg) marshal() []byte {
   2358 	if m.raw != nil {
   2359 		return m.raw
   2360 	}
   2361 
   2362 	length := 1 + 2 + 2 + 2 + 2 + len(m.cipherSuites)*3 + len(m.sessionId) + len(m.challenge)
   2363 
   2364 	x := make([]byte, length)
   2365 	x[0] = 1
   2366 	x[1] = uint8(m.vers >> 8)
   2367 	x[2] = uint8(m.vers)
   2368 	x[3] = uint8((len(m.cipherSuites) * 3) >> 8)
   2369 	x[4] = uint8(len(m.cipherSuites) * 3)
   2370 	x[5] = uint8(len(m.sessionId) >> 8)
   2371 	x[6] = uint8(len(m.sessionId))
   2372 	x[7] = uint8(len(m.challenge) >> 8)
   2373 	x[8] = uint8(len(m.challenge))
   2374 	y := x[9:]
   2375 	for i, spec := range m.cipherSuites {
   2376 		y[i*3] = 0
   2377 		y[i*3+1] = uint8(spec >> 8)
   2378 		y[i*3+2] = uint8(spec)
   2379 	}
   2380 	y = y[len(m.cipherSuites)*3:]
   2381 	copy(y, m.sessionId)
   2382 	y = y[len(m.sessionId):]
   2383 	copy(y, m.challenge)
   2384 
   2385 	m.raw = x
   2386 
   2387 	return x
   2388 }
   2389 
   2390 type helloVerifyRequestMsg struct {
   2391 	raw    []byte
   2392 	vers   uint16
   2393 	cookie []byte
   2394 }
   2395 
   2396 func (m *helloVerifyRequestMsg) marshal() []byte {
   2397 	if m.raw != nil {
   2398 		return m.raw
   2399 	}
   2400 
   2401 	length := 2 + 1 + len(m.cookie)
   2402 
   2403 	x := make([]byte, 4+length)
   2404 	x[0] = typeHelloVerifyRequest
   2405 	x[1] = uint8(length >> 16)
   2406 	x[2] = uint8(length >> 8)
   2407 	x[3] = uint8(length)
   2408 	vers := m.vers
   2409 	x[4] = uint8(vers >> 8)
   2410 	x[5] = uint8(vers)
   2411 	x[6] = uint8(len(m.cookie))
   2412 	copy(x[7:7+len(m.cookie)], m.cookie)
   2413 
   2414 	return x
   2415 }
   2416 
   2417 func (m *helloVerifyRequestMsg) unmarshal(data []byte) bool {
   2418 	if len(data) < 4+2+1 {
   2419 		return false
   2420 	}
   2421 	m.raw = data
   2422 	m.vers = uint16(data[4])<<8 | uint16(data[5])
   2423 	cookieLen := int(data[6])
   2424 	if cookieLen > 32 || len(data) != 7+cookieLen {
   2425 		return false
   2426 	}
   2427 	m.cookie = data[7 : 7+cookieLen]
   2428 
   2429 	return true
   2430 }
   2431 
   2432 type channelIDMsg struct {
   2433 	raw       []byte
   2434 	channelID []byte
   2435 }
   2436 
   2437 func (m *channelIDMsg) marshal() []byte {
   2438 	if m.raw != nil {
   2439 		return m.raw
   2440 	}
   2441 
   2442 	length := 2 + 2 + len(m.channelID)
   2443 
   2444 	x := make([]byte, 4+length)
   2445 	x[0] = typeChannelID
   2446 	x[1] = uint8(length >> 16)
   2447 	x[2] = uint8(length >> 8)
   2448 	x[3] = uint8(length)
   2449 	x[4] = uint8(extensionChannelID >> 8)
   2450 	x[5] = uint8(extensionChannelID & 0xff)
   2451 	x[6] = uint8(len(m.channelID) >> 8)
   2452 	x[7] = uint8(len(m.channelID) & 0xff)
   2453 	copy(x[8:], m.channelID)
   2454 
   2455 	return x
   2456 }
   2457 
   2458 func (m *channelIDMsg) unmarshal(data []byte) bool {
   2459 	if len(data) != 4+2+2+128 {
   2460 		return false
   2461 	}
   2462 	m.raw = data
   2463 	if (uint16(data[4])<<8)|uint16(data[5]) != extensionChannelID {
   2464 		return false
   2465 	}
   2466 	if int(data[6])<<8|int(data[7]) != 128 {
   2467 		return false
   2468 	}
   2469 	m.channelID = data[4+2+2:]
   2470 
   2471 	return true
   2472 }
   2473 
   2474 type helloRequestMsg struct {
   2475 }
   2476 
   2477 func (*helloRequestMsg) marshal() []byte {
   2478 	return []byte{typeHelloRequest, 0, 0, 0}
   2479 }
   2480 
   2481 func (*helloRequestMsg) unmarshal(data []byte) bool {
   2482 	return len(data) == 4
   2483 }
   2484 
   2485 type keyUpdateMsg struct {
   2486 	raw              []byte
   2487 	keyUpdateRequest byte
   2488 }
   2489 
   2490 func (m *keyUpdateMsg) marshal() []byte {
   2491 	if m.raw != nil {
   2492 		return m.raw
   2493 	}
   2494 
   2495 	return []byte{typeKeyUpdate, 0, 0, 1, m.keyUpdateRequest}
   2496 }
   2497 
   2498 func (m *keyUpdateMsg) unmarshal(data []byte) bool {
   2499 	m.raw = data
   2500 
   2501 	if len(data) != 5 {
   2502 		return false
   2503 	}
   2504 
   2505 	length := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
   2506 	if len(data)-4 != length {
   2507 		return false
   2508 	}
   2509 
   2510 	m.keyUpdateRequest = data[4]
   2511 	return m.keyUpdateRequest == keyUpdateNotRequested || m.keyUpdateRequest == keyUpdateRequested
   2512 }
   2513 
   2514 type endOfEarlyDataMsg struct {
   2515 	nonEmpty bool
   2516 }
   2517 
   2518 func (m *endOfEarlyDataMsg) marshal() []byte {
   2519 	if m.nonEmpty {
   2520 		return []byte{typeEndOfEarlyData, 0, 0, 1, 42}
   2521 	}
   2522 	return []byte{typeEndOfEarlyData, 0, 0, 0}
   2523 }
   2524 
   2525 func (*endOfEarlyDataMsg) unmarshal(data []byte) bool {
   2526 	return len(data) == 4
   2527 }
   2528 
   2529 // ssl3NoCertificateMsg is a dummy message to handle SSL 3.0 using a warning
   2530 // alert in the handshake.
   2531 type ssl3NoCertificateMsg struct{}
   2532 
   2533 func eqUint16s(x, y []uint16) bool {
   2534 	if len(x) != len(y) {
   2535 		return false
   2536 	}
   2537 	for i, v := range x {
   2538 		if y[i] != v {
   2539 			return false
   2540 		}
   2541 	}
   2542 	return true
   2543 }
   2544 
   2545 func eqCurveIDs(x, y []CurveID) bool {
   2546 	if len(x) != len(y) {
   2547 		return false
   2548 	}
   2549 	for i, v := range x {
   2550 		if y[i] != v {
   2551 			return false
   2552 		}
   2553 	}
   2554 	return true
   2555 }
   2556 
   2557 func eqStrings(x, y []string) bool {
   2558 	if len(x) != len(y) {
   2559 		return false
   2560 	}
   2561 	for i, v := range x {
   2562 		if y[i] != v {
   2563 			return false
   2564 		}
   2565 	}
   2566 	return true
   2567 }
   2568 
   2569 func eqByteSlices(x, y [][]byte) bool {
   2570 	if len(x) != len(y) {
   2571 		return false
   2572 	}
   2573 	for i, v := range x {
   2574 		if !bytes.Equal(v, y[i]) {
   2575 			return false
   2576 		}
   2577 	}
   2578 	return true
   2579 }
   2580 
   2581 func eqSignatureAlgorithms(x, y []signatureAlgorithm) bool {
   2582 	if len(x) != len(y) {
   2583 		return false
   2584 	}
   2585 	for i, v := range x {
   2586 		v2 := y[i]
   2587 		if v != v2 {
   2588 			return false
   2589 		}
   2590 	}
   2591 	return true
   2592 }
   2593 
   2594 func eqKeyShareEntryLists(x, y []keyShareEntry) bool {
   2595 	if len(x) != len(y) {
   2596 		return false
   2597 	}
   2598 	for i, v := range x {
   2599 		if y[i].group != v.group || !bytes.Equal(y[i].keyExchange, v.keyExchange) {
   2600 			return false
   2601 		}
   2602 	}
   2603 	return true
   2604 
   2605 }
   2606 
   2607 func eqPSKIdentityLists(x, y []pskIdentity) bool {
   2608 	if len(x) != len(y) {
   2609 		return false
   2610 	}
   2611 	for i, v := range x {
   2612 		if !bytes.Equal(y[i].ticket, v.ticket) || y[i].obfuscatedTicketAge != v.obfuscatedTicketAge {
   2613 			return false
   2614 		}
   2615 	}
   2616 	return true
   2617 
   2618 }
   2619