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.
Index ¶
- Constants
- type ControlType
- type DirectionStats
- type GSO
- type GSOEndpoint
- type GSOType
- type ICMPRateLimiter
- type InjectableLinkEndpoint
- type LinkAddressCache
- type LinkAddressResolver
- type LinkEndpoint
- type LinkEndpointCapabilities
- type NDPConfigurations
- type NDPDispatcher
- type NIC
- func (n *NIC) AddAddress(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) *tcpip.Error
- func (n *NIC) AddAddressRange(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet)
- func (n *NIC) AddressRanges() []tcpip.Subnet
- func (n *NIC) AllAddresses() []tcpip.ProtocolAddress
- func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.LinkAddress, ...)
- func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, ...)
- func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, pkt tcpip.PacketBuffer)
- func (n *NIC) ID() tcpip.NICID
- func (n *NIC) PrimaryAddresses() []tcpip.ProtocolAddress
- func (n *NIC) RemoveAddress(addr tcpip.Address) *tcpip.Error
- func (n *NIC) RemoveAddressRange(subnet tcpip.Subnet)
- func (n *NIC) Stack() *Stack
- type NICInfo
- type NICStateFlags
- type NICStats
- type NetworkDispatcher
- type NetworkEndpoint
- type NetworkEndpointID
- type NetworkHeaderParams
- type NetworkProtocol
- type Options
- type PacketDescriptor
- type PacketEndpoint
- type PacketLooping
- type PrimaryEndpointBehavior
- type RawFactory
- type RawTransportEndpoint
- type RcvBufAutoTuneParams
- type ResumableEndpoint
- type Route
- func (r *Route) Capabilities() LinkEndpointCapabilities
- func (r *Route) Clone() Route
- func (r *Route) DefaultTTL() uint8
- func (r *Route) GSOMaxSize() uint32
- func (r *Route) IsResolutionRequired() bool
- func (r *Route) MTU() uint32
- func (r *Route) MakeLoopedRoute() Route
- func (r *Route) MaxHeaderLength() uint16
- func (r *Route) NICID() tcpip.NICID
- func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, totalLen uint16) 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) Stack() *Stack
- func (r *Route) Stats() tcpip.Stats
- func (r *Route) WriteHeaderIncludedPacket(pkt tcpip.PacketBuffer) *tcpip.Error
- func (r *Route) WritePacket(gso *GSO, params NetworkHeaderParams, pkt tcpip.PacketBuffer) *tcpip.Error
- func (r *Route) WritePackets(gso *GSO, hdrs []PacketDescriptor, payload buffer.VectorisedView, ...) (int, *tcpip.Error)
- type Stack
- func (s *Stack) AddAddress(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) *tcpip.Error
- func (s *Stack) AddAddressRange(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *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) AddProtocolAddress(id tcpip.NICID, protocolAddress tcpip.ProtocolAddress) *tcpip.Error
- func (s *Stack) AddProtocolAddressWithOptions(id tcpip.NICID, protocolAddress tcpip.ProtocolAddress, ...) *tcpip.Error
- func (s *Stack) AddTCPProbe(probe TCPProbeFunc)
- func (s *Stack) AllAddresses() map[tcpip.NICID][]tcpip.ProtocolAddress
- func (s *Stack) AllowICMPMessage() bool
- func (s *Stack) CheckLocalAddress(nicID tcpip.NICID, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.NICID
- func (s *Stack) CheckNIC(id tcpip.NICID) bool
- func (s *Stack) CheckNetworkProtocol(protocol tcpip.NetworkProtocolNumber) bool
- func (s *Stack) CleanupEndpoints() []TransportEndpoint
- func (s *Stack) Close()
- func (s *Stack) CompleteTransportEndpointCleanup(ep TransportEndpoint)
- func (s *Stack) CreateDisabledNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error
- func (s *Stack) CreateDisabledNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error
- func (s *Stack) CreateNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error
- func (s *Stack) CreateNamedLoopbackNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error
- func (s *Stack) CreateNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error
- func (s *Stack) DupTentativeAddrDetected(id tcpip.NICID, addr tcpip.Address) *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) FindTransportEndpoint(netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ...) TransportEndpoint
- 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.AddressWithPrefix, *tcpip.Error)
- func (s *Stack) GetRouteTable() []tcpip.Route
- func (s *Stack) GetTCPProbe() TCPProbeFunc
- func (s *Stack) HandleNDPRA(id tcpip.NICID, ip tcpip.Address, ra header.NDPRouterAdvert) *tcpip.Error
- func (s *Stack) ICMPBurst() int
- func (s *Stack) ICMPLimit() rate.Limit
- func (s *Stack) IPTables() iptables.IPTables
- func (s *Stack) IsAddrTentative(id tcpip.NICID, addr tcpip.Address) (bool, *tcpip.Error)
- 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) NICAddressRanges() map[tcpip.NICID][]tcpip.Subnet
- func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo
- 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) NewPacketEndpoint(cooked bool, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error)
- func (s *Stack) NewRawEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, ...) (tcpip.Endpoint, *tcpip.Error)
- func (s *Stack) NowNanoseconds() int64
- func (s *Stack) RegisterPacketEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) *tcpip.Error
- func (s *Stack) RegisterRawTransportEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ...) *tcpip.Error
- func (s *Stack) RegisterRestoredEndpoint(e ResumableEndpoint)
- func (s *Stack) RegisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, ...) *tcpip.Error
- func (s *Stack) RegisteredEndpoints() []TransportEndpoint
- func (s *Stack) RemoveAddress(id tcpip.NICID, addr tcpip.Address) *tcpip.Error
- func (s *Stack) RemoveAddressRange(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) RestoreCleanupEndpoints(es []TransportEndpoint)
- func (s *Stack) Resume()
- func (s *Stack) Seed() uint32
- func (s *Stack) SetForwarding(enable bool)
- func (s *Stack) SetICMPBurst(burst int)
- func (s *Stack) SetICMPLimit(newLimit rate.Limit)
- func (s *Stack) SetIPTables(ipt iptables.IPTables)
- func (s *Stack) SetNDPConfigurations(id tcpip.NICID, c NDPConfigurations) *tcpip.Error
- 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) StartTransportEndpointCleanup(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, ...)
- 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) UniqueID() uint64
- func (s *Stack) UnregisterPacketEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint)
- func (s *Stack) UnregisterRawTransportEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ...)
- func (s *Stack) UnregisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, ...)
- func (s *Stack) Wait()
- func (s *Stack) WritePacket(nicID tcpip.NICID, dst tcpip.LinkAddress, netProto tcpip.NetworkProtocolNumber, ...) *tcpip.Error
- func (s *Stack) WriteRawPacket(nicID tcpip.NICID, payload buffer.VectorisedView) *tcpip.Error
- type TCPCubicState
- type TCPEndpointID
- type TCPEndpointState
- type TCPFastRecoveryState
- type TCPProbeFunc
- type TCPReceiverState
- type TCPSACKInfo
- type TCPSenderState
- type TransportDispatcher
- type TransportEndpoint
- type TransportEndpointID
- type TransportEndpointInfo
- type TransportProtocol
- type UniqueID
Constants ¶
const ( // MaxDiscoveredDefaultRouters is the maximum number of discovered // default routers. The stack should stop discovering new routers after // discovering MaxDiscoveredDefaultRouters routers. // // This value MUST be at minimum 2 as per RFC 4861 section 6.3.4, and // SHOULD be more. // // Max = 10. // // MaxDiscoveredDefaultRouters 是已发现的默认路由器的最大数量。 // 在发现 MaxDiscoveredDefaultRouters 个路由器后,协议栈应停止发现新路由器。 // 根据 RFC 4861 第 6.3.4 节的规定,这个值必须至少是 2 ,而且应该更大。 MaxDiscoveredDefaultRouters = 10 // MaxDiscoveredOnLinkPrefixes is the maximum number of discovered // on-link prefixes. The stack should stop discovering new on-link // prefixes after discovering MaxDiscoveredOnLinkPrefixes on-link // prefixes. // // Max = 10. // // MaxDiscoveredOnLinkPrefixes 是被发现的 on-link 前缀的最大数量。 // 在发现 MaxDiscoveredOnLinkPrefixes 个 on-link prefixes 后,协议栈应停止发现新的 on-link prefixes 。 MaxDiscoveredOnLinkPrefixes = 10 )
const (
// DefaultTOS is the default type of service value for network endpoints.
DefaultTOS = 0
)
const SoftwareGSOMaxSize = (1 << 16)
SoftwareGSOMaxSize is a maximum allowed size of a software GSO segment. This isn't a hard limit, because it is never set into packet headers.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
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 DirectionStats ¶
type DirectionStats struct { // 包数 Packets *tcpip.StatCounter // 字节数 Bytes *tcpip.StatCounter }
DirectionStats includes packet and byte counts.
type GSO ¶
type GSO struct { // Type is one of GSONone, GSOTCPv4, etc. Type GSOType // NeedsCsum is set if the checksum offload is enabled. NeedsCsum bool // CsumOffset is offset after that to place checksum. CsumOffset uint16 // Mss is maximum segment size. MSS uint16 // L3Len is L3 (IP) header length. L3HdrLen uint16 // MaxSize is maximum GSO packet size. MaxSize uint32 }
GSO contains generic segmentation offload properties.
+stateify savable
type GSOEndpoint ¶
type GSOEndpoint interface { // GSOMaxSize returns the maximum GSO packet size. GSOMaxSize() uint32 }
GSOEndpoint provides access to GSO properties.
type ICMPRateLimiter ¶
ICMPRateLimiter is a global rate limiter that controls the generation of ICMP messages generated by the stack. ICMPRateLimiter 是一个全局速率限制器,用于控制协议栈产生 ICMP 消息的速率。
func NewICMPRateLimiter ¶
func NewICMPRateLimiter() *ICMPRateLimiter
NewICMPRateLimiter returns a global rate limiter for controlling the rate at which ICMP messages are generated by the stack. NewICMPRateLimiter 返回一个全局速率限制器,用于控制协议栈产生 ICMP 消息的速率。
type InjectableLinkEndpoint ¶
type InjectableLinkEndpoint interface { LinkEndpoint // InjectInbound injects an inbound packet. InjectInbound(protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) // InjectOutbound writes a fully formed outbound packet directly to the link. // // dest is used by endpoints with multiple raw destinations. InjectOutbound(dest tcpip.Address, packet []byte) *tcpip.Error }
InjectableLinkEndpoint is a LinkEndpoint where inbound packets are delivered via the Inject method.
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 查找缓存,以将地址翻译成链路地址(如 IP->MAC )。 // // 如果链路层端点 LinkEndpoint 请求地址解析,并且有一个 LinkAddressResolver 在网络协议中注册, // 缓存会尝试解析地址并返回 ErrWouldBlock 。当地址解析完成时(成功或失败),Waker 会得到通知。 // // 如果需要地址解析,则返回 ErrNoLinkAddress 和一个通知通道,供调用者阻塞式等待,在地址解析完成后(无论成功与否),通道即被关闭。 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(). // // 删除一个在 GetLinkAddress() 中添加的 waker 。 RemoveWaker(nicID tcpip.NICID, addr tcpip.Address, waker *sleep.Waker) }
A LinkAddressCache caches link addresses. LinkAddressCache 会缓存链路层地址。
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 的 LinkAddress 的请求。 // 该请求在 linkEP 上发送,以 localAddr 作为源。 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 尝试在不发送请求的情况下解析地址。它要么立即解析名称,要么返回空的 LinkAddress 。 // 例如,它可以用于解析广播地址。 ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bool) // LinkAddressProtocol returns the network protocol of the // addresses this this resolver can resolve. // // LinkAddressProtocol 返回此解析器可以解析的网络协议。 LinkAddressProtocol() tcpip.NetworkProtocolNumber }
A LinkAddressResolver is an extension to a NetworkProtocol that can resolve link addresses.
LinkAddressResolver 是 NetworkProtocol 的扩展,可以解析链接地址。
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 是此端点的最大传输单元。 // 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 返回链路层端点的链路层地址(通常为MAC)。 LinkAddress() tcpip.LinkAddress // WritePacket writes a packet with the given protocol through the // given route. It sets pkt.LinkHeader if a link layer header exists. // pkt.NetworkHeader and pkt.TransportHeader must have already been // set. // // 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 通过给定的路由写入指定协议的数据包。 // 如果存在数据链接层头,则需设置 pkt.LinkHeader ,而 pkt.NetworkHeader 和 pkt.TransportHeader 必须被设置。 // // 要参与透明桥接,实现 LinkEndpoint 接口的对象应调用 eth.Encode 并将 header.EthernetFields.SrcAddr 设置 // 为 r.LocalLinkAddress(如果已提供)。 WritePacket(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) *tcpip.Error // WritePackets writes packets with the given protocol through the // given route. // // Right now, WritePackets is used only when the software segmentation // offload is enabled. If it will be used for something else, it may // require to change syscall filters. // // WritePackets 通过给定的路由写入指定协议的数据包。 // 现在,仅在启用软件分段卸载时才使用 WritePackets 。 // 如果将其用于其他用途,则可能需要更改 syscall filters 。 WritePackets(r *Route, gso *GSO, hdrs []PacketDescriptor, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) (int, *tcpip.Error) // WriteRawPacket writes a packet directly to the link. // The packet should already have an ethernet header. // // WriteRawPacket 直接向数据链路层写入一个数据包。该数据包已经添加以太网头。 WriteRawPacket(vv buffer.VectorisedView) *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 返回 NetworkDispatcher 是否连接到端点。 IsAttached() bool // Wait waits for any worker goroutines owned by the endpoint to stop. // // For now, requesting that an endpoint's worker goroutine(s) stop is // implementation specific. // // Wait will not block if the endpoint hasn't started any goroutines // yet, even if it might later. // // // Wait 等待端点拥有的任何 worker goroutines 停止。 // // 目前,要求端点的 worker goroutine 停止是特定的实现。 // // 如果端点还没有启动任何 goroutine ,即使以后可能会启动,Wait 也不会阻塞。 Wait() }
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.
When a link header exists, it sets each tcpip.PacketBuffer's LinkHeader field before passing it up the stack.
LinkEndpoint 是由数据链路层协议(例如,以太网,环回,原始)实现的接口,被网络层协议用来发送数据包到关联的数据链路层。
当数据链接层报头存在时,在将数据传递到协议栈之前要设置每个 tcpip.PacketBuffer 的 LinkHeader 字段。
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.
LinkEndpointCapabilities 描述链路层端点支持的功能。
const ( CapabilityNone LinkEndpointCapabilities = 0 // CapabilityTXChecksumOffload indicates that the link endpoint supports // checksum computation for outgoing packets and the stack can skip // computing checksums when sending packets. // // CapabilityTXChecksumOffload 表示链路层端点支持对出栈数据包进行校验和计算, // 此时,网络层在发送数据包时可以跳过计算校验和。 // // CheckSum Offload 实际上就是是将 TCP/UDP/IP 校验和工作交给了网卡硬件完成,以节约系统的 CPU 资源。 // 譬如:以太网发送网卡计算以太网 CRC32 校验和,接收网卡验证这个校验和。如果接收到的校验和错误,网卡会在内部丢弃数据包。 CapabilityTXChecksumOffload LinkEndpointCapabilities = 1 << iota // CapabilityRXChecksumOffload indicates that the link endpoint supports // checksum verification on received packets and that it's safe for the // stack to skip checksum verification. // // CapabilityRXChecksumOffload 表示链路层端点支持对接收到的数据包进行校验和验证,对于协议栈而言,跳过校验和验证是安全的。 CapabilityRXChecksumOffload CapabilityResolutionRequired CapabilitySaveRestore CapabilityDisconnectOk CapabilityLoopback CapabilityHardwareGSO // CapabilitySoftwareGSO indicates the link endpoint supports of sending // multiple packets using a single call (LinkEndpoint.WritePackets). // // CapabilitySoftwareGSO 表示链接端点支持使用单个调用发送多个数据包( LinkEndpoint.WritePackets )。 CapabilitySoftwareGSO )
The following are the supported link endpoint capabilities. 以下是支持的链接层端点功能。
type NDPConfigurations ¶
type NDPConfigurations struct { // The number of Neighbor Solicitation messages to send when doing // Duplicate Address Detection for a tentative address. // // Note, a value of zero effectively disables DAD. // // 在对 tentative 地址进行重复地址检测(DAD)时,要发送的邻居问询请求 NS 消息的数量。 // 请注意,值为零时将禁用 DAD 。 DupAddrDetectTransmits uint8 // The amount of time to wait between sending Neighbor Solicitation // messages. // // Must be greater than 0.5s. // // 发送邻居问询请求 NS 消息之间的等待时间。 RetransmitTimer time.Duration // HandleRAs determines whether or not Router Advertisements will be // processed. // // HandleRAs 决定是否处理路由器广告 。 HandleRAs bool // DiscoverDefaultRouters determines whether or not default routers will // be discovered from Router Advertisements. This configuration is // ignored if HandleRAs is false. // // DiscoverDefaultRouters 决定是否会从路由器广告中发现默认路由器。 // 如果 HandleRAs 为 false ,则会忽略此配置。 DiscoverDefaultRouters bool // DiscoverOnLinkPrefixes determines whether or not on-link prefixes // will be discovered from Router Advertisements' Prefix Information // option. This configuration is ignored if HandleRAs is false. // // DiscoverOnLinkPrefixes 决定是否会从 Router Advertisements 的 Prefix Information 选项中发现链路前缀。 // 如果 HandleRAs 为 false ,则会忽略此配置。 DiscoverOnLinkPrefixes bool }
NDPConfigurations is the NDP configurations for the netstack.
func DefaultNDPConfigurations ¶
func DefaultNDPConfigurations() NDPConfigurations
DefaultNDPConfigurations returns an NDPConfigurations populated with default values. DefaultNDPConfigurations 返回一个用默认值填充的 NDPConfigurations 。
type NDPDispatcher ¶
type NDPDispatcher interface { // OnDuplicateAddressDetectionStatus will be called when the DAD process // for an address (addr) on a NIC (with ID nicID) completes. resolved // will be set to true if DAD completed successfully (no duplicate addr // detected); false otherwise (addr was detected to be a duplicate on // the link the NIC is a part of, or it was stopped for some other // reason, such as the address being removed). If an error occured // during DAD, err will be set and resolved must be ignored. // // This function is permitted to block indefinitely without interfering // with the stack's operation. // // // 当 NIC(nicID)上的地址(addr)的 DAD 处理完成时,将调用 OnDuplicateAddressDetectionStatus 。 // // 如果 DAD 成功完成(未检测到重复的地址),则将 resolve 设置为 true ;否则为false // ( 检测到 addr 在 NIC 所属的链路上是重复的,或者因为其他原因被停止,比如地址被删除)。 // // 如果在 DAD 期间发生错误,将设置 err ,并且必须忽略 resolved 。 // // OnDuplicateAddressDetectionStatus(nicID tcpip.NICID, addr tcpip.Address, resolved bool, err *tcpip.Error) // OnDefaultRouterDiscovered will be called when a new default router is // discovered. Implementations must return true along with a new valid // route table if the newly discovered router should be remembered. If // an implementation returns false, the second return value will be // ignored. // // This function is not permitted to block indefinitely. This function // is also not permitted to call into the stack. // // // 当发现一个新的默认路由器时,OnDefaultRouterDiscovered 将被调用。 // 如果新发现的路由器应该被记住,那么实现必须返回 true 以及一个新的有效路由表。 // 如果一个实现返回 false ,第二个返回值将被忽略。 // // 该函数不允许无限期阻塞。此函数也不允许调用到堆栈中。 OnDefaultRouterDiscovered(nicID tcpip.NICID, addr tcpip.Address) (bool, []tcpip.Route) // OnDefaultRouterInvalidated will be called when a discovered default // router is invalidated. Implementers must return a new valid route // table. // // This function is not permitted to block indefinitely. This function // is also not permitted to call into the stack. // // // 当发现的默认路由器无效时,将调用 OnDefaultRouterInvalidated 。 // 实现者必须返回一个新的有效路由表。 // // 本功能不允许无限阻塞,也不允许在协议栈中调用。 OnDefaultRouterInvalidated(nicID tcpip.NICID, addr tcpip.Address) []tcpip.Route // OnOnLinkPrefixDiscovered will be called when a new on-link prefix is // discovered. Implementations must return true along with a new valid // route table if the newly discovered on-link prefix should be // remembered. If an implementation returns false, the second return // value will be ignored. // // This function is not permitted to block indefinitely. This function // is also not permitted to call into the stack. // // // 当发现一个新的 on-link 前缀时,OnOnLinkPrefixDiscovered 将被调用。 // 如果新发现的 on-link prefix 应该被记住,实现必须返回 true ,同时返回一个新的有效路由表。 // 如果一个实现返回false,第二个返回值将被忽略。 // // 本功能不允许无限阻塞,也不允许在协议栈中调用。 OnOnLinkPrefixDiscovered(nicID tcpip.NICID, prefix tcpip.Subnet) (bool, []tcpip.Route) // OnOnLinkPrefixInvalidated will be called when a discovered on-link // prefix is invalidated. Implementers must return a new valid route // table. // // This function is not permitted to block indefinitely. This function // is also not permitted to call into the stack. // // // OnOnLinkPrefixInvalidated 将在发现的 on-link 前缀无效时被调用。 // 实现者必须返回一个新的有效路由表。 // OnOnLinkPrefixInvalidated(nicID tcpip.NICID, prefix tcpip.Subnet) []tcpip.Route }
NDPDispatcher is the interface integrators of netstack must implement to receive and handle NDP related events.
NDPDispatcher 是 netstack 的集成者必须实现的接口,用于接收和处理 NDP 相关事件。
type NIC ¶
type NIC struct {
// contains filtered or unexported fields
}
NIC represents a "network interface card" to which the networking stack is attached.
NIC 代表网络协议栈所关联的网卡。
***** 收包方向 *****
在收包方向,NIC 是连接物理层、网络层、传输层的桥梁。
NIC 的主要功能是从数据链路层接收数据包,然后通过 NIC.DeliverNetworkPacket() 完成网络层数据包的分发。 其内部先取出关心当前数据包的网络层 ep ,然后通过 ep.HandlePacket 投递给它。
所有网络层 ep 的注册,都是间接通过协议栈 stack 注册到 NIC 上的,因此当网卡 NIC 收到链路层数据包时, 能够知道本 NIC 上哪些网络层 ep 关心来包,从而投递给它。
传输层协议在 Connect/Disconnect/Bind/Listen 时,会调用 stack.RegisterTransportEndpoint() 将 对应的传输层端点注册到 stack.demux 中。
网络层端点 ep 通过 ep.HandlePacket(r, pkt) 收到网络包之后,会调用 ep.dispatcher.DeliverTransportPacket 将数据包 投递给传输层端点,看目前实现中,仅 NIC 实现了 DeliverTransportPacket 函数,其内部是通过调用 nic.stack.demux.deliverPacket() 来 完成传输层包的分发,而 nic.stack.demux 中保存的传输层端点,正是通过前述 stack.RegisterTransportEndpoint() 注册的。
因此, 网络层端点是通过协议栈 stack 间接注册在某个网卡对象上,通过网卡 NIC 接收物理层的来包。 传输层端点是直接注册到协议栈 stack 的(demux成员),当网络层端点需要向传输层投递数据包时,通过调用协议栈 demux 成员函数来完成。
***** 发包方向 *****
在发包方向,Route 是连接传输层和网络层的桥梁。
传输层通过 Route.WritePacket 或 Route.WritePackets 完成网络层数据包的发送,而 Route 是通过内部网络层端点引用 ep_ref.WritePacket() 实现发包。
传输层通过 stack.FindRoute() 获取 Route 对象,而网络层端点 ref 都是注册在某个 NIC 上的,所以 FindRoute() 内部会先定位到目标 NIC ,然后 通过 nic.findEndpoint() 获取到该网卡上关联的网络层端点 ref 。
***** 总结 *****
网络层端点是注册到 NIC 上的,所以无论是收包还是发包,都能通过 NIC 找到所需的 netEp 。 传输层端点是注册到协议栈上的,当收包时,网络层端点 netEp 需要通过协议栈的 stack.demux 才能将数据包投递给相应的 transEp ; 当发包时,传输层端点 transEp 需要先确认网卡 nic ,然后通过 nic.findEndpoint() 选出用于发包的 netEp ,然后进行发包。
***** 遗留问题 ***** 为什么传输层需要知道网卡信息?
func (*NIC) AddAddress ¶
func (n *NIC) AddAddress(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) *tcpip.Error
AddAddress adds a new address to n, so that it starts accepting packets targeted at the given address (and network protocol).
AddAddress 将一个新的地址添加到 n *NIC 中,这样网卡就可以接收发往给定网络协议和地址的数据包。
func (*NIC) AddAddressRange ¶
func (n *NIC) AddAddressRange(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet)
AddAddressRange adds a range of addresses to n, so that it starts accepting packets targeted at the given addresses and network protocol. The range is given by a subnet address, and all addresses contained in the subnet are used except for the subnet address itself and the subnet's broadcast address.
func (*NIC) AddressRanges ¶
Subnets returns the Subnets associated with this NIC. Subnets 返回与该 NIC 相关联的 Subnets。
func (*NIC) AllAddresses ¶
func (n *NIC) AllAddresses() []tcpip.ProtocolAddress
AllAddresses returns all addresses (primary and non-primary) associated with this NIC.
AllAddresses 返回与此 NIC 关联的所有地址 (primary and non-primary) 。
func (*NIC) DeliverNetworkPacket ¶
func (n *NIC) DeliverNetworkPacket( linkEP LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer, )
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.
当网卡收到来自物理接口的数据包时,会调用此函数,让与 NIC 关联的网络层 ep 能接收并处理包。
func (*NIC) DeliverTransportControlPacket ¶
func (n *NIC) DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, pkt tcpip.PacketBuffer)
DeliverTransportControlPacket delivers control packets to the appropriate transport protocol endpoint.
DeliverTransportControlPacket 将控制数据包传送到相应的传输层端点。
func (*NIC) DeliverTransportPacket ¶
func (n *NIC) DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, pkt tcpip.PacketBuffer)
DeliverTransportPacket delivers the packets to the appropriate transport protocol endpoint.
DeliverTransportPacket 将数据包传送到相应的传输层端点。
func (*NIC) PrimaryAddresses ¶
func (n *NIC) PrimaryAddresses() []tcpip.ProtocolAddress
PrimaryAddresses returns the primary addresses associated with this NIC.
PrimaryAddresses 返回与此 NIC 关联的 primary 地址。
func (*NIC) RemoveAddress ¶
RemoveAddress removes an address from n.
func (*NIC) RemoveAddressRange ¶
RemoveAddressRange removes the given address range from n.
type NICInfo ¶
type NICInfo struct { // 名称 Name string // MAC 地址 LinkAddress tcpip.LinkAddress // IP 地址 ProtocolAddresses []tcpip.ProtocolAddress // Flags indicate the state of the NIC. // 网卡状态(启动、停止、混淆、回环) Flags NICStateFlags // MTU is the maximum transmission unit. // 最大传输单元 MTU uint32 // 统计信息(发送/接收的字节数、包数) Stats NICStats }
NICInfo captures the name and addresses assigned to a NIC. NICInfo 包含网卡名称和地址。
type NICStateFlags ¶
type NICStateFlags struct { // Up indicates whether the interface is running. // Up 标识网卡是否正在运行。 Up bool // Running indicates whether resources are allocated. // Running 标识是否已分配资源。 Running bool // Promiscuous indicates whether the interface is in promiscuous mode. // Promiscuous 标识网卡是否处于混杂模式。 Promiscuous bool // Loopback indicates whether the interface is a loopback. // Loopback 标识网卡是否为环回。 Loopback bool }
NICStateFlags holds information about the state of an NIC. NICStateFlags 保存 NIC 的状态信息。
type NICStats ¶
type NICStats struct { // 传出 Tx DirectionStats // 接收 Rx DirectionStats }
NICStats includes transmitted and received stats.
type NetworkDispatcher ¶
type NetworkDispatcher interface { // DeliverNetworkPacket finds the appropriate network protocol endpoint // and hands the packet over for further processing. // // pkt.LinkHeader may or may not be set before calling // DeliverNetworkPacket. Some packets do not have link headers (e.g. // packets sent via loopback), and won't have the field set. // // DeliverNetworkPacket takes ownership of pkt. // // DeliverNetworkPacket 找到适当的网络层协议端点,并将数据包移交给它进一步处理。 // 在调用 DeliverNetworkPacket 之前,可能会也可能不会设置 pkt.LinkHeader 字段。 // 某些数据包没有数据链路层头(例如,通过环回发送的数据包),将不会设置该字段。 // DeliverNetworkPacket 拥有 pkt 的所有权。 DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) }
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.
NetworkDispatcher 包含网络协议栈在数据链路层处理完数据包后将数据包传递到适当的网络层端点的方法。
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 返回底层链路层端点支持的能力集。 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. // It sets pkt.NetworkHeader. pkt.TransportHeader must have already been set. // // WritePacket 将一个数据包写入给定的目标地址和协议。 // 它设置了 pkt.NetworkHeader,而 pkt.TransportHeader 必须已被设置。 WritePacket(r *Route, gso *GSO, params NetworkHeaderParams, loop PacketLooping, pkt tcpip.PacketBuffer) *tcpip.Error // WritePackets writes packets to the given destination address and protocol. WritePackets(r *Route, gso *GSO, hdrs []PacketDescriptor, payload buffer.VectorisedView, params NetworkHeaderParams, loop PacketLooping) (int, *tcpip.Error) // WriteHeaderIncludedPacket writes a packet that includes a network // header to the given destination address. // // WriteHeaderIncludedPacket 将包含网络头的数据包写入给定的目标地址。 WriteHeaderIncludedPacket(r *Route, loop PacketLooping, pkt tcpip.PacketBuffer) *tcpip.Error // ID returns the network protocol endpoint ID. ID() *NetworkEndpointID // PrefixLen returns the network endpoint's subnet prefix length in bits. // PrefixLen 返回网络端点的子网前缀长度,单位为比特。 PrefixLen() int // NICID returns the id of the NIC this endpoint belongs to. // NICID 返回此端点所属的 NIC id。 NICID() tcpip.NICID // HandlePacket is called by the link layer when new packets arrive to // this network endpoint. It sets pkt.NetworkHeader. // // HandlePacket takes ownership of pkt. // // 当有新的数据包到达时,链路层会调用 HandlePacket 。 HandlePacket(r *Route, pkt tcpip.PacketBuffer) // 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)端点需要实现的接口。
入栈数据包 => HandlePacket() 出栈数据包 => WritePacket() / WritePackets()
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.
NetworkEndpointID 是网络层协议端点的标识符。
type NetworkHeaderParams ¶
type NetworkHeaderParams struct { // Protocol refers to the transport protocol number. // 传输层协议号。 Protocol tcpip.TransportProtocolNumber // TTL refers to Time To Live field of the IP-header. // 报文最大生存时间。 TTL uint8 // TOS refers to TypeOfService or TrafficClass field of the IP-header. // 服务类型,该字段描述了 IP 包的优先级和 QoS 选项。 TOS uint8 }
NetworkHeaderParams are the header parameters given as input by the transport endpoint to the network.
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 // DefaultPrefixLen returns the protocol's default prefix length. DefaultPrefixLen() int // ParseAddresses returns the source and destination addresses stored in a // packet of this protocol. // // ParseAddresses 返回存储在该协议数据包中的源地址和目的地址。 ParseAddresses(v buffer.View) (src, dst tcpip.Address) // NewEndpoint creates a new endpoint of this protocol. // NewEndpoint 创建该协议的新端点。 NewEndpoint( nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, 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 Options ¶
type Options struct { // NetworkProtocols lists the network protocols to enable. NetworkProtocols []NetworkProtocol // TransportProtocols lists the transport protocols to enable. TransportProtocols []TransportProtocol // 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 // HandleLocal indicates whether packets destined to their source // should be handled by the stack internally (true) or outside the // stack (false). HandleLocal bool // UniqueID is an optional generator of unique identifiers. UniqueID UniqueID // NDPConfigs is the default NDP configurations used by interfaces. // // By default, NDPConfigs will have a zero value for its // DupAddrDetectTransmits field, implying that DAD will not be performed // before assigning an address to a NIC. NDPConfigs NDPConfigurations // AutoGenIPv6LinkLocal determins whether or not the stack will attempt // to auto-generate an IPv6 link-local address for newly enabled NICs. // Note, setting this to true does not mean that a link-local address // will be assigned right away, or at all. If Duplicate Address // Detection is enabled, an address will only be assigned if it // successfully resolves. If it fails, no further attempt will be made // to auto-generate an IPv6 link-local address. // // The generated link-local address will follow RFC 4291 Appendix A // guidelines. AutoGenIPv6LinkLocal bool // NDPDisp is the NDP event dispatcher that an integrator can provide to // receive NDP related events. NDPDisp NDPDispatcher // RawFactory produces raw endpoints. Raw endpoints are enabled only if // this is non-nil. RawFactory RawFactory }
Options contains optional Stack configuration.
type PacketDescriptor ¶
type PacketDescriptor struct { Hdr buffer.Prependable // 包头 Off int // payload 偏移量 Size int // payload 大小 }
PacketDescriptor is a packet descriptor which contains a packet header and offset and size of packet data in a payload view.
PacketDescriptor 是数据包描述符。
func NewPacketDescriptors ¶
func NewPacketDescriptors(n int, hdrSize int) []PacketDescriptor
NewPacketDescriptors allocates a set of packet descriptors.
type PacketEndpoint ¶
type PacketEndpoint interface { // HandlePacket is called by the stack when new packets arrive that // match the endpoint. // // Implementers should treat packet as immutable and should copy it // before before modification. // // linkHeader may have a length of 0, in which case the PacketEndpoint // should construct its own ethernet header for applications. // // HandlePacket takes ownership of pkt. // // 当有与端点匹配的新数据包到达时,堆栈会调用 HandlePacket 。 // 实现者应将数据包视为不可更改的,在修改前应先将其复制。 // linkHeader 的长度可能为 0 ,在这种情况下,PacketEndpoint 应该为应用构建自己的以太网头。 // HandlePacket 拥有 pkt 的所有权。 HandlePacket(nicID tcpip.NICID, addr tcpip.LinkAddress, netProto tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) }
PacketEndpoint is the interface that needs to be implemented by packet transport protocol endpoints. These endpoints receive link layer headers in addition to whatever they contain (usually network and transport layer headers and a payload).
PacketEndpoint 是需要由数据包传输协议端点实现的接口。 这些端点除了接收它们所包含的内容(通常是网络和传输层头以及有效负载)之外,还接收链路层头。
type PacketLooping ¶
type PacketLooping byte
PacketLooping specifies where an outbound packet should be sent. PacketLooping 指定出站数据包应该发送到哪里。
const ( // PacketOut indicates that the packet should be passed to the link endpoint. // PacketOut 表示应该将数据包传递给链路层端点。 PacketOut PacketLooping = 1 << iota // PacketLoop indicates that the packet should be handled locally. // PacketLoop 表示应该在本地处理数据包。 PacketLoop )
type PrimaryEndpointBehavior ¶
type PrimaryEndpointBehavior int
PrimaryEndpointBehavior is an enumeration of an endpoint's primacy behavior. PrimaryEndpointBehavior 是端点首要行为的枚举。
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 表示端点可以作为主端点。 // 当调用 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 表示该端点应该是考虑的第一个主要端点。 // 如果有多个端点具有这种行为,则最近添加的端点将是第一个。 FirstPrimaryEndpoint // NeverPrimaryEndpoint indicates the endpoint should never be a primary endpoint. // // NeverPrimaryEndpoint 表示该端点永远不应成为主要端点。 NeverPrimaryEndpoint )
type RawFactory ¶
type RawFactory interface { // NewUnassociatedEndpoint produces endpoints for writing packets not // associated with a particular transport protocol. Such endpoints can // be used to write arbitrary packets that include the network header. NewUnassociatedEndpoint(stack *Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) // NewPacketEndpoint produces endpoints for reading and writing packets // that include network and (when cooked is false) link layer headers. NewPacketEndpoint(stack *Stack, cooked bool, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error) }
RawFactory produces endpoints for writing various types of raw packets.
type RawTransportEndpoint ¶
type RawTransportEndpoint interface { // HandlePacket is called by the stack when new packets arrive to // this transport endpoint. The packet contains all data from the link // layer up. // // HandlePacket takes ownership of pkt. HandlePacket(r *Route, pkt tcpip.PacketBuffer) }
RawTransportEndpoint is the interface that needs to be implemented by raw transport protocol endpoints. RawTransportEndpoints receive the entire packet - including the network and transport headers - as delivered to netstack.
type RcvBufAutoTuneParams ¶
type RcvBufAutoTuneParams struct { // MeasureTime is the time at which the current measurement // was started. MeasureTime time.Time // CopiedBytes is the number of bytes copied to user space since // this measure began. CopiedBytes int // PrevCopiedBytes is the number of bytes copied to user space in // the previous RTT period. PrevCopiedBytes int // RcvBufSize is the auto tuned receive buffer size. RcvBufSize int // RTT is the smoothed RTT as measured by observing the time between // when a byte is first acknowledged and the receipt of data that is at // least one window beyond the sequence number that was acknowledged. RTT time.Duration // RTTVar is the "round-trip time variation" as defined in section 2 // of RFC6298. RTTVar time.Duration // RTTMeasureSeqNumber is the highest acceptable sequence number at the // time this RTT measurement period began. RTTMeasureSeqNumber seqnum.Value // RTTMeasureTime is the absolute time at which the current RTT // measurement period began. RTTMeasureTime time.Time // Disabled is true if an explicit receive buffer is set for the // endpoint. Disabled bool }
RcvBufAutoTuneParams holds state related to TCP receive buffer auto-tuning.
type ResumableEndpoint ¶
type ResumableEndpoint interface { // Resume resumes an endpoint after restore. This can be used to restart // background workers such as protocol goroutines. This must be called after // all indirect dependencies of the endpoint has been restored, which // generally implies at the end of the restore process. Resume(*Stack) }
ResumableEndpoint is an endpoint that needs to be resumed after restore.
type Route ¶
type Route struct { // RemoteAddress is the final destination of the route. // RemoteAddress 是路由最终目的地的网络层(IP)地址。 RemoteAddress tcpip.Address // RemoteLinkAddress is the link-layer (MAC) address of the final destination of the route. // RemoteLinkAddress 是路由最终目的地的链路层(MAC)地址。 RemoteLinkAddress tcpip.LinkAddress // LocalAddress is the local address where the route starts. // LocalAddress 是指本地网络层(IP)地址。 LocalAddress tcpip.Address // LocalLinkAddress is the link-layer (MAC) address of the where the route starts. // LocalLinkAddress 是指本地链路层(MAC)地址。 LocalLinkAddress tcpip.LinkAddress // NextHop is the next node in the path to the destination. // NextHop 是通往目的地的路径中的下一个节点。 NextHop tcpip.Address // NetProto is the network-layer protocol. // NetProto 是指网络层协议。 NetProto tcpip.NetworkProtocolNumber // Loop controls where WritePacket should send packets. // Loop 控制 WritePacket 应该在哪里发送数据包。 Loop PacketLooping // contains filtered or unexported fields }
Route represents a route through the networking stack to a given destination. Route 表示通过网络栈到达目的地的路由信息。
主要有:
目的 IP 地址 目的 MAC 地址 本地 IP 地址 本地 MAC 地址 下一跳 IP 地址 网络层协议号 本地网络层端点 回环处理标识
在发包方向,Route 是连接传输层和网络层的桥梁,传输层根据发送参数获取合适的 Route 对象, 通过 Route.WritePacket 或 Route.WritePackets 完成网络层数据包的发送,Route 内部 会通过网络层 ep ref 完成发包。
func (*Route) Capabilities ¶
func (r *Route) Capabilities() LinkEndpointCapabilities
Capabilities returns the link-layer capabilities of the route.
Capabilities 返回路由的链路层能力。
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. DefaultTTL 返回底层网络层端点的默认 TTL 。
func (*Route) GSOMaxSize ¶
GSOMaxSize returns the maximum GSO packet size.
GSOMaxSize 返回最大的 GSO 数据包大小。
func (*Route) IsResolutionRequired ¶
IsResolutionRequired returns true if Resolve() must be called to resolve the link address before the this route can be written to.
如果必须调用 Resolve() 来解析链路层地址,IsResolutionRequired 返回 true 。
func (*Route) MakeLoopedRoute ¶
MakeLoopedRoute duplicates the given route with special handling for routes used for sending multicast or broadcast packets. In those cases the multicast/broadcast address is the remote address when sending out, but for incoming (looped) packets it becomes the local address. Similarly, the local interface address that was the local address going out becomes the remote address coming in. This is different to unicast routes where local and remote addresses remain the same as they identify location (local vs remote) not direction (source vs destination).
MakeLoopedRoute 复制给定的路由,并对用于发送组播/广播数据包的路由进行特殊处理。
在这些情况下,多播/广播 地址在发送出去的时候是远程地址,但对于传入(looped)的数据包,它就变成了本地地址。 同理,出去的时候是本地接口地址,进来的时候就变成了远程地址。
这与单播路由不同,本地地址和远程地址保持不变,因为它们标识的是位置(本地与远程)而不是方向(源与目的)。
func (*Route) MaxHeaderLength ¶
MaxHeaderLength forwards the call to the network endpoint's implementation.
MaxHeaderLength 将调用转发给网络端点的实现。
func (*Route) NICID ¶
NICID returns the id of the NIC from which this route originates.
NICID 返回该路由所属的 NIC 的 ID。
func (*Route) PseudoHeaderChecksum ¶
func (r *Route) PseudoHeaderChecksum(protocol tcpip.TransportProtocolNumber, totalLen uint16) uint16
PseudoHeaderChecksum forwards the call to the network endpoint's implementation.
PseudoHeaderChecksum 将调用转发给网络端点的实现。
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() 尝试解析链接层地址(MAC地址)。 当地址解析需要阻塞时,返回 ErrWouldBlock ,例如等待 ARP 回复。 当地址解析完成(成功或失败)时,Waker 会收到通知。
如果需要地址解析,则返回 ErrNoLinkAddress 和一个通知管道,供上层调用者阻塞式等待。 地址解析完成后(无论成功与否),通道被 close 以通知调用者。
Resolve() 函数根据下一跳 IP 地址解析出目标 Mac 地址,保存到 r.RemoteLinkAddress 变量。
func (*Route) WriteHeaderIncludedPacket ¶
func (r *Route) WriteHeaderIncludedPacket(pkt tcpip.PacketBuffer) *tcpip.Error
WriteHeaderIncludedPacket writes a packet already containing a network header through the given route.
func (*Route) WritePacket ¶
func (r *Route) WritePacket(gso *GSO, params NetworkHeaderParams, pkt tcpip.PacketBuffer) *tcpip.Error
WritePacket writes the packet through the given route. WritePacket 通过给定路由写入网络层数据包。
func (*Route) WritePackets ¶
func (r *Route) WritePackets(gso *GSO, hdrs []PacketDescriptor, payload buffer.VectorisedView, params NetworkHeaderParams) (int, *tcpip.Error)
WritePackets writes the set of packets 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.
Stack 是一个网络堆栈,其中包含所支持的协议、网卡和路由表。
func New ¶
New allocates a new networking stack with only the requested networking and transport protocols configured with default options.
Note, NDPConfigurations will be fixed before being used by the Stack. That is, if an invalid value was provided, it will be reset to the default value.
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.
New 构造一个新的网络协议栈。
可以通过调用堆栈提供的 SetNetworkProtocolOption/SetTransportProtocolOption 方法来更改协议选项。
请参阅各个协议的实现,以了解支持哪些选项。
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. AddAddress 将新的网络层地址添加到指定的 NIC 。
func (*Stack) AddAddressRange ¶
func (s *Stack) AddAddressRange(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error
AddAddressRange adds a range of addresses to the specified NIC. The range is given by a subnet address, and all addresses contained in the subnet are used except for the subnet address itself and the subnet's broadcast address.
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.
AddAddressWithOptions 与 AddAddress 相同,但是允许您指定新端点是否可以是主要端点。
func (*Stack) AddLinkAddress ¶
AddLinkAddress adds a link address to the stack link cache. AddLinkAddress 将 Mac 地址添加到协议栈的 ARP 缓存。
func (*Stack) AddProtocolAddress ¶
func (s *Stack) AddProtocolAddress(id tcpip.NICID, protocolAddress tcpip.ProtocolAddress) *tcpip.Error
AddProtocolAddress adds a new network-layer protocol address to the specified NIC.
func (*Stack) AddProtocolAddressWithOptions ¶
func (s *Stack) AddProtocolAddressWithOptions(id tcpip.NICID, protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) *tcpip.Error
AddProtocolAddressWithOptions is the same as AddProtocolAddress, but allows you to specify whether the new endpoint can be primary or not.
AddProtocolAddressWithOptions 与 AddProtocolAddress 相同,但是允许您指定新端点是否可以是主要端点。
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 before and after processing of the segment.
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) AllAddresses ¶
func (s *Stack) AllAddresses() map[tcpip.NICID][]tcpip.ProtocolAddress
AllAddresses returns a map of NICIDs to their protocol addresses (primary and non-primary).
func (*Stack) AllowICMPMessage ¶
AllowICMPMessage returns true if we the rate limiter allows at least one ICMP message to be sent at this instant.
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.
确定给定的本地地址是否存在,如果存在,则返回它所绑定的 NIC 的 id 。如果地址不存在,则返回 0 。
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) CleanupEndpoints ¶
func (s *Stack) CleanupEndpoints() []TransportEndpoint
CleanupEndpoints returns endpoints currently in the cleanup state.
func (*Stack) Close ¶
func (s *Stack) Close()
Close closes all currently registered transport endpoints.
Endpoints created or modified during this call may not get closed.
func (*Stack) CompleteTransportEndpointCleanup ¶
func (s *Stack) CompleteTransportEndpointCleanup(ep TransportEndpoint)
CompleteTransportEndpointCleanup removes the endpoint from the cleanup stage.
func (*Stack) CreateDisabledNIC ¶
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.
CreateDisabledNIC 使用提供的 ID 和链路层端点 ep 创建 NIC ,但将其禁用。 在链路层端点开始向其传递数据包之前,必须先调用 Stack.EnableNIC 。
func (*Stack) CreateDisabledNamedNIC ¶
CreateDisabledNamedNIC is a combination of CreateNamedNIC and CreateDisabledNIC.
CreateDisabledNamedNIC 是 CreateNamedNIC 和 CreateDisabledNIC 的组合。
func (*Stack) CreateNIC ¶
CreateNIC creates a NIC with the provided id and link-layer endpoint. CreateNIC 使用所提供的网卡 id 和链路层端点 ep 创建 NIC 。
func (*Stack) CreateNamedLoopbackNIC ¶
CreateNamedLoopbackNIC creates a NIC with the provided id and link-layer endpoint, and a human-readable name. CreateNamedLoopbackNIC 使用提供的网卡 id 和链路层端点 ep 以及易于理解的名称创建 NIC 。
func (*Stack) CreateNamedNIC ¶
CreateNamedNIC creates a NIC with the provided id and link-layer endpoint, and a human-readable name. CreateNamedNIC 使用提供的网卡 id 和链路层端点 ep 以及易于理解的名称创建 NIC 。
func (*Stack) DupTentativeAddrDetected ¶
DupTentativeAddrDetected attempts to inform the NIC with ID id that a tentative addr on it is a duplicate on a link.
func (*Stack) EnableNIC ¶
EnableNIC enables the given NIC so that the link-layer endpoint can start delivering packets to it.
EnableNIC 启用给定的 NIC ,以便链路层端点可以开始向其传递数据包。
func (*Stack) FindRoute ¶
func (s *Stack) FindRoute( id tcpip.NICID, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber, multicastLoop bool, ) (Route, *tcpip.Error)
FindRoute creates a route to the given destination address, leaving through the given nic and local address (if provided).
FindRoute() 创建一条通往给定目标地址的路由,通过给定的 nic 和本地地址(如果提供)来发包。
[重要] FindRoute() 它根据网卡 nic、本地和远端地址、网络层协议、是否广播等参数, 从注册到网卡 nic 上的网络层 eps 选择合适的端点的 ref ,封装成 Route 对象,以支持网络层数据包的发送。
func (*Stack) FindTransportEndpoint ¶
func (s *Stack) FindTransportEndpoint( netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, id TransportEndpointID, r *Route, ) TransportEndpoint
FindTransportEndpoint finds an endpoint that most closely matches the provided id. If no endpoint is found it returns nil.
func (*Stack) Forwarding ¶
Forwarding returns if the packet forwarding between NICs is enabled. 如果启用了 NIC 之间的数据包转发,则返回 true 。
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.AddressWithPrefix, *tcpip.Error)
GetMainNICAddress returns the first primary address and prefix for the given NIC and protocol. Returns an error if the NIC doesn't exist and an empty value if the NIC doesn't have a primary address for the given protocol.
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) HandleNDPRA ¶
func (s *Stack) HandleNDPRA(id tcpip.NICID, ip tcpip.Address, ra header.NDPRouterAdvert) *tcpip.Error
HandleNDPRA provides a NIC with ID id a validated NDP Router Advertisement message that it needs to handle.
func (*Stack) ICMPBurst ¶
ICMPBurst returns the maximum number of ICMP messages that can be sent in a single burst.
func (*Stack) ICMPLimit ¶
ICMPLimit returns the maximum number of ICMP messages that can be sent in one second.
func (*Stack) IsAddrTentative ¶
IsAddrTentative returns true if addr is tentative on the NIC with ID id.
Note that if addr is not associated with a NIC with id ID, then this function will return false. It will only return true if the address is associated with the NIC AND it is tentative.
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) NICAddressRanges ¶
NICSubnets returns a map of NICIDs to their associated subnets. NICSubnets 返回 NICID 到其关联子网的映射。
func (*Stack) NICInfo ¶
NICInfo returns a map of NICIDs to their associated information.
NICInfo 返回 NICIDs 与其相关信息的 Map 。
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) NewPacketEndpoint ¶
func (s *Stack) NewPacketEndpoint(cooked bool, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, *tcpip.Error)
NewPacketEndpoint creates a new packet endpoint listening for the given netProto.
func (*Stack) NewRawEndpoint ¶
func (s *Stack) NewRawEndpoint(transport tcpip.TransportProtocolNumber, network tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue, associated bool) (tcpip.Endpoint, *tcpip.Error)
NewRawEndpoint creates a new raw transport layer endpoint of the given protocol. Raw endpoints receive all traffic for a given protocol regardless of address.
func (*Stack) NowNanoseconds ¶
NowNanoseconds implements tcpip.Clock.NowNanoseconds.
func (*Stack) RegisterPacketEndpoint ¶
func (s *Stack) RegisterPacketEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) *tcpip.Error
RegisterPacketEndpoint registers ep with the stack, causing it to receive all traffic of the specified netProto on the given NIC. If nicID is 0, it receives traffic from every NIC.
func (*Stack) RegisterRawTransportEndpoint ¶
func (s *Stack) RegisterRawTransportEndpoint( nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint, ) *tcpip.Error
RegisterRawTransportEndpoint registers the given endpoint with the stack transport dispatcher. Received packets that match the provided transport protocol will be delivered to the given endpoint.
RegisterRawTransportEndpoint() 将给定的端点注册到协议栈传输层分发器中。 当协议栈接收到与 netProto、transProto 协议相匹配的数据包时,会投递给这些 ep 。
func (*Stack) RegisterRestoredEndpoint ¶
func (s *Stack) RegisterRestoredEndpoint(e ResumableEndpoint)
RegisterRestoredEndpoint records e as an endpoint that has been restored on this stack.
func (*Stack) RegisterTransportEndpoint ¶
func (s *Stack) RegisterTransportEndpoint( nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, reusePort bool, bindToDevice tcpip.NICID, ) *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 将给定的 endpoint 注册到协议栈传输层调度器上。 接收到的 id 的数据包将被传送到给定的 endpoint ; 指定 nic 是可选的,但 nic 特定的 id 比全局的 id 优先。
func (*Stack) RegisteredEndpoints ¶
func (s *Stack) RegisteredEndpoints() []TransportEndpoint
RegisteredEndpoints returns all endpoints which are currently registered.
func (*Stack) RemoveAddress ¶
RemoveAddress removes an existing network-layer address from the specified NIC.
func (*Stack) RemoveAddressRange ¶
RemoveAddressRange removes the range of addresses 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) RestoreCleanupEndpoints ¶
func (s *Stack) RestoreCleanupEndpoints(es []TransportEndpoint)
RestoreCleanupEndpoints adds endpoints to cleanup tracking. This is useful for restoring a stack after a save.
func (*Stack) Resume ¶
func (s *Stack) Resume()
Resume restarts the stack after a restore. This must be called after the entire system has been restored.
func (*Stack) Seed ¶
Seed returns a 32 bit value that can be used as a seed value for port picking, ISN generation etc.
NOTE: The seed is generated once during stack initialization only.
func (*Stack) SetForwarding ¶
SetForwarding enables or disables the packet forwarding between NICs.
func (*Stack) SetICMPBurst ¶
SetICMPBurst sets the maximum number of ICMP messages that can be sent in a single burst.
func (*Stack) SetICMPLimit ¶
SetICMPLimit sets the maximum number of ICMP messages that be sent in one second.
func (*Stack) SetIPTables ¶
SetIPTables sets the stack's iptables.
func (*Stack) SetNDPConfigurations ¶
SetNDPConfigurations sets the per-interface NDP configurations on the NIC with ID id to c.
Note, if c contains invalid NDP configuration values, it will be fixed to use default values for the erroneous values.
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.
启用或禁用指定 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.
启用或禁用指定 NIC 上的地址欺诈,允许端点绑定到 NIC 中的任何地址。
func (*Stack) SetTransportProtocolHandler ¶
func (s *Stack) SetTransportProtocolHandler(p tcpip.TransportProtocolNumber, h func(*Route, TransportEndpointID, tcpip.PacketBuffer) 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) StartTransportEndpointCleanup ¶
func (s *Stack) StartTransportEndpointCleanup( nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, bindToDevice tcpip.NICID, )
StartTransportEndpointCleanup removes the endpoint with the given id from the stack transport dispatcher. It also transitions it to the cleanup stage.
从堆栈传输调度器中删除给定id的端点。
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) UnregisterPacketEndpoint ¶
func (s *Stack) UnregisterPacketEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint)
UnregisterPacketEndpoint unregisters ep for packets of the specified netProto from the specified NIC. If nicID is 0, ep is unregistered from all NICs.
func (*Stack) UnregisterRawTransportEndpoint ¶
func (s *Stack) UnregisterRawTransportEndpoint( nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint, )
UnregisterRawTransportEndpoint removes the endpoint for the transport protocol from the stack transport dispatcher.
func (*Stack) UnregisterTransportEndpoint ¶
func (s *Stack) UnregisterTransportEndpoint( nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, bindToDevice tcpip.NICID, )
UnregisterTransportEndpoint removes the endpoint with the given id from the stack transport dispatcher.
func (*Stack) Wait ¶
func (s *Stack) Wait()
Wait waits for all transport and link endpoints to halt their worker goroutines.
Endpoints created or modified during this call may not get waited on.
Note that link endpoints must be stopped via an implementation specific mechanism.
func (*Stack) WritePacket ¶
func (s *Stack) WritePacket(nicID tcpip.NICID, dst tcpip.LinkAddress, netProto tcpip.NetworkProtocolNumber, payload buffer.VectorisedView) *tcpip.Error
WritePacket writes data directly to the specified NIC. It adds an ethernet header based on the arguments.
func (*Stack) WriteRawPacket ¶
WriteRawPacket writes data directly to the specified NIC without adding any headers.
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.
TCP 四元组
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 // RcvBufAutoTuneParams is used to hold state variables to compute // the auto tuned receive buffer size. RcvAutoParams RcvBufAutoTuneParams // 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 // HighRxt is the highest sequence number which has been retransmitted // during the current loss recovery phase. // See: RFC 6675 Section 2 for details. HighRxt seqnum.Value // RescueRxt is the highest sequence number which has been // optimistically retransmitted to prevent stalling of the ACK clock // when there is loss at the end of the window and no new data is // available for transmission. // See: RFC 6675 Section 2 for details. RescueRxt seqnum.Value }
TCPFastRecoveryState holds a copy of the internal fast recovery state of a TCP endpoint.
TCP 快速恢复状态
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 Blocks that identify the out of order segments // held by a given TCP endpoint. Blocks []header.SACKBlock // ReceivedBlocks are the SACK blocks received by this endpoint // from the peer endpoint. ReceivedBlocks []header.SACKBlock // MaxSACKED is the highest sequence number that has been SACKED // by the peer. MaxSACKED seqnum.Value }
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. // // pkt.NetworkHeader must be set before calling DeliverTransportPacket. // // DeliverTransportPacket takes ownership of pkt. // // DeliverTransportPacket() 将数据包传送到适当的传输协议端点。 // 在调用 DeliverTransportPacket() 之前必须设置 pkt.NetworkHeader 。 // DeliverTransportPacket() 会获得 pkt.NetworkHeader 的所有权。 DeliverTransportPacket(r *Route, protocol tcpip.TransportProtocolNumber, pkt tcpip.PacketBuffer) // DeliverTransportControlPacket delivers control packets to the appropriate transport protocol endpoint. // // pkt.NetworkHeader must be set before calling DeliverTransportControlPacket. // // DeliverTransportControlPacket takes ownership of pkt. DeliverTransportControlPacket(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, typ ControlType, extra uint32, pkt tcpip.PacketBuffer) }
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.
TransportDispatcher 包含协议栈在处理完网络层数据包后,将数据包传递到合适的传输层端点的方法。
type TransportEndpoint ¶
type TransportEndpoint interface { // UniqueID returns an unique ID for this transport endpoint. UniqueID() uint64 // HandlePacket is called by the stack when new packets arrive to // this transport endpoint. It sets pkt.TransportHeader. // HandlePacket takes ownership of pkt. // // 当新数据包到达这个传输端点时,协议栈会调用 HandlePacket() 。 HandlePacket(r *Route, id TransportEndpointID, pkt tcpip.PacketBuffer) // HandleControlPacket is called by the stack when new control (e.g. ICMP) // packets arrive to this transport endpoint. // HandleControlPacket takes ownership of pkt. // // 当新的控制报文(如 ICMP )到达这个传输端点时,协议栈会调用 HandleControlPacket() 。 HandleControlPacket(id TransportEndpointID, typ ControlType, extra uint32, pkt tcpip.PacketBuffer) // Close puts the endpoint in a closed state and frees all resources // associated with it. This cleanup may happen asynchronously. Wait can // be used to block on this asynchronous cleanup. Close() // Wait waits for any worker goroutines owned by the endpoint to stop. // // An endpoint can be requested to stop its worker goroutines by calling // its Close method. // // Wait will not block if the endpoint hasn't started any goroutines // yet, even if it might later. Wait() }
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 是与端点相关联的本地端口。 LocalPort uint16 // LocalAddress is the local [network layer] address associated with the endpoint. // LocalAddress 是与端点相关联的本地[网络层]地址。 LocalAddress tcpip.Address // RemotePort is the remote port associated with the endpoint. // RemotePort 是与端点相关联的远程端口。 RemotePort uint16 // RemoteAddress is the remote [network layer] address associated with the endpoint. // RemoteAddress 是与端点相关联的远程[网络层]地址。 RemoteAddress tcpip.Address }
TransportEndpointID is the identifier of a transport layer protocol endpoint.
TransportEndpointID 是传输层协议端点的标识符,<本地端口, 本地地址,远程端口,远程地址>。
+stateify savable
type TransportEndpointInfo ¶
type TransportEndpointInfo struct { // The following fields are initialized at creation time and are immutable. NetProto tcpip.NetworkProtocolNumber TransProto tcpip.TransportProtocolNumber // The following fields are protected by endpoint mu. ID TransportEndpointID // BindNICID and bindAddr are set via calls to Bind(). // They are used to reject attempts to send data or connect via a different NIC or address // // BindNICID 和 BindAddr 是通过调用 Bind() 来设置的。 // 用于绑定连接、发送所使用的 NIC 和地址。 BindNICID tcpip.NICID BindAddr tcpip.Address RegisterNICID tcpip.NICID }
TransportEndpointInfo holds useful information about a transport endpoint which can be queried by monitoring tools.
+stateify savable
func (*TransportEndpointInfo) IsEndpointInfo ¶
func (*TransportEndpointInfo) IsEndpointInfo()
IsEndpointInfo is an empty method to implement the tcpip.EndpointInfo marker interface.
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) // NewRawEndpoint creates a new raw endpoint of the transport protocol. NewRawEndpoint(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 takes ownership of pkt. HandleUnknownDestinationPacket(r *Route, id TransportEndpointID, pkt tcpip.PacketBuffer) 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.