Movatterモバイル変換


[0]ホーム

URL:


packet

package
v1.92.3Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License:BSD-3-ClauseImports:14Imported by:27

Details

Repository

github.com/tailscale/tailscale

Links

Documentation

Overview

Package packet contains packet parsing and marshaling utilities.

Parsed provides allocation-free minimal packet header decoding, foruse in packet filtering. The other types in the package are forconstructing and marshaling packets into []bytes.

To support allocation-free parsing, this package defines IPv4 andIPv6 address types. You should prefer to use netaddr's types,except where you absolutely need allocation-free IP handling(i.e. in the tunnel datapath) and are willing to implement allcodepaths and data structures twice, once per IP family.

Index

Constants

View Source
const (// GeneveProtocolDisco is the IEEE 802 Ethertype number used to represent// the Tailscale Disco protocol in a Geneve header.GeneveProtocolDiscouint16 = 0x7A11// GeneveProtocolWireGuard is the IEEE 802 Ethertype number used to represent the// WireGuard protocol in a Geneve header.GeneveProtocolWireGuarduint16 = 0x7A12)
View Source
const (// GeneveFixedHeaderLength is the length of the fixed size portion of the// Geneve header, in bytes.GeneveFixedHeaderLength = 8)

Variables

View Source
var ErrGeneveVNIUnset =errors.New("VNI is unset")

Functions

funcGenerate

func Generate(hHeader, payload []byte) []byte

Generate generates a new packet with the given Header andpayload. This function allocates memory, see Header.Marshal for anallocation-free option.

funcHexdump

func Hexdump(b []byte)string

funcICMPEchoPayloadadded inv1.26.0

func ICMPEchoPayload(payload []byte) (idSequint32, buf []byte)

ICMPEchoPayload generates a new random ID/Sequence pair, and returns a uint32derived from them, along with the id, sequence and given payload in a buffer.It returns an error if the random source could not be read.

Types

typeCaptureCallbackadded inv1.80.0

type CaptureCallback func(CapturePath,time.Time, []byte,CaptureMeta)

Callback describes a function which is called torecord packets when debugging packet-capture.Such callbacks must not take ownership of theprovided data slice: it may only copy out of itwithin the lifetime of the function.

typeCaptureMetaadded inv1.40.0

type CaptureMeta struct {DidSNATbool// SNAT was performed & the address was updated.OriginalSrcnetip.AddrPort// The source address before SNAT was performed.DidDNATbool// DNAT was performed & the address was updated.OriginalDstnetip.AddrPort// The destination address before DNAT was performed.}

CaptureMeta contains metadata that is used when debugging.

typeCapturePathadded inv1.80.0

type CapturePathuint8

CapturePath describes where in the data path the packet was captured.

const (// FromLocal indicates the packet was logged as it traversed the FromLocal path:// i.e.: A packet from the local system into the TUN.FromLocalCapturePath = 0// FromPeer indicates the packet was logged upon reception from a remote peer.FromPeerCapturePath = 1// SynthesizedToLocal indicates the packet was generated from within tailscaled,// and is being routed to the local machine's network stack.SynthesizedToLocalCapturePath = 2// SynthesizedToPeer indicates the packet was generated from within tailscaled,// and is being routed to a remote Wireguard peer.SynthesizedToPeerCapturePath = 3// PathDisco indicates the packet is information about a disco frame.PathDiscoCapturePath = 254)

CapturePath values

typeCaptureSinkadded inv1.80.0

type CaptureSink interface {// Close closesClose()error// NumOutputs returns the number of outputs registered with the sink.NumOutputs()int// CaptureCallback returns a callback which can be used to// write packets to the sink.CaptureCallback()CaptureCallback// WaitCh returns a channel which blocks until// the sink is closed.WaitCh() <-chan struct{}// RegisterOutput connects an output to this sink, which// will be written to with a pcap stream as packets are logged.// A function is returned which unregisters the output when// called.//// If w implements io.Closer, it will be closed upon error// or when the sink is closed. If w implements http.Flusher,// it will be flushed periodically.RegisterOutput(wio.Writer) (unregister func())}

CaptureSink is the minimal interface fromtailscale.com/feature/capture'sSink type that is needed by the core (magicsock/LocalBackend/wgengine/etc).This lets the relativel heavy feature/capture package be optionally linked.

typeGeneveHeaderadded inv1.82.0

type GeneveHeader struct {// Ver (2 bits): The current version number is 0. Packets received by a// tunnel endpoint with an unknown version MUST be dropped. Transit devices// interpreting Geneve packets with an unknown version number MUST treat// them as UDP packets with an unknown payload.Versionuint8// Protocol Type (16 bits): The type of protocol data unit appearing after// the Geneve header. This follows the Ethertype [ETYPES] convention, with// Ethernet itself being represented by the value 0x6558.Protocoluint16// Virtual Network Identifier (VNI) (24 bits): An identifier for a unique// element of a virtual network. In many situations, this may represent an// L2 segment; however, the control plane defines the forwarding semantics// of decapsulated packets. The VNI MAY be used as part of ECMP forwarding// decisions or MAY be used as a mechanism to distinguish between// overlapping address spaces contained in the encapsulated packet when load// balancing across CPUs.VNIVirtualNetworkID// O (1 bit): Control packet. This packet contains a control message.// Control messages are sent between tunnel endpoints. Tunnel endpoints MUST// NOT forward the payload, and transit devices MUST NOT attempt to// interpret it. Since control messages are less frequent, it is RECOMMENDED// that tunnel endpoints direct these packets to a high-priority control// queue (for example, to direct the packet to a general purpose CPU from a// forwarding Application-Specific Integrated Circuit (ASIC) or to separate// out control traffic on a NIC). Transit devices MUST NOT alter forwarding// behavior on the basis of this bit, such as ECMP link selection.Controlbool}

GeneveHeader represents the fixed size Geneve header from RFC8926.TLVs/options are not implemented/supported.

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+|Ver|  Opt Len  |O|C|    Rsvd.  |          Protocol Type        |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+|        Virtual Network Identifier (VNI)       |    Reserved   |+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

func (*GeneveHeader)Decodeadded inv1.82.0

func (h *GeneveHeader) Decode(b []byte)error

Decode decodes GeneveHeader from b. If len(b) <GeneveFixedHeaderLength anio.ErrShortBuffer error is returned.

func (*GeneveHeader)Encodeadded inv1.82.0

func (h *GeneveHeader) Encode(b []byte)error

Encode encodes GeneveHeader into b. If len(b) <GeneveFixedHeaderLength anio.ErrShortBuffer error is returned. If !h.VNI.IsSet() then anErrGeneveVNIUnset error is returned.

typeHeader

type Header interface {// Len returns the length of the marshaled packet.Len()int// Marshal serializes the header into buf, which must be at// least Len() bytes long. Implementations of Marshal assume// that bytes after the first Len() are payload bytes for the// purpose of computing length and checksum fields. Marshal// implementations must not allocate memory.Marshal(buf []byte)error}

Header is a packet header capable of marshaling itself into a bytebuffer.

typeHeaderChecksummeradded inv1.20.0

type HeaderChecksummer interface {Header// WriteCheck writes the correct checksum into buf, which should// be be the already-marshalled header and payload.WriteChecksum(buf []byte)}

HeaderChecksummer is implemented by Header implementations thatneed to do a checksum over their payloads.

typeICMP4Code

type ICMP4Codeuint8

ICMP4Code is an ICMPv4 code, as specified inhttps://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml

const (ICMP4NoCodeICMP4Code = 0)

typeICMP4Header

type ICMP4Header struct {IP4HeaderTypeICMP4TypeCodeICMP4Code}

ICMP4Header is an IPv4+ICMPv4 header.

func (ICMP4Header)Len

func (hICMP4Header) Len()int

Len implements Header.

func (ICMP4Header)Marshal

func (hICMP4Header) Marshal(buf []byte)error

Marshal implements Header.

func (*ICMP4Header)ToResponse

func (h *ICMP4Header) ToResponse()

ToResponse implements Header. TODO: it doesn't implement itcorrectly, instead it statically generates an ICMP Echo Replypacket.

typeICMP4Type

type ICMP4Typeuint8

ICMP4Type is an ICMPv4 type, as specified inhttps://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml

const (ICMP4EchoReplyICMP4Type = 0x00ICMP4EchoRequestICMP4Type = 0x08ICMP4UnreachableICMP4Type = 0x03ICMP4TimeExceededICMP4Type = 0x0bICMP4ParamProblemICMP4Type = 0x12)

func (ICMP4Type)String

func (tICMP4Type) String()string

typeICMP6Code

type ICMP6Codeuint8

ICMP6Code is an ICMPv6 code, as specified inhttps://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml

const (ICMP6NoCodeICMP6Code = 0)

typeICMP6Headeradded inv1.20.0

type ICMP6Header struct {IP6HeaderTypeICMP6TypeCodeICMP6Code}

ICMP6Header is an IPv4+ICMPv4 header.

func (ICMP6Header)Lenadded inv1.20.0

func (hICMP6Header) Len()int

Len implements Header.

func (ICMP6Header)Marshaladded inv1.20.0

func (hICMP6Header) Marshal(buf []byte)error

Marshal implements Header.

func (*ICMP6Header)ToResponseadded inv1.20.0

func (h *ICMP6Header) ToResponse()

ToResponse implements Header. TODO: it doesn't implement itcorrectly, instead it statically generates an ICMP Echo Replypacket.

func (ICMP6Header)WriteChecksumadded inv1.20.0

func (hICMP6Header) WriteChecksum(p []byte)

WriteChecksum implements HeaderChecksummer, writing just the checksum bytesinto the otherwise fully marshaled ICMP6 packet p (which should include theIPv6 header, ICMPv6 header, and payload).

typeICMP6Type

type ICMP6Typeuint8

ICMP6Type is an ICMPv6 type, as specified inhttps://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml

const (ICMP6UnreachableICMP6Type = 1ICMP6PacketTooBigICMP6Type = 2ICMP6TimeExceededICMP6Type = 3ICMP6ParamProblemICMP6Type = 4ICMP6EchoRequestICMP6Type = 128ICMP6EchoReplyICMP6Type = 129)

func (ICMP6Type)String

func (tICMP6Type) String()string

typeIP4Header

type IP4Header struct {IPProtoipproto.ProtoIPIDuint16Srcnetip.AddrDstnetip.Addr}

IP4Header represents an IPv4 packet header.

func (IP4Header)Len

func (hIP4Header) Len()int

Len implements Header.

func (IP4Header)Marshal

func (hIP4Header) Marshal(buf []byte)error

Marshal implements Header.

func (*IP4Header)ToResponse

func (h *IP4Header) ToResponse()

ToResponse implements Header.

typeIP6Header

type IP6Header struct {IPProtoipproto.ProtoIPIDuint32// only lower 20 bits usedSrcnetip.AddrDstnetip.Addr}

IP6Header represents an IPv6 packet header.

func (IP6Header)Len

func (hIP6Header) Len()int

Len implements Header.

func (IP6Header)Marshal

func (hIP6Header) Marshal(buf []byte)error

Marshal implements Header.

func (*IP6Header)ToResponse

func (h *IP6Header) ToResponse()

ToResponse implements Header.

typeParsed

type Parsed struct {// IPVersion is the IP protocol version of the packet (4 or// 6), or 0 if the packet doesn't look like IPv4 or IPv6.IPVersionuint8// IPProto is the IP subprotocol (UDP, TCP, etc.). Valid iff IPVersion != 0.IPProtoipproto.Proto// Src is the source address. Family matches IPVersion. Port is// valid iff IPProto == TCP || IPProto == UDP || IPProto == SCTP.Srcnetip.AddrPort// Dst is the destination address. Family matches IPVersion. Port is// valid iff IPProto == TCP || IPProto == UDP || IPProto == SCTP.Dstnetip.AddrPort// TCPFlags is the packet's TCP flag bits. Valid iff IPProto == TCP.TCPFlagsTCPFlag// CaptureMeta contains metadata that is used when debugging.CaptureMetaCaptureMeta// contains filtered or unexported fields}

Parsed is a minimal decoding of a packet suitable for use in filters.

func (*Parsed)AsTSMPDiscoAdvertisementadded inv1.92.0

func (pp *Parsed) AsTSMPDiscoAdvertisement() (tkaTSMPDiscoKeyAdvertisement, okbool)

func (*Parsed)AsTSMPPingadded inv1.8.0

func (pp *Parsed) AsTSMPPing() (hTSMPPingRequest, okbool)

func (*Parsed)AsTSMPPongadded inv1.8.0

func (pp *Parsed) AsTSMPPong() (pongTSMPPongReply, okbool)

AsTSMPPong returns pp as a TSMPPongReply and whether it is one.The pong.IPHeader field is not populated.

func (*Parsed)AsTailscaleRejectedHeader

func (pp *Parsed) AsTailscaleRejectedHeader() (hTailscaleRejectedHeader, okbool)

AsTailscaleRejectedHeader parses pp as an incoming rejectionconnection TSMP message.

ok reports whether pp was a valid TSMP rejection packet.

func (*Parsed)Buffer

func (q *Parsed) Buffer() []byte

Buffer returns the entire packet buffer.This is a read-only view; that is, q retains the ownership of the buffer.

func (*Parsed)Decode

func (q *Parsed) Decode(b []byte)

Decode extracts data from the packet in b into q.It performs extremely simple packet decoding for basic IPv4 and IPv6 packet types.It extracts only the subprotocol id, IP addresses, and (if any) ports,and shouldn't need any memory allocation.

func (*Parsed)EchoIDSeqadded inv1.26.0

func (q *Parsed) EchoIDSeq()uint32

EchoIDSeq extracts the identifier/sequence bytes from an ICMP Echo response,and returns them as a uint32, used to lookup internally routed ICMP echoresponses. This function is intentionally lightweight as it is called onevery incoming ICMP packet.

func (*Parsed)ICMP4Header

func (q *Parsed) ICMP4Header()ICMP4Header

func (*Parsed)ICMP6Headeradded inv1.20.0

func (q *Parsed) ICMP6Header()ICMP6Header

func (*Parsed)IP4Header

func (q *Parsed) IP4Header()IP4Header

func (*Parsed)IP6Headeradded inv1.8.0

func (q *Parsed) IP6Header()IP6Header

func (*Parsed)IsEchoRequest

func (q *Parsed) IsEchoRequest()bool

IsEchoRequest reports whether q is an ICMP Echo Request.

func (*Parsed)IsEchoResponse

func (q *Parsed) IsEchoResponse()bool

IsEchoResponse reports whether q is an IPv4 ICMP Echo Response.

func (*Parsed)IsError

func (q *Parsed) IsError()bool

IsError reports whether q is an ICMP "Error" packet.

func (*Parsed)IsTCPSyn

func (q *Parsed) IsTCPSyn()bool

IsTCPSyn reports whether q is a TCP SYN packet,without ACK set. (i.e. the first packet in a new connection)

func (*Parsed)Payload

func (q *Parsed) Payload() []byte

Payload returns the payload of the IP subprotocol section.This is a read-only view; that is, q retains the ownership of the buffer.

func (*Parsed)String

func (p *Parsed) String()string

func (*Parsed)StuffForTestingadded inv1.6.0

func (q *Parsed) StuffForTesting(lenint)

StuffForTesting makes Parsed contain a len-bytes buffer. Used intests to build up a synthetic parse result with a non-zero buffer.

func (*Parsed)Transportadded inv1.20.2

func (p *Parsed) Transport() []byte

Transport returns the transport header and payload (IP subprotocol, such as TCP or UDP).This is a read-only view; that is, p retains the ownership of the buffer.

func (*Parsed)UDP4Header

func (q *Parsed) UDP4Header()UDP4Header

typeTCPFlag

type TCPFlaguint8
const (TCPFinTCPFlag = 0x01TCPSynTCPFlag = 0x02TCPRstTCPFlag = 0x04TCPPshTCPFlag = 0x08TCPAckTCPFlag = 0x10TCPUrgTCPFlag = 0x20TCPECNEchoTCPFlag = 0x40TCPCWRTCPFlag = 0x80TCPSynAckTCPFlag =TCPSyn |TCPAckTCPECNBitsTCPFlag =TCPECNEcho |TCPCWR)

typeTSMPDiscoKeyAdvertisementadded inv1.92.0

type TSMPDiscoKeyAdvertisement struct {Src, Dstnetip.AddrKeykey.DiscoPublic}

TSMPDiscoKeyAdvertisement is a TSMP message that's used for distributing Disco Keys.

On the wire, after the IP header, it's currently 33 bytes:

  • 'a' (TSMPTypeDiscoAdvertisement)
  • 32 disco key bytes

func (*TSMPDiscoKeyAdvertisement)Marshaladded inv1.92.0

func (ka *TSMPDiscoKeyAdvertisement) Marshal() ([]byte,error)

typeTSMPPingRequestadded inv1.8.0

type TSMPPingRequest struct {Data [8]byte}

TSMPPingRequest is a TSMP message that's like an ICMP ping request.

On the wire, after the IP header, it's currently 9 bytes:

  • 'p' (TSMPTypePing)
  • 8 opaque ping bytes to copy back in the response

typeTSMPPongReplyadded inv1.8.0

type TSMPPongReply struct {IPHeaderHeaderData        [8]bytePeerAPIPortuint16}

func (TSMPPongReply)Lenadded inv1.8.0

func (hTSMPPongReply) Len()int

func (TSMPPongReply)Marshaladded inv1.8.0

func (hTSMPPongReply) Marshal(buf []byte)error

typeTSMPType

type TSMPTypeuint8
const (// TSMPTypeRejectedConn is the type byte for a TailscaleRejectedHeader.TSMPTypeRejectedConnTSMPType = '!'// TSMPTypePing is the type byte for a TailscalePingRequest.TSMPTypePingTSMPType = 'p'// TSMPTypePong is the type byte for a TailscalePongResponse.TSMPTypePongTSMPType = 'o'// TSPMTypeDiscoAdvertisement is the type byte for sending disco keysTSMPTypeDiscoAdvertisementTSMPType = 'a')

typeTailscaleRejectReason

type TailscaleRejectReasonbyte
const (// TailscaleRejectReasonNone is the TailscaleRejectReason zero value.TailscaleRejectReasonNoneTailscaleRejectReason = 0// RejectedDueToACLs means that the host rejected the connection due to ACLs.RejectedDueToACLsTailscaleRejectReason = 'A'// RejectedDueToShieldsUp means that the host rejected the connection due to shields being up.RejectedDueToShieldsUpTailscaleRejectReason = 'S'// RejectedDueToIPForwarding means that the relay node's IP// forwarding is disabled.RejectedDueToIPForwardingTailscaleRejectReason = 'F'// RejectedDueToHostFirewall means that the target host's// firewall is blocking the traffic.RejectedDueToHostFirewallTailscaleRejectReason = 'W')

func (TailscaleRejectReason)IsZeroadded inv1.4.3

func (rTailscaleRejectReason) IsZero()bool

IsZero reports whether r is the zero value, representing no rejection.

func (TailscaleRejectReason)String

typeTailscaleRejectedHeader

type TailscaleRejectedHeader struct {IPSrcnetip.Addr// IPv4 or IPv6 header's src IPIPDstnetip.Addr// IPv4 or IPv6 header's dst IPSrcnetip.AddrPort// rejected flow's srcDstnetip.AddrPort// rejected flow's dstProtoipproto.Proto// proto that was rejected (TCP or UDP)ReasonTailscaleRejectReason// why the connection was rejected// MaybeBroken is whether the rejection is non-terminal (the// client should not fail immediately). This is sent by a// target when it's not sure whether it's totally broken, but// it might be. For example, the target tailscaled might think// its host firewall or IP forwarding aren't configured// properly, but tailscaled might be wrong (not having enough// visibility into what the OS is doing). When true, the// message is simply an FYI as a potential reason to use for// later when the pendopen connection tracking timer expires.MaybeBrokenbool}

TailscaleRejectedHeader is a TSMP message that says that oneTailscale node has rejected the connection from another. Unlike aTCP RST, this includes a reason.

On the wire, after the IP header, it's currently 7 or 8 bytes:

  • '!'
  • IPProto byte (IANA protocol number: TCP or UDP)
  • 'A' or 'S' (RejectedDueToACLs, RejectedDueToShieldsUp)
  • srcPort big endian uint16
  • dstPort big endian uint16
  • [optional] byte of flag bits:lowest bit (0x1): MaybeBroken

In the future it might also accept 16 byte IP flow src/dst IPsafter the header, if they're different than the IP-level ones.

func (TailscaleRejectedHeader)Len

func (TailscaleRejectedHeader)Marshal

func (hTailscaleRejectedHeader) Marshal(buf []byte)error

func (TailscaleRejectedHeader)String

typeUDP4Header

type UDP4Header struct {IP4HeaderSrcPortuint16DstPortuint16}

UDP4Header is an IPv4+UDP header.

func (UDP4Header)Len

func (hUDP4Header) Len()int

Len implements Header.

func (UDP4Header)Marshal

func (hUDP4Header) Marshal(buf []byte)error

Marshal implements Header.

func (*UDP4Header)ToResponse

func (h *UDP4Header) ToResponse()

ToResponse implements Header.

typeUDP6Header

type UDP6Header struct {IP6HeaderSrcPortuint16DstPortuint16}

UDP6Header is an IPv6+UDP header.

func (UDP6Header)Len

func (hUDP6Header) Len()int

Len implements Header.

func (UDP6Header)Marshal

func (hUDP6Header) Marshal(buf []byte)error

Marshal implements Header.

func (*UDP6Header)ToResponse

func (h *UDP6Header) ToResponse()

ToResponse implements Header.

typeVirtualNetworkIDadded inv1.88.0

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

VirtualNetworkID is a Geneve header (RFC8926) 3-byte virtual networkidentifier. Its methods are NOT thread-safe.

func (*VirtualNetworkID)Getadded inv1.88.0

func (v *VirtualNetworkID) Get()uint32

Get returns the VNI value.

func (*VirtualNetworkID)IsSetadded inv1.88.0

func (v *VirtualNetworkID) IsSet()bool

IsSet returns true if Set() had been called previously, otherwise false.

func (*VirtualNetworkID)Setadded inv1.88.0

func (v *VirtualNetworkID) Set(vniuint32)

Set sets the provided VNI. If VNI exceeds the 3-byte storage it will beclamped.

Source Files

View all Source files

Directories

PathSynopsis
Package checksum provides functions for updating checksums in parsed packets.
Package checksum provides functions for updating checksums in parsed packets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp