gitee.com/lh-her-team/common@v1.5.1/crypto/tls/conn.go (about)

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