warp

package
v0.1.22 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: AGPL-3.0 Imports: 31 Imported by: 0 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 warp is the node's WARP egress.

One Cloudflare WARP account per node, run as a plain WireGuard tunnel (device "mgwarp"). Two kinds of traffic leave through it:

  • Hysteria2 inbounds with egress "warp": their dialers are bound to the device (egress.WithDevice), an "oif" rule sends that to the WARP routing table.
  • AWG inbounds with egress "warp": "ip rule from <client subnet>" sends the forwarded traffic into the same table, and the node masquerades it to the WARP address (WARP accepts only its own address as source).

Fail closed. The WARP table always ends in "unreachable default", so a dead or missing tunnel makes the selected traffic fail with "no route to host" instead of leaving the node directly; the rules for the client subnets stay while the tunnel is paused or gone. Only Cleanup removes everything.

The package has three layers: the Manager (state machine, health, the recovery ladder; portable, unit-tested with fakes), the dataplane (Linux: netlink, wgctrl or amneziawg-go on a TUN, nft; other OSes: a stub that reports UNAVAILABLE) and cfapi (the Cloudflare registration client, used by the panel, not by the agent).

Index

Constants

View Source
const (
	// DefaultIface is the tunnel device. It has no fwmark (an encapsulated packet must not enter the WARP table).
	DefaultIface = "mgwarp"
	// DefaultTable is the routing table of the WARP path; the two preferences are the "oif" rule and the
	// "from <client subnet>" rules. Preflight reports a clash with another tool on the host.
	DefaultTable      = 51820
	DefaultOifPref    = 90
	DefaultSubnetPref = 110
	// NftTable is the WARP nft table (masquerade, MSS clamp, optional "reserved" stamping). The doctor treats it as ours.
	NftTable = "mistgate_warp"
)
View Source
const (
	DefaultProbeA = "http://connectivity.cloudflareclient.com/cdn-cgi/trace"
	DefaultProbeB = "http://connectivitycheck.gstatic.com/generate_204"
)

Default probe targets: A is Cloudflare's own trace (tells warp=on|plus|off and the colo), B must not be Cloudflare (a handshake can work while everything else is black-holed, wgcf issue 619).

Variables

View Source
var ErrNotActive = errors.New("warp: egress not active")

ErrNotActive is what the WARP egress returns while the node has no WARP, it is paused or unavailable: there is no silent direct exit.

View Source
var ErrUnavailable = errors.New("warp: no usable WireGuard backend (kernel module or /dev/net/tun)")

ErrUnavailable means no WireGuard backend can run on this host.

Functions

func CleanupHost

func CleanupHost(ctx context.Context, s Settings) error

CleanupHost removes everything a run of the manager leaves on the host, by name, preference and table number only (no state needed), so the unit's ExecStopPost can call it after a crash: an orphaned "unreachable default" would black-hole every socket that still selects the table. It removes only what is ours: the rules with our two preferences that look up the WARP table, the routes of the table that go through the device, the fail-closed "unreachable default metric 4096" and the "throw" routes of our client subnets, the device and the nft table; one failure does not stop the rest. The table number is a setting because it is wg-quick's default (51820) too: another tool's rules and routes in the same table are left alone.

Types

type Event

type Event struct {
	Code   string
	Warn   bool
	Params map[string]string
}

Event is what the manager tells the agent (which turns it into an agent.v1.Event). Codes: "warp_state" {state, from}, "warp_needs_attention" {reason}.

type Finding

type Finding struct {
	// "table_in_use" | "rule_pref_in_use" | "forward_drop" | "interface_in_use"
	ID     string
	Detail string
}

Finding is one preflight result (the doctor shows it); a clash the owner has to resolve.

type Health

type Health struct {
	State State
	// "kernel" | "userspace" | "".
	Backend string
	// ip:port in use right now (after a rotation).
	Endpoint      string
	LastHandshake time.Time
	// Probe A: "on" | "plus" | "off" | "" (failed).
	WarpFlag          string
	Colo              string
	ProbeCloudflareOK bool
	ProbeOtherOK      bool
	// Consecutive failed checks.
	Failures uint32
	RxBytes  uint64
	TxBytes  uint64
	// Short English fact for the LATEST check ("" when it passed), e.g. "probe_other_failed", "handshake_never", then
	// "; ladder: <note>" with the last recovery action. The codes are listed in web/src/lib/warp-error.ts.
	LastError string
	// The latest round of each probe; nil when the round did not run it (link down, no stats).
	ProbeCloudflare, ProbeOther *ProbeResult
	// When the latest health check finished (zero before the first one).
	CheckedAt time.Time
}

Health mirrors agent.v1.WarpHealth; the agent converts it.

type Manager

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

Manager owns the WARP tunnel of the node. The agent calls Apply with every DesiredState (nil = no WARP), SetRoutedSubnets with the client subnets of AWG inbounds whose egress is "warp", hands Egress() to the engines, runs Run in a goroutine and calls Cleanup on the way out. Safe for concurrent use.

func New

func New(o Options) (*Manager, error)

New builds the manager for this OS.

func (*Manager) Apply

func (m *Manager) Apply(ctx context.Context, spec *plugin.WarpSpec) error

Apply makes the node match spec: nil removes WARP (the tunnel goes, the client-subnet rules stay closed while subnets are still routed), Enabled=false pauses it. A spec equal to the applied one only re-asserts routing and repairs a vanished device; the WireGuard peer is never touched without a difference.

func (*Manager) CheckNow added in v0.1.1

func (m *Manager) CheckNow(ctx context.Context) (checked, thresholdDown bool, err error)

CheckNow reruns one bounded health check only when the configured tunnel is up/starting and its latest check failed. thresholdDown reports whether the manager is Down at the failure threshold, including when a scheduled check reached the threshold just before this call. It serializes with the periodic check and never resets a tunnel.

func (*Manager) Cleanup

func (m *Manager) Cleanup(ctx context.Context) error

Cleanup removes everything the manager installed: rules, routes of the table, the device, the nft table. Called by the agent on shutdown (and by the stateless CleanupHost from the unit's ExecStopPost).

func (*Manager) Configured

func (m *Manager) Configured() bool

Configured reports whether the node has a WARP configuration (paused included). The agent refuses to start an inbound with egress "warp" while it is false.

func (*Manager) Egress

func (m *Manager) Egress() engine.Egress

Egress is the engine.Egress for inbounds with egress "warp". Every dial goes through the tunnel device; while the node has no WARP, it is paused or unavailable, every dial fails with ErrNotActive, and a dead tunnel fails in the kernel ("no route to host"): never a silent direct exit.

func (*Manager) Health

func (m *Manager) Health() (Health, bool)

Health returns the last measured state; ok=false when the node has no WARP (nothing to report).

func (*Manager) Preflight

func (m *Manager) Preflight(ctx context.Context) []Finding

Preflight reports clashes with the host (table, rule preferences, device name, a FORWARD drop policy).

func (*Manager) Reconnect

func (m *Manager) Reconnect(ctx context.Context) (bool, error)

Reconnect rebuilds the current tunnel only while it is down. It leaves the configured account and routed subnets intact; the routes remain fail-closed while the tunnel comes back. A fresh doctor result may make this a no-op.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context)

Run drives the handshake watch and the health checks until ctx ends. It does not clean up; the agent calls Cleanup.

func (*Manager) SetRoutedSubnets

func (m *Manager) SetRoutedSubnets(ctx context.Context, subnets []netip.Prefix) error

SetRoutedSubnets sets the client subnets whose forwarded traffic must leave through WARP (AWG inbounds with egress "warp"). The rules stay while the tunnel is down or paused: those clients fail closed.

type Options

type Options struct {
	Log      *slog.Logger
	Settings Settings
	// DNS is the node's resolver list (engine.Env.DNS); the WARP egress resolves names like the direct one.
	DNS func() []string
	// Emit receives state-change events; nil drops them.
	Emit func(Event)
	Now  func() time.Time
	// Interval between health checks (30 s); FastInterval while the tunnel is still starting (5 s).
	Interval, FastInterval time.Duration
	// HandshakeWait is how long a fresh tunnel may go without a handshake before the next endpoint is tried (15 s).
	HandshakeWait time.Duration
	// ProbeAURL and ProbeBURL override the probe targets (tests); see DefaultProbeA and DefaultProbeB.
	ProbeAURL, ProbeBURL string
	// ProbeTimeout bounds one probe, dial included (20 s by default).
	ProbeTimeout time.Duration
	// AllowPrivate lets the tunnel egress dial private and documentation-range addresses (tests, dev).
	AllowPrivate bool
}

Options configures a Manager. Everything has a default.

type ProbeResult

type ProbeResult struct {
	OK          bool
	Latency     time.Duration
	At          time.Time
	FailureCode string
}

ProbeResult is one probe of a health check: ok, how long it took (a timeout shows the timeout) and when it ended.

type Settings

type Settings struct {
	Iface      string
	Table      int
	OifPref    int
	SubnetPref int
	NftTable   string
}

Settings are the host-level knobs. The zero value means the defaults. The table and the preferences can clash with other tools (Tailscale, wg-quick), which is why they are settings; Preflight detects a clash.

func (Settings) Validate

func (s Settings) Validate() error

Validate checks a Settings value after defaults.

type State

type State int

State is the WARP path state (agent.v1.WarpState without the UNSPECIFIED value).

const (
	// StateNone: the node has no WarpSpec.
	StateNone State = iota
	// StateUnavailable: no usable backend on this host (no kernel WireGuard and no /dev/net/tun).
	StateUnavailable
	StateStarting
	StateUp
	StateDown
	// StateDisabled: the spec is present but enabled = false (paused).
	StateDisabled
)

func (State) String

func (s State) String() string

Directories

Path Synopsis
Package cfapi is the Cloudflare WARP registration client and the importer for wgcf profiles.
Package cfapi is the Cloudflare WARP registration client and the importer for wgcf profiles.

Jump to

Keyboard shortcuts

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