github.com/hellobchain/newcryptosm@v0.0.0-20221019060107-edb949a317e9/tls/conn.go (about)

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