Home | History | Annotate | Download | only in tls
      1 // Copyright 2010 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 // TLS low level connection and record layer
      6 
      7 package tls
      8 
      9 import (
     10 	"bytes"
     11 	"crypto/cipher"
     12 	"crypto/subtle"
     13 	"crypto/x509"
     14 	"errors"
     15 	"fmt"
     16 	"io"
     17 	"net"
     18 	"sync"
     19 	"sync/atomic"
     20 	"time"
     21 )
     22 
     23 // A Conn represents a secured connection.
     24 // It implements the net.Conn interface.
     25 type Conn struct {
     26 	// constant
     27 	conn     net.Conn
     28 	isClient bool
     29 
     30 	// constant after handshake; protected by handshakeMutex
     31 	handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex
     32 	// handshakeCond, if not nil, indicates that a goroutine is committed
     33 	// to running the handshake for this Conn. Other goroutines that need
     34 	// to wait for the handshake can wait on this, under handshakeMutex.
     35 	handshakeCond *sync.Cond
     36 	handshakeErr  error   // error resulting from handshake
     37 	vers          uint16  // TLS version
     38 	haveVers      bool    // version has been negotiated
     39 	config        *Config // configuration passed to constructor
     40 	// handshakeComplete is true if the connection is currently transferring
     41 	// application data (i.e. is not currently processing a handshake).
     42 	handshakeComplete bool
     43 	// handshakes counts the number of handshakes performed on the
     44 	// connection so far. If renegotiation is disabled then this is either
     45 	// zero or one.
     46 	handshakes       int
     47 	didResume        bool // whether this connection was a session resumption
     48 	cipherSuite      uint16
     49 	ocspResponse     []byte   // stapled OCSP response
     50 	scts             [][]byte // signed certificate timestamps from server
     51 	peerCertificates []*x509.Certificate
     52 	// verifiedChains contains the certificate chains that we built, as
     53 	// opposed to the ones presented by the server.
     54 	verifiedChains [][]*x509.Certificate
     55 	// serverName contains the server name indicated by the client, if any.
     56 	serverName string
     57 	// secureRenegotiation is true if the server echoed the secure
     58 	// renegotiation extension. (This is meaningless as a server because
     59 	// renegotiation is not supported in that case.)
     60 	secureRenegotiation bool
     61 
     62 	// clientFinishedIsFirst is true if the client sent the first Finished
     63 	// message during the most recent handshake. This is recorded because
     64 	// the first transmitted Finished message is the tls-unique
     65 	// channel-binding value.
     66 	clientFinishedIsFirst bool
     67 
     68 	// closeNotifyErr is any error from sending the alertCloseNotify record.
     69 	closeNotifyErr error
     70 	// closeNotifySent is true if the Conn attempted to send an
     71 	// alertCloseNotify record.
     72 	closeNotifySent bool
     73 
     74 	// clientFinished and serverFinished contain the Finished message sent
     75 	// by the client or server in the most recent handshake. This is
     76 	// retained to support the renegotiation extension and tls-unique
     77 	// channel-binding.
     78 	clientFinished [12]byte
     79 	serverFinished [12]byte
     80 
     81 	clientProtocol         string
     82 	clientProtocolFallback bool
     83 
     84 	// input/output
     85 	in, out   halfConn     // in.Mutex < out.Mutex
     86 	rawInput  *block       // raw input, right off the wire
     87 	input     *block       // application data waiting to be read
     88 	hand      bytes.Buffer // handshake data waiting to be read
     89 	buffering bool         // whether records are buffered in sendBuf
     90 	sendBuf   []byte       // a buffer of records waiting to be sent
     91 
     92 	// bytesSent counts the bytes of application data sent.
     93 	// packetsSent counts packets.
     94 	bytesSent   int64
     95 	packetsSent int64
     96 
     97 	// activeCall is an atomic int32; the low bit is whether Close has
     98 	// been called. the rest of the bits are the number of goroutines
     99 	// in Conn.Write.
    100 	activeCall int32
    101 
    102 	tmp [16]byte
    103 }
    104 
    105 // Access to net.Conn methods.
    106 // Cannot just embed net.Conn because that would
    107 // export the struct field too.
    108 
    109 // LocalAddr returns the local network address.
    110 func (c *Conn) LocalAddr() net.Addr {
    111 	return c.conn.LocalAddr()
    112 }
    113 
    114 // RemoteAddr returns the remote network address.
    115 func (c *Conn) RemoteAddr() net.Addr {
    116 	return c.conn.RemoteAddr()
    117 }
    118 
    119 // SetDeadline sets the read and write deadlines associated with the connection.
    120 // A zero value for t means Read and Write will not time out.
    121 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    122 func (c *Conn) SetDeadline(t time.Time) error {
    123 	return c.conn.SetDeadline(t)
    124 }
    125 
    126 // SetReadDeadline sets the read deadline on the underlying connection.
    127 // A zero value for t means Read will not time out.
    128 func (c *Conn) SetReadDeadline(t time.Time) error {
    129 	return c.conn.SetReadDeadline(t)
    130 }
    131 
    132 // SetWriteDeadline sets the write deadline on the underlying connection.
    133 // A zero value for t means Write will not time out.
    134 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error.
    135 func (c *Conn) SetWriteDeadline(t time.Time) error {
    136 	return c.conn.SetWriteDeadline(t)
    137 }
    138 
    139 // A halfConn represents one direction of the record layer
    140 // connection, either sending or receiving.
    141 type halfConn struct {
    142 	sync.Mutex
    143 
    144 	err            error       // first permanent error
    145 	version        uint16      // protocol version
    146 	cipher         interface{} // cipher algorithm
    147 	mac            macFunction
    148 	seq            [8]byte  // 64-bit sequence number
    149 	bfree          *block   // list of free blocks
    150 	additionalData [13]byte // to avoid allocs; interface method args escape
    151 
    152 	nextCipher interface{} // next encryption state
    153 	nextMac    macFunction // next MAC algorithm
    154 
    155 	// used to save allocating a new buffer for each MAC.
    156 	inDigestBuf, outDigestBuf []byte
    157 }
    158 
    159 func (hc *halfConn) setErrorLocked(err error) error {
    160 	hc.err = err
    161 	return err
    162 }
    163 
    164 // prepareCipherSpec sets the encryption and MAC states
    165 // that a subsequent changeCipherSpec will use.
    166 func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) {
    167 	hc.version = version
    168 	hc.nextCipher = cipher
    169 	hc.nextMac = mac
    170 }
    171 
    172 // changeCipherSpec changes the encryption and MAC states
    173 // to the ones previously passed to prepareCipherSpec.
    174 func (hc *halfConn) changeCipherSpec() error {
    175 	if hc.nextCipher == nil {
    176 		return alertInternalError
    177 	}
    178 	hc.cipher = hc.nextCipher
    179 	hc.mac = hc.nextMac
    180 	hc.nextCipher = nil
    181 	hc.nextMac = nil
    182 	for i := range hc.seq {
    183 		hc.seq[i] = 0
    184 	}
    185 	return nil
    186 }
    187 
    188 // incSeq increments the sequence number.
    189 func (hc *halfConn) incSeq() {
    190 	for i := 7; i >= 0; i-- {
    191 		hc.seq[i]++
    192 		if hc.seq[i] != 0 {
    193 			return
    194 		}
    195 	}
    196 
    197 	// Not allowed to let sequence number wrap.
    198 	// Instead, must renegotiate before it does.
    199 	// Not likely enough to bother.
    200 	panic("TLS: sequence number wraparound")
    201 }
    202 
    203 // extractPadding returns, in constant time, the length of the padding to remove
    204 // from the end of payload. It also returns a byte which is equal to 255 if the
    205 // padding was valid and 0 otherwise. See RFC 2246, section 6.2.3.2
    206 func extractPadding(payload []byte) (toRemove int, good byte) {
    207 	if len(payload) < 1 {
    208 		return 0, 0
    209 	}
    210 
    211 	paddingLen := payload[len(payload)-1]
    212 	t := uint(len(payload)-1) - uint(paddingLen)
    213 	// if len(payload) >= (paddingLen - 1) then the MSB of t is zero
    214 	good = byte(int32(^t) >> 31)
    215 
    216 	toCheck := 255 // the maximum possible padding length
    217 	// The length of the padded data is public, so we can use an if here
    218 	if toCheck+1 > len(payload) {
    219 		toCheck = len(payload) - 1
    220 	}
    221 
    222 	for i := 0; i < toCheck; i++ {
    223 		t := uint(paddingLen) - uint(i)
    224 		// if i <= paddingLen then the MSB of t is zero
    225 		mask := byte(int32(^t) >> 31)
    226 		b := payload[len(payload)-1-i]
    227 		good &^= mask&paddingLen ^ mask&b
    228 	}
    229 
    230 	// We AND together the bits of good and replicate the result across
    231 	// all the bits.
    232 	good &= good << 4
    233 	good &= good << 2
    234 	good &= good << 1
    235 	good = uint8(int8(good) >> 7)
    236 
    237 	toRemove = int(paddingLen) + 1
    238 	return
    239 }
    240 
    241 // extractPaddingSSL30 is a replacement for extractPadding in the case that the
    242 // protocol version is SSLv3. In this version, the contents of the padding
    243 // are random and cannot be checked.
    244 func extractPaddingSSL30(payload []byte) (toRemove int, good byte) {
    245 	if len(payload) < 1 {
    246 		return 0, 0
    247 	}
    248 
    249 	paddingLen := int(payload[len(payload)-1]) + 1
    250 	if paddingLen > len(payload) {
    251 		return 0, 0
    252 	}
    253 
    254 	return paddingLen, 255
    255 }
    256 
    257 func roundUp(a, b int) int {
    258 	return a + (b-a%b)%b
    259 }
    260 
    261 // cbcMode is an interface for block ciphers using cipher block chaining.
    262 type cbcMode interface {
    263 	cipher.BlockMode
    264 	SetIV([]byte)
    265 }
    266 
    267 // decrypt checks and strips the mac and decrypts the data in b. Returns a
    268 // success boolean, the number of bytes to skip from the start of the record in
    269 // order to get the application payload, and an optional alert value.
    270 func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) {
    271 	// pull out payload
    272 	payload := b.data[recordHeaderLen:]
    273 
    274 	macSize := 0
    275 	if hc.mac != nil {
    276 		macSize = hc.mac.Size()
    277 	}
    278 
    279 	paddingGood := byte(255)
    280 	paddingLen := 0
    281 	explicitIVLen := 0
    282 
    283 	// decrypt
    284 	if hc.cipher != nil {
    285 		switch c := hc.cipher.(type) {
    286 		case cipher.Stream:
    287 			c.XORKeyStream(payload, payload)
    288 		case aead:
    289 			explicitIVLen = c.explicitNonceLen()
    290 			if len(payload) < explicitIVLen {
    291 				return false, 0, alertBadRecordMAC
    292 			}
    293 			nonce := payload[:explicitIVLen]
    294 			payload = payload[explicitIVLen:]
    295 
    296 			if len(nonce) == 0 {
    297 				nonce = hc.seq[:]
    298 			}
    299 
    300 			copy(hc.additionalData[:], hc.seq[:])
    301 			copy(hc.additionalData[8:], b.data[:3])
    302 			n := len(payload) - c.Overhead()
    303 			hc.additionalData[11] = byte(n >> 8)
    304 			hc.additionalData[12] = byte(n)
    305 			var err error
    306 			payload, err = c.Open(payload[:0], nonce, payload, hc.additionalData[:])
    307 			if err != nil {
    308 				return false, 0, alertBadRecordMAC
    309 			}
    310 			b.resize(recordHeaderLen + explicitIVLen + len(payload))
    311 		case cbcMode:
    312 			blockSize := c.BlockSize()
    313 			if hc.version >= VersionTLS11 {
    314 				explicitIVLen = blockSize
    315 			}
    316 
    317 			if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) {
    318 				return false, 0, alertBadRecordMAC
    319 			}
    320 
    321 			if explicitIVLen > 0 {
    322 				c.SetIV(payload[:explicitIVLen])
    323 				payload = payload[explicitIVLen:]
    324 			}
    325 			c.CryptBlocks(payload, payload)
    326 			if hc.version == VersionSSL30 {
    327 				paddingLen, paddingGood = extractPaddingSSL30(payload)
    328 			} else {
    329 				paddingLen, paddingGood = extractPadding(payload)
    330 
    331 				// To protect against CBC padding oracles like Lucky13, the data
    332 				// past paddingLen (which is secret) is passed to the MAC
    333 				// function as extra data, to be fed into the HMAC after
    334 				// computing the digest. This makes the MAC constant time as
    335 				// long as the digest computation is constant time and does not
    336 				// affect the subsequent write.
    337 			}
    338 		default:
    339 			panic("unknown cipher type")
    340 		}
    341 	}
    342 
    343 	// check, strip mac
    344 	if hc.mac != nil {
    345 		if len(payload) < macSize {
    346 			return false, 0, alertBadRecordMAC
    347 		}
    348 
    349 		// strip mac off payload, b.data
    350 		n := len(payload) - macSize - paddingLen
    351 		n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 }
    352 		b.data[3] = byte(n >> 8)
    353 		b.data[4] = byte(n)
    354 		remoteMAC := payload[n : n+macSize]
    355 		localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n], payload[n+macSize:])
    356 
    357 		if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 {
    358 			return false, 0, alertBadRecordMAC
    359 		}
    360 		hc.inDigestBuf = localMAC
    361 
    362 		b.resize(recordHeaderLen + explicitIVLen + n)
    363 	}
    364 	hc.incSeq()
    365 
    366 	return true, recordHeaderLen + explicitIVLen, 0
    367 }
    368 
    369 // padToBlockSize calculates the needed padding block, if any, for a payload.
    370 // On exit, prefix aliases payload and extends to the end of the last full
    371 // block of payload. finalBlock is a fresh slice which contains the contents of
    372 // any suffix of payload as well as the needed padding to make finalBlock a
    373 // full block.
    374 func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) {
    375 	overrun := len(payload) % blockSize
    376 	paddingLen := blockSize - overrun
    377 	prefix = payload[:len(payload)-overrun]
    378 	finalBlock = make([]byte, blockSize)
    379 	copy(finalBlock, payload[len(payload)-overrun:])
    380 	for i := overrun; i < blockSize; i++ {
    381 		finalBlock[i] = byte(paddingLen - 1)
    382 	}
    383 	return
    384 }
    385 
    386 // encrypt encrypts and macs the data in b.
    387 func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) {
    388 	// mac
    389 	if hc.mac != nil {
    390 		mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:], nil)
    391 
    392 		n := len(b.data)
    393 		b.resize(n + len(mac))
    394 		copy(b.data[n:], mac)
    395 		hc.outDigestBuf = mac
    396 	}
    397 
    398 	payload := b.data[recordHeaderLen:]
    399 
    400 	// encrypt
    401 	if hc.cipher != nil {
    402 		switch c := hc.cipher.(type) {
    403 		case cipher.Stream:
    404 			c.XORKeyStream(payload, payload)
    405 		case aead:
    406 			payloadLen := len(b.data) - recordHeaderLen - explicitIVLen
    407 			b.resize(len(b.data) + c.Overhead())
    408 			nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
    409 			if len(nonce) == 0 {
    410 				nonce = hc.seq[:]
    411 			}
    412 			payload := b.data[recordHeaderLen+explicitIVLen:]
    413 			payload = payload[:payloadLen]
    414 
    415 			copy(hc.additionalData[:], hc.seq[:])
    416 			copy(hc.additionalData[8:], b.data[:3])
    417 			hc.additionalData[11] = byte(payloadLen >> 8)
    418 			hc.additionalData[12] = byte(payloadLen)
    419 
    420 			c.Seal(payload[:0], nonce, payload, hc.additionalData[:])
    421 		case cbcMode:
    422 			blockSize := c.BlockSize()
    423 			if explicitIVLen > 0 {
    424 				c.SetIV(payload[:explicitIVLen])
    425 				payload = payload[explicitIVLen:]
    426 			}
    427 			prefix, finalBlock := padToBlockSize(payload, blockSize)
    428 			b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock))
    429 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix)
    430 			c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock)
    431 		default:
    432 			panic("unknown cipher type")
    433 		}
    434 	}
    435 
    436 	// update length to include MAC and any block padding needed.
    437 	n := len(b.data) - recordHeaderLen
    438 	b.data[3] = byte(n >> 8)
    439 	b.data[4] = byte(n)
    440 	hc.incSeq()
    441 
    442 	return true, 0
    443 }
    444 
    445 // A block is a simple data buffer.
    446 type block struct {
    447 	data []byte
    448 	off  int // index for Read
    449 	link *block
    450 }
    451 
    452 // resize resizes block to be n bytes, growing if necessary.
    453 func (b *block) resize(n int) {
    454 	if n > cap(b.data) {
    455 		b.reserve(n)
    456 	}
    457 	b.data = b.data[0:n]
    458 }
    459 
    460 // reserve makes sure that block contains a capacity of at least n bytes.
    461 func (b *block) reserve(n int) {
    462 	if cap(b.data) >= n {
    463 		return
    464 	}
    465 	m := cap(b.data)
    466 	if m == 0 {
    467 		m = 1024
    468 	}
    469 	for m < n {
    470 		m *= 2
    471 	}
    472 	data := make([]byte, len(b.data), m)
    473 	copy(data, b.data)
    474 	b.data = data
    475 }
    476 
    477 // readFromUntil reads from r into b until b contains at least n bytes
    478 // or else returns an error.
    479 func (b *block) readFromUntil(r io.Reader, n int) error {
    480 	// quick case
    481 	if len(b.data) >= n {
    482 		return nil
    483 	}
    484 
    485 	// read until have enough.
    486 	b.reserve(n)
    487 	for {
    488 		m, err := r.Read(b.data[len(b.data):cap(b.data)])
    489 		b.data = b.data[0 : len(b.data)+m]
    490 		if len(b.data) >= n {
    491 			// TODO(bradfitz,agl): slightly suspicious
    492 			// that we're throwing away r.Read's err here.
    493 			break
    494 		}
    495 		if err != nil {
    496 			return err
    497 		}
    498 	}
    499 	return nil
    500 }
    501 
    502 func (b *block) Read(p []byte) (n int, err error) {
    503 	n = copy(p, b.data[b.off:])
    504 	b.off += n
    505 	return
    506 }
    507 
    508 // newBlock allocates a new block, from hc's free list if possible.
    509 func (hc *halfConn) newBlock() *block {
    510 	b := hc.bfree
    511 	if b == nil {
    512 		return new(block)
    513 	}
    514 	hc.bfree = b.link
    515 	b.link = nil
    516 	b.resize(0)
    517 	return b
    518 }
    519 
    520 // freeBlock returns a block to hc's free list.
    521 // The protocol is such that each side only has a block or two on
    522 // its free list at a time, so there's no need to worry about
    523 // trimming the list, etc.
    524 func (hc *halfConn) freeBlock(b *block) {
    525 	b.link = hc.bfree
    526 	hc.bfree = b
    527 }
    528 
    529 // splitBlock splits a block after the first n bytes,
    530 // returning a block with those n bytes and a
    531 // block with the remainder.  the latter may be nil.
    532 func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) {
    533 	if len(b.data) <= n {
    534 		return b, nil
    535 	}
    536 	bb := hc.newBlock()
    537 	bb.resize(len(b.data) - n)
    538 	copy(bb.data, b.data[n:])
    539 	b.data = b.data[0:n]
    540 	return b, bb
    541 }
    542 
    543 // RecordHeaderError results when a TLS record header is invalid.
    544 type RecordHeaderError struct {
    545 	// Msg contains a human readable string that describes the error.
    546 	Msg string
    547 	// RecordHeader contains the five bytes of TLS record header that
    548 	// triggered the error.
    549 	RecordHeader [5]byte
    550 }
    551 
    552 func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
    553 
    554 func (c *Conn) newRecordHeaderError(msg string) (err RecordHeaderError) {
    555 	err.Msg = msg
    556 	copy(err.RecordHeader[:], c.rawInput.data)
    557 	return err
    558 }
    559 
    560 // readRecord reads the next TLS record from the connection
    561 // and updates the record layer state.
    562 // c.in.Mutex <= L; c.input == nil.
    563 func (c *Conn) readRecord(want recordType) error {
    564 	// Caller must be in sync with connection:
    565 	// handshake data if handshake not yet completed,
    566 	// else application data.
    567 	switch want {
    568 	default:
    569 		c.sendAlert(alertInternalError)
    570 		return c.in.setErrorLocked(errors.New("tls: unknown record type requested"))
    571 	case recordTypeHandshake, recordTypeChangeCipherSpec:
    572 		if c.handshakeComplete {
    573 			c.sendAlert(alertInternalError)
    574 			return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested while not in handshake"))
    575 		}
    576 	case recordTypeApplicationData:
    577 		if !c.handshakeComplete {
    578 			c.sendAlert(alertInternalError)
    579 			return c.in.setErrorLocked(errors.New("tls: application data record requested while in handshake"))
    580 		}
    581 	}
    582 
    583 Again:
    584 	if c.rawInput == nil {
    585 		c.rawInput = c.in.newBlock()
    586 	}
    587 	b := c.rawInput
    588 
    589 	// Read header, payload.
    590 	if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil {
    591 		// RFC suggests that EOF without an alertCloseNotify is
    592 		// an error, but popular web sites seem to do this,
    593 		// so we can't make it an error.
    594 		// if err == io.EOF {
    595 		// 	err = io.ErrUnexpectedEOF
    596 		// }
    597 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    598 			c.in.setErrorLocked(err)
    599 		}
    600 		return err
    601 	}
    602 	typ := recordType(b.data[0])
    603 
    604 	// No valid TLS record has a type of 0x80, however SSLv2 handshakes
    605 	// start with a uint16 length where the MSB is set and the first record
    606 	// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
    607 	// an SSLv2 client.
    608 	if want == recordTypeHandshake && typ == 0x80 {
    609 		c.sendAlert(alertProtocolVersion)
    610 		return c.in.setErrorLocked(c.newRecordHeaderError("unsupported SSLv2 handshake received"))
    611 	}
    612 
    613 	vers := uint16(b.data[1])<<8 | uint16(b.data[2])
    614 	n := int(b.data[3])<<8 | int(b.data[4])
    615 	if c.haveVers && vers != c.vers {
    616 		c.sendAlert(alertProtocolVersion)
    617 		msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers)
    618 		return c.in.setErrorLocked(c.newRecordHeaderError(msg))
    619 	}
    620 	if n > maxCiphertext {
    621 		c.sendAlert(alertRecordOverflow)
    622 		msg := fmt.Sprintf("oversized record received with length %d", n)
    623 		return c.in.setErrorLocked(c.newRecordHeaderError(msg))
    624 	}
    625 	if !c.haveVers {
    626 		// First message, be extra suspicious: this might not be a TLS
    627 		// client. Bail out before reading a full 'body', if possible.
    628 		// The current max version is 3.3 so if the version is >= 16.0,
    629 		// it's probably not real.
    630 		if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 {
    631 			c.sendAlert(alertUnexpectedMessage)
    632 			return c.in.setErrorLocked(c.newRecordHeaderError("first record does not look like a TLS handshake"))
    633 		}
    634 	}
    635 	if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil {
    636 		if err == io.EOF {
    637 			err = io.ErrUnexpectedEOF
    638 		}
    639 		if e, ok := err.(net.Error); !ok || !e.Temporary() {
    640 			c.in.setErrorLocked(err)
    641 		}
    642 		return err
    643 	}
    644 
    645 	// Process message.
    646 	b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n)
    647 	ok, off, alertValue := c.in.decrypt(b)
    648 	if !ok {
    649 		c.in.freeBlock(b)
    650 		return c.in.setErrorLocked(c.sendAlert(alertValue))
    651 	}
    652 	b.off = off
    653 	data := b.data[b.off:]
    654 	if len(data) > maxPlaintext {
    655 		err := c.sendAlert(alertRecordOverflow)
    656 		c.in.freeBlock(b)
    657 		return c.in.setErrorLocked(err)
    658 	}
    659 
    660 	switch typ {
    661 	default:
    662 		c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    663 
    664 	case recordTypeAlert:
    665 		if len(data) != 2 {
    666 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    667 			break
    668 		}
    669 		if alert(data[1]) == alertCloseNotify {
    670 			c.in.setErrorLocked(io.EOF)
    671 			break
    672 		}
    673 		switch data[0] {
    674 		case alertLevelWarning:
    675 			// drop on the floor
    676 			c.in.freeBlock(b)
    677 			goto Again
    678 		case alertLevelError:
    679 			c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])})
    680 		default:
    681 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    682 		}
    683 
    684 	case recordTypeChangeCipherSpec:
    685 		if typ != want || len(data) != 1 || data[0] != 1 {
    686 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    687 			break
    688 		}
    689 		err := c.in.changeCipherSpec()
    690 		if err != nil {
    691 			c.in.setErrorLocked(c.sendAlert(err.(alert)))
    692 		}
    693 
    694 	case recordTypeApplicationData:
    695 		if typ != want {
    696 			c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    697 			break
    698 		}
    699 		c.input = b
    700 		b = nil
    701 
    702 	case recordTypeHandshake:
    703 		// TODO(rsc): Should at least pick off connection close.
    704 		if typ != want && !(c.isClient && c.config.Renegotiation != RenegotiateNever) {
    705 			return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation))
    706 		}
    707 		c.hand.Write(data)
    708 	}
    709 
    710 	if b != nil {
    711 		c.in.freeBlock(b)
    712 	}
    713 	return c.in.err
    714 }
    715 
    716 // sendAlert sends a TLS alert message.
    717 // c.out.Mutex <= L.
    718 func (c *Conn) sendAlertLocked(err alert) error {
    719 	switch err {
    720 	case alertNoRenegotiation, alertCloseNotify:
    721 		c.tmp[0] = alertLevelWarning
    722 	default:
    723 		c.tmp[0] = alertLevelError
    724 	}
    725 	c.tmp[1] = byte(err)
    726 
    727 	_, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2])
    728 	if err == alertCloseNotify {
    729 		// closeNotify is a special case in that it isn't an error.
    730 		return writeErr
    731 	}
    732 
    733 	return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err})
    734 }
    735 
    736 // sendAlert sends a TLS alert message.
    737 // L < c.out.Mutex.
    738 func (c *Conn) sendAlert(err alert) error {
    739 	c.out.Lock()
    740 	defer c.out.Unlock()
    741 	return c.sendAlertLocked(err)
    742 }
    743 
    744 const (
    745 	// tcpMSSEstimate is a conservative estimate of the TCP maximum segment
    746 	// size (MSS). A constant is used, rather than querying the kernel for
    747 	// the actual MSS, to avoid complexity. The value here is the IPv6
    748 	// minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40
    749 	// bytes) and a TCP header with timestamps (32 bytes).
    750 	tcpMSSEstimate = 1208
    751 
    752 	// recordSizeBoostThreshold is the number of bytes of application data
    753 	// sent after which the TLS record size will be increased to the
    754 	// maximum.
    755 	recordSizeBoostThreshold = 128 * 1024
    756 )
    757 
    758 // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
    759 // next application data record. There is the following trade-off:
    760 //
    761 //   - For latency-sensitive applications, such as web browsing, each TLS
    762 //     record should fit in one TCP segment.
    763 //   - For throughput-sensitive applications, such as large file transfers,
    764 //     larger TLS records better amortize framing and encryption overheads.
    765 //
    766 // A simple heuristic that works well in practice is to use small records for
    767 // the first 1MB of data, then use larger records for subsequent data, and
    768 // reset back to smaller records after the connection becomes idle. See "High
    769 // Performance Web Networking", Chapter 4, or:
    770 // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/
    771 //
    772 // In the interests of simplicity and determinism, this code does not attempt
    773 // to reset the record size once the connection is idle, however.
    774 //
    775 // c.out.Mutex <= L.
    776 func (c *Conn) maxPayloadSizeForWrite(typ recordType, explicitIVLen int) int {
    777 	if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData {
    778 		return maxPlaintext
    779 	}
    780 
    781 	if c.bytesSent >= recordSizeBoostThreshold {
    782 		return maxPlaintext
    783 	}
    784 
    785 	// Subtract TLS overheads to get the maximum payload size.
    786 	macSize := 0
    787 	if c.out.mac != nil {
    788 		macSize = c.out.mac.Size()
    789 	}
    790 
    791 	payloadBytes := tcpMSSEstimate - recordHeaderLen - explicitIVLen
    792 	if c.out.cipher != nil {
    793 		switch ciph := c.out.cipher.(type) {
    794 		case cipher.Stream:
    795 			payloadBytes -= macSize
    796 		case cipher.AEAD:
    797 			payloadBytes -= ciph.Overhead()
    798 		case cbcMode:
    799 			blockSize := ciph.BlockSize()
    800 			// The payload must fit in a multiple of blockSize, with
    801 			// room for at least one padding byte.
    802 			payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1
    803 			// The MAC is appended before padding so affects the
    804 			// payload size directly.
    805 			payloadBytes -= macSize
    806 		default:
    807 			panic("unknown cipher type")
    808 		}
    809 	}
    810 
    811 	// Allow packet growth in arithmetic progression up to max.
    812 	pkt := c.packetsSent
    813 	c.packetsSent++
    814 	if pkt > 1000 {
    815 		return maxPlaintext // avoid overflow in multiply below
    816 	}
    817 
    818 	n := payloadBytes * int(pkt+1)
    819 	if n > maxPlaintext {
    820 		n = maxPlaintext
    821 	}
    822 	return n
    823 }
    824 
    825 // c.out.Mutex <= L.
    826 func (c *Conn) write(data []byte) (int, error) {
    827 	if c.buffering {
    828 		c.sendBuf = append(c.sendBuf, data...)
    829 		return len(data), nil
    830 	}
    831 
    832 	n, err := c.conn.Write(data)
    833 	c.bytesSent += int64(n)
    834 	return n, err
    835 }
    836 
    837 func (c *Conn) flush() (int, error) {
    838 	if len(c.sendBuf) == 0 {
    839 		return 0, nil
    840 	}
    841 
    842 	n, err := c.conn.Write(c.sendBuf)
    843 	c.bytesSent += int64(n)
    844 	c.sendBuf = nil
    845 	c.buffering = false
    846 	return n, err
    847 }
    848 
    849 // writeRecordLocked writes a TLS record with the given type and payload to the
    850 // connection and updates the record layer state.
    851 // c.out.Mutex <= L.
    852 func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) {
    853 	b := c.out.newBlock()
    854 	defer c.out.freeBlock(b)
    855 
    856 	var n int
    857 	for len(data) > 0 {
    858 		explicitIVLen := 0
    859 		explicitIVIsSeq := false
    860 
    861 		var cbc cbcMode
    862 		if c.out.version >= VersionTLS11 {
    863 			var ok bool
    864 			if cbc, ok = c.out.cipher.(cbcMode); ok {
    865 				explicitIVLen = cbc.BlockSize()
    866 			}
    867 		}
    868 		if explicitIVLen == 0 {
    869 			if c, ok := c.out.cipher.(aead); ok {
    870 				explicitIVLen = c.explicitNonceLen()
    871 
    872 				// The AES-GCM construction in TLS has an
    873 				// explicit nonce so that the nonce can be
    874 				// random. However, the nonce is only 8 bytes
    875 				// which is too small for a secure, random
    876 				// nonce. Therefore we use the sequence number
    877 				// as the nonce.
    878 				explicitIVIsSeq = explicitIVLen > 0
    879 			}
    880 		}
    881 		m := len(data)
    882 		if maxPayload := c.maxPayloadSizeForWrite(typ, explicitIVLen); m > maxPayload {
    883 			m = maxPayload
    884 		}
    885 		b.resize(recordHeaderLen + explicitIVLen + m)
    886 		b.data[0] = byte(typ)
    887 		vers := c.vers
    888 		if vers == 0 {
    889 			// Some TLS servers fail if the record version is
    890 			// greater than TLS 1.0 for the initial ClientHello.
    891 			vers = VersionTLS10
    892 		}
    893 		b.data[1] = byte(vers >> 8)
    894 		b.data[2] = byte(vers)
    895 		b.data[3] = byte(m >> 8)
    896 		b.data[4] = byte(m)
    897 		if explicitIVLen > 0 {
    898 			explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen]
    899 			if explicitIVIsSeq {
    900 				copy(explicitIV, c.out.seq[:])
    901 			} else {
    902 				if _, err := io.ReadFull(c.config.rand(), explicitIV); err != nil {
    903 					return n, err
    904 				}
    905 			}
    906 		}
    907 		copy(b.data[recordHeaderLen+explicitIVLen:], data)
    908 		c.out.encrypt(b, explicitIVLen)
    909 		if _, err := c.write(b.data); err != nil {
    910 			return n, err
    911 		}
    912 		n += m
    913 		data = data[m:]
    914 	}
    915 
    916 	if typ == recordTypeChangeCipherSpec {
    917 		if err := c.out.changeCipherSpec(); err != nil {
    918 			return n, c.sendAlertLocked(err.(alert))
    919 		}
    920 	}
    921 
    922 	return n, nil
    923 }
    924 
    925 // writeRecord writes a TLS record with the given type and payload to the
    926 // connection and updates the record layer state.
    927 // L < c.out.Mutex.
    928 func (c *Conn) writeRecord(typ recordType, data []byte) (int, error) {
    929 	c.out.Lock()
    930 	defer c.out.Unlock()
    931 
    932 	return c.writeRecordLocked(typ, data)
    933 }
    934 
    935 // readHandshake reads the next handshake message from
    936 // the record layer.
    937 // c.in.Mutex < L; c.out.Mutex < L.
    938 func (c *Conn) readHandshake() (interface{}, error) {
    939 	for c.hand.Len() < 4 {
    940 		if err := c.in.err; err != nil {
    941 			return nil, err
    942 		}
    943 		if err := c.readRecord(recordTypeHandshake); err != nil {
    944 			return nil, err
    945 		}
    946 	}
    947 
    948 	data := c.hand.Bytes()
    949 	n := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
    950 	if n > maxHandshake {
    951 		c.sendAlertLocked(alertInternalError)
    952 		return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake))
    953 	}
    954 	for c.hand.Len() < 4+n {
    955 		if err := c.in.err; err != nil {
    956 			return nil, err
    957 		}
    958 		if err := c.readRecord(recordTypeHandshake); err != nil {
    959 			return nil, err
    960 		}
    961 	}
    962 	data = c.hand.Next(4 + n)
    963 	var m handshakeMessage
    964 	switch data[0] {
    965 	case typeHelloRequest:
    966 		m = new(helloRequestMsg)
    967 	case typeClientHello:
    968 		m = new(clientHelloMsg)
    969 	case typeServerHello:
    970 		m = new(serverHelloMsg)
    971 	case typeNewSessionTicket:
    972 		m = new(newSessionTicketMsg)
    973 	case typeCertificate:
    974 		m = new(certificateMsg)
    975 	case typeCertificateRequest:
    976 		m = &certificateRequestMsg{
    977 			hasSignatureAndHash: c.vers >= VersionTLS12,
    978 		}
    979 	case typeCertificateStatus:
    980 		m = new(certificateStatusMsg)
    981 	case typeServerKeyExchange:
    982 		m = new(serverKeyExchangeMsg)
    983 	case typeServerHelloDone:
    984 		m = new(serverHelloDoneMsg)
    985 	case typeClientKeyExchange:
    986 		m = new(clientKeyExchangeMsg)
    987 	case typeCertificateVerify:
    988 		m = &certificateVerifyMsg{
    989 			hasSignatureAndHash: c.vers >= VersionTLS12,
    990 		}
    991 	case typeNextProtocol:
    992 		m = new(nextProtoMsg)
    993 	case typeFinished:
    994 		m = new(finishedMsg)
    995 	default:
    996 		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
    997 	}
    998 
    999 	// The handshake message unmarshalers
   1000 	// expect to be able to keep references to data,
   1001 	// so pass in a fresh copy that won't be overwritten.
   1002 	data = append([]byte(nil), data...)
   1003 
   1004 	if !m.unmarshal(data) {
   1005 		return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
   1006 	}
   1007 	return m, nil
   1008 }
   1009 
   1010 var (
   1011 	errClosed   = errors.New("tls: use of closed connection")
   1012 	errShutdown = errors.New("tls: protocol is shutdown")
   1013 )
   1014 
   1015 // Write writes data to the connection.
   1016 func (c *Conn) Write(b []byte) (int, error) {
   1017 	// interlock with Close below
   1018 	for {
   1019 		x := atomic.LoadInt32(&c.activeCall)
   1020 		if x&1 != 0 {
   1021 			return 0, errClosed
   1022 		}
   1023 		if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) {
   1024 			defer atomic.AddInt32(&c.activeCall, -2)
   1025 			break
   1026 		}
   1027 	}
   1028 
   1029 	if err := c.Handshake(); err != nil {
   1030 		return 0, err
   1031 	}
   1032 
   1033 	c.out.Lock()
   1034 	defer c.out.Unlock()
   1035 
   1036 	if err := c.out.err; err != nil {
   1037 		return 0, err
   1038 	}
   1039 
   1040 	if !c.handshakeComplete {
   1041 		return 0, alertInternalError
   1042 	}
   1043 
   1044 	if c.closeNotifySent {
   1045 		return 0, errShutdown
   1046 	}
   1047 
   1048 	// SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext
   1049 	// attack when using block mode ciphers due to predictable IVs.
   1050 	// This can be prevented by splitting each Application Data
   1051 	// record into two records, effectively randomizing the IV.
   1052 	//
   1053 	// http://www.openssl.org/~bodo/tls-cbc.txt
   1054 	// https://bugzilla.mozilla.org/show_bug.cgi?id=665814
   1055 	// http://www.imperialviolet.org/2012/01/15/beastfollowup.html
   1056 
   1057 	var m int
   1058 	if len(b) > 1 && c.vers <= VersionTLS10 {
   1059 		if _, ok := c.out.cipher.(cipher.BlockMode); ok {
   1060 			n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1])
   1061 			if err != nil {
   1062 				return n, c.out.setErrorLocked(err)
   1063 			}
   1064 			m, b = 1, b[1:]
   1065 		}
   1066 	}
   1067 
   1068 	n, err := c.writeRecordLocked(recordTypeApplicationData, b)
   1069 	return n + m, c.out.setErrorLocked(err)
   1070 }
   1071 
   1072 // handleRenegotiation processes a HelloRequest handshake message.
   1073 // c.in.Mutex <= L
   1074 func (c *Conn) handleRenegotiation() error {
   1075 	msg, err := c.readHandshake()
   1076 	if err != nil {
   1077 		return err
   1078 	}
   1079 
   1080 	_, ok := msg.(*helloRequestMsg)
   1081 	if !ok {
   1082 		c.sendAlert(alertUnexpectedMessage)
   1083 		return alertUnexpectedMessage
   1084 	}
   1085 
   1086 	if !c.isClient {
   1087 		return c.sendAlert(alertNoRenegotiation)
   1088 	}
   1089 
   1090 	switch c.config.Renegotiation {
   1091 	case RenegotiateNever:
   1092 		return c.sendAlert(alertNoRenegotiation)
   1093 	case RenegotiateOnceAsClient:
   1094 		if c.handshakes > 1 {
   1095 			return c.sendAlert(alertNoRenegotiation)
   1096 		}
   1097 	case RenegotiateFreelyAsClient:
   1098 		// Ok.
   1099 	default:
   1100 		c.sendAlert(alertInternalError)
   1101 		return errors.New("tls: unknown Renegotiation value")
   1102 	}
   1103 
   1104 	c.handshakeMutex.Lock()
   1105 	defer c.handshakeMutex.Unlock()
   1106 
   1107 	c.handshakeComplete = false
   1108 	if c.handshakeErr = c.clientHandshake(); c.handshakeErr == nil {
   1109 		c.handshakes++
   1110 	}
   1111 	return c.handshakeErr
   1112 }
   1113 
   1114 // Read can be made to time out and return a net.Error with Timeout() == true
   1115 // after a fixed time limit; see SetDeadline and SetReadDeadline.
   1116 func (c *Conn) Read(b []byte) (n int, err error) {
   1117 	if err = c.Handshake(); err != nil {
   1118 		return
   1119 	}
   1120 	if len(b) == 0 {
   1121 		// Put this after Handshake, in case people were calling
   1122 		// Read(nil) for the side effect of the Handshake.
   1123 		return
   1124 	}
   1125 
   1126 	c.in.Lock()
   1127 	defer c.in.Unlock()
   1128 
   1129 	// Some OpenSSL servers send empty records in order to randomize the
   1130 	// CBC IV. So this loop ignores a limited number of empty records.
   1131 	const maxConsecutiveEmptyRecords = 100
   1132 	for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ {
   1133 		for c.input == nil && c.in.err == nil {
   1134 			if err := c.readRecord(recordTypeApplicationData); err != nil {
   1135 				// Soft error, like EAGAIN
   1136 				return 0, err
   1137 			}
   1138 			if c.hand.Len() > 0 {
   1139 				// We received handshake bytes, indicating the
   1140 				// start of a renegotiation.
   1141 				if err := c.handleRenegotiation(); err != nil {
   1142 					return 0, err
   1143 				}
   1144 			}
   1145 		}
   1146 		if err := c.in.err; err != nil {
   1147 			return 0, err
   1148 		}
   1149 
   1150 		n, err = c.input.Read(b)
   1151 		if c.input.off >= len(c.input.data) {
   1152 			c.in.freeBlock(c.input)
   1153 			c.input = nil
   1154 		}
   1155 
   1156 		// If a close-notify alert is waiting, read it so that
   1157 		// we can return (n, EOF) instead of (n, nil), to signal
   1158 		// to the HTTP response reading goroutine that the
   1159 		// connection is now closed. This eliminates a race
   1160 		// where the HTTP response reading goroutine would
   1161 		// otherwise not observe the EOF until its next read,
   1162 		// by which time a client goroutine might have already
   1163 		// tried to reuse the HTTP connection for a new
   1164 		// request.
   1165 		// See https://codereview.appspot.com/76400046
   1166 		// and https://golang.org/issue/3514
   1167 		if ri := c.rawInput; ri != nil &&
   1168 			n != 0 && err == nil &&
   1169 			c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert {
   1170 			if recErr := c.readRecord(recordTypeApplicationData); recErr != nil {
   1171 				err = recErr // will be io.EOF on closeNotify
   1172 			}
   1173 		}
   1174 
   1175 		if n != 0 || err != nil {
   1176 			return n, err
   1177 		}
   1178 	}
   1179 
   1180 	return 0, io.ErrNoProgress
   1181 }
   1182 
   1183 // Close closes the connection.
   1184 func (c *Conn) Close() error {
   1185 	// Interlock with Conn.Write above.
   1186 	var x int32
   1187 	for {
   1188 		x = atomic.LoadInt32(&c.activeCall)
   1189 		if x&1 != 0 {
   1190 			return errClosed
   1191 		}
   1192 		if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) {
   1193 			break
   1194 		}
   1195 	}
   1196 	if x != 0 {
   1197 		// io.Writer and io.Closer should not be used concurrently.
   1198 		// If Close is called while a Write is currently in-flight,
   1199 		// interpret that as a sign that this Close is really just
   1200 		// being used to break the Write and/or clean up resources and
   1201 		// avoid sending the alertCloseNotify, which may block
   1202 		// waiting on handshakeMutex or the c.out mutex.
   1203 		return c.conn.Close()
   1204 	}
   1205 
   1206 	var alertErr error
   1207 
   1208 	c.handshakeMutex.Lock()
   1209 	defer c.handshakeMutex.Unlock()
   1210 	if c.handshakeComplete {
   1211 		alertErr = c.closeNotify()
   1212 	}
   1213 
   1214 	if err := c.conn.Close(); err != nil {
   1215 		return err
   1216 	}
   1217 	return alertErr
   1218 }
   1219 
   1220 var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete")
   1221 
   1222 // CloseWrite shuts down the writing side of the connection. It should only be
   1223 // called once the handshake has completed and does not call CloseWrite on the
   1224 // underlying connection. Most callers should just use Close.
   1225 func (c *Conn) CloseWrite() error {
   1226 	c.handshakeMutex.Lock()
   1227 	defer c.handshakeMutex.Unlock()
   1228 	if !c.handshakeComplete {
   1229 		return errEarlyCloseWrite
   1230 	}
   1231 
   1232 	return c.closeNotify()
   1233 }
   1234 
   1235 func (c *Conn) closeNotify() error {
   1236 	c.out.Lock()
   1237 	defer c.out.Unlock()
   1238 
   1239 	if !c.closeNotifySent {
   1240 		c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify)
   1241 		c.closeNotifySent = true
   1242 	}
   1243 	return c.closeNotifyErr
   1244 }
   1245 
   1246 // Handshake runs the client or server handshake
   1247 // protocol if it has not yet been run.
   1248 // Most uses of this package need not call Handshake
   1249 // explicitly: the first Read or Write will call it automatically.
   1250 func (c *Conn) Handshake() error {
   1251 	// c.handshakeErr and c.handshakeComplete are protected by
   1252 	// c.handshakeMutex. In order to perform a handshake, we need to lock
   1253 	// c.in also and c.handshakeMutex must be locked after c.in.
   1254 	//
   1255 	// However, if a Read() operation is hanging then it'll be holding the
   1256 	// lock on c.in and so taking it here would cause all operations that
   1257 	// need to check whether a handshake is pending (such as Write) to
   1258 	// block.
   1259 	//
   1260 	// Thus we first take c.handshakeMutex to check whether a handshake is
   1261 	// needed.
   1262 	//
   1263 	// If so then, previously, this code would unlock handshakeMutex and
   1264 	// then lock c.in and handshakeMutex in the correct order to run the
   1265 	// handshake. The problem was that it was possible for a Read to
   1266 	// complete the handshake once handshakeMutex was unlocked and then
   1267 	// keep c.in while waiting for network data. Thus a concurrent
   1268 	// operation could be blocked on c.in.
   1269 	//
   1270 	// Thus handshakeCond is used to signal that a goroutine is committed
   1271 	// to running the handshake and other goroutines can wait on it if they
   1272 	// need. handshakeCond is protected by handshakeMutex.
   1273 	c.handshakeMutex.Lock()
   1274 	defer c.handshakeMutex.Unlock()
   1275 
   1276 	for {
   1277 		if err := c.handshakeErr; err != nil {
   1278 			return err
   1279 		}
   1280 		if c.handshakeComplete {
   1281 			return nil
   1282 		}
   1283 		if c.handshakeCond == nil {
   1284 			break
   1285 		}
   1286 
   1287 		c.handshakeCond.Wait()
   1288 	}
   1289 
   1290 	// Set handshakeCond to indicate that this goroutine is committing to
   1291 	// running the handshake.
   1292 	c.handshakeCond = sync.NewCond(&c.handshakeMutex)
   1293 	c.handshakeMutex.Unlock()
   1294 
   1295 	c.in.Lock()
   1296 	defer c.in.Unlock()
   1297 
   1298 	c.handshakeMutex.Lock()
   1299 
   1300 	// The handshake cannot have completed when handshakeMutex was unlocked
   1301 	// because this goroutine set handshakeCond.
   1302 	if c.handshakeErr != nil || c.handshakeComplete {
   1303 		panic("handshake should not have been able to complete after handshakeCond was set")
   1304 	}
   1305 
   1306 	if c.isClient {
   1307 		c.handshakeErr = c.clientHandshake()
   1308 	} else {
   1309 		c.handshakeErr = c.serverHandshake()
   1310 	}
   1311 	if c.handshakeErr == nil {
   1312 		c.handshakes++
   1313 	} else {
   1314 		// If an error occurred during the hadshake try to flush the
   1315 		// alert that might be left in the buffer.
   1316 		c.flush()
   1317 	}
   1318 
   1319 	if c.handshakeErr == nil && !c.handshakeComplete {
   1320 		panic("handshake should have had a result.")
   1321 	}
   1322 
   1323 	// Wake any other goroutines that are waiting for this handshake to
   1324 	// complete.
   1325 	c.handshakeCond.Broadcast()
   1326 	c.handshakeCond = nil
   1327 
   1328 	return c.handshakeErr
   1329 }
   1330 
   1331 // ConnectionState returns basic TLS details about the connection.
   1332 func (c *Conn) ConnectionState() ConnectionState {
   1333 	c.handshakeMutex.Lock()
   1334 	defer c.handshakeMutex.Unlock()
   1335 
   1336 	var state ConnectionState
   1337 	state.HandshakeComplete = c.handshakeComplete
   1338 	state.ServerName = c.serverName
   1339 
   1340 	if c.handshakeComplete {
   1341 		state.Version = c.vers
   1342 		state.NegotiatedProtocol = c.clientProtocol
   1343 		state.DidResume = c.didResume
   1344 		state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback
   1345 		state.CipherSuite = c.cipherSuite
   1346 		state.PeerCertificates = c.peerCertificates
   1347 		state.VerifiedChains = c.verifiedChains
   1348 		state.SignedCertificateTimestamps = c.scts
   1349 		state.OCSPResponse = c.ocspResponse
   1350 		if !c.didResume {
   1351 			if c.clientFinishedIsFirst {
   1352 				state.TLSUnique = c.clientFinished[:]
   1353 			} else {
   1354 				state.TLSUnique = c.serverFinished[:]
   1355 			}
   1356 		}
   1357 	}
   1358 
   1359 	return state
   1360 }
   1361 
   1362 // OCSPResponse returns the stapled OCSP response from the TLS server, if
   1363 // any. (Only valid for client connections.)
   1364 func (c *Conn) OCSPResponse() []byte {
   1365 	c.handshakeMutex.Lock()
   1366 	defer c.handshakeMutex.Unlock()
   1367 
   1368 	return c.ocspResponse
   1369 }
   1370 
   1371 // VerifyHostname checks that the peer certificate chain is valid for
   1372 // connecting to host. If so, it returns nil; if not, it returns an error
   1373 // describing the problem.
   1374 func (c *Conn) VerifyHostname(host string) error {
   1375 	c.handshakeMutex.Lock()
   1376 	defer c.handshakeMutex.Unlock()
   1377 	if !c.isClient {
   1378 		return errors.New("tls: VerifyHostname called on TLS server connection")
   1379 	}
   1380 	if !c.handshakeComplete {
   1381 		return errors.New("tls: handshake has not yet been performed")
   1382 	}
   1383 	if len(c.verifiedChains) == 0 {
   1384 		return errors.New("tls: handshake did not verify certificate chain")
   1385 	}
   1386 	return c.peerCertificates[0].VerifyHostname(host)
   1387 }
   1388