tcpip

package
v0.0.0-...-522126a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2019 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package tcpip provides the interfaces and related types that users of the tcpip stack will use in order to create endpoints used to send and receive data over the network stack.

The starting point is the creation and configuration of a stack. A stack can be created by calling the New() function of the tcpip/stack/stack package; configuring a stack involves creating NICs (via calls to Stack.CreateNIC()), adding network addresses (via calls to Stack.AddAddress()), and setting a route table (via a call to Stack.SetRouteTable()).

Once a stack is configured, endpoints can be created by calling Stack.NewEndpoint(). Such endpoints can be used to send/receive data, connect to peers, listen for connections, accept connections, etc., depending on the transport protocol selected.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnknownProtocol           = &Error{msg: "unknown protocol"}
	ErrUnknownNICID              = &Error{msg: "unknown nic id"}
	ErrUnknownDevice             = &Error{msg: "unknown device"}
	ErrUnknownProtocolOption     = &Error{msg: "unknown option for protocol"}
	ErrDuplicateNICID            = &Error{msg: "duplicate nic id"}
	ErrDuplicateAddress          = &Error{msg: "duplicate address"}
	ErrNoRoute                   = &Error{msg: "no route"}
	ErrBadLinkEndpoint           = &Error{msg: "bad link layer endpoint"}
	ErrAlreadyBound              = &Error{msg: "endpoint already bound", ignoreStats: true}
	ErrInvalidEndpointState      = &Error{msg: "endpoint is in invalid state"}
	ErrAlreadyConnecting         = &Error{msg: "endpoint is already connecting", ignoreStats: true}
	ErrAlreadyConnected          = &Error{msg: "endpoint is already connected", ignoreStats: true}
	ErrNoPortAvailable           = &Error{msg: "no ports are available"}
	ErrPortInUse                 = &Error{msg: "port is in use"}
	ErrBadLocalAddress           = &Error{msg: "bad local address"}
	ErrClosedForSend             = &Error{msg: "endpoint is closed for send"}
	ErrClosedForReceive          = &Error{msg: "endpoint is closed for receive"}
	ErrWouldBlock                = &Error{msg: "operation would block", ignoreStats: true}
	ErrConnectionRefused         = &Error{msg: "connection was refused"}
	ErrTimeout                   = &Error{msg: "operation timed out"}
	ErrAborted                   = &Error{msg: "operation aborted"}
	ErrConnectStarted            = &Error{msg: "connection attempt started", ignoreStats: true}
	ErrDestinationRequired       = &Error{msg: "destination address is required"}
	ErrNotSupported              = &Error{msg: "operation not supported"}
	ErrQueueSizeNotSupported     = &Error{msg: "queue size querying not supported"}
	ErrNotConnected              = &Error{msg: "endpoint not connected"}
	ErrConnectionReset           = &Error{msg: "connection reset by peer"}
	ErrConnectionAborted         = &Error{msg: "connection aborted"}
	ErrNoSuchFile                = &Error{msg: "no such file"}
	ErrInvalidOptionValue        = &Error{msg: "invalid option value specified"}
	ErrNoLinkAddress             = &Error{msg: "no remote link address"}
	ErrBadAddress                = &Error{msg: "bad address"}
	ErrNetworkUnreachable        = &Error{msg: "network is unreachable"}
	ErrMessageTooLong            = &Error{msg: "message too long"}
	ErrNoBufferSpace             = &Error{msg: "no buffer space available"}
	ErrBroadcastDisabled         = &Error{msg: "broadcast socket option disabled"}
	ErrNotPermitted              = &Error{msg: "operation not permitted"}
	ErrAddressFamilyNotSupported = &Error{msg: "address family not supported by protocol"}
)

Errors that can be returned by the network stack.

View Source
var AsyncLoading sync.WaitGroup

AsyncLoading is the global barrier for asynchronous endpoint loading activities.

Functions

func AddDanglingEndpoint

func AddDanglingEndpoint(e Endpoint)

AddDanglingEndpoint adds a dangling endpoint.

func DeleteDanglingEndpoint

func DeleteDanglingEndpoint(e Endpoint)

DeleteDanglingEndpoint removes a dangling endpoint.

Types

type AddMembershipOption

type AddMembershipOption MembershipOption

AddMembershipOption is used by SetSockOpt/GetSockOpt to join a multicast group identified by the given multicast address, on the interface matching the given interface address.

type Address

type Address string

Address is a byte slice cast as a string that represents the address of a network node. Or, in the case of unix endpoints, it may represent a path.

func (Address) String

func (a Address) String() string

String implements the fmt.Stringer interface.

func (Address) To4

func (a Address) To4() Address

To4 converts the IPv4 address to a 4-byte representation. If the address is not an IPv4 address, To4 returns "".

type AddressMask

type AddressMask string

AddressMask is a bitmask for an address.

func (AddressMask) Prefix

func (m AddressMask) Prefix() int

Prefix returns the number of bits before the first host bit.

func (AddressMask) String

func (m AddressMask) String() string

String implements Stringer.

type AddressWithPrefix

type AddressWithPrefix struct {
	// Address is a network address.
	Address Address

	// PrefixLen is the subnet prefix length.
	PrefixLen int
}

AddressWithPrefix is an address with its subnet prefix length.

func (AddressWithPrefix) String

func (a AddressWithPrefix) String() string

String implements the fmt.Stringer interface.

func (AddressWithPrefix) Subnet

func (a AddressWithPrefix) Subnet() Subnet

Subnet converts the address and prefix into a Subnet value and returns it.

type AvailableCongestionControlOption

type AvailableCongestionControlOption string

AvailableCongestionControlOption is used to query the supported congestion control algorithms.

type BindToDeviceOption

type BindToDeviceOption string

BindToDeviceOption is used by SetSockOpt/GetSockOpt to specify that sockets should bind only on a specific NIC.

type BroadcastOption

type BroadcastOption int

BroadcastOption is used by SetSockOpt/GetSockOpt to specify whether datagram sockets are allowed to send packets to a broadcast address.

type Clock

type Clock interface {
	// NowNanoseconds returns the current real time as a number of
	// nanoseconds since the Unix epoch.
	NowNanoseconds() int64

	// NowMonotonic returns a monotonic time value.
	NowMonotonic() int64
}

A Clock provides the current time.

Times returned by a Clock should always be used for application-visible time. Only monotonic times should be used for netstack internal timekeeping.

type CongestionControlOption

type CongestionControlOption string

CongestionControlOption is used by SetSockOpt/GetSockOpt to set/get the current congestion control algorithm.

type ControlMessages

type ControlMessages struct {
	// HasTimestamp indicates whether Timestamp is valid/set.
	HasTimestamp bool

	// Timestamp is the time (in ns) that the last packet used to create
	// the read data was received.
	Timestamp int64

	// HasInq indicates whether Inq is valid/set.
	HasInq bool

	// Inq is the number of bytes ready to be received.
	Inq int32

	// HasTOS indicates whether Tos is valid/set.
	HasTOS bool

	// TOS is the IPv4 type of service of the associated packet.
	TOS int8

	// HasTClass indicates whether Tclass is valid/set.
	HasTClass bool

	// Tclass is the IPv6 traffic class of the associated packet.
	TClass int32
}

A ControlMessages contains socket control messages for IP sockets.

+stateify savable

type CorkOption

type CorkOption int

CorkOption is used by SetSockOpt/GetSockOpt to specify if data should be held until segments are full by the TCP transport protocol.

type DefaultTTLOption

type DefaultTTLOption uint8

DefaultTTLOption is used by stack.(*Stack).NetworkProtocolOption to specify a default TTL.

type Endpoint

type Endpoint interface {
	// Close puts the endpoint in a closed state and frees all resources
	// associated with it.
	Close()

	// Read reads data from the endpoint and optionally returns the sender.
	//
	// This method does not block if there is no data pending. It will also
	// either return an error or data, never both.
	Read(*FullAddress) (buffer.View, ControlMessages, *Error)

	// Write writes data to the endpoint's peer. This method does not block if
	// the data cannot be written.
	//
	// Unlike io.Writer.Write, Endpoint.Write transfers ownership of any bytes
	// successfully written to the Endpoint. That is, if a call to
	// Write(SlicePayload{data}) returns (n, err), it may retain data[:n], and
	// the caller should not use data[:n] after Write returns.
	//
	// Note that unlike io.Writer.Write, it is not an error for Write to
	// perform a partial write (if n > 0, no error may be returned). Only
	// stream (TCP) Endpoints may return partial writes, and even then only
	// in the case where writing additional data would block. Other Endpoints
	// will either write the entire message or return an error.
	//
	// For UDP and Ping sockets if address resolution is required,
	// ErrNoLinkAddress and a notification channel is returned for the caller to
	// block. Channel is closed once address resolution is complete (success or
	// not). The channel is only non-nil in this case.
	Write(Payloader, WriteOptions) (int64, <-chan struct{}, *Error)

	// Peek reads data without consuming it from the endpoint.
	//
	// This method does not block if there is no data pending.
	Peek([][]byte) (int64, ControlMessages, *Error)

	// Connect connects the endpoint to its peer. Specifying a NIC is
	// optional.
	//
	// There are three classes of return values:
	//	nil -- the attempt to connect succeeded.
	//	ErrConnectStarted/ErrAlreadyConnecting -- the connect attempt started
	//		but hasn't completed yet. In this case, the caller must call Connect
	//		or GetSockOpt(ErrorOption) when the endpoint becomes writable to
	//		get the actual result. The first call to Connect after the socket has
	//		connected returns nil. Calling connect again results in ErrAlreadyConnected.
	//	Anything else -- the attempt to connect failed.
	//
	// If address.Addr is empty, this means that Enpoint has to be
	// disconnected if this is supported, otherwise
	// ErrAddressFamilyNotSupported must be returned.
	Connect(address FullAddress) *Error

	// Disconnect disconnects the endpoint from its peer.
	Disconnect() *Error

	// Shutdown closes the read and/or write end of the endpoint connection
	// to its peer.
	Shutdown(flags ShutdownFlags) *Error

	// Listen puts the endpoint in "listen" mode, which allows it to accept
	// new connections.
	Listen(backlog int) *Error

	// Accept returns a new endpoint if a peer has established a connection
	// to an endpoint previously set to listen mode. This method does not
	// block if no new connections are available.
	//
	// The returned Queue is the wait queue for the newly created endpoint.
	Accept() (Endpoint, *waiter.Queue, *Error)

	// Bind binds the endpoint to a specific local address and port.
	// Specifying a NIC is optional.
	Bind(address FullAddress) *Error

	// GetLocalAddress returns the address to which the endpoint is bound.
	GetLocalAddress() (FullAddress, *Error)

	// GetRemoteAddress returns the address to which the endpoint is
	// connected.
	GetRemoteAddress() (FullAddress, *Error)

	// Readiness returns the current readiness of the endpoint. For example,
	// if waiter.EventIn is set, the endpoint is immediately readable.
	Readiness(mask waiter.EventMask) waiter.EventMask

	// SetSockOpt sets a socket option. opt should be one of the *Option types.
	SetSockOpt(opt interface{}) *Error

	// SetSockOptInt sets a socket option, for simple cases where a value
	// has the int type.
	SetSockOptInt(opt SockOpt, v int) *Error

	// GetSockOpt gets a socket option. opt should be a pointer to one of the
	// *Option types.
	GetSockOpt(opt interface{}) *Error

	// GetSockOptInt gets a socket option for simple cases where a return
	// value has the int type.
	GetSockOptInt(SockOpt) (int, *Error)

	// State returns a socket's lifecycle state. The returned value is
	// protocol-specific and is primarily used for diagnostics.
	State() uint32

	// ModerateRecvBuf should be called everytime data is copied to the user
	// space. This allows for dynamic tuning of recv buffer space for a
	// given socket.
	//
	// NOTE: This method is a no-op for sockets other than TCP.
	ModerateRecvBuf(copied int)

	// IPTables returns the iptables for this endpoint's stack.
	IPTables() (iptables.IPTables, error)

	// Info returns a copy to the transport endpoint info.
	Info() EndpointInfo

	// Stats returns a reference to the endpoint stats.
	Stats() EndpointStats
}

Endpoint is the interface implemented by transport protocols (e.g., tcp, udp) that exposes functionality like read, write, connect, etc. to users of the networking stack.

func GetDanglingEndpoints

func GetDanglingEndpoints() []Endpoint

GetDanglingEndpoints returns all dangling endpoints.

type EndpointInfo

type EndpointInfo interface {
	// IsEndpointInfo is an empty method to implement the tcpip.EndpointInfo
	// marker interface.
	IsEndpointInfo()
}

EndpointInfo is the interface implemented by each endpoint info struct.

type EndpointStats

type EndpointStats interface {
	// IsEndpointStats is an empty method to implement the tcpip.EndpointStats
	// marker interface.
	IsEndpointStats()
}

EndpointStats is the interface implemented by each endpoint stats struct.

type ErrSaveRejection

type ErrSaveRejection struct {
	Err error
}

ErrSaveRejection indicates a failed save due to unsupported networking state. This type of errors is only used for save logic.

func (ErrSaveRejection) Error

func (e ErrSaveRejection) Error() string

Error returns a sensible description of the save rejection error.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error represents an error in the netstack error space. Using a special type ensures that errors outside of this space are not accidentally introduced.

Note: to support save / restore, it is important that all tcpip errors have distinct error messages.

func (*Error) IgnoreStats

func (e *Error) IgnoreStats() bool

IgnoreStats indicates whether this error type should be included in failure counts in tcpip.Stats structs.

func (*Error) String

func (e *Error) String() string

String implements fmt.Stringer.String.

type ErrorOption

type ErrorOption struct{}

ErrorOption is used in GetSockOpt to specify that the last error reported by the endpoint should be cleared and returned.

type FullAddress

type FullAddress struct {
	// NIC is the ID of the NIC this address refers to.
	//
	// This may not be used by all endpoint types.
	NIC NICID

	// Addr is the network or link layer address.
	Addr Address

	// Port is the transport port.
	//
	// This may not be used by all endpoint types.
	Port uint16
}

FullAddress represents a full transport node address, as required by the Connect() and Bind() methods.

+stateify savable

type ICMPStats

type ICMPStats struct {
	// ICMPv4SentPacketStats contains counts of sent packets by ICMPv4 packet type
	// and a single count of packets which failed to write to the link
	// layer.
	V4PacketsSent ICMPv4SentPacketStats

	// ICMPv4ReceivedPacketStats contains counts of received packets by ICMPv4
	// packet type and a single count of invalid packets received.
	V4PacketsReceived ICMPv4ReceivedPacketStats

	// ICMPv6SentPacketStats contains counts of sent packets by ICMPv6 packet type
	// and a single count of packets which failed to write to the link
	// layer.
	V6PacketsSent ICMPv6SentPacketStats

	// ICMPv6ReceivedPacketStats contains counts of received packets by ICMPv6
	// packet type and a single count of invalid packets received.
	V6PacketsReceived ICMPv6ReceivedPacketStats
}

ICMPStats collects ICMP-specific stats (both v4 and v6).

type ICMPv4PacketStats

type ICMPv4PacketStats struct {
	// Echo is the total number of ICMPv4 echo packets counted.
	Echo *StatCounter

	// EchoReply is the total number of ICMPv4 echo reply packets counted.
	EchoReply *StatCounter

	// DstUnreachable is the total number of ICMPv4 destination unreachable
	// packets counted.
	DstUnreachable *StatCounter

	// SrcQuench is the total number of ICMPv4 source quench packets
	// counted.
	SrcQuench *StatCounter

	// Redirect is the total number of ICMPv4 redirect packets counted.
	Redirect *StatCounter

	// TimeExceeded is the total number of ICMPv4 time exceeded packets
	// counted.
	TimeExceeded *StatCounter

	// ParamProblem is the total number of ICMPv4 parameter problem packets
	// counted.
	ParamProblem *StatCounter

	// Timestamp is the total number of ICMPv4 timestamp packets counted.
	Timestamp *StatCounter

	// TimestampReply is the total number of ICMPv4 timestamp reply packets
	// counted.
	TimestampReply *StatCounter

	// InfoRequest is the total number of ICMPv4 information request
	// packets counted.
	InfoRequest *StatCounter

	// InfoReply is the total number of ICMPv4 information reply packets
	// counted.
	InfoReply *StatCounter
}

ICMPv4PacketStats enumerates counts for all ICMPv4 packet types.

type ICMPv4ReceivedPacketStats

type ICMPv4ReceivedPacketStats struct {
	ICMPv4PacketStats

	// Invalid is the total number of ICMPv4 packets received that the
	// transport layer could not parse.
	Invalid *StatCounter
}

ICMPv4ReceivedPacketStats collects inbound ICMPv4-specific stats.

type ICMPv4SentPacketStats

type ICMPv4SentPacketStats struct {
	ICMPv4PacketStats

	// Dropped is the total number of ICMPv4 packets dropped due to link
	// layer errors.
	Dropped *StatCounter

	// RateLimited is the total number of ICMPv6 packets dropped due to
	// rate limit being exceeded.
	RateLimited *StatCounter
}

ICMPv4SentPacketStats collects outbound ICMPv4-specific stats.

type ICMPv6PacketStats

type ICMPv6PacketStats struct {
	// EchoRequest is the total number of ICMPv6 echo request packets
	// counted.
	EchoRequest *StatCounter

	// EchoReply is the total number of ICMPv6 echo reply packets counted.
	EchoReply *StatCounter

	// DstUnreachable is the total number of ICMPv6 destination unreachable
	// packets counted.
	DstUnreachable *StatCounter

	// PacketTooBig is the total number of ICMPv6 packet too big packets
	// counted.
	PacketTooBig *StatCounter

	// TimeExceeded is the total number of ICMPv6 time exceeded packets
	// counted.
	TimeExceeded *StatCounter

	// ParamProblem is the total number of ICMPv6 parameter problem packets
	// counted.
	ParamProblem *StatCounter

	// RouterSolicit is the total number of ICMPv6 router solicit packets
	// counted.
	RouterSolicit *StatCounter

	// RouterAdvert is the total number of ICMPv6 router advert packets
	// counted.
	RouterAdvert *StatCounter

	// NeighborSolicit is the total number of ICMPv6 neighbor solicit
	// packets counted.
	NeighborSolicit *StatCounter

	// NeighborAdvert is the total number of ICMPv6 neighbor advert packets
	// counted.
	NeighborAdvert *StatCounter

	// RedirectMsg is the total number of ICMPv6 redirect message packets
	// counted.
	RedirectMsg *StatCounter
}

ICMPv6PacketStats enumerates counts for all ICMPv6 packet types.

type ICMPv6ReceivedPacketStats

type ICMPv6ReceivedPacketStats struct {
	ICMPv6PacketStats

	// Invalid is the total number of ICMPv6 packets received that the
	// transport layer could not parse.
	Invalid *StatCounter
}

ICMPv6ReceivedPacketStats collects inbound ICMPv6-specific stats.

type ICMPv6SentPacketStats

type ICMPv6SentPacketStats struct {
	ICMPv6PacketStats

	// Dropped is the total number of ICMPv6 packets dropped due to link
	// layer errors.
	Dropped *StatCounter

	// RateLimited is the total number of ICMPv6 packets dropped due to
	// rate limit being exceeded.
	RateLimited *StatCounter
}

ICMPv6SentPacketStats collects outbound ICMPv6-specific stats.

type IPStats

type IPStats struct {
	// PacketsReceived is the total number of IP packets received from the
	// link layer in nic.DeliverNetworkPacket.
	PacketsReceived *StatCounter

	// InvalidAddressesReceived is the total number of IP packets received
	// with an unknown or invalid destination address.
	InvalidAddressesReceived *StatCounter

	// PacketsDelivered is the total number of incoming IP packets that
	// are successfully delivered to the transport layer via HandlePacket.
	PacketsDelivered *StatCounter

	// PacketsSent is the total number of IP packets sent via WritePacket.
	PacketsSent *StatCounter

	// OutgoingPacketErrors is the total number of IP packets which failed
	// to write to a link-layer endpoint.
	OutgoingPacketErrors *StatCounter

	// MalformedPacketsReceived is the total number of IP Packets that were
	// dropped due to the IP packet header failing validation checks.
	MalformedPacketsReceived *StatCounter

	// MalformedFragmentsReceived is the total number of IP Fragments that were
	// dropped due to the fragment failing validation checks.
	MalformedFragmentsReceived *StatCounter
}

IPStats collects IP-specific stats (both v4 and v6).

type IPv4TOSOption

type IPv4TOSOption uint8

IPv4TOSOption is used by SetSockOpt/GetSockOpt to specify TOS for all subsequent outgoing IPv4 packets from the endpoint.

type IPv6TrafficClassOption

type IPv6TrafficClassOption uint8

IPv6TrafficClassOption is used by SetSockOpt/GetSockOpt to specify TOS for all subsequent outgoing IPv6 packets from the endpoint.

type KeepaliveCountOption

type KeepaliveCountOption int

KeepaliveCountOption is used by SetSockOpt/GetSockOpt to specify the number of un-ACKed TCP keepalives that will be sent before the connection is closed.

type KeepaliveEnabledOption

type KeepaliveEnabledOption int

KeepaliveEnabledOption is used by SetSockOpt/GetSockOpt to specify whether TCP keepalive is enabled for this socket.

type KeepaliveIdleOption

type KeepaliveIdleOption time.Duration

KeepaliveIdleOption is used by SetSockOpt/GetSockOpt to specify the time a connection must remain idle before the first TCP keepalive packet is sent. Once this time is reached, KeepaliveIntervalOption is used instead.

type KeepaliveIntervalOption

type KeepaliveIntervalOption time.Duration

KeepaliveIntervalOption is used by SetSockOpt/GetSockOpt to specify the interval between sending TCP keepalive packets.

type LinkAddress

type LinkAddress string

LinkAddress is a byte slice cast as a string that represents a link address. It is typically a 6-byte MAC address.

func ParseMACAddress

func ParseMACAddress(s string) (LinkAddress, error)

ParseMACAddress parses an IEEE 802 address.

It must be in the format aa:bb:cc:dd:ee:ff or aa-bb-cc-dd-ee-ff.

func (LinkAddress) String

func (a LinkAddress) String() string

String implements the fmt.Stringer interface.

type MaxSegOption

type MaxSegOption int

MaxSegOption is used by SetSockOpt/GetSockOpt to set/get the current Maximum Segment Size(MSS) value as specified using the TCP_MAXSEG option.

type MembershipOption

type MembershipOption struct {
	NIC           NICID
	InterfaceAddr Address
	MulticastAddr Address
}

MembershipOption is used by SetSockOpt/GetSockOpt as an argument to AddMembershipOption and RemoveMembershipOption.

type ModerateReceiveBufferOption

type ModerateReceiveBufferOption bool

ModerateReceiveBufferOption allows the caller to enable/disable TCP receive buffer moderation.

type MulticastInterfaceOption

type MulticastInterfaceOption struct {
	NIC           NICID
	InterfaceAddr Address
}

MulticastInterfaceOption is used by SetSockOpt/GetSockOpt to specify a default interface for multicast.

type MulticastLoopOption

type MulticastLoopOption bool

MulticastLoopOption is used by SetSockOpt/GetSockOpt to specify whether multicast packets sent over a non-loopback interface will be looped back.

type MulticastTTLOption

type MulticastTTLOption uint8

MulticastTTLOption is used by SetSockOpt/GetSockOpt to control the default TTL value for multicast messages. The default is 1.

type NICID

type NICID int32

NICID is a number that uniquely identifies a NIC.

type NetworkProtocolNumber

type NetworkProtocolNumber uint32

NetworkProtocolNumber is the number of a network protocol.

type OutOfBandInlineOption

type OutOfBandInlineOption int

OutOfBandInlineOption is used by SetSockOpt/GetSockOpt to specify whether TCP out-of-band data is delivered along with the normal in-band data.

type PacketBuffer

type PacketBuffer struct {
	// Data holds the payload of the packet. For inbound packets, it also
	// holds the headers, which are consumed as the packet moves up the
	// stack. Headers are guaranteed not to be split across views.
	//
	// The bytes backing Data are immutable, but Data itself may be trimmed
	// or otherwise modified.
	Data buffer.VectorisedView

	// DataOffset is used for GSO output. It is the offset into the Data
	// field where the payload of this packet starts.
	DataOffset int

	// DataSize is used for GSO output. It is the size of this packet's
	// payload.
	DataSize int

	// Header holds the headers of outbound packets. As a packet is passed
	// down the stack, each layer adds to Header.
	Header buffer.Prependable

	// These fields are used by both inbound and outbound packets. They
	// typically overlap with the Data and Header fields.
	//
	// The bytes backing these views are immutable. Each field may be nil
	// if either it has not been set yet or no such header exists (e.g.
	// packets sent via loopback may not have a link header).
	//
	// These fields may be Views into other slices (either Data or Header).
	// SR dosen't support this, so deep copies are necessary in some cases.
	LinkHeader      buffer.View
	NetworkHeader   buffer.View
	TransportHeader buffer.View
}

A PacketBuffer contains all the data of a network packet.

As a PacketBuffer traverses up the stack, it may be necessary to pass it to multiple endpoints. Clone() should be called in such cases so that modifications to the Data field do not affect other copies.

+stateify savable

func (PacketBuffer) Clone

func (pk PacketBuffer) Clone() PacketBuffer

Clone makes a copy of pk. It clones the Data field, which creates a new VectorisedView but does not deep copy the underlying bytes.

Clone also does not deep copy any of its other fields.

type PasscredOption

type PasscredOption int

PasscredOption is used by SetSockOpt/GetSockOpt to specify whether SCM_CREDENTIALS socket control messages are enabled.

Only supported on Unix sockets.

type Payloader

type Payloader interface {
	// FullPayload returns all available bytes.
	FullPayload() ([]byte, *Error)

	// Payload returns a slice containing at most size bytes.
	Payload(size int) ([]byte, *Error)
}

Payloader is an interface that provides data.

This interface allows the endpoint to request the amount of data it needs based on internal buffers without exposing them.

type ProtocolAddress

type ProtocolAddress struct {
	// Protocol is the protocol of the address.
	Protocol NetworkProtocolNumber

	// AddressWithPrefix is a network address with its subnet prefix length.
	AddressWithPrefix AddressWithPrefix
}

ProtocolAddress is an address and the network protocol it is associated with.

type QuickAckOption

type QuickAckOption int

QuickAckOption is stubbed out in SetSockOpt/GetSockOpt.

type ReadErrors

type ReadErrors struct {
	// ReadClosed is the number of received packet drops because the endpoint
	// was shutdown for read.
	ReadClosed StatCounter

	// InvalidEndpointState is the number of times we found the endpoint state
	// to be unexpected.
	InvalidEndpointState StatCounter
}

ReadErrors collects segment read errors from an endpoint read call.

type ReceiveErrors

type ReceiveErrors struct {
	// ReceiveBufferOverflow is the number of received packets dropped
	// due to the receive buffer being full.
	ReceiveBufferOverflow StatCounter

	// MalformedPacketsReceived is the number of incoming packets
	// dropped due to the packet header being in a malformed state.
	MalformedPacketsReceived StatCounter

	// ClosedReceiver is the number of received packets dropped because
	// of receiving endpoint state being closed.
	ClosedReceiver StatCounter
}

ReceiveErrors collects packet receive errors within transport endpoint.

type RemoveMembershipOption

type RemoveMembershipOption MembershipOption

RemoveMembershipOption is used by SetSockOpt/GetSockOpt to leave a multicast group identified by the given multicast address, on the interface matching the given interface address.

type ReuseAddressOption

type ReuseAddressOption int

ReuseAddressOption is used by SetSockOpt/GetSockOpt to specify whether Bind() should allow reuse of local address.

type ReusePortOption

type ReusePortOption int

ReusePortOption is used by SetSockOpt/GetSockOpt to permit multiple sockets to be bound to an identical socket address.

type Route

type Route struct {
	// Destination must contain the target address for this row to be viable.
	Destination Subnet

	// Gateway is the gateway to be used if this row is viable.
	Gateway Address

	// NIC is the id of the nic to be used if this row is viable.
	NIC NICID
}

Route is a row in the routing table. It specifies through which NIC (and gateway) sets of packets should be routed. A row is considered viable if the masked target address matches the destination address in the row.

func (Route) String

func (r Route) String() string

String implements the fmt.Stringer interface.

type SendErrors

type SendErrors struct {
	// SendToNetworkFailed is the number of packets failed to be written to
	// the network endpoint.
	SendToNetworkFailed StatCounter

	// NoRoute is the number of times we failed to resolve IP route.
	NoRoute StatCounter

	// NoLinkAddr is the number of times we failed to resolve ARP.
	NoLinkAddr StatCounter
}

SendErrors collects packet send errors within the transport layer for an endpoint.

type ShutdownFlags

type ShutdownFlags int

ShutdownFlags represents flags that can be passed to the Shutdown() method of the Endpoint interface.

const (
	ShutdownRead ShutdownFlags = 1 << iota
	ShutdownWrite
)

Values of the flags that can be passed to the Shutdown() method. They can be OR'ed together.

type SlicePayload

type SlicePayload []byte

SlicePayload implements Payloader for slices.

This is typically used for tests.

func (SlicePayload) FullPayload

func (s SlicePayload) FullPayload() ([]byte, *Error)

FullPayload implements Payloader.FullPayload.

func (SlicePayload) Payload

func (s SlicePayload) Payload(size int) ([]byte, *Error)

Payload implements Payloader.Payload.

type SockOpt

type SockOpt int

SockOpt represents socket options which values have the int type.

const (
	// ReceiveQueueSizeOption is used in GetSockOptInt to specify that the
	// number of unread bytes in the input buffer should be returned.
	ReceiveQueueSizeOption SockOpt = iota

	// SendBufferSizeOption is used by SetSockOptInt/GetSockOptInt to
	// specify the send buffer size option.
	SendBufferSizeOption

	// ReceiveBufferSizeOption is used by SetSockOptInt/GetSockOptInt to
	// specify the receive buffer size option.
	ReceiveBufferSizeOption

	// SendQueueSizeOption is used in GetSockOptInt to specify that the
	// number of unread bytes in the output buffer should be returned.
	SendQueueSizeOption

	// DelayOption is used by SetSockOpt/GetSockOpt to specify if data
	// should be sent out immediately by the transport protocol. For TCP,
	// it determines if the Nagle algorithm is on or off.
	DelayOption
)

type StatCounter

type StatCounter struct {
	// contains filtered or unexported fields
}

A StatCounter keeps track of a statistic.

func (*StatCounter) Decrement

func (s *StatCounter) Decrement()

Decrement minuses one to the counter.

func (*StatCounter) Increment

func (s *StatCounter) Increment()

Increment adds one to the counter.

func (*StatCounter) IncrementBy

func (s *StatCounter) IncrementBy(v uint64)

IncrementBy increments the counter by v.

func (*StatCounter) String

func (s *StatCounter) String() string

func (*StatCounter) Value

func (s *StatCounter) Value() uint64

Value returns the current value of the counter.

type Stats

type Stats struct {
	// UnknownProtocolRcvdPackets is the number of packets received by the
	// stack that were for an unknown or unsupported protocol.
	UnknownProtocolRcvdPackets *StatCounter

	// MalformedRcvdPackets is the number of packets received by the stack
	// that were deemed malformed.
	MalformedRcvdPackets *StatCounter

	// DroppedPackets is the number of packets dropped due to full queues.
	DroppedPackets *StatCounter

	// ICMP breaks out ICMP-specific stats (both v4 and v6).
	ICMP ICMPStats

	// IP breaks out IP-specific stats (both v4 and v6).
	IP IPStats

	// TCP breaks out TCP-specific stats.
	TCP TCPStats

	// UDP breaks out UDP-specific stats.
	UDP UDPStats
}

Stats holds statistics about the networking stack.

All fields are optional.

func (Stats) FillIn

func (s Stats) FillIn() Stats

FillIn returns a copy of s with nil fields initialized to new StatCounters.

type Subnet

type Subnet struct {
	// contains filtered or unexported fields
}

Subnet is a subnet defined by its address and mask.

func NewSubnet

func NewSubnet(a Address, m AddressMask) (Subnet, error)

NewSubnet creates a new Subnet, checking that the address and mask are the same length.

func (*Subnet) Bits

func (s *Subnet) Bits() (ones int, zeros int)

Bits returns the number of ones (network bits) and zeros (host bits) in the subnet mask.

func (*Subnet) Broadcast

func (s *Subnet) Broadcast() Address

Broadcast returns the subnet's broadcast address.

func (*Subnet) Contains

func (s *Subnet) Contains(a Address) bool

Contains returns true iff the address is of the same length and matches the subnet address and mask.

func (Subnet) Equal

func (s Subnet) Equal(o Subnet) bool

Equal returns true if s equals o.

Needed to use cmp.Equal on Subnet as its fields are unexported.

func (*Subnet) ID

func (s *Subnet) ID() Address

ID returns the subnet ID.

func (*Subnet) Mask

func (s *Subnet) Mask() AddressMask

Mask returns the subnet mask.

func (*Subnet) Prefix

func (s *Subnet) Prefix() int

Prefix returns the number of bits before the first host bit.

func (Subnet) String

func (s Subnet) String() string

String implements Stringer.

type TCPInfoOption

type TCPInfoOption struct {
	RTT    time.Duration
	RTTVar time.Duration
}

TCPInfoOption is used by GetSockOpt to expose TCP statistics.

TODO(b/64800844): Add and populate stat fields.

type TCPLingerTimeoutOption

type TCPLingerTimeoutOption time.Duration

TCPLingerTimeoutOption is used by SetSockOpt/GetSockOpt to set/get the maximum duration for which a socket lingers in the TCP_FIN_WAIT_2 state before being marked closed.

type TCPStats

type TCPStats struct {
	// ActiveConnectionOpenings is the number of connections opened
	// successfully via Connect.
	ActiveConnectionOpenings *StatCounter

	// PassiveConnectionOpenings is the number of connections opened
	// successfully via Listen.
	PassiveConnectionOpenings *StatCounter

	// CurrentEstablished is the number of TCP connections for which the
	// current state is either ESTABLISHED or CLOSE-WAIT.
	CurrentEstablished *StatCounter

	// EstablishedResets is the number of times TCP connections have made
	// a direct transition to the CLOSED state from either the
	// ESTABLISHED state or the CLOSE-WAIT state.
	EstablishedResets *StatCounter

	// EstablishedClosed is the number of times established TCP connections
	// made a transition to CLOSED state.
	EstablishedClosed *StatCounter

	// EstablishedTimedout is the number of times an established connection
	// was reset because of keep-alive time out.
	EstablishedTimedout *StatCounter

	// ListenOverflowSynDrop is the number of times the listen queue overflowed
	// and a SYN was dropped.
	ListenOverflowSynDrop *StatCounter

	// ListenOverflowAckDrop is the number of times the final ACK
	// in the handshake was dropped due to overflow.
	ListenOverflowAckDrop *StatCounter

	// ListenOverflowCookieSent is the number of times a SYN cookie was sent.
	ListenOverflowSynCookieSent *StatCounter

	// ListenOverflowSynCookieRcvd is the number of times a valid SYN
	// cookie was received.
	ListenOverflowSynCookieRcvd *StatCounter

	// ListenOverflowInvalidSynCookieRcvd is the number of times an invalid SYN cookie
	// was received.
	ListenOverflowInvalidSynCookieRcvd *StatCounter

	// FailedConnectionAttempts is the number of calls to Connect or Listen
	// (active and passive openings, respectively) that end in an error.
	FailedConnectionAttempts *StatCounter

	// ValidSegmentsReceived is the number of TCP segments received that
	// the transport layer successfully parsed.
	ValidSegmentsReceived *StatCounter

	// InvalidSegmentsReceived is the number of TCP segments received that
	// the transport layer could not parse.
	InvalidSegmentsReceived *StatCounter

	// SegmentsSent is the number of TCP segments sent.
	SegmentsSent *StatCounter

	// SegmentSendErrors is the number of TCP segments failed to be sent.
	SegmentSendErrors *StatCounter

	// ResetsSent is the number of TCP resets sent.
	ResetsSent *StatCounter

	// ResetsReceived is the number of TCP resets received.
	ResetsReceived *StatCounter

	// Retransmits is the number of TCP segments retransmitted.
	Retransmits *StatCounter

	// FastRecovery is the number of times Fast Recovery was used to
	// recover from packet loss.
	FastRecovery *StatCounter

	// SACKRecovery is the number of times SACK Recovery was used to
	// recover from packet loss.
	SACKRecovery *StatCounter

	// SlowStartRetransmits is the number of segments retransmitted in slow
	// start.
	SlowStartRetransmits *StatCounter

	// FastRetransmit is the number of segments retransmitted in fast
	// recovery.
	FastRetransmit *StatCounter

	// Timeouts is the number of times the RTO expired.
	Timeouts *StatCounter

	// ChecksumErrors is the number of segments dropped due to bad checksums.
	ChecksumErrors *StatCounter
}

TCPStats collects TCP-specific stats.

type TCPTimeWaitTimeoutOption

type TCPTimeWaitTimeoutOption time.Duration

TCPTimeWaitTimeoutOption is used by SetSockOpt/GetSockOpt to set/get the maximum duration for which a socket lingers in the TIME_WAIT state before being marked closed.

type TCPUserTimeoutOption

type TCPUserTimeoutOption time.Duration

TCPUserTimeoutOption is used by SetSockOpt/GetSockOpt to specify a user specified timeout for a given TCP connection. See: RFC5482 for details.

type TTLOption

type TTLOption uint8

TTLOption is used by SetSockOpt/GetSockOpt to control the default TTL/hop limit value for unicast messages. The default is protocol specific.

A zero value indicates the default.

type TransportEndpointStats

type TransportEndpointStats struct {
	// PacketsReceived is the number of successful packet receives.
	PacketsReceived StatCounter

	// PacketsSent is the number of successful packet sends.
	PacketsSent StatCounter

	// ReceiveErrors collects packet receive errors within transport layer.
	ReceiveErrors ReceiveErrors

	// ReadErrors collects packet read errors from an endpoint read call.
	ReadErrors ReadErrors

	// SendErrors collects packet send errors within the transport layer.
	SendErrors SendErrors

	// WriteErrors collects packet write errors from an endpoint write call.
	WriteErrors WriteErrors
}

TransportEndpointStats collects statistics about the endpoint.

func (*TransportEndpointStats) Clone

Clone returns a copy of the TransportEndpointStats by atomically reading each field.

func (*TransportEndpointStats) IsEndpointStats

func (*TransportEndpointStats) IsEndpointStats()

IsEndpointStats is an empty method to implement the tcpip.EndpointStats marker interface.

type TransportProtocolNumber

type TransportProtocolNumber uint32

TransportProtocolNumber is the number of a transport protocol.

type UDPStats

type UDPStats struct {
	// PacketsReceived is the number of UDP datagrams received via
	// HandlePacket.
	PacketsReceived *StatCounter

	// UnknownPortErrors is the number of incoming UDP datagrams dropped
	// because they did not have a known destination port.
	UnknownPortErrors *StatCounter

	// ReceiveBufferErrors is the number of incoming UDP datagrams dropped
	// due to the receiving buffer being in an invalid state.
	ReceiveBufferErrors *StatCounter

	// MalformedPacketsReceived is the number of incoming UDP datagrams
	// dropped due to the UDP header being in a malformed state.
	MalformedPacketsReceived *StatCounter

	// PacketsSent is the number of UDP datagrams sent via sendUDP.
	PacketsSent *StatCounter

	// PacketSendErrors is the number of datagrams failed to be sent.
	PacketSendErrors *StatCounter
}

UDPStats collects UDP-specific stats.

type V6OnlyOption

type V6OnlyOption int

V6OnlyOption is used by SetSockOpt/GetSockOpt to specify whether an IPv6 socket is to be restricted to sending and receiving IPv6 packets only.

type WriteErrors

type WriteErrors struct {
	// WriteClosed is the number of packet drops because the endpoint
	// was shutdown for write.
	WriteClosed StatCounter

	// InvalidEndpointState is the number of times we found the endpoint state
	// to be unexpected.
	InvalidEndpointState StatCounter

	// InvalidArgs is the number of times invalid input arguments were
	// provided for endpoint Write call.
	InvalidArgs StatCounter
}

WriteErrors collects packet write errors from an endpoint write call.

type WriteOptions

type WriteOptions struct {
	// If To is not nil, write to the given address instead of the endpoint's
	// peer.
	To *FullAddress

	// More has the same semantics as Linux's MSG_MORE.
	More bool

	// EndOfRecord has the same semantics as Linux's MSG_EOR.
	EndOfRecord bool

	// Atomic means that all data fetched from Payloader must be written to the
	// endpoint. If Atomic is false, then data fetched from the Payloader may be
	// discarded if available endpoint buffer space is unsufficient.
	Atomic bool
}

WriteOptions contains options for Endpoint.Write.

Directories

Path Synopsis
adapters
gonet
Package gonet provides a Go net package compatible wrapper for a tcpip stack.
Package gonet provides a Go net package compatible wrapper for a tcpip stack.
Package buffer provides the implementation of a buffer view.
Package buffer provides the implementation of a buffer view.
Package checker provides helper functions to check networking packets for validity.
Package checker provides helper functions to check networking packets for validity.
hash
jenkins
Package jenkins implements Jenkins's one_at_a_time, non-cryptographic hash functions created by by Bob Jenkins.
Package jenkins implements Jenkins's one_at_a_time, non-cryptographic hash functions created by by Bob Jenkins.
Package header provides the implementation of the encoding and decoding of network protocol headers.
Package header provides the implementation of the encoding and decoding of network protocol headers.
Package iptables supports packet filtering and manipulation via the iptables tool.
Package iptables supports packet filtering and manipulation via the iptables tool.
link
channel
Package channel provides the implemention of channel-based data-link layer endpoints.
Package channel provides the implemention of channel-based data-link layer endpoints.
fdbased
Package fdbased provides the implemention of data-link layer endpoints backed by boundary-preserving file descriptors (e.g., TUN devices, seqpacket/datagram sockets).
Package fdbased provides the implemention of data-link layer endpoints backed by boundary-preserving file descriptors (e.g., TUN devices, seqpacket/datagram sockets).
loopback
Package loopback provides the implemention of loopback data-link layer endpoints.
Package loopback provides the implemention of loopback data-link layer endpoints.
muxed
Package muxed provides a muxed link endpoints.
Package muxed provides a muxed link endpoints.
rawfile
Package rawfile contains utilities for using the netstack with raw host files on Linux hosts.
Package rawfile contains utilities for using the netstack with raw host files on Linux hosts.
sharedmem
Package sharedmem provides the implemention of data-link layer endpoints backed by shared memory.
Package sharedmem provides the implemention of data-link layer endpoints backed by shared memory.
sharedmem/pipe
Package pipe implements a shared memory ring buffer on which a single reader and a single writer can operate (read/write) concurrently.
Package pipe implements a shared memory ring buffer on which a single reader and a single writer can operate (read/write) concurrently.
sharedmem/queue
Package queue provides the implementation of transmit and receive queues based on shared memory ring buffers.
Package queue provides the implementation of transmit and receive queues based on shared memory ring buffers.
sniffer
Package sniffer provides the implementation of data-link layer endpoints that wrap another endpoint and logs inbound and outbound packets.
Package sniffer provides the implementation of data-link layer endpoints that wrap another endpoint and logs inbound and outbound packets.
tun
Package tun contains methods to open TAP and TUN devices.
Package tun contains methods to open TAP and TUN devices.
waitable
Package waitable provides the implementation of data-link layer endpoints that wrap other endpoints, and can wait for inflight calls to WritePacket or DeliverNetworkPacket to finish (and new ones to be prevented).
Package waitable provides the implementation of data-link layer endpoints that wrap other endpoints, and can wait for inflight calls to WritePacket or DeliverNetworkPacket to finish (and new ones to be prevented).
network
arp
Package arp implements the ARP network protocol.
Package arp implements the ARP network protocol.
fragmentation
Package fragmentation contains the implementation of IP fragmentation.
Package fragmentation contains the implementation of IP fragmentation.
hash
Package hash contains utility functions for hashing.
Package hash contains utility functions for hashing.
ipv4
Package ipv4 contains the implementation of the ipv4 network protocol.
Package ipv4 contains the implementation of the ipv4 network protocol.
ipv6
Package ipv6 contains the implementation of the ipv6 network protocol.
Package ipv6 contains the implementation of the ipv6 network protocol.
Package ports provides PortManager that manages allocating, reserving and releasing ports.
Package ports provides PortManager that manages allocating, reserving and releasing ports.
sample
tun_tcp_connect
This sample creates a stack with TCP and IPv4 protocols on top of a TUN device, and connects to a peer.
This sample creates a stack with TCP and IPv4 protocols on top of a TUN device, and connects to a peer.
tun_tcp_echo
This sample creates a stack with TCP and IPv4 protocols on top of a TUN device, and listens on a port.
This sample creates a stack with TCP and IPv4 protocols on top of a TUN device, and listens on a port.
Package seqnum defines the types and methods for TCP sequence numbers such that they fit in 32-bit words and work properly when overflows occur.
Package seqnum defines the types and methods for TCP sequence numbers such that they fit in 32-bit words and work properly when overflows occur.
Package stack provides the glue between networking protocols and the consumers of the networking stack.
Package stack provides the glue between networking protocols and the consumers of the networking stack.
transport
icmp
Package icmp contains the implementation of the ICMP and IPv6-ICMP transport protocols for use in ping.
Package icmp contains the implementation of the ICMP and IPv6-ICMP transport protocols for use in ping.
packet
Package packet provides the implementation of packet sockets (see packet(7)).
Package packet provides the implementation of packet sockets (see packet(7)).
raw
Package raw provides the implementation of raw sockets (see raw(7)).
Package raw provides the implementation of raw sockets (see raw(7)).
tcp
Package tcp contains the implementation of the TCP transport protocol.
Package tcp contains the implementation of the TCP transport protocol.
tcp/testing/context
Package context provides a test context for use in tcp tests.
Package context provides a test context for use in tcp tests.
tcpconntrack
Package tcpconntrack implements a TCP connection tracking object.
Package tcpconntrack implements a TCP connection tracking object.
udp
Package udp contains the implementation of the UDP transport protocol.
Package udp contains the implementation of the UDP transport protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL