Documentation
¶
Overview ¶
Package holepunch is the client side of holepunch, a UDP hole-punching library: given a control connection to a holepunch coordinator (package coord), Punch finds a direct UDP path to the peer the coordinator pairs it with and hands the confirmed socket to the caller.
Usage ¶
The caller opens an authenticated, encrypted stream to the coordinator — TLS works as is — sends whatever its application needs first, and calls Punch:
sess, err := holepunch.Punch(ctx, conn, holepunch.Options{})
if err != nil {
// a *holepunch.Error: keep relaying, maybe retry (see below)
}
defer sess.Close()
pc := sess.PacketConn() // the punched UDP socket, now the caller's
peer := sess.Result().Path.RemoteAddr // the peer's address on it
The control connection stays the caller's throughout: Punch never closes it, and closing it is how a caller stops a running Punch. A stream that is not TLS but protected by an outer layer needs Options.ControlSecurity protocol.ControlSecurityDeclared.
The control channel ¶
The control channel is any reliable, ordered byte stream the caller has authenticated, with net.Conn's deadline semantics: a deadline in the past makes a blocked Read or Write return a timeout error at once. TLS over TCP is the usual one; a stream of a multiplexed connection the application already has (a QUIC stream, a stream of its own multiplexer over TLS, an encrypted bridge) works as well. One stream carries one session: run each Punch on a stream of its own. The coordinator may also run in the same process as one of the clients, or in the application's own server: coord.Session.Attach takes the other end of the stream, for example one end of net.Pipe with the other given to Punch (ControlSecurityDeclared on both sides: the pipe never leaves the process).
The server decides the session: its punch_start carries the policy, the timeouts and the observers. Options.Policy can only tighten the server's policy (protocol.Tighten), and the timeouts are clamped to the protocol's ranges (protocol.Timeouts.Normalize), whatever either side asks for.
What a session hands over ¶
A Session holds the sockets of the confirmed paths: the primary path (PacketConn, Result.Path) and, with Options.MaxPaths above 1, extra paths on another family or kind of network (Result.ExtraPaths, PacketConns). When Punch returns, the library is done with them: it no longer reads or writes them, their deadlines are cleared and their TTL restored. The caller reads and writes them freely; the Session owns them until Close, which releases their port mappings and closes them, or Detach, which hands both over to the caller. Each Path says what kind of network it crosses (public, LAN, overlay, port mapping), its RTT and the keepalive that keeps its NAT mappings open. An upper layer other than QUIC reads through Session.FilterResidual, which drops the peer's last handshake packets; QUIC needs nothing.
Failures ¶
Every failure is an *Error whose Reason is one of the protocol.Reason values, with the phase it happened in, a detail and, from the server, advice for the next attempt (Error.Advice: relay and punch again in Background mode, or relay only) and a RetryAfter. NextAttempt turns them into a retry policy — retry after a backoff, switch to Background mode, stay on the relay for hours, or give up:
switch next := holepunch.NextAttempt(err, failures); next.Action {
case holepunch.ActionRetry, holepunch.ActionBackground:
// keep relaying; punch again after next.Delay
// (ActionBackground: with Options.AcceptBackground)
case holepunch.ActionRelayOnly:
// keep relaying; do not punch this pair for next.Delay
case holepunch.ActionGiveUp:
// stopped by the caller, or a configuration error
}
Diagnostics — on the Session and on the Error — tell how the session went: both sides' NAT traits, the rounds run, counters, timings, warnings and hints for people (HintHostFirewall, HintServerSeesLAN). Options.Logger logs the milestones and the failure of each session.
Related packages ¶
- coord and natprobe are the server side; portmapper adds UPnP, NAT-PMP and PCP port mappings (Options.PortMapper).
- stun, udpsock and hostaddr are standalone tools the library is built on: STUN queries and a server, ICMP reports and TTLs of UDP sockets, and the host's LAN, public and overlay addresses.
- nattest simulates NATs and networks in process, and clock provides the Fake clock that drives a whole deployment deterministically; the package example runs one.
Guarantees ¶
Punch does not panic: user code — Network, PortMapper, HopLimiter, Clock, OnProgress, the Logger's handler — runs outside every lock and inside a recover boundary, and a panic in the library becomes an *Error with Reason internal. When Punch returns, every goroutine it started has exited and every resource it did not hand over is released, on success and failure alike. Every wait has its own deadline, so Punch returns within the session cap (71 s by default, 150 s at most) even with context.Background(), plus a TLS handshake it ran for the caller (15 s at most). Nothing polls: an idle session sleeps until its next deadline.
Settings: the zero value of a field selects its default, stated in the field's documentation; for timeouts and limits it is a safe bound unless the field says otherwise. A negative timeout means no timeout, as for http.Server.IdleTimeout. Other negative values are an error unless the field gives them a meaning. The coordinator's TTLConfig and Limits keep their own rules, which their documentation states: deadlines are clamped to protocol ranges, and the bounds of its memory and its write deadlines cannot be lifted, so a negative value of them is an error.
Example ¶
Example runs a whole deployment on a simulated Internet: a server with the NAT observer and the coordinator, and two clients behind NATs that punch a direct UDP path and send a datagram over it.
A real deployment differs in three places only: the sockets are the operating system's (no Listen and no Network), the control connections are TLS or another authenticated, encrypted stream (no ControlSecurityInsecureForTesting), and the server pairs the two connections by its own matchmaking.
package main
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/netip"
"sync"
"time"
"github.com/djylb/holepunch"
"github.com/djylb/holepunch/coord"
"github.com/djylb/holepunch/natprobe"
"github.com/djylb/holepunch/nattest"
"github.com/djylb/holepunch/protocol"
)
func main() {
n := nattest.NewNetwork(nattest.WithSeed(1))
defer func() { _ = n.Close() }()
server := n.PublicHost(netip.IPv4Unspecified())
hosts := [2]*nattest.Host{
n.NAT(nattest.PortRestricted()).Host(),
n.NAT(nattest.SymmetricSeq(1)).Host(),
}
// Server side: natprobe measures the clients' NATs, the coordinator
// runs the sessions and tells the clients where natprobe listens.
reg := natprobe.NewRegistry(natprobe.RegistryConfig{})
probe, err := natprobe.NewServer(natprobe.ServerConfig{
Registry: reg,
Groups: []natprobe.ObserverGroup{{Bind: server.Addrs()[0]}},
Listen: server.Listen,
})
if err != nil {
log.Print(err)
return
}
if err := probe.Start(); err != nil {
log.Print(err)
return
}
defer func() { _ = probe.Close() }()
co, err := coord.New(coord.Config{Registry: reg, DefaultProbe: probe.ProbeSpec()})
if err != nil {
log.Print(err)
return
}
defer func() { _ = co.Close() }()
// One session pairs the two clients: each control connection is
// attached to it under its role, and each client runs Punch on
// its end.
sess, err := co.NewSession(coord.SessionOptions{})
if err != nil {
log.Print(err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
var (
wg sync.WaitGroup
ends [2]net.Conn
sessions [2]*holepunch.Session
errs [2]error
)
defer func() {
for _, c := range ends {
if c != nil {
_ = c.Close()
}
}
}()
for i, role := range []protocol.Role{protocol.RoleInitiator, protocol.RoleResponder} {
clientEnd, serverEnd := n.Pipe(nattest.PipeConfig{A: hosts[i], B: server})
ends[i] = clientEnd
err := sess.Attach(role, serverEnd, coord.AttachOptions{Security: protocol.ControlSecurityInsecureForTesting})
if err != nil {
log.Print(err)
return
}
wg.Go(func() {
sessions[i], errs[i] = holepunch.Punch(ctx, clientEnd, holepunch.Options{
ControlSecurity: protocol.ControlSecurityInsecureForTesting,
Network: hosts[i],
})
})
}
wg.Wait()
if err := errors.Join(errs[:]...); err != nil {
log.Print(err)
return
}
initiator, responder := sessions[0], sessions[1]
defer func() { _ = initiator.Close() }()
defer func() { _ = responder.Close() }()
for _, s := range sessions {
p := s.Result().Path
fmt.Printf("%s: %s path over %s\n", s.Result().Role, p.Kind, p.Family)
}
// The sockets are the caller's now. An upper layer other than QUIC
// filters the late handshake packets of the session out first.
in := responder.FilterResidual(responder.PacketConn())
to := net.UDPAddrFromAddrPort(initiator.Result().Path.RemoteAddr)
if _, err := initiator.PacketConn().WriteTo([]byte("hello"), to); err != nil {
log.Print(err)
return
}
_ = in.SetReadDeadline(time.Now().Add(5 * time.Second))
buf := make([]byte, 1500)
nr, _, err := in.ReadFrom(buf)
if err != nil {
log.Print(err)
return
}
fmt.Printf("responder read %q\n", buf[:nr])
}
Output: initiator: public path over udp4 responder: public path over udp4 responder read "hello"
Index ¶
- Constants
- Variables
- type Action
- type Attempt
- type Counters
- type Detached
- type Diagnostics
- type Error
- type FamilyDiagnostics
- type FilteredConn
- type Hint
- type HopLimiter
- type KeepaliveAdvice
- type KeepaliveReason
- type Network
- type Options
- type PanicError
- type Path
- type Phase
- type PortMapper
- type Result
- type Session
- func (s *Session) Close() error
- func (s *Session) ConfirmTransport(path Path) bool
- func (s *Session) Detach() Detached
- func (s *Session) Diagnostics() Diagnostics
- func (s *Session) FilterResidual(pc net.PacketConn) FilteredConn
- func (s *Session) PacketConn() net.PacketConn
- func (s *Session) PacketConns() []net.PacketConn
- func (s *Session) Result() Result
- type SharedPortStats
- type SharedPorts
- type Timing
- type Transition
- type TransportConfirmation
Examples ¶
Constants ¶
const ( PurposeProbe = "probe" // primary, second and sandwich-helper sockets PurposeSibling = "sibling" // sockets bound on other local addresses during probing PurposeWarmup = "warmup" // extra round sockets that pre-open mappings with a low TTL PurposeBirthday = "birthday" // extra round sockets of multi-socket (birthday) rounds PurposeFresh = "fresh" // fresh sockets bound at drawn ports for one round )
Socket purposes passed to Network.ListenPacket. Package portmapper opens its request sockets with purpose "portmap".
Variables ¶
var ErrClosed = errors.New("holepunch: session closed")
ErrClosed is the Err of a canceled session whose control connection the caller closed while Punch was running: the library never closes that connection, so its closing is the caller's way to stop the session.
ErrLocalPortUnavailable is reached through Error.Err (errors.Is) when the port Options.LocalPort pins cannot carry the session: another socket holds it or the system refuses it to this process, or — with SharedPorts — a confirmed path would run between the same two endpoints as a path another session handed over on the shared socket. The session fails with Reason local_port_bind_failed; the caller falls back by punching again with LocalPort 0.
Functions ¶
This section is empty.
Types ¶
type Action ¶
type Action uint8
Action is what to do after a failed Punch (NextAttempt).
const ( // ActionGiveUp means: do not punch again on a timer. The caller stopped // the session, or the failure is one of configuration, version or a // bug, which the next attempt repeats; punch again only after something // changed (a new configuration, a network change). ActionGiveUp Action = iota // ActionRetry means: punch again in the same mode after Attempt.Delay. ActionRetry // ActionBackground means: keep relaying and punch again after // Attempt.Delay in a Background session — Options.AcceptBackground on // the clients, coord.SessionOptions.Mode on the server — where a pair // of hard NATs may take its time. ActionBackground // ActionRelayOnly means that no punch is expected to connect this pair: // keep the relay and do not punch for it again for Attempt.Delay // (hours). ActionRelayOnly )
Actions. The zero value is ActionGiveUp.
type Attempt ¶
Attempt is NextAttempt's advice: an action and the wait before it.
func NextAttempt ¶
NextAttempt maps the error of a failed Punch and the number of consecutive failures of this pair so far, this one included (attempt ≥ 1; less counts as 1), to the next step. It is a policy built on the error's Advice, Reason and RetryAfter, which a caller may follow or replace; the server's own view of the same failure is coord.Result.Retry.
- nil, ErrClosed, a canceled context and Reason canceled from one: ActionGiveUp, since the caller ended the session. A context that reached its deadline — a caller's per-attempt timeout — is transient, and so is Reason canceled in a punch_abort (AbortedBy set): the server or the peer canceled the session, not the caller.
- Advice relay_only, and the reasons that rule a direct path out for this host or pair (udp_blocked, no_common_family): ActionRelayOnly after 30–60 min, the step doubling up to 24 h.
- A hard_symmetric_random pair without explicit background advice also uses ActionRelayOnly.
- Advice background_viable: ActionBackground after 15–30 s, doubling up to 30 min.
- The other NAT-hard reasons without advice (candidate_timeout, one_way_udp_only, packet_budget_exceeded): ActionRetry after 7.5–15 s, doubling up to 30 min.
- The transient reasons (timeouts, the peer offline, the server busy or shutting down, aborts), local_port_bind_failed, internal, unknown reasons and errors that are not an *Error: ActionRetry after 0.5–1 s, doubling up to 5 min.
- The other fatal reasons (invalid_argument, protocol and version mismatches, token_mismatch, transport_mismatch, no_probe_endpoint): ActionGiveUp — the next attempt would fail the same way.
Each delay is drawn uniformly from the upper half of its step, so that many clients that failed together do not come back together. The error's RetryAfter (the server's server_busy wait), at most the step's ceiling, is a floor, with up to a quarter of it added at random for the same reason.
type Counters ¶
type Counters struct {
TxPackets int // initiated packets (bounded by MaxPackets)
TxByStage map[string]int // direct, predict, random, birthday, warmup (low TTL), reply, handshake, handover, probe
RxPackets int // datagrams read
RxVerified int // peer packets that passed AEAD, role and replay checks
Drops map[string]int
TokenMismatch int // AEAD failures from a verified peer IP outside the handover window (token_mismatch evidence; not Drops["auth"])
TargetRejected int // targets refused by admission
ReplyUnlisted int // replies to peer-reflexive sources outside the verified set
DistinctTargets int // distinct initiated destinations
SocketsOpened int // sockets opened by the session
PeakPPS int // most initiated packets within any second
BudgetUsedPct int // initiated packets as a percentage of MaxPackets
ControlFramesIn int // control frames read
ControlFramesOut int // control frames written
ProgressDropped int // progress copies dropped (local queue full or delivery window over)
CallbackPanics int // panics recovered in user callbacks and implementations
LeakedGoroutines int // goroutines still running when cleanup gave up waiting; always 0 in a healthy build
PeerSeenUs bool // the peer reported, through peer_seen, receiving our packets
}
Counters are the packet and event counts of a session or family. Drops uses the keys of punch_result.stats.drops (protocol.DropKeys).
type Detached ¶
type Detached struct {
// Conns are the sockets of the session's paths, each once, the primary
// path's first (Session.PacketConns).
Conns []net.PacketConn
// Releases release the port mappings of these sockets
// (Path.PortMapping), in no particular order: call every one before
// closing any of Conns, or a mapping stays on the router until its
// lifetime runs out. Each is
// idempotent, recovers a panic of the port mapper and returns within
// 2 s.
Releases []func() error
}
Detached is what Session.Detach hands over: the caller's from then on.
type Diagnostics ¶
type Diagnostics struct {
SessionID string
Role protocol.Role
Phase Phase // the phase the session ended in
Reason protocol.Reason // "" on success
LastEvent string
Timeline []Transition // at most 64, session and family scopes, most recent kept
Self []protocol.Traits // per family: this side's traits from probe_summary, with punch-time corrections
Peer []protocol.Traits // per family: the peer's traits from probe_summary
Plan *protocol.PlanSpec // probe_summary.plan
Rounds []protocol.RoundPlan // the rounds actually run (rescue included)
Path *protocol.PathInfo // on success: the confirmed path, with confirmed_by
// ExtraPaths are, on success, the extra paths handed over with Path, as
// punch_result.extra_paths reports them.
ExtraPaths []protocol.PathInfo
Families []FamilyDiagnostics
Counters Counters
Timing Timing
RTT time.Duration // the server's estimate of this control link's RTT (punch_go.rtt_ms)
Warn []protocol.Warning // at most 8, the protocol.Warn* values this side recorded
}
Diagnostics is the full account of a session: how it went and why it ended. Session.Diagnostics and Error.Diagnostics return deep copies; token and route never appear in it.
type Error ¶
type Error struct {
PairClass string // coordinator classification, when available
Reason protocol.Reason
Phase Phase
Round int // the round the session was in; 0 before punching
LastEvent string // the last recorded event
AbortedBy protocol.Role // "", initiator, responder or server: punch_abort.by
Detail string // fine-grained cause, at most 256 bytes; the peer's or server's abort detail verbatim
RetryAfter time.Duration // punch_abort.retry_after_ms (server_busy and the like)
// Advice is the server's suggestion for the next attempt, from the
// summary (probe_summary.plan.advice):
// background_viable — stay on the relay and punch again in Background
// mode — relay_only, or "" (retry as before, or failed before the
// summary). Diagnostics.Plan.BackgroundOnly tells whether the server
// saw this pair connect only in Background mode before.
Advice protocol.Advice
Diagnostics *Diagnostics // nil when the session failed before punch_start was read
Err error // the underlying error: I/O, context, decoding or *PanicError
}
Error is the failure of Punch. Reason is one of the 26 protocol.Reason values; match the error with errors.As and compare Reason.
type FamilyDiagnostics ¶
type FamilyDiagnostics struct {
Family protocol.Family
Strategy string // diagnostic name "<pair_class>/<variant>" of the family's last round ("<pair_class>" before one ran), with ";lowttl=unavailable" when the family sends no low TTL
Candidates map[string]int // candidate state -> count
Confirmed netip.AddrPort // the confirmed remote of this family's path: the primary path's, else the first extra path's
Counters Counters
// Hints are likely causes of what the traits show, for people; no
// decision depends on them: HintHostFirewall, HintPeerHostFirewall,
// HintServerSeesLAN, HintPeerServerSeesLAN.
Hints []Hint
}
FamilyDiagnostics is one address family of a session.
type FilteredConn ¶
type FilteredConn interface {
net.PacketConn
// Dropped returns how many residual handshake packets the filter has
// dropped so far.
Dropped() uint64
}
FilteredConn is a socket read through Session.FilterResidual.
type Hint ¶
type Hint string
Hint is a likely cause of what a family's traits show (FamilyDiagnostics.Hints).
const ( // HintHostFirewall means this side's mapping is endpoint independent — or // there is no NAT — but its filtering is port dependent, which is what // a host firewall (Windows Defender Firewall, iptables, pf) makes of a // full-cone NAT: it lets in only replies to the exact remote a socket // sent to. The library plans by the filtering it measured and never // counts on the host letting packets in; allowing inbound UDP for the // program may connect more peers directly. HintHostFirewall Hint = "host_firewall" // HintPeerHostFirewall is HintHostFirewall for the peer. HintPeerHostFirewall Hint = "peer_host_firewall" // HintServerSeesLAN means the server's public observers saw this side // only at a private address (protocol.Traits.LANObserved): it reaches // the server over a LAN route, or through a router hairpin that keeps // the source address, so the server knows none of its public addresses. // It connects to a peer on the same LAN directly, and to others only at // the addresses its STUN servers or port mapping reported, if the server // allows them. Letting the server see the client through its public // address — a hairpin with source NAT, or no LAN route to the server's // public IP — removes the restriction. HintServerSeesLAN Hint = "server_sees_lan" // HintPeerServerSeesLAN is HintServerSeesLAN for the peer. HintPeerServerSeesLAN Hint = "peer_server_sees_lan" )
Hints.
type HopLimiter ¶
HopLimiter is the optional TTL / hop-limit capability of a conn returned by Network.ListenPacket. SetHopLimit(0) restores the system default, as udpsock.SetHopLimit does.
The library prefers this interface; otherwise it sets the option through syscall.Conn. The decision is made by interface, never by the concrete *net.UDPConn type, so wrapping conns keep their behaviour. A conn with neither capability, or one whose setting fails, makes the session send without low TTL: probe_report announces low_ttl=false and Diagnostics.Warn carries low_ttl_unsupported. Before the winning socket is handed over, a HopLimiter is set to 0, and a socket set through syscall.Conn gets back the value it had when it was created.
type KeepaliveAdvice ¶
type KeepaliveAdvice struct {
Interval time.Duration
Timeout time.Duration
MappingLifetimeHint time.Duration // the estimated NAT mapping idle timeout; 0 without NAT evidence
Reason KeepaliveReason // what set the interval
}
KeepaliveAdvice is the keepalive the upper layer should run on a confirmed path: both sides send every Interval and declare the path dead after Timeout without inbound traffic. Interval is within [5 s, 25 s] and Timeout = 3 × Interval.
The library sends nothing on a handed-over socket; the upper layer keeps the path alive and notices when it dies — a NAT mapping that expired, a network change. A QUIC connection takes Interval as its keep-alive period and Timeout as its idle timeout. Another protocol sends a small datagram whenever it has sent nothing for Interval, and gives up on the path after Timeout without receiving anything; a write that succeeds says nothing about the path, since UDP has no acknowledgement.
type KeepaliveReason ¶
type KeepaliveReason string
KeepaliveReason is the evidence a KeepaliveAdvice rests on.
const ( KeepaliveNoNAT KeepaliveReason = "no_nat" // no NAT on the path, at most a stateful firewall KeepaliveEIMKnown KeepaliveReason = "eim_known" // endpoint-independent NATs measured with confidence KeepaliveRestricted KeepaliveReason = "restricted_or_edm" // restricted filtering or endpoint-dependent mapping KeepaliveCGNAT KeepaliveReason = "cgnat" // carrier-grade NAT, several exits or a drifting mapping KeepalivePortmapped KeepaliveReason = "portmapped" // a port-mapping lease caps the interval KeepaliveUnknown KeepaliveReason = "unknown" // too little evidence )
Keepalive reasons.
type Network ¶
type Network interface {
// ListenPacket opens a UDP socket on laddr ("udp4" or "udp6"; a zero
// laddr address means every address of the family, port 0 means any).
// The library binds each family on its own socket and never asks for a
// dual-stack one. purpose is one of the Purpose constants, for
// simulators and diagnostics. The returned conn may implement
// HopLimiter. Reads and writes failing with an ICMP report (port or host
// unreachable, TTL expired) are soft signals, so a conn that keeps the
// Windows reports on still works.
ListenPacket(ctx context.Context, network string, laddr netip.AddrPort, purpose string) (net.PacketConn, error) //holepunch:callback
// InterfaceAddrs returns the host's network interfaces and, at the same
// index, each one's addresses with their prefixes, as
// hostaddr.Interfaces does. The library classifies them with
// hostaddr.Classify, from the name and the flags net.FlagUp,
// net.FlagLoopback and net.FlagPointToPoint: overlay addresses —
// Tailscale, WireGuard, ZeroTier, other tunnels, 100.64/10 — are kept
// apart from the LAN ones (Options.ExcludeOverlay), and
// Options.LocalInterface is looked up by name. SystemNetwork's works on
// Android 11 and later too (hostaddr.Interfaces), where an interface
// may then have no name. On failure the session runs without LAN and
// overlay addresses and Diagnostics.Warn carries
// interface_list_unavailable; a host app that knows its interfaces can
// inject a Network that returns them.
InterfaceAddrs() ([]net.Interface, [][]netip.Prefix, error) //holepunch:callback
// OutboundAddr returns the source address the host uses towards the
// Internet for network ("udp4", "udp6"); no packet is sent.
OutboundAddr(ctx context.Context, network string) (netip.Addr, error) //holepunch:callback
// LookupNetIP resolves host for network ("ip", "ip4", "ip6").
LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error) //holepunch:callback
}
Network abstracts every operating-system network access of a session: sockets, interface addresses, the outbound source address and name resolution. Its methods use standard-library types only, so a simulator such as nattest.Host implements it without importing this package. The library calls these methods outside its locks and inside a recover boundary; a panic is treated as an error of that call.
To change one method, embed SystemNetwork and override it — a socket option on every socket, say:
type tunedNetwork struct{ holepunch.Network }
func (n tunedNetwork) ListenPacket(ctx context.Context, network string, laddr netip.AddrPort, purpose string) (net.PacketConn, error) {
c, err := n.Network.ListenPacket(ctx, network, laddr, purpose)
// tune c
return c, err
}
opts.Network = tunedNetwork{holepunch.SystemNetwork()}
On Android inside a VPN app, every socket must be protected so that it bypasses the VPN; protect is the app's VpnService.protect, reached through its bindings:
func (n protectedNetwork) ListenPacket(ctx context.Context, network string, laddr netip.AddrPort, purpose string) (net.PacketConn, error) {
c, err := n.Network.ListenPacket(ctx, network, laddr, purpose)
if err != nil {
return nil, err
}
rc, err := c.(syscall.Conn).SyscallConn()
if err == nil {
cerr := rc.Control(func(fd uintptr) {
if !protect(int(fd)) {
err = errors.New("protect failed")
}
})
err = errors.Join(err, cerr)
}
if err != nil {
_ = c.Close()
return nil, err
}
return c, nil
}
Every socket of a session goes through ListenPacket — package quicpath runs QUIC on the session's own sockets, and package portmapper opens its request sockets here too (purpose "portmap") — so this one method covers them all.
func SystemNetwork ¶
func SystemNetwork() Network
SystemNetwork returns the Network of the operating system: package net sockets, interfaces and resolver. ListenPacket switches the Windows ICMP reports off on every socket it opens. OutboundAddr learns the source address by connecting a UDP socket to a public address, which sends nothing.
type Options ¶
type Options struct {
// LocalAddr is the preferred local IP of its family's primary socket;
// the zero value binds every address.
LocalAddr netip.Addr
// LocalInterface is the preferred network interface of the primary
// sockets ("" = any), looked up by name in Network.InterfaceAddrs.
LocalInterface string
// TransportMode is the upper-layer transport this side offers ("quic",
// "kcp", ...; at most 16 bytes of printable ASCII, see
// protocol.CheckTransportMode); the server's decision is
// Result.TransportMode.
TransportMode string
// TransportData is opaque bytes for the peer, at most 8 KiB (a QUIC
// caller may put its certificate digest here), delivered unchanged as
// the peer's Result.PeerTransportData.
TransportData []byte
// Policy is this side's local policy. It only tightens the server's
// (protocol.Tighten).
Policy *protocol.Policy
// ExcludeOverlay leaves the host's overlay addresses out of the
// session: those on tunnel and overlay interfaces (Tailscale,
// WireGuard, ZeroTier, tun, utun) and in 100.64/10 are then neither
// reported to the peer nor aimed at. The
// zero value includes them, ranked below the public and LAN paths: an
// overlay path wins only when nothing else answers or when its RTT is
// at most 0.8 × the best other one, and Result.Path.Kind says so.
// Measurements that must not go through a tunnel exclude them.
ExcludeOverlay bool
// ControlSecurity says how the control connection is protected. The
// default, ControlSecurityAuto, lets the library judge the connection:
// it accepts one that shows it is secure (ConnectionState, as *tls.Conn
// has) and completes a handshake that has not run yet; Declared
// vouches for a channel the library cannot judge (an encrypted bridge, a
// QUIC stream);
// InsecureForTesting is for tests and loopback only and is marked in
// Diagnostics.Warn and every progress meta.
ControlSecurity protocol.ControlSecurity
// AcceptBackground accepts a Background session when the server offers
// one (coord.SessionOptions.Mode): the caller already relays its
// traffic and nobody waits for this one, so a pair of hard NATs may run
// the slow birthday — up to about a minute, many sockets opened slowly.
// Without it every session runs interactive.
AcceptBackground bool
// ThirdPartySTUN permits plaintext mapping queries to the STUN servers
// explicitly listed by the coordinator.
ThirdPartySTUN bool
// LocalPort pins the local port of the primary sockets, one per family,
// on LocalAddr or the preferred interface; 0 lets the system choose.
// The other sockets — the second probe socket among them — keep
// system-chosen or drawn ports. A port another socket holds, or that the
// system refuses, fails the session with Reason local_port_bind_failed
// and an Err that matches ErrLocalPortUnavailable: punch again with 0 to
// fall back. Concurrent sessions pinning one port share it through
// SharedPorts; without it each session binds the port itself. A shared
// socket gets no port mapping (PortMapper), and a session whose
// confirmed path would run between the same two endpoints as one
// already handed over on it fails the same way. Error.Detail tells
// them apart: local_port for the bind, local_port_path for the path.
LocalPort uint16
// the same LocalPort share one socket per family and address (see
// SharedPorts). nil shares nothing.
SharedPorts *SharedPorts
// OnProgress receives a copy of every progress event, in order, on one
// library goroutine (queue of 256, the oldest dropped when full). It must
// not block for long; a panic is recovered and counted. It is never
// called after Punch returns.
OnProgress func(protocol.Progress) //holepunch:callback
// Network is the network access of the session; nil is SystemNetwork().
Network Network
// PortMapper creates port mappings; nil disables them.
PortMapper PortMapper
// Clock is the session's time source; nil is the system clock.
Clock timeshim.Clock
// MaxPaths is how many confirmed paths the Session hands over: the
// primary path, chosen exactly as with one, and up to MaxPaths-1 extra
// paths that already carried the peer's packets, each confirmed on its
// own pair within the handover. Paths differ
// in family, in the kind of network (Path.Kind; a port mapping counts
// as public) or in the sockets at both ends; two paths of different
// kinds may share a socket. The session keeps as many as both sides
// allow and found, waiting at most about 150 ms more before the
// handover for them. 0 means 1; negative values and more than
// protocol.MaxPaths are an error.
MaxPaths int
// Logger, optional, receives the session's milestones: punch_start at
// Info, every phase transition at Debug, the progress events (the
// summary, each round's go and end, the confirmation and the handover
// at Info, the others at Debug) and how the session ended — the path at
// Info, the failure with its reason, phase, detail and advice at Warn.
// It never logs the token, the route or transport data. Its handler
// runs inline on library goroutines and must not block; a panic in it
// is recovered and counted. nil logs nothing. OnProgress is independent
// of it.
Logger *slog.Logger
}
Options configures Punch. The zero value is usable when the control connection is TLS (see ControlSecurity).
type PanicError ¶
type PanicError = life.PanicError
PanicError is a panic the library recovered: reachable through Error.Err (Reason internal, Detail "panic:<goroutine>"), and returned by coord.Coordinator.Close and portmapper.Mapper.Map. Its methods are Error, Where (where it was recovered), Stack (for local logs only; the textual forms never contain it) and Unwrap (the panic value when it was an error). Match it with errors.As.
type Path ¶
type Path struct {
// SocketIndex identifies Conn in Session.PacketConns. Paths can share a socket.
SocketIndex int
Conn net.PacketConn // the path's socket, closed by Session.Close (unless detached)
Family protocol.Family
Kind protocol.PathKind // public, lan, overlay or portmap
LocalAddr netip.AddrPort // concrete local address; wildcards replaced by the interface address
RemoteAddr netip.AddrPort // the confirmed peer address
RTT time.Duration // the smallest UDP round trip measured on the path; 0 without a sample
Keepalive KeepaliveAdvice // keepalive advice for the upper layer on this path
PortMapping *protocol.PortMappingInfo // the port mapping of the path's socket, released by Session.Close (unless detached); nil without
}
Path is one confirmed path of a session: its socket's address, the peer's address on it, the kind of network between the two and what the upper layer needs to keep it alive. A caller that must not run over a tunnel checks Kind, or excludes overlay paths up front (Options.ExcludeOverlay).
type Phase ¶
Phase is a session phase: the value of Error.Phase, Diagnostics.Phase and the wire field punch_result.phase. It is defined in package protocol because it travels on the wire; the values are protocol.PhaseCreated … protocol.PhaseFailed.
type PortMapper ¶
type PortMapper interface {
// Map requests an external mapping for conn's local port. release must
// be idempotent, stop any renewal and delete the mapping, and return
// within 2 s. Map must honour ctx. conn is the session's own socket,
// passed only so that Map can read its LocalAddr.
Map(ctx context.Context, conn net.PacketConn, policy protocol.PortMappingPolicy) (info protocol.PortMappingInfo, release func() error, err error) //holepunch:callback
}
PortMapper creates port mappings (UPnP, NAT-PMP, PCP) for a session's primary sockets. Pass portmapper.New(...) in Options.PortMapper to enable it; the root package itself never links a port-mapping implementation.
type Result ¶
type Result struct {
Transport *TransportConfirmation // nil until ConfirmTransport accepts a report
SessionID string
Role protocol.Role
Path Path // the primary path, on Session.PacketConn
// ExtraPaths are the other confirmed paths: at most Options.MaxPaths-1,
// empty with one path. The peer holds the same paths.
ExtraPaths []Path
TransportMode string // the server's transport decision, equal on both sides
PeerTransportData []byte // the peer's Options.TransportData
TransportTimeout time.Duration // timeouts.transport_timeout_ms, for the upper layer
Variant string // the winning round's RoundPlan.variant (always the server's)
Rounds int // rounds run
Timing Timing
}
Result describes a successful session.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is a successful hole punch and the owner of the sockets of its confirmed paths — the primary path's and, with Options.MaxPaths above 1, those of the extra paths — and of their port mappings. When Punch returns it, the library is done with these sockets: it has stopped reading and writing them for good, cleared their deadlines and restored their TTL, and never touches them again. The caller reads and writes them freely (PacketConns); the Session only closes them, and releases their port mappings, on Close. Detach ends that ownership instead: the caller then closes the sockets and releases the mappings itself. The methods are safe for concurrent use. Obtain a Session from a successful Punch.
func Punch ¶
Punch runs one hole-punching session over an established control connection and returns the winning UDP socket.
control must be a reliable stream the caller has authenticated and encrypted (Options.ControlSecurity) and that supports read and write deadlines (else invalid_argument, detail deadline_unsupported) with net.Conn's semantics: a deadline in the past makes a blocked Read or Write return a timeout error at once, and the zero time means none. The library hands control back by moving its read deadline into the past; a stream that only records the deadline delays Punch's return by about half a second and leaves Diagnostics.Warn with control_unreturnable. The first frame the library reads must be punch_start; bytes before it belong to the caller.
When Punch returns:
- every library goroutine has exited, but for the reader of a socket shared through Options.SharedPorts, which runs until the socket's last member closes;
- the library no longer reads or writes control, and has cleared its deadlines; control always stays the caller's and is never closed;
- on success the Session owns the winning socket, which the library no longer reads or writes and whose deadlines and TTL are back to normal;
- on failure the error is an *Error and every resource the library created is released;
- even with context.Background() it returns within the session cap T (71 s by default, at most 150 s), plus the TLS handshake when it ran one (at most 15 s).
Punch does not panic: a panic inside the library becomes an *Error with Reason internal. Closing control while the session runs stops it with Reason canceled (Err ErrClosed).
Example ¶
ExamplePunch is the client side against a real server: the caller opens and authenticates the control connection, runs the session on it and, when no direct path is found, decides from the error whether and how to try again.
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"net"
"time"
"github.com/djylb/holepunch"
"github.com/djylb/holepunch/protocol"
)
func main() {
ctx := context.Background()
var d tls.Dialer
d.Config = &tls.Config{MinVersion: tls.VersionTLS13, ServerName: "coordinator.example"}
conn, err := d.DialContext(ctx, "tcp", "coordinator.example:4343")
if err != nil {
log.Fatal(err)
}
// The connection stays the caller's: the library never closes it. Any
// application messages before the session (a login, the peer's name) go
// here, before Punch.
defer func() { _ = conn.Close() }()
sess, err := holepunch.Punch(ctx, conn, holepunch.Options{})
if err != nil {
var herr *holepunch.Error
if !errors.As(err, &herr) {
log.Print(err) // Punch only returns *holepunch.Error
return
}
switch {
case herr.Advice == protocol.AdviceRelayOnly:
log.Printf("no direct path to this peer (%s): keep the relay", herr.Reason)
case herr.Advice == protocol.AdviceBackgroundViable:
log.Printf("%v: serve over the relay and punch again with Options.Mode = protocol.ModeBackground", herr)
case herr.Reason.Class() == protocol.ClassTransient:
log.Printf("%v: try again in %v", herr, max(herr.RetryAfter, 5*time.Second))
default: // fatal, nat_hard or canceled: retrying now would end the same way
log.Printf("hole punching failed: %v", herr)
}
return
}
defer func() { _ = sess.Close() }()
res := sess.Result()
pc := sess.PacketConn()
_, err = pc.WriteTo([]byte("hello"), net.UDPAddrFromAddrPort(res.Path.RemoteAddr))
fmt.Println(res.Path.Kind, res.Path.RemoteAddr, err)
}
Output:
func (*Session) Close ¶
Close releases the port mappings of the handed-over sockets, if any, and then closes every socket of the session's paths, each once; after Detach it does nothing and returns nil. It is idempotent and safe for concurrent use: every caller gets the first error (net.ErrClosed is not an error). It returns within the port mapper's release bound (2 s per mapping, released one after the other).
func (*Session) ConfirmTransport ¶
ConfirmTransport records the first time the application authenticated the peer and verified its response on path, one of Result.Paths(). It returns true only to the caller that records the confirmation. Close and Detach end the acceptance of new reports. Prior confirmation remains in Result. The caller can export that snapshot with its application metrics.
func (*Session) Detach ¶
Detach ends the Session's ownership of the sockets and port mappings and returns them: Close then does nothing, and the caller closes the sockets and releases the mappings itself — for an upper layer that takes over their whole lifetime. Detach after Close or a first Detach returns an empty Detached.
func (*Session) Diagnostics ¶
func (s *Session) Diagnostics() Diagnostics
Diagnostics returns the session's diagnostics (a deep copy).
func (*Session) FilterResidual ¶
func (s *Session) FilterResidual(pc net.PacketConn) FilteredConn
FilterResidual wraps pc, one of the session's sockets, so that the late holepunch handshake packets still arriving after the handover — the peer's retransmissions — never reach the upper layer, which might take them for a new connection. An upper layer other than QUIC — KCP, a custom protocol — reads through it:
pc := sess.FilterResidual(sess.PacketConn())
QUIC needs no wrapper: it drops these packets by their first byte.
For 10 s after the call, a datagram from a confirmed remote that authenticates as a session packet is dropped and the next one read; every other datagram is returned unchanged, and an upper-layer packet is dropped only if it forges a GCM tag. Afterwards a read costs one atomic load more than pc's. The wrapper starts no goroutine and never touches deadlines; closing it closes pc. It returns nil for a nil pc.
func (*Session) PacketConn ¶
func (s *Session) PacketConn() net.PacketConn
PacketConn returns the primary path's socket (Result.Path.Conn), exactly as Network.ListenPacket returned it: no wrapper, so optional capabilities such as *net.UDPConn's stay available. A socket shared through Options.SharedPorts is the exception: the conn is the session's member of it, which reads only the datagrams of the confirmed remotes. Close the Session rather than the conn directly, so that a port mapping on it is released too.
func (*Session) PacketConns ¶
func (s *Session) PacketConns() []net.PacketConn
PacketConns returns every socket of the session's paths once, the primary path's first: what an upper layer reads from. Two paths of different kinds of network — a LAN and a public path — can run through one socket, which then appears once here and in both paths' Path.Conn; their datagrams differ by the remote address. Close the Session rather than these conns directly.
type SharedPortStats ¶
type SharedPortStats struct {
SharedPortStats counts classification and delivery work across a registry.
type SharedPorts ¶
type SharedPorts struct {
// contains filtered or unexported fields
}
SharedPorts lets concurrent sessions that pin the same Options.LocalPort share one socket per family and local address instead of each binding the port. Every session that names the same SharedPorts and the same Network joins the socket the first one bound; the socket closes when the last session using it ends, or when the last Session it was handed over to closes.
The shared socket's single reader gives each datagram to one session: to the punching session whose key opens it, else to the session whose handed-over path runs to its source, else to the punching sessions that wrote to its source (a STUN server's answer, an upper-layer packet ahead of the handover). A session's packets carry nothing that names it on the wire. A Session handed over on a shared socket receives only the datagrams of its confirmed remotes; it owns a member of the socket, not the socket, so its PacketConn is the library's member conn rather than what Network.ListenPacket returned.
Sharing needs a comparable Network value (SystemNetwork's is, and so is a pointer); with one that is not, every session binds the port itself and a second one at the same time fails with ErrLocalPortUnavailable. The member conn is no *net.UDPConn, and after the handover it does not follow the peer to a new address: a datagram from anywhere but the confirmed remotes does not reach it.
The zero value is ready to use; a SharedPorts must not be copied after first use. It is safe for concurrent use.
func (*SharedPorts) Stats ¶
func (sp *SharedPorts) Stats() SharedPortStats
Stats returns cumulative counters for every socket in sp.
type Transition ¶
type Transition struct {
Scope string // "session", "udp4" or "udp6"
From, To Phase
Event string
At time.Time
}
Transition is one phase change.
type TransportConfirmation ¶
type TransportConfirmation struct {
At time.Time // when the application marked the authenticated round trip
PathIndex int // index into Result.Paths(), zero for the primary
}
TransportConfirmation records the first application-confirmed transport on a session. Its timestamp and path remain available after teardown.
Source Files
¶
- assist.go
- budget.go
- control.go
- diagnostics.go
- dispatch.go
- doc.go
- errors.go
- famround.go
- finish.go
- handoff.go
- handover.go
- hostaddrs.go
- logging.go
- network.go
- nomination.go
- pacer.go
- paths.go
- phase.go
- portmap.go
- portshare.go
- prepare.go
- probe.go
- progress.go
- punch.go
- punchstate.go
- refresh.go
- reobserve.go
- report.go
- retry.go
- rounds.go
- runs.go
- schedule.go
- session.go
- sockets.go
- workers.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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.
|
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. |
|
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. |
|
Package e2e is holepunch's end-to-end acceptance suite: the real coordinator, a real natprobe Server and two real clients of the root package, all on the in-process NAT simulator nattest, with the clients' control links as nattest pipes.
|
Package e2e is holepunch's end-to-end acceptance suite: the real coordinator, a real natprobe Server and two real clients of the root package, all on the in-process NAT simulator nattest, with the clients' control links as nattest pipes. |
|
internal/kpi
Package kpi holds the measurements shared by the E2E suite and its reports.
|
Package kpi holds the measurements shared by the E2E suite and its reports. |
|
kpiagg
command
Command kpiagg aggregates the kpi.json files of the e2e suite into Markdown: the per-cell table, a summary per group, and the two summary views of the 49 ordered IPv4 cells — the 15 combinations (unordered pairs of the classes OPEN, ADF, PDF, SEQ, RND) and the connectivity classes — and the combination gate view: the 15 combinations weighing the same, per ablation configuration found (full and plain in the ablation output) — and, from the escalation sequences, the eventual direct rate after background escalation.
|
Command kpiagg aggregates the kpi.json files of the e2e suite into Markdown: the per-cell table, a summary per group, and the two summary views of the 49 ordered IPv4 cells — the 15 combinations (unordered pairs of the classes OPEN, ADF, PDF, SEQ, RND) and the connectivity classes — and the combination gate view: the 15 combinations weighing the same, per ablation configuration found (full and plain in the ablation output) — and, from the escalation sequences, the eventual direct rate after background escalation. |
|
Package hostaddr lists the addresses of this host's network interfaces and tells what kind of network each one is on: loopback, a LAN, the public Internet, or an overlay — a tunnel or mesh VPN such as Tailscale, WireGuard or ZeroTier.
|
Package hostaddr lists the addresses of this host's network interfaces and tells what kind of network each one is on: loopback, a LAN, the public Internet, or an overlay — a tunnel or mesh VPN such as Tailscale, WireGuard or ZeroTier. |
|
internal
|
|
|
ablation
Package ablation holds the ablation switches: each switch turns off one mechanism that relies on the control link both clients hold with the server before punching, so that the nightly ablation run can measure what the mechanism is worth.
|
Package ablation holds the ablation switches: each switch turns off one mechanism that relies on the control link both clients hold with the server before punching, so that the nightly ablation run can measure what the mechanism is worth. |
|
candidate
Package candidate is the client's candidate scoring/selection and the UDP nomination/handover state machine.
|
Package candidate is the client's candidate scoring/selection and the UDP nomination/handover state machine. |
|
clonetest
Package clonetest checks that a Clone function is a deep copy: that the copy shares no pointer, slice element or map with the value it was made from.
|
Package clonetest checks that a Clone function is a deep copy: that the copy shares no pointer, slice element or map with the value it was made from. |
|
controlwire
Package controlwire carries holepunch control frames over a reliable, encrypted and authenticated stream.
|
Package controlwire carries holepunch control frames over a reliable, encrypted and authenticated stream. |
|
faultconn
Package faultconn wraps a net.Conn for the robustness tests of control links: faults armed on the whole connection (writes that fail, writes that block until Close whatever the deadline, no deadline support), hooks run inside Write and SetWriteDeadline (which may block or panic), counters of the calls the code under test made and an optional log of them.
|
Package faultconn wraps a net.Conn for the robustness tests of control links: faults armed on the whole connection (writes that fail, writes that block until Close whatever the deadline, no deadline support), hooks run inside Write and SetWriteDeadline (which may block or panic), counters of the calls the code under test made and an optional log of them. |
|
faultinject
Package faultinject provides named fault injection points for robustness tests.
|
Package faultinject provides named fault injection points for robustness tests. |
|
goroutines
Package goroutines checks tests for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first; VerifyNone fails a test with them and VerifyTestMain a whole test binary.
|
Package goroutines checks tests for leaked goroutines: Find lists the goroutines still running besides the caller, the test framework's and the runtime's own, waiting a while for them to end first; VerifyNone fails a test with them and VerifyTestMain a whole test binary. |
|
leak
Package leak provides the resource accounting that package goroutines does not cover: sockets opened through a holepunch Network and file descriptors of the process.
|
Package leak provides the resource accounting that package goroutines does not cover: sockets opened through a holepunch Network and file descriptors of the process. |
|
life
Package life is the single place where holepunch starts goroutines, recovers panics and interrupts blocked reads on connections it does not own.
|
Package life is the single place where holepunch starts goroutines, recovers panics and interrupts blocked reads on connections it does not own. |
|
msgframe
Package msgframe converts between the control messages of package protocol and the frames of internal/controlwire that carry them, for the client runtime and coord.
|
Package msgframe converts between the control messages of package protocol and the frames of internal/controlwire that carry them, for the client runtime and coord. |
|
nat
Package nat is the NAT observation model that the client prober (internal/probe) and natprobe's authoritative merge (nat.ProbeHandle.Merge) share.
|
Package nat is the NAT observation model that the client prober (internal/probe) and natprobe's authoritative merge (nat.ProbeHandle.Merge) share. |
|
netaddr
Package netaddr holds the address helpers of the holepunch client runtime: canonical forms of netip values, conversion from net.Addr, and the address classes that target admission rejects.
|
Package netaddr holds the address helpers of the holepunch client runtime: canonical forms of netip values, conversion from net.Addr, and the address classes that target admission rejects. |
|
plan
Package plan is the pure-function direct-connection strategy engine the server coordinator (coord) and the client runtime share.
|
Package plan is the pure-function direct-connection strategy engine the server coordinator (coord) and the client runtime share. |
|
probe
Package probe is the client NAT prober of one address family.
|
Package probe is the client NAT prober of one address family. |
|
probetest
Package probetest builds and reads the datagrams of a session client that probes natprobe observers, for tests that play that client by hand: the natprobe server's own tests and the coordinator's tests against a real natprobe.
|
Package probetest builds and reads the datagrams of a session client that probes natprobe observers, for tests that play that client by hand: the natprobe server's own tests and the coordinator's tests against a real natprobe. |
|
ratelimit
Package ratelimit bounds the processing of unauthenticated datagrams.
|
Package ratelimit bounds the processing of unauthenticated datagrams. |
|
testkit
Package testkit holds the helpers the module's tests share: bounded polling waits that scale with the test binary's deadline, the race detector flag, and clocks that misbehave on purpose.
|
Package testkit holds the helpers the module's tests share: bounded polling waits that scale with the test binary's deadline, the race detector flag, and clocks that misbehave on purpose. |
|
trunc
Package trunc cuts text to a byte limit on a rune boundary.
|
Package trunc cuts text to a byte limit on a rune boundary. |
|
udpwire
Package udpwire encodes and decodes holepunch UDP packets: the punch, nomination and handover packets that clients exchange with each other, the probes clients send to natprobe, and natprobe's replies.
|
Package udpwire encodes and decodes holepunch UDP packets: the punch, nomination and handover packets that clients exchange with each other, the probes clients send to natprobe, and natprobe's replies. |
|
wiretype
Package wiretype is the frame type table of the control protocol: the major version every frame header carries, and each type's number, wire name, payload cap, direction and write priority.
|
Package wiretype is the frame type table of the control protocol: the major version every frame header carries, and each type's number, wire name, payload cap, direction and write priority. |
|
Package natprobe is holepunch's server-side NAT observer.
|
Package natprobe is holepunch's server-side NAT observer. |
|
Package nattest is an in-process NAT simulator for deterministic end-to-end tests of UDP hole punching: no real sockets, no root privileges and no dependence on the machine's network.
|
Package nattest is an in-process NAT simulator for deterministic end-to-end tests of UDP hole punching: no real sockets, no root privileges and no dependence on the machine's network. |
|
Package plan is the contract between holepunch's server coordinator (package coord) and a punch planner: the Planner interface and the values it reads and returns.
|
Package plan is the contract between holepunch's server coordinator (package coord) and a punch planner: the Planner interface and the values it reads and returns. |
|
Package portmapper asks the local NAT gateway to forward a UDP port to a socket — with PCP (RFC 6887), NAT-PMP (RFC 6886) or UPnP IGD — and keeps the mapping alive until it is released.
|
Package portmapper asks the local NAT gateway to forward a UDP port to a socket — with PCP (RFC 6887), NAT-PMP (RFC 6886) or UPnP IGD — and keeps the mapping alive until it is released. |
|
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, the 26 failure Reasons with their classes, and ControlSecurity.
|
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, the 26 failure Reasons with their classes, and ControlSecurity. |
|
quicpath
module
|
|
|
standalone
module
|
|
|
Package stun encodes and decodes the STUN Binding messages of RFC 8489 that discover a socket's public mapping, and asks a STUN server for it.
|
Package stun encodes and decodes the STUN Binding messages of RFC 8489 that discover a socket's public mapping, and asks a STUN server for it. |
|
tools
|
|
|
lintcheck
command
Command lintcheck enforces the holepunch robustness rules that go vet and staticcheck do not know about.
|
Command lintcheck enforces the holepunch robustness rules that go vet and staticcheck do not know about. |
|
Package udpsock holds the socket-level helpers that UDP NAT traversal needs and package net leaves out: ICMP error reports, the unicast TTL, and truncated reads.
|
Package udpsock holds the socket-level helpers that UDP NAT traversal needs and package net leaves out: ICMP error reports, the unicast TTL, and truncated reads. |