engine

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: BSD-3-Clause Imports: 41 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package engine provides local socket capabilities and explicit network probes. Every probe disables Tailscale network namespace binding for the process.

Index

Constants

View Source
const DirectPacketLimit = 1452

DirectPacketLimit is 1500 minus the IPv6 (40) and UDP (8) headers. IPv4 permits 1472, but pinned quic-go caps packets at this common limit. Magicsock strips our eight bytes of headroom on direct UDP sends.

View Source
const SocketBufferBytes = 7 << 20

SocketBufferBytes is magicsock's fixed socket buffer request in bytes.

Variables

View Source
var ErrNoCredential = errors.New("no signaling credential")

ErrNoCredential lets a caller refuse a dial when no current credential exists.

View Source
var ErrPortUnavailable = errors.New("requested UDP port unavailable")

ErrPortUnavailable means the requested fixed UDP port could not be bound.

Functions

func WebSocketDialer

func WebSocketDialer(tlsConfig *tls.Config, headers func(context.Context) (http.Header, error)) func(ctx context.Context, url string) (net.Conn, error)

WebSocketDialer returns a binary DERP stream dialer. Each attempt calls headers afresh; its errors are wrapped. HTTPS, TLS verification and no redirects apply. The dialer uses no proxy and reads no environment variable. A nil headers function supplies no credential headers. The caller closes streams.

Types

type Addr

type Addr struct{ Key protocol.NodeKey }

Addr identifies a node independently of its current UDP endpoint.

func (Addr) Network

func (Addr) Network() string

Network returns the logical transport name.

func (Addr) String

func (a Addr) String() string

String returns the node's canonical public key.

type BufferReport

type BufferReport struct {
	Requested  int
	Granted    int
	Forced     bool
	ForceErrno string
}

BufferReport records a Linux socket buffer request and its outcome. Granted is the raw kernel readback, including Linux's doubling. Exactly one of Forced and a nonempty ForceErrno describes the FORCE attempt. All fields are zero on other platforms.

type CapabilityReport

type CapabilityReport struct {
	Platform      string
	GSO           Support
	GRO           Support
	DF            Support
	ReceiveBuffer BufferReport
	SendBuffer    BufferReport
	BBRSender     string
}

CapabilityReport describes local facilities without sending network traffic. Platform is runtime.GOOS. ReceiveBuffer and SendBuffer describe the IPv4 socket; feature support covers IPv4 and IPv6 when IPv6 is available. BBRSender names the default QUIC sender.

func ProbeCapabilities

func ProbeCapabilities(ctx context.Context, log *slog.Logger) (CapabilityReport, error)

ProbeCapabilities opens unconnected loopback UDP sockets, reads local socket facilities, and closes the sockets without sending packets. It returns an error if no probe can run or ctx ends. A nil log discards diagnostic messages.

type Config

type Config struct {
	PrivateKey         NodePrivate
	Port               uint16
	Logger             *slog.Logger
	Signaling          *Signaling
	Regions            []protocol.Region
	STUNServers        []string
	PortMapping        bool
	GSO                bool
	RelayedDataAllowed func(peer protocol.NodeKey) bool
	StaticNetwork      bool
	// Window, when set, returns the instant the engine's permission to exchange
	// packets with peers ends; a zero or past instant means it has ended. The
	// engine reads it before each probe, on each pong, confirmation read, peer
	// update and lease check, and again at the instant it returned, so a later
	// instant extends the permission. Once it has ended the engine removes every
	// peer, so magicsock sends and accepts no discovery for them, and it records
	// no confirmation and installs no later peer until Close. Until the expiry
	// loop has removed the peers, magicsock can still answer a ping already in
	// flight: one timer firing and one peer update, or up to one 500 ms probe
	// round when Window ends without moving its instant. The engine may call
	// Window while it holds its own locks, so Window must not call the engine.
	// Nil sets no limit.
	Window func() time.Time
}

Config controls one engine. A zero Port requests an ephemeral UDP port. Nil RelayedDataAllowed denies all relayed data. StaticNetwork disables mapping.

func (Config) Validate

func (c Config) Validate() error

Validate refuses an unconfigured key, missing dialer and malformed servers or regions.

type Counters

type Counters struct {
	UDP4     uint64 `json:"udp4"`
	UDP6     uint64 `json:"udp6"`
	DERP     uint64 `json:"derp"`
	DERPSent uint64 `json:"derp_sent"`

	LazyDrops uint64 `json:"lazy_drops"`
	DERPDrops uint64 `json:"derp_drops"`

	GSOEnabled           bool    `json:"gso_enabled"`
	BindSends            uint64  `json:"bind_sends"`
	SendDatagrams        uint64  `json:"send_datagrams"`
	MeanDatagramsPerSend float64 `json:"mean_datagrams_per_bind_send"`
	// Receive batches and their mean include only datagrams admitted to ReadFrom.
	ReceiveBatches               uint64  `json:"receive_batches"`
	MeanDatagramsPerReceiveBatch float64 `json:"mean_datagrams_per_receive_batch"`
}

Counters are cumulative from socket creation, including establishment. DERP includes both received media packets and successful media sends, even when the relay drops those sends before delivery. Disco frames are excluded.

type Engine

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

Engine owns one magicsock bind and its shared packet adapter. Close releases both.

func New

func New(ctx context.Context, c Config) (_ *Engine, retErr error)

New validates c and opens ordinary UDP sockets. It returns ErrPortUnavailable if the configured fixed port is unavailable, releasing all partial resources.

func (*Engine) Changed

func (e *Engine) Changed() <-chan struct{}

Changed returns a capacity-1 coalescing channel for one registration reader.

func (*Engine) Close

func (e *Engine) Close() error

Close cancels work and releases connections, sockets and monitors exactly once. It returns any socket or monitor close error; repeated calls return that error.

func (*Engine) Counters

func (e *Engine) Counters() Counters

Counters returns cumulative adapter statistics without resetting them.

func (*Engine) DERPDataSuppressed

func (e *Engine) DERPDataSuppressed() int64

DERPDataSuppressed returns the number of relayed sends denied by policy.

func (*Engine) DiscoKey

func (e *Engine) DiscoKey() protocol.DiscoKey

DiscoKey returns the current discovery identity.

func (*Engine) Expire

func (e *Engine) Expire()

Expire removes every peer, its admission handles and tracked connections now.

func (*Engine) IsPeer

func (e *Engine) IsPeer(k protocol.NodeKey) bool

IsPeer reports whether k has a live lease on this open engine.

func (*Engine) LocalPort

func (e *Engine) LocalPort() uint16

LocalPort returns the actual bound UDP port.

func (*Engine) PacketConn

func (e *Engine) PacketConn() net.PacketConn

PacketConn returns the shared packet adapter. Its lifetime ends with Close.

func (*Engine) Path

func (e *Engine) Path(k protocol.NodeKey) PathStatus

Path returns the current path for a live peer, or class "none". It never stamps TimeToDirect; the direct pong callback owns that timestamp.

func (*Engine) PublicKey

func (e *Engine) PublicKey() protocol.NodeKey

PublicKey returns this engine's stable node identity.

func (*Engine) Ready

func (e *Engine) Ready(ctx context.Context, k protocol.NodeKey) error

Ready waits for independent direct evidence in both directions. Cancellation, engine closure or an absent lease prevents readiness.

func (*Engine) Rebind

func (e *Engine) Rebind()

Rebind resets mappings and confirmation evidence, then signals port drift.

func (*Engine) Registration

func (e *Engine) Registration() (protocol.Registration, error)

Registration returns at most 64 endpoints, preferring STUN and port mappings, then IPv4 and IPv6. It includes at most 64 live confirmations, the first by peer key, or returns net.ErrClosed.

func (*Engine) SetPeers

func (e *Engine) SetPeers(ps []Peer) error

SetPeers replaces the graph. Keys and endpoints are copied; expired peers are removed. Discovery identity changes close that peer's tracked connections. Malformed or duplicate identities refuse the update before changing the graph.

func (*Engine) SetRegions

func (e *Engine) SetRegions(rs []protocol.Region) error

SetRegions atomically replaces listed HTTPS signaling regions. A missing home region is synthesized for Signaling.Dial. Closed engines return net.ErrClosed.

func (*Engine) TrackConnection

func (e *Engine) TrackConnection(c *quic.Conn) error

TrackConnection binds c to its live peer lease, closing it on removal or key change. It closes and refuses connections with an unknown or expired identity.

type NATReport

type NATReport struct {
	UDP                 bool
	IPv4                bool
	IPv6                bool
	GlobalV4            netip.AddrPort
	GlobalV6            netip.AddrPort
	MappingVariesByDest Tri
}

NATReport records STUN observations. Unobserved addresses are zero. MappingVariesByDest describes IPv4 mapping variation only.

func CheckNAT

func CheckNAT(ctx context.Context, log *slog.Logger, stunServers []string) (NATReport, error)

CheckNAT uses only the supplied host:port STUN servers. It returns an error for invalid server addresses, failure to start, or an ended context. Missing STUN responses leave false or unknown fields. A nil log discards diagnostics.

type NodePrivate

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

NodePrivate holds a clamped X25519 scalar. Its zero value is unconfigured.

func NodePrivateFromBytes

func NodePrivateFromBytes(b [32]byte) NodePrivate

NodePrivateFromBytes accepts any bytes and clamps them as RFC 7748 specifies.

func (NodePrivate) Public

func (k NodePrivate) Public() protocol.NodeKey

Public returns the public identity; an unconfigured private key returns zero.

type PathClass

type PathClass string

PathClass is "none", "direct", or "relayed" for the current observed path.

type PathStatus

type PathStatus struct {
	Class        PathClass      `json:"class"`
	Endpoint     netip.AddrPort `json:"endpoint"`
	TimeToDirect time.Duration  `json:"time_to_direct_ns"`
}

PathStatus separates the observed UDP endpoint from permitted relay use. JSON fields are class, endpoint, and time_to_direct_ns (nanoseconds). TimeToDirect is zero until the first confirmed direct observation.

type Peer

type Peer struct {
	NodeKey      protocol.NodeKey
	DiscoKey     protocol.DiscoKey
	Endpoints    []netip.AddrPort
	HomeRegion   int
	Expires      time.Time
	Confirmation *protocol.Confirmation
}

Peer is a leased node identity and its independent confirmation of this engine.

type PortMappingReport

type PortMappingReport struct {
	UPnP      bool
	PMP       bool
	PCP       bool
	NoGateway bool
}

PortMappingReport records discovered router services without creating a mapping. NoGateway means the default gateway lookup failed and no probe packet was sent.

func ProbePortMapping

func ProbePortMapping(ctx context.Context, log *slog.Logger) (PortMappingReport, error)

ProbePortMapping discovers UPnP, NAT-PMP, and PCP without creating a mapping. With no default gateway it returns NoGateway and sends nothing. It returns an error if the probe cannot run or ctx ends. A nil log discards diagnostics.

type Signaling

type Signaling struct {
	RegionID int
	Dial     func(ctx context.Context, url string) (net.Conn, error)
}

Signaling supplies the only connection path to the engine's home region. Dial receives an empty URL until a listed region supplies one.

type Support

type Support uint8

Support describes whether a socket facility is available.

const (
	// SupportUnknown means the probe could not determine support.
	SupportUnknown Support = iota
	// Supported means the socket facility is available.
	Supported
	// Unsupported means the socket facility is unavailable.
	Unsupported
)

type Tri

type Tri uint8

Tri is a result that distinguishes an unmeasured value from yes and no.

const (
	// TriUnknown means the probe could not determine a value.
	TriUnknown Tri = iota
	// TriYes means the observed value is true.
	TriYes
	// TriNo means the observed value is false.
	TriNo
)

Directories

Path Synopsis
cmd
n4peer command
Command n4peer runs a server or a timed client over a static peer graph.
Command n4peer runs a server or a timed client over a static peer graph.
Package coordclient keeps an engine's registration and peer set current against a coordination service.
Package coordclient keeps an engine's registration and peer set current against a coordination service.
Package n4 serves HTTP/3 over an engine's admitted peer graph.
Package n4 serves HTTP/3 over an engine's admitted peer graph.

Jump to

Keyboard shortcuts

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