github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/crypto/tls/conn.go (about)

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