github.com/sagernet/gvisor@v0.0.0-20240428053021-e691de28565f/pkg/tcpip/transport/tcp/connect.go (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     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  package tcp
    16  
    17  import (
    18  	"crypto/sha256"
    19  	"encoding/binary"
    20  	"fmt"
    21  	"math"
    22  	"time"
    23  
    24  	"github.com/sagernet/gvisor/pkg/sync"
    25  	"github.com/sagernet/gvisor/pkg/tcpip"
    26  	"github.com/sagernet/gvisor/pkg/tcpip/checksum"
    27  	"github.com/sagernet/gvisor/pkg/tcpip/header"
    28  	"github.com/sagernet/gvisor/pkg/tcpip/seqnum"
    29  	"github.com/sagernet/gvisor/pkg/tcpip/stack"
    30  	"github.com/sagernet/gvisor/pkg/waiter"
    31  )
    32  
    33  // InitialRTO is the initial retransmission timeout.
    34  // https://github.com/torvalds/linux/blob/7c636d4d20f/include/net/tcp.h#L142
    35  const InitialRTO = time.Second
    36  
    37  // maxSegmentsPerWake is the maximum number of segments to process in the main
    38  // protocol goroutine per wake-up. Yielding [after this number of segments are
    39  // processed] allows other events to be processed as well (e.g., timeouts,
    40  // resets, etc.).
    41  const maxSegmentsPerWake = 100
    42  
    43  type handshakeState int
    44  
    45  // The following are the possible states of the TCP connection during a 3-way
    46  // handshake. A depiction of the states and transitions can be found in RFC 793,
    47  // page 23.
    48  const (
    49  	handshakeSynSent handshakeState = iota
    50  	handshakeSynRcvd
    51  	handshakeCompleted
    52  )
    53  
    54  const (
    55  	// Maximum space available for options.
    56  	maxOptionSize = 40
    57  )
    58  
    59  // handshake holds the state used during a TCP 3-way handshake.
    60  //
    61  // NOTE: handshake.ep.mu is held during handshake processing. It is released if
    62  // we are going to block and reacquired when we start processing an event.
    63  //
    64  // +stateify savable
    65  type handshake struct {
    66  	ep       *Endpoint
    67  	listenEP *Endpoint
    68  	state    handshakeState
    69  	active   bool
    70  	flags    header.TCPFlags
    71  	ackNum   seqnum.Value
    72  
    73  	// iss is the initial send sequence number, as defined in RFC 793.
    74  	iss seqnum.Value
    75  
    76  	// rcvWnd is the receive window, as defined in RFC 793.
    77  	rcvWnd seqnum.Size
    78  
    79  	// sndWnd is the send window, as defined in RFC 793.
    80  	sndWnd seqnum.Size
    81  
    82  	// mss is the maximum segment size received from the peer.
    83  	mss uint16
    84  
    85  	// sndWndScale is the send window scale, as defined in RFC 1323. A
    86  	// negative value means no scaling is supported by the peer.
    87  	sndWndScale int
    88  
    89  	// rcvWndScale is the receive window scale, as defined in RFC 1323.
    90  	rcvWndScale int
    91  
    92  	// startTime is the time at which the first SYN/SYN-ACK was sent.
    93  	startTime tcpip.MonotonicTime
    94  
    95  	// deferAccept if non-zero will drop the final ACK for a passive
    96  	// handshake till an ACK segment with data is received or the timeout is
    97  	// hit.
    98  	deferAccept time.Duration
    99  
   100  	// acked is true if the final ACK for a 3-way handshake has
   101  	// been received. This is required to stop retransmitting the
   102  	// original SYN-ACK when deferAccept is enabled.
   103  	acked bool
   104  
   105  	// sendSYNOpts is the cached values for the SYN options to be sent.
   106  	sendSYNOpts header.TCPSynOptions
   107  
   108  	// sampleRTTWithTSOnly is true when the segment was retransmitted or we can't
   109  	// tell; then RTT can only be sampled when the incoming segment has timestamp
   110  	// options enabled.
   111  	sampleRTTWithTSOnly bool
   112  
   113  	// retransmitTimer is used to retransmit SYN/SYN-ACK with exponential backoff
   114  	// till handshake is either completed or timesout.
   115  	retransmitTimer *backoffTimer `state:"nosave"`
   116  }
   117  
   118  // timerHandler takes a handler function for a timer and returns a function that
   119  // will invoke the provided handler with the endpoint mutex held. In addition
   120  // the returned function will perform any cleanup that may be required if the
   121  // timer handler returns an error. In the case of no errors it will notify the
   122  // processor if there are pending segments that need to be processed.
   123  //
   124  // NOTE: e.mu is held for the duration of the call to f().
   125  func timerHandler(e *Endpoint, f func() tcpip.Error) func() {
   126  	return func() {
   127  		e.mu.Lock()
   128  		if err := f(); err != nil {
   129  			e.lastErrorMu.Lock()
   130  			// If the handler timed out and we have a lastError recorded (maybe due
   131  			// to an ICMP message received), promote it to be the hard error.
   132  			if _, isTimeout := err.(*tcpip.ErrTimeout); e.lastError != nil && isTimeout {
   133  				e.hardError = e.lastError
   134  			} else {
   135  				e.hardError = err
   136  			}
   137  			e.lastError = err
   138  			e.lastErrorMu.Unlock()
   139  			e.cleanupLocked()
   140  			e.setEndpointState(StateError)
   141  			e.mu.Unlock()
   142  			e.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)
   143  			return
   144  		}
   145  		processor := e.protocol.dispatcher.selectProcessor(e.ID)
   146  		e.mu.Unlock()
   147  
   148  		// notify processor if there are pending segments to be
   149  		// processed.
   150  		if !e.segmentQueue.empty() {
   151  			processor.queueEndpoint(e)
   152  		}
   153  	}
   154  }
   155  
   156  // +checklocks:e.mu
   157  // +checklocksacquire:h.ep.mu
   158  func (e *Endpoint) newHandshake() (h *handshake) {
   159  	h = &handshake{
   160  		ep:          e,
   161  		active:      true,
   162  		rcvWnd:      seqnum.Size(e.initialReceiveWindow()),
   163  		rcvWndScale: e.rcvWndScaleForHandshake(),
   164  	}
   165  	h.ep.AssertLockHeld(e)
   166  	h.resetState()
   167  	// Store reference to handshake state in endpoint.
   168  	e.h = h
   169  	// By the time handshake is created, e.ID is already initialized.
   170  	e.TSOffset = e.protocol.tsOffset(e.ID.LocalAddress, e.ID.RemoteAddress)
   171  	timer, err := newBackoffTimer(h.ep.stack.Clock(), InitialRTO, MaxRTO, timerHandler(e, h.retransmitHandlerLocked))
   172  	if err != nil {
   173  		panic(fmt.Sprintf("newBackOffTimer(_, %s, %s, _) failed: %s", InitialRTO, MaxRTO, err))
   174  	}
   175  	h.retransmitTimer = timer
   176  	return h
   177  }
   178  
   179  // +checklocks:e.mu
   180  // +checklocksacquire:h.ep.mu
   181  func (e *Endpoint) newPassiveHandshake(isn, irs seqnum.Value, opts header.TCPSynOptions, deferAccept time.Duration) (h *handshake) {
   182  	h = e.newHandshake()
   183  	h.resetToSynRcvd(isn, irs, opts, deferAccept)
   184  	return h
   185  }
   186  
   187  // FindWndScale determines the window scale to use for the given maximum window
   188  // size.
   189  func FindWndScale(wnd seqnum.Size) int {
   190  	if wnd < 0x10000 {
   191  		return 0
   192  	}
   193  
   194  	max := seqnum.Size(math.MaxUint16)
   195  	s := 0
   196  	for wnd > max && s < header.MaxWndScale {
   197  		s++
   198  		max <<= 1
   199  	}
   200  
   201  	return s
   202  }
   203  
   204  // resetState resets the state of the handshake object such that it becomes
   205  // ready for a new 3-way handshake.
   206  func (h *handshake) resetState() {
   207  	h.state = handshakeSynSent
   208  	h.flags = header.TCPFlagSyn
   209  	h.ackNum = 0
   210  	h.mss = 0
   211  	h.iss = generateSecureISN(h.ep.TransportEndpointInfo.ID, h.ep.stack.Clock(), h.ep.protocol.seqnumSecret)
   212  }
   213  
   214  // generateSecureISN generates a secure Initial Sequence number based on the
   215  // recommendation here https://tools.ietf.org/html/rfc6528#page-3.
   216  func generateSecureISN(id stack.TransportEndpointID, clock tcpip.Clock, seed [16]byte) seqnum.Value {
   217  	isnHasher := sha256.New()
   218  
   219  	// Per hash.Hash.Writer:
   220  	//
   221  	// It never returns an error.
   222  	_, _ = isnHasher.Write(seed[:])
   223  	_, _ = isnHasher.Write(id.LocalAddress.AsSlice())
   224  	_, _ = isnHasher.Write(id.RemoteAddress.AsSlice())
   225  	portBuf := make([]byte, 2)
   226  	binary.LittleEndian.PutUint16(portBuf, id.LocalPort)
   227  	_, _ = isnHasher.Write(portBuf)
   228  	binary.LittleEndian.PutUint16(portBuf, id.RemotePort)
   229  	_, _ = isnHasher.Write(portBuf)
   230  	// The time period here is 64ns. This is similar to what linux uses
   231  	// generate a sequence number that overlaps less than one
   232  	// time per MSL (2 minutes).
   233  	//
   234  	// A 64ns clock ticks 10^9/64 = 15625000) times in a second.
   235  	// To wrap the whole 32 bit space would require
   236  	// 2^32/1562500 ~ 274 seconds.
   237  	//
   238  	// Which sort of guarantees that we won't reuse the ISN for a new
   239  	// connection for the same tuple for at least 274s.
   240  	hash := binary.LittleEndian.Uint32(isnHasher.Sum(nil)[:4])
   241  	isn := hash + uint32(clock.NowMonotonic().Sub(tcpip.MonotonicTime{}).Nanoseconds()>>6)
   242  	return seqnum.Value(isn)
   243  }
   244  
   245  // effectiveRcvWndScale returns the effective receive window scale to be used.
   246  // If the peer doesn't support window scaling, the effective rcv wnd scale is
   247  // zero; otherwise it's the value calculated based on the initial rcv wnd.
   248  func (h *handshake) effectiveRcvWndScale() uint8 {
   249  	if h.sndWndScale < 0 {
   250  		return 0
   251  	}
   252  	return uint8(h.rcvWndScale)
   253  }
   254  
   255  // resetToSynRcvd resets the state of the handshake object to the SYN-RCVD
   256  // state.
   257  // +checklocks:h.ep.mu
   258  func (h *handshake) resetToSynRcvd(iss seqnum.Value, irs seqnum.Value, opts header.TCPSynOptions, deferAccept time.Duration) {
   259  	h.active = false
   260  	h.state = handshakeSynRcvd
   261  	h.flags = header.TCPFlagSyn | header.TCPFlagAck
   262  	h.iss = iss
   263  	h.ackNum = irs + 1
   264  	h.mss = opts.MSS
   265  	h.sndWndScale = opts.WS
   266  	h.deferAccept = deferAccept
   267  	h.ep.setEndpointState(StateSynRecv)
   268  }
   269  
   270  // checkAck checks if the ACK number, if present, of a segment received during
   271  // a TCP 3-way handshake is valid.
   272  func (h *handshake) checkAck(s *segment) bool {
   273  	return !(s.flags.Contains(header.TCPFlagAck) && s.ackNumber != h.iss+1)
   274  }
   275  
   276  // synSentState handles a segment received when the TCP 3-way handshake is in
   277  // the SYN-SENT state.
   278  // +checklocks:h.ep.mu
   279  func (h *handshake) synSentState(s *segment) tcpip.Error {
   280  	// RFC 793, page 37, states that in the SYN-SENT state, a reset is
   281  	// acceptable if the ack field acknowledges the SYN.
   282  	if s.flags.Contains(header.TCPFlagRst) {
   283  		if s.flags.Contains(header.TCPFlagAck) && s.ackNumber == h.iss+1 {
   284  			// RFC 793, page 67, states that "If the RST bit is set [and] If the ACK
   285  			// was acceptable then signal the user "error: connection reset", drop
   286  			// the segment, enter CLOSED state, delete TCB, and return."
   287  			// Although the RFC above calls out ECONNRESET, Linux actually returns
   288  			// ECONNREFUSED here so we do as well.
   289  			return &tcpip.ErrConnectionRefused{}
   290  		}
   291  		return nil
   292  	}
   293  
   294  	if !h.checkAck(s) {
   295  		// RFC 793, page 72 (https://datatracker.ietf.org/doc/html/rfc793#page-72):
   296  		//   If the segment acknowledgment is not acceptable, form a reset segment,
   297  		//        <SEQ=SEG.ACK><CTL=RST>
   298  		//   and send it.
   299  		h.ep.sendEmptyRaw(header.TCPFlagRst, s.ackNumber, 0, 0)
   300  		return nil
   301  	}
   302  
   303  	// We are in the SYN-SENT state. We only care about segments that have
   304  	// the SYN flag.
   305  	if !s.flags.Contains(header.TCPFlagSyn) {
   306  		return nil
   307  	}
   308  
   309  	// Parse the SYN options.
   310  	rcvSynOpts := parseSynSegmentOptions(s)
   311  
   312  	// Remember if the Timestamp option was negotiated.
   313  	h.ep.maybeEnableTimestamp(rcvSynOpts)
   314  
   315  	// Remember if the SACKPermitted option was negotiated.
   316  	h.ep.maybeEnableSACKPermitted(rcvSynOpts)
   317  
   318  	// Remember the sequence we'll ack from now on.
   319  	h.ackNum = s.sequenceNumber + 1
   320  	h.flags |= header.TCPFlagAck
   321  	h.mss = rcvSynOpts.MSS
   322  	h.sndWndScale = rcvSynOpts.WS
   323  
   324  	// If this is a SYN ACK response, we only need to acknowledge the SYN
   325  	// and the handshake is completed.
   326  	if s.flags.Contains(header.TCPFlagAck) {
   327  		h.state = handshakeCompleted
   328  		h.transitionToStateEstablishedLocked(s)
   329  
   330  		h.ep.sendEmptyRaw(header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd>>h.effectiveRcvWndScale())
   331  		return nil
   332  	}
   333  
   334  	// A SYN segment was received, but no ACK in it. We acknowledge the SYN
   335  	// but resend our own SYN and wait for it to be acknowledged in the
   336  	// SYN-RCVD state.
   337  	h.state = handshakeSynRcvd
   338  	ttl := calculateTTL(h.ep.route, h.ep.ipv4TTL, h.ep.ipv6HopLimit)
   339  	amss := h.ep.amss
   340  	h.ep.setEndpointState(StateSynRecv)
   341  	synOpts := header.TCPSynOptions{
   342  		WS:    int(h.effectiveRcvWndScale()),
   343  		TS:    rcvSynOpts.TS,
   344  		TSVal: h.ep.tsValNow(),
   345  		TSEcr: h.ep.recentTimestamp(),
   346  
   347  		// We only send SACKPermitted if the other side indicated it
   348  		// permits SACK. This is not explicitly defined in the RFC but
   349  		// this is the behaviour implemented by Linux.
   350  		SACKPermitted: rcvSynOpts.SACKPermitted,
   351  		MSS:           amss,
   352  	}
   353  	if ttl == 0 {
   354  		ttl = h.ep.route.DefaultTTL()
   355  	}
   356  	h.ep.sendSynTCP(h.ep.route, tcpFields{
   357  		id:     h.ep.TransportEndpointInfo.ID,
   358  		ttl:    ttl,
   359  		tos:    h.ep.sendTOS,
   360  		flags:  h.flags,
   361  		seq:    h.iss,
   362  		ack:    h.ackNum,
   363  		rcvWnd: h.rcvWnd,
   364  	}, synOpts)
   365  	return nil
   366  }
   367  
   368  // synRcvdState handles a segment received when the TCP 3-way handshake is in
   369  // the SYN-RCVD state.
   370  // +checklocks:h.ep.mu
   371  func (h *handshake) synRcvdState(s *segment) tcpip.Error {
   372  	if s.flags.Contains(header.TCPFlagRst) {
   373  		// RFC 793, page 37, states that in the SYN-RCVD state, a reset
   374  		// is acceptable if the sequence number is in the window.
   375  		if s.sequenceNumber.InWindow(h.ackNum, h.rcvWnd) {
   376  			return &tcpip.ErrConnectionRefused{}
   377  		}
   378  		return nil
   379  	}
   380  
   381  	// It's possible that s is an ACK of a SYN cookie. This can happen if:
   382  	//
   383  	//   - We receive a SYN while under load and issue a SYN/ACK with
   384  	//     cookie S.
   385  	//   - We receive a retransmitted SYN while space exists in the SYN
   386  	//     queue, and issue a SYN/ACK with seqnum S'.
   387  	//   - We receive the ACK based on S.
   388  	//
   389  	// If we receive a SYN cookie ACK, just use the cookie seqnum.
   390  	if !h.checkAck(s) && h.listenEP != nil {
   391  		iss := s.ackNumber - 1
   392  		data, ok := h.listenEP.listenCtx.isCookieValid(s.id, iss, s.sequenceNumber-1)
   393  		if !ok || int(data) >= len(mssTable) {
   394  			// This isn't a valid cookie.
   395  			// RFC 793, page 72 (https://datatracker.ietf.org/doc/html/rfc793#page-72):
   396  			//   If the segment acknowledgment is not acceptable, form a reset segment,
   397  			//        <SEQ=SEG.ACK><CTL=RST>
   398  			//   and send it.
   399  			h.ep.sendEmptyRaw(header.TCPFlagRst, s.ackNumber, 0, 0)
   400  			return nil
   401  		}
   402  		// This is a cookie that snuck its way in after we stopped using them.
   403  		h.mss = mssTable[data]
   404  		h.iss = iss
   405  	}
   406  
   407  	// RFC 793, Section 3.9, page 69, states that in the SYN-RCVD state, a
   408  	// sequence number outside of the window causes an ACK with the proper seq
   409  	// number and "After sending the acknowledgment, drop the unacceptable
   410  	// segment and return."
   411  	if !s.sequenceNumber.InWindow(h.ackNum, h.rcvWnd) {
   412  		if h.ep.allowOutOfWindowAck() {
   413  			h.ep.sendEmptyRaw(header.TCPFlagAck, h.iss+1, h.ackNum, h.rcvWnd)
   414  		}
   415  		return nil
   416  	}
   417  
   418  	if s.flags.Contains(header.TCPFlagSyn) && s.sequenceNumber != h.ackNum-1 {
   419  		// We received two SYN segments with different sequence
   420  		// numbers, so we reset this and restart the whole
   421  		// process, except that we don't reset the timer.
   422  		ack := s.sequenceNumber.Add(s.logicalLen())
   423  		seq := seqnum.Value(0)
   424  		if s.flags.Contains(header.TCPFlagAck) {
   425  			seq = s.ackNumber
   426  		}
   427  		h.ep.sendEmptyRaw(header.TCPFlagRst|header.TCPFlagAck, seq, ack, 0)
   428  
   429  		if !h.active {
   430  			return &tcpip.ErrInvalidEndpointState{}
   431  		}
   432  
   433  		h.resetState()
   434  		synOpts := header.TCPSynOptions{
   435  			WS:            h.rcvWndScale,
   436  			TS:            h.ep.SendTSOk,
   437  			TSVal:         h.ep.tsValNow(),
   438  			TSEcr:         h.ep.recentTimestamp(),
   439  			SACKPermitted: h.ep.SACKPermitted,
   440  			MSS:           h.ep.amss,
   441  		}
   442  		h.ep.sendSynTCP(h.ep.route, tcpFields{
   443  			id:     h.ep.TransportEndpointInfo.ID,
   444  			ttl:    calculateTTL(h.ep.route, h.ep.ipv4TTL, h.ep.ipv6HopLimit),
   445  			tos:    h.ep.sendTOS,
   446  			flags:  h.flags,
   447  			seq:    h.iss,
   448  			ack:    h.ackNum,
   449  			rcvWnd: h.rcvWnd,
   450  		}, synOpts)
   451  		return nil
   452  	}
   453  
   454  	// We have previously received (and acknowledged) the peer's SYN. If the
   455  	// peer acknowledges our SYN, the handshake is completed.
   456  	if s.flags.Contains(header.TCPFlagAck) {
   457  		// If deferAccept is not zero and this is a bare ACK and the
   458  		// timeout is not hit then drop the ACK.
   459  		if h.deferAccept != 0 && s.payloadSize() == 0 && h.ep.stack.Clock().NowMonotonic().Sub(h.startTime) < h.deferAccept {
   460  			h.acked = true
   461  			h.ep.stack.Stats().DroppedPackets.Increment()
   462  			return nil
   463  		}
   464  
   465  		// If the timestamp option is negotiated and the segment does
   466  		// not carry a timestamp option then the segment must be dropped
   467  		// as per https://tools.ietf.org/html/rfc7323#section-3.2.
   468  		if h.ep.SendTSOk && !s.parsedOptions.TS {
   469  			h.ep.stack.Stats().DroppedPackets.Increment()
   470  			return nil
   471  		}
   472  
   473  		// Drop the ACK if the accept queue is full.
   474  		// https://github.com/torvalds/linux/blob/7acac4b3196/net/ipv4/tcp_ipv4.c#L1523
   475  		// We could abort the connection as well with a tunable as in
   476  		// https://github.com/torvalds/linux/blob/7acac4b3196/net/ipv4/tcp_minisocks.c#L788
   477  		if listenEP := h.listenEP; listenEP != nil && listenEP.acceptQueueIsFull() {
   478  			listenEP.stack.Stats().DroppedPackets.Increment()
   479  			return nil
   480  		}
   481  
   482  		// Update timestamp if required. See RFC7323, section-4.3.
   483  		if h.ep.SendTSOk && s.parsedOptions.TS {
   484  			h.ep.updateRecentTimestamp(s.parsedOptions.TSVal, h.ackNum, s.sequenceNumber)
   485  		}
   486  
   487  		h.state = handshakeCompleted
   488  		h.transitionToStateEstablishedLocked(s)
   489  
   490  		// Requeue the segment if the ACK completing the handshake has more info
   491  		// to be processed by the newly established endpoint.
   492  		if (s.flags.Contains(header.TCPFlagFin) || s.payloadSize() > 0) && h.ep.enqueueSegment(s) {
   493  			h.ep.protocol.dispatcher.selectProcessor(h.ep.ID).queueEndpoint(h.ep)
   494  
   495  		}
   496  		return nil
   497  	}
   498  
   499  	return nil
   500  }
   501  
   502  // +checklocks:h.ep.mu
   503  func (h *handshake) handleSegment(s *segment) tcpip.Error {
   504  	h.sndWnd = s.window
   505  	if !s.flags.Contains(header.TCPFlagSyn) && h.sndWndScale > 0 {
   506  		h.sndWnd <<= uint8(h.sndWndScale)
   507  	}
   508  
   509  	switch h.state {
   510  	case handshakeSynRcvd:
   511  		return h.synRcvdState(s)
   512  	case handshakeSynSent:
   513  		return h.synSentState(s)
   514  	}
   515  	return nil
   516  }
   517  
   518  // processSegments goes through the segment queue and processes up to
   519  // maxSegmentsPerWake (if they're available).
   520  // +checklocks:h.ep.mu
   521  func (h *handshake) processSegments() tcpip.Error {
   522  	for i := 0; i < maxSegmentsPerWake; i++ {
   523  		s := h.ep.segmentQueue.dequeue()
   524  		if s == nil {
   525  			return nil
   526  		}
   527  
   528  		err := h.handleSegment(s)
   529  		s.DecRef()
   530  		if err != nil {
   531  			return err
   532  		}
   533  
   534  		// We stop processing packets once the handshake is completed,
   535  		// otherwise we may process packets meant to be processed by
   536  		// the main protocol goroutine.
   537  		if h.state == handshakeCompleted {
   538  			break
   539  		}
   540  	}
   541  
   542  	return nil
   543  }
   544  
   545  // start sends the first SYN/SYN-ACK. It does not block, even if link address
   546  // resolution is required.
   547  func (h *handshake) start() {
   548  	h.startTime = h.ep.stack.Clock().NowMonotonic()
   549  	h.ep.amss = calculateAdvertisedMSS(h.ep.userMSS, h.ep.route)
   550  	var sackEnabled tcpip.TCPSACKEnabled
   551  	if err := h.ep.stack.TransportProtocolOption(ProtocolNumber, &sackEnabled); err != nil {
   552  		// If stack returned an error when checking for SACKEnabled
   553  		// status then just default to switching off SACK negotiation.
   554  		sackEnabled = false
   555  	}
   556  
   557  	synOpts := header.TCPSynOptions{
   558  		WS:            h.rcvWndScale,
   559  		TS:            true,
   560  		TSVal:         h.ep.tsValNow(),
   561  		TSEcr:         h.ep.recentTimestamp(),
   562  		SACKPermitted: bool(sackEnabled),
   563  		MSS:           h.ep.amss,
   564  	}
   565  
   566  	// start() is also called in a listen context so we want to make sure we only
   567  	// send the TS/SACK option when we received the TS/SACK in the initial SYN.
   568  	if h.state == handshakeSynRcvd {
   569  		synOpts.TS = h.ep.SendTSOk
   570  		synOpts.SACKPermitted = h.ep.SACKPermitted && bool(sackEnabled)
   571  		if h.sndWndScale < 0 {
   572  			// Disable window scaling if the peer did not send us
   573  			// the window scaling option.
   574  			synOpts.WS = -1
   575  		}
   576  	}
   577  
   578  	h.sendSYNOpts = synOpts
   579  	h.ep.sendSynTCP(h.ep.route, tcpFields{
   580  		id:     h.ep.TransportEndpointInfo.ID,
   581  		ttl:    calculateTTL(h.ep.route, h.ep.ipv4TTL, h.ep.ipv6HopLimit),
   582  		tos:    h.ep.sendTOS,
   583  		flags:  h.flags,
   584  		seq:    h.iss,
   585  		ack:    h.ackNum,
   586  		rcvWnd: h.rcvWnd,
   587  	}, synOpts)
   588  }
   589  
   590  // retransmitHandler handles retransmissions of un-acked SYNs.
   591  // +checklocks:h.ep.mu
   592  func (h *handshake) retransmitHandlerLocked() tcpip.Error {
   593  	e := h.ep
   594  	// If the endpoint has already transition out of a connecting state due
   595  	// to say an error (e.g) peer send RST or an ICMP error. Then just
   596  	// return. Any required cleanup should have been done when the RST/error
   597  	// was handled.
   598  	if !e.EndpointState().connecting() {
   599  		return nil
   600  	}
   601  
   602  	if err := h.retransmitTimer.reset(); err != nil {
   603  		return err
   604  	}
   605  
   606  	// Resend the SYN/SYN-ACK only if the following conditions hold.
   607  	//  - It's an active handshake (deferAccept does not apply)
   608  	//  - It's a passive handshake and we have not yet got the final-ACK.
   609  	//  - It's a passive handshake and we got an ACK but deferAccept is
   610  	//    enabled and we are now past the deferAccept duration.
   611  	// The last is required to provide a way for the peer to complete
   612  	// the connection with another ACK or data (as ACKs are never
   613  	// retransmitted on their own).
   614  	if h.active || !h.acked || h.deferAccept != 0 && e.stack.Clock().NowMonotonic().Sub(h.startTime) > h.deferAccept {
   615  		e.sendSynTCP(e.route, tcpFields{
   616  			id:     e.TransportEndpointInfo.ID,
   617  			ttl:    calculateTTL(e.route, e.ipv4TTL, e.ipv6HopLimit),
   618  			tos:    e.sendTOS,
   619  			flags:  h.flags,
   620  			seq:    h.iss,
   621  			ack:    h.ackNum,
   622  			rcvWnd: h.rcvWnd,
   623  		}, h.sendSYNOpts)
   624  		// If we have ever retransmitted the SYN-ACK or
   625  		// SYN segment, we should only measure RTT if
   626  		// TS option is present.
   627  		h.sampleRTTWithTSOnly = true
   628  	}
   629  	return nil
   630  }
   631  
   632  // transitionToStateEstablisedLocked transitions the endpoint of the handshake
   633  // to an established state given the last segment received from peer. It also
   634  // initializes sender/receiver.
   635  // +checklocks:h.ep.mu
   636  func (h *handshake) transitionToStateEstablishedLocked(s *segment) {
   637  	// Stop the SYN retransmissions now that handshake is complete.
   638  	if h.retransmitTimer != nil {
   639  		h.retransmitTimer.stop()
   640  	}
   641  
   642  	// Transfer handshake state to TCP connection. We disable
   643  	// receive window scaling if the peer doesn't support it
   644  	// (indicated by a negative send window scale).
   645  	h.ep.snd = newSender(h.ep, h.iss, h.ackNum-1, h.sndWnd, h.mss, h.sndWndScale)
   646  
   647  	now := h.ep.stack.Clock().NowMonotonic()
   648  
   649  	var rtt time.Duration
   650  	if h.ep.SendTSOk && s.parsedOptions.TSEcr != 0 {
   651  		rtt = h.ep.elapsed(now, s.parsedOptions.TSEcr)
   652  	}
   653  	if !h.sampleRTTWithTSOnly && rtt == 0 {
   654  		rtt = now.Sub(h.startTime)
   655  	}
   656  
   657  	if rtt > 0 {
   658  		h.ep.snd.updateRTO(rtt)
   659  	}
   660  
   661  	h.ep.rcvQueueMu.Lock()
   662  	h.ep.rcv = newReceiver(h.ep, h.ackNum-1, h.rcvWnd, h.effectiveRcvWndScale())
   663  	// Bootstrap the auto tuning algorithm. Starting at zero will
   664  	// result in a really large receive window after the first auto
   665  	// tuning adjustment.
   666  	h.ep.RcvAutoParams.PrevCopiedBytes = int(h.rcvWnd)
   667  	h.ep.rcvQueueMu.Unlock()
   668  
   669  	h.ep.setEndpointState(StateEstablished)
   670  
   671  	// Completing the 3-way handshake is an indication that the route is valid
   672  	// and the remote is reachable as the only way we can complete a handshake
   673  	// is if our SYN reached the remote and their ACK reached us.
   674  	h.ep.route.ConfirmReachable()
   675  
   676  	// Tell waiters that the endpoint is connected and writable.
   677  	h.ep.waiterQueue.Notify(waiter.WritableEvents)
   678  }
   679  
   680  type backoffTimer struct {
   681  	timeout    time.Duration
   682  	maxTimeout time.Duration
   683  	t          tcpip.Timer
   684  }
   685  
   686  func newBackoffTimer(clock tcpip.Clock, timeout, maxTimeout time.Duration, f func()) (*backoffTimer, tcpip.Error) {
   687  	if timeout > maxTimeout {
   688  		return nil, &tcpip.ErrTimeout{}
   689  	}
   690  	bt := &backoffTimer{timeout: timeout, maxTimeout: maxTimeout}
   691  	bt.t = clock.AfterFunc(timeout, f)
   692  	return bt, nil
   693  }
   694  
   695  func (bt *backoffTimer) reset() tcpip.Error {
   696  	bt.timeout *= 2
   697  	if bt.timeout > bt.maxTimeout {
   698  		return &tcpip.ErrTimeout{}
   699  	}
   700  	bt.t.Reset(bt.timeout)
   701  	return nil
   702  }
   703  
   704  func (bt *backoffTimer) stop() {
   705  	bt.t.Stop()
   706  }
   707  
   708  func parseSynSegmentOptions(s *segment) header.TCPSynOptions {
   709  	synOpts := header.ParseSynOptions(s.options, s.flags.Contains(header.TCPFlagAck))
   710  	if synOpts.TS {
   711  		s.parsedOptions.TSVal = synOpts.TSVal
   712  		s.parsedOptions.TSEcr = synOpts.TSEcr
   713  	}
   714  	return synOpts
   715  }
   716  
   717  var optionPool = sync.Pool{
   718  	New: func() any {
   719  		return &[maxOptionSize]byte{}
   720  	},
   721  }
   722  
   723  func getOptions() []byte {
   724  	return (*optionPool.Get().(*[maxOptionSize]byte))[:]
   725  }
   726  
   727  func putOptions(options []byte) {
   728  	// Reslice to full capacity.
   729  	optionPool.Put(optionsToArray(options))
   730  }
   731  
   732  func makeSynOptions(opts header.TCPSynOptions) []byte {
   733  	// Emulate linux option order. This is as follows:
   734  	//
   735  	// if md5: NOP NOP MD5SIG 18 md5sig(16)
   736  	// if mss: MSS 4 mss(2)
   737  	// if ts and sack_advertise:
   738  	//	SACK 2 TIMESTAMP 2 timestamp(8)
   739  	// elif ts: NOP NOP TIMESTAMP 10 timestamp(8)
   740  	// elif sack: NOP NOP SACK 2
   741  	// if wscale: NOP WINDOW 3 ws(1)
   742  	// if sack_blocks: NOP NOP SACK ((2 + (#blocks * 8))
   743  	//	[for each block] start_seq(4) end_seq(4)
   744  	// if fastopen_cookie:
   745  	//	if exp: EXP (4 + len(cookie)) FASTOPEN_MAGIC(2)
   746  	// 	else: FASTOPEN (2 + len(cookie))
   747  	//	cookie(variable) [padding to four bytes]
   748  	//
   749  	options := getOptions()
   750  
   751  	// Always encode the mss.
   752  	offset := header.EncodeMSSOption(uint32(opts.MSS), options)
   753  
   754  	// Special ordering is required here. If both TS and SACK are enabled,
   755  	// then the SACK option precedes TS, with no padding. If they are
   756  	// enabled individually, then we see padding before the option.
   757  	if opts.TS && opts.SACKPermitted {
   758  		offset += header.EncodeSACKPermittedOption(options[offset:])
   759  		offset += header.EncodeTSOption(opts.TSVal, opts.TSEcr, options[offset:])
   760  	} else if opts.TS {
   761  		offset += header.EncodeNOP(options[offset:])
   762  		offset += header.EncodeNOP(options[offset:])
   763  		offset += header.EncodeTSOption(opts.TSVal, opts.TSEcr, options[offset:])
   764  	} else if opts.SACKPermitted {
   765  		offset += header.EncodeNOP(options[offset:])
   766  		offset += header.EncodeNOP(options[offset:])
   767  		offset += header.EncodeSACKPermittedOption(options[offset:])
   768  	}
   769  
   770  	// Initialize the WS option.
   771  	if opts.WS >= 0 {
   772  		offset += header.EncodeNOP(options[offset:])
   773  		offset += header.EncodeWSOption(opts.WS, options[offset:])
   774  	}
   775  
   776  	// Padding to the end; note that this never apply unless we add a
   777  	// fastopen option, we always expect the offset to remain the same.
   778  	if delta := header.AddTCPOptionPadding(options, offset); delta != 0 {
   779  		panic("unexpected option encoding")
   780  	}
   781  
   782  	return options[:offset]
   783  }
   784  
   785  // tcpFields is a struct to carry different parameters required by the
   786  // send*TCP variant functions below.
   787  type tcpFields struct {
   788  	id     stack.TransportEndpointID
   789  	ttl    uint8
   790  	tos    uint8
   791  	flags  header.TCPFlags
   792  	seq    seqnum.Value
   793  	ack    seqnum.Value
   794  	rcvWnd seqnum.Size
   795  	opts   []byte
   796  	txHash uint32
   797  }
   798  
   799  func (e *Endpoint) sendSynTCP(r *stack.Route, tf tcpFields, opts header.TCPSynOptions) tcpip.Error {
   800  	tf.opts = makeSynOptions(opts)
   801  	// We ignore SYN send errors and let the callers re-attempt send.
   802  	p := stack.NewPacketBuffer(stack.PacketBufferOptions{ReserveHeaderBytes: header.TCPMinimumSize + int(r.MaxHeaderLength()) + len(tf.opts)})
   803  	defer p.DecRef()
   804  	if err := e.sendTCP(r, tf, p, stack.GSO{}); err != nil {
   805  		e.stats.SendErrors.SynSendToNetworkFailed.Increment()
   806  	}
   807  	putOptions(tf.opts)
   808  	return nil
   809  }
   810  
   811  // This method takes ownership of pkt.
   812  func (e *Endpoint) sendTCP(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso stack.GSO) tcpip.Error {
   813  	tf.txHash = e.txHash
   814  	if err := sendTCP(r, tf, pkt, gso, e.owner); err != nil {
   815  		e.stats.SendErrors.SegmentSendToNetworkFailed.Increment()
   816  		return err
   817  	}
   818  	e.stats.SegmentsSent.Increment()
   819  	return nil
   820  }
   821  
   822  func buildTCPHdr(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso stack.GSO) {
   823  	optLen := len(tf.opts)
   824  	tcp := header.TCP(pkt.TransportHeader().Push(header.TCPMinimumSize + optLen))
   825  	pkt.TransportProtocolNumber = header.TCPProtocolNumber
   826  	tcp.Encode(&header.TCPFields{
   827  		SrcPort:    tf.id.LocalPort,
   828  		DstPort:    tf.id.RemotePort,
   829  		SeqNum:     uint32(tf.seq),
   830  		AckNum:     uint32(tf.ack),
   831  		DataOffset: uint8(header.TCPMinimumSize + optLen),
   832  		Flags:      tf.flags,
   833  		WindowSize: uint16(tf.rcvWnd),
   834  	})
   835  	copy(tcp[header.TCPMinimumSize:], tf.opts)
   836  
   837  	xsum := r.PseudoHeaderChecksum(ProtocolNumber, uint16(pkt.Size()))
   838  	// Only calculate the checksum if offloading isn't supported.
   839  	if gso.Type != stack.GSONone && gso.NeedsCsum {
   840  		// This is called CHECKSUM_PARTIAL in the Linux kernel. We
   841  		// calculate a checksum of the pseudo-header and save it in the
   842  		// TCP header, then the kernel calculate a checksum of the
   843  		// header and data and get the right sum of the TCP packet.
   844  		tcp.SetChecksum(xsum)
   845  	} else if r.RequiresTXTransportChecksum() {
   846  		xsum = checksum.Combine(xsum, pkt.Data().Checksum())
   847  		tcp.SetChecksum(^tcp.CalculateChecksum(xsum))
   848  	}
   849  }
   850  
   851  func sendTCPBatch(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso stack.GSO, owner tcpip.PacketOwner) tcpip.Error {
   852  	optLen := len(tf.opts)
   853  	if tf.rcvWnd > math.MaxUint16 {
   854  		tf.rcvWnd = math.MaxUint16
   855  	}
   856  
   857  	mss := int(gso.MSS)
   858  	n := (pkt.Data().Size() + mss - 1) / mss
   859  
   860  	size := pkt.Data().Size()
   861  	hdrSize := header.TCPMinimumSize + int(r.MaxHeaderLength()) + optLen
   862  	for i := 0; i < n; i++ {
   863  		packetSize := mss
   864  		if packetSize > size {
   865  			packetSize = size
   866  		}
   867  		size -= packetSize
   868  
   869  		pkt := pkt
   870  		// No need to split the packet in the final iteration. The original
   871  		// packet already has the truncated data.
   872  		shouldSplitPacket := i != n-1
   873  		if shouldSplitPacket {
   874  			splitPkt := stack.NewPacketBuffer(stack.PacketBufferOptions{ReserveHeaderBytes: hdrSize})
   875  			splitPkt.Data().ReadFromPacketData(pkt.Data(), packetSize)
   876  			pkt = splitPkt
   877  		}
   878  		pkt.Hash = tf.txHash
   879  		pkt.Owner = owner
   880  
   881  		buildTCPHdr(r, tf, pkt, gso)
   882  		tf.seq = tf.seq.Add(seqnum.Size(packetSize))
   883  		pkt.GSOOptions = gso
   884  		if err := r.WritePacket(stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: tf.ttl, TOS: tf.tos}, pkt); err != nil {
   885  			r.Stats().TCP.SegmentSendErrors.Increment()
   886  			if shouldSplitPacket {
   887  				pkt.DecRef()
   888  			}
   889  			return err
   890  		}
   891  		r.Stats().TCP.SegmentsSent.Increment()
   892  		if shouldSplitPacket {
   893  			pkt.DecRef()
   894  		}
   895  	}
   896  	return nil
   897  }
   898  
   899  // sendTCP sends a TCP segment with the provided options via the provided
   900  // network endpoint and under the provided identity. This method takes
   901  // ownership of pkt.
   902  func sendTCP(r *stack.Route, tf tcpFields, pkt *stack.PacketBuffer, gso stack.GSO, owner tcpip.PacketOwner) tcpip.Error {
   903  	if tf.rcvWnd > math.MaxUint16 {
   904  		tf.rcvWnd = math.MaxUint16
   905  	}
   906  
   907  	if r.Loop()&stack.PacketLoop == 0 && gso.Type == stack.GSOGvisor && int(gso.MSS) < pkt.Data().Size() {
   908  		return sendTCPBatch(r, tf, pkt, gso, owner)
   909  	}
   910  
   911  	pkt.GSOOptions = gso
   912  	pkt.Hash = tf.txHash
   913  	pkt.Owner = owner
   914  	buildTCPHdr(r, tf, pkt, gso)
   915  
   916  	if err := r.WritePacket(stack.NetworkHeaderParams{Protocol: ProtocolNumber, TTL: tf.ttl, TOS: tf.tos}, pkt); err != nil {
   917  		r.Stats().TCP.SegmentSendErrors.Increment()
   918  		return err
   919  	}
   920  	r.Stats().TCP.SegmentsSent.Increment()
   921  	if (tf.flags & header.TCPFlagRst) != 0 {
   922  		r.Stats().TCP.ResetsSent.Increment()
   923  	}
   924  	return nil
   925  }
   926  
   927  // makeOptions makes an options slice.
   928  func (e *Endpoint) makeOptions(sackBlocks []header.SACKBlock) []byte {
   929  	options := getOptions()
   930  	offset := 0
   931  
   932  	// N.B. the ordering here matches the ordering used by Linux internally
   933  	// and described in the raw makeOptions function. We don't include
   934  	// unnecessary cases here (post connection.)
   935  	if e.SendTSOk {
   936  		// Embed the timestamp if timestamp has been enabled.
   937  		//
   938  		// We only use the lower 32 bits of the unix time in
   939  		// milliseconds. This is similar to what Linux does where it
   940  		// uses the lower 32 bits of the jiffies value in the tsVal
   941  		// field of the timestamp option.
   942  		//
   943  		// Further, RFC7323 section-5.4 recommends millisecond
   944  		// resolution as the lowest recommended resolution for the
   945  		// timestamp clock.
   946  		//
   947  		// Ref: https://tools.ietf.org/html/rfc7323#section-5.4.
   948  		offset += header.EncodeNOP(options[offset:])
   949  		offset += header.EncodeNOP(options[offset:])
   950  		offset += header.EncodeTSOption(e.tsValNow(), e.recentTimestamp(), options[offset:])
   951  	}
   952  	if e.SACKPermitted && len(sackBlocks) > 0 {
   953  		offset += header.EncodeNOP(options[offset:])
   954  		offset += header.EncodeNOP(options[offset:])
   955  		offset += header.EncodeSACKBlocks(sackBlocks, options[offset:])
   956  	}
   957  
   958  	// We expect the above to produce an aligned offset.
   959  	if delta := header.AddTCPOptionPadding(options, offset); delta != 0 {
   960  		panic("unexpected option encoding")
   961  	}
   962  
   963  	return options[:offset]
   964  }
   965  
   966  // sendEmptyRaw sends a TCP segment with no payload to the endpoint's peer.
   967  func (e *Endpoint) sendEmptyRaw(flags header.TCPFlags, seq, ack seqnum.Value, rcvWnd seqnum.Size) tcpip.Error {
   968  	pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{})
   969  	defer pkt.DecRef()
   970  	return e.sendRaw(pkt, flags, seq, ack, rcvWnd)
   971  }
   972  
   973  // sendRaw sends a TCP segment to the endpoint's peer. This method takes
   974  // ownership of pkt. pkt must not have any headers set.
   975  func (e *Endpoint) sendRaw(pkt *stack.PacketBuffer, flags header.TCPFlags, seq, ack seqnum.Value, rcvWnd seqnum.Size) tcpip.Error {
   976  	var sackBlocks []header.SACKBlock
   977  	if e.EndpointState() == StateEstablished && e.rcv.pendingRcvdSegments.Len() > 0 && (flags&header.TCPFlagAck != 0) {
   978  		sackBlocks = e.sack.Blocks[:e.sack.NumBlocks]
   979  	}
   980  	options := e.makeOptions(sackBlocks)
   981  	defer putOptions(options)
   982  	pkt.ReserveHeaderBytes(header.TCPMinimumSize + int(e.route.MaxHeaderLength()) + len(options))
   983  	return e.sendTCP(e.route, tcpFields{
   984  		id:     e.TransportEndpointInfo.ID,
   985  		ttl:    calculateTTL(e.route, e.ipv4TTL, e.ipv6HopLimit),
   986  		tos:    e.sendTOS,
   987  		flags:  flags,
   988  		seq:    seq,
   989  		ack:    ack,
   990  		rcvWnd: rcvWnd,
   991  		opts:   options,
   992  	}, pkt, e.gso)
   993  }
   994  
   995  // +checklocks:e.mu
   996  // +checklocksalias:e.snd.ep.mu=e.mu
   997  func (e *Endpoint) sendData(next *segment) {
   998  	// Initialize the next segment to write if it's currently nil.
   999  	if e.snd.writeNext == nil {
  1000  		if next == nil {
  1001  			return
  1002  		}
  1003  		e.snd.updateWriteNext(next)
  1004  	}
  1005  
  1006  	// Push out any new packets.
  1007  	e.snd.sendData()
  1008  }
  1009  
  1010  // resetConnectionLocked puts the endpoint in an error state with the given
  1011  // error code and sends a RST if and only if the error is not ErrConnectionReset
  1012  // indicating that the connection is being reset due to receiving a RST. This
  1013  // method must only be called from the protocol goroutine.
  1014  // +checklocks:e.mu
  1015  func (e *Endpoint) resetConnectionLocked(err tcpip.Error) {
  1016  	// Only send a reset if the connection is being aborted for a reason
  1017  	// other than receiving a reset.
  1018  	e.hardError = err
  1019  	switch err.(type) {
  1020  	case *tcpip.ErrConnectionReset, *tcpip.ErrTimeout:
  1021  	default:
  1022  		// The exact sequence number to be used for the RST is the same as the
  1023  		// one used by Linux. We need to handle the case of window being shrunk
  1024  		// which can cause sndNxt to be outside the acceptable window on the
  1025  		// receiver.
  1026  		//
  1027  		// See: https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for more
  1028  		// information.
  1029  		sndWndEnd := e.snd.SndUna.Add(e.snd.SndWnd)
  1030  		resetSeqNum := sndWndEnd
  1031  		if !sndWndEnd.LessThan(e.snd.SndNxt) || e.snd.SndNxt.Size(sndWndEnd) < (1<<e.snd.SndWndScale) {
  1032  			resetSeqNum = e.snd.SndNxt
  1033  		}
  1034  		e.sendEmptyRaw(header.TCPFlagAck|header.TCPFlagRst, resetSeqNum, e.rcv.RcvNxt, 0)
  1035  	}
  1036  	// Don't purge read queues here. If there's buffered data, it's still allowed
  1037  	// to be read.
  1038  	e.purgeWriteQueue()
  1039  	e.purgePendingRcvQueue()
  1040  	e.cleanupLocked()
  1041  	e.setEndpointState(StateError)
  1042  }
  1043  
  1044  // transitionToStateCloseLocked ensures that the endpoint is
  1045  // cleaned up from the transport demuxer, "before" moving to
  1046  // StateClose. This will ensure that no packet will be
  1047  // delivered to this endpoint from the demuxer when the endpoint
  1048  // is transitioned to StateClose.
  1049  // +checklocks:e.mu
  1050  func (e *Endpoint) transitionToStateCloseLocked() {
  1051  	s := e.EndpointState()
  1052  	if s == StateClose {
  1053  		return
  1054  	}
  1055  
  1056  	if s.connected() {
  1057  		e.stack.Stats().TCP.EstablishedClosed.Increment()
  1058  	}
  1059  
  1060  	e.cleanupLocked()
  1061  	// Mark the endpoint as fully closed for reads/writes.
  1062  	e.setEndpointState(StateClose)
  1063  }
  1064  
  1065  // tryDeliverSegmentFromClosedEndpoint attempts to deliver the parsed
  1066  // segment to any other endpoint other than the current one. This is called
  1067  // only when the endpoint is in StateClose and we want to deliver the segment
  1068  // to any other listening endpoint. We reply with RST if we cannot find one.
  1069  func (e *Endpoint) tryDeliverSegmentFromClosedEndpoint(s *segment) {
  1070  	ep := e.stack.FindTransportEndpoint(e.NetProto, e.TransProto, e.TransportEndpointInfo.ID, s.pkt.NICID)
  1071  	if ep == nil && e.NetProto == header.IPv6ProtocolNumber && e.TransportEndpointInfo.ID.LocalAddress.To4() != (tcpip.Address{}) {
  1072  		// Dual-stack socket, try IPv4.
  1073  		ep = e.stack.FindTransportEndpoint(
  1074  			header.IPv4ProtocolNumber,
  1075  			e.TransProto,
  1076  			e.TransportEndpointInfo.ID,
  1077  			s.pkt.NICID,
  1078  		)
  1079  	}
  1080  	if ep == nil {
  1081  		if !s.flags.Contains(header.TCPFlagRst) {
  1082  			replyWithReset(e.stack, s, stack.DefaultTOS, tcpip.UseDefaultIPv4TTL, tcpip.UseDefaultIPv6HopLimit)
  1083  		}
  1084  		return
  1085  	}
  1086  
  1087  	if e == ep {
  1088  		panic(fmt.Sprintf("current endpoint not removed from demuxer, enqueuing segments to itself, endpoint in state %v", e.EndpointState()))
  1089  	}
  1090  
  1091  	if ep := ep.(*Endpoint); ep.enqueueSegment(s) {
  1092  		ep.notifyProcessor()
  1093  	}
  1094  }
  1095  
  1096  // Drain segment queue from the endpoint and try to re-match the segment to a
  1097  // different endpoint. This is used when the current endpoint is transitioned to
  1098  // StateClose and has been unregistered from the transport demuxer.
  1099  func (e *Endpoint) drainClosingSegmentQueue() {
  1100  	for {
  1101  		s := e.segmentQueue.dequeue()
  1102  		if s == nil {
  1103  			break
  1104  		}
  1105  
  1106  		e.tryDeliverSegmentFromClosedEndpoint(s)
  1107  		s.DecRef()
  1108  	}
  1109  }
  1110  
  1111  // +checklocks:e.mu
  1112  func (e *Endpoint) handleReset(s *segment) (ok bool, err tcpip.Error) {
  1113  	if e.rcv.acceptable(s.sequenceNumber, 0) {
  1114  		// RFC 793, page 37 states that "in all states
  1115  		// except SYN-SENT, all reset (RST) segments are
  1116  		// validated by checking their SEQ-fields." So
  1117  		// we only process it if it's acceptable.
  1118  		switch e.EndpointState() {
  1119  		// In case of a RST in CLOSE-WAIT linux moves
  1120  		// the socket to closed state with an error set
  1121  		// to indicate EPIPE.
  1122  		//
  1123  		// Technically this seems to be at odds w/ RFC.
  1124  		// As per https://tools.ietf.org/html/rfc793#section-2.7
  1125  		// page 69 the behavior for a segment arriving
  1126  		// w/ RST bit set in CLOSE-WAIT is inlined below.
  1127  		//
  1128  		//  ESTABLISHED
  1129  		//  FIN-WAIT-1
  1130  		//  FIN-WAIT-2
  1131  		//  CLOSE-WAIT
  1132  
  1133  		//  If the RST bit is set then, any outstanding RECEIVEs and
  1134  		//  SEND should receive "reset" responses. All segment queues
  1135  		//  should be flushed.  Users should also receive an unsolicited
  1136  		//  general "connection reset" signal. Enter the CLOSED state,
  1137  		//  delete the TCB, and return.
  1138  		case StateCloseWait:
  1139  			e.transitionToStateCloseLocked()
  1140  			e.hardError = &tcpip.ErrAborted{}
  1141  			return false, nil
  1142  		default:
  1143  			// RFC 793, page 37 states that "in all states
  1144  			// except SYN-SENT, all reset (RST) segments are
  1145  			// validated by checking their SEQ-fields." So
  1146  			// we only process it if it's acceptable.
  1147  
  1148  			// Notify protocol goroutine. This is required when
  1149  			// handleSegment is invoked from the processor goroutine
  1150  			// rather than the worker goroutine.
  1151  			return false, &tcpip.ErrConnectionReset{}
  1152  		}
  1153  	}
  1154  	return true, nil
  1155  }
  1156  
  1157  // handleSegments processes all inbound segments.
  1158  //
  1159  // +checklocks:e.mu
  1160  // +checklocksalias:e.snd.ep.mu=e.mu
  1161  func (e *Endpoint) handleSegmentsLocked() tcpip.Error {
  1162  	sndUna := e.snd.SndUna
  1163  	for i := 0; i < maxSegmentsPerWake; i++ {
  1164  		if state := e.EndpointState(); state.closed() || state == StateTimeWait || state == StateError {
  1165  			return nil
  1166  		}
  1167  		s := e.segmentQueue.dequeue()
  1168  		if s == nil {
  1169  			break
  1170  		}
  1171  		cont, err := e.handleSegmentLocked(s)
  1172  		s.DecRef()
  1173  		if err != nil {
  1174  			return err
  1175  		}
  1176  		if !cont {
  1177  			return nil
  1178  		}
  1179  	}
  1180  
  1181  	// The remote ACK-ing at least 1 byte is an indication that we have a
  1182  	// full-duplex connection to the remote as the only way we will receive an
  1183  	// ACK is if the remote received data that we previously sent.
  1184  	//
  1185  	// As of writing, Linux seems to only confirm a route as reachable when
  1186  	// forward progress is made which is indicated by an ACK that removes data
  1187  	// from the retransmit queue, i.e. sender makes forward progress.
  1188  	if sndUna.LessThan(e.snd.SndUna) {
  1189  		e.route.ConfirmReachable()
  1190  	}
  1191  
  1192  	// Send an ACK for all processed packets if needed.
  1193  	if e.rcv.RcvNxt != e.snd.MaxSentAck {
  1194  		e.snd.sendAck()
  1195  	}
  1196  
  1197  	e.resetKeepaliveTimer(true /* receivedData */)
  1198  
  1199  	return nil
  1200  }
  1201  
  1202  // +checklocks:e.mu
  1203  func (e *Endpoint) probeSegmentLocked() {
  1204  	if fn := e.probe; fn != nil {
  1205  		var state stack.TCPEndpointState
  1206  		e.completeStateLocked(&state)
  1207  		fn(&state)
  1208  	}
  1209  }
  1210  
  1211  // handleSegment handles a given segment and notifies the worker goroutine if
  1212  // if the connection should be terminated.
  1213  //
  1214  // +checklocks:e.mu
  1215  // +checklocksalias:e.rcv.ep.mu=e.mu
  1216  // +checklocksalias:e.snd.ep.mu=e.mu
  1217  func (e *Endpoint) handleSegmentLocked(s *segment) (cont bool, err tcpip.Error) {
  1218  	// Invoke the tcp probe if installed. The tcp probe function will update
  1219  	// the TCPEndpointState after the segment is processed.
  1220  	defer e.probeSegmentLocked()
  1221  
  1222  	if s.flags.Contains(header.TCPFlagRst) {
  1223  		if ok, err := e.handleReset(s); !ok {
  1224  			return false, err
  1225  		}
  1226  	} else if s.flags.Contains(header.TCPFlagSyn) {
  1227  		// See: https://tools.ietf.org/html/rfc5961#section-4.1
  1228  		//   1) If the SYN bit is set, irrespective of the sequence number, TCP
  1229  		//    MUST send an ACK (also referred to as challenge ACK) to the remote
  1230  		//    peer:
  1231  		//
  1232  		//    <SEQ=SND.NXT><ACK=RCV.NXT><CTL=ACK>
  1233  		//
  1234  		//    After sending the acknowledgment, TCP MUST drop the unacceptable
  1235  		//    segment and stop processing further.
  1236  		//
  1237  		// By sending an ACK, the remote peer is challenged to confirm the loss
  1238  		// of the previous connection and the request to start a new connection.
  1239  		// A legitimate peer, after restart, would not have a TCB in the
  1240  		// synchronized state.  Thus, when the ACK arrives, the peer should send
  1241  		// a RST segment back with the sequence number derived from the ACK
  1242  		// field that caused the RST.
  1243  
  1244  		// This RST will confirm that the remote peer has indeed closed the
  1245  		// previous connection.  Upon receipt of a valid RST, the local TCP
  1246  		// endpoint MUST terminate its connection.  The local TCP endpoint
  1247  		// should then rely on SYN retransmission from the remote end to
  1248  		// re-establish the connection.
  1249  		e.snd.maybeSendOutOfWindowAck(s)
  1250  	} else if s.flags.Contains(header.TCPFlagAck) {
  1251  		// Patch the window size in the segment according to the
  1252  		// send window scale.
  1253  		s.window <<= e.snd.SndWndScale
  1254  
  1255  		// RFC 793, page 41 states that "once in the ESTABLISHED
  1256  		// state all segments must carry current acknowledgment
  1257  		// information."
  1258  		drop, err := e.rcv.handleRcvdSegment(s)
  1259  		if err != nil {
  1260  			return false, err
  1261  		}
  1262  		if drop {
  1263  			return true, nil
  1264  		}
  1265  
  1266  		// Now check if the received segment has caused us to transition
  1267  		// to a CLOSED state, if yes then terminate processing and do
  1268  		// not invoke the sender.
  1269  		state := e.EndpointState()
  1270  		if state == StateClose {
  1271  			// When we get into StateClose while processing from the queue,
  1272  			// return immediately and let the protocolMainloop handle it.
  1273  			//
  1274  			// We can reach StateClose only while processing a previous segment
  1275  			// or a notification from the protocolMainLoop (caller goroutine).
  1276  			// This means that with this return, the segment dequeue below can
  1277  			// never occur on a closed endpoint.
  1278  			return false, nil
  1279  		}
  1280  
  1281  		e.snd.handleRcvdSegment(s)
  1282  	}
  1283  
  1284  	return true, nil
  1285  }
  1286  
  1287  // keepaliveTimerExpired is called when the keepaliveTimer fires. We send TCP
  1288  // keepalive packets periodically when the connection is idle. If we don't hear
  1289  // from the other side after a number of tries, we terminate the connection.
  1290  // +checklocks:e.mu
  1291  // +checklocksalias:e.snd.ep.mu=e.mu
  1292  func (e *Endpoint) keepaliveTimerExpired() tcpip.Error {
  1293  	userTimeout := e.userTimeout
  1294  
  1295  	// If the route is not ready or already cleaned up, then we don't need to
  1296  	// send keepalives.
  1297  	if e.route == nil {
  1298  		return nil
  1299  	}
  1300  	e.keepalive.Lock()
  1301  	if !e.SocketOptions().GetKeepAlive() || e.keepalive.timer.isUninitialized() || !e.keepalive.timer.checkExpiration() {
  1302  		e.keepalive.Unlock()
  1303  		return nil
  1304  	}
  1305  
  1306  	// If a userTimeout is set then abort the connection if it is
  1307  	// exceeded.
  1308  	if userTimeout != 0 && e.stack.Clock().NowMonotonic().Sub(e.rcv.lastRcvdAckTime) >= userTimeout && e.keepalive.unacked > 0 {
  1309  		e.keepalive.Unlock()
  1310  		e.stack.Stats().TCP.EstablishedTimedout.Increment()
  1311  		return &tcpip.ErrTimeout{}
  1312  	}
  1313  
  1314  	if e.keepalive.unacked >= e.keepalive.count {
  1315  		e.keepalive.Unlock()
  1316  		e.stack.Stats().TCP.EstablishedTimedout.Increment()
  1317  		return &tcpip.ErrTimeout{}
  1318  	}
  1319  
  1320  	// RFC1122 4.2.3.6: TCP keepalive is a dataless ACK with
  1321  	// seg.seq = snd.nxt-1.
  1322  	e.keepalive.unacked++
  1323  	e.keepalive.Unlock()
  1324  	e.snd.sendEmptySegment(header.TCPFlagAck, e.snd.SndNxt-1)
  1325  	e.resetKeepaliveTimer(false)
  1326  	return nil
  1327  }
  1328  
  1329  // resetKeepaliveTimer restarts or stops the keepalive timer, depending on
  1330  // whether it is enabled for this endpoint.
  1331  func (e *Endpoint) resetKeepaliveTimer(receivedData bool) {
  1332  	e.keepalive.Lock()
  1333  	defer e.keepalive.Unlock()
  1334  	if e.keepalive.timer.isUninitialized() {
  1335  		if state := e.EndpointState(); !state.closed() {
  1336  			panic(fmt.Sprintf("Unexpected state when the keepalive time is cleaned up, got %s, want %s or %s", state, StateClose, StateError))
  1337  		}
  1338  		return
  1339  	}
  1340  	if receivedData {
  1341  		e.keepalive.unacked = 0
  1342  	}
  1343  	// Start the keepalive timer IFF it's enabled and there is no pending
  1344  	// data to send.
  1345  	if !e.SocketOptions().GetKeepAlive() || e.snd == nil || e.snd.SndUna != e.snd.SndNxt {
  1346  		e.keepalive.timer.disable()
  1347  		return
  1348  	}
  1349  	if e.keepalive.unacked > 0 {
  1350  		e.keepalive.timer.enable(e.keepalive.interval)
  1351  	} else {
  1352  		e.keepalive.timer.enable(e.keepalive.idle)
  1353  	}
  1354  }
  1355  
  1356  // disableKeepaliveTimer stops the keepalive timer.
  1357  func (e *Endpoint) disableKeepaliveTimer() {
  1358  	e.keepalive.Lock()
  1359  	e.keepalive.timer.disable()
  1360  	e.keepalive.Unlock()
  1361  }
  1362  
  1363  // finWait2TimerExpired is called when the FIN-WAIT-2 timeout is hit
  1364  // and the peer hasn't sent us a FIN.
  1365  func (e *Endpoint) finWait2TimerExpired() {
  1366  	e.mu.Lock()
  1367  	e.transitionToStateCloseLocked()
  1368  	e.mu.Unlock()
  1369  	e.drainClosingSegmentQueue()
  1370  	e.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)
  1371  }
  1372  
  1373  // +checklocks:e.mu
  1374  func (e *Endpoint) handshakeFailed(err tcpip.Error) {
  1375  	e.lastErrorMu.Lock()
  1376  	e.lastError = err
  1377  	e.lastErrorMu.Unlock()
  1378  	// handshakeFailed is also called from startHandshake when a listener
  1379  	// transitions out of Listen state by the time the SYN is processed. In
  1380  	// such cases the handshake is never initialized and the newly created
  1381  	// endpoint is closed right away.
  1382  	if e.h != nil && e.h.retransmitTimer != nil {
  1383  		e.h.retransmitTimer.stop()
  1384  	}
  1385  	e.hardError = err
  1386  	e.cleanupLocked()
  1387  	e.setEndpointState(StateError)
  1388  }
  1389  
  1390  // handleTimeWaitSegments processes segments received during TIME_WAIT
  1391  // state.
  1392  // +checklocks:e.mu
  1393  // +checklocksalias:e.rcv.ep.mu=e.mu
  1394  func (e *Endpoint) handleTimeWaitSegments() (extendTimeWait bool, reuseTW func()) {
  1395  	for i := 0; i < maxSegmentsPerWake; i++ {
  1396  		s := e.segmentQueue.dequeue()
  1397  		if s == nil {
  1398  			break
  1399  		}
  1400  		extTW, newSyn := e.rcv.handleTimeWaitSegment(s)
  1401  		if newSyn {
  1402  			info := e.TransportEndpointInfo
  1403  			newID := info.ID
  1404  			newID.RemoteAddress = tcpip.Address{}
  1405  			newID.RemotePort = 0
  1406  			netProtos := []tcpip.NetworkProtocolNumber{info.NetProto}
  1407  			// If the local address is an IPv4 address then also
  1408  			// look for IPv6 dual stack endpoints that might be
  1409  			// listening on the local address.
  1410  			if newID.LocalAddress.To4() != (tcpip.Address{}) {
  1411  				netProtos = []tcpip.NetworkProtocolNumber{header.IPv4ProtocolNumber, header.IPv6ProtocolNumber}
  1412  			}
  1413  			for _, netProto := range netProtos {
  1414  				if listenEP := e.stack.FindTransportEndpoint(netProto, info.TransProto, newID, s.pkt.NICID); listenEP != nil {
  1415  					tcpEP := listenEP.(*Endpoint)
  1416  					if EndpointState(tcpEP.State()) == StateListen {
  1417  						reuseTW = func() {
  1418  							if !tcpEP.enqueueSegment(s) {
  1419  								return
  1420  							}
  1421  							tcpEP.notifyProcessor()
  1422  							s.DecRef()
  1423  						}
  1424  						// We explicitly do not DecRef the segment as it's still valid and
  1425  						// being reflected to a listening endpoint.
  1426  						return false, reuseTW
  1427  					}
  1428  				}
  1429  			}
  1430  		}
  1431  		if extTW {
  1432  			extendTimeWait = true
  1433  		}
  1434  		s.DecRef()
  1435  	}
  1436  	return extendTimeWait, nil
  1437  }
  1438  
  1439  // +checklocks:e.mu
  1440  func (e *Endpoint) getTimeWaitDuration() time.Duration {
  1441  	timeWaitDuration := DefaultTCPTimeWaitTimeout
  1442  
  1443  	// Get the stack wide configuration.
  1444  	var tcpTW tcpip.TCPTimeWaitTimeoutOption
  1445  	if err := e.stack.TransportProtocolOption(ProtocolNumber, &tcpTW); err == nil {
  1446  		timeWaitDuration = time.Duration(tcpTW)
  1447  	}
  1448  	return timeWaitDuration
  1449  }
  1450  
  1451  // timeWaitTimerExpired is called when an endpoint completes the required time
  1452  // (typically 2 * MSL unless configured to something else at a stack level) in
  1453  // TIME-WAIT state.
  1454  func (e *Endpoint) timeWaitTimerExpired() {
  1455  	e.mu.Lock()
  1456  	if e.EndpointState() != StateTimeWait {
  1457  		e.mu.Unlock()
  1458  		return
  1459  	}
  1460  	e.transitionToStateCloseLocked()
  1461  	e.mu.Unlock()
  1462  	e.drainClosingSegmentQueue()
  1463  	e.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)
  1464  }
  1465  
  1466  // notifyProcessor queues this endpoint for processing to its TCP processor.
  1467  func (e *Endpoint) notifyProcessor() {
  1468  	// We use TryLock here to avoid deadlocks in cases where a listening endpoint that is being
  1469  	// closed tries to abort half completed connections which in turn try to queue any segments
  1470  	// queued to that endpoint back to the same listening endpoint (because it may have got
  1471  	// segments that matched its id but were either a RST or a new SYN which must be handled
  1472  	// by a listening endpoint). In such cases the Close() on the listening endpoint will handle
  1473  	// any queued segments after it releases the lock.
  1474  	if !e.mu.TryLock() {
  1475  		return
  1476  	}
  1477  	processor := e.protocol.dispatcher.selectProcessor(e.ID)
  1478  	e.mu.Unlock()
  1479  	processor.queueEndpoint(e)
  1480  }