github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/tcpip/tcpip.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 tcpip provides the interfaces and related types that users of the
    16  // tcpip stack will use in order to create endpoints used to send and receive
    17  // data over the network stack.
    18  //
    19  // The starting point is the creation and configuration of a stack. A stack can
    20  // be created by calling the New() function of the tcpip/stack/stack package;
    21  // configuring a stack involves creating NICs (via calls to Stack.CreateNIC()),
    22  // adding network addresses (via calls to Stack.AddAddress()), and
    23  // setting a route table (via a call to Stack.SetRouteTable()).
    24  //
    25  // Once a stack is configured, endpoints can be created by calling
    26  // Stack.NewEndpoint(). Such endpoints can be used to send/receive data, connect
    27  // to peers, listen for connections, accept connections, etc., depending on the
    28  // transport protocol selected.
    29  package tcpip
    30  
    31  import (
    32  	"bytes"
    33  	"errors"
    34  	"fmt"
    35  	"io"
    36  	"math/bits"
    37  	"reflect"
    38  	"strconv"
    39  	"strings"
    40  	"time"
    41  
    42  	"github.com/SagerNet/gvisor/pkg/atomicbitops"
    43  	"github.com/SagerNet/gvisor/pkg/sync"
    44  	"github.com/SagerNet/gvisor/pkg/waiter"
    45  )
    46  
    47  // Using header.IPv4AddressSize would cause an import cycle.
    48  const ipv4AddressSize = 4
    49  
    50  // Errors related to Subnet
    51  var (
    52  	errSubnetLengthMismatch = errors.New("subnet length of address and mask differ")
    53  	errSubnetAddressMasked  = errors.New("subnet address has bits set outside the mask")
    54  )
    55  
    56  // ErrSaveRejection indicates a failed save due to unsupported networking state.
    57  // This type of errors is only used for save logic.
    58  type ErrSaveRejection struct {
    59  	Err error
    60  }
    61  
    62  // Error returns a sensible description of the save rejection error.
    63  func (e *ErrSaveRejection) Error() string {
    64  	return "save rejected due to unsupported networking state: " + e.Err.Error()
    65  }
    66  
    67  // MonotonicTime is a monotonic clock reading.
    68  //
    69  // +stateify savable
    70  type MonotonicTime struct {
    71  	nanoseconds int64
    72  }
    73  
    74  // Before reports whether the monotonic clock reading mt is before u.
    75  func (mt MonotonicTime) Before(u MonotonicTime) bool {
    76  	return mt.nanoseconds < u.nanoseconds
    77  }
    78  
    79  // After reports whether the monotonic clock reading mt is after u.
    80  func (mt MonotonicTime) After(u MonotonicTime) bool {
    81  	return mt.nanoseconds > u.nanoseconds
    82  }
    83  
    84  // Add returns the monotonic clock reading mt+d.
    85  func (mt MonotonicTime) Add(d time.Duration) MonotonicTime {
    86  	return MonotonicTime{
    87  		nanoseconds: time.Unix(0, mt.nanoseconds).Add(d).Sub(time.Unix(0, 0)).Nanoseconds(),
    88  	}
    89  }
    90  
    91  // Sub returns the duration mt-u. If the result exceeds the maximum (or minimum)
    92  // value that can be stored in a Duration, the maximum (or minimum) duration
    93  // will be returned. To compute t-d for a duration d, use t.Add(-d).
    94  func (mt MonotonicTime) Sub(u MonotonicTime) time.Duration {
    95  	return time.Unix(0, mt.nanoseconds).Sub(time.Unix(0, u.nanoseconds))
    96  }
    97  
    98  // A Clock provides the current time and schedules work for execution.
    99  //
   100  // Times returned by a Clock should always be used for application-visible
   101  // time. Only monotonic times should be used for netstack internal timekeeping.
   102  type Clock interface {
   103  	// Now returns the current local time.
   104  	Now() time.Time
   105  
   106  	// NowMonotonic returns the current monotonic clock reading.
   107  	NowMonotonic() MonotonicTime
   108  
   109  	// AfterFunc waits for the duration to elapse and then calls f in its own
   110  	// goroutine. It returns a Timer that can be used to cancel the call using
   111  	// its Stop method.
   112  	AfterFunc(d time.Duration, f func()) Timer
   113  }
   114  
   115  // Timer represents a single event. A Timer must be created with
   116  // Clock.AfterFunc.
   117  type Timer interface {
   118  	// Stop prevents the Timer from firing. It returns true if the call stops the
   119  	// timer, false if the timer has already expired or been stopped.
   120  	//
   121  	// If Stop returns false, then the timer has already expired and the function
   122  	// f of Clock.AfterFunc(d, f) has been started in its own goroutine; Stop
   123  	// does not wait for f to complete before returning. If the caller needs to
   124  	// know whether f is completed, it must coordinate with f explicitly.
   125  	Stop() bool
   126  
   127  	// Reset changes the timer to expire after duration d.
   128  	//
   129  	// Reset should be invoked only on stopped or expired timers. If the timer is
   130  	// known to have expired, Reset can be used directly. Otherwise, the caller
   131  	// must coordinate with the function f of Clock.AfterFunc(d, f).
   132  	Reset(d time.Duration)
   133  }
   134  
   135  // Address is a byte slice cast as a string that represents the address of a
   136  // network node. Or, in the case of unix endpoints, it may represent a path.
   137  type Address string
   138  
   139  // WithPrefix returns the address with a prefix that represents a point subnet.
   140  func (a Address) WithPrefix() AddressWithPrefix {
   141  	return AddressWithPrefix{
   142  		Address:   a,
   143  		PrefixLen: len(a) * 8,
   144  	}
   145  }
   146  
   147  // Unspecified returns true if the address is unspecified.
   148  func (a Address) Unspecified() bool {
   149  	for _, b := range a {
   150  		if b != 0 {
   151  			return false
   152  		}
   153  	}
   154  	return true
   155  }
   156  
   157  // MatchingPrefix returns the matching prefix length in bits.
   158  //
   159  // Panics if b and a have different lengths.
   160  func (a Address) MatchingPrefix(b Address) uint8 {
   161  	const bitsInAByte = 8
   162  
   163  	if len(a) != len(b) {
   164  		panic(fmt.Sprintf("addresses %s and %s do not have the same length", a, b))
   165  	}
   166  
   167  	var prefix uint8
   168  	for i := range a {
   169  		aByte := a[i]
   170  		bByte := b[i]
   171  
   172  		if aByte == bByte {
   173  			prefix += bitsInAByte
   174  			continue
   175  		}
   176  
   177  		// Count the remaining matching bits in the byte from MSbit to LSBbit.
   178  		mask := uint8(1) << (bitsInAByte - 1)
   179  		for {
   180  			if aByte&mask == bByte&mask {
   181  				prefix++
   182  				mask >>= 1
   183  				continue
   184  			}
   185  
   186  			break
   187  		}
   188  
   189  		break
   190  	}
   191  
   192  	return prefix
   193  }
   194  
   195  // AddressMask is a bitmask for an address.
   196  type AddressMask string
   197  
   198  // String implements Stringer.
   199  func (m AddressMask) String() string {
   200  	return Address(m).String()
   201  }
   202  
   203  // Prefix returns the number of bits before the first host bit.
   204  func (m AddressMask) Prefix() int {
   205  	p := 0
   206  	for _, b := range []byte(m) {
   207  		p += bits.LeadingZeros8(^b)
   208  	}
   209  	return p
   210  }
   211  
   212  // Subnet is a subnet defined by its address and mask.
   213  type Subnet struct {
   214  	address Address
   215  	mask    AddressMask
   216  }
   217  
   218  // NewSubnet creates a new Subnet, checking that the address and mask are the same length.
   219  func NewSubnet(a Address, m AddressMask) (Subnet, error) {
   220  	if len(a) != len(m) {
   221  		return Subnet{}, errSubnetLengthMismatch
   222  	}
   223  	for i := 0; i < len(a); i++ {
   224  		if a[i]&^m[i] != 0 {
   225  			return Subnet{}, errSubnetAddressMasked
   226  		}
   227  	}
   228  	return Subnet{a, m}, nil
   229  }
   230  
   231  // String implements Stringer.
   232  func (s Subnet) String() string {
   233  	return fmt.Sprintf("%s/%d", s.ID(), s.Prefix())
   234  }
   235  
   236  // Contains returns true iff the address is of the same length and matches the
   237  // subnet address and mask.
   238  func (s *Subnet) Contains(a Address) bool {
   239  	if len(a) != len(s.address) {
   240  		return false
   241  	}
   242  	for i := 0; i < len(a); i++ {
   243  		if a[i]&s.mask[i] != s.address[i] {
   244  			return false
   245  		}
   246  	}
   247  	return true
   248  }
   249  
   250  // ID returns the subnet ID.
   251  func (s *Subnet) ID() Address {
   252  	return s.address
   253  }
   254  
   255  // Bits returns the number of ones (network bits) and zeros (host bits) in the
   256  // subnet mask.
   257  func (s *Subnet) Bits() (ones int, zeros int) {
   258  	ones = s.mask.Prefix()
   259  	return ones, len(s.mask)*8 - ones
   260  }
   261  
   262  // Prefix returns the number of bits before the first host bit.
   263  func (s *Subnet) Prefix() int {
   264  	return s.mask.Prefix()
   265  }
   266  
   267  // Mask returns the subnet mask.
   268  func (s *Subnet) Mask() AddressMask {
   269  	return s.mask
   270  }
   271  
   272  // Broadcast returns the subnet's broadcast address.
   273  func (s *Subnet) Broadcast() Address {
   274  	addr := []byte(s.address)
   275  	for i := range addr {
   276  		addr[i] |= ^s.mask[i]
   277  	}
   278  	return Address(addr)
   279  }
   280  
   281  // IsBroadcast returns true if the address is considered a broadcast address.
   282  func (s *Subnet) IsBroadcast(address Address) bool {
   283  	// Only IPv4 supports the notion of a broadcast address.
   284  	if len(address) != ipv4AddressSize {
   285  		return false
   286  	}
   287  
   288  	// Normally, we would just compare address with the subnet's broadcast
   289  	// address but there is an exception where a simple comparison is not
   290  	// correct. This exception is for /31 and /32 IPv4 subnets where all
   291  	// addresses are considered valid host addresses.
   292  	//
   293  	// For /31 subnets, the case is easy. RFC 3021 Section 2.1 states that
   294  	// both addresses in a /31 subnet "MUST be interpreted as host addresses."
   295  	//
   296  	// For /32, the case is a bit more vague. RFC 3021 makes no mention of /32
   297  	// subnets. However, the same reasoning applies - if an exception is not
   298  	// made, then there do not exist any host addresses in a /32 subnet. RFC
   299  	// 4632 Section 3.1 also vaguely implies this interpretation by referring
   300  	// to addresses in /32 subnets as "host routes."
   301  	return s.Prefix() <= 30 && s.Broadcast() == address
   302  }
   303  
   304  // Equal returns true if this Subnet is equal to the given Subnet.
   305  func (s Subnet) Equal(o Subnet) bool {
   306  	// If this changes, update Route.Equal accordingly.
   307  	return s == o
   308  }
   309  
   310  // NICID is a number that uniquely identifies a NIC.
   311  type NICID int32
   312  
   313  // ShutdownFlags represents flags that can be passed to the Shutdown() method
   314  // of the Endpoint interface.
   315  type ShutdownFlags int
   316  
   317  // Values of the flags that can be passed to the Shutdown() method. They can
   318  // be OR'ed together.
   319  const (
   320  	ShutdownRead ShutdownFlags = 1 << iota
   321  	ShutdownWrite
   322  )
   323  
   324  // PacketType is used to indicate the destination of the packet.
   325  type PacketType uint8
   326  
   327  const (
   328  	// PacketHost indicates a packet addressed to the local host.
   329  	PacketHost PacketType = iota
   330  
   331  	// PacketOtherHost indicates an outgoing packet addressed to
   332  	// another host caught by a NIC in promiscuous mode.
   333  	PacketOtherHost
   334  
   335  	// PacketOutgoing for a packet originating from the local host
   336  	// that is looped back to a packet socket.
   337  	PacketOutgoing
   338  
   339  	// PacketBroadcast indicates a link layer broadcast packet.
   340  	PacketBroadcast
   341  
   342  	// PacketMulticast indicates a link layer multicast packet.
   343  	PacketMulticast
   344  )
   345  
   346  // FullAddress represents a full transport node address, as required by the
   347  // Connect() and Bind() methods.
   348  //
   349  // +stateify savable
   350  type FullAddress struct {
   351  	// NIC is the ID of the NIC this address refers to.
   352  	//
   353  	// This may not be used by all endpoint types.
   354  	NIC NICID
   355  
   356  	// Addr is the network or link layer address.
   357  	Addr Address
   358  
   359  	// Port is the transport port.
   360  	//
   361  	// This may not be used by all endpoint types.
   362  	Port uint16
   363  }
   364  
   365  // Payloader is an interface that provides data.
   366  //
   367  // This interface allows the endpoint to request the amount of data it needs
   368  // based on internal buffers without exposing them.
   369  type Payloader interface {
   370  	io.Reader
   371  
   372  	// Len returns the number of bytes of the unread portion of the
   373  	// Reader.
   374  	Len() int
   375  }
   376  
   377  var _ Payloader = (*bytes.Buffer)(nil)
   378  var _ Payloader = (*bytes.Reader)(nil)
   379  
   380  var _ io.Writer = (*SliceWriter)(nil)
   381  
   382  // SliceWriter implements io.Writer for slices.
   383  type SliceWriter []byte
   384  
   385  // Write implements io.Writer.Write.
   386  func (s *SliceWriter) Write(b []byte) (int, error) {
   387  	n := copy(*s, b)
   388  	*s = (*s)[n:]
   389  	var err error
   390  	if n != len(b) {
   391  		err = io.ErrShortWrite
   392  	}
   393  	return n, err
   394  }
   395  
   396  var _ io.Writer = (*LimitedWriter)(nil)
   397  
   398  // A LimitedWriter writes to W but limits the amount of data copied to just N
   399  // bytes. Each call to Write updates N to reflect the new amount remaining.
   400  type LimitedWriter struct {
   401  	W io.Writer
   402  	N int64
   403  }
   404  
   405  func (l *LimitedWriter) Write(p []byte) (int, error) {
   406  	pLen := int64(len(p))
   407  	if pLen > l.N {
   408  		p = p[:l.N]
   409  	}
   410  	n, err := l.W.Write(p)
   411  	n64 := int64(n)
   412  	if err == nil && n64 != pLen {
   413  		err = io.ErrShortWrite
   414  	}
   415  	l.N -= n64
   416  	return n, err
   417  }
   418  
   419  // A ControlMessages contains socket control messages for IP sockets.
   420  //
   421  // +stateify savable
   422  type ControlMessages struct {
   423  	// HasTimestamp indicates whether Timestamp is valid/set.
   424  	HasTimestamp bool
   425  
   426  	// Timestamp is the time (in ns) that the last packet used to create
   427  	// the read data was received.
   428  	Timestamp int64
   429  
   430  	// HasInq indicates whether Inq is valid/set.
   431  	HasInq bool
   432  
   433  	// Inq is the number of bytes ready to be received.
   434  	Inq int32
   435  
   436  	// HasTOS indicates whether Tos is valid/set.
   437  	HasTOS bool
   438  
   439  	// TOS is the IPv4 type of service of the associated packet.
   440  	TOS uint8
   441  
   442  	// HasTClass indicates whether TClass is valid/set.
   443  	HasTClass bool
   444  
   445  	// TClass is the IPv6 traffic class of the associated packet.
   446  	TClass uint32
   447  
   448  	// HasIPPacketInfo indicates whether PacketInfo is set.
   449  	HasIPPacketInfo bool
   450  
   451  	// PacketInfo holds interface and address data on an incoming packet.
   452  	PacketInfo IPPacketInfo
   453  
   454  	// HasOriginalDestinationAddress indicates whether OriginalDstAddress is
   455  	// set.
   456  	HasOriginalDstAddress bool
   457  
   458  	// OriginalDestinationAddress holds the original destination address
   459  	// and port of the incoming packet.
   460  	OriginalDstAddress FullAddress
   461  
   462  	// SockErr is the dequeued socket error on recvmsg(MSG_ERRQUEUE).
   463  	SockErr *SockError
   464  }
   465  
   466  // PacketOwner is used to get UID and GID of the packet.
   467  type PacketOwner interface {
   468  	// UID returns KUID of the packet.
   469  	KUID() uint32
   470  
   471  	// GID returns KGID of the packet.
   472  	KGID() uint32
   473  }
   474  
   475  // ReadOptions contains options for Endpoint.Read.
   476  type ReadOptions struct {
   477  	// Peek indicates whether this read is a peek.
   478  	Peek bool
   479  
   480  	// NeedRemoteAddr indicates whether to return the remote address, if
   481  	// supported.
   482  	NeedRemoteAddr bool
   483  
   484  	// NeedLinkPacketInfo indicates whether to return the link-layer information,
   485  	// if supported.
   486  	NeedLinkPacketInfo bool
   487  }
   488  
   489  // ReadResult represents result for a successful Endpoint.Read.
   490  type ReadResult struct {
   491  	// Count is the number of bytes received and written to the buffer.
   492  	Count int
   493  
   494  	// Total is the number of bytes of the received packet. This can be used to
   495  	// determine whether the read is truncated.
   496  	Total int
   497  
   498  	// ControlMessages is the control messages received.
   499  	ControlMessages ControlMessages
   500  
   501  	// RemoteAddr is the remote address if ReadOptions.NeedAddr is true.
   502  	RemoteAddr FullAddress
   503  
   504  	// LinkPacketInfo is the link-layer information of the received packet if
   505  	// ReadOptions.NeedLinkPacketInfo is true.
   506  	LinkPacketInfo LinkPacketInfo
   507  }
   508  
   509  // Endpoint is the interface implemented by transport protocols (e.g., tcp, udp)
   510  // that exposes functionality like read, write, connect, etc. to users of the
   511  // networking stack.
   512  type Endpoint interface {
   513  	// Close puts the endpoint in a closed state and frees all resources
   514  	// associated with it. Close initiates the teardown process, the
   515  	// Endpoint may not be fully closed when Close returns.
   516  	Close()
   517  
   518  	// Abort initiates an expedited endpoint teardown. As compared to
   519  	// Close, Abort prioritizes closing the Endpoint quickly over cleanly.
   520  	// Abort is best effort; implementing Abort with Close is acceptable.
   521  	Abort()
   522  
   523  	// Read reads data from the endpoint and optionally writes to dst.
   524  	//
   525  	// This method does not block if there is no data pending; in this case,
   526  	// ErrWouldBlock is returned.
   527  	//
   528  	// If non-zero number of bytes are successfully read and written to dst, err
   529  	// must be nil. Otherwise, if dst failed to write anything, ErrBadBuffer
   530  	// should be returned.
   531  	Read(io.Writer, ReadOptions) (ReadResult, Error)
   532  
   533  	// Write writes data to the endpoint's peer. This method does not block if
   534  	// the data cannot be written.
   535  	//
   536  	// Unlike io.Writer.Write, Endpoint.Write transfers ownership of any bytes
   537  	// successfully written to the Endpoint. That is, if a call to
   538  	// Write(SlicePayload{data}) returns (n, err), it may retain data[:n], and
   539  	// the caller should not use data[:n] after Write returns.
   540  	//
   541  	// Note that unlike io.Writer.Write, it is not an error for Write to
   542  	// perform a partial write (if n > 0, no error may be returned). Only
   543  	// stream (TCP) Endpoints may return partial writes, and even then only
   544  	// in the case where writing additional data would block. Other Endpoints
   545  	// will either write the entire message or return an error.
   546  	Write(Payloader, WriteOptions) (int64, Error)
   547  
   548  	// Connect connects the endpoint to its peer. Specifying a NIC is
   549  	// optional.
   550  	//
   551  	// There are three classes of return values:
   552  	//	nil -- the attempt to connect succeeded.
   553  	//	ErrConnectStarted/ErrAlreadyConnecting -- the connect attempt started
   554  	//		but hasn't completed yet. In this case, the caller must call Connect
   555  	//		or GetSockOpt(ErrorOption) when the endpoint becomes writable to
   556  	//		get the actual result. The first call to Connect after the socket has
   557  	//		connected returns nil. Calling connect again results in ErrAlreadyConnected.
   558  	//	Anything else -- the attempt to connect failed.
   559  	//
   560  	// If address.Addr is empty, this means that Endpoint has to be
   561  	// disconnected if this is supported, otherwise
   562  	// ErrAddressFamilyNotSupported must be returned.
   563  	Connect(address FullAddress) Error
   564  
   565  	// Disconnect disconnects the endpoint from its peer.
   566  	Disconnect() Error
   567  
   568  	// Shutdown closes the read and/or write end of the endpoint connection
   569  	// to its peer.
   570  	Shutdown(flags ShutdownFlags) Error
   571  
   572  	// Listen puts the endpoint in "listen" mode, which allows it to accept
   573  	// new connections.
   574  	Listen(backlog int) Error
   575  
   576  	// Accept returns a new endpoint if a peer has established a connection
   577  	// to an endpoint previously set to listen mode. This method does not
   578  	// block if no new connections are available.
   579  	//
   580  	// The returned Queue is the wait queue for the newly created endpoint.
   581  	//
   582  	// If peerAddr is not nil then it is populated with the peer address of the
   583  	// returned endpoint.
   584  	Accept(peerAddr *FullAddress) (Endpoint, *waiter.Queue, Error)
   585  
   586  	// Bind binds the endpoint to a specific local address and port.
   587  	// Specifying a NIC is optional.
   588  	Bind(address FullAddress) Error
   589  
   590  	// GetLocalAddress returns the address to which the endpoint is bound.
   591  	GetLocalAddress() (FullAddress, Error)
   592  
   593  	// GetRemoteAddress returns the address to which the endpoint is
   594  	// connected.
   595  	GetRemoteAddress() (FullAddress, Error)
   596  
   597  	// Readiness returns the current readiness of the endpoint. For example,
   598  	// if waiter.EventIn is set, the endpoint is immediately readable.
   599  	Readiness(mask waiter.EventMask) waiter.EventMask
   600  
   601  	// SetSockOpt sets a socket option.
   602  	SetSockOpt(opt SettableSocketOption) Error
   603  
   604  	// SetSockOptInt sets a socket option, for simple cases where a value
   605  	// has the int type.
   606  	SetSockOptInt(opt SockOptInt, v int) Error
   607  
   608  	// GetSockOpt gets a socket option.
   609  	GetSockOpt(opt GettableSocketOption) Error
   610  
   611  	// GetSockOptInt gets a socket option for simple cases where a return
   612  	// value has the int type.
   613  	GetSockOptInt(SockOptInt) (int, Error)
   614  
   615  	// State returns a socket's lifecycle state. The returned value is
   616  	// protocol-specific and is primarily used for diagnostics.
   617  	State() uint32
   618  
   619  	// ModerateRecvBuf should be called everytime data is copied to the user
   620  	// space. This allows for dynamic tuning of recv buffer space for a
   621  	// given socket.
   622  	//
   623  	// NOTE: This method is a no-op for sockets other than TCP.
   624  	ModerateRecvBuf(copied int)
   625  
   626  	// Info returns a copy to the transport endpoint info.
   627  	Info() EndpointInfo
   628  
   629  	// Stats returns a reference to the endpoint stats.
   630  	Stats() EndpointStats
   631  
   632  	// SetOwner sets the task owner to the endpoint owner.
   633  	SetOwner(owner PacketOwner)
   634  
   635  	// LastError clears and returns the last error reported by the endpoint.
   636  	LastError() Error
   637  
   638  	// SocketOptions returns the structure which contains all the socket
   639  	// level options.
   640  	SocketOptions() *SocketOptions
   641  }
   642  
   643  // LinkPacketInfo holds Link layer information for a received packet.
   644  //
   645  // +stateify savable
   646  type LinkPacketInfo struct {
   647  	// Protocol is the NetworkProtocolNumber for the packet.
   648  	Protocol NetworkProtocolNumber
   649  
   650  	// PktType is used to indicate the destination of the packet.
   651  	PktType PacketType
   652  }
   653  
   654  // EndpointInfo is the interface implemented by each endpoint info struct.
   655  type EndpointInfo interface {
   656  	// IsEndpointInfo is an empty method to implement the tcpip.EndpointInfo
   657  	// marker interface.
   658  	IsEndpointInfo()
   659  }
   660  
   661  // EndpointStats is the interface implemented by each endpoint stats struct.
   662  type EndpointStats interface {
   663  	// IsEndpointStats is an empty method to implement the tcpip.EndpointStats
   664  	// marker interface.
   665  	IsEndpointStats()
   666  }
   667  
   668  // WriteOptions contains options for Endpoint.Write.
   669  type WriteOptions struct {
   670  	// If To is not nil, write to the given address instead of the endpoint's
   671  	// peer.
   672  	To *FullAddress
   673  
   674  	// More has the same semantics as Linux's MSG_MORE.
   675  	More bool
   676  
   677  	// EndOfRecord has the same semantics as Linux's MSG_EOR.
   678  	EndOfRecord bool
   679  
   680  	// Atomic means that all data fetched from Payloader must be written to the
   681  	// endpoint. If Atomic is false, then data fetched from the Payloader may be
   682  	// discarded if available endpoint buffer space is unsufficient.
   683  	Atomic bool
   684  }
   685  
   686  // SockOptInt represents socket options which values have the int type.
   687  type SockOptInt int
   688  
   689  const (
   690  	// KeepaliveCountOption is used by SetSockOptInt/GetSockOptInt to
   691  	// specify the number of un-ACKed TCP keepalives that will be sent
   692  	// before the connection is closed.
   693  	KeepaliveCountOption SockOptInt = iota
   694  
   695  	// IPv4TOSOption is used by SetSockOptInt/GetSockOptInt to specify TOS
   696  	// for all subsequent outgoing IPv4 packets from the endpoint.
   697  	IPv4TOSOption
   698  
   699  	// IPv6TrafficClassOption is used by SetSockOptInt/GetSockOptInt to
   700  	// specify TOS for all subsequent outgoing IPv6 packets from the
   701  	// endpoint.
   702  	IPv6TrafficClassOption
   703  
   704  	// MaxSegOption is used by SetSockOptInt/GetSockOptInt to set/get the
   705  	// current Maximum Segment Size(MSS) value as specified using the
   706  	// TCP_MAXSEG option.
   707  	MaxSegOption
   708  
   709  	// MTUDiscoverOption is used to set/get the path MTU discovery setting.
   710  	//
   711  	// NOTE: Setting this option to any other value than PMTUDiscoveryDont
   712  	// is not supported and will fail as such, and getting this option will
   713  	// always return PMTUDiscoveryDont.
   714  	MTUDiscoverOption
   715  
   716  	// MulticastTTLOption is used by SetSockOptInt/GetSockOptInt to control
   717  	// the default TTL value for multicast messages. The default is 1.
   718  	MulticastTTLOption
   719  
   720  	// ReceiveQueueSizeOption is used in GetSockOptInt to specify that the
   721  	// number of unread bytes in the input buffer should be returned.
   722  	ReceiveQueueSizeOption
   723  
   724  	// SendQueueSizeOption is used in GetSockOptInt to specify that the
   725  	// number of unread bytes in the output buffer should be returned.
   726  	SendQueueSizeOption
   727  
   728  	// TTLOption is used by SetSockOptInt/GetSockOptInt to control the
   729  	// default TTL/hop limit value for unicast messages. The default is
   730  	// protocol specific.
   731  	//
   732  	// A zero value indicates the default.
   733  	TTLOption
   734  
   735  	// TCPSynCountOption is used by SetSockOptInt/GetSockOptInt to specify
   736  	// the number of SYN retransmits that TCP should send before aborting
   737  	// the attempt to connect. It cannot exceed 255.
   738  	//
   739  	// NOTE: This option is currently only stubbed out and is no-op.
   740  	TCPSynCountOption
   741  
   742  	// TCPWindowClampOption is used by SetSockOptInt/GetSockOptInt to bound
   743  	// the size of the advertised window to this value.
   744  	//
   745  	// NOTE: This option is currently only stubed out and is a no-op
   746  	TCPWindowClampOption
   747  )
   748  
   749  const (
   750  	// PMTUDiscoveryWant is a setting of the MTUDiscoverOption to use
   751  	// per-route settings.
   752  	PMTUDiscoveryWant int = iota
   753  
   754  	// PMTUDiscoveryDont is a setting of the MTUDiscoverOption to disable
   755  	// path MTU discovery.
   756  	PMTUDiscoveryDont
   757  
   758  	// PMTUDiscoveryDo is a setting of the MTUDiscoverOption to always do
   759  	// path MTU discovery.
   760  	PMTUDiscoveryDo
   761  
   762  	// PMTUDiscoveryProbe is a setting of the MTUDiscoverOption to set DF
   763  	// but ignore path MTU.
   764  	PMTUDiscoveryProbe
   765  )
   766  
   767  // GettableNetworkProtocolOption is a marker interface for network protocol
   768  // options that may be queried.
   769  type GettableNetworkProtocolOption interface {
   770  	isGettableNetworkProtocolOption()
   771  }
   772  
   773  // SettableNetworkProtocolOption is a marker interface for network protocol
   774  // options that may be set.
   775  type SettableNetworkProtocolOption interface {
   776  	isSettableNetworkProtocolOption()
   777  }
   778  
   779  // DefaultTTLOption is used by stack.(*Stack).NetworkProtocolOption to specify
   780  // a default TTL.
   781  type DefaultTTLOption uint8
   782  
   783  func (*DefaultTTLOption) isGettableNetworkProtocolOption() {}
   784  
   785  func (*DefaultTTLOption) isSettableNetworkProtocolOption() {}
   786  
   787  // GettableTransportProtocolOption is a marker interface for transport protocol
   788  // options that may be queried.
   789  type GettableTransportProtocolOption interface {
   790  	isGettableTransportProtocolOption()
   791  }
   792  
   793  // SettableTransportProtocolOption is a marker interface for transport protocol
   794  // options that may be set.
   795  type SettableTransportProtocolOption interface {
   796  	isSettableTransportProtocolOption()
   797  }
   798  
   799  // TCPSACKEnabled the SACK option for TCP.
   800  //
   801  // See: https://tools.ietf.org/html/rfc2018.
   802  type TCPSACKEnabled bool
   803  
   804  func (*TCPSACKEnabled) isGettableTransportProtocolOption() {}
   805  
   806  func (*TCPSACKEnabled) isSettableTransportProtocolOption() {}
   807  
   808  // TCPRecovery is the loss deteoction algorithm used by TCP.
   809  type TCPRecovery int32
   810  
   811  func (*TCPRecovery) isGettableTransportProtocolOption() {}
   812  
   813  func (*TCPRecovery) isSettableTransportProtocolOption() {}
   814  
   815  // TCPAlwaysUseSynCookies indicates unconditional usage of syncookies.
   816  type TCPAlwaysUseSynCookies bool
   817  
   818  func (*TCPAlwaysUseSynCookies) isGettableTransportProtocolOption() {}
   819  
   820  func (*TCPAlwaysUseSynCookies) isSettableTransportProtocolOption() {}
   821  
   822  const (
   823  	// TCPRACKLossDetection indicates RACK is used for loss detection and
   824  	// recovery.
   825  	TCPRACKLossDetection TCPRecovery = 1 << iota
   826  
   827  	// TCPRACKStaticReoWnd indicates the reordering window should not be
   828  	// adjusted when DSACK is received.
   829  	TCPRACKStaticReoWnd
   830  
   831  	// TCPRACKNoDupTh indicates RACK should not consider the classic three
   832  	// duplicate acknowledgements rule to mark the segments as lost. This
   833  	// is used when reordering is not detected.
   834  	TCPRACKNoDupTh
   835  )
   836  
   837  // TCPDelayEnabled enables/disables Nagle's algorithm in TCP.
   838  type TCPDelayEnabled bool
   839  
   840  func (*TCPDelayEnabled) isGettableTransportProtocolOption() {}
   841  
   842  func (*TCPDelayEnabled) isSettableTransportProtocolOption() {}
   843  
   844  // TCPSendBufferSizeRangeOption is the send buffer size range for TCP.
   845  type TCPSendBufferSizeRangeOption struct {
   846  	Min     int
   847  	Default int
   848  	Max     int
   849  }
   850  
   851  func (*TCPSendBufferSizeRangeOption) isGettableTransportProtocolOption() {}
   852  
   853  func (*TCPSendBufferSizeRangeOption) isSettableTransportProtocolOption() {}
   854  
   855  // TCPReceiveBufferSizeRangeOption is the receive buffer size range for TCP.
   856  type TCPReceiveBufferSizeRangeOption struct {
   857  	Min     int
   858  	Default int
   859  	Max     int
   860  }
   861  
   862  func (*TCPReceiveBufferSizeRangeOption) isGettableTransportProtocolOption() {}
   863  
   864  func (*TCPReceiveBufferSizeRangeOption) isSettableTransportProtocolOption() {}
   865  
   866  // TCPAvailableCongestionControlOption is the supported congestion control
   867  // algorithms for TCP
   868  type TCPAvailableCongestionControlOption string
   869  
   870  func (*TCPAvailableCongestionControlOption) isGettableTransportProtocolOption() {}
   871  
   872  func (*TCPAvailableCongestionControlOption) isSettableTransportProtocolOption() {}
   873  
   874  // TCPModerateReceiveBufferOption enables/disables receive buffer moderation
   875  // for TCP.
   876  type TCPModerateReceiveBufferOption bool
   877  
   878  func (*TCPModerateReceiveBufferOption) isGettableTransportProtocolOption() {}
   879  
   880  func (*TCPModerateReceiveBufferOption) isSettableTransportProtocolOption() {}
   881  
   882  // GettableSocketOption is a marker interface for socket options that may be
   883  // queried.
   884  type GettableSocketOption interface {
   885  	isGettableSocketOption()
   886  }
   887  
   888  // SettableSocketOption is a marker interface for socket options that may be
   889  // configured.
   890  type SettableSocketOption interface {
   891  	isSettableSocketOption()
   892  }
   893  
   894  // EndpointState represents the state of an endpoint.
   895  type EndpointState uint8
   896  
   897  // CongestionControlState indicates the current congestion control state for
   898  // TCP sender.
   899  type CongestionControlState int
   900  
   901  const (
   902  	// Open indicates that the sender is receiving acks in order and
   903  	// no loss or dupACK's etc have been detected.
   904  	Open CongestionControlState = iota
   905  	// RTORecovery indicates that an RTO has occurred and the sender
   906  	// has entered an RTO based recovery phase.
   907  	RTORecovery
   908  	// FastRecovery indicates that the sender has entered FastRecovery
   909  	// based on receiving nDupAck's. This state is entered only when
   910  	// SACK is not in use.
   911  	FastRecovery
   912  	// SACKRecovery indicates that the sender has entered SACK based
   913  	// recovery.
   914  	SACKRecovery
   915  	// Disorder indicates the sender either received some SACK blocks
   916  	// or dupACK's.
   917  	Disorder
   918  )
   919  
   920  // TCPInfoOption is used by GetSockOpt to expose TCP statistics.
   921  //
   922  // TODO(b/64800844): Add and populate stat fields.
   923  type TCPInfoOption struct {
   924  	// RTT is the smoothed round trip time.
   925  	RTT time.Duration
   926  
   927  	// RTTVar is the round trip time variation.
   928  	RTTVar time.Duration
   929  
   930  	// RTO is the retransmission timeout for the endpoint.
   931  	RTO time.Duration
   932  
   933  	// State is the current endpoint protocol state.
   934  	State EndpointState
   935  
   936  	// CcState is the congestion control state.
   937  	CcState CongestionControlState
   938  
   939  	// SndCwnd is the congestion window, in packets.
   940  	SndCwnd uint32
   941  
   942  	// SndSsthresh is the threshold between slow start and congestion
   943  	// avoidance.
   944  	SndSsthresh uint32
   945  
   946  	// ReorderSeen indicates if reordering is seen in the endpoint.
   947  	ReorderSeen bool
   948  }
   949  
   950  func (*TCPInfoOption) isGettableSocketOption() {}
   951  
   952  // KeepaliveIdleOption is used by SetSockOpt/GetSockOpt to specify the time a
   953  // connection must remain idle before the first TCP keepalive packet is sent.
   954  // Once this time is reached, KeepaliveIntervalOption is used instead.
   955  type KeepaliveIdleOption time.Duration
   956  
   957  func (*KeepaliveIdleOption) isGettableSocketOption() {}
   958  
   959  func (*KeepaliveIdleOption) isSettableSocketOption() {}
   960  
   961  // KeepaliveIntervalOption is used by SetSockOpt/GetSockOpt to specify the
   962  // interval between sending TCP keepalive packets.
   963  type KeepaliveIntervalOption time.Duration
   964  
   965  func (*KeepaliveIntervalOption) isGettableSocketOption() {}
   966  
   967  func (*KeepaliveIntervalOption) isSettableSocketOption() {}
   968  
   969  // TCPUserTimeoutOption is used by SetSockOpt/GetSockOpt to specify a user
   970  // specified timeout for a given TCP connection.
   971  // See: RFC5482 for details.
   972  type TCPUserTimeoutOption time.Duration
   973  
   974  func (*TCPUserTimeoutOption) isGettableSocketOption() {}
   975  
   976  func (*TCPUserTimeoutOption) isSettableSocketOption() {}
   977  
   978  // CongestionControlOption is used by SetSockOpt/GetSockOpt to set/get
   979  // the current congestion control algorithm.
   980  type CongestionControlOption string
   981  
   982  func (*CongestionControlOption) isGettableSocketOption() {}
   983  
   984  func (*CongestionControlOption) isSettableSocketOption() {}
   985  
   986  func (*CongestionControlOption) isGettableTransportProtocolOption() {}
   987  
   988  func (*CongestionControlOption) isSettableTransportProtocolOption() {}
   989  
   990  // TCPLingerTimeoutOption is used by SetSockOpt/GetSockOpt to set/get the
   991  // maximum duration for which a socket lingers in the TCP_FIN_WAIT_2 state
   992  // before being marked closed.
   993  type TCPLingerTimeoutOption time.Duration
   994  
   995  func (*TCPLingerTimeoutOption) isGettableSocketOption() {}
   996  
   997  func (*TCPLingerTimeoutOption) isSettableSocketOption() {}
   998  
   999  func (*TCPLingerTimeoutOption) isGettableTransportProtocolOption() {}
  1000  
  1001  func (*TCPLingerTimeoutOption) isSettableTransportProtocolOption() {}
  1002  
  1003  // TCPTimeWaitTimeoutOption is used by SetSockOpt/GetSockOpt to set/get the
  1004  // maximum duration for which a socket lingers in the TIME_WAIT state
  1005  // before being marked closed.
  1006  type TCPTimeWaitTimeoutOption time.Duration
  1007  
  1008  func (*TCPTimeWaitTimeoutOption) isGettableSocketOption() {}
  1009  
  1010  func (*TCPTimeWaitTimeoutOption) isSettableSocketOption() {}
  1011  
  1012  func (*TCPTimeWaitTimeoutOption) isGettableTransportProtocolOption() {}
  1013  
  1014  func (*TCPTimeWaitTimeoutOption) isSettableTransportProtocolOption() {}
  1015  
  1016  // TCPDeferAcceptOption is used by SetSockOpt/GetSockOpt to allow a
  1017  // accept to return a completed connection only when there is data to be
  1018  // read. This usually means the listening socket will drop the final ACK
  1019  // for a handshake till the specified timeout until a segment with data arrives.
  1020  type TCPDeferAcceptOption time.Duration
  1021  
  1022  func (*TCPDeferAcceptOption) isGettableSocketOption() {}
  1023  
  1024  func (*TCPDeferAcceptOption) isSettableSocketOption() {}
  1025  
  1026  // TCPMinRTOOption is use by SetSockOpt/GetSockOpt to allow overriding
  1027  // default MinRTO used by the Stack.
  1028  type TCPMinRTOOption time.Duration
  1029  
  1030  func (*TCPMinRTOOption) isGettableSocketOption() {}
  1031  
  1032  func (*TCPMinRTOOption) isSettableSocketOption() {}
  1033  
  1034  func (*TCPMinRTOOption) isGettableTransportProtocolOption() {}
  1035  
  1036  func (*TCPMinRTOOption) isSettableTransportProtocolOption() {}
  1037  
  1038  // TCPMaxRTOOption is use by SetSockOpt/GetSockOpt to allow overriding
  1039  // default MaxRTO used by the Stack.
  1040  type TCPMaxRTOOption time.Duration
  1041  
  1042  func (*TCPMaxRTOOption) isGettableSocketOption() {}
  1043  
  1044  func (*TCPMaxRTOOption) isSettableSocketOption() {}
  1045  
  1046  func (*TCPMaxRTOOption) isGettableTransportProtocolOption() {}
  1047  
  1048  func (*TCPMaxRTOOption) isSettableTransportProtocolOption() {}
  1049  
  1050  // TCPMaxRetriesOption is used by SetSockOpt/GetSockOpt to set/get the
  1051  // maximum number of retransmits after which we time out the connection.
  1052  type TCPMaxRetriesOption uint64
  1053  
  1054  func (*TCPMaxRetriesOption) isGettableSocketOption() {}
  1055  
  1056  func (*TCPMaxRetriesOption) isSettableSocketOption() {}
  1057  
  1058  func (*TCPMaxRetriesOption) isGettableTransportProtocolOption() {}
  1059  
  1060  func (*TCPMaxRetriesOption) isSettableTransportProtocolOption() {}
  1061  
  1062  // TCPSynRetriesOption is used by SetSockOpt/GetSockOpt to specify stack-wide
  1063  // default for number of times SYN is retransmitted before aborting a connect.
  1064  type TCPSynRetriesOption uint8
  1065  
  1066  func (*TCPSynRetriesOption) isGettableSocketOption() {}
  1067  
  1068  func (*TCPSynRetriesOption) isSettableSocketOption() {}
  1069  
  1070  func (*TCPSynRetriesOption) isGettableTransportProtocolOption() {}
  1071  
  1072  func (*TCPSynRetriesOption) isSettableTransportProtocolOption() {}
  1073  
  1074  // MulticastInterfaceOption is used by SetSockOpt/GetSockOpt to specify a
  1075  // default interface for multicast.
  1076  type MulticastInterfaceOption struct {
  1077  	NIC           NICID
  1078  	InterfaceAddr Address
  1079  }
  1080  
  1081  func (*MulticastInterfaceOption) isGettableSocketOption() {}
  1082  
  1083  func (*MulticastInterfaceOption) isSettableSocketOption() {}
  1084  
  1085  // MembershipOption is used to identify a multicast membership on an interface.
  1086  type MembershipOption struct {
  1087  	NIC           NICID
  1088  	InterfaceAddr Address
  1089  	MulticastAddr Address
  1090  }
  1091  
  1092  // AddMembershipOption identifies a multicast group to join on some interface.
  1093  type AddMembershipOption MembershipOption
  1094  
  1095  func (*AddMembershipOption) isSettableSocketOption() {}
  1096  
  1097  // RemoveMembershipOption identifies a multicast group to leave on some
  1098  // interface.
  1099  type RemoveMembershipOption MembershipOption
  1100  
  1101  func (*RemoveMembershipOption) isSettableSocketOption() {}
  1102  
  1103  // SocketDetachFilterOption is used by SetSockOpt to detach a previously attached
  1104  // classic BPF filter on a given endpoint.
  1105  type SocketDetachFilterOption int
  1106  
  1107  func (*SocketDetachFilterOption) isSettableSocketOption() {}
  1108  
  1109  // OriginalDestinationOption is used to get the original destination address
  1110  // and port of a redirected packet.
  1111  type OriginalDestinationOption FullAddress
  1112  
  1113  func (*OriginalDestinationOption) isGettableSocketOption() {}
  1114  
  1115  // TCPTimeWaitReuseOption is used stack.(*Stack).TransportProtocolOption to
  1116  // specify if the stack can reuse the port bound by an endpoint in TIME-WAIT for
  1117  // new connections when it is safe from protocol viewpoint.
  1118  type TCPTimeWaitReuseOption uint8
  1119  
  1120  func (*TCPTimeWaitReuseOption) isGettableSocketOption() {}
  1121  
  1122  func (*TCPTimeWaitReuseOption) isSettableSocketOption() {}
  1123  
  1124  func (*TCPTimeWaitReuseOption) isGettableTransportProtocolOption() {}
  1125  
  1126  func (*TCPTimeWaitReuseOption) isSettableTransportProtocolOption() {}
  1127  
  1128  const (
  1129  	// TCPTimeWaitReuseDisabled indicates reuse of port bound by endponts in TIME-WAIT cannot
  1130  	// be reused for new connections.
  1131  	TCPTimeWaitReuseDisabled TCPTimeWaitReuseOption = iota
  1132  
  1133  	// TCPTimeWaitReuseGlobal indicates reuse of port bound by endponts in TIME-WAIT can
  1134  	// be reused for new connections irrespective of the src/dest addresses.
  1135  	TCPTimeWaitReuseGlobal
  1136  
  1137  	// TCPTimeWaitReuseLoopbackOnly indicates reuse of port bound by endpoint in TIME-WAIT can
  1138  	// only be reused if the connection was a connection over loopback. i.e src/dest adddresses
  1139  	// are loopback addresses.
  1140  	TCPTimeWaitReuseLoopbackOnly
  1141  )
  1142  
  1143  // LingerOption is used by SetSockOpt/GetSockOpt to set/get the
  1144  // duration for which a socket lingers before returning from Close.
  1145  //
  1146  // +marshal
  1147  // +stateify savable
  1148  type LingerOption struct {
  1149  	Enabled bool
  1150  	Timeout time.Duration
  1151  }
  1152  
  1153  // IPPacketInfo is the message structure for IP_PKTINFO.
  1154  //
  1155  // +stateify savable
  1156  type IPPacketInfo struct {
  1157  	// NIC is the ID of the NIC to be used.
  1158  	NIC NICID
  1159  
  1160  	// LocalAddr is the local address.
  1161  	LocalAddr Address
  1162  
  1163  	// DestinationAddr is the destination address found in the IP header.
  1164  	DestinationAddr Address
  1165  }
  1166  
  1167  // SendBufferSizeOption is used by stack.(Stack*).Option/SetOption to
  1168  // get/set the default, min and max send buffer sizes.
  1169  type SendBufferSizeOption struct {
  1170  	// Min is the minimum size for send buffer.
  1171  	Min int
  1172  
  1173  	// Default is the default size for send buffer.
  1174  	Default int
  1175  
  1176  	// Max is the maximum size for send buffer.
  1177  	Max int
  1178  }
  1179  
  1180  // ReceiveBufferSizeOption is used by stack.(Stack*).Option/SetOption to
  1181  // get/set the default, min and max receive buffer sizes.
  1182  type ReceiveBufferSizeOption struct {
  1183  	// Min is the minimum size for send buffer.
  1184  	Min int
  1185  
  1186  	// Default is the default size for send buffer.
  1187  	Default int
  1188  
  1189  	// Max is the maximum size for send buffer.
  1190  	Max int
  1191  }
  1192  
  1193  // GetSendBufferLimits is used to get the send buffer size limits.
  1194  type GetSendBufferLimits func(StackHandler) SendBufferSizeOption
  1195  
  1196  // GetStackSendBufferLimits is used to get default, min and max send buffer size.
  1197  func GetStackSendBufferLimits(so StackHandler) SendBufferSizeOption {
  1198  	var ss SendBufferSizeOption
  1199  	if err := so.Option(&ss); err != nil {
  1200  		panic(fmt.Sprintf("s.Option(%#v) = %s", ss, err))
  1201  	}
  1202  	return ss
  1203  }
  1204  
  1205  // GetReceiveBufferLimits is used to get the send buffer size limits.
  1206  type GetReceiveBufferLimits func(StackHandler) ReceiveBufferSizeOption
  1207  
  1208  // GetStackReceiveBufferLimits is used to get default, min and max send buffer size.
  1209  func GetStackReceiveBufferLimits(so StackHandler) ReceiveBufferSizeOption {
  1210  	var ss ReceiveBufferSizeOption
  1211  	if err := so.Option(&ss); err != nil {
  1212  		panic(fmt.Sprintf("s.Option(%#v) = %s", ss, err))
  1213  	}
  1214  	return ss
  1215  }
  1216  
  1217  // Route is a row in the routing table. It specifies through which NIC (and
  1218  // gateway) sets of packets should be routed. A row is considered viable if the
  1219  // masked target address matches the destination address in the row.
  1220  type Route struct {
  1221  	// Destination must contain the target address for this row to be viable.
  1222  	Destination Subnet
  1223  
  1224  	// Gateway is the gateway to be used if this row is viable.
  1225  	Gateway Address
  1226  
  1227  	// NIC is the id of the nic to be used if this row is viable.
  1228  	NIC NICID
  1229  }
  1230  
  1231  // String implements the fmt.Stringer interface.
  1232  func (r Route) String() string {
  1233  	var out strings.Builder
  1234  	fmt.Fprintf(&out, "%s", r.Destination)
  1235  	if len(r.Gateway) > 0 {
  1236  		fmt.Fprintf(&out, " via %s", r.Gateway)
  1237  	}
  1238  	fmt.Fprintf(&out, " nic %d", r.NIC)
  1239  	return out.String()
  1240  }
  1241  
  1242  // Equal returns true if the given Route is equal to this Route.
  1243  func (r Route) Equal(to Route) bool {
  1244  	// NOTE: This relies on the fact that r.Destination == to.Destination
  1245  	return r == to
  1246  }
  1247  
  1248  // TransportProtocolNumber is the number of a transport protocol.
  1249  type TransportProtocolNumber uint32
  1250  
  1251  // NetworkProtocolNumber is the EtherType of a network protocol in an Ethernet
  1252  // frame.
  1253  //
  1254  // See: https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml
  1255  type NetworkProtocolNumber uint32
  1256  
  1257  // A StatCounter keeps track of a statistic.
  1258  type StatCounter struct {
  1259  	count atomicbitops.AlignedAtomicUint64
  1260  }
  1261  
  1262  // Increment adds one to the counter.
  1263  func (s *StatCounter) Increment() {
  1264  	s.IncrementBy(1)
  1265  }
  1266  
  1267  // Decrement minuses one to the counter.
  1268  func (s *StatCounter) Decrement() {
  1269  	s.IncrementBy(^uint64(0))
  1270  }
  1271  
  1272  // Value returns the current value of the counter.
  1273  func (s *StatCounter) Value(name ...string) uint64 {
  1274  	return s.count.Load()
  1275  }
  1276  
  1277  // IncrementBy increments the counter by v.
  1278  func (s *StatCounter) IncrementBy(v uint64) {
  1279  	s.count.Add(v)
  1280  }
  1281  
  1282  func (s *StatCounter) String() string {
  1283  	return strconv.FormatUint(s.Value(), 10)
  1284  }
  1285  
  1286  // A MultiCounterStat keeps track of two counters at once.
  1287  type MultiCounterStat struct {
  1288  	a, b *StatCounter
  1289  }
  1290  
  1291  // Init sets both internal counters to point to a and b.
  1292  func (m *MultiCounterStat) Init(a, b *StatCounter) {
  1293  	m.a = a
  1294  	m.b = b
  1295  }
  1296  
  1297  // Increment adds one to the counters.
  1298  func (m *MultiCounterStat) Increment() {
  1299  	m.a.Increment()
  1300  	m.b.Increment()
  1301  }
  1302  
  1303  // IncrementBy increments the counters by v.
  1304  func (m *MultiCounterStat) IncrementBy(v uint64) {
  1305  	m.a.IncrementBy(v)
  1306  	m.b.IncrementBy(v)
  1307  }
  1308  
  1309  // ICMPv4PacketStats enumerates counts for all ICMPv4 packet types.
  1310  type ICMPv4PacketStats struct {
  1311  	// LINT.IfChange(ICMPv4PacketStats)
  1312  
  1313  	// EchoRequest is the number of ICMPv4 echo packets counted.
  1314  	EchoRequest *StatCounter
  1315  
  1316  	// EchoReply is the number of ICMPv4 echo reply packets counted.
  1317  	EchoReply *StatCounter
  1318  
  1319  	// DstUnreachable is the number of ICMPv4 destination unreachable packets
  1320  	// counted.
  1321  	DstUnreachable *StatCounter
  1322  
  1323  	// SrcQuench is the number of ICMPv4 source quench packets counted.
  1324  	SrcQuench *StatCounter
  1325  
  1326  	// Redirect is the number of ICMPv4 redirect packets counted.
  1327  	Redirect *StatCounter
  1328  
  1329  	// TimeExceeded is the number of ICMPv4 time exceeded packets counted.
  1330  	TimeExceeded *StatCounter
  1331  
  1332  	// ParamProblem is the number of ICMPv4 parameter problem packets counted.
  1333  	ParamProblem *StatCounter
  1334  
  1335  	// Timestamp is the number of ICMPv4 timestamp packets counted.
  1336  	Timestamp *StatCounter
  1337  
  1338  	// TimestampReply is the number of ICMPv4 timestamp reply packets counted.
  1339  	TimestampReply *StatCounter
  1340  
  1341  	// InfoRequest is the number of ICMPv4 information request packets counted.
  1342  	InfoRequest *StatCounter
  1343  
  1344  	// InfoReply is the number of ICMPv4 information reply packets counted.
  1345  	InfoReply *StatCounter
  1346  
  1347  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterICMPv4PacketStats)
  1348  }
  1349  
  1350  // ICMPv4SentPacketStats collects outbound ICMPv4-specific stats.
  1351  type ICMPv4SentPacketStats struct {
  1352  	// LINT.IfChange(ICMPv4SentPacketStats)
  1353  
  1354  	ICMPv4PacketStats
  1355  
  1356  	// Dropped is the number of ICMPv4 packets dropped due to link layer errors.
  1357  	Dropped *StatCounter
  1358  
  1359  	// RateLimited is the number of ICMPv4 packets dropped due to rate limit being
  1360  	// exceeded.
  1361  	RateLimited *StatCounter
  1362  
  1363  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterICMPv4SentPacketStats)
  1364  }
  1365  
  1366  // ICMPv4ReceivedPacketStats collects inbound ICMPv4-specific stats.
  1367  type ICMPv4ReceivedPacketStats struct {
  1368  	// LINT.IfChange(ICMPv4ReceivedPacketStats)
  1369  
  1370  	ICMPv4PacketStats
  1371  
  1372  	// Invalid is the number of invalid ICMPv4 packets received.
  1373  	Invalid *StatCounter
  1374  
  1375  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterICMPv4ReceivedPacketStats)
  1376  }
  1377  
  1378  // ICMPv4Stats collects ICMPv4-specific stats.
  1379  type ICMPv4Stats struct {
  1380  	// LINT.IfChange(ICMPv4Stats)
  1381  
  1382  	// PacketsSent contains statistics about sent packets.
  1383  	PacketsSent ICMPv4SentPacketStats
  1384  
  1385  	// PacketsReceived contains statistics about received packets.
  1386  	PacketsReceived ICMPv4ReceivedPacketStats
  1387  
  1388  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterICMPv4Stats)
  1389  }
  1390  
  1391  // ICMPv6PacketStats enumerates counts for all ICMPv6 packet types.
  1392  type ICMPv6PacketStats struct {
  1393  	// LINT.IfChange(ICMPv6PacketStats)
  1394  
  1395  	// EchoRequest is the number of ICMPv6 echo request packets counted.
  1396  	EchoRequest *StatCounter
  1397  
  1398  	// EchoReply is the number of ICMPv6 echo reply packets counted.
  1399  	EchoReply *StatCounter
  1400  
  1401  	// DstUnreachable is the number of ICMPv6 destination unreachable packets
  1402  	// counted.
  1403  	DstUnreachable *StatCounter
  1404  
  1405  	// PacketTooBig is the number of ICMPv6 packet too big packets counted.
  1406  	PacketTooBig *StatCounter
  1407  
  1408  	// TimeExceeded is the number of ICMPv6 time exceeded packets counted.
  1409  	TimeExceeded *StatCounter
  1410  
  1411  	// ParamProblem is the number of ICMPv6 parameter problem packets counted.
  1412  	ParamProblem *StatCounter
  1413  
  1414  	// RouterSolicit is the number of ICMPv6 router solicit packets counted.
  1415  	RouterSolicit *StatCounter
  1416  
  1417  	// RouterAdvert is the number of ICMPv6 router advert packets counted.
  1418  	RouterAdvert *StatCounter
  1419  
  1420  	// NeighborSolicit is the number of ICMPv6 neighbor solicit packets counted.
  1421  	NeighborSolicit *StatCounter
  1422  
  1423  	// NeighborAdvert is the number of ICMPv6 neighbor advert packets counted.
  1424  	NeighborAdvert *StatCounter
  1425  
  1426  	// RedirectMsg is the number of ICMPv6 redirect message packets counted.
  1427  	RedirectMsg *StatCounter
  1428  
  1429  	// MulticastListenerQuery is the number of Multicast Listener Query messages
  1430  	// counted.
  1431  	MulticastListenerQuery *StatCounter
  1432  
  1433  	// MulticastListenerReport is the number of Multicast Listener Report messages
  1434  	// counted.
  1435  	MulticastListenerReport *StatCounter
  1436  
  1437  	// MulticastListenerDone is the number of Multicast Listener Done messages
  1438  	// counted.
  1439  	MulticastListenerDone *StatCounter
  1440  
  1441  	// LINT.ThenChange(network/ipv6/stats.go:multiCounterICMPv6PacketStats)
  1442  }
  1443  
  1444  // ICMPv6SentPacketStats collects outbound ICMPv6-specific stats.
  1445  type ICMPv6SentPacketStats struct {
  1446  	// LINT.IfChange(ICMPv6SentPacketStats)
  1447  
  1448  	ICMPv6PacketStats
  1449  
  1450  	// Dropped is the number of ICMPv6 packets dropped due to link layer errors.
  1451  	Dropped *StatCounter
  1452  
  1453  	// RateLimited is the number of ICMPv6 packets dropped due to rate limit being
  1454  	// exceeded.
  1455  	RateLimited *StatCounter
  1456  
  1457  	// LINT.ThenChange(network/ipv6/stats.go:multiCounterICMPv6SentPacketStats)
  1458  }
  1459  
  1460  // ICMPv6ReceivedPacketStats collects inbound ICMPv6-specific stats.
  1461  type ICMPv6ReceivedPacketStats struct {
  1462  	// LINT.IfChange(ICMPv6ReceivedPacketStats)
  1463  
  1464  	ICMPv6PacketStats
  1465  
  1466  	// Unrecognized is the number of ICMPv6 packets received that the transport
  1467  	// layer does not know how to parse.
  1468  	Unrecognized *StatCounter
  1469  
  1470  	// Invalid is the number of invalid ICMPv6 packets received.
  1471  	Invalid *StatCounter
  1472  
  1473  	// RouterOnlyPacketsDroppedByHost is the number of ICMPv6 packets dropped due
  1474  	// to being router-specific packets.
  1475  	RouterOnlyPacketsDroppedByHost *StatCounter
  1476  
  1477  	// LINT.ThenChange(network/ipv6/stats.go:multiCounterICMPv6ReceivedPacketStats)
  1478  }
  1479  
  1480  // ICMPv6Stats collects ICMPv6-specific stats.
  1481  type ICMPv6Stats struct {
  1482  	// LINT.IfChange(ICMPv6Stats)
  1483  
  1484  	// PacketsSent contains statistics about sent packets.
  1485  	PacketsSent ICMPv6SentPacketStats
  1486  
  1487  	// PacketsReceived contains statistics about received packets.
  1488  	PacketsReceived ICMPv6ReceivedPacketStats
  1489  
  1490  	// LINT.ThenChange(network/ipv6/stats.go:multiCounterICMPv6Stats)
  1491  }
  1492  
  1493  // ICMPStats collects ICMP-specific stats (both v4 and v6).
  1494  type ICMPStats struct {
  1495  	// V4 contains the ICMPv4-specifics stats.
  1496  	V4 ICMPv4Stats
  1497  
  1498  	// V6 contains the ICMPv4-specifics stats.
  1499  	V6 ICMPv6Stats
  1500  }
  1501  
  1502  // IGMPPacketStats enumerates counts for all IGMP packet types.
  1503  type IGMPPacketStats struct {
  1504  	// LINT.IfChange(IGMPPacketStats)
  1505  
  1506  	// MembershipQuery is the number of Membership Query messages counted.
  1507  	MembershipQuery *StatCounter
  1508  
  1509  	// V1MembershipReport is the number of Version 1 Membership Report messages
  1510  	// counted.
  1511  	V1MembershipReport *StatCounter
  1512  
  1513  	// V2MembershipReport is the number of Version 2 Membership Report messages
  1514  	// counted.
  1515  	V2MembershipReport *StatCounter
  1516  
  1517  	// LeaveGroup is the number of Leave Group messages counted.
  1518  	LeaveGroup *StatCounter
  1519  
  1520  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterIGMPPacketStats)
  1521  }
  1522  
  1523  // IGMPSentPacketStats collects outbound IGMP-specific stats.
  1524  type IGMPSentPacketStats struct {
  1525  	// LINT.IfChange(IGMPSentPacketStats)
  1526  
  1527  	IGMPPacketStats
  1528  
  1529  	// Dropped is the number of IGMP packets dropped.
  1530  	Dropped *StatCounter
  1531  
  1532  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterIGMPSentPacketStats)
  1533  }
  1534  
  1535  // IGMPReceivedPacketStats collects inbound IGMP-specific stats.
  1536  type IGMPReceivedPacketStats struct {
  1537  	// LINT.IfChange(IGMPReceivedPacketStats)
  1538  
  1539  	IGMPPacketStats
  1540  
  1541  	// Invalid is the number of invalid IGMP packets received.
  1542  	Invalid *StatCounter
  1543  
  1544  	// ChecksumErrors is the number of IGMP packets dropped due to bad checksums.
  1545  	ChecksumErrors *StatCounter
  1546  
  1547  	// Unrecognized is the number of unrecognized messages counted, these are
  1548  	// silently ignored for forward-compatibilty.
  1549  	Unrecognized *StatCounter
  1550  
  1551  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterIGMPReceivedPacketStats)
  1552  }
  1553  
  1554  // IGMPStats collects IGMP-specific stats.
  1555  type IGMPStats struct {
  1556  	// LINT.IfChange(IGMPStats)
  1557  
  1558  	// PacketsSent contains statistics about sent packets.
  1559  	PacketsSent IGMPSentPacketStats
  1560  
  1561  	// PacketsReceived contains statistics about received packets.
  1562  	PacketsReceived IGMPReceivedPacketStats
  1563  
  1564  	// LINT.ThenChange(network/ipv4/stats.go:multiCounterIGMPStats)
  1565  }
  1566  
  1567  // IPForwardingStats collects stats related to IP forwarding (both v4 and v6).
  1568  type IPForwardingStats struct {
  1569  	// LINT.IfChange(IPForwardingStats)
  1570  
  1571  	// Unrouteable is the number of IP packets received which were dropped
  1572  	// because a route to their destination could not be constructed.
  1573  	Unrouteable *StatCounter
  1574  
  1575  	// ExhaustedTTL is the number of IP packets received which were dropped
  1576  	// because their TTL was exhausted.
  1577  	ExhaustedTTL *StatCounter
  1578  
  1579  	// LinkLocalSource is the number of IP packets which were dropped
  1580  	// because they contained a link-local source address.
  1581  	LinkLocalSource *StatCounter
  1582  
  1583  	// LinkLocalDestination is the number of IP packets which were dropped
  1584  	// because they contained a link-local destination address.
  1585  	LinkLocalDestination *StatCounter
  1586  
  1587  	// PacketTooBig is the number of IP packets which were dropped because they
  1588  	// were too big for the outgoing MTU.
  1589  	PacketTooBig *StatCounter
  1590  
  1591  	// HostUnreachable is the number of IP packets received which could not be
  1592  	// successfully forwarded due to an unresolvable next hop.
  1593  	HostUnreachable *StatCounter
  1594  
  1595  	// ExtensionHeaderProblem is the number of IP packets which were dropped
  1596  	// because of a problem encountered when processing an IPv6 extension
  1597  	// header.
  1598  	ExtensionHeaderProblem *StatCounter
  1599  
  1600  	// Errors is the number of IP packets received which could not be
  1601  	// successfully forwarded.
  1602  	Errors *StatCounter
  1603  
  1604  	// LINT.ThenChange(network/internal/ip/stats.go:multiCounterIPForwardingStats)
  1605  }
  1606  
  1607  // IPStats collects IP-specific stats (both v4 and v6).
  1608  type IPStats struct {
  1609  	// LINT.IfChange(IPStats)
  1610  
  1611  	// PacketsReceived is the number of IP packets received from the link layer.
  1612  	PacketsReceived *StatCounter
  1613  
  1614  	// ValidPacketsReceived is the number of valid IP packets that reached the IP
  1615  	// layer.
  1616  	ValidPacketsReceived *StatCounter
  1617  
  1618  	// DisabledPacketsReceived is the number of IP packets received from the link
  1619  	// layer when the IP layer is disabled.
  1620  	DisabledPacketsReceived *StatCounter
  1621  
  1622  	// InvalidDestinationAddressesReceived is the number of IP packets received
  1623  	// with an unknown or invalid destination address.
  1624  	InvalidDestinationAddressesReceived *StatCounter
  1625  
  1626  	// InvalidSourceAddressesReceived is the number of IP packets received with a
  1627  	// source address that should never have been received on the wire.
  1628  	InvalidSourceAddressesReceived *StatCounter
  1629  
  1630  	// PacketsDelivered is the number of incoming IP packets that are successfully
  1631  	// delivered to the transport layer.
  1632  	PacketsDelivered *StatCounter
  1633  
  1634  	// PacketsSent is the number of IP packets sent via WritePacket.
  1635  	PacketsSent *StatCounter
  1636  
  1637  	// OutgoingPacketErrors is the number of IP packets which failed to write to a
  1638  	// link-layer endpoint.
  1639  	OutgoingPacketErrors *StatCounter
  1640  
  1641  	// MalformedPacketsReceived is the number of IP Packets that were dropped due
  1642  	// to the IP packet header failing validation checks.
  1643  	MalformedPacketsReceived *StatCounter
  1644  
  1645  	// MalformedFragmentsReceived is the number of IP Fragments that were dropped
  1646  	// due to the fragment failing validation checks.
  1647  	MalformedFragmentsReceived *StatCounter
  1648  
  1649  	// IPTablesPreroutingDropped is the number of IP packets dropped in the
  1650  	// Prerouting chain.
  1651  	IPTablesPreroutingDropped *StatCounter
  1652  
  1653  	// IPTablesInputDropped is the number of IP packets dropped in the Input
  1654  	// chain.
  1655  	IPTablesInputDropped *StatCounter
  1656  
  1657  	// IPTablesForwardDropped is the number of IP packets dropped in the Forward
  1658  	// chain.
  1659  	IPTablesForwardDropped *StatCounter
  1660  
  1661  	// IPTablesOutputDropped is the number of IP packets dropped in the Output
  1662  	// chain.
  1663  	IPTablesOutputDropped *StatCounter
  1664  
  1665  	// IPTablesPostroutingDropped is the number of IP packets dropped in the
  1666  	// Postrouting chain.
  1667  	IPTablesPostroutingDropped *StatCounter
  1668  
  1669  	// TODO(https://github.com/SagerNet/issues/5529): Move the IPv4-only option stats out
  1670  	// of IPStats.
  1671  	// OptionTimestampReceived is the number of Timestamp options seen.
  1672  	OptionTimestampReceived *StatCounter
  1673  
  1674  	// OptionRecordRouteReceived is the number of Record Route options seen.
  1675  	OptionRecordRouteReceived *StatCounter
  1676  
  1677  	// OptionRouterAlertReceived is the number of Router Alert options seen.
  1678  	OptionRouterAlertReceived *StatCounter
  1679  
  1680  	// OptionUnknownReceived is the number of unknown IP options seen.
  1681  	OptionUnknownReceived *StatCounter
  1682  
  1683  	// Forwarding collects stats related to IP forwarding.
  1684  	Forwarding IPForwardingStats
  1685  
  1686  	// LINT.ThenChange(network/internal/ip/stats.go:MultiCounterIPStats)
  1687  }
  1688  
  1689  // ARPStats collects ARP-specific stats.
  1690  type ARPStats struct {
  1691  	// LINT.IfChange(ARPStats)
  1692  
  1693  	// PacketsReceived is the number of ARP packets received from the link layer.
  1694  	PacketsReceived *StatCounter
  1695  
  1696  	// DisabledPacketsReceived is the number of ARP packets received from the link
  1697  	// layer when the ARP layer is disabled.
  1698  	DisabledPacketsReceived *StatCounter
  1699  
  1700  	// MalformedPacketsReceived is the number of ARP packets that were dropped due
  1701  	// to being malformed.
  1702  	MalformedPacketsReceived *StatCounter
  1703  
  1704  	// RequestsReceived is the number of ARP requests received.
  1705  	RequestsReceived *StatCounter
  1706  
  1707  	// RequestsReceivedUnknownTargetAddress is the number of ARP requests that
  1708  	// were targeted to an interface different from the one it was received on.
  1709  	RequestsReceivedUnknownTargetAddress *StatCounter
  1710  
  1711  	// OutgoingRequestInterfaceHasNoLocalAddressErrors is the number of failures
  1712  	// to send an ARP request because the interface has no network address
  1713  	// assigned to it.
  1714  	OutgoingRequestInterfaceHasNoLocalAddressErrors *StatCounter
  1715  
  1716  	// OutgoingRequestBadLocalAddressErrors is the number of failures to send an
  1717  	// ARP request with a bad local address.
  1718  	OutgoingRequestBadLocalAddressErrors *StatCounter
  1719  
  1720  	// OutgoingRequestsDropped is the number of ARP requests which failed to write
  1721  	// to a link-layer endpoint.
  1722  	OutgoingRequestsDropped *StatCounter
  1723  
  1724  	// OutgoingRequestSent is the number of ARP requests successfully written to a
  1725  	// link-layer endpoint.
  1726  	OutgoingRequestsSent *StatCounter
  1727  
  1728  	// RepliesReceived is the number of ARP replies received.
  1729  	RepliesReceived *StatCounter
  1730  
  1731  	// OutgoingRepliesDropped is the number of ARP replies which failed to write
  1732  	// to a link-layer endpoint.
  1733  	OutgoingRepliesDropped *StatCounter
  1734  
  1735  	// OutgoingRepliesSent is the number of ARP replies successfully written to a
  1736  	// link-layer endpoint.
  1737  	OutgoingRepliesSent *StatCounter
  1738  
  1739  	// LINT.ThenChange(network/arp/stats.go:multiCounterARPStats)
  1740  }
  1741  
  1742  // TCPStats collects TCP-specific stats.
  1743  type TCPStats struct {
  1744  	// ActiveConnectionOpenings is the number of connections opened
  1745  	// successfully via Connect.
  1746  	ActiveConnectionOpenings *StatCounter
  1747  
  1748  	// PassiveConnectionOpenings is the number of connections opened
  1749  	// successfully via Listen.
  1750  	PassiveConnectionOpenings *StatCounter
  1751  
  1752  	// CurrentEstablished is the number of TCP connections for which the
  1753  	// current state is ESTABLISHED.
  1754  	CurrentEstablished *StatCounter
  1755  
  1756  	// CurrentConnected is the number of TCP connections that
  1757  	// are in connected state.
  1758  	CurrentConnected *StatCounter
  1759  
  1760  	// EstablishedResets is the number of times TCP connections have made
  1761  	// a direct transition to the CLOSED state from either the
  1762  	// ESTABLISHED state or the CLOSE-WAIT state.
  1763  	EstablishedResets *StatCounter
  1764  
  1765  	// EstablishedClosed is the number of times established TCP connections
  1766  	// made a transition to CLOSED state.
  1767  	EstablishedClosed *StatCounter
  1768  
  1769  	// EstablishedTimedout is the number of times an established connection
  1770  	// was reset because of keep-alive time out.
  1771  	EstablishedTimedout *StatCounter
  1772  
  1773  	// ListenOverflowSynDrop is the number of times the listen queue overflowed
  1774  	// and a SYN was dropped.
  1775  	ListenOverflowSynDrop *StatCounter
  1776  
  1777  	// ListenOverflowAckDrop is the number of times the final ACK
  1778  	// in the handshake was dropped due to overflow.
  1779  	ListenOverflowAckDrop *StatCounter
  1780  
  1781  	// ListenOverflowCookieSent is the number of times a SYN cookie was sent.
  1782  	ListenOverflowSynCookieSent *StatCounter
  1783  
  1784  	// ListenOverflowSynCookieRcvd is the number of times a valid SYN
  1785  	// cookie was received.
  1786  	ListenOverflowSynCookieRcvd *StatCounter
  1787  
  1788  	// ListenOverflowInvalidSynCookieRcvd is the number of times an invalid SYN cookie
  1789  	// was received.
  1790  	ListenOverflowInvalidSynCookieRcvd *StatCounter
  1791  
  1792  	// FailedConnectionAttempts is the number of calls to Connect or Listen
  1793  	// (active and passive openings, respectively) that end in an error.
  1794  	FailedConnectionAttempts *StatCounter
  1795  
  1796  	// ValidSegmentsReceived is the number of TCP segments received that
  1797  	// the transport layer successfully parsed.
  1798  	ValidSegmentsReceived *StatCounter
  1799  
  1800  	// InvalidSegmentsReceived is the number of TCP segments received that
  1801  	// the transport layer could not parse.
  1802  	InvalidSegmentsReceived *StatCounter
  1803  
  1804  	// SegmentsSent is the number of TCP segments sent.
  1805  	SegmentsSent *StatCounter
  1806  
  1807  	// SegmentSendErrors is the number of TCP segments failed to be sent.
  1808  	SegmentSendErrors *StatCounter
  1809  
  1810  	// ResetsSent is the number of TCP resets sent.
  1811  	ResetsSent *StatCounter
  1812  
  1813  	// ResetsReceived is the number of TCP resets received.
  1814  	ResetsReceived *StatCounter
  1815  
  1816  	// Retransmits is the number of TCP segments retransmitted.
  1817  	Retransmits *StatCounter
  1818  
  1819  	// FastRecovery is the number of times Fast Recovery was used to
  1820  	// recover from packet loss.
  1821  	FastRecovery *StatCounter
  1822  
  1823  	// SACKRecovery is the number of times SACK Recovery was used to
  1824  	// recover from packet loss.
  1825  	SACKRecovery *StatCounter
  1826  
  1827  	// TLPRecovery is the number of times recovery was accomplished by the tail
  1828  	// loss probe.
  1829  	TLPRecovery *StatCounter
  1830  
  1831  	// SlowStartRetransmits is the number of segments retransmitted in slow
  1832  	// start.
  1833  	SlowStartRetransmits *StatCounter
  1834  
  1835  	// FastRetransmit is the number of segments retransmitted in fast
  1836  	// recovery.
  1837  	FastRetransmit *StatCounter
  1838  
  1839  	// Timeouts is the number of times the RTO expired.
  1840  	Timeouts *StatCounter
  1841  
  1842  	// ChecksumErrors is the number of segments dropped due to bad checksums.
  1843  	ChecksumErrors *StatCounter
  1844  
  1845  	// FailedPortReservations is the number of times TCP failed to reserve
  1846  	// a port.
  1847  	FailedPortReservations *StatCounter
  1848  }
  1849  
  1850  // UDPStats collects UDP-specific stats.
  1851  type UDPStats struct {
  1852  	// PacketsReceived is the number of UDP datagrams received via
  1853  	// HandlePacket.
  1854  	PacketsReceived *StatCounter
  1855  
  1856  	// UnknownPortErrors is the number of incoming UDP datagrams dropped
  1857  	// because they did not have a known destination port.
  1858  	UnknownPortErrors *StatCounter
  1859  
  1860  	// ReceiveBufferErrors is the number of incoming UDP datagrams dropped
  1861  	// due to the receiving buffer being in an invalid state.
  1862  	ReceiveBufferErrors *StatCounter
  1863  
  1864  	// MalformedPacketsReceived is the number of incoming UDP datagrams
  1865  	// dropped due to the UDP header being in a malformed state.
  1866  	MalformedPacketsReceived *StatCounter
  1867  
  1868  	// PacketsSent is the number of UDP datagrams sent via sendUDP.
  1869  	PacketsSent *StatCounter
  1870  
  1871  	// PacketSendErrors is the number of datagrams failed to be sent.
  1872  	PacketSendErrors *StatCounter
  1873  
  1874  	// ChecksumErrors is the number of datagrams dropped due to bad checksums.
  1875  	ChecksumErrors *StatCounter
  1876  }
  1877  
  1878  // NICNeighborStats holds metrics for the neighbor table.
  1879  type NICNeighborStats struct {
  1880  	// LINT.IfChange(NICNeighborStats)
  1881  
  1882  	// UnreachableEntryLookups counts the number of lookups performed on an
  1883  	// entry in Unreachable state.
  1884  	UnreachableEntryLookups *StatCounter
  1885  
  1886  	// LINT.ThenChange(stack/nic_stats.go:multiCounterNICNeighborStats)
  1887  }
  1888  
  1889  // NICPacketStats holds basic packet statistics.
  1890  type NICPacketStats struct {
  1891  	// LINT.IfChange(NICPacketStats)
  1892  
  1893  	// Packets is the number of packets counted.
  1894  	Packets *StatCounter
  1895  
  1896  	// Bytes is the number of bytes counted.
  1897  	Bytes *StatCounter
  1898  
  1899  	// LINT.ThenChange(stack/nic_stats.go:multiCounterNICPacketStats)
  1900  }
  1901  
  1902  // NICStats holds NIC statistics.
  1903  type NICStats struct {
  1904  	// LINT.IfChange(NICStats)
  1905  
  1906  	// UnknownL3ProtocolRcvdPackets is the number of packets received that were
  1907  	// for an unknown or unsupported network protocol.
  1908  	UnknownL3ProtocolRcvdPackets *StatCounter
  1909  
  1910  	// UnknownL4ProtocolRcvdPackets is the number of packets received that were
  1911  	// for an unknown or unsupported transport protocol.
  1912  	UnknownL4ProtocolRcvdPackets *StatCounter
  1913  
  1914  	// MalformedL4RcvdPackets is the number of packets received by a NIC that
  1915  	// could not be delivered to a transport endpoint because the L4 header could
  1916  	// not be parsed.
  1917  	MalformedL4RcvdPackets *StatCounter
  1918  
  1919  	// Tx contains statistics about transmitted packets.
  1920  	Tx NICPacketStats
  1921  
  1922  	// Rx contains statistics about received packets.
  1923  	Rx NICPacketStats
  1924  
  1925  	// DisabledRx contains statistics about received packets on disabled NICs.
  1926  	DisabledRx NICPacketStats
  1927  
  1928  	// Neighbor contains statistics about neighbor entries.
  1929  	Neighbor NICNeighborStats
  1930  
  1931  	// LINT.ThenChange(stack/nic_stats.go:multiCounterNICStats)
  1932  }
  1933  
  1934  // FillIn returns a copy of s with nil fields initialized to new StatCounters.
  1935  func (s NICStats) FillIn() NICStats {
  1936  	InitStatCounters(reflect.ValueOf(&s).Elem())
  1937  	return s
  1938  }
  1939  
  1940  // Stats holds statistics about the networking stack.
  1941  type Stats struct {
  1942  	// TODO(https://github.com/SagerNet/issues/5986): Make the DroppedPackets stat less
  1943  	// ambiguous.
  1944  
  1945  	// DroppedPackets is the number of packets dropped at the transport layer.
  1946  	DroppedPackets *StatCounter
  1947  
  1948  	// NICs is an aggregation of every NIC's statistics. These should not be
  1949  	// incremented using this field, but using the relevant NIC multicounters.
  1950  	NICs NICStats
  1951  
  1952  	// ICMP is an aggregation of every NetworkEndpoint's ICMP statistics (both v4
  1953  	// and v6). These should not be incremented using this field, but using the
  1954  	// relevant NetworkEndpoint ICMP multicounters.
  1955  	ICMP ICMPStats
  1956  
  1957  	// IGMP is an aggregation of every NetworkEndpoint's IGMP statistics. These
  1958  	// should not be incremented using this field, but using the relevant
  1959  	// NetworkEndpoint IGMP multicounters.
  1960  	IGMP IGMPStats
  1961  
  1962  	// IP is an aggregation of every NetworkEndpoint's IP statistics. These should
  1963  	// not be incremented using this field, but using the relevant NetworkEndpoint
  1964  	// IP multicounters.
  1965  	IP IPStats
  1966  
  1967  	// ARP is an aggregation of every NetworkEndpoint's ARP statistics. These
  1968  	// should not be incremented using this field, but using the relevant
  1969  	// NetworkEndpoint ARP multicounters.
  1970  	ARP ARPStats
  1971  
  1972  	// TCP holds TCP-specific stats.
  1973  	TCP TCPStats
  1974  
  1975  	// UDP holds UDP-specific stats.
  1976  	UDP UDPStats
  1977  }
  1978  
  1979  // ReceiveErrors collects packet receive errors within transport endpoint.
  1980  type ReceiveErrors struct {
  1981  	// ReceiveBufferOverflow is the number of received packets dropped
  1982  	// due to the receive buffer being full.
  1983  	ReceiveBufferOverflow StatCounter
  1984  
  1985  	// MalformedPacketsReceived is the number of incoming packets
  1986  	// dropped due to the packet header being in a malformed state.
  1987  	MalformedPacketsReceived StatCounter
  1988  
  1989  	// ClosedReceiver is the number of received packets dropped because
  1990  	// of receiving endpoint state being closed.
  1991  	ClosedReceiver StatCounter
  1992  
  1993  	// ChecksumErrors is the number of packets dropped due to bad checksums.
  1994  	ChecksumErrors StatCounter
  1995  }
  1996  
  1997  // SendErrors collects packet send errors within the transport layer for
  1998  // an endpoint.
  1999  type SendErrors struct {
  2000  	// SendToNetworkFailed is the number of packets failed to be written to
  2001  	// the network endpoint.
  2002  	SendToNetworkFailed StatCounter
  2003  
  2004  	// NoRoute is the number of times we failed to resolve IP route.
  2005  	NoRoute StatCounter
  2006  }
  2007  
  2008  // ReadErrors collects segment read errors from an endpoint read call.
  2009  type ReadErrors struct {
  2010  	// ReadClosed is the number of received packet drops because the endpoint
  2011  	// was shutdown for read.
  2012  	ReadClosed StatCounter
  2013  
  2014  	// InvalidEndpointState is the number of times we found the endpoint state
  2015  	// to be unexpected.
  2016  	InvalidEndpointState StatCounter
  2017  
  2018  	// NotConnected is the number of times we tried to read but found that the
  2019  	// endpoint was not connected.
  2020  	NotConnected StatCounter
  2021  }
  2022  
  2023  // WriteErrors collects packet write errors from an endpoint write call.
  2024  type WriteErrors struct {
  2025  	// WriteClosed is the number of packet drops because the endpoint
  2026  	// was shutdown for write.
  2027  	WriteClosed StatCounter
  2028  
  2029  	// InvalidEndpointState is the number of times we found the endpoint state
  2030  	// to be unexpected.
  2031  	InvalidEndpointState StatCounter
  2032  
  2033  	// InvalidArgs is the number of times invalid input arguments were
  2034  	// provided for endpoint Write call.
  2035  	InvalidArgs StatCounter
  2036  }
  2037  
  2038  // TransportEndpointStats collects statistics about the endpoint.
  2039  type TransportEndpointStats struct {
  2040  	// PacketsReceived is the number of successful packet receives.
  2041  	PacketsReceived StatCounter
  2042  
  2043  	// PacketsSent is the number of successful packet sends.
  2044  	PacketsSent StatCounter
  2045  
  2046  	// ReceiveErrors collects packet receive errors within transport layer.
  2047  	ReceiveErrors ReceiveErrors
  2048  
  2049  	// ReadErrors collects packet read errors from an endpoint read call.
  2050  	ReadErrors ReadErrors
  2051  
  2052  	// SendErrors collects packet send errors within the transport layer.
  2053  	SendErrors SendErrors
  2054  
  2055  	// WriteErrors collects packet write errors from an endpoint write call.
  2056  	WriteErrors WriteErrors
  2057  }
  2058  
  2059  // IsEndpointStats is an empty method to implement the tcpip.EndpointStats
  2060  // marker interface.
  2061  func (*TransportEndpointStats) IsEndpointStats() {}
  2062  
  2063  // InitStatCounters initializes v's fields with nil StatCounter fields to new
  2064  // StatCounters.
  2065  func InitStatCounters(v reflect.Value) {
  2066  	for i := 0; i < v.NumField(); i++ {
  2067  		v := v.Field(i)
  2068  		if s, ok := v.Addr().Interface().(**StatCounter); ok {
  2069  			if *s == nil {
  2070  				*s = new(StatCounter)
  2071  			}
  2072  		} else {
  2073  			InitStatCounters(v)
  2074  		}
  2075  	}
  2076  }
  2077  
  2078  // FillIn returns a copy of s with nil fields initialized to new StatCounters.
  2079  func (s Stats) FillIn() Stats {
  2080  	InitStatCounters(reflect.ValueOf(&s).Elem())
  2081  	return s
  2082  }
  2083  
  2084  // Clone returns a copy of the TransportEndpointStats by atomically reading
  2085  // each field.
  2086  func (src *TransportEndpointStats) Clone() TransportEndpointStats {
  2087  	var dst TransportEndpointStats
  2088  	clone(reflect.ValueOf(&dst).Elem(), reflect.ValueOf(src).Elem())
  2089  	return dst
  2090  }
  2091  
  2092  func clone(dst reflect.Value, src reflect.Value) {
  2093  	for i := 0; i < dst.NumField(); i++ {
  2094  		d := dst.Field(i)
  2095  		s := src.Field(i)
  2096  		if c, ok := s.Addr().Interface().(*StatCounter); ok {
  2097  			d.Addr().Interface().(*StatCounter).IncrementBy(c.Value())
  2098  		} else {
  2099  			clone(d, s)
  2100  		}
  2101  	}
  2102  }
  2103  
  2104  // String implements the fmt.Stringer interface.
  2105  func (a Address) String() string {
  2106  	switch len(a) {
  2107  	case 4:
  2108  		return fmt.Sprintf("%d.%d.%d.%d", int(a[0]), int(a[1]), int(a[2]), int(a[3]))
  2109  	case 16:
  2110  		// Find the longest subsequence of hexadecimal zeros.
  2111  		start, end := -1, -1
  2112  		for i := 0; i < len(a); i += 2 {
  2113  			j := i
  2114  			for j < len(a) && a[j] == 0 && a[j+1] == 0 {
  2115  				j += 2
  2116  			}
  2117  			if j > i+2 && j-i > end-start {
  2118  				start, end = i, j
  2119  			}
  2120  		}
  2121  
  2122  		var b strings.Builder
  2123  		for i := 0; i < len(a); i += 2 {
  2124  			if i == start {
  2125  				b.WriteString("::")
  2126  				i = end
  2127  				if end >= len(a) {
  2128  					break
  2129  				}
  2130  			} else if i > 0 {
  2131  				b.WriteByte(':')
  2132  			}
  2133  			v := uint16(a[i+0])<<8 | uint16(a[i+1])
  2134  			if v == 0 {
  2135  				b.WriteByte('0')
  2136  			} else {
  2137  				const digits = "0123456789abcdef"
  2138  				for i := uint(3); i < 4; i-- {
  2139  					if v := v >> (i * 4); v != 0 {
  2140  						b.WriteByte(digits[v&0xf])
  2141  					}
  2142  				}
  2143  			}
  2144  		}
  2145  		return b.String()
  2146  	default:
  2147  		return fmt.Sprintf("%x", []byte(a))
  2148  	}
  2149  }
  2150  
  2151  // To4 converts the IPv4 address to a 4-byte representation.
  2152  // If the address is not an IPv4 address, To4 returns "".
  2153  func (a Address) To4() Address {
  2154  	const (
  2155  		ipv4len = 4
  2156  		ipv6len = 16
  2157  	)
  2158  	if len(a) == ipv4len {
  2159  		return a
  2160  	}
  2161  	if len(a) == ipv6len &&
  2162  		isZeros(a[0:10]) &&
  2163  		a[10] == 0xff &&
  2164  		a[11] == 0xff {
  2165  		return a[12:16]
  2166  	}
  2167  	return ""
  2168  }
  2169  
  2170  // isZeros reports whether a is all zeros.
  2171  func isZeros(a Address) bool {
  2172  	for i := 0; i < len(a); i++ {
  2173  		if a[i] != 0 {
  2174  			return false
  2175  		}
  2176  	}
  2177  	return true
  2178  }
  2179  
  2180  // LinkAddress is a byte slice cast as a string that represents a link address.
  2181  // It is typically a 6-byte MAC address.
  2182  type LinkAddress string
  2183  
  2184  // String implements the fmt.Stringer interface.
  2185  func (a LinkAddress) String() string {
  2186  	switch len(a) {
  2187  	case 6:
  2188  		return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", a[0], a[1], a[2], a[3], a[4], a[5])
  2189  	default:
  2190  		return fmt.Sprintf("%x", []byte(a))
  2191  	}
  2192  }
  2193  
  2194  // ParseMACAddress parses an IEEE 802 address.
  2195  //
  2196  // It must be in the format aa:bb:cc:dd:ee:ff or aa-bb-cc-dd-ee-ff.
  2197  func ParseMACAddress(s string) (LinkAddress, error) {
  2198  	parts := strings.FieldsFunc(s, func(c rune) bool {
  2199  		return c == ':' || c == '-'
  2200  	})
  2201  	if len(parts) != 6 {
  2202  		return "", fmt.Errorf("inconsistent parts: %s", s)
  2203  	}
  2204  	addr := make([]byte, 0, len(parts))
  2205  	for _, part := range parts {
  2206  		u, err := strconv.ParseUint(part, 16, 8)
  2207  		if err != nil {
  2208  			return "", fmt.Errorf("invalid hex digits: %s", s)
  2209  		}
  2210  		addr = append(addr, byte(u))
  2211  	}
  2212  	return LinkAddress(addr), nil
  2213  }
  2214  
  2215  // AddressWithPrefix is an address with its subnet prefix length.
  2216  type AddressWithPrefix struct {
  2217  	// Address is a network address.
  2218  	Address Address
  2219  
  2220  	// PrefixLen is the subnet prefix length.
  2221  	PrefixLen int
  2222  }
  2223  
  2224  // String implements the fmt.Stringer interface.
  2225  func (a AddressWithPrefix) String() string {
  2226  	return fmt.Sprintf("%s/%d", a.Address, a.PrefixLen)
  2227  }
  2228  
  2229  // Subnet converts the address and prefix into a Subnet value and returns it.
  2230  func (a AddressWithPrefix) Subnet() Subnet {
  2231  	addrLen := len(a.Address)
  2232  	if a.PrefixLen <= 0 {
  2233  		return Subnet{
  2234  			address: Address(strings.Repeat("\x00", addrLen)),
  2235  			mask:    AddressMask(strings.Repeat("\x00", addrLen)),
  2236  		}
  2237  	}
  2238  	if a.PrefixLen >= addrLen*8 {
  2239  		return Subnet{
  2240  			address: a.Address,
  2241  			mask:    AddressMask(strings.Repeat("\xff", addrLen)),
  2242  		}
  2243  	}
  2244  
  2245  	sa := make([]byte, addrLen)
  2246  	sm := make([]byte, addrLen)
  2247  	n := uint(a.PrefixLen)
  2248  	for i := 0; i < addrLen; i++ {
  2249  		if n >= 8 {
  2250  			sa[i] = a.Address[i]
  2251  			sm[i] = 0xff
  2252  			n -= 8
  2253  			continue
  2254  		}
  2255  		sm[i] = ^byte(0xff >> n)
  2256  		sa[i] = a.Address[i] & sm[i]
  2257  		n = 0
  2258  	}
  2259  
  2260  	// For extra caution, call NewSubnet rather than directly creating the Subnet
  2261  	// value. If that fails it indicates a serious bug in this code, so panic is
  2262  	// in order.
  2263  	s, err := NewSubnet(Address(sa), AddressMask(sm))
  2264  	if err != nil {
  2265  		panic("invalid subnet: " + err.Error())
  2266  	}
  2267  	return s
  2268  }
  2269  
  2270  // ProtocolAddress is an address and the network protocol it is associated
  2271  // with.
  2272  type ProtocolAddress struct {
  2273  	// Protocol is the protocol of the address.
  2274  	Protocol NetworkProtocolNumber
  2275  
  2276  	// AddressWithPrefix is a network address with its subnet prefix length.
  2277  	AddressWithPrefix AddressWithPrefix
  2278  }
  2279  
  2280  var (
  2281  	// danglingEndpointsMu protects access to danglingEndpoints.
  2282  	danglingEndpointsMu sync.Mutex
  2283  
  2284  	// danglingEndpoints tracks all dangling endpoints no longer owned by the app.
  2285  	danglingEndpoints = make(map[Endpoint]struct{})
  2286  )
  2287  
  2288  // GetDanglingEndpoints returns all dangling endpoints.
  2289  func GetDanglingEndpoints() []Endpoint {
  2290  	danglingEndpointsMu.Lock()
  2291  	es := make([]Endpoint, 0, len(danglingEndpoints))
  2292  	for e := range danglingEndpoints {
  2293  		es = append(es, e)
  2294  	}
  2295  	danglingEndpointsMu.Unlock()
  2296  	return es
  2297  }
  2298  
  2299  // AddDanglingEndpoint adds a dangling endpoint.
  2300  func AddDanglingEndpoint(e Endpoint) {
  2301  	danglingEndpointsMu.Lock()
  2302  	danglingEndpoints[e] = struct{}{}
  2303  	danglingEndpointsMu.Unlock()
  2304  }
  2305  
  2306  // DeleteDanglingEndpoint removes a dangling endpoint.
  2307  func DeleteDanglingEndpoint(e Endpoint) {
  2308  	danglingEndpointsMu.Lock()
  2309  	delete(danglingEndpoints, e)
  2310  	danglingEndpointsMu.Unlock()
  2311  }
  2312  
  2313  // AsyncLoading is the global barrier for asynchronous endpoint loading
  2314  // activities.
  2315  var AsyncLoading sync.WaitGroup