Documentation
¶
Overview ¶
Package protocol is the holepunch control plane as data: the twelve control messages and their shared structures, the domain model they carry (Traits and its predicates, plans, Policy and Budget), the client Phase and the failure Reasons with their classes.
Encoding and checking ¶
Marshal, Unmarshal and Decode convert between messages and the JSON payloads of their frames; MessageType names a frame's type and its payload cap. Decoding enforces the JSON rules of a control payload — a UTF-8 object nested at most 8 levels — and then Validate, the structural check: required fields, enumeration values, string and list limits. The list limits of the messages a client sends are checked before decoding as well, so that a frame cannot make the server allocate many times its size. A violation is a *ValidationError whose Reason (protocol_violation or control_version_mismatch) and Detail (the field path) go on the wire. Normalize is separate: it returns the message with the receiver-side clamps applied and whether anything changed, which the client reports as punch_ready.families[].clamped. Assists are checked by direction (see Assist).
Concurrency and ownership ¶
The package does no I/O, starts no goroutines and keeps no state. Messages are plain values: concurrent reads are safe, and a decoded message belongs to the caller.
Secrets ¶
Token and RouteID never print their value: fmt and log/slog show a placeholder or the 4-hex-digit route prefix, and PunchStart, ProbeReport and ProbeSummary log without key material or transport data. Only the JSON encoding carries them.
protocol depends only on the standard library and the module's frame table.
Index ¶
- Constants
- Variables
- func CheckOrigin(m Message, sessionID string, role Role) error
- func CheckTransportMode(mode string) error
- func DropKeys() []string
- func Marshal(m Message) ([]byte, error)
- func MinSet[T ~uint8 | ~uint16 | ~uint32](a, b T) T
- func NeedsPeerPortPrediction(self, peer Traits) bool
- func NewSessionID() string
- func RelayOnly(fams []Family, pair PairFacts, views [2]PeerView) bool
- func Unmarshal[T any, P interface{ ... }](t MessageType, payload []byte) (T, error)
- func UsableEndpoint(f Family, a netip.AddrPort) bool
- type Abort
- type Advice
- type Assist
- type AssistKind
- type BirthdaySpec
- type BirthdayTier
- type Budget
- type BudgetClass
- type CandKind
- type ClassLimits
- type ClientCaps
- type ClockSample
- type Conf
- type ControlSpec
- type Detail
- type Endpoint
- type EndpointSource
- type EventName
- type Family
- type FamilyAddition
- type FamilyCaps
- type FamilyOutcome
- type FamilyReady
- type FamilyReport
- type FamilySide
- type FamilyView
- type Feature
- type FilterReport
- type Filtering
- type HandoverEvidence
- type Mapping
- type Message
- type MessageType
- type ObserverSpec
- type PairClass
- type PairFacts
- type PathInfo
- type PathKind
- type PeerView
- type Phase
- type Ping
- type PlanSpec
- type Policy
- type Pong
- type PortAlloc
- type PortMapMethod
- type PortMapReport
- type PortMappingInfo
- type PortMappingPolicy
- type PortWindow
- type ProbeReport
- type ProbeSpec
- type ProbeSummary
- type Progress
- type ProgressStatus
- type PunchGo
- type PunchReady
- type PunchResult
- type PunchStart
- type Reason
- type ReasonClass
- type Remap
- type RetryHint
- type Role
- type RoundPlan
- type RoundResult
- type RoundStatus
- type RouteID
- type RowReport
- type SessionMode
- type SideRole
- type SocketKind
- type SocketLimit
- type SocketReport
- type Stage
- type StageKind
- type Stats
- type TargetSource
- type Timeouts
- type Timing
- type Token
- type Traits
- type TraitsSource
- type TraitsUpdate
- type Transport
- type TransportPick
- type Tri
- type ValidationError
- type Warning
- type WireSpec
Constants ¶
const ( // MaxSessionID is the longest session id, in bytes. MaxSessionID = 64 // MaxObservers bounds ProbeSpec.Observers. MaxObservers = 16 // MaxReportSockets bounds FamilyReport.Sockets. MaxReportSockets = 6 // MaxReportRows bounds SocketReport.Rows: one per observer. MaxReportRows = 16 // MaxReportFilters bounds FamilyReport.Filters. MaxReportFilters = 24 // MaxReportSTUNRows bounds FamilyReport.STUN. MaxReportSTUNRows = 8 // MaxLocalAddrs bounds FamilyReport.LocalAddrs. MaxLocalAddrs = 16 // MaxOverlayAddrs bounds FamilyReport.Overlay. MaxOverlayAddrs = 2 // MaxTransportData bounds Transport.Data, in bytes. MaxTransportData = 8 << 10 // MaxEndpoints bounds FamilyView.Endpoints. MaxEndpoints = 12 // MaxRound is the highest round number; rescue rounds take one too. MaxRound = 8 // MaxSeenFrom bounds FamilyOutcome.SeenFrom. MaxSeenFrom = 4 // MaxWarn bounds PunchResult.Warn. MaxWarn = 8 // MaxLowTTLHops bounds Policy.LowTTLHops. MaxLowTTLHops = 8 // MaxDetail bounds punch_abort.detail and punch_result.detail, in bytes. MaxDetail = 256 // MaxProgressDetail bounds punch_progress.detail, in bytes. MaxProgressDetail = 128 // MaxPortWindowWidth bounds PortWindow: hi − lo. MaxPortWindowWidth = 63 )
Structural limits checked by Validate: a list over one of them is a protocol violation. The exported ones bound what a sender may put in a message, so the library's senders build their messages against them.
const ( // MaxDelayMs bounds PunchGo.DelayMs. MaxDelayMs = 2000 // MaxSendDelayMs bounds FamilySide.SendDelayMs. MaxSendDelayMs = 3000 // MaxSideSockets bounds FamilySide.Sockets and a fresh stage's Count. MaxSideSockets = 256 // MaxStages bounds FamilySide.Stages. MaxStages = 8 // MaxStageTargets bounds Stage.Targets. MaxStageTargets = 16 // MaxSteps bounds Stage.Steps. MaxSteps = 3 // MaxSpanCount bounds Stage.Span and Stage.Count. MaxSpanCount = 4096 // MaxRepeats bounds Stage.Repeats. MaxRepeats = 8 // MinLowTTL and MaxLowTTL bound a set Stage.TTL. MinLowTTL = 2 MaxLowTTL = 64 // MaxSiblings bounds ProbeSpec.Siblings. MaxSiblings = 2 )
Ranges the receiver clamps (Normalize) instead of refusing the message.
const ( // MaxLANTargets bounds a peer's private addresses that a side aims at // (a peer on the same LAN, or an upstream port mapping of one behind the // same public IP), per round, and the distinct LAN IPs of its peer a // client keeps. MaxLANTargets = 4 // MaxOverlayTargets bounds a peer's overlay addresses that a side aims // at, per round, when both sides have some. MaxOverlayTargets = 2 // LANRepeats is how many packets a side sends each LAN or overlay // target per round. LANRepeats = 2 // MaxReportedIPs is how many distinct global IPs a peer reported itself // a side keeps as targets of a family the server could not verify. MaxReportedIPs = 4 // MaxUnverifiedTargets bounds the distinct targets of an unverified // family per side and round; MaxRelayOnlyTargets replaces it when the // server verified none of the families (RelayOnly). MaxUnverifiedTargets = 4 MaxRelayOnlyTargets = 16 // UnverifiedRepeats is how many packets a side sends each target of an // unverified family per round, at most. UnverifiedRepeats = 8 // PushPackets is how many packets a client sends each peer_targets // target or window port, each round. PushPackets = 2 // MaxPushPerRound bounds the peer_targets targets and window ports a // client takes per family and round. MaxPushPerRound = 64 // MaxDrifted bounds the drifted mappings of a peer (peer_targets with // source drift) a server pushes, and a client keeps, per session. MaxDrifted = 16 )
Target rules both ends of a session apply: the coordinator plans and admits within them, and a client admits what it is sent within them, so a plan the coordinator grants is a plan the client runs.
const ( MsgPunchStart = MessageType(wiretype.PunchStart) // S→C MsgProbeReport = MessageType(wiretype.ProbeReport) // C→S MsgProbeSummary = MessageType(wiretype.ProbeSummary) // S→C MsgPunchReady = MessageType(wiretype.PunchReady) // C→S MsgPunchGo = MessageType(wiretype.PunchGo) // S→C MsgProgress = MessageType(wiretype.Progress) // C→S, telemetry only MsgAssist = MessageType(wiretype.Assist) // C→S→C and S→C MsgAbort = MessageType(wiretype.Abort) // S→C only MsgPing = MessageType(wiretype.Ping) // S→C MsgPong = MessageType(wiretype.Pong) // C→S MsgRoundResult = MessageType(wiretype.RoundResult) // C→S MsgPunchResult = MessageType(wiretype.PunchResult) // C→S )
The twelve message types.
const ( DropShort = "short" DropForeign = "foreign" DropRate = "rate" DropAuth = "auth" DropPayload = "payload" DropRole = "role" DropReplay = "replay" DropBudget = "budget" DropTargetRejected = "target_rejected" DropSendErr = "send_err" )
The keys of Stats.Drops: the client's packet-drop classes. Packets of another protocol version, of an old session and of another session all fail authentication and count as auth.
const DefaultPortMapLease = time.Hour
DefaultPortMapLease is the lease requested when LeaseSeconds is unset.
const MaxPaths = 8
MaxPaths is the most confirmed paths one session hands over: the primary path and up to MaxPaths-1 extra paths.
const MaxProbeSTUN = 16
MaxProbeSTUN is the most STUN servers a ProbeSpec lists. A client asks at most 8 of each family, all at once.
const ProbeSpecVersion = 3
ProbeSpecVersion is the only ProbeSpec.V this implementation runs; any other value is control_version_mismatch with detail probe_v.
Variables ¶
var ErrUnexpectedMessage = errors.New("protocol: unexpected message")
ErrUnexpectedMessage is returned when the frame's type is not the one expected (Unmarshal), or not a message type at all (Decode).
Functions ¶
func CheckOrigin ¶
CheckOrigin verifies a received message against its link: every message except ping/pong must carry the link's session_id (else protocol_violation, detail session_mismatch), and a client-to-server message must carry the link's role (detail role_mismatch). A client passes role "": server messages carry no sender role. m may be a message value or pointer.
func CheckTransportMode ¶
CheckTransportMode checks a transport mode name: at most 16 bytes of printable ASCII other than the space ("quic", "kcp"), or empty.
func Marshal ¶
Marshal validates m (a message value or pointer) and encodes it as the JSON payload of a frame of type m.MessageType(). JSON is written without HTML escaping. A payload above the type's cap (MessageType.MaxPayload) is refused with a *ValidationError, detail frame_too_large: an oversized or invalid outbound message is an implementation bug, and a relayed message whose re-encoding grew past the cap is dropped by the relay rather than sent.
func MinSet ¶
MinSet is the tighter of two limits of which 0 means unset: the smaller of a and b, or the one that is set, or 0 when neither is.
func NeedsPeerPortPrediction ¶
NeedsPeerPortPrediction reports whether this side must aim at predicted peer ports: the peer's port depends on the destination and this side filters by port.
func NewSessionID ¶
func NewSessionID() string
NewSessionID returns a random session id: base64url of 18 bytes, 24 characters of [A-Za-z0-9_-].
func RelayOnly ¶
RelayOnly reports whether the server verified none of families fams in the pair: each is unverified (PairFacts.Unverified) without a LAN-observed side in views — a LAN-observed family keeps the tighter unverified bounds. This is the coordinator's NoObserver mode, or a registry that observes none of the families; an unverified family's distinct targets per side and round rise from MaxUnverifiedTargets to MaxRelayOnlyTargets. It is false without a family.
func Unmarshal ¶
func Unmarshal[T any, P interface { *T Message }](t MessageType, payload []byte) (T, error)
Unmarshal decodes the payload of a frame of type t into the message type T (a value type such as PunchGo) and validates it. Another type t returns ErrUnexpectedMessage. A payload above the type's cap, or that is not a UTF-8 JSON object nested at most 8 levels, or that fails Validate, returns a *ValidationError. Unknown fields are ignored. Unmarshal does not clamp: the caller runs Normalize and reports whether a clamp happened.
func UsableEndpoint ¶
UsableEndpoint reports whether a may stand in an address field of family f on the wire: an address with a port that is neither unspecified nor multicast, of family f — of either family when f is empty — and never IPv4-mapped. Validation refuses a frame with any other endpoint, so a sender checks what it reports against the same rule. It is a wire rule, not admission: loopback and private addresses pass.
Types ¶
type Abort ¶
type Abort struct {
Advice Advice `json:"advice,omitempty"`
PairClass PairClass `json:"pair_class,omitempty"`
SessionID string `json:"session_id"`
By Role `json:"by"` // initiator | responder | server: where the failure came from
Reason Reason `json:"code"` // empty or unknown: the client fails with aborted_by_<by>
Detail Detail `json:"detail,omitempty"` // <= 256 B
RetryAfterMs uint32 `json:"retry_after_ms,omitempty"` // suggested retry delay (server_busy, ...)
}
Abort ends a session from the server. The server never forwards a client's frame; it always writes a new one. A client never sends it: a client's terminal report is punch_result, and a punch_abort arriving at the server is a wrong-direction frame, discarded and counted.
type Advice ¶
type Advice string
Advice is what a failed session suggests for the next attempt: "" (retry as before), background_viable or relay_only.
const ( // AdviceBackgroundViable means the pair connects slowly: serve the // caller over the relay and punch again in ModeBackground. AdviceBackgroundViable Advice = "background_viable" // AdviceRelayOnly means no mode is expected to connect the pair; keep // the relay. AdviceRelayOnly Advice = "relay_only" )
Advice values.
type Assist ¶
type Assist struct {
SessionID string `json:"session_id"`
Role Role `json:"role,omitempty"` // C→S: the sender (consistency check); S→C: omitted
From Role `json:"from,omitempty"` // S→C: the original sender, written by the server
Kind AssistKind `json:"kind"`
Family Family `json:"family"`
// peer_seen
Remote netip.AddrPort `json:"remote,omitzero"` // source of the received packet = the peer's mapping on this path
Local netip.AddrPort `json:"local,omitzero"` // C→S only: the receiving socket; removed before forwarding
Round uint8 `json:"round"`
Sock uint8 `json:"sock"` // from the packet header: the peer's sending socket
Cand uint16 `json:"cand"` // from the packet header: the peer's target id (stage<<12 | idx)
Type uint8 `json:"type"` // the packet's UDP type
First bool `json:"first,omitempty"` // first valid packet from the peer in the session
// peer_targets (S→C only)
Targets []netip.AddrPort `json:"targets,omitempty"` // <= 16, all admitted by the server
Window *PortWindow `json:"window,omitempty"` // hi - lo <= 63; ip must be a verified peer IP
Source TargetSource `json:"source,omitempty"`
// common
Meta map[string]string `json:"meta,omitempty"` // <= 8 keys, values <= 64 B, <= 1 KiB in all; caller pass-through
}
Assist relays punch-time evidence.
From, Targets, Window and Source are written by the server only. They are checked where they are consumed — by the client, with ValidateRelayed — and a server drops whatever a client put there (StripServerFields) instead of failing the session: such fields are dropped and counted.
func (Assist) Normalize ¶
Normalize truncates targets to 16, the window to 64 ports and meta to 8 keys.
func (Assist) Relayed ¶
Relayed is the assist the server forwards for a client's peer_seen: the sender's role moves to from, and local and the server-only fields are removed. The server never forwards the client's frame itself.
func (Assist) StripServerFields ¶
StripServerFields returns an assist received from a client without what only the server may write — from, targets, window and source — and whether there was anything to remove (the server counts that as assist_rejected).
func (Assist) Validate ¶
Validate implements Message. It checks what both directions carry; the server-written fields are left to ValidateRelayed. Assists of an unknown kind only get the common checks: the receiver ignores and counts them.
func (Assist) ValidateRelayed ¶
ValidateRelayed checks the fields the server writes, on an assist received from the server (after Validate): from, and for peer_targets the targets, the window and the source.
type AssistKind ¶
type AssistKind string
AssistKind is the kind of an assist.
const ( // AssistPeerSeen (C→S→C): the reporter received a valid UDP packet from // its peer. The server rewrites from and strips local before forwarding. AssistPeerSeen AssistKind = "peer_seen" // AssistPeerTargets (S→C only): new targets generated by the server. AssistPeerTargets AssistKind = "peer_targets" // AssistRefresh (S→C only): before the go of Round, the server asks the // client for an anchor refresh in Family: two // new sockets, about 100 ms apart, each send one probe to the family's // first global observer, so natprobe sees where the sequential // allocator is now and how fast others move it. Accepted before the // summary too. AssistRefresh AssistKind = "refresh" )
Assist kinds; any other kind is ignored and counted by the receiver.
type BirthdaySpec ¶
type BirthdaySpec struct {
OneSidedSockets, OneSidedTargets int
TwoSidedSockets, TwoSidedTargets int
Class BudgetClass
RequiresExtreme bool
MinHandshakeMs uint32 // aggressive: handshake_timeout_ms >= 30000
}
BirthdaySpec is the scale of a birthday tier: the one-sided birthday opens OneSidedSockets sockets on one side against OneSidedTargets random ports of the other; the two-sided birthday (aggressive only) opens TwoSidedSockets per side against TwoSidedTargets. Class is the BudgetClass the round needs.
type BirthdayTier ¶
type BirthdayTier string
BirthdayTier is the birthday-spray scale: off | conservative | balanced | aggressive. Ordered by Rank. The empty value means "unset" in a Policy.
const ( BirthdayOff BirthdayTier = "off" BirthdayConservative BirthdayTier = "conservative" BirthdayBalanced BirthdayTier = "balanced" BirthdayAggressive BirthdayTier = "aggressive" )
BirthdayTier values.
func (BirthdayTier) Rank ¶
func (t BirthdayTier) Rank() int
Rank orders the tiers: off 0, conservative 1, balanced 2, aggressive 3; -1 for anything else.
func (BirthdayTier) Spec ¶
func (t BirthdayTier) Spec() (s BirthdaySpec, ok bool)
Spec is the tier's scale: conservative 32×384 (heavy), balanced 64×768 (extreme), aggressive adds two-sided 16×256 (extreme, handshake >= 30 s). ok is false for off and invalid tiers.
func (BirthdayTier) Valid ¶
func (t BirthdayTier) Valid() bool
Valid reports whether t is one of the four tiers.
type Budget ¶
type Budget struct {
MaxPackets uint32 `json:"max_packets"` // initiated UDP packets per session
MaxPPS uint16 `json:"max_pps"` // token bucket shared by all sockets
MaxDistinctTargets uint16 `json:"max_distinct_targets"` // distinct destination ip:port
MaxSockets uint16 `json:"max_sockets"` // sockets open at once
MaxNewPerSec uint16 `json:"max_new_per_sec"` // new targets per second
Birthday BirthdayTier `json:"birthday"` // "" = unset
}
Budget is a side's session budget (each field: 0 = unset, see TightenBudget). The packet, rate and target limits apply to initiated packets only; replies and handshake packets have their own rules.
func BackgroundBudget ¶
func BackgroundBudget() Budget
BackgroundBudget is the default session budget of a Background session: DefaultBudget with the 128 sockets and 2048 distinct targets the slow birthday needs — both within SessionBudgetLimit(false).
func CeilingBudget ¶
func CeilingBudget() Budget
CeilingBudget is the library's hard ceiling; no source can exceed it: 40000 / 1500 / 4096 / 256 / 256 / aggressive.
func DefaultBudget ¶
func DefaultBudget() Budget
DefaultBudget is the session budget when nothing tighter is configured: 3000 packets, 300 pps, 1024 targets, 40 sockets, 100 new targets/s, birthday conservative.
func SessionBudgetLimit ¶
SessionBudgetLimit is the highest session budget an operator may grant: CeilingBudget with AllowExtreme, otherwise 6000 / 1000 / 4096 / 128 / 256 / conservative (balanced and aggressive birthday need AllowExtreme).
func TightenBudget ¶
TightenBudget merges budget levels from the outermost (levels[0], usually punch_start.policy.budget) to the innermost (for example Options.Sockets.Limits). Each field of the result is the minimum over the levels, so a level can only tighten what is above it:
- a zero field of levels[0] means DefaultBudget's value;
- a zero field of a later level means "no further restriction";
- Birthday takes the lowest tier by Rank ("" = unset; an invalid name counts as off);
- the result is clamped to CeilingBudget.
With no levels the result is DefaultBudget. Set BirthdayOff to disable birthday rounds.
type BudgetClass ¶
type BudgetClass string
BudgetClass is a per-round budget ceiling: light | balanced | heavy | extreme | background. Ordered by Rank.
const ( BudgetLight BudgetClass = "light" BudgetBalanced BudgetClass = "balanced" BudgetHeavy BudgetClass = "heavy" BudgetExtreme BudgetClass = "extreme" // BudgetBackground is the slow birthday of a Background session: many // sockets opened slowly, a long window and a low rate — wide in time, // gentle per second. It ranks with heavy and runs only in a Background // session. BudgetBackground BudgetClass = "background" )
BudgetClass values.
func ClassOfRank ¶
func ClassOfRank(r int) BudgetClass
ClassOfRank is the class of rank r on the escalation ladder: light at or below 1, balanced 2, heavy 3, extreme at or above 4. Background, which shares heavy's rank, is off the ladder and never returned.
func (BudgetClass) Limits ¶
func (c BudgetClass) Limits() (l ClassLimits, ok bool)
Limits is the class ceiling: light 150/80/16/2, balanced 800/200/64/8, heavy 3000/400/512/32, extreme 20000/1000/1024/128, background 2000/64/1152/128 (packets / pps / distinct ports / sockets). ok is false for an invalid class.
func (BudgetClass) MaxWindowMs ¶
func (c BudgetClass) MaxWindowMs() uint16
MaxWindowMs is the longest window_ms of a round of class c.
func (BudgetClass) Min ¶
func (c BudgetClass) Min(d BudgetClass) BudgetClass
Min is the lower-ranked of c and d; c on a tie.
func (BudgetClass) Rank ¶
func (c BudgetClass) Rank() int
Rank orders the classes: light 1, balanced 2, heavy and background 3, extreme 4; 0 for anything else. Consecutive rounds rise by at most one rank.
func (BudgetClass) RequiresExtreme ¶
func (c BudgetClass) RequiresExtreme() bool
RequiresExtreme reports whether the class needs AllowExtreme.
func (BudgetClass) Valid ¶
func (c BudgetClass) Valid() bool
Valid reports whether c is one of the five classes.
type CandKind ¶
type CandKind string
CandKind is PathInfo.CandKind: how the confirmed target was found.
const ( CandDirect CandKind = "direct" CandPredicted CandKind = "predicted" CandRandom CandKind = "random" CandBirthday CandKind = "birthday" CandPeerReflexive CandKind = "peer_reflexive" CandLAN CandKind = "lan" CandTargets CandKind = "targets" CandOverlay CandKind = "overlay" // an overlay address of the peer )
Candidate kinds.
type ClassLimits ¶
type ClassLimits struct {
MaxPackets uint32
MaxPPS uint16
MaxDistinctPorts uint16 // per peer IP per round
MaxSockets uint16
}
ClassLimits is the per-round ceiling of a BudgetClass, per side.
type ClientCaps ¶
type ClientCaps struct {
Impl string `json:"impl"` // "holepunch-go/1.0.0", <= 64 B
Families []FamilyCaps `json:"families"` // <= 2
MaxSockets uint16 `json:"max_sockets"` // sockets this host can use for the session
PortMap []PortMapMethod `json:"port_map,omitempty"` // enabled methods: pcp | natpmp | upnp
}
ClientCaps is probe_report.caps: this host's runtime capabilities for the session (not protocol semantics).
type ClockSample ¶
ClockSample is the minimum-RTT sample of the UDP probe path. The offset is diagnostic only: no protocol decision reads a wall clock.
type Conf ¶
type Conf uint8
Conf is a confidence level, ordered: none < low < medium < high.
func (Conf) MarshalText ¶
MarshalText encodes c as its wire name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (Conf) String ¶
String returns the wire name of c. The value receiver makes this method available on values as well as pointers.
func (*Conf) UnmarshalText ¶
UnmarshalText accepts exactly the wire names. Decoding uses a pointer receiver to update the value in place.
type ControlSpec ¶
type ControlSpec struct {
Version uint8 `json:"version"` // the control protocol's major version, 1
Features []Feature `json:"features,omitempty"` // server: offered; client: accepted
}
ControlSpec appears in punch_start.control (server offer) and probe_report.control (client echo of the accepted subset). There is no version range: Version must equal the frame header major exactly.
func DefaultControlSpec ¶
func DefaultControlSpec() ControlSpec
DefaultControlSpec is what a server offers: the protocol's version and every supported feature.
type Detail ¶
type Detail string
Detail is bounded diagnostic text attached to a progress report or failure.
type Endpoint ¶
type Endpoint struct {
Addr netip.AddrPort `json:"addr"`
Source EndpointSource `json:"src"`
Socket uint8 `json:"sock"`
Verified bool `json:"v"` // recorded by the server and its cookie echoed
}
Endpoint is a candidate address of a client.
func (Endpoint) VerifiedPublicPrimary ¶
VerifiedPublicPrimary reports whether e is a cookie-verified observer record for f's public primary socket.
type EndpointSource ¶
type EndpointSource string
EndpointSource says where an Endpoint comes from.
const ( EndpointServer EndpointSource = "server" EndpointSecond EndpointSource = "second" EndpointSibling EndpointSource = "sibling" EndpointSTUN EndpointSource = "stun" EndpointPortmap EndpointSource = "portmap" EndpointLAN EndpointSource = "lan" // EndpointOverlay is an overlay address of the client at its primary // socket's port (FamilyReport.Overlay). EndpointOverlay EndpointSource = "overlay" // EndpointLocalPort is the verified public IP at the primary socket's local // port, when natprobe saw that socket at another port: a NAT that keeps the // local port on the path toward the peer maps it there. A guess, never // verified. EndpointLocalPort EndpointSource = "local_port" )
Endpoint sources.
type EventName ¶
type EventName string
EventName names a diagnostic event in a session's progress or phase timeline.
type Family ¶
type Family string
Family is an address family.
func (Family) Index ¶
Index is f's index in arrays by family: 1 for udp6, 0 for udp4 and anything else.
func (Family) Matches ¶
Matches reports whether a belongs to f: an IPv4 address for udp4, an IPv6 address that is not IPv4-mapped for udp6. Plans and assists only carry addresses of the family they are about.
func (Family) UsableTarget ¶
UsableTarget reports whether a can be the destination of a packet a client initiates in family f: an address of f with a port that is not netaddr.Unusable (unspecified, multicast, the IPv4 broadcast, loopback or IPv6 link-local). Which of these a side may aim at is admission's call.
type FamilyAddition ¶
type FamilyAddition struct {
Self FamilyView `json:"self"`
Peer FamilyView `json:"peer"`
}
FamilyAddition carries the cookie-verified public primary endpoint of each peer and the measured traits of that family. Both sides have finished the corresponding local probe before the coordinator can send it.
type FamilyCaps ¶
type FamilyCaps struct {
Family Family `json:"family"`
LowTTL bool `json:"low_ttl"` // per-packet TTL / hop limit
RecvErr bool `json:"recv_err,omitempty"` // Linux IP_RECVERR (ICMP soft-signal counting)
}
FamilyCaps is one family's capabilities.
type FamilyOutcome ¶
type FamilyOutcome struct {
DistinctTargets uint16 `json:"distinct_targets,omitempty"` // distinct destination address/port pairs written this round
NewDestinations uint16 `json:"new_destinations,omitempty"` // first successful writes to public socket/destination pairs
Reserved uint32 `json:"reserved,omitempty"` // initiated packets charged against the round
Attempted uint32 `json:"attempted,omitempty"` // initiated datagram writes attempted
FirstWriteMs uint32 `json:"first_write_ms,omitempty"` // go read to first successful initiated write; meaningful with Sent > 0
Remap *Remap `json:"remap,omitempty"` // the primary socket's new mapping, re-observed this round
Family Family `json:"family"`
SeenFrom []netip.AddrPort `json:"seen_from,omitempty"` // peer sources seen this round, <= 4
Sent uint32 `json:"sent"`
Recv uint32 `json:"recv"`
DistinctPorts uint16 `json:"distinct_ports"`
ICMPUnreach uint16 `json:"icmp_unreach,omitempty"`
BindFailed uint16 `json:"bind_failed,omitempty"`
Rejected uint16 `json:"rejected,omitempty"` // targets admission refused this round
SocketsUsed uint16 `json:"sockets_used,omitempty"` // sockets available for stages, including fresh and paced binds
SocketLimit SocketLimit `json:"socket_limit,omitempty"`
Hit bool `json:"hit"` // a peer success was received
PeerSeenUs bool `json:"peer_seen_us"` // a peer_seen about us arrived this round
BudgetHit bool `json:"budget_hit,omitempty"`
Drift bool `json:"drift,omitempty"`
// Halted: the side stopped initiating in this family for the rest of
// the round on a spike of write or bind failures, as the slow birthday
// of a Background session does.
Halted bool `json:"halted,omitempty"`
}
FamilyOutcome is one family of round_result.
func (FamilyOutcome) Contact ¶
func (f FamilyOutcome) Contact() bool
Contact reports whether this side received an authenticated peer packet.
type FamilyReady ¶
type FamilyReady struct {
Family Family `json:"family"`
Sockets uint16 `json:"sockets"` // pre-bound sockets, primary included
Clamped bool `json:"clamped,omitempty"` // the plan was clamped locally
Rejected uint16 `json:"rejected,omitempty"` // targets removed by admission
PortMap *PortMapReport `json:"port_map,omitempty"` // port mapping finished after probe_report
}
FamilyReady is one family of punch_ready.
type FamilyReport ¶
type FamilyReport struct {
Family Family `json:"family"`
Failure Reason `json:"failure,omitempty"` // probe_timeout | udp_blocked | no_probe_endpoint | internal
Sockets []SocketReport `json:"sockets"` // [0] is the primary socket; <= 6
Filters []FilterReport `json:"filters,omitempty"` // <= 24
STUN []RowReport `json:"stun,omitempty"` // self-reported; <= 8
PortMap *PortMapReport `json:"port_map,omitempty"` // self-reported; later results go in punch_ready
// PortMapFailed: the port mapping attempt of the primary socket ended
// without a mapping, so punch_ready will carry none either.
PortMapFailed bool `json:"port_map_failed,omitempty"`
LocalAddrs []netip.Addr `json:"local_addrs,omitempty"` // <= 16; overlay addresses left out
// Overlay are the host's addresses of the family classified as overlay
// by hostaddr.IsOverlay, including addresses in 100.64.0.0/10. The primary
// socket listens on them and they form a separate class of candidates.
// Empty when the client excludes them or binds its primary socket to one
// address; <= 2.
Overlay []netip.Addr `json:"overlay,omitempty"`
Traits Traits `json:"traits"` // client provisional; the server recomputes
}
FamilyReport is one family of probe_report.families.
type FamilySide ¶
type FamilySide struct {
Family Family `json:"family"`
Role SideRole `json:"role"`
SendDelayMs uint16 `json:"send_delay_ms,omitempty"` // <= 3000
Sockets uint16 `json:"sockets"` // 1..256
MaxPackets uint32 `json:"max_packets"` // initiated packets this round
MaxPPS uint16 `json:"max_pps"` // <= 1500
MaxNewPerSec uint16 `json:"max_new_per_sec"` // <= 256
MaxDistinctPorts uint16 `json:"max_distinct_ports"` // per peer IP this round
// OpenPerSec paces the side's sockets beyond the primary: the k-th is
// opened k/OpenPerSec seconds after firing, sends its Direct stages then —
// each target's repeats spread over the rest of the window, so its mapping
// stays alive — and is closed when the round ends unless it heard the peer.
// 0 opens them all before firing, kept for later rounds. Set for the slow
// birthday of a Background session.
OpenPerSec uint16 `json:"open_per_sec,omitempty"`
// Sandwich runs the sandwich probe in this family, only when
// the feature was negotiated. It is per family: the coordinator matches
// a probe to the family whose round it brackets, so the two families of
// a dual-stack side never mix their windows.
Sandwich bool `json:"sandwich,omitempty"`
Stages []Stage `json:"stages"` // 1..8
}
FamilySide is one family's part of a round.
func (FamilySide) FreshSockets ¶
func (s FamilySide) FreshSockets() int
FreshSockets is how many fresh sockets the side binds this round: the Count of its fresh stage, 0 without one (StageFresh). They come on top of Sockets in every socket limit.
func (FamilySide) SocketsBeforeFiring ¶
func (s FamilySide) SocketsBeforeFiring() int
SocketsBeforeFiring is how many of the side's sockets a client binds before firing: all of them, or only the primary when they are paced (OpenPerSec).
type FamilyView ¶
type FamilyView struct {
Family Family `json:"family"`
Traits Traits `json:"traits"`
Endpoints []Endpoint `json:"endpoints"` // <= 12
}
FamilyView is one family of a PeerView.
type Feature ¶
type Feature string
Feature is an optional client behaviour offered in punch_start.control and echoed (accepted subset) in probe_report.control. Syntax [a-z][a-z0-9_]{0,31}; at most 16 per message; unknown names are ignored.
const FeatureLateFamily Feature = "late_family"
FeatureLateFamily permits adding a verified family after the summary.
const FeatureSandwich Feature = "sandwich" // execute FamilySide.sandwich
FeatureSandwich offers an experimental capability the operator may enable. Multiple rounds (preemption, rescue round), peer_seen assists, RTT alignment, server plans, ping/pong, round_result/punch_result and handover_ack are behaviour every implementation has, not features.
func AcceptFeatures ¶
AcceptFeatures is the client's echo: offered ∩ supported, exact match, duplicates removed, in offer order.
func SupportedFeatures ¶
func SupportedFeatures() []Feature
SupportedFeatures are the features this implementation understands.
type FilterReport ¶
type FilterReport struct {
Socket uint8 `json:"socket"`
Observer uint8 `json:"observer"`
ExtraSeen uint8 `json:"extra_seen"`
AltSeen uint8 `json:"alt_seen"`
}
FilterReport counts extra/alt replies seen by the client.
type Filtering ¶
type Filtering uint8
Filtering is the NAT filtering behaviour: unknown | eif | adf | pdf | not_pdf (EIF and ADF cannot be told apart with a single server IP).
func (Filtering) MarshalText ¶
MarshalText encodes f as its wire name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (Filtering) String ¶
String returns the wire name of f. The value receiver makes this method available on values as well as pointers.
func (*Filtering) UnmarshalText ¶
UnmarshalText accepts exactly the wire names. Decoding uses a pointer receiver to update the value in place.
type HandoverEvidence ¶
type HandoverEvidence string
HandoverEvidence is PathInfo.ConfirmedBy: what completed the UDP handover.
const ( ConfirmedByAck HandoverEvidence = "ack" ConfirmedByUpperLayer HandoverEvidence = "upper_layer" ConfirmedByQuiet HandoverEvidence = "quiet" ConfirmedByReady HandoverEvidence = "ready" )
Handover evidence.
type Mapping ¶
type Mapping uint8
Mapping is the NAT mapping behaviour: unknown | eim | adm | apdm.
const ( MapUnknown Mapping = iota MapEIM // endpoint-independent MapADM // address-dependent MapAPDM // address-and-port-dependent )
Mapping values.
func (Mapping) MarshalText ¶
MarshalText encodes m as its wire name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (Mapping) String ¶
String returns the wire name of m. The value receiver makes this method available on values as well as pointers.
func (*Mapping) UnmarshalText ¶
UnmarshalText accepts exactly the wire names. Decoding uses a pointer receiver to update the value in place.
type Message ¶
type Message interface {
// MessageType is the frame type the message travels in.
MessageType() MessageType
// Validate checks the message's structure: required fields, enumeration
// values, string and list lengths. Numeric limits that the receiver clamps
// are not errors; see Normalize.
Validate() error
}
Message is implemented by the twelve message types (values and pointers). Each type also has a Normalize method, which returns the message with the receiver-side clamps applied and whether a value changed.
func Decode ¶
func Decode(t MessageType, payload []byte) (Message, error)
Decode decodes and validates the payload of a frame of type t, any of the twelve message types, and returns a pointer to the message (*PunchStart, *ProbeReport, ...), ready for Normalize. Type 0 and the reserved types return ErrUnexpectedMessage.
type MessageType ¶
type MessageType uint8
MessageType is the type byte of a control frame. The twelve types are numbered contiguously from 1; 13–255 are reserved. MaxPayload gives each type's payload cap.
func (MessageType) Known ¶
func (t MessageType) Known() bool
Known reports whether t is one of the twelve message types.
func (MessageType) MaxPayload ¶
func (t MessageType) MaxPayload() int
MaxPayload is the type's payload cap.
func (MessageType) String ¶
func (t MessageType) String() string
String is the wire name of the type ("punch_go"), or "type(N)".
type ObserverSpec ¶
type ObserverSpec struct {
Addr netip.AddrPort `json:"addr"` // literal ip:port
ID uint8 `json:"id"`
Group uint8 `json:"group"` // same group = same server public IP
Alt bool `json:"alt,omitempty"`
}
ObserverSpec is one natprobe observer.
type PairClass ¶
type PairClass string
PairClass names a ladder selected from the pair's observed NAT traits.
type PairFacts ¶
type PairFacts struct {
SamePublicIP map[Family]bool `json:"same_public_ip,omitempty"`
LikelySameLAN map[Family]bool `json:"same_lan,omitempty"`
// SharedOverlay marks the families in which both clients reported
// overlay addresses: each may aim at the other's.
ProbeRTTMs map[Role]uint32 `json:"probe_rtt_ms,omitempty"` // by role
ClockOffsetMs map[Role]int64 `json:"clock_offset_ms,omitempty"` // by role; diagnostic
// Unverified marks the families whose peer endpoints the server could not
// verify: every family when the coordinator runs without a natprobe
// registry, or a family the server has no observer for. Such a
// family carries only Direct stages to self-reported global addresses.
Unverified map[Family]bool `json:"unverified,omitempty"`
}
PairFacts holds what only a server seeing both clients can compute.
type PathInfo ¶
type PathInfo struct {
Family Family `json:"family"`
Local netip.AddrPort `json:"local"`
Remote netip.AddrPort `json:"remote"`
Epoch uint16 `json:"epoch"`
Round uint8 `json:"round"`
Sock uint8 `json:"sock"`
Cand uint16 `json:"cand"`
RTTMs uint16 `json:"rtt_ms"` // UDP path RTT
CandKind CandKind `json:"cand_kind"`
Kind PathKind `json:"kind"` // the network the path runs over
ConfirmedBy HandoverEvidence `json:"confirmed_by,omitempty"` // punch_result only
}
PathInfo is a confirmed path: the primary path of round_result and punch_result, or one of punch_result.extra_paths.
type PathKind ¶
type PathKind string
PathKind is PathInfo.Kind: what kind of network a confirmed path runs over, so that a caller can tell a tunnel from a direct path.
const ( PathPublic PathKind = "public" // through the public Internet: observed, predicted or sprayed mappings PathLAN PathKind = "lan" // a LAN the two clients share PathOverlay PathKind = "overlay" // an overlay or tunnel network both clients are on PathPortmap PathKind = "portmap" // a port mapping of the peer's gateway (UPnP, NAT-PMP, PCP) )
Path kinds.
type PeerView ¶
type PeerView struct {
Families []FamilyView `json:"families"` // <= 2
}
PeerView is the server's authoritative view of one client.
type Phase ¶
type Phase string
Phase is the client session phase. It is the value of punch_result.phase and of the client API's phase.
const ( PhaseCreated Phase = "created" // Punch called PhaseProbing Phase = "probing" // punch_start accepted PhaseReported Phase = "reported" // probe_report written PhasePlanned Phase = "planned" // summary accepted, sockets pre-bound PhaseReady Phase = "ready" // punch_ready written PhasePunching Phase = "punching" // a go's delay elapsed; also between rounds PhaseNegotiating Phase = "negotiating" // first success or nomination PhaseConfirmed Phase = "confirmed" // local Confirm, round_result{confirmed} sent PhaseHandover Phase = "handover" // waiting for / sending handover_ack PhaseDone Phase = "done" // handed over; terminal PhaseFailed Phase = "failed" // terminal )
Phase values.
type Ping ¶
type Ping struct {
Seq uint8 `json:"seq"` // 1..8, increasing per link
}
Ping asks for a pong; answered in every phase.
type PlanSpec ¶
type PlanSpec struct {
ID string `json:"id"` // 1..64 B of [A-Za-z0-9_-]
PairClass PairClass `json:"pair_class"` // diagnostic name, e.g. "pdf_x_seq"
Ladder []string `json:"ladder,omitempty"` // informative; <= 16 names
Budget Budget `json:"budget"` // this side's session budget
Round1 RoundPlan `json:"round1"` // the first round, for pre-binding
// Mode is the session's mode: background only when the server offered
// it and both clients accepted it.
Mode SessionMode `json:"mode,omitempty"`
// Advice is what to do should the session fail.
Advice Advice `json:"advice,omitempty"`
RoundsMax uint8 `json:"rounds_max"` // 1..6 (<= timeouts.max_rounds; rescue not counted)
// BackgroundOnly: the server's strategy memory saw this pair of exits
// connect only through the slow birthday of a Background session; the
// caller may go to the relay and Background at once.
BackgroundOnly bool `json:"background_only,omitempty"`
}
PlanSpec is probe_summary.plan.
type Policy ¶
type Policy struct {
Budget Budget `json:"budget"`
PortMapping PortMappingPolicy `json:"port_mapping"`
LowTTL *bool `json:"low_ttl,omitempty"` // nil: as the plan says
LowTTLHops []int `json:"low_ttl_hops,omitempty"` // clamped to [2,32]; default {4,7}; <= 8 entries
}
Policy is a side's session policy: punch_start.policy from the server and holepunch.Options.Sockets.Limits locally. Policies only ever tighten: CeilingBudget ≥ punch_start.policy ≥ summary.plan.budget ≥ each round's FamilySide ≥ Options.Sockets.Limits. See Tighten.
func Tighten ¶
Tighten merges the server's policy (punch_start.policy) with the local one (Options.Sockets.Limits); either may be nil. The local policy can only tighten:
- Budget: TightenBudget(server.Budget, local.Budget);
- LowTTL and the port-mapping switches: AND, nil inherits the other side, both nil stays nil;
- LowTTLHops: the server's set (default {4,7}) clamped to [2,32]; a local set keeps only the hops the server allows, and if none is left low TTL is switched off;
- LeaseSeconds: the smaller non-zero value.
type Pong ¶
type Pong struct {
Seq uint8 `json:"seq"` // echoed
HoldUs uint32 `json:"hold_us"` // ping read → pong written, local monotonic
ClientUnixMs int64 `json:"client_unix_ms"` // the client's wall clock; diagnostic only
}
Pong answers a ping.
func PongFor ¶
PongFor is the answer to ping p read at readAt (Frame.At) and written at now: hold_us covers the local time between the two (the server subtracts it from the RTT sample); client_unix_ms is now's wall clock, for clock-skew diagnostics only.
type PortAlloc ¶
type PortAlloc uint8
PortAlloc is the external port allocation: unknown | preserving | sequential | pool | random | preserve_fresh.
const ( AllocUnknown PortAlloc = iota AllocPreserving AllocSequential AllocPool AllocRandom // AllocPreserveFresh is an endpoint-dependent allocator whose fresh // socket keeps its local port for its first mapping, while the later // mappings of the same socket get other ports: the first mapping of a // socket bound at a chosen port is known // in advance. AllocPreserveFresh )
PortAlloc values.
func (PortAlloc) MarshalText ¶
MarshalText encodes a as its wire name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (PortAlloc) String ¶
String returns the wire name of a. The value receiver makes this method available on values as well as pointers.
func (*PortAlloc) UnmarshalText ¶
UnmarshalText accepts exactly the wire names. Decoding uses a pointer receiver to update the value in place.
type PortMapMethod ¶
type PortMapMethod string
PortMapMethod is the port-mapping protocol that produced a mapping.
const ( PortMapUPnP PortMapMethod = "upnp" PortMapPCP PortMapMethod = "pcp" PortMapNATPMP PortMapMethod = "natpmp" )
Port-mapping methods.
func (PortMapMethod) Valid ¶
func (m PortMapMethod) Valid() bool
Valid reports whether m is one of the three methods.
type PortMapReport ¶
type PortMapReport struct {
Method PortMapMethod `json:"method"`
External netip.AddrPort `json:"external,omitzero"`
Internal netip.AddrPort `json:"internal,omitzero"`
LeaseSeconds uint32 `json:"lease_seconds"`
}
PortMapReport is a port-mapping result on the wire (port_map).
type PortMappingInfo ¶
type PortMappingInfo struct {
Method PortMapMethod
External netip.AddrPort
Internal netip.AddrPort
Lease time.Duration
}
PortMappingInfo is the port mapping held by a session (holepunch Result, portmapper.Mapper.Map). Report gives its wire form.
func (PortMappingInfo) Report ¶
func (i PortMappingInfo) Report() PortMapReport
Report is the wire form of i; the lease is rounded down to whole seconds.
type PortMappingPolicy ¶
type PortMappingPolicy struct {
EnableUPnP *bool `json:"upnp,omitempty"`
EnablePCP *bool `json:"pcp,omitempty"`
EnableNATPMP *bool `json:"natpmp,omitempty"`
LeaseSeconds uint32 `json:"lease_seconds,omitempty"` // 0: DefaultPortMapLease
}
PortMappingPolicy enables port-mapping methods. A nil switch inherits the other level in Tighten and means "enabled" when the policy is applied.
func (PortMappingPolicy) Clone ¶
func (p PortMappingPolicy) Clone() PortMappingPolicy
Clone returns a deep copy of p.
func (PortMappingPolicy) Enabled ¶
func (p PortMappingPolicy) Enabled(m PortMapMethod) bool
Enabled reports whether method m may be used; unset switches are on.
func (PortMappingPolicy) Lease ¶
func (p PortMappingPolicy) Lease() time.Duration
Lease is the lease to request.
type PortWindow ¶
type PortWindow struct {
IP netip.Addr `json:"ip"`
Lo uint16 `json:"lo"`
Hi uint16 `json:"hi"` // hi - lo <= 63
}
PortWindow is a port window pushed by peer_targets.
type ProbeReport ¶
type ProbeReport struct {
SessionID string `json:"session_id"`
Role Role `json:"role"` // consistency check only
Control ControlSpec `json:"control"` // version + accepted features
Caps ClientCaps `json:"caps"`
ElapsedMs uint32 `json:"elapsed_ms"` // punch_start received → this frame written (an RTT sample)
// Early marks a cumulative report before all families finish. Warm
// permits reporting a first ACK with no traits. Incremental permits
// reporting completed measurements (Traits.Samples > 0). The final
// report replaces all earlier ones and carries pending port mappings.
Early bool `json:"early,omitempty"`
Families []FamilyReport `json:"families"` // 1..2
Clock ClockSample `json:"clock"`
Transport Transport `json:"transport"`
// Mode is the mode this client accepts: background only when
// punch_start offered it and the caller asked for it.
Mode SessionMode `json:"mode,omitempty"`
}
ProbeReport carries the client's probe results. It is not sent when probing failed for every family (punch_result{ok:false} instead).
func (ProbeReport) LogValue ¶
func (m ProbeReport) LogValue() slog.Value
LogValue implements slog.LogValuer without transport data.
func (ProbeReport) MessageType ¶
func (ProbeReport) MessageType() MessageType
MessageType implements Message.
func (ProbeReport) Normalize ¶
func (m ProbeReport) Normalize() (ProbeReport, bool)
Normalize clamps caps.max_sockets to 256.
type ProbeSpec ¶
type ProbeSpec struct {
// Families restricts probing and punching to the listed address families.
// An empty list allows both.
Families []Family `json:"families,omitempty"`
Observers []ObserverSpec `json:"observers"` // <= 16
STUN []netip.AddrPort `json:"stun,omitempty"` // <= MaxProbeSTUN; literal addresses
RTTHintMs uint16 `json:"rtt_hint_ms,omitempty"` // known control-link RTT; omitted when unknown
V uint8 `json:"v"` // ProbeSpecVersion
ExtraReply bool `json:"extra"` // hint only; the ack declares what is really sent
SecondSocket bool `json:"second_socket"` // probe a second socket when APDM is suspected
Siblings uint8 `json:"siblings"` // sibling interfaces to probe, clamped to 2
// Warm asks for an early probe_report as soon as the primary socket of
// one family has an answer. The server may plan on it and the NAT traits
// it remembers of this client while probing continues to the final report.
Warm bool `json:"warm,omitempty"`
// Incremental permits a completed family to be reported while another
// is probing and permits cumulative early reports. The coordinator verifies
// the current primary observation.
Incremental bool `json:"incremental,omitempty"`
}
ProbeSpec is punch_start.probe.
type ProbeSummary ¶
type ProbeSummary struct {
SessionID string `json:"session_id"`
Self PeerView `json:"self"` // the receiver as the server sees it
Peer PeerView `json:"peer"` // endpoints: verified or constrained self-reported
Pair PairFacts `json:"pair"`
Transport TransportPick `json:"transport"`
Timeouts Timeouts `json:"timeouts"` // only tighter than punch_start's
Plan PlanSpec `json:"plan"`
}
ProbeSummary is the server's merged view and the first round's plan.
func (ProbeSummary) LogValue ¶
func (m ProbeSummary) LogValue() slog.Value
LogValue implements slog.LogValuer without the peer's transport data.
func (ProbeSummary) MessageType ¶
func (ProbeSummary) MessageType() MessageType
MessageType implements Message.
func (ProbeSummary) Normalize ¶
func (m ProbeSummary) Normalize() (ProbeSummary, bool)
Normalize clamps the timeouts and the plan.
type Progress ¶
type Progress struct {
Counters map[string]uint32 `json:"counters,omitempty"` // <= 16 keys
Meta map[string]string `json:"meta,omitempty"` // <= 16 keys, values <= 64 B; caller pass-through
SessionID string `json:"session_id"`
Role Role `json:"role"`
Stage EventName `json:"stage"` // open enumeration, [a-z][a-z0-9_]{0,63}
Status ProgressStatus `json:"status,omitempty"`
Detail Detail `json:"detail,omitempty"` // <= 128 B
AtMs uint32 `json:"at_ms"` // since punch_start, monotonic
Seq uint16 `json:"seq"` // sender's monotonic sequence
Round uint8 `json:"round,omitempty"` // <= 8
}
Progress is telemetry: droppable, rate limited, never an input of any server decision.
func (Progress) MessageType ¶
func (Progress) MessageType() MessageType
MessageType implements Message.
type ProgressStatus ¶
type ProgressStatus string
ProgressStatus is Progress.Status.
const ( StatusOK ProgressStatus = "ok" StatusFail ProgressStatus = "fail" StatusInfo ProgressStatus = "info" )
Progress statuses.
type PunchGo ¶
type PunchGo struct {
// Retry replaces both summary fields together after reclassification.
Retry *RetryHint `json:"retry,omitempty"`
// AddFamily introduces one newly verified family from round two onward.
// It travels with every go using that family, so a skipped go is harmless.
AddFamily *FamilyAddition `json:"add_family,omitempty"`
Plan *RoundPlan `json:"plan,omitempty"` // round 1: absent (the plan is summary.plan.round1); round >= 2: required
SessionID string `json:"session_id"`
DelayMs uint16 `json:"delay_ms"` // clamped to [0, 2000]
WindowMs uint16 `json:"window_ms"` // = plan.window_ms; clamped to 10000, 45000 for a background round
RTTMs uint16 `json:"rtt_ms,omitempty"` // server's estimate of this link's RTT
Round uint8 `json:"round"` // 1..8, strictly increasing; a larger round preempts
Final bool `json:"final,omitempty"`
}
PunchGo starts a round: fire at (the instant the frame was read) + DelayMs.
func (PunchGo) MessageType ¶
func (PunchGo) MessageType() MessageType
MessageType implements Message.
type PunchReady ¶
type PunchReady struct {
SessionID string `json:"session_id"`
Role Role `json:"role"`
ElapsedMs uint32 `json:"elapsed_ms"` // summary received → this frame written (an RTT sample)
Families []FamilyReady `json:"families"` // 1..2
}
PunchReady reports that the sockets for round 1 are bound.
func (PunchReady) MessageType ¶
func (PunchReady) MessageType() MessageType
MessageType implements Message.
func (PunchReady) Normalize ¶
func (m PunchReady) Normalize() (PunchReady, bool)
Normalize implements the clamps of punch_ready (none).
type PunchResult ¶
type PunchResult struct {
SessionID string `json:"session_id"`
Role Role `json:"role"`
Reason Reason `json:"code,omitempty"` // required when !ok
Phase Phase `json:"phase"` // the client phase at the end
Detail Detail `json:"detail,omitempty"` // <= 256 B, human-readable, no key material
Path *PathInfo `json:"path,omitempty"` // required when ok, with confirmed_by
ExtraPaths []PathInfo `json:"extra_paths,omitempty"` // only when ok: the other paths handed over with Path, <= MaxPaths-1, each with confirmed_by
Stats Stats `json:"stats"`
OK bool `json:"ok"`
Timing Timing `json:"timing"`
Traits []TraitsUpdate `json:"traits,omitempty"` // <= 2: corrections of this side's traits
Warn []Warning `json:"warn,omitempty"` // <= 8
}
PunchResult is a client's terminal report (success after the UDP handover, failure or cancellation before cleanup), best effort with a bounded flush.
func (PunchResult) MessageType ¶
func (PunchResult) MessageType() MessageType
MessageType implements Message.
func (PunchResult) Normalize ¶
func (m PunchResult) Normalize() (PunchResult, bool)
Normalize truncates stats.drops to 16 keys.
type PunchStart ¶
type PunchStart struct {
SessionID string `json:"session_id"` // 1..64 bytes of [A-Za-z0-9_-]
Role Role `json:"role"` // the receiver's role; the peer's is Role.Peer()
Token Token `json:"token"` // base64url of 32 random bytes
Control ControlSpec `json:"control"` // version == frame major; features offered
Probe ProbeSpec `json:"probe"`
Wire WireSpec `json:"wire"`
Timeouts Timeouts `json:"timeouts"`
Policy *Policy `json:"policy,omitempty"` // this side's ceiling; the client may only tighten
// Mode is the server's offer: background
// only when the caller of the coordinator runs the session behind a
// relay; "" is interactive. The client may only decline it.
Mode SessionMode `json:"mode,omitempty"`
}
PunchStart opens a session on a control link: the first library frame. Token and route appear on the wire only here; its LogValue redacts them.
func (PunchStart) LogValue ¶
func (m PunchStart) LogValue() slog.Value
LogValue implements slog.LogValuer without the token and the full route.
func (PunchStart) MessageType ¶
func (PunchStart) MessageType() MessageType
MessageType implements Message.
func (PunchStart) Normalize ¶
func (m PunchStart) Normalize() (PunchStart, bool)
Normalize clamps the wire range and the timeouts, the sibling count and the policy (budget to CeilingBudget, low-TTL hops to [2,32]).
type Reason ¶
type Reason string
Reason is the single failure-code enumeration of holepunch: the client's *Error.Reason, coord.Result.Reason and the wire field code of punch_result, round_result and punch_abort. Only the 26 names below exist on the wire; a receiver treats any other code as unknown: a punch_abort carrying one fails the client with aborted_by_server or aborted_by_peer. Fine-grained information goes into a separate detail string.
Reason is a plain wire code, not an error: errors carry it in a field, such as holepunch's *Error and *ValidationError, and are matched with errors.As.
const ( ReasonNoCommonFamily Reason = "no_common_family" ReasonNoProbeEndpoint Reason = "no_probe_endpoint" ReasonProbeTimeout Reason = "probe_timeout" ReasonUDPBlocked Reason = "udp_blocked" ReasonLocalPortBindFailed Reason = "local_port_bind_failed" ReasonControlInterrupted Reason = "control_interrupted" ReasonControlTimeout Reason = "control_timeout" ReasonNotSynchronized Reason = "not_synchronized" ReasonOneWayUDPOnly Reason = "one_way_udp_only" ReasonTokenMismatch Reason = "token_mismatch" ReasonCandidateTimeout Reason = "candidate_timeout" ReasonHardSymmetricRandom Reason = "hard_symmetric_random" ReasonPacketBudgetExceeded Reason = "packet_budget_exceeded" ReasonHandoverTimeout Reason = "handover_timeout" ReasonControlVersionMismatch Reason = "control_version_mismatch" ReasonProtocolViolation Reason = "protocol_violation" ReasonInvalidArgument Reason = "invalid_argument" ReasonPeerOffline Reason = "peer_offline" ReasonSessionExpired Reason = "session_expired" ReasonServerBusy Reason = "server_busy" ReasonServerShutdown Reason = "server_shutdown" ReasonTransportMismatch Reason = "transport_mismatch" ReasonAbortedByPeer Reason = "aborted_by_peer" ReasonAbortedByServer Reason = "aborted_by_server" ReasonCanceled Reason = "canceled" ReasonInternal Reason = "internal" )
The 26 reasons.
func (Reason) Class ¶
func (r Reason) Class() ReasonClass
Class is r's class; ClassNone for an unknown reason.
type ReasonClass ¶
type ReasonClass uint8
ReasonClass groups protocol failures as unknown, fatal, transient, hard NAT or canceled. The path supervisor uses these classes and server retry hints.
const ( ClassNone ReasonClass = iota ClassFatal ClassTransient ClassNATHard ClassCanceled )
Reason classes.
func (ReasonClass) MarshalText ¶
func (c ReasonClass) MarshalText() ([]byte, error)
MarshalText encodes c as its name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (ReasonClass) String ¶
func (c ReasonClass) String() string
String returns the wire name of c. The value receiver makes this method available on values as well as pointers.
func (*ReasonClass) UnmarshalText ¶
func (c *ReasonClass) UnmarshalText(b []byte) error
UnmarshalText accepts exactly the names. Decoding uses a pointer receiver to update the value in place.
type Remap ¶
type Remap struct {
Observed netip.AddrPort `json:"a"`
Observer uint8 `json:"o"`
Cookie uint32 `json:"c"`
}
Remap is a new mapping of a family's primary socket that the client re-observed in a round without contact: observer Observer's probe_ack showed Observed. Cookie echoes that ack's COOKIE, so the server can verify the mapping as it verifies the probe's: only a client that receives at Observed can know it.
type RetryHint ¶
type RetryHint struct {
PairClass PairClass `json:"pair_class,omitempty"`
Advice Advice `json:"advice,omitempty"`
}
RetryHint is the coordinator's current classification and failure advice. The pair class describes the primary family. Advice covers all families.
type Role ¶
type Role string
Role is a session role. RoleServer only appears in Abort.By and Assist.From.
const ( RoleInitiator Role = "initiator" RoleResponder Role = "responder" RoleServer Role = "server" )
Role values.
func (Role) Code ¶
Code is the role code in the UDP payload header: 1 initiator, 2 responder, 3 server, 0 otherwise. The spray seed's info string uses it too.
type RoundPlan ¶
type RoundPlan struct {
Round uint8 `json:"round"` // 1..8 (rescue rounds take a number too)
Variant string `json:"variant"` // diagnostic / memory name
Budget BudgetClass `json:"budget"` // the round's ceiling class
WindowMs uint16 `json:"window_ms"` // from firing; <= 10000
Final bool `json:"final,omitempty"` // no round follows
Rescue bool `json:"rescue,omitempty"` // rescue round
Seed uint32 `json:"seed"` // server random; input of the spray seed
Sides []FamilySide `json:"sides"` // 1..2, this side only
}
RoundPlan is one round for this side.
func (RoundPlan) CheckAnchorUpdate ¶
CheckAnchorUpdate reports whether u, the plan a round-1 go carries, is r — the summary's round-1 plan — re-aimed as Reanchor does, in any number of its predict stages, and otherwise the same: the same sides, stages, sockets, limits and window. Anything else is a protocol_violation with detail round1_plan.
func (RoundPlan) ClampTo ¶
ClampTo limits every side of the round to the session budget b (zero fields of b do not limit): sockets, max_packets, max_pps and max_new_per_sec. It is the "only tighter" step between summary.plan.budget (or the merged policy) and each round's FamilySide.
func (RoundPlan) Normalize ¶
Normalize clamps a round to the protocol limits and to the ceiling of its BudgetClass: window_ms <= 10000; per side send_delay_ms <= 3000, sockets <= min(256, class), max_packets <= min(40000, class), max_pps <= min(1500, class), max_new_per_sec <= 256, max_distinct_ports <= class, at most 8 stages; per stage at most 16 targets and 3 steps, span and count <= 4096, repeats <= 8, ttl in {0} ∪ [2,64].
func (RoundPlan) Reanchor ¶
Reanchor returns the plan with the predict stage si of family side fi aimed at anchor over span, which must be at least 1 and at most the stage's span; otherwise, or for another kind of stage, the plan comes back as it is. The positions a shorter span cuts leave the side's MaxPackets and MaxDistinctPorts, which stay what the stages expand to. The plan's slices are copied, never written.
type RoundResult ¶
type RoundResult struct {
Path *PathInfo `json:"path,omitempty"` // required when confirmed
SessionID string `json:"session_id"`
Role Role `json:"role"`
Status RoundStatus `json:"status"`
Reason Reason `json:"code,omitempty"` // status fatal: udp_blocked | local_port_bind_failed | ...
Families []FamilyOutcome `json:"families"` // <= 2
ElapsedMs uint32 `json:"elapsed_ms"` // the round's punch_go read → this frame written (sample Sk)
FireSkewMs int16 `json:"fire_skew_ms"` // actual fire − (t_recv + delay_ms)
Round uint8 `json:"round"` // 1..8
}
RoundResult reports a round: at window end, on budget exhaustion, on a fatal local error, and immediately on local Confirm (status confirmed — the server's signal to stop new rounds and wind down). A preempted round sends none.
func (RoundResult) MessageType ¶
func (RoundResult) MessageType() MessageType
MessageType implements Message.
func (RoundResult) Normalize ¶
func (m RoundResult) Normalize() (RoundResult, bool)
Normalize implements the clamps of round_result (none).
type RoundStatus ¶
type RoundStatus string
RoundStatus is RoundResult.Status.
const ( RoundWindowEnd RoundStatus = "window_end" RoundBudgetExhausted RoundStatus = "budget_exhausted" RoundConfirmed RoundStatus = "confirmed" // sent at the instant of local Confirm RoundFatal RoundStatus = "fatal" )
Round statuses.
type RouteID ¶
type RouteID [16]byte
RouteID is the session route of punch_start.wire: 16 random bytes, the HKDF salt and natprobe's lookup key. On the wire it is base64url without padding; String shows only the first 4 hex digits.
func (RouteID) Format ¶
Format keeps every fmt verb to the loggable prefix. The value receiver makes this method available on values as well as pointers.
func (RouteID) GoString ¶
GoString keeps %#v to the loggable prefix. The value receiver makes this method available on values as well as pointers.
func (RouteID) IsZero ¶
IsZero reports whether r is unset. The value receiver makes this method available on values as well as pointers.
func (RouteID) LogValue ¶
LogValue keeps log/slog to the loggable prefix. The value receiver makes this method available on values as well as pointers.
func (RouteID) MarshalText ¶
MarshalText returns the wire form: base64url without padding. The value receiver makes this method available on values as well as pointers.
func (RouteID) String ¶
String returns the loggable prefix of the route: its first 4 hex digits. The value receiver makes this method available on values as well as pointers.
func (*RouteID) UnmarshalText ¶
UnmarshalText accepts exactly the canonical base64url of 16 bytes. Decoding uses a pointer receiver to update the value in place.
type RowReport ¶
type RowReport struct {
Observed netip.AddrPort `json:"a,omitzero"` // the value in the ack (the server overrides it)
FirstSeq uint32 `json:"tx"` // seq of the row's first probe
SentMs uint32 `json:"s"` // relative to the probe start
Observer uint8 `json:"o"`
RTTMs uint16 `json:"rtt,omitempty"` // 0 = no ack
Cookie uint32 `json:"c,omitempty"` // COOKIE of the row's latest ack; 0 = no ack
}
RowReport is one (socket, observer) observation.
type SessionMode ¶
type SessionMode string
SessionMode says whether anyone waits for a session: interactive | background. The empty value is interactive.
const ( // ModeInteractive means the caller waits for the session; the ladder // fails fast. The default. ModeInteractive SessionMode = "interactive" // ModeBackground means a relay already serves the caller and nobody // waits; a PDF × RND pair may run the slow birthday (BudgetBackground). ModeBackground SessionMode = "background" )
Session modes.
func (SessionMode) Valid ¶
func (m SessionMode) Valid() bool
Valid reports whether m is empty or one of the modes.
type SocketKind ¶
type SocketKind string
SocketKind is SocketReport.Kind.
const ( SocketPrimary SocketKind = "primary" SocketSecond SocketKind = "second" SocketSibling SocketKind = "sibling" )
Socket kinds.
type SocketLimit ¶
type SocketLimit uint8
SocketLimit identifies the resources that reduced a family socket request.
const ( SocketLimitClass SocketLimit = 1 << iota // per-round class or protocol ceiling SocketLimitBudget // session socket budget or remaining slots SocketLimitIndex // remaining wire indexes in the family )
Socket limits may apply together.
type SocketReport ¶
type SocketReport struct {
ID uint8 `json:"id"` // sock = family<<7 | index
Kind SocketKind `json:"kind"`
Local netip.AddrPort `json:"local"`
Rows []RowReport `json:"rows"` // one per observer (first value); <= 16
}
SocketReport is one probed socket.
type Stage ¶
type Stage struct {
Kind StageKind `json:"kind"`
Targets []netip.AddrPort `json:"targets,omitempty"` // direct: <= 16
Steps []int16 `json:"steps,omitempty"` // predict steps, <= 3, may be negative
IP netip.Addr `json:"ip,omitzero"` // predict / random target IP
AtMs uint16 `json:"at_ms"` // relative to firing
Anchor uint16 `json:"anchor,omitempty"` // predict start port
Span uint16 `json:"span,omitempty"` // predict ports, <= 4096
Count uint16 `json:"count,omitempty"` // random ports, <= 4096
Lo uint16 `json:"lo,omitempty"` // random range low (optional)
Hi uint16 `json:"hi,omitempty"` // random range high (optional; 0 = 65535)
Repeats uint8 `json:"repeats,omitempty"` // direct repeats per target, <= 8
TTL uint8 `json:"ttl,omitempty"` // 0 = system default; [2,64] = low TTL for initiated packets
// Pair marks a paired predict stage, the predict stage of seq_x_seq: its
// ports are the Span ports Anchor+Steps[0]·1 … Anchor+Steps[0]·Span,
// wrapping inside [1024, 65535] — exactly where the peer's sequential NAT
// allocates the mappings of the peer's own paired stage — sent in an order
// both sides draw from the initiator's spray seed of the round, so that
// their mappings target each other in pairs.
// Only a predict stage may be paired.
Pair bool `json:"pair,omitempty"`
}
Stage is one stage of a round.
type StageKind ¶
type StageKind string
StageKind is Stage.Kind.
const ( StageDirect StageKind = "direct" StagePredict StageKind = "predict" StageRandom StageKind = "random" StageReplyOnly StageKind = "reply_only" // StageFresh binds Count fresh sockets, beyond the side's Sockets, at // the local ports FreshPorts draws from the initiator's spray seed of // the round, on a NAT whose fresh socket keeps its local port for its // first mapping (AllocPreserveFresh). Each // sends Repeats packets to every one of Targets — the peer's endpoints // — or, when IP is set instead (the peer runs a fresh stage too), to // IP and the port of the same draw. They are released at the round's // end unless they heard the peer. StageFresh StageKind = "fresh" // StageFreshPeer aims at the peer's fresh sockets: Repeats packets from // the primary socket to IP and each of the Count ports of the same draw. StageFreshPeer StageKind = "fresh_peer" )
Stage kinds.
type Stats ¶
type Stats struct {
Drops map[string]uint32 `json:"drops"` // keys: DropKeys; unknown keys are kept (forward compatible)
Sent uint32 `json:"sent"`
Recv uint32 `json:"recv"`
Replies uint32 `json:"replies"`
Rounds uint8 `json:"rounds"`
Hits uint8 `json:"hits"`
BudgetHit bool `json:"budget_hit,omitempty"`
}
Stats are punch_result.stats.
type TargetSource ¶
type TargetSource string
TargetSource is Assist.Source: why the server pushes peer_targets.
const ( TargetsSandwich TargetSource = "sandwich" TargetsInject TargetSource = "inject" TargetsDrift TargetSource = "drift" TargetsPortmap TargetSource = "portmap" )
Target sources.
type Timeouts ¶
type Timeouts struct {
ProbeTimeoutMs uint32 `json:"probe_timeout_ms"` // default 2000, [500, 10000]
SummaryWaitMs uint32 `json:"summary_wait_ms"` // server promise from writing punch_start; default 20000, [1000, 60000]
GoWaitMs uint32 `json:"go_wait_ms"` // ready → first go, and between rounds; default 5000, [500, 15000]
HandshakeTimeoutMs uint32 `json:"handshake_timeout_ms"` // from the first punch_go, all rounds; default 20000, [2000, 60000]
HandoverTimeoutMs uint32 `json:"handover_timeout_ms"` // from local Confirm; default 2000, [500, 10000]
TransportTimeoutMs uint32 `json:"transport_timeout_ms"` // passed through to the caller; default 10000, [1000, 60000]
MaxRounds uint8 `json:"max_rounds"` // default 5, [1, 6]; excludes the one rescue round
}
Timeouts are the protocol timeouts in milliseconds. Zero fields mean the default; Normalize clamps to the ranges below.
func DefaultTimeouts ¶
func DefaultTimeouts() Timeouts
DefaultTimeouts are the defaults of every field.
type Timing ¶
type Timing struct {
ProbeMs uint32 `json:"probe_ms"`
SummaryWaitMs uint32 `json:"summary_wait_ms"`
GoWaitMs uint32 `json:"go_wait_ms"`
PunchMs uint32 `json:"punch_ms"`
HandoverMs uint32 `json:"handover_ms"`
}
Timing is punch_result.timing.
type Token ¶
type Token [32]byte
Token is the session token of punch_start: 32 random bytes, the input key material of the session's UDP key. On the wire it is base64url without padding. Its String and every fmt verb print a fixed placeholder, so a token cannot reach a log by accident; only MarshalText produces the wire form.
func (Token) Format ¶
Format hides the token from every fmt verb. The value receiver makes this method available on values as well as pointers.
func (Token) GoString ¶
GoString hides the token from %#v as well. The value receiver makes this method available on values as well as pointers.
func (Token) IsZero ¶
IsZero reports whether t is unset. The value receiver makes this method available on values as well as pointers.
func (Token) LogValue ¶
LogValue hides the token from log/slog, which would otherwise use MarshalText. The value receiver makes this method available on values as well as pointers.
func (Token) MarshalText ¶
MarshalText returns the wire form: base64url without padding. The value receiver makes this method available on values as well as pointers.
func (Token) String ¶
String hides the token. The value receiver makes this method available on values as well as pointers.
func (*Token) UnmarshalText ¶
UnmarshalText accepts exactly the canonical base64url of 32 bytes. Decoding uses a pointer receiver to update the value in place.
type Traits ¶
type Traits struct {
Family Family `json:"family,omitempty"` // omitted where the container names the family
NoNAT Tri `json:"no_nat,omitempty"` // observed == local (IP and port)
Mapping Mapping `json:"mapping,omitempty"`
MappingConf Conf `json:"mapping_conf,omitempty"`
Filtering Filtering `json:"filtering,omitempty"`
FilteringConf Conf `json:"filtering_conf,omitempty"`
PortAlloc PortAlloc `json:"port_alloc,omitempty"`
PortStep int16 `json:"port_step,omitempty"` // sequential: signed step
PortVelocity float32 `json:"port_velocity,omitempty"` // other hosts' allocation rate, ports/s
PortAllocConf Conf `json:"port_alloc_conf,omitempty"`
PortNoisy bool `json:"port_noisy,omitempty"` // sequential: other hosts allocated between this side's probes, however short the baseline
PortAnchor uint16 `json:"port_anchor,omitempty"` // last external port by creation order
PortAnchorMs int64 `json:"port_anchor_ms,omitempty"` // creation time on the server's monotonic axis
PortRangeLo uint16 `json:"port_lo,omitempty"` // pool: estimated port block
PortRangeHi uint16 `json:"port_hi,omitempty"`
FirstPreserved bool `json:"first_preserved,omitempty"` // APDM but the first mapping kept the local port
MultiExit bool `json:"multi_exit,omitempty"` // one socket seen with >= 2 public IPs
MultiHomed bool `json:"multi_homed,omitempty"` // sockets leave through different public IPs
Drifted bool `json:"drifted,omitempty"`
Hairpin Tri `json:"hairpin,omitempty"`
CGNAT Tri `json:"cgnat,omitempty"`
CrossIP bool `json:"cross_ip,omitempty"` // checked against a source with another IP
// PathDependent: a third party's STUN server saw the primary socket at
// another port of the verified public IP than natprobe did, so the mapping
// depends on the path and an endpoint-independent conclusion is not to be
// trusted; planning treats the side as endpoint dependent. It never raises
// a confidence.
PathDependent bool `json:"path_dependent,omitempty"`
// LANObserved: the server's public observers saw this side only at
// private addresses — it reaches the server over a LAN route or through
// a hairpin without source NAT — so PublicIP and Observed are LAN
// addresses and the traits say nothing of its NAT toward the Internet:
// mapping, filtering and allocation are unknown. Two LAN-observed sides
// on one LAN connect over it; a LAN-observed side is otherwise reached
// at the public addresses it reported itself (STUN, port mapping), in the
// unverified mode, unless the server allows verified targets only.
LANObserved bool `json:"lan_observed,omitempty"`
Samples uint8 `json:"samples,omitempty"` // server observers with a valid sample
Provisional bool `json:"provisional,omitempty"`
PublicIP netip.Addr `json:"public_ip,omitzero"`
Observed netip.AddrPort `json:"observed,omitzero"` // primary socket as seen by observer 0
}
Traits describes one family's NAT as orthogonal fields with confidences. It is produced by the NAT classifier, carried in probe_report (client provisional) and probe_summary (server authoritative), and consumed by the planner through the predicates below.
func (Traits) AcceptsAfterIPContact ¶
AcceptsAfterIPContact reports whether packets from an IP this side has contacted get in whatever their source port.
func (Traits) EndpointDependent ¶
EndpointDependent reports whether the external port depends on the destination.
func (Traits) NeedsSimultaneous ¶
NeedsSimultaneous reports whether the peer's packets must arrive after this side sent (port-dependent or unknown filtering).
func (Traits) ObservedUsable ¶
ObservedUsable reports whether Observed is a usable candidate on its own.
func (Traits) Predictable ¶
Predictable reports whether the next external port of an endpoint-dependent mapping can be predicted — sequential, or a pool, with medium confidence or better. ADM counts as well as APDM.
type TraitsSource ¶
type TraitsSource string
TraitsSource says which evidence produced a TraitsUpdate.
const ( TraitsSourcePeer TraitsSource = "peer" TraitsSourceAlt TraitsSource = "alt" TraitsSourceSTUN TraitsSource = "stun" TraitsSourceHairpin TraitsSource = "hairpin" )
Traits update sources.
type TraitsUpdate ¶
type TraitsUpdate struct {
Family Family `json:"family"`
Mapping *Mapping `json:"mapping,omitempty"`
MappingConf *Conf `json:"mapping_conf,omitempty"`
Filtering *Filtering `json:"filtering,omitempty"`
FilteringConf *Conf `json:"filtering_conf,omitempty"`
PortStep *int16 `json:"port_step,omitempty"`
PortVelocity *float32 `json:"port_velocity,omitempty"`
Hairpin *Tri `json:"hairpin,omitempty"`
Source TraitsSource `json:"source"`
}
TraitsUpdate is a punch-time correction of this side's traits (punch_result.traits; the only input of the server's traits memory). Nil fields are unchanged.
func (TraitsUpdate) Clone ¶
func (u TraitsUpdate) Clone() TraitsUpdate
Clone returns independent copies of every field in the correction.
type Transport ¶
type Transport struct {
Mode string `json:"mode"` // a token of <= 16 printable ASCII bytes, or empty
Data []byte `json:"data,omitempty"` // opaque bytes, <= 8 KiB (a certificate digest, for example); base64 on the wire
}
Transport is the client's upper-layer transport offer.
type TransportPick ¶
type TransportPick struct {
Mode string `json:"mode"`
PeerData []byte `json:"peer_data,omitempty"` // the peer's Transport.Data, verbatim
}
TransportPick is the server's transport decision, the same on both sides.
type Tri ¶
type Tri uint8
Tri is a three-valued boolean: unknown | false | true.
func (Tri) MarshalText ¶
MarshalText encodes t as its wire name; an out-of-range value is an error. The value receiver makes this method available on values as well as pointers.
func (Tri) String ¶
String returns the wire name of t. The value receiver makes this method available on values as well as pointers.
func (*Tri) UnmarshalText ¶
UnmarshalText accepts exactly the wire names. Decoding uses a pointer receiver to update the value in place.
type ValidationError ¶
ValidationError is a message or argument that cannot be accepted. Reason is the code to report (protocol_violation, control_version_mismatch for version fields, invalid_argument for a caller's argument) and Detail the detail to send with it: a field path such as "plan.round1.sides[0].stages[2].kind", or role_mismatch / session_mismatch / round1_plan. Match it with errors.As and compare Reason. The text never contains field values that could be key material.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error reports the reason, the field path and the problem.
type Warning ¶
type Warning string
Warning is a non-fatal condition a session recorded: in punch_result.warn, holepunch.Diagnostics.Warn and coord.Result.Warn. The set is open: a name this version does not know is kept as it is.
const ( WarnClockSkew Warning = "clock_skew" // the client clock is far from the server's (diagnostic only) WarnGoroutineJoinTimeout Warning = "goroutine_join_timeout" // cleanup gave up waiting for a goroutine stuck in user code WarnLowTTLUnsupported Warning = "low_ttl_unsupported" // the sockets cannot send with a low TTL WarnPeerResultMissing Warning = "peer_result_missing" // a client's punch_result never arrived WarnUnverifiedTargets Warning = "unverified_targets" // some targets were self-reported, not verified by the server // WarnLANObserved means the server saw a client only at private addresses // (Traits.LANObserved), a deployment where clients reach the server // over a LAN route or a hairpin without source NAT. WarnLANObserved Warning = "lan_observed" // WarnAbortAfterConfirm means a punch_abort arrived after this side had // confirmed the path; the path was kept. WarnAbortAfterConfirm Warning = "abort_after_confirm" // WarnControlLostAfterConfirm means the control link ended after this // side had confirmed the path; the path was kept. WarnControlLostAfterConfirm Warning = "control_lost_after_confirm" )
Warnings.
type WireSpec ¶
type WireSpec struct {
RouteID RouteID `json:"route_id"` // base64url of exactly 16 bytes
PayloadMin uint16 `json:"payload_min"` // server: U[48, 160]; client clamps to [48, 1024]
PayloadMax uint16 `json:"payload_max"` // server: PayloadMin + U[64, 256]; client clamps to [PayloadMin, 1024]
}
WireSpec is punch_start.wire: the session route and the session's random plaintext length range for client-to-client UDP packets.
func NewWireSpec ¶
func NewWireSpec() WireSpec
NewWireSpec returns a fresh wire spec: a random route, payload_min ∈ U[48, 160] and payload_max = payload_min + U[64, 256].