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