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 ¶
- Variables
- func AddDanglingEndpoint(e Endpoint)
- func DeleteDanglingEndpoint(e Endpoint)
- type AddMembershipOption
- type Address
- type AddressMask
- type Clock
- type ControlMessages
- type Endpoint
- type ErrSaveRejection
- type Error
- type ErrorOption
- type FullAddress
- type IPStats
- type KeepaliveCountOption
- type KeepaliveEnabledOption
- type KeepaliveIdleOption
- type KeepaliveIntervalOption
- type LinkAddress
- type LinkEndpointID
- type MembershipOption
- type MulticastTTLOption
- type NICID
- type NetworkProtocolNumber
- type NoDelayOption
- type PasscredOption
- type Payload
- type ProtocolAddress
- type ReceiveBufferSizeOption
- type ReceiveQueueSizeOption
- type RemoveMembershipOption
- type ReuseAddressOption
- type Route
- type SendBufferSizeOption
- type SendQueueSizeOption
- type ShutdownFlags
- type SlicePayload
- type StatCounter
- type Stats
- type StdClock
- type Subnet
- type TCPInfoOption
- type TCPStats
- type TimestampOption
- type TransportProtocolNumber
- type UDPStats
- type V6OnlyOption
- type WriteOptions
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnknownProtocol = &Error{msg: "unknown protocol"} ErrUnknownNICID = &Error{msg: "unknown nic id"} 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"} ErrControlPortUnreachable = &Error{msg: "Destination unreachable (Port unreachable)"} ErrControlPacketTooBig = &Error{msg: "control packet is too big"} )
Errors that can be returned by the network stack.
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.
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, but never for github.com/liuxp0827/net-protocol internal timekeeping.
type ControlMessages ¶
type ControlMessages struct { // HasTimestamp indicates whether Timestamp is valid/set. HasTimestamp bool // Timestamp is the time (in ns) that the last packed used to create // the read data was received. Timestamp int64 }
A ControlMessages contains socket control messages for IP sockets.
+stateify savable
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. // // A timestamp (in ns) is optionally returned. A zero value indicates // that no timestamp was available. 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. // // 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(Payload, WriteOptions) (uintptr, <-chan struct{}, *Error) // Peek reads data without consuming it from the endpoint. // // This method does not block if there is no data pending. // // A timestamp (in ns) is optionally returned. A zero value indicates // that no timestamp was available. Peek([][]byte) (uintptr, 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. Connect(address FullAddress) *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. // // An optional commit function will be executed atomically with respect // to binding the endpoint. If this returns an error, the bind will not // occur and the error will be propagated back to the caller. Bind(address FullAddress, commit func() *Error) *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 // GetSockOpt gets a socket option. opt should be a pointer to one of the // *Option types. GetSockOpt(opt interface{}) *Error }
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 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 github.com/liuxp0827/net-protocol 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 ¶
IgnoreStats indicates whether this error type should be included in failure counts in tcpip.Stats structs.
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 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
func (FullAddress) String ¶
func (fa FullAddress) String() string
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 }
IPStats collects IP-specific stats (both v4 and v6).
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 ¶
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 ¶
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 LinkEndpointID ¶
type LinkEndpointID uint64
LinkEndpointID represents a data link layer endpoint.
type MembershipOption ¶
MembershipOption is used by SetSockOpt/GetSockOpt as an argument to AddMembershipOption and RemoveMembershipOption.
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 NetworkProtocolNumber ¶
type NetworkProtocolNumber uint32
NetworkProtocolNumber is the number of a network protocol.
type NoDelayOption ¶
type NoDelayOption int
NoDelayOption 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.
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 Payload ¶
type Payload interface { // Get returns a slice containing exactly 'min(size, p.Size())' bytes. Get(size int) ([]byte, *Error) // Size returns the payload size. Size() int }
Payload provides an interface around data that is being sent to an endpoint. This allows the endpoint to request the amount of data it needs based on internal buffers without exposing them. 'p.Get(p.Size())' reads all the data.
type ProtocolAddress ¶
type ProtocolAddress struct { // Protocol is the protocol of the address. Protocol NetworkProtocolNumber // Address is a network address. Address Address }
ProtocolAddress is an address and the network protocol it is associated with.
type ReceiveBufferSizeOption ¶
type ReceiveBufferSizeOption int
ReceiveBufferSizeOption is used by SetSockOpt/GetSockOpt to specify the receive buffer size option.
type ReceiveQueueSizeOption ¶
type ReceiveQueueSizeOption int
ReceiveQueueSizeOption is used in GetSockOpt to specify that the number of unread bytes in the input buffer should be returned.
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 Route ¶
type Route struct { // Destination is the address that must be matched against the masked // target address to check if this row is viable. Destination Address // Mask specifies which bits of the Destination and the target address // must match for this row to be viable. Mask AddressMask // 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 adddress in the row.
type SendBufferSizeOption ¶
type SendBufferSizeOption int
SendBufferSizeOption is used by SetSockOpt/GetSockOpt to specify the send buffer size option.
type SendQueueSizeOption ¶
type SendQueueSizeOption int
SendQueueSizeOption is used in GetSockOpt to specify that the number of unread bytes in the output buffer should be returned.
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 Payload on top of slices for convenience.
type StatCounter ¶
type StatCounter struct {
// contains filtered or unexported fields
}
A StatCounter keeps track of a statistic.
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) 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 // MalformedRcvPackets 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 // 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.
type StdClock ¶
type StdClock struct{}
StdClock implements Clock with the time package.
func (*StdClock) NowMonotonic ¶
NowMonotonic implements Clock.NowMonotonic.
func (*StdClock) NowNanoseconds ¶
NowNanoseconds implements Clock.NowNanoseconds.
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 ¶
Bits returns the number of ones (network bits) and zeros (host bits) in the subnet mask.
type TCPInfoOption ¶
TCPInfoOption is used by GetSockOpt to expose TCP statistics.
TODO: Add and populate stat fields.
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 // 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 // ResetsSent is the number of TCP resets sent. ResetsSent *StatCounter // ResetsReceived is the number of TCP resets received. ResetsReceived *StatCounter }
TCPStats collects TCP-specific stats.
type TimestampOption ¶
type TimestampOption int
TimestampOption is used by SetSockOpt/GetSockOpt to specify whether SO_TIMESTAMP socket control messages are enabled.
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 }
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 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 }
WriteOptions contains options for Endpoint.Write.
Directories ¶
Path | Synopsis |
---|---|
application
|
|
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. |
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. |
loopback
Package loopback provides the implemention of loopback data-link layer endpoints.
|
Package loopback provides the implemention of loopback data-link layer endpoints. |
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. |
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. |
transport
|
|
ping
Package ping contains the implementation of the ICMP and IPv6-ICMP transport protocols for use in ping.
|
Package ping contains the implementation of the ICMP and IPv6-ICMP transport protocols for use in ping. |
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. |