Documentation ¶
Overview ¶
Package stack provides the glue between networking protocols and the consumers of the networking stack.
For consumers, the only function of interest is New(), everything else is provided by the tcpip/public package.
For protocol implementers, RegisterTransportProtocolFactory() and RegisterNetworkProtocolFactory() are used to register protocol factories with the stack, which will then be used to instantiate protocol objects when consumers interact with the stack.
Index ¶
- func RegisterLinkEndpoint(linkEP LinkEndpoint) tcpip.LinkEndpointID
- func RegisterNetworkProtocolFactory(name string, p NetworkProtocolFactory)
- func RegisterTransportProtocolFactory(name string, p TransportProtocolFactory)
- type ControlType
- type LinkAddressCache
- type LinkAddressResolver
- type LinkEndpoint
- type LinkEndpointCapabilities
- type NIC
- func (n *NIC) AddAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) *tcpip.Error
- func (n *NIC) AddAddressWithOptions(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, ...) *tcpip.Error
- func (n *NIC) AddSubnet(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet)
- func (n *NIC) Addresses() []tcpip.ProtocolAddress
- func (n *NIC) ContainsSubnet(subnet tcpip.Subnet) bool
- func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remoteLinkAddr, localLinkAddr tcpip.LinkAddress, ...)
- func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, ...)
- func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, vv buffer.VectorisedView)
- func (n *NIC) ID() tcpip.NICID
- func (n *NIC) RemoveAddress(addr tcpip.Address) *tcpip.Error
- func (n *NIC) RemoveSubnet(subnet tcpip.Subnet)
- func (n *NIC) Subnets() []tcpip.Subnet
- type NICInfo
- type NICStateFlags
- type NetworkDispatcher
- type NetworkEndpoint
- type NetworkEndpointID
- type NetworkProtocol
- type NetworkProtocolFactory
- type Options
- type PrimaryEndpointBehavior
- type Route
- func (r *Route) Capabilities() LinkEndpointCapabilities
- func (r *Route) Clone() Route
- func (r *Route) DefaultTTL() uint8
- func (r *Route) IsResolutionRequired() bool
- func (r *Route) MTU() uint32
- func (r *Route) MaxHeaderLength() uint16
- func (r *Route) NICID() tcpip.NICID
- func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber) uint16
- func (r *Route) Release()
- func (r *Route) RemoveWaker(waker *sleep.Waker)
- func (r *Route) Resolve(waker *sleep.Waker) (<-chan struct{}, *tcpip.Error)
- func (r *Route) Stats() tcpip.Stats
- func (r *Route) WritePacket(hdr buffer.Prependable, payload buffer.VectorisedView, ...) *tcpip.Error
- type Stack
- func (s *Stack) AddAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) *tcpip.Error
- func (s *Stack) AddAddressWithOptions(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, ...) *tcpip.Error
- func (s *Stack) AddLinkAddress(nicid tcpip.NICID, addr tcpip.Address, linkAddr tcpip.LinkAddress)
- func (s *Stack) AddRouteTable(r tcpip.Route)
- func (s *Stack) AddSubnet(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error
- func (s *Stack) AddTCPProbe(probe TCPProbeFunc)
- func (s *Stack) CheckLocalAddress(nicid tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.NICID
- func (s *Stack) CheckNetworkProtocol(protocol tcpip.NetworkProtocolNumber) bool
- func (s *Stack) ContainsSubnet(id tcpip.NICID, subnet tcpip.Subnet) (bool, *tcpip.Error)
- func (s *Stack) CreateDisabledNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
- func (s *Stack) CreateDisabledNamedNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
- func (s *Stack) CreateNIC(id tcpip.NICID, linkEP tcpip.LinkEndpointID) *tcpip.Error
- func (s *Stack) CreateNamedNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
- func (s *Stack) EnableNIC(id tcpip.NICID) *tcpip.Error
- func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, ...) (Route, *tcpip.Error)
- func (s *Stack) Forwarding() bool
- func (s *Stack) GetLinkAddress(nicid tcpip.NICID, addr, localAddr tcpip.Address, ...) (tcpip.LinkAddress, <-chan struct{}, *tcpip.Error)
- func (s *Stack) GetMainNICAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber) (tcpip.Address, tcpip.Subnet, *tcpip.Error)
- func (s *Stack) GetRouteTable() []tcpip.Route
- func (s *Stack) GetTCPProbe() TCPProbeFunc
- func (s *Stack) JoinGroup(protocol tcpip.NetworkProtocolNumber, nicID tcpip.NICID, ...) *tcpip.Error
- func (s *Stack) LeaveGroup(protocol tcpip.NetworkProtocolNumber, nicID tcpip.NICID, ...) *tcpip.Error
- func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo
- func (s *Stack) NICSubnets() map[tcpip.NICID][]tcpip.Subnet
- func (s *Stack) NetworkProtocolInstance(num tcpip.NetworkProtocolNumber) NetworkProtocol
- func (s *Stack) NetworkProtocolOption(network tcpip.NetworkProtocolNumber, option interface{}) *tcpip.Error
- func (s *Stack) NewEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, ...) (tcpip.Endpoint, *tcpip.Error)
- func (s *Stack) NowNanoseconds() int64
- func (s *Stack) RegisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, ...) *tcpip.Error
- func (s *Stack) RemoveAddress(id tcpip.NICID, addr tcpip.Address) *tcpip.Error
- func (s *Stack) RemoveSubnet(id tcpip.NICID, subnet tcpip.Subnet) *tcpip.Error
- func (s *Stack) RemoveTCPProbe()
- func (s *Stack) RemoveWaker(nicid tcpip.NICID, addr tcpip.Address, waker *sleep.Waker)
- func (s *Stack) SetForwarding(enable bool)
- func (s *Stack) SetNetworkProtocolOption(network tcpip.NetworkProtocolNumber, option interface{}) *tcpip.Error
- func (s *Stack) SetPromiscuousMode(nicID tcpip.NICID, enable bool) *tcpip.Error
- func (s *Stack) SetRouteTable(table []tcpip.Route)
- func (s *Stack) SetSpoofing(nicID tcpip.NICID, enable bool) *tcpip.Error
- func (s *Stack) SetTransportProtocolHandler(p tcpip.TransportProtocolNumber, ...)
- func (s *Stack) SetTransportProtocolOption(transport tcpip.TransportProtocolNumber, option interface{}) *tcpip.Error
- func (s *Stack) Stats() tcpip.Stats
- func (s *Stack) TransportProtocolInstance(num tcpip.TransportProtocolNumber) TransportProtocol
- func (s *Stack) TransportProtocolOption(transport tcpip.TransportProtocolNumber, option interface{}) *tcpip.Error
- func (s *Stack) UnregisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, ...)
- type TCPCubicState
- type TCPEndpointID
- type TCPEndpointState
- type TCPFastRecoveryState
- type TCPProbeFunc
- type TCPReceiverState
- type TCPSACKInfo
- type TCPSenderState
- type TransportDispatcher
- type TransportEndpoint
- type TransportEndpointID
- type TransportProtocol
- type TransportProtocolFactory
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func RegisterLinkEndpoint ¶
func RegisterLinkEndpoint(linkEP LinkEndpoint) tcpip.LinkEndpointID
RegisterLinkEndpoint register a link-layer protocol endpoint and returns an ID that can be used to refer to it. 注册一个链路层设备
func RegisterNetworkProtocolFactory ¶
func RegisterNetworkProtocolFactory(name string, p NetworkProtocolFactory)
RegisterNetworkProtocolFactory registers a new network protocol factory with the stack so that it becomes available to users of the stack. This function is intended to be called by init() functions of the protocols. RegisterNetworkProtocolFactory 在协议栈中注册一个新的网络协议工厂, 以便协议栈可以使用它。此函数在由协议的init函数中使用。
func RegisterTransportProtocolFactory ¶
func RegisterTransportProtocolFactory(name string, p TransportProtocolFactory)
RegisterTransportProtocolFactory registers a new transport protocol factory with the stack so that it becomes available to users of the stack. This function is intended to be called by init() functions of the protocols. RegisterTransportProtocolFactory 在协议栈中注册一个新的传输协议工厂, 以便协议栈可以使用它。此函数在由协议的init函数中使用。
Types ¶
type ControlType ¶
type ControlType int
ControlType is the type of network control message.
const ( ControlPacketTooBig ControlType = iota ControlPortUnreachable ControlUnknown )
The following are the allowed values for ControlType values.
type LinkAddressCache ¶
type LinkAddressCache interface { // CheckLocalAddress determines if the given local address exists, and if it // does not exist. CheckLocalAddress(nicid tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.NICID // AddLinkAddress adds a link address to the cache. AddLinkAddress(nicid tcpip.NICID, addr tcpip.Address, linkAddr tcpip.LinkAddress) // GetLinkAddress looks up the cache to translate address to link address (e.g. IP -> MAC). // If the LinkEndpoint requests address resolution and there is a LinkAddressResolver // registered with the network protocol, the cache attempts to resolve the address // and returns ErrWouldBlock. Waker is notified when address resolution is // complete (success or not). // // If address resolution is required, ErrNoLinkAddress and a notification channel is // returned for the top level caller to block. Channel is closed once address resolution // is complete (success or not). GetLinkAddress(nicid tcpip.NICID, addr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, w *sleep.Waker) (tcpip.LinkAddress, <-chan struct{}, *tcpip.Error) // RemoveWaker removes a waker that has been added in GetLinkAddress(). RemoveWaker(nicid tcpip.NICID, addr tcpip.Address, waker *sleep.Waker) }
A LinkAddressCache caches link addresses.
type LinkAddressResolver ¶
type LinkAddressResolver interface { // LinkAddressRequest sends a request for the LinkAddress of addr. // The request is sent on linkEP with localAddr as the source. // // A valid response will cause the discovery protocol's network // endpoint to call AddLinkAddress. LinkAddressRequest(addr, localAddr tcpip.Address, linkEP LinkEndpoint) *tcpip.Error // ResolveStaticAddress attempts to resolve address without sending // requests. It either resolves the name immediately or returns the // empty LinkAddress. // // It can be used to resolve broadcast addresses for example. ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bool) // LinkAddressProtocol returns the network protocol of the // addresses this this resolver can resolve. LinkAddressProtocol() tcpip.NetworkProtocolNumber }
A LinkAddressResolver is an extension to a NetworkProtocol that can resolve link addresses.
type LinkEndpoint ¶
type LinkEndpoint interface { // MTU is the maximum transmission unit for this endpoint. This is // usually dictated by the backing physical network; when such a // physical network doesn't exist, the limit is generally 64k, which // includes the maximum size of an IP packet. // MTU是此端点的最大传输单位。这通常由支持物理网络决定; // 当这种物理网络不存在时,限制通常为64k,其中包括IP数据包的最大大小。 MTU() uint32 // Capabilities returns the set of capabilities supported by the // endpoint. // Capabilities返回链路层端点支持的功能集。 Capabilities() LinkEndpointCapabilities // MaxHeaderLength returns the maximum size the data link (and // lower level layers combined) headers can have. Higher levels use this // information to reserve space in the front of the packets they're // building. // MaxHeaderLength 返回数据链接(和较低级别的图层组合)标头可以具有的最大大小。 // 较高级别使用此信息来保留它们正在构建的数据包前面预留空间。 MaxHeaderLength() uint16 // LinkAddress returns the link address (typically a MAC) of the // link endpoint. // 本地链路层地址 LinkAddress() tcpip.LinkAddress // WritePacket writes a packet with the given protocol through the given // route. // // To participate in transparent bridging, a LinkEndpoint implementation // should call eth.Encode with header.EthernetFields.SrcAddr set to // r.LocalLinkAddress if it is provided. // WritePacket通过给定的路由写入具有给定协议的数据包。 // 要参与透明桥接,LinkEndpoint实现应调用eth.Encode,并将header.EthernetFields.SrcAddr设置为r.LocalLinkAddress(如果已提供)。 WritePacket(r *Route, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error // Attach attaches the data link layer endpoint to the network-layer // dispatcher of the stack. // Attach 将数据链路层端点附加到协议栈的网络层调度程序。 Attach(dispatcher NetworkDispatcher) // IsAttached returns whether a NetworkDispatcher is attached to the // endpoint. // 是否已经添加了网络层调度器 IsAttached() bool }
LinkEndpoint is the interface implemented by data link layer protocols (e.g., ethernet, loopback, raw) and used by network layer protocols to send packets out through the implementer's data link endpoint. LinkEndpoint是由数据链路层协议(例如,以太网,环回,原始)实现的接口,并由网络层协议用于通过实施者的数据链路端点发送数据包。
func FindLinkEndpoint ¶
func FindLinkEndpoint(id tcpip.LinkEndpointID) LinkEndpoint
FindLinkEndpoint finds the link endpoint associated with the given ID. 根据ID找到网卡设备
type LinkEndpointCapabilities ¶
type LinkEndpointCapabilities uint
LinkEndpointCapabilities is the type associated with the capabilities supported by a link-layer endpoint. It is a set of bitfields.
const ( CapabilityChecksumOffload LinkEndpointCapabilities = 1 << iota CapabilityResolutionRequired CapabilitySaveRestore CapabilityDisconnectOk CapabilityLoopback )
The following are the supported link endpoint capabilities.
type NIC ¶
type NIC struct {
// contains filtered or unexported fields
}
NIC represents a "network interface card" to which the networking stack is attached. 代表一个网卡对象
func (*NIC) AddAddress ¶
AddAddress adds a new address to n, so that it starts accepting packets targeted at the given address (and network protocol). AddAddress向n添加一个新地址,以便它开始接受针对给定地址(和网络协议)的数据包 最终会生成一个网络端注册到 endpoints
func (*NIC) AddAddressWithOptions ¶
func (n *NIC) AddAddressWithOptions(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, peb PrimaryEndpointBehavior) *tcpip.Error
AddAddressWithOptions is the same as AddAddress, but allows you to specify whether the new endpoint can be primary or not. AddAddressWithOptions与AddAddress相同,但允许您指定新端点是否可以是主端点。
func (*NIC) AddSubnet ¶
func (n *NIC) AddSubnet(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet)
AddSubnet adds a new subnet to n, so that it starts accepting packets targeted at the given address and network protocol. AddSubnet向n添加一个新子网,以便它开始接受针对给定地址和网络协议的数据包。
func (*NIC) Addresses ¶
func (n *NIC) Addresses() []tcpip.ProtocolAddress
Addresses returns the addresses associated with this NIC. 获取网卡已分配的协议和对应的地址
func (*NIC) ContainsSubnet ¶
ContainsSubnet reports whether this NIC contains the given subnet. 判断 subnet 这个子网是否在该网卡下
func (*NIC) DeliverNetworkPacket ¶
func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remoteLinkAddr, localLinkAddr tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView)
DeliverNetworkPacket finds the appropriate network protocol endpoint and hands the packet over for further processing. This function is called when the NIC receives a packet from the physical interface. Note that the ownership of the slice backing vv is retained by the caller. This rule applies only to the slice itself, not to the items of the slice; the ownership of the items is not retained by the caller. DeliverNetworkPacket 找到适当的网络协议端点并将数据包交给它进一步处理。 当NIC从物理接口接收数据包时,将调用此函数。比如protocol是arp协议号, 那么会找到arp.HandlePacket来处理数据报。 protocol是ipv4协议号, 那么会找到ipv4.HandlePacket来处理数据报。
func (*NIC) DeliverTransportControlPacket ¶
func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, vv buffer.VectorisedView)
DeliverTransportControlPacket delivers control packets to the appropriate transport protocol endpoint.
func (*NIC) DeliverTransportPacket ¶
func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, vv buffer.VectorisedView)
DeliverTransportPacket delivers the packets to the appropriate transport protocol endpoint. DeliverTransportPacket 按照传输层协议号和传输层ID,将数据包分发给相应的传输层端 比如 protocol=6表示为tcp协议,将会给相应的tcp端分发消息。
func (*NIC) RemoveAddress ¶
RemoveAddress removes an address from n.
func (*NIC) RemoveSubnet ¶
RemoveSubnet removes the given subnet from n. 从n中删除一个子网
type NICInfo ¶
type NICInfo struct { Name string LinkAddress tcpip.LinkAddress ProtocolAddresses []tcpip.ProtocolAddress // Flags indicate the state of the NIC. Flags NICStateFlags // MTU is the maximum transmission unit. MTU uint32 }
NICInfo captures the name and addresses assigned to a NIC.
type NICStateFlags ¶
type NICStateFlags struct { // Up indicates whether the interface is running. Up bool // Running indicates whether resources are allocated. Running bool // Promiscuous indicates whether the interface is in promiscuous mode. Promiscuous bool // Loopback indicates whether the interface is a loopback. Loopback bool }
NICStateFlags holds information about the state of an NIC.
type NetworkDispatcher ¶
type NetworkDispatcher interface { // DeliverNetworkPacket finds the appropriate network protocol // endpoint and hands the packet over for further processing. DeliverNetworkPacket(linkEP LinkEndpoint, dstLinkAddr, srcLinkAddr tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, vv buffer.VectorisedView) }
NetworkDispatcher contains the methods used by the network stack to deliver packets to the appropriate network endpoint after it has been handled by the data link layer.
type NetworkEndpoint ¶
type NetworkEndpoint interface { // DefaultTTL is the default time-to-live value (or hop limit, in ipv6) // for this endpoint. DefaultTTL() uint8 // MTU is the maximum transmission unit for this endpoint. This is // generally calculated as the MTU of the underlying data link endpoint // minus the network endpoint max header length. MTU() uint32 // Capabilities returns the set of capabilities supported by the // underlying link-layer endpoint. Capabilities() LinkEndpointCapabilities // MaxHeaderLength returns the maximum size the network (and lower // level layers combined) headers can have. Higher levels use this // information to reserve space in the front of the packets they're // building. MaxHeaderLength() uint16 // WritePacket writes a packet to the given destination address and // protocol. WritePacket(r *Route, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8) *tcpip.Error // ID returns the network protocol endpoint ID. ID() *NetworkEndpointID // NICID returns the id of the NIC this endpoint belongs to. NICID() tcpip.NICID // HandlePacket is called by the link layer when new packets arrive to // this network endpoint. HandlePacket(r *Route, vv buffer.VectorisedView) // Close is called when the endpoint is reomved from a stack. Close() }
NetworkEndpoint is the interface that needs to be implemented by endpoints of network layer protocols (e.g., ipv4, ipv6). NetworkEndpoint是需要由网络层协议(例如,ipv4,ipv6)的端点实现的接口。
type NetworkEndpointID ¶
NetworkEndpointID is the identifier of a network layer protocol endpoint. Currently the local address is sufficient because all supported protocols (i.e., IPv4 and IPv6) have different sizes for their addresses.
type NetworkProtocol ¶
type NetworkProtocol interface { // Number returns the network protocol number. Number() tcpip.NetworkProtocolNumber // MinimumPacketSize returns the minimum valid packet size of this // network protocol. The stack automatically drops any packets smaller // than this targeted at this protocol. MinimumPacketSize() int // ParsePorts returns the source and destination addresses stored in a // packet of this protocol. ParseAddresses(v buffer.View) (src, dst tcpip.Address) // NewEndpoint creates a new endpoint of this protocol. NewEndpoint(nicid tcpip.NICID, addr tcpip.Address, linkAddrCache LinkAddressCache, dispatcher TransportDispatcher, sender LinkEndpoint) (NetworkEndpoint, *tcpip.Error) // SetOption allows enabling/disabling protocol specific features. // SetOption returns an error if the option is not supported or the // provided option value is invalid. SetOption(option interface{}) *tcpip.Error // Option allows retrieving protocol specific option values. // Option returns an error if the option is not supported or the // provided option value is invalid. Option(option interface{}) *tcpip.Error }
NetworkProtocol is the interface that needs to be implemented by network protocols (e.g., ipv4, ipv6) that want to be part of the networking stack.
type NetworkProtocolFactory ¶
type NetworkProtocolFactory func() NetworkProtocol
NetworkProtocolFactory provides methods to be used by the stack to instantiate network protocols.
type Options ¶
type Options struct { // Clock is an optional clock source used for timestampping packets. // // If no Clock is specified, the clock source will be time.Now. Clock tcpip.Clock // Stats are optional statistic counters. Stats tcpip.Stats }
Options contains optional Stack configuration.
type PrimaryEndpointBehavior ¶
type PrimaryEndpointBehavior int
PrimaryEndpointBehavior is an enumeration of an endpoint's primacy behavior.
const ( // CanBePrimaryEndpoint indicates the endpoint can be used as a primary // endpoint for new connections with no local address. This is the // default when calling NIC.AddAddress. CanBePrimaryEndpoint PrimaryEndpointBehavior = iota // FirstPrimaryEndpoint indicates the endpoint should be the first // primary endpoint considered. If there are multiple endpoints with // this behavior, the most recently-added one will be first. FirstPrimaryEndpoint // NeverPrimaryEndpoint indicates the endpoint should never be a // primary endpoint. NeverPrimaryEndpoint )
type Route ¶
type Route struct { // 远端网络层地址,ipv4或者ipv6地址 RemoteAddress tcpip.Address // RemoteLinkAddress is the link-layer (MAC) address of the // final destination of the route. // 远端网卡MAC地址 RemoteLinkAddress tcpip.LinkAddress // LocalAddress is the local address where the route starts. // 本地网络层地址,ipv4或者ipv6地址 LocalAddress tcpip.Address // LocalLinkAddress is the link-layer (MAC) address of the // where the route starts. // 本地网卡MAC地址 LocalLinkAddress tcpip.LinkAddress // NextHop is the next node in the path to the destination. // 下一跳网络层地址 NextHop tcpip.Address // NetProto is the network-layer protocol. // 网络层协议号 NetProto tcpip.NetworkProtocolNumber // contains filtered or unexported fields }
Route represents a route through the networking stack to a given destination. 贯穿整个协议栈的路由,也就是在链路层和网络层都可以路由 如果目标地址是链路层地址,那么在链路层路由, 如果目标地址是网络层地址,那么在网络层路由。
func (*Route) Capabilities ¶
func (r *Route) Capabilities() LinkEndpointCapabilities
Capabilities returns the link-layer capabilities of the route.
func (*Route) Clone ¶
Clone Clone a route such that the original one can be released and the new one will remain valid.
func (*Route) DefaultTTL ¶
DefaultTTL returns the default TTL of the underlying network endpoint.
func (*Route) IsResolutionRequired ¶
IsResolutionRequired returns true if Resolve() must be called to resolve the link address before the this route can be written to.
func (*Route) MaxHeaderLength ¶
MaxHeaderLength forwards the call to the network endpoint's implementation.
func (*Route) PseudoHeaderChecksum ¶
func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber) uint16
PseudoHeaderChecksum forwards the call to the network endpoint's implementation. udp或tcp伪首部校验和的计算
func (*Route) Release ¶
func (r *Route) Release()
Release frees all resources associated with the route.
func (*Route) RemoveWaker ¶
RemoveWaker removes a waker that has been added in Resolve().
func (*Route) Resolve ¶
Resolve attempts to resolve the link address if necessary. Returns ErrWouldBlock in case address resolution requires blocking, e.g. wait for ARP reply. Waker is notified when address resolution is complete (success or not).
If address resolution is required, ErrNoLinkAddress and a notification channel is returned for the top level caller to block. Channel is closed once address resolution is complete (success or not).
Resolve 如有必要,解决尝试解析链接地址的问题。如果地址解析需要阻塞,则返回ErrWouldBlock, 例如等待ARP回复。地址解析完成(成功与否)时通知Waker。 如果需要地址解析,则返回ErrNoLinkAddress和通知通道,以阻止顶级调用者。 地址解析完成后,通道关闭(不管成功与否)。
func (*Route) WritePacket ¶
func (r *Route) WritePacket(hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.TransportProtocolNumber, ttl uint8) *tcpip.Error
WritePacket writes the packet through the given route.
type Stack ¶
type Stack struct { *ports.PortManager // contains filtered or unexported fields }
Stack is a networking stack, with all supported protocols, NICs, and route table.
var Pstack *Stack
Pstack global stack
func New ¶
New allocates a new networking stack with only the requested networking and transport protocols configured with default options.
Protocol options can be changed by calling the SetNetworkProtocolOption/SetTransportProtocolOption methods provided by the stack. Please refer to individual protocol implementations as to what options are supported. 新建一个协议栈对象
func (*Stack) AddAddress ¶
func (s *Stack) AddAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) *tcpip.Error
AddAddress adds a new network-layer address to the specified NIC.
func (*Stack) AddAddressWithOptions ¶
func (s *Stack) AddAddressWithOptions(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, peb PrimaryEndpointBehavior) *tcpip.Error
AddAddressWithOptions is the same as AddAddress, but allows you to specify whether the new endpoint can be primary or not.
func (*Stack) AddLinkAddress ¶
AddLinkAddress adds a link address to the stack link cache.
func (*Stack) AddRouteTable ¶
AddRouteTable add on remote route to table ,used to be tcp client
func (*Stack) AddSubnet ¶
func (s *Stack) AddSubnet(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error
AddSubnet adds a subnet range to the specified NIC.
func (*Stack) AddTCPProbe ¶
func (s *Stack) AddTCPProbe(probe TCPProbeFunc)
AddTCPProbe installs a probe function that will be invoked on every segment received by a given TCP endpoint. The probe function is passed a copy of the TCP endpoint state.
NOTE: TCPProbe is added only to endpoints created after this call. Endpoints created prior to this call will not call the probe function.
Further, installing two different probes back to back can result in some endpoints calling the first one and some the second one. There is no guarantee provided on which probe will be invoked. Ideally this should only be called once per stack.
func (*Stack) CheckLocalAddress ¶
func (s *Stack) CheckLocalAddress(nicid tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.NICID
CheckLocalAddress determines if the given local address exists, and if it does, returns the id of the NIC it's bound to. Returns 0 if the address does not exist. nicid 网卡id protocol 协议号[arp|ipv4|...] 通过以太网协议第12-14字节获得 addr 地址
func (*Stack) CheckNetworkProtocol ¶
func (s *Stack) CheckNetworkProtocol(protocol tcpip.NetworkProtocolNumber) bool
CheckNetworkProtocol checks if a given network protocol is enabled in the stack.
func (*Stack) ContainsSubnet ¶
ContainsSubnet reports whether the specified NIC contains the specified subnet.
func (*Stack) CreateDisabledNIC ¶
func (s *Stack) CreateDisabledNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
CreateDisabledNIC creates a NIC with the provided id and link-layer endpoint, but leave it disable. Stack.EnableNIC must be called before the link-layer endpoint starts delivering packets to it.
func (*Stack) CreateDisabledNamedNIC ¶
func (s *Stack) CreateDisabledNamedNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
CreateDisabledNamedNIC is a combination of CreateNamedNIC and CreateDisabledNIC.
func (*Stack) CreateNIC ¶
CreateNIC creates a NIC with the provided id and link-layer endpoint. 根据nic id和linkEP id来创建和注册一个网卡对象
func (*Stack) CreateNamedNIC ¶
func (s *Stack) CreateNamedNIC(id tcpip.NICID, name string, linkEP tcpip.LinkEndpointID) *tcpip.Error
CreateNamedNIC creates a NIC with the provided id and link-layer endpoint, and a human-readable name.
func (*Stack) EnableNIC ¶
EnableNIC enables the given NIC so that the link-layer endpoint can start delivering packets to it.
func (*Stack) FindRoute ¶
func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber) (Route, *tcpip.Error)
FindRoute creates a route to the given destination address, leaving through the given nic and local address (if provided). 路由查找实现,比如当tcp建立连接时,会用该函数得到路由信息
func (*Stack) Forwarding ¶
Forwarding returns if the packet forwarding between NICs is enabled.
func (*Stack) GetLinkAddress ¶
func (s *Stack) GetLinkAddress(nicid tcpip.NICID, addr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, waker *sleep.Waker) (tcpip.LinkAddress, <-chan struct{}, *tcpip.Error)
GetLinkAddress implements LinkAddressCache.GetLinkAddress. 获取链路层地址的方法
func (*Stack) GetMainNICAddress ¶
func (s *Stack) GetMainNICAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber) (tcpip.Address, tcpip.Subnet, *tcpip.Error)
GetMainNICAddress returns the first primary address (and the subnet that contains it) for the given NIC and protocol. Returns an arbitrary endpoint's address if no primary addresses exist. Returns an error if the NIC doesn't exist or has no endpoints.
func (*Stack) GetRouteTable ¶
GetRouteTable returns the route table which is currently in use.
func (*Stack) GetTCPProbe ¶
func (s *Stack) GetTCPProbe() TCPProbeFunc
GetTCPProbe returns the TCPProbeFunc if installed with AddTCPProbe, nil otherwise.
func (*Stack) JoinGroup ¶
func (s *Stack) JoinGroup(protocol tcpip.NetworkProtocolNumber, nicID tcpip.NICID, multicastAddr tcpip.Address) *tcpip.Error
JoinGroup joins the given multicast group on the given NIC.
func (*Stack) LeaveGroup ¶
func (s *Stack) LeaveGroup(protocol tcpip.NetworkProtocolNumber, nicID tcpip.NICID, multicastAddr tcpip.Address) *tcpip.Error
LeaveGroup leaves the given multicast group on the given NIC.
func (*Stack) NICSubnets ¶
NICSubnets returns a map of NICIDs to their associated subnets.
func (*Stack) NetworkProtocolInstance ¶
func (s *Stack) NetworkProtocolInstance(num tcpip.NetworkProtocolNumber) NetworkProtocol
NetworkProtocolInstance returns the protocol instance in the stack for the specified network protocol. This method is public for protocol implementers and tests to use.
func (*Stack) NetworkProtocolOption ¶
func (s *Stack) NetworkProtocolOption(network tcpip.NetworkProtocolNumber, option interface{}) *tcpip.Error
NetworkProtocolOption allows retrieving individual protocol level option values. This method returns an error if the protocol is not supported or option is not supported by the protocol implementation. e.g. var v ipv4.MyOption err := s.NetworkProtocolOption(tcpip.IPv4ProtocolNumber, &v)
if err != nil { ... }
func (*Stack) NewEndpoint ¶
func (s *Stack) NewEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error)
NewEndpoint creates a new transport layer endpoint of the given protocol.
func (*Stack) NowNanoseconds ¶
NowNanoseconds implements tcpip.Clock.NowNanoseconds.
func (*Stack) RegisterTransportEndpoint ¶
func (s *Stack) RegisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint) *tcpip.Error
RegisterTransportEndpoint registers the given endpoint with the stack transport dispatcher. Received packets that match the provided id will be delivered to the given endpoint; specifying a nic is optional, but nic-specific IDs have precedence over global ones. RegisterTransportEndpoint 协议栈或者NIC的分流器注册给定传输层端点。 收到的与提供的id匹配的数据包将被传送到给定的端点;指定nic是可选的,但特定于nic的ID优先于全局ID。 最终调用 demuxer.registerEndpoint 函数来实现注册。
func (*Stack) RemoveAddress ¶
RemoveAddress removes an existing network-layer address from the specified NIC.
func (*Stack) RemoveSubnet ¶
RemoveSubnet removes the subnet range from the specified NIC.
func (*Stack) RemoveTCPProbe ¶
func (s *Stack) RemoveTCPProbe()
RemoveTCPProbe removes an installed TCP probe.
NOTE: This only ensures that endpoints created after this call do not have a probe attached. Endpoints already created will continue to invoke TCP probe.
func (*Stack) RemoveWaker ¶
RemoveWaker implements LinkAddressCache.RemoveWaker.
func (*Stack) SetForwarding ¶
SetForwarding enables or disables the packet forwarding between NICs.
func (*Stack) SetNetworkProtocolOption ¶
func (s *Stack) SetNetworkProtocolOption(network tcpip.NetworkProtocolNumber, option interface{}) *tcpip.Error
SetNetworkProtocolOption allows configuring individual protocol level options. This method returns an error if the protocol is not supported or option is not supported by the protocol implementation or the provided value is incorrect.
func (*Stack) SetPromiscuousMode ¶
SetPromiscuousMode enables or disables promiscuous mode in the given NIC.
func (*Stack) SetRouteTable ¶
SetRouteTable assigns the route table to be used by this stack. It specifies which NIC to use for given destination address ranges.
func (*Stack) SetSpoofing ¶
SetSpoofing enables or disables address spoofing in the given NIC, allowing endpoints to bind to any address in the NIC.
func (*Stack) SetTransportProtocolHandler ¶
func (s *Stack) SetTransportProtocolHandler(p tcpip.TransportProtocolNumber, h func(*Route, TransportEndpointID, buffer.VectorisedView) bool)
SetTransportProtocolHandler sets the per-stack default handler for the given protocol.
It must be called only during initialization of the stack. Changing it as the stack is operating is not supported.
func (*Stack) SetTransportProtocolOption ¶
func (s *Stack) SetTransportProtocolOption(transport tcpip.TransportProtocolNumber, option interface{}) *tcpip.Error
SetTransportProtocolOption allows configuring individual protocol level options. This method returns an error if the protocol is not supported or option is not supported by the protocol implementation or the provided value is incorrect.
func (*Stack) Stats ¶
Stats returns a mutable copy of the current stats.
This is not generally exported via the public interface, but is available internally.
func (*Stack) TransportProtocolInstance ¶
func (s *Stack) TransportProtocolInstance(num tcpip.TransportProtocolNumber) TransportProtocol
TransportProtocolInstance returns the protocol instance in the stack for the specified transport protocol. This method is public for protocol implementers and tests to use.
func (*Stack) TransportProtocolOption ¶
func (s *Stack) TransportProtocolOption(transport tcpip.TransportProtocolNumber, option interface{}) *tcpip.Error
TransportProtocolOption allows retrieving individual protocol level option values. This method returns an error if the protocol is not supported or option is not supported by the protocol implementation. var v tcp.SACKEnabled
if err := s.TransportProtocolOption(tcpip.TCPProtocolNumber, &v); err != nil { ... }
func (*Stack) UnregisterTransportEndpoint ¶
func (s *Stack) UnregisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID)
UnregisterTransportEndpoint removes the endpoint with the given id from the stack transport dispatcher.
type TCPCubicState ¶
type TCPCubicState struct { WLastMax float64 WMax float64 T time.Time TimeSinceLastCongestion time.Duration C float64 K float64 Beta float64 WC float64 WEst float64 }
TCPCubicState is used to hold a copy of the internal cubic state when the TCPProbeFunc is invoked.
type TCPEndpointID ¶
type TCPEndpointID struct { // LocalPort is the local port associated with the endpoint. LocalPort uint16 // LocalAddress is the local [network layer] address associated with // the endpoint. LocalAddress tcpip.Address // RemotePort is the remote port associated with the endpoint. RemotePort uint16 // RemoteAddress it the remote [network layer] address associated with // the endpoint. RemoteAddress tcpip.Address }
TCPEndpointID is the unique 4 tuple that identifies a given endpoint.
type TCPEndpointState ¶
type TCPEndpointState struct { // ID is a copy of the TransportEndpointID for the endpoint. ID TCPEndpointID // SegTime denotes the absolute time when this segment was received. SegTime time.Time // RcvBufSize is the size of the receive socket buffer for the endpoint. RcvBufSize int // RcvBufUsed is the amount of bytes actually held in the receive socket // buffer for the endpoint. RcvBufUsed int // RcvClosed if true, indicates the endpoint has been closed for reading. RcvClosed bool // SendTSOk is used to indicate when the TS Option has been negotiated. // When sendTSOk is true every non-RST segment should carry a TS as per // RFC7323#section-1.1. SendTSOk bool // RecentTS is the timestamp that should be sent in the TSEcr field of // the timestamp for future segments sent by the endpoint. This field is // updated if required when a new segment is received by this endpoint. RecentTS uint32 // TSOffset is a randomized offset added to the value of the TSVal field // in the timestamp option. TSOffset uint32 // SACKPermitted is set to true if the peer sends the TCPSACKPermitted // option in the SYN/SYN-ACK. SACKPermitted bool // SACK holds TCP SACK related information for this endpoint. SACK TCPSACKInfo // SndBufSize is the size of the socket send buffer. SndBufSize int // SndBufUsed is the number of bytes held in the socket send buffer. SndBufUsed int // SndClosed indicates that the endpoint has been closed for sends. SndClosed bool // SndBufInQueue is the number of bytes in the send queue. SndBufInQueue seqnum.Size // PacketTooBigCount is used to notify the main protocol routine how // many times a "packet too big" control packet is received. PacketTooBigCount int // SndMTU is the smallest MTU seen in the control packets received. SndMTU int // Receiver holds variables related to the TCP receiver for the endpoint. Receiver TCPReceiverState // Sender holds state related to the TCP Sender for the endpoint. Sender TCPSenderState }
TCPEndpointState is a copy of the internal state of a TCP endpoint.
type TCPFastRecoveryState ¶
type TCPFastRecoveryState struct { // Active if true indicates the endpoint is in fast recovery. Active bool // First is the first unacknowledged sequence number being recovered. First seqnum.Value // Last is the 'recover' sequence number that indicates the point at // which we should exit recovery barring any timeouts etc. Last seqnum.Value // MaxCwnd is the maximum value we are permitted to grow the congestion // window during recovery. This is set at the time we enter recovery. MaxCwnd int }
TCPFastRecoveryState holds a copy of the internal fast recovery state of a TCP endpoint.
type TCPProbeFunc ¶
type TCPProbeFunc func(s TCPEndpointState)
TCPProbeFunc is the expected function type for a TCP probe function to be passed to stack.AddTCPProbe.
type TCPReceiverState ¶
type TCPReceiverState struct { // RcvNxt is the TCP variable RCV.NXT. RcvNxt seqnum.Value // RcvAcc is the TCP variable RCV.ACC. RcvAcc seqnum.Value // RcvWndScale is the window scaling to use for inbound segments. RcvWndScale uint8 // PendingBufUsed is the number of bytes pending in the receive // queue. PendingBufUsed seqnum.Size // PendingBufSize is the size of the socket receive buffer. PendingBufSize seqnum.Size }
TCPReceiverState holds a copy of the internal state of the receiver for a given TCP endpoint.
type TCPSACKInfo ¶
type TCPSACKInfo struct { // Blocks is the list of SACK block currently received by the // TCP endpoint. Blocks []header.SACKBlock }
TCPSACKInfo holds TCP SACK related information for a given TCP endpoint.
type TCPSenderState ¶
type TCPSenderState struct { // LastSendTime is the time at which we sent the last segment. LastSendTime time.Time // DupAckCount is the number of Duplicate ACK's received. DupAckCount int // SndCwnd is the size of the sending congestion window in packets. SndCwnd int // Ssthresh is the slow start threshold in packets. Ssthresh int // SndCAAckCount is the number of packets consumed in congestion // avoidance mode. SndCAAckCount int // Outstanding is the number of packets in flight. Outstanding int // SndWnd is the send window size in bytes. SndWnd seqnum.Size // SndUna is the next unacknowledged sequence number. SndUna seqnum.Value // SndNxt is the sequence number of the next segment to be sent. SndNxt seqnum.Value // RTTMeasureSeqNum is the sequence number being used for the latest RTT // measurement. RTTMeasureSeqNum seqnum.Value // RTTMeasureTime is the time when the RTTMeasureSeqNum was sent. RTTMeasureTime time.Time // Closed indicates that the caller has closed the endpoint for sending. Closed bool // SRTT is the smoothed round-trip time as defined in section 2 of // RFC 6298. SRTT time.Duration // RTO is the retransmit timeout as defined in section of 2 of RFC 6298. RTO time.Duration // RTTVar is the round-trip time variation as defined in section 2 of // RFC 6298. RTTVar time.Duration // SRTTInited if true indicates take a valid RTT measurement has been // completed. SRTTInited bool // MaxPayloadSize is the maximum size of the payload of a given segment. // It is initialized on demand. MaxPayloadSize int // SndWndScale is the number of bits to shift left when reading the send // window size from a segment. SndWndScale uint8 // MaxSentAck is the highest acknowledgement number sent till now. MaxSentAck seqnum.Value // FastRecovery holds the fast recovery state for the endpoint. FastRecovery TCPFastRecoveryState // Cubic holds the state related to CUBIC congestion control. Cubic TCPCubicState }
TCPSenderState holds a copy of the internal state of the sender for a given TCP Endpoint.
type TransportDispatcher ¶
type TransportDispatcher interface { // DeliverTransportPacket delivers packets to the appropriate // transport protocol endpoint. DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, vv buffer.VectorisedView) // DeliverTransportControlPacket delivers control packets to the // appropriate transport protocol endpoint. DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, vv buffer.VectorisedView) }
TransportDispatcher contains the methods used by the network stack to deliver packets to the appropriate transport endpoint after it has been handled by the network layer.
type TransportEndpoint ¶
type TransportEndpoint interface { // HandlePacket is called by the stack when new packets arrive to // this transport endpoint. HandlePacket(r *Route, id TransportEndpointID, vv buffer.VectorisedView) // HandleControlPacket is called by the stack when new control (e.g., // ICMP) packets arrive to this transport endpoint. HandleControlPacket(id TransportEndpointID, typ ControlType, extra uint32, vv buffer.VectorisedView) }
TransportEndpoint is the interface that needs to be implemented by transport protocol (e.g., tcp, udp) endpoints that can handle packets.
type TransportEndpointID ¶
type TransportEndpointID struct { // LocalPort is the local port associated with the endpoint. LocalPort uint16 // LocalAddress is the local [network layer] address associated with // the endpoint. LocalAddress tcpip.Address // RemotePort is the remote port associated with the endpoint. RemotePort uint16 // RemoteAddress it the remote [network layer] address associated with // the endpoint. RemoteAddress tcpip.Address }
TransportEndpointID is the identifier of a transport layer protocol endpoint.
+stateify savable
type TransportProtocol ¶
type TransportProtocol interface { // Number returns the transport protocol number. Number() tcpip.TransportProtocolNumber // NewEndpoint creates a new endpoint of the transport protocol. NewEndpoint(stack *Stack, netProto tcpip.NetworkProtocolNumber, waitQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) // MinimumPacketSize returns the minimum valid packet size of this // transport protocol. The stack automatically drops any packets smaller // than this targeted at this protocol. MinimumPacketSize() int // ParsePorts returns the source and destination ports stored in a // packet of this protocol. ParsePorts(v buffer.View) (src, dst uint16, err *tcpip.Error) // HandleUnknownDestinationPacket handles packets targeted at this // protocol but that don't match any existing endpoint. For example, // it is targeted at a port that have no listeners. // // The return value indicates whether the packet was well-formed (for // stats purposes only). HandleUnknownDestinationPacket(r *Route, id TransportEndpointID, vv buffer.VectorisedView) bool // SetOption allows enabling/disabling protocol specific features. // SetOption returns an error if the option is not supported or the // provided option value is invalid. SetOption(option interface{}) *tcpip.Error // Option allows retrieving protocol specific option values. // Option returns an error if the option is not supported or the // provided option value is invalid. Option(option interface{}) *tcpip.Error }
TransportProtocol is the interface that needs to be implemented by transport protocols (e.g., tcp, udp) that want to be part of the networking stack.
type TransportProtocolFactory ¶
type TransportProtocolFactory func() TransportProtocol
TransportProtocolFactory functions are used by the stack to instantiate transport protocols.