coord

package
v0.0.0-...-9e84d59 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 39 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 coord is holepunch's server-side coordinator: it takes over the control links of two clients that the caller has already authenticated, runs their NAT probing against natprobe, plans every round of the punch, aligns the two clients' start instants by their control-link round-trip times, relays what each client sees of the other while punching, and lets the session go as soon as the clients confirm a UDP path.

Usage

A deployment shares one natprobe.Registry between its natprobe.Server and its Coordinator, then pairs two authenticated client connections in a session:

co, err := coord.New(coord.Config{Registry: reg, DefaultProbe: probe.ProbeSpec()})
...
sess, err := co.NewSession(coord.SessionOptions{})
err = sess.Attach(protocol.RoleInitiator, connA, coord.AttachOptions{})
err = sess.Attach(protocol.RoleResponder, connB, coord.AttachOptions{})
res, err := sess.Wait(ctx) // or Config.OnResult for every session

A long-running server reads the probe spec afresh for every session instead — Config.Probe: ProbeFrom(natprobe.SpecSource{...}), with STUN servers and server addresses that natprobe keeps up to date — and gives a client's own addresses in AttachOptions.Probe.

Once Attach returns nil the connection belongs to the session, which closes it when the session ends. A failed session's Result.Retry says whether to try again and in which mode; a client that should keep relaying and punch in the background gets SessionOptions.Mode protocol.ModeBackground.

Model

A Coordinator creates sessions; a Session needs no connection to exist. NewSession pre-generates both punch_start messages, registers the probe route with the natprobe Registry and reserves the callers' quotas. Attach hands the session one client's control stream, in either order (the initiator typically probes before the responder has joined). From then on the session drives itself through created → binding → probing → summarized → punching(k) → confirming → closed, each state with its own deadline, and ends exactly once in finish, the single cleanup path shared by success, failure, abort, panic and shutdown. The Result is delivered to Config.OnResult exactly once, after every resource of the session is gone.

The planning decisions are made by a plan.Planner (DefaultPlanner unless Config.Planner supplies one); the coordinator does not trust it: every decision is clamped to the per-round budget classes, the session and per-key budgets and the protocol limits, its targets pass admission (addresses natprobe verified with a return-path cookie; private addresses of a peer on the same LAN or behind the same upstream NAT; in an unverified family — NoObserver mode, or a family no observer covers — Direct stages to a few self-reported global addresses), and escalation is guarded (a round rises at most one budget class). The admission sets are the ones the clients build from their summaries, and the planner sees the views exactly as the clients receive them. Clamping keeps a grant within its limits but does not keep the planner's equality "MaxPackets = what the stages expand to". The peer_targets the coordinator pushes — with each go (upstream-LAN candidates every round, port mappings, drifted mappings) or within a round (sandwich windows, Inject) — are cut to what the side may still be charged and charged when sent, two packets a target, since the clients send them on a quota of their own; the audit pays a side's packets beyond its grant from that charge. The natprobe registration outlives the summary until the first confirmation: natprobe keeps observing the primary sockets, and a mapping that moved while punching is pushed to the peer as drift — on a new IP only once its client echoed the mapping's cookie in a round_result remap, the return-path check of the summary's endpoints. A round in which both clients refused every target and sent nothing ends the session (no_admissible_target). After every round the coordinator counts, per side and family, the new NAT mappings the side made — its grant's new (socket, destination) pairs cut to what its round_result reports, the peer_targets it was pushed, its sandwich, re-observation and anchor-refresh probes — into RoundOutcome.Families[].Mapped, by which the planner places the next seq_x_seq windows. Before the go of a round that aims at a SEQ side's next ports — every paired SEQ × SEQ round, others on noise evidence, never one natprobe found hopeless — the coordinator asks the side for an anchor refresh, two new mappings 60 ms apart that natprobe hands over, and plans the round again from them; it waits for a side's second probe at most refreshGap and one and a half UDP round trips after its first and plans with what came; round 1 asks with its summaries and its go carries the summary's plan re-aimed, predict anchors and spans only. Rounds share one handshake deadline, failures never escalate (the slow birthday's background class of a Background session — offered by SessionOptions.Mode, accepted by both clients — escapes the guard: wide in time, not in rate), and the strategy memory only promotes variants that succeeded before; a pair it saw connect only through the slow birthday is reported as background_only in the summaries and the Result.

Custom planners and memories

Package plan holds the planner contract. A custom planner usually wraps DefaultPlanner, whose Round derives everything it needs from its input, and changes only what it means to:

type relayFirst struct{ plan.Planner }

// Classify sends the pairs classified rnd_x_rnd straight to the relay.
func (p relayFirst) Classify(in plan.ClassifyInput) plan.Classification {
	cl := p.Planner.Classify(in)
	if cl.PairClass == "rnd_x_rnd" {
		cl.Reject = protocol.ReasonHardSymmetricRandom
	}
	return cl
}

co, err := coord.New(coord.Config{Planner: relayFirst{coord.DefaultPlanner()}, ...})

A StrategyMemory of the caller's own gets the built-in memory's place in planning through its interface alone: Recommend orders the primary ladder, and Score says which variants proved themselves for the pair — which decides the memory hit, the promotion of a proven variant and background_only.

Concurrency

Each attached control stream is framed by one reading and one writing goroutine. Accepted frames go into a small bounded channel per link. One session goroutine consumes both links' channels and their Done signals in a single select: every frame, every link failure and every planning step of a session runs on it, so the state machine sees one ordered stream of events. A session therefore has at most five goroutines (two per link plus the session goroutine) and none before its first Attach; an idle session blocks in reads and selects and is never woken.

The session state is guarded by one mutex. Timers do not run user code: a session owns a single Clock timer, re-armed under the mutex to the nearest of its stage deadline, its next ping and pending sandwich events; the timer callback only changes state or wakes the session goroutine. User code — the Planner, StrategyMemory, natprobe.TraitsMemory, the natprobe merge, the Observer, OnResult, and the methods of the errors the caller's connections fail with — always runs outside the mutex, inside a recover boundary, and the result of an out-of-lock call is discarded when the session's generation changed meanwhile. A Planner that never returns keeps only the session goroutine; the stage deadline still ends the session and frees everything else, and Done waits for that goroutine. The Clock is not user code but infrastructure, injected for tests and simulation: it is called directly, under the mutex too, and must not panic.

Frames are queued in decision order under the mutex: punch_start precedes ping#1, a summary precedes the first go, the two go frames of a round are queued in one critical section, and an abort is the last frame of a link.

Ownership

A control connection belongs to the session once Attach returns nil and to the caller otherwise; the session closes it in finish. Attach returns an error only while it has not touched the stream; once the stream is wrapped it is the session's, and a failure from then on ends the session with internal. The natprobe registration, the quota reservations, the index entry, the timer, the session context and the parent-context registration are owned by the session and released by finish. finish closes the session before it works anything out, and runs every release step, and every link's close, in a recover boundary of its own, after the step's fault point rather than behind it: no failure, of another step or of its own point, keeps a resource. A session holds a reference for finish, for its goroutine, for each Attach in progress and for each timer call; each is dropped on every path, a panic included, and Done is closed by the last one, when finish has completed and every goroutine of the session has returned.

Every entry point is a recover boundary: a panic in New, NewSession, Attach or Close becomes an error (Close's once the shutdown is complete), one in Abort or in a timer or context callback ends the session with internal, and none reaches a caller or a goroutine without one. A session that fails after it went live during NewSession is ended before NewSession returns the error.

The Coordinator owns the housekeeping goroutine (quota table, strategy memory sweeping every 10 s) and, when an Observer is set, one event dispatcher with a bounded queue. Close ends every session with server_shutdown and joins them within 3 s; its steps have a recover boundary each, so a panic in one is counted and skips none of the others, and Close returns it as a *holepunch.PanicError. Every channel that signals an end — Close's, a session's quit, a link's quit — is closed in a defer, or before anything that could fail, on the path that ends.

Memory bounds

Everything the coordinator keeps that grows with its input has a cap that cannot be removed: the session index (Limits.MaxSessions), the per-key quota table (Limits.MaxKeys, fixed-size entries; a new key in a full table evicts the entry idle the longest, and with every entry in use NewSession fails with ErrBusy), the event queue (Limits.ObserverQueue), the strategy memory (StrategyMemoryConfig.MaxEntries) and natprobe's own tables. Within a session every list is bounded by a constant or by the round count (at most 8): views (12 endpoints a family), admission sets, evidence, punch-time mappings (16 a side), queued peer_targets (4 port-mapping and 4 drift assists a side), upstream-LAN candidates (4 a side and family), drifted mappings, remap echoes (one a side and family), the Direct targets each side has sent (the targets of at most 8 rounds), sandwich events (8), warnings (8) and the timeline.

coord depends on protocol, natprobe, clock and internal packages; it never links the client root package or the port mapper.

Example

Example is a minimal server on real sockets: natprobe observes the clients' NATs on the server's public IP, and a TLS listener pairs the clients two by two, the first of a pair as the initiator. Each client dials the listener and calls holepunch.Punch on its connection.

A real server authenticates the clients and pairs them by its own matchmaking, usually with a few application messages on the same stream before the session (the standalone module does exactly that). It is only compiled: it needs a public IP.

package main

import (
	"context"
	"crypto/tls"
	"errors"
	"log"
	"net"
	"net/netip"
	"time"

	"github.com/djylb/holepunch/coord"
	"github.com/djylb/holepunch/natprobe"
	"github.com/djylb/holepunch/protocol"
	"github.com/djylb/holepunch/stun"
)

func main() {
	public := netip.MustParseAddr("203.0.113.10") // an address of this host

	reg := natprobe.NewRegistry(natprobe.RegistryConfig{})
	probe, err := natprobe.NewServer(natprobe.ServerConfig{
		Registry: reg,
		Groups:   []natprobe.ObserverGroup{{Bind: public}},
		BasePort: 3478, // UDP 3478-3480
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := probe.Start(); err != nil {
		log.Fatal(err)
	}
	defer func() { _ = probe.Close() }()

	// Public STUN servers give the clients a second view of their mapping,
	// and a public address to a client on this server's own LAN.
	spec := probe.ProbeSpec()
	spec.STUN, err = natprobe.ResolveSTUN(context.Background(), nil, stun.DefaultServers())
	if err != nil {
		log.Print(err) // the servers that resolved are kept
	}
	co, err := coord.New(coord.Config{
		Registry:     reg,
		DefaultProbe: spec,
		OnResult: func(r coord.Result) {
			log.Printf("session %s %s %s", r.SessionID, r.Outcome, r.Reason)
		},
	})
	if err != nil {
		log.Print(err)
		return
	}
	defer func() { _ = co.Close() }()

	cert, err := tls.LoadX509KeyPair("server.pem", "server.key")
	if err != nil {
		log.Print(err)
		return
	}
	l, err := tls.Listen("tcp", ":4343", &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}})
	if err != nil {
		log.Print(err)
		return
	}
	defer func() { _ = l.Close() }()

	// handshake completes the TLS handshake: by default the coordinator
	// accepts only completed TLS connections.
	handshake := func(c net.Conn) error {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		return c.(*tls.Conn).HandshakeContext(ctx)
	}
	var waiting net.Conn // a client waiting for its peer
	for {
		c, err := l.Accept()
		if errors.Is(err, net.ErrClosed) {
			return
		}
		if err != nil {
			log.Print(err)
			continue
		}
		if err := handshake(c); err != nil {
			log.Print(err)
			_ = c.Close()
			continue
		}
		if waiting == nil {
			waiting = c
			continue
		}
		pair := [2]net.Conn{waiting, c}
		waiting = nil
		sess, err := co.NewSession(coord.SessionOptions{})
		if err != nil { // coord.ErrBusy, for one
			log.Print(err)
			_, _ = pair[0].Close(), pair[1].Close()
			continue
		}
		// Once Attach returns nil the connection is the session's, which
		// closes it when the session ends; after an error it is still ours.
		for i, role := range []protocol.Role{protocol.RoleInitiator, protocol.RoleResponder} {
			if err := sess.Attach(role, pair[i], coord.AttachOptions{}); err != nil {
				log.Print(err)
				_ = pair[i].Close()
				sess.Abort(protocol.ReasonCanceled, "attach_failed")
			}
		}
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is returned once the Coordinator was closed.
	ErrClosed = errors.New("coord: coordinator closed")
	// ErrBusy is returned when a session, rate or quota limit refused a new
	// session. It is a *ReasonError with Reason server_busy, shared by every
	// such return: read it, never modify it.
	ErrBusy error = &ReasonError{Reason: protocol.ReasonServerBusy}
	// ErrAlreadyAttached is returned when the role already has a control link.
	ErrAlreadyAttached = errors.New("coord: role already attached")
	// ErrSessionDone is returned when the session has ended; it no longer
	// takes links.
	ErrSessionDone = errors.New("coord: session done")
	// ErrInvalidRole is returned when the role is neither initiator nor
	// responder.
	ErrInvalidRole = errors.New("coord: invalid role")
	// ErrInvalidConn is returned when the connection is nil, a typed nil, or
	// does not support deadlines.
	ErrInvalidConn = errors.New("coord: invalid control connection")
	// ErrShutdownTimeout is returned when Close gave up waiting for sessions or
	// goroutines stuck in user code after 3 s; they are counted in
	// Stats.Stuck.
	ErrShutdownTimeout = errors.New("coord: shutdown timeout")
)

Errors returned by the Coordinator and Session methods. A failed Attach leaves the connection with the caller.

Functions

func DefaultPlanner

func DefaultPlanner() plan.Planner

DefaultPlanner returns the built-in planner, the one a nil Config.Planner selects. A custom planner may wrap it and adjust its classifications and decisions: the built-in Round derives everything it needs from its plan.RoundInput, so it plans whatever Classification it is handed — the families of Classification.Families it shares, in that order, the primary one on Classification.Ladder (or RoundInput.Order).

Example

ExampleDefaultPlanner wraps the built-in planner in a custom one. The coordinator clamps whatever a planner decides, so a wrapper only has to be right about what it changes.

package main

import (
	"log"

	"github.com/djylb/holepunch/coord"
	"github.com/djylb/holepunch/natprobe"
	"github.com/djylb/holepunch/plan"
	"github.com/djylb/holepunch/protocol"
)

// relayFirst is the built-in planner, except that it sends pairs it
// classifies rnd_x_rnd straight to the relay and punches at most three
// rounds.
type relayFirst struct{ plan.Planner }

func (p relayFirst) Classify(in plan.ClassifyInput) plan.Classification {
	cl := p.Planner.Classify(in)
	if cl.PairClass == "rnd_x_rnd" {
		cl.Reject = protocol.ReasonHardSymmetricRandom
	}
	return cl
}

func (p relayFirst) Round(in plan.RoundInput) plan.RoundDecision {
	in.MaxRounds = min(in.MaxRounds, 3)
	return p.Planner.Round(in)
}

// ExampleDefaultPlanner wraps the built-in planner in a custom one. The
// coordinator clamps whatever a planner decides, so a wrapper only has to
// be right about what it changes.
func main() {
	reg := natprobe.NewRegistry(natprobe.RegistryConfig{})
	var spec protocol.ProbeSpec // the natprobe server's ProbeSpec, as in Example
	co, err := coord.New(coord.Config{
		Registry:     reg,
		DefaultProbe: spec,
		Planner:      relayFirst{coord.DefaultPlanner()},
	})
	if err != nil {
		log.Print(err)
		return
	}
	_ = co.Close()
}

Types

type AttachOptions

type AttachOptions struct {
	// Probe, when set, replaces this role's ProbeSpec — the one
	// SessionOptions or Config.Probe gave NewSession — in the punch_start
	// written on this stream: the observers' addresses the client is known
	// to reach only now, such as the server address it reports when it
	// joins (natprobe.Server.ProbeSpecAt builds one). Session.PunchStart
	// reports it once Attach has returned.
	Probe *protocol.ProbeSpec
	// Security vouches for the control stream: the default,
	// protocol.ControlSecurityAuto, accepts a TLS connection and completes
	// its handshake if it has not run yet; Declared trusts the caller's
	// outer encryption; InsecureForTesting accepts anything and warns
	// insecure_control_for_testing.
	Security protocol.ControlSecurity
}

AttachOptions configures one Attach.

type AttachedData

type AttachedData struct {
	ClientKey string
}

AttachedData is the data of EvAttached.

type BudgetConfig

type BudgetConfig struct {
	// AllowExtreme permits the extreme budget class (from round 3, at most
	// ExtremePerHour times per client key) and the balanced and aggressive
	// birthday tiers.
	AllowExtreme bool
}

BudgetConfig holds the operator's budget switches.

type ClientFinal

type ClientFinal struct {
	Reason     protocol.Reason
	Phase      protocol.Phase
	Detail     string
	Path       *protocol.PathInfo
	ExtraPaths []protocol.PathInfo // punch_result.extra_paths: the other paths handed over with Path
	Stats      protocol.Stats
	OK         bool
	Timing     protocol.Timing
	Traits     []protocol.TraitsUpdate
	Warn       []protocol.Warning
}

ClientFinal is a client's punch_result.

type Config

type Config struct {
	// Registry is the natprobe registry the sessions register their probe
	// routes with, shared with the natprobe.Server that observes the
	// clients. It is required unless NoObserver is set.
	Registry *natprobe.Registry
	// NoObserver runs the coordinator without natprobe, with a nil
	// Registry: nothing is verified, so the plans may only aim Direct
	// stages at the peer's self-reported public endpoints (at most 16, 8
	// packets each per round), the summary marks every family in
	// pair.unverified and the Result warns unverified_targets. It needs
	// Targets TargetsBounded.
	NoObserver bool
	// Targets says whether the clients may aim at addresses the server
	// could not verify; see TargetPolicy.
	Targets TargetPolicy
	// Timeouts are the protocol timeouts of the sessions (zero fields:
	// protocol.DefaultTimeouts); summary_wait_ms is computed per link.
	Timeouts protocol.Timeouts
	// Probe builds each role's ProbeSpec; nil uses DefaultProbe.
	Probe ProbeFunc
	// DefaultProbe is the ProbeSpec used when Probe is nil and the session
	// options give none: normally natprobe.Server.ProbeSpec of the server
	// whose Registry this is. Its zero V is ProbeSpecVersion.
	DefaultProbe protocol.ProbeSpec
	// Policy is the default session policy; its budget is clamped to the
	// operator ceiling (protocol.SessionBudgetLimit).
	Policy *protocol.Policy
	// TransportFallback is the transport mode used when the clients' modes
	// conflict ("" → transport_mismatch; "kcp", for example).
	TransportFallback string
	// TTL holds the server's stage deadlines.
	TTL TTLConfig
	// Limits are the admission, rate and frame limits.
	Limits Limits
	// Planner plans the rounds; nil uses DefaultPlanner(). The coordinator
	// does not trust it: it calls it outside every lock and inside a
	// recover boundary, clamps every decision to the budget classes, the
	// session and per-key budgets and the protocol limits, admits only
	// targets the clients admit, guards the escalation (one class a round,
	// the first round's cap) and ends a session whose planner names an
	// unknown reason with internal. A Planner that panics is replaced by
	// the built-in one for the rest of the session.
	Planner plan.Planner
	// Memory is the cross-session strategy memory; nil uses
	// NewStrategyMemory(StrategyMemoryConfig{}) and NoMemory{} turns it off.
	Memory StrategyMemory
	// StrategySalt is the StrategyKey salt (DeriveStrategyKey) for a Memory
	// that is not the built-in one, which keeps its own
	// StrategyMemoryConfig.Salt; nil draws a random salt per Coordinator.
	// Coordinators that share one such memory must share the salt.
	StrategySalt []byte
	// TraitsMemory is the cross-session NAT traits memory consulted by the
	// merge and fed at the end of a session; nil uses
	// natprobe.NewTraitsMemory with its defaults and NoMemory{} turns it off.
	TraitsMemory natprobe.TraitsMemory
	// Observer receives the session events, asynchronously and in order per
	// session, from one dispatcher goroutine with a bounded queue: events
	// that do not fit are dropped and counted. nil starts no dispatcher.
	// Coordinator.Close joins the dispatcher, so Observer must not call Close.
	//
	//holepunch:callback
	Observer func(Event)
	// Budget holds the extreme switch.
	Budget BudgetConfig
	// NoWarm turns warm starts off. By default a client the TraitsMemory
	// knows starts warm: a session with its ClientKey asks it
	// (ProbeSpec.Warm) for an early probe_report once
	// one probe of each family is answered, and when the memory remembers an
	// endpoint-independent mapping (EIM) of that client at the public IP just
	// observed — and the observation does not contradict it — the session
	// is planned on that report instead of waiting for probing to end
	// (natprobe Merge, MergeOptions.Warm). Otherwise it waits for the final
	// report as before, which costs nothing; and when the final report of a
	// warm side contradicts the memory, it replaces the planning input from
	// the next round on. It needs a Registry, a TraitsMemory and the
	// sessions' ClientKeys. Result.Warm tells how each side started.
	NoWarm bool
	// ObserveProgress also turns every accepted punch_progress into an event.
	ObserveProgress bool
	// OnResult receives every session's Result exactly once, after all of the
	// session's resources were released, outside every lock and inside a
	// recover boundary. Coordinator.Close waits for the calls in progress, so
	// OnResult must not call Close: Close would wait for it until its bound.
	//
	//holepunch:callback
	OnResult func(Result)
	// Clock is the time source; nil uses the system clock. A Clock is
	// infrastructure for tests and simulation, not a callback: it is called
	// directly, with the session mutex held too, and must not panic.
	Clock timeshim.Clock
	// Rand is the randomness for session ids, tokens, routes, wire lengths
	// and round seeds; nil uses crypto/rand.
	Rand io.Reader
}

Config configures a Coordinator. Zero fields take the defaults.

type Coordinator

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

Coordinator creates and supervises sessions. Its methods are safe for concurrent use.

func New

func New(cfg Config) (c *Coordinator, err error)

New validates cfg and starts a Coordinator: its housekeeping goroutine and, with an Observer, its event dispatcher.

func (*Coordinator) Close

func (c *Coordinator) Close() error

Close ends every session with server_shutdown — sessions still before the punch get punch_abort{server_shutdown}, punching and confirming sessions only have their links closed — delivers their Results (OnResult has returned for each, and their EvClosed events are queued before the event dispatcher stops) and stops the coordinator's goroutines. It waits at most 3.25 s: 3 s for the sessions, and at least 250 ms to join its own goroutines. It is idempotent and safe for concurrent use: every caller waits for the first call's shutdown and gets its result. NewSession and Attach return ErrClosed afterwards.

Close returns nil, or what went wrong, in the order of the shutdown's steps: a panic as a *holepunch.PanicError, and ErrShutdownTimeout when sessions or goroutines stuck in user code were left behind (counted in Stats.Stuck). A single failure is returned as it is, several are joined (errors.Join). A panic never reaches the caller and skips no later step: it is also counted in Stats.Panics and reported as an EvInternalError event, and the shutdown still ends every session and joins the coordinator's goroutines before Close returns it.

func (*Coordinator) Len

func (c *Coordinator) Len() int

Len returns the number of live sessions.

func (*Coordinator) Lookup

func (c *Coordinator) Lookup(sessionID string) (*Session, bool)

Lookup returns the live session with the given id.

func (*Coordinator) Memory

func (c *Coordinator) Memory() StrategyMemory

Memory returns the strategy memory, for callers that report outcomes of their own: an upper-layer transport that failed on a confirmed path is Report(key, Result.Winner.Variant, MemFailure), key being Result.StrategyKey decoded from hex. The key has no transport dimension (StrategyMemory).

func (*Coordinator) NewSession

func (c *Coordinator) NewSession(opts SessionOptions) (s *Session, err error)

NewSession creates a session; it needs no connection yet. It pre-generates both punch_start messages, registers the probe route with the Registry, reserves both client keys' quotas and arms the bind deadline.

Errors: ErrClosed; ErrBusy (session count, pending count, creation rate or a key's limit); natprobe.ErrRouteInUse, ErrConflict or ErrRegistryFull from the Registry; a *protocol.ValidationError with Reason invalid_argument for invalid options.

func (*Coordinator) Stats

func (c *Coordinator) Stats() Stats

Stats returns a snapshot of the coordinator's counters.

type Counters

type Counters struct {
	FramesIn        [2]uint64 // frames read per link, discarded ones included
	FramesOut       [2]uint64 // frames written per link
	UnknownFrames   uint64    // reserved or wrong-direction frames read and dropped
	AssistForwarded uint64
	AssistDropped   uint64 // over a rate or quota, or the peer link busy
	AssistRejected  uint64 // not peer_seen, server-only fields set, bad round or address
	ProgressDropped uint64
	TargetRejected  uint64 // targets refused by admission
	BudgetViolation uint64 // rounds a side sent more than granted × 1.1
	PlanClamped     uint64 // plan fields the coordinator changed
	PeerTargets     uint64 // peer_targets sent
	PingsSent       uint64
	STUNConflicts   uint64 // STUN values that contradicted natprobe's records; only counted
	Refreshes       uint64 // anchor refreshes asked of a side and family before a round
}

Counters are a session's frame and relay counters.

type Event

type Event struct {
	Kind      EventKind
	At        time.Time
	SessionID string
	Role      protocol.Role
	Round     int
	Reason    protocol.Reason
	Detail    string
	Labels    map[string]string // independent snapshot
	Result    *Result           // EvClosed only
	Data      any               // the Kind's data type
}

Event is an observation of a session. Events of one session are delivered in order; the queue drops events it cannot hold, so an Observer must not rely on seeing every one (the reliable end is Config.OnResult).

type EventKind

type EventKind uint8

EventKind is the kind of an Event.

const (
	EvCreated        EventKind = iota + 1
	EvAttached                 // Role; Data: AttachedData
	EvReported                 // Role
	EvPlanned                  // Data: PlannedData
	EvGo                       // Round; Data: GoData
	EvRoundEnded               // Round; Data: RoundEndedData
	EvConfirmed                // Role, Round; Data: protocol.PathInfo
	EvPeerTargets              // Role (receiver), Round; Data: PeerTargetsData
	EvProgress                 // Role; Data: ProgressData (only with Config.ObserveProgress)
	EvRateLimited              // Data: RateLimitedData
	EvPlanClamped              // Round; Data: PlanClampedData
	EvTargetRejected           // Round; Data: TargetRejectedData
	EvInternalError            // Detail: location; Data: PanicInfo
	EvClosed                   // Result
)

Event kinds.

func (EventKind) String

func (k EventKind) String() string

String returns the event name.

type GoData

type GoData struct {
	Delay   [2]time.Duration
	RTT     [2]time.Duration
	Variant string
	Budget  protocol.BudgetClass
	Granted [2]int
	Rescue  bool
	// Eager reports a round 1 started right after the summaries, without
	// waiting for the readies (nothing to prepare on either side).
	Eager bool
	// Sandwich are, by role, the families whose sandwich probe runs this
	// round.
	Sandwich [2][]protocol.Family
}

GoData is the data of EvGo.

type Limits

type Limits struct {
	// DestinationPacketsPerMinute bounds initiated packet grants to one IP
	// across sessions, with a full minute of burst. Each possible destination
	// of a family plan is charged its entire grant. Zero defaults to 120000,
	// a negative value removes the limit.
	DestinationPacketsPerMinute int
	MaxSessions                 int    // concurrent sessions, the bound of the session index: 4096
	MaxPending                  int    // sessions in created or binding: 2048
	NewSessions                 Rate   // NewSession rate: {200, 400}
	InitiatorKeyRate            Rate   // NewSession rate per initiator key: {2, 6}
	MaxPerInitiatorKey          int    // concurrent sessions per initiator key: 8
	MaxPerResponderKey          int    // concurrent sessions per responder key: 32
	PacketsPerMinute            [2]int // packets granted per key per minute, [initiator, responder]: 30000, 120000
	ExtremePerHour              int    // extreme rounds per client key per hour: 2
	FramesPerLink               int    // frames received per link: 512
	FrameRate                   Rate   // client-to-server frames per link: {50, 100}
	ProgressPerLink             int    // punch_progress accepted per link: 64
	AssistIn                    Rate   // peer_seen received per link: {20, 40}
	AssistPerRound              int    // peer_seen per link, round and family: 8
	AssistRelay                 Rate   // peer_seen forwarded per direction: {30, 60}
	TargetsPerRound             int    // peer_targets per receiving link and round: 4
	ObserverQueue               int    // queued events: 4096
	// MaxKeys bounds the per-key quota table: 65536 entries of a fixed size
	// (about 300 B each with the map's share, some 20 MiB in all). A new key
	// in a full table evicts the entry idle the longest; with every entry in
	// use NewSession fails with ErrBusy. 0 takes the default; it cannot be
	// removed, so a negative value is an error.
	MaxKeys int

	// WriteTimeout is the deadline of one control frame: 3 s. A negative
	// value is an error.
	WriteTimeout time.Duration
	// AbortTimeout is the absolute deadline shared by the punch_abort
	// notices of a closing session: 500 ms. A negative value is an error.
	AbortTimeout time.Duration
}

Limits are the coordinator's admission and anti-abuse limits. A zero field takes the default; a negative count or rate removes the limit, except for the bounds of the coordinator's memory — MaxSessions, MaxKeys, ObserverQueue and FramesPerLink — and WriteTimeout and AbortTimeout, which keep a client that does not read from holding the coordinator: these cannot be lifted, and a negative value is an error.

type MemoryResult

type MemoryResult uint8

MemoryResult is the outcome of one round reported to a StrategyMemory.

const (
	// MemSuccess means the round's variant was confirmed (UDP handshake done).
	MemSuccess MemoryResult = iota + 1
	// MemFailure means the round ended unconfirmed with NoContact, OneWay or
	// Blocked.
	MemFailure
	// MemNeutral means no evidence either way (ConfirmLost, NoReport, aborted).
	MemNeutral
	// MemHalfConfirmed means only one role confirmed the path.
	MemHalfConfirmed
)

Memory results.

type NoMemory

type NoMemory struct{}

NoMemory remembers nothing. It is both a StrategyMemory and a natprobe.TraitsMemory, so Config.Memory = NoMemory{} and Config.TraitsMemory = NoMemory{} turn the two memories off.

func (NoMemory) Apply

Apply returns current unchanged.

func (NoMemory) Observe

Observe does nothing.

func (NoMemory) Recall

Recall remembers nothing.

func (NoMemory) Recommend

func (NoMemory) Recommend(_ StrategyKey, ladder []plan.VariantID) []plan.VariantID

Recommend returns a copy of ladder.

func (NoMemory) Report

Report does nothing.

func (NoMemory) Score

Score returns 0.

type Outcome

type Outcome uint8

Outcome is how a session ended.

const (
	// OutcomeSucceeded means at least one client confirmed a UDP path, which
	// includes one-sided confirmations and quiet handovers.
	OutcomeSucceeded Outcome = iota + 1
	// OutcomeFailed means the punch failed — a NATHard reason, or
	// probe_timeout, not_synchronized, udp_blocked, no_common_family,
	// no_probe_endpoint, local_port_bind_failed or transport_mismatch.
	OutcomeFailed
	// OutcomeAborted means everything else — control plane, caller, limits,
	// protocol, internal.
	OutcomeAborted
)

Outcomes.

func (Outcome) String

func (o Outcome) String() string

String returns the outcome name.

type PanicInfo

type PanicInfo struct {
	Value string
	Stack []byte
}

PanicInfo is the data of EvInternalError. The stack is for local logs only; it never reaches a wire frame or a Result.

type PeerTargetsData

type PeerTargetsData struct {
	Source  protocol.TargetSource
	Targets []netip.AddrPort
	Window  *protocol.PortWindow
}

PeerTargetsData is the data of EvPeerTargets.

type PlanClampedData

type PlanClampedData struct {
	Field    string
	From, To int64
}

PlanClampedData is the data of EvPlanClamped: a plan field the coordinator changed (budget classes are given by rank).

type PlannedData

type PlannedData struct {
	PairClass string
	Variant   string // round 1
	Budget    protocol.BudgetClass
	MemoryHit bool
	Rejected  protocol.Reason
	Transport string
}

PlannedData is the data of EvPlanned.

type ProbeFunc

type ProbeFunc func(role protocol.Role, opts *SessionOptions) (protocol.ProbeSpec, error)

ProbeFunc returns the ProbeSpec a role receives in punch_start (normally built from natprobe.Server.ProbeSpec). It runs in NewSession, outside every lock and inside a recover boundary; an error or a panic fails NewSession.

func ProbeFrom

func ProbeFrom(src natprobe.SpecSource) ProbeFunc

ProbeFrom returns the ProbeFunc of a long-running server: every session gets src.Spec() — the natprobe.Server's live observers at the current natprobe.ServerAddrs, with the current natprobe.STUNList — read afresh for each session. A client's own control connection is known only at Attach: give AttachOptions.Probe src.SpecFor(conn) there to put the address it connected to first.

type ProgressData

type ProgressData struct {
	Stage  string
	Status protocol.ProgressStatus
	Round  int
}

ProgressData is the data of EvProgress.

type Rate

type Rate struct{ PerSec, Burst int }

Rate is a token bucket: PerSec tokens per second, at most Burst at once. A zero field takes the default, a negative PerSec removes the limit, and a negative Burst is an error.

type RateLimitedData

type RateLimitedData struct {
	Dimension string
	Key       string
}

RateLimitedData is the data of EvRateLimited: the refused dimension and the client key it concerned ("" for global limits).

type ReasonError

type ReasonError struct {
	Reason protocol.Reason
	Detail string // the session end's detail, if any
}

ReasonError is a coordinator error that stands for a protocol reason: ErrBusy (server_busy), and the cancellation cause of the context of a session that did not succeed. Match a sentinel with errors.Is, or read the reason with errors.As.

func (*ReasonError) Error

func (e *ReasonError) Error() string

Error formats the error as "coord: <reason>", followed by ": <detail>" when there is one.

type Result

type Result struct {
	SessionID  string
	Reason     protocol.Reason // "" on success, otherwise one of the 26 reasons
	Detail     string          // human readable, standard details (join_timeout, ...), never a stack
	FailedRole protocol.Role   // the side that caused the failure; "" for the server or the caller
	Outcome    Outcome
	Attached   [2]bool            // [initiator, responder]
	Confirmed  [2]bool            // the role reported round_result{confirmed} or punch_result{ok}
	MemoryHit  bool               // the first round's variant came from the strategy memory
	Warn       []protocol.Warning // at most 8: the server's own, such as peer_result_missing and unverified_targets
	Winner     *WinnerInfo        // non-nil on success
	PairClass  string             // the Planner's diagnostic pair class
	// StrategyKey is the hex StrategyKey of the pair ("" when no key was
	// derived); it contains no plain address.
	StrategyKey string
	Warm        [2]WarmStart  // how each side started (warm starts: Config.NoWarm)
	Rounds      []RoundRecord // <= 8, rescue round included
	RTT         [2]time.Duration
	ClockOffset [2]time.Duration // diagnostic only (pong.client_unix_ms)
	Timing      Timing
	Counters    Counters
	Timeline    []StageMark     // the latest <= 32 progress marks
	Clients     [2]*ClientFinal // the clients' punch_result, nil when none arrived
	Retry       RetryAdvice
	Labels      map[string]string // SessionOptions.Labels
}

Result is a session's end, produced exactly once; when it is delivered, all of the session's resources have been released.

type RetryAdvice

type RetryAdvice struct {
	// Advice is what a failed session suggests: background_viable — relay
	// and punch again with SessionOptions.Mode background — or relay_only;
	// "" after a success or for a pair a retry as before suits.
	Advice    protocol.Advice
	After     time.Duration
	Retryable bool
	// BackgroundOnly reports that the strategy memory saw this pair of exits
	// connect only through the slow birthday; the next session may go to the
	// relay and Background at once.
	BackgroundOnly bool
}

RetryAdvice tells the caller whether and when a new attempt makes sense, and in which mode.

type RoundEndedData

type RoundEndedData struct {
	Sent  [2]int
	Hit   [2]bool
	Class plan.RoundClass
}

RoundEndedData is the data of EvRoundEnded.

type RoundFamilyUsage

type RoundFamilyUsage struct {
	SocketLimit                      protocol.SocketLimit
	DistinctTargets, NewDestinations uint16
	PlannedSockets, SocketsUsed      uint16
	// For clients reporting only Sent, Reserved and Attempted are lower bounds equal to Sent.
	Reserved, Attempted, Sent           uint32
	DistinctPorts, BindFailed, Rejected uint16
	Hit, BudgetHit                      bool
	FirstWrite                          time.Duration // since this client's go read, meaningful when Sent > 0
}

RoundFamilyUsage is the planned and reported work of one role and family.

type RoundRecord

type RoundRecord struct {
	// GoQueued and GoWritten are the native-clock instants of queue admission
	// and full socket write by role. A missing event has a zero timestamp.
	// StartedAt and Duration use the coordinator's configured protocol clock.
	GoQueued, GoWritten [2]time.Time
	Usage               [2][2]RoundFamilyUsage // indexed by role and Family.Index()
	StartedAt           time.Time
	Budget              protocol.BudgetClass // the class actually granted
	Granted             [2]int               // MaxPackets granted to each side
	Sent                [2]int               // initiated packets each side reported
	Round               int
	Duration            time.Duration
	Variant             plan.VariantID
	Rescue              bool
	Class               plan.RoundClass
}

RoundRecord describes one round.

type Session

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

Session is one punch between two clients. Its methods are safe for concurrent use.

func (*Session) Abort

func (s *Session) Abort(reason protocol.Reason, detail string)

Abort ends the session with reason (an unknown reason means canceled) and detail: each client still connected and not yet confirmed gets punch_abort{by: server, code: reason}, within one shared 500 ms deadline, and the links are closed. It is idempotent and returns when the session's own cleanup is done.

func (*Session) Attach

func (s *Session) Attach(role protocol.Role, conn net.Conn, opts AttachOptions) (err error)

Attach gives the session role's control stream, which the caller has authenticated; the roles attach in either order, each once. On nil the connection belongs to the session — it is written punch_start and ping#1 right away and closed when the session ends, even if the session ends while Attach runs, as it does with internal when the coordinator fails after taking the stream over. On error it is still the caller's and nothing was read or written but a TLS handshake: ErrSessionDone, ErrClosed, ErrAlreadyAttached, ErrInvalidRole, ErrInvalidConn (nil, typed nil, or no deadline support: the stream needs net.Conn's deadline semantics, a deadline in the past interrupting a blocked Read or Write), a recovered panic, or a *protocol.ValidationError with Reason invalid_argument and Detail insecure_control when the stream is not vouched for, or tls_handshake when its handshake failed.

With protocol.ControlSecurityAuto a TLS conn whose handshake has not run yet — a tls.Listener's fresh conn — is handshaken first, within 10 s of wall-clock time and the session's life; that is the only time Attach blocks. A failed handshake leaves the conn unusable but open, still the caller's to close.

func (*Session) Context

func (s *Session) Context() context.Context

Context is canceled when the session ends; its cause is ErrSessionDone after a success, the recovered panic after a panic in a session goroutine, and a *ReasonError with the end's reason and detail otherwise (server_shutdown after Coordinator.Close). Callers can tie their own resources to it.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done is closed once the session has ended, every resource is released and every goroutine of the session has returned.

func (*Session) ID

func (s *Session) ID() string

ID returns the session id.

func (*Session) Inject

func (s *Session) Inject(target protocol.Role, a protocol.Assist) error

Inject sends the target side targets the caller learned elsewhere, as peer_targets{source: inject}: only while punching, through the same admission and the same per-round limit as the server's own targets. Only a.Family, a.Targets, a.Window and a.Meta are used. Errors: ErrInvalidRole, ErrSessionDone, ErrBusy (round limit, no budget left for the targets, or the link's queue), and a *protocol.ValidationError with Reason invalid_argument (not punching, an unknown family or a malformed Meta, nothing admitted).

func (*Session) PunchStart

func (s *Session) PunchStart(role protocol.Role) protocol.PunchStart

PunchStart returns a copy of the punch_start pre-generated for role, for announcing the session out of band (a caller may signal the responder with it); the same message is written on the stream at Attach, with the AttachOptions.Probe given there. It returns the zero value for an invalid role.

func (*Session) Result

func (s *Session) Result() (Result, bool)

Result returns the session's Result once Done is closed.

func (*Session) Snapshot

func (s *Session) Snapshot() Snapshot

Snapshot returns a copy of the session's state.

func (*Session) Wait

func (s *Session) Wait(ctx context.Context) (Result, error)

Wait blocks until the session has ended — Done is closed — and returns its Result, or returns ctx's cause first if ctx ends.

type SessionOptions

type SessionOptions struct {
	// SessionID and Token are generated when empty (18 B id and 32 B token,
	// base64url). A Token given here must be the base64url of 32 bytes.
	SessionID, Token string
	// Wire is generated when zero: a random route and a per-session random
	// payload range. A given Wire needs a route, payload_min in [48, 160],
	// payload_max − payload_min in [64, 256] and payload_max <= 1024.
	Wire protocol.WireSpec
	// Timeouts replaces Config.Timeouts.
	Timeouts *protocol.Timeouts
	// InitiatorProbe and ResponderProbe replace Config.Probe for one role.
	InitiatorProbe, ResponderProbe *protocol.ProbeSpec
	// Policy replaces Config.Policy; its budget is clamped to the operator
	// ceiling.
	Policy *protocol.Policy
	// ClientKeys are the [initiator, responder] keys of the per-key limits
	// and packet quotas (Limits: sessions and session rate per initiator
	// key, sessions per responder key, packets per minute); an empty key is
	// not limited. A key is the unit those limits protect from each other:
	// one per device or process keeps several devices that share an account
	// from crowding each other out, and a caller that wants a total per
	// account as well counts it itself before NewSession.
	ClientKeys [2]string
	// Parent, when set, aborts the session with canceled when it is done.
	Parent context.Context
	// Labels are copied into events and the Result, never onto the wire.
	Labels map[string]string
	// Mode offers the clients a Background session: the caller already
	// relays their traffic and nobody waits.
	// It runs in Background only when both clients accept; a PDF × RND
	// pair then runs the slow birthday. A Background offer defaults the
	// session budget to protocol.BackgroundBudget and, without Timeouts,
	// the handshake to 60 s. The zero value is interactive.
	Mode protocol.SessionMode
}

SessionOptions configures one session.

type Snapshot

type Snapshot struct {
	ID                   string
	State                State
	Round                int
	Attached, Reported   [2]bool // index 0 initiator, 1 responder
	Ready, Confirmed     [2]bool
	LastStage            [2]string
	RTT                  [2]time.Duration
	Variant              string
	CreatedAt, UpdatedAt time.Time
}

Snapshot is a small copy of a session's state.

type StageMark

type StageMark struct {
	Role     protocol.Role
	Stage    string
	Status   protocol.ProgressStatus
	Round    int
	OffsetMs int64 // since the session was created
}

StageMark is one progress report.

type State

type State string

State is a session's state. States only move forward; whether a closed session succeeded is in its Result.

const (
	StateCreated    State = "created"    // no link yet
	StateBinding    State = "binding"    // one link attached
	StateProbing    State = "probing"    // both attached, waiting for both reports
	StateSummarized State = "summarized" // summaries written, waiting for both readies
	StatePunching   State = "punching"   // round k under way
	StateConfirming State = "confirming" // at least one confirmation
	StateClosed     State = "closed"
)

States.

type Stats

type Stats struct {
	DestinationLimited            int64 // family plans and assists refused by the per-IP packet quota
	SessionsActive, SessionsTotal int64
	ByOutcome                     [3]int64                  // succeeded, failed, aborted
	ByReason                      map[protocol.Reason]int64 // failures by reason
	BothHandedOver                int64                     // successes with two final handover reports
	QuietHandover                 int64                     // successful sessions with a primary handover inferred from silence
	HalfConfirmed                 int64                     // successes with only one confirmation
	RoundsByClass                 [6]int64                  // indexed by RoundClass
	ConfirmAtRound                [9]int64                  // 0: never confirmed; 1..8: the confirming round
	RTTHistogramMs                [8]int64                  // <20, <50, <100, <200, <400, <800, <1600, >=1600
	TimeToConfirm                 [8]int64                  // <0.5, <1, <2, <4, <8, <12, <16, >=16 s
	MemoryEntries, MemoryHits     int64
	AssistForwarded               int64
	AssistDropped                 int64
	AssistRejected                int64
	PeerTargets                   int64
	PingsSent                     int64
	ProgressDropped               int64
	UnknownFrames                 int64
	PlanClamped                   int64
	TargetRejected                int64
	BudgetViolation               int64
	STUNConflicts                 int64 // STUN values that contradicted natprobe's records
	EventsDropped                 int64
	Panics                        int64
	RateLimited                   int64 // refused NewSession calls
	ActiveByKey                   int64 // key entries in use (leak check: 0 when idle)
	KeyEntries                    int64 // key table entries, idle ones included (≤ Limits.MaxKeys)
	KeysEvicted                   int64 // idle key entries evicted for a new key in a full table
	KeyTableFull                  int64 // NewSession calls refused because every key entry was in use
	Stuck                         int64 // sessions or goroutines Close gave up on
}

Stats is a snapshot of the coordinator's counters.

type StrategyKey

type StrategyKey [16]byte

StrategyKey identifies a pair of NAT exits across sessions: an HMAC of the two canonical sides' IP prefixes and NAT class bits, so it carries no plaintext address.

func DeriveStrategyKey

func DeriveStrategyKey(salt []byte, a, b StrategySide) StrategyKey

DeriveStrategyKey derives the key of the canonical pair (A, B) = HMAC-SHA256(salt, A.IPPrefix ‖ A.ClassBits ‖ B.IPPrefix ‖ B.ClassBits)[:16]. A is the Planner's rule side, so the same pair of exits maps to the same key whichever client initiates.

func (StrategyKey) String

func (k StrategyKey) String() string

String returns the key in hex.

type StrategyMemory

type StrategyMemory interface {
	// Recommend returns the ladder reordered by preference, a permutation
	// of ladder; anything else keeps the ladder's order. The built-in
	// memory also lowers the first entry by RotatePenalty, which rotates
	// repeatedly failing variants away.
	Recommend(key StrategyKey, ladder []plan.VariantID) []plan.VariantID
	// Score is what the memory knows of variant v for key: positive when v
	// connected the pair before, negative when it failed and its failures
	// outweigh its successes, 0 for nothing either way. Only the sign is
	// read. It must not count as a use of the key.
	Score(key StrategyKey, v plan.VariantID) int
	// Report records the outcome of one round.
	Report(key StrategyKey, v plan.VariantID, r MemoryResult)
}

StrategyMemory remembers which variants worked for a pair of exits. Implementations must be safe for concurrent use and must not block; the coordinator calls them outside every lock and inside a recover boundary, and a panicking memory is ignored for the rest of the session.

Planning a session, the coordinator asks Recommend for the order of the primary ladder and then Score for what the memory knows: a first variant that scores positive is a memory hit (Result.MemoryHit) and, when the memory moved it ahead of the ladder's first, may lift the first round's class cap up to heavy (plan.RoundInput.MemoryPromoted); a reordering without a positive score is used as an order only. A pair whose one positive variant is the slow birthday while the interactive pdf_x_rnd rounds failed is reported as background_only in the summaries.

The key has no transport dimension: the variants open the NATs for UDP, whatever upper-layer transport then runs over the path, so a success under one transport mode is evidence for every other. A transport that fails on a confirmed path (Coordinator.Memory) counts against the variant for the pair as a whole, a weak signal against the gain of a success.

func NewStrategyMemory

func NewStrategyMemory(cfg StrategyMemoryConfig) StrategyMemory

NewStrategyMemory returns the built-in StrategyMemory: a sharded LRU (one mutex, one map and one list per shard) with lazy TTL checks and no goroutine. The returned value also has the methods

Sweep(now time.Time, max int) int // drops expired entries, scanning at most max
Export(w io.Writer) error         // 16 B key + 32 B scores + 4 B last use per entry
Import(r io.Reader) error

reached through a type assertion; the coordinator's housekeeping calls Sweep every 10 s.

type StrategyMemoryConfig

type StrategyMemoryConfig struct {
	TTL            time.Duration // 72 h, clamped to [1 h, 30 d]
	MaxEntries     int           // 65536, evicted least recently used per shard
	Shards         int           // 16
	Salt           []byte        // key salt; nil draws a random one (keep it with exported data)
	SuccessGain    int8          // +2
	FailurePenalty int8          // 1
	RotatePenalty  int8          // 1
	ScoreMin       int8          // -10
	ScoreMax       int8          // +10
	ReportsPerMin  int           // 6 reports per key and minute; more are ignored
	// Clock is the time source of TTLs and report rates; nil means the
	// system clock.
	Clock timeshim.Clock
}

StrategyMemoryConfig configures NewStrategyMemory. Zero fields take the defaults; negative gains and penalties count as zero.

type StrategySide

type StrategySide struct {
	IPPrefix  netip.Prefix
	ClassBits uint32
}

StrategySide is one canonical side of a StrategyKey: the verified public IP prefix (IPv4 /32, IPv6 /64) and the class bits of its traits.

type TTLConfig

type TTLConfig struct {
	// BindTimeout bounds created and binding from NewSession: 15 s,
	// [3 s, 60 s].
	BindTimeout time.Duration
	// ReportSlack is added to probe_timeout after the second Attach:
	// 3 s, (0, 10 s].
	ReportSlack time.Duration
	// ReadyTimeout bounds summarized: go_wait_ms, [500 ms, 15 s].
	ReadyTimeout time.Duration
	// PunchSlack is added to handshake_timeout after the first go:
	// 1 s, (0, 5 s].
	PunchSlack time.Duration
	// ConfirmLinger is how long one confirmation waits for the other:
	// handover_timeout + 1 s, (0, 5 s]; a negative value ends the session at
	// the first confirmation.
	ConfirmLinger time.Duration
	// ResultGrace is how long two confirmations wait for both
	// punch_result frames: 300 ms, (0, 1 s]; a negative value ends the session
	// at the second confirmation.
	ResultGrace time.Duration
}

TTLConfig holds the server deadlines. Each zero field takes its default and other values are clamped to the range given, which the protocol fixes. A negative BindTimeout, ReportSlack, ReadyTimeout or PunchSlack is an error: the session's deadlines cannot be lifted.

type TargetPolicy

type TargetPolicy uint8

TargetPolicy says which peer addresses the clients may aim at (Config.Targets).

const (
	// TargetsBounded is the default: the clients aim at the addresses the
	// server verified, and also at self-reported addresses where nothing
	// could be verified, within tight bounds: Direct stages only, at most 4 IPs and
	// 8 packets per target and round. That covers a family the server has
	// no observer for (IPv6 on a v4-only server with two dual-stack
	// clients) and a client the server saw only at a private address
	// (protocol.Traits.LANObserved: it reaches the server over a LAN route
	// or a hairpin without source NAT), which is then reached at the global
	// addresses its STUN servers and port mapping reported. The summary
	// marks such a family in pair.unverified and the Result warns
	// unverified_targets. A client could report a third party's address
	// there; the bounds keep what that third party receives small.
	TargetsBounded TargetPolicy = iota
	// TargetsVerifiedOnly aims only at addresses the server verified, and at
	// LAN and overlay addresses where both sides share one: a family no
	// observer covers is left out of the session, and a LAN-observed
	// client is reached only on the LAN.
	TargetsVerifiedOnly
)

Target policies.

type TargetRejectedData

type TargetRejectedData struct {
	Rule string
	Addr netip.AddrPort
}

TargetRejectedData is the data of EvTargetRejected: the admission rule and the refused address.

type Timing

type Timing struct {
	Created      time.Time
	Attached     [2]time.Time
	Summary      time.Time
	FirstGo      time.Time
	FirstConfirm time.Time
	Closed       time.Time
}

Timing are the instants of a session's milestones (zero: not reached).

type WarmStart

type WarmStart string

WarmStart is how a side of a session started (Config.NoWarm).

const (
	// WarmOff means the side started cold: not offered, its early report
	// never came, or its final report came before the session was planned.
	WarmOff WarmStart = ""
	// WarmHit means the session was planned on the side's early report and the
	// remembered traits, and its final report, if it came before the
	// session confirmed, did not overturn them.
	WarmHit WarmStart = "hit"
	// WarmCold means the early report was not enough (no remembered mapping, a
	// new public IP, an observation that contradicted the memory): the
	// session waited for the final report.
	WarmCold WarmStart = "cold"
	// WarmContradicted means the session was planned on the early report, and
	// the final report overturned the remembered traits; the rounds after
	// it were planned on the final report.
	WarmContradicted WarmStart = "contradicted"
)

Warm starts.

type WinnerInfo

type WinnerInfo struct {
	Round   int
	Variant plan.VariantID
	Family  protocol.Family
	Path    [2]*protocol.PathInfo // by role; nil for a side that did not report its path
	// ExtraPaths are, by role, the other paths each side handed over with
	// Path, from its punch_result; empty with one
	// path or without the report.
	ExtraPaths [2][]protocol.PathInfo
}

WinnerInfo is the confirmed path.

Directories

Path Synopsis
internal
simclient
Package simclient is a scripted holepunch client for coord's tests: it speaks the holepunch control protocol over one connection, answers pings by itself (unless told not to) and leaves every other step to the test, which reads what the coordinator writes and sends what the script says.
Package simclient is a scripted holepunch client for coord's tests: it speaks the holepunch control protocol over one connection, answers pings by itself (unless told not to) and leaves every other step to the test, which reads what the coordinator writes and sends what the script says.

Jump to

Keyboard shortcuts

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