Documentation
¶
Overview ¶
Package nat gets two peers behind NATs talking directly: it gathers the addresses a peer might be reachable at (candidates), discovers how the local NAT behaves, and punches UDP holes so that a QUIC connection can be established peer to peer. There is no relay; when no direct path exists the caller gets ErrNoPath and Explain says why that is likely.
Everything runs on one UDP socket per process (Socket). The same socket carries the QUIC connection to the rendezvous server, the punch probes and finally the P2P QUIC session, because a NAT mapping belongs to a socket: the public address the rendezvous server observed is only useful to the peer if the session later leaves from that very socket.
Sharing the socket with QUIC ¶
quic-go's Transport demultiplexes on the first byte of each datagram: it treats a packet as QUIC when bit 0x80 (long header) or bit 0x40 (the QUIC "fixed bit") is set and hands everything else to ReadNonQUICPacket. All packets defined here therefore start with a type byte below 0x40. They are sent with Transport.WriteTo.
probe / probe-ack (36 bytes) type(1)=0x01|0x02 magic(3)="SDK" tag(8) txid(8) mac(16) reflect request (40 bytes) / response (36 bytes) type(1)=0x03 magic(3) txid(12) zero padding(24) type(1)=0x04 magic(3) txid(12) port(2) ip(16) alt-port(2)
Punching ¶
The rendezvous server gives both peers the same fresh 32-byte nonce and each other's candidates. Both then send probes to every candidate of the other side, repeatedly, for a few seconds. The first probes usually die at the receiving NAT, but each one opens (or refreshes) the sender's own mapping, so that the other side's next probe gets through. A probe is answered with a probe-ack to the address it came from; receiving an ack proves the path works in both directions, and the client then dials QUIC to that address.
tag and mac are derived from the nonce (HMAC-SHA256), so a peer only reacts to probes of a session it was told about, and the mac covers the sender's role so a probe cannot be bounced back at its sender. This is not what authenticates the session (the rendezvous server knows the nonce): it only keeps strangers from steering our probes. A valid probe from an address that is not among the candidates (peer-reflexive: the peer's NAT picked a new port for this destination, as symmetric NATs do) is answered and adopted as a further candidate, a bounded number of times per session.
Who sends first ¶
Many NATs keep state for packets they refuse. A Linux router whose own input chain accepts unsolicited packets is the common case: a probe that arrives at its public address before the machine behind it has sent anything to the prober is recorded as a flow to the router itself, and when the inside machine then sends its own probe, the router finds the obvious translation taken and moves the packet to a different source port. A cone NAT has turned symmetric for exactly this peer, and the punch is lost.
The host learns about a connection attempt before the client does (the rendezvous server asks the host first), so it is the host's probes that would arrive early. A host therefore starts by sending its probes to the client's public candidates with a very low TTL: enough to cross its own NAT and open the mapping there, not enough to reach the client's NAT. Normal probes follow once the host has heard from the client, whose own first probe has then already opened the client's NAT, or after hostHold at the latest. While it has not heard from the client, the host raises the TTL step by step (primeLadder): its own NAT may be more hops away than the first probes get, as an office firewall or a carrier-grade NAT is, and until that NAT is open the client's probes cannot get in. The client just sends. Where a per-packet TTL is not available (not Linux, or not a kernel UDP socket) the host sends normal probes from the start, as it would have to anyway to open its own NAT.
Symmetric NATs ¶
A peer behind a symmetric NAT reaches the other side from a port nobody advertised; that works when the other NAT does not filter by port, and the address is then adopted as peer-reflexive. When the other NAT does filter by port, the punch still works if the symmetric NAT hands out its ports in sequence: the symmetric side advertises a prediction of its next ports and the other side probes a bounded window of them (see predict.go). Two symmetric NATs, or one with random ports and a port-restricted one, cannot be punched.
Index ¶
- Constants
- Variables
- func ExcludeNetworks(nets ...netip.Prefix) (release func())
- func Excluded(ip netip.Addr) bool
- func Explain(local, remote Type, predicted bool) string
- func ExtractNAT64(prefix netip.Prefix, ip netip.Addr) (netip.Addr, bool)
- func InterfaceAddrs() []netip.Addr
- func NAT64PrefixFrom(addrs []netip.Addr) (netip.Prefix, bool)
- func NAT64Wanted() bool
- func PunchTime(local, remote Type, predicted bool) time.Duration
- func ResolveUDP(ctx context.Context, local net.Addr, hostport string) (*net.UDPAddr, error)
- func Routable(ip netip.Addr) bool
- func ServeReflect(pc net.PacketConn) error
- func ServeReflectQUIC(ctx context.Context, tr *quic.Transport, altPort uint16) error
- func SetNAT64LookupForTest(f func(context.Context) ([]netip.Addr, error)) (restore func())
- func SynthesizeNAT64(prefix netip.Prefix, v4 netip.Addr) (netip.Addr, bool)
- func UsesPrediction(local, remote Type, localPred, remotePred bool) bool
- func WrapNAT64(pc net.PacketConn) net.PacketConn
- type ByteBudget
- type ConnectConfig
- type PathConn
- func (c *PathConn) Close() error
- func (c *PathConn) LocalAddr() net.Addr
- func (c *PathConn) ReadFrom([]byte) (int, net.Addr, error)
- func (c *PathConn) SetDeadline(t time.Time) error
- func (c *PathConn) SetReadBuffer(int) error
- func (c *PathConn) SetReadDeadline(t time.Time) error
- func (c *PathConn) SetTarget(to netip.AddrPort)
- func (c *PathConn) SetWriteBuffer(int) error
- func (c *PathConn) SetWriteDeadline(time.Time) error
- func (c *PathConn) Target() netip.AddrPort
- func (c *PathConn) WriteTo(p []byte, _ net.Addr) (int, error)
- type Prediction
- type PunchConfig
- type Punched
- type RelayLimits
- type RelayStats
- type Role
- type Session
- type Socket
- func (s *Socket) BindRelay(ctx context.Context, relay netip.AddrPort, nonce []byte, role Role) error
- func (s *Socket) Candidates() []netip.AddrPort
- func (s *Socket) Close() error
- func (s *Socket) Connect(ctx context.Context, cfg ConnectConfig) (*quic.Conn, Punched, error)
- func (s *Socket) LocalAddr() net.Addr
- func (s *Socket) NATType() Type
- func (s *Socket) NewPathConn() *PathConn
- func (s *Socket) Prediction() (Prediction, bool)
- func (s *Socket) ProbeNAT(ctx context.Context, server netip.AddrPort) Type
- func (s *Socket) Punch(nonce []byte, role Role, remote []netip.AddrPort, lifetime time.Duration) (*Session, error)
- func (s *Socket) PunchWith(cfg PunchConfig) (*Session, error)
- func (s *Socket) Redirect(from, to netip.AddrPort)
- func (s *Socket) Reflexive(ctx context.Context, server netip.AddrPort) (netip.AddrPort, error)
- func (s *Socket) RefreshPrediction(ctx context.Context)
- func (s *Socket) ReleaseRelay(relay netip.AddrPort, nonce []byte, role Role)
- func (s *Socket) Transport() *quic.Transport
- type SocketOptions
- type Type
Constants ¶
const ( // NonceSize is the length of the session nonce the rendezvous server // hands to both peers. NonceSize = 32 // DefaultPunchTime is how long the peers keep probing before the // attempt is declared failed. NATs that are going to open do so within // the first few probes; the rest is margin for packet loss. DefaultPunchTime = 8 * time.Second )
const DefaultPreferWait = time.Second
DefaultPreferWait is how long a proven but not preferred path waits for a preferred one. An overlay network answers within its round trip, which through its own relays can be a few hundred milliseconds.
const InitialPacketSize = 1200
InitialPacketSize is the UDP payload size every QUIC connection on a RemoHop socket starts with: the smallest QUIC allows. quic-go's default (1280 bytes, 1308 on the wire over IPv4) is more than paths through a WireGuard, Tailscale or other tunnel at MTU 1280, many corporate VPNs and some IPv6 tunnels carry, and the DF bit it sets turns such a path into a black hole: the handshake never completes while the small punch probes pass. Path MTU discovery raises the size within a few round trips where the path allows. Every quic.Config RemoHop uses sets it.
const MaxCandidates = 6
MaxCandidates bounds how many local addresses a peer advertises. The rendezvous server enforces the same bound; it also caps how many addresses a stranger can make us send probes to.
Variables ¶
var ErrNoPath = errors.New("no direct path to the peer")
ErrNoPath is returned when no candidate answered: the peers could not be connected directly.
Functions ¶
func ExcludeNetworks ¶
ExcludeNetworks marks networks this process tunnels itself, which must never carry a punched path, until release is called. Registering the same network twice needs two releases; release may be called more than once.
func Explain ¶
Explain turns the two sides' NAT types into the most likely reason a punch failed, for the error shown to the user. predicted says the punch used port prediction (see UsesPrediction).
func ExtractNAT64 ¶
ExtractNAT64 returns the IPv4 address embedded in ip under prefix, if ip is in it.
func InterfaceAddrs ¶
InterfaceAddrs returns the addresses of this machine's active network interfaces that a peer might reach: every IPv4 address except loopback and link-local (private ones matter most: they are how two machines on the same LAN find each other), and global or unique-local IPv6 addresses; not those in a network the mesh registered (see ExcludeNetworks).
Only the first MaxCandidates are advertised, so the order matters:
- the addresses of a Tailscale interface: they work through any NAT when both peers are on the same tailnet (see internal/tailnet);
- the addresses the machine sends from on its default routes, IPv4 then IPv6: the real LAN address, and the IPv6 address a punch's packets actually leave from (a stateful firewall opens only for that one);
- other IPv4, then IPv6, addresses of interfaces that are up and do not look virtual;
- last, those of virtual adapters (Hyper-V and WSL switches, Docker and libvirt bridges, VMware, VirtualBox) and of interfaces without a carrier, which on a developer's machine could otherwise crowd the real LAN address out of the list.
func NAT64PrefixFrom ¶
NAT64PrefixFrom finds the NAT64 prefix in the AAAA answer for ipv4only.arpa (RFC 7050 section 3): an address that embeds one of the well-known IPv4 addresses at a valid position.
func NAT64Wanted ¶
func NAT64Wanted() bool
NAT64Wanted reports whether Listen wraps its sockets with WrapNAT64: on iOS (where Apple's review network is IPv6-only and the system offers no translation of IPv4 literals to BSD sockets), or as REMOHOP_NAT64 says ("on"/"off"). Android translates in the system (464XLAT), desktops and hosts rarely need it, and the wrapper costs quic-go's batched I/O.
func PunchTime ¶
PunchTime is how long it is worth probing given what both sides measured. Two symmetric NATs cannot be punched, so only a moment is spent on the chance that a LAN or IPv6 candidate answers; with one symmetric NAT it either works within the first few probes (the other NAT does not filter by port) or never. With port prediction (predicted, see UsesPrediction) the window of predicted ports is probed in several passes over the first few seconds, the first of them possibly only after predictLead.
func ResolveUDP ¶
ResolveUDP resolves "host:port" for a socket that is bound as local says (an IPv4-only socket can only use IPv4 addresses), within ctx: a resolver that hangs (a dead first name server, a captive portal, the moment after a network switch) cannot hold a dial past its deadline or keep the user's Disconnect waiting.
Of the name's addresses it returns the first this machine has a route to, IPv4 first: on an IPv6-only network without NAT64 a dual-stack name then still works through its AAAA record, where the system's first answer, the A record, would fail with "network is unreachable".
func Routable ¶
Routable reports whether ip is a globally routable address: one that packets sent blindly could bother a stranger at. Carrier-grade NAT space is not; like RFC 1918 space it never leaves the network it is used in.
func ServeReflect ¶
func ServeReflect(pc net.PacketConn) error
ServeReflect answers reflect requests on pc with the source address each request arrived from, until pc is closed. A rendezvous server runs it on a second UDP port: a peer that compares the address reported there with the one reported on the main port learns whether its NAT maps per destination.
func ServeReflectQUIC ¶
ServeReflectQUIC answers reflect requests arriving on a QUIC transport's socket (they are not QUIC packets, see the package comment) until ctx ends, also telling each requester altPort, the port ServeReflect runs on. A rendezvous server runs it on its main port, so a peer can learn its public address there, find the second service and measure its NAT without a round trip on the rendezvous connection, and before it has asked for any introduction.
func SetNAT64LookupForTest ¶
SetNAT64LookupForTest replaces the ipv4only.arpa lookup (tests of other packages simulating an IPv6-only network) and returns the function that restores it.
The swap happens under the discovery lock, which discoverNAT64 holds while it calls nat64Lookup: a socket left over from an earlier test may still be sending (and so discovering) while the next test swaps the function.
func SynthesizeNAT64 ¶
SynthesizeNAT64 returns the IPv4-embedded IPv6 address of v4 under the NAT64 prefix (RFC 6052 section 2.2).
func UsesPrediction ¶
UsesPrediction reports whether a punch between two sides with these NAT types uses port prediction: one side is symmetric and has a prediction (localPred, remotePred), and the other, whose NAT is a cone or who has none, probes the predicted ports. Two symmetric NATs do not: probing a window from a symmetric NAT would take a new port per probe and run its own allocator past what the peer predicted.
func WrapNAT64 ¶
func WrapNAT64(pc net.PacketConn) net.PacketConn
WrapNAT64 returns pc with IPv4 destinations translated through the network's NAT64 when IPv4 itself is unreachable (see the comment at the top of this file). pc should be a dual-stack (or IPv6) UDP socket.
Types ¶
type ByteBudget ¶
type ByteBudget struct {
// contains filtered or unexported fields
}
ByteBudget is a token bucket of bytes, safe for concurrent use. It can police (Take) or pace (reserve: go into debt for up to a given delay).
func NewByteBudget ¶
func NewByteBudget(rate int) *ByteBudget
NewByteBudget allows rate bytes per second, with bursts of one second's worth.
func (*ByteBudget) Take ¶
func (b *ByteBudget) Take(n int) bool
Take spends n bytes if the budget has them and reports whether it did. A nil budget always has them.
type ConnectConfig ¶
type ConnectConfig struct {
Nonce []byte // session nonce from the rendezvous server
Remote []netip.AddrPort // the host's candidates
TLS *tls.Config
QUIC *quic.Config
// PunchTime overrides DefaultPunchTime.
PunchTime time.Duration
// Prefer, if set, marks candidates worth waiting for: the host's
// address on an overlay network both peers are on, such as a tailnet.
// A proven path that is neither preferred nor on a LAN is held back
// for up to PreferWait (default DefaultPreferWait) in case a
// preferred one answers, and while a handshake over a preferred path
// is in progress. Preferring a path never changes what runs over it:
// the same QUIC session and login, whatever the path.
Prefer func(netip.AddrPort) bool
PreferWait time.Duration
// Predicted is the host's port prediction; see PunchConfig.
Predicted Prediction
// Logger, if set, gets the timing of each step at debug level: when
// each path answered, when each handshake started and how it ended.
Logger *slog.Logger
// OnPath, if set, is called (from Connect's goroutine) when the first
// path has answered: a direct connection is under way. A caller racing
// a relay against the punch uses it to keep waiting for the direct one.
OnPath func()
}
ConnectConfig describes a P2P connection attempt.
type PathConn ¶
type PathConn struct {
// contains filtered or unexported fields
}
A relayed session can move to a direct path without being re-established: QUIC lets the client probe a new path for its connection and switch to it (connection migration, RFC 9000 section 9), and quic-go's client does so with Conn.AddPath, given another quic.Transport to send on. The server side accepts the move by itself once the new path has been validated.
quic-go assumes a new path means a new local socket towards the same server address. Here it is the reverse: the same socket, but a new address for the host (its punched address instead of the relay). A PathConn bridges the two: a packet connection on this socket that sends whatever QUIC hands it to the address set with SetTarget, whatever address QUIC names (the relay's, which the connection keeps calling the host's).
It only sends. What the host sends back over the new path arrives on the socket like any other packet and reaches the connection through the socket's own transport, which knows all of the connection's IDs. So ReadFrom returns nothing until the PathConn is closed or its read deadline passes.
Nothing about the session's security changes: the new path carries the same QUIC connection, under the keys negotiated with the authenticated host. A path is validated by a PATH_CHALLENGE answered inside that connection, which only the host holding those keys can do; a path to anybody else (a third party that answered the punch, a stray address) is never validated and never used.
func (*PathConn) Close ¶
Close makes ReadFrom return and drops every later send. Close the quic.Transport on a PathConn only once the connection that added a path on it has ended: closing a transport ends every connection registered with it.
func (*PathConn) ReadFrom ¶
ReadFrom blocks until the PathConn is closed or its read deadline passes; see the type's comment.
func (*PathConn) SetDeadline ¶
SetDeadline sets the read deadline; writes never block.
func (*PathConn) SetReadBuffer ¶
SetReadBuffer and SetWriteBuffer do nothing: the socket underneath has its buffers set already. They keep quic-go from warning that they are missing.
func (*PathConn) SetReadDeadline ¶
SetReadDeadline implements net.PacketConn.
func (*PathConn) SetWriteBuffer ¶
func (*PathConn) SetWriteDeadline ¶
SetWriteDeadline implements net.PacketConn; writes never block.
type Prediction ¶
Prediction describes a NAT that allocates its public ports in sequence: Last is the most recent port observed, on public address IP, and Step the stride to the next one (negative for an allocator counting down).
func ReadHint ¶
ReadHint looks for a Hint at the end of a peer's self-reported candidates local, and returns the prediction it encodes together with the remaining candidates; without one it returns local unchanged. reflexive is the peer's address as the rendezvous server observed it: a hint counts only on that address, and the prediction is always for that address. Honest peers without a hint never end their list with two addresses on it (the only public address they report, a router-mapped one, comes first).
func (Prediction) Hint ¶
func (p Prediction) Hint() []netip.AddrPort
Hint encodes p for the peer as two self-reported candidates: the first two predicted ports on the public address. That address is the one the rendezvous server observes, so they pass its filter (it forwards self-reported IPv4 addresses only on the observed one), and the server needs no change. They go last in the list (see ReadHint). A peer that does not know about predictions simply probes them, which is harmless and can even work.
func (Prediction) Port ¶
func (p Prediction) Port(k int) uint16
Port returns the k-th port predicted after Last, wrapping around the port space; 0 means that guess falls on port 0 and is skipped.
func (Prediction) Valid ¶
func (p Prediction) Valid() bool
Valid reports whether p describes a usable prediction: an IPv4 address and a stride of at least one and at most maxPredictStep ports.
type PunchConfig ¶
type PunchConfig struct {
Nonce []byte
Role Role
Remote []netip.AddrPort
Lifetime time.Duration
// Predicted is the peer's port prediction (see predict.go) as the
// rendezvous exchange delivered it: its IP is the address the server
// observed the peer at. When it is valid and our NAT is a cone (or
// there is none), the session also probes up to maxPredicted
// predicted ports on that address. It is ignored for an address that
// is not among Remote or not globally routable.
Predicted Prediction
}
PunchConfig describes a punch session; see Punch.
type Punched ¶
type Punched struct {
// Remote is the host address the connection runs to.
Remote netip.AddrPort
// Predicted reports that Remote is one of the host's predicted ports
// this side probed (ConnectConfig.Predicted), adopted when it answered.
Predicted bool
}
Punched is the path Connect found.
type RelayLimits ¶
type RelayLimits struct {
// Rate is the session's budget in bytes per second (both directions
// together). Traffic above it is paced: held back for up to MaxDelay
// and then dropped, like at any bottleneck router with a short queue.
// The queueing delay and the occasional tail drop are signals the
// peers' QUIC congestion control handles well; dropping every packet
// over the rate at once (a policer) makes it collapse to a fraction
// of the rate.
Rate int
// Global, if not nil, is a budget shared with other sessions; it is
// paced the same way.
Global *ByteBudget
// Idle ends a session that has passed nothing for this long.
Idle time.Duration
// Meter, if set, is told the size of every relayed packet.
Meter func(n int)
// MaxDelay is the longest a packet is held back. Default 100 ms;
// negative drops instead of delaying (a policer with a one-second
// bucket, which is how the relay used to work).
MaxDelay time.Duration
}
RelayLimits bounds what one relayed session may cost the operator.
type RelayStats ¶
type RelayStats struct {
// Packets and Bytes were relayed; Delayed of the packets were paced;
// Dropped were not relayed for want of budget.
Packets, Bytes, Delayed, Dropped int64
}
RelayStats is what a finished relay session passed on.
func ServeRelay ¶
func ServeRelay(ctx context.Context, pc net.PacketConn, nonce []byte, limits RelayLimits) RelayStats
ServeRelay relays between the two peers that bind to pc with nonce until ctx ends or the session has been idle for limits.Idle, then closes pc.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session is one punch in progress towards one peer.
type Socket ¶
type Socket struct {
// Locals lists the machine's own addresses for candidate gathering and
// NAT detection. It defaults to InterfaceAddrs; tests on a virtual
// network replace it before use.
Locals func() []netip.Addr
// Mapped, if set, returns the public address the local router forwards
// to this socket's port (see internal/portmap), or the zero value while
// there is none. Candidates puts it first. Set it before use.
Mapped func() netip.AddrPort
// Excluded reports addresses no punched path may use: neither
// advertised, nor probed, nor accepted as the source of a probe or an
// ack. It defaults to the package's Excluded (networks the mesh
// registered with ExcludeNetworks); tests replace it before use.
Excluded func(netip.Addr) bool
// contains filtered or unexported fields
}
Socket is the one UDP socket a peer does everything on: QUIC (through Transport) and the non-QUIC punch and reflect packets handled here.
func Listen ¶
Listen opens a UDP socket on addr ("" or ":0" for any port on all interfaces) and wraps it. A socket on all interfaces is dual-stack and, where NAT64Wanted, reaches IPv4 addresses through the network's NAT64 when there is no IPv4 (see nat64.go).
func ListenWith ¶
func ListenWith(addr string, o SocketOptions) (*Socket, error)
ListenWith is Listen with options.
func NewSocket ¶
func NewSocket(pc net.PacketConn) (*Socket, error)
NewSocket wraps an existing packet connection, which the Socket then owns.
func NewSocketWith ¶
func NewSocketWith(pc net.PacketConn, o SocketOptions) (*Socket, error)
NewSocketWith is NewSocket with options.
func (*Socket) BindRelay ¶
func (s *Socket) BindRelay(ctx context.Context, relay netip.AddrPort, nonce []byte, role Role) error
BindRelay attaches this socket to the relay session at relay, as role. It returns once the relay has acknowledged with proof that it holds the session nonce.
func (*Socket) Candidates ¶
Candidates returns the socket's self-reported candidates: its port on each address in Locals, or just the bound address if the socket is bound to one; and first, when the router forwards a public port to the socket (Mapped), that address.
At most MaxCandidates local addresses are listed, so the mapped address makes the list one longer rather than pushing a LAN address out; the rendezvous server's bound on what a peer reports leaves room for it.
func (*Socket) Close ¶
Close shuts the socket down, abruptly ending any QUIC connection still using it; close those first.
func (*Socket) Connect ¶
Connect punches towards the host and establishes QUIC over the first path that works, returning the connection and the path it runs on. When several candidates answer, their handshakes race and the losers are cancelled. It returns an error wrapping ErrNoPath when no candidate answers within the punch time.
func (*Socket) NewPathConn ¶
NewPathConn returns a PathConn on this socket with no target yet: sends are dropped until SetTarget names one.
func (*Socket) Prediction ¶
func (s *Socket) Prediction() (Prediction, bool)
Prediction returns how the socket's NAT allocates ports, if ProbeNAT found it symmetric with ports handed out in sequence.
func (*Socket) ProbeNAT ¶
ProbeNAT classifies the NAT in front of this socket with the help of a rendezvous server at server (its main address, where ServeReflectQUIC runs), and remembers the answer for NATType. It asks the main port and the server's second reflect port what public address its packets come from; a different answer means the NAT picks the mapping per destination.
It must run before the socket starts probing peers: a NAT that has seen punch traffic for this socket can answer differently afterwards. It can run while the rendezvous connection is still being established: the second port is almost always the one after the main port, so that is asked right away, and the main port's answer says if it is another one.
A NAT that maps per destination address but not per port would be taken for a cone here, since both observations come from one server address; such NATs are rare and the punch itself is the final judge anyway. When either port does not answer before ctx ends the result is TypeUnknown.
For a symmetric NAT the two observations are also two consecutive mappings, which say whether its ports can be predicted (see Prediction). The request to the main port therefore leaves first: the mapping towards it is made by that request or by the rendezvous handshake, never after the one towards the second port.
func (*Socket) Punch ¶
func (s *Socket) Punch(nonce []byte, role Role, remote []netip.AddrPort, lifetime time.Duration) (*Session, error)
Punch starts probing remote, the peer's candidates, and answering the peer's probes, for at most lifetime. Both peers must call it with the same nonce and opposite roles. The caller should Close the session once it has what it wanted.
func (*Socket) PunchWith ¶
func (s *Socket) PunchWith(cfg PunchConfig) (*Session, error)
PunchWith is Punch with the whole configuration.
func (*Socket) Redirect ¶
Redirect makes the socket send every QUIC packet addressed to from to the address to instead, until another call replaces the redirect; an invalid to (the zero value) ends it. Packets from either address arrive as they are. See the comment above for what it is for.
func (*Socket) Reflexive ¶
Reflexive asks a reflect server (see ServeReflect) for the public address this socket's packets arrive from. The request is retransmitted until an answer arrives or ctx ends.
func (*Socket) RefreshPrediction ¶
RefreshPrediction brings the last port of the prediction up to date, for a long-running host whose measurement is old while the allocator has moved on with the LAN's other traffic. It asks the rendezvous server's second port again: once the NAT has forgotten the mapping towards it from the measurement (an idle UDP mapping lasts from half a minute to a few minutes), the answer is a new mapping, at the allocator's current position. Until then the answer is the old mapping, and nothing changes. It costs one round trip to the server, bounded by ctx.
func (*Socket) ReleaseRelay ¶
ReleaseRelay tells the relay at relay that this socket's session (of nonce, as role) is over, so that it is freed at once. Best effort: the relay ends idle sessions by itself anyway.
type SocketOptions ¶
type SocketOptions struct {
// StatelessResetKey, if set, makes the socket answer a packet of a
// QUIC connection it does not know, such as one of this program's
// previous run on the same port, with a stateless reset (RFC 9000,
// 10.3). The other end then drops the connection at once instead of
// after its idle timeout. The key must stay secret, and the same across
// restarts for the resets to be recognised.
StatelessResetKey *quic.StatelessResetKey
}
SocketOptions tune a Socket when it is made.
type Type ¶
type Type string
Type describes a NAT's mapping behaviour, which decides whether hole punching can work.
const ( // TypeUnknown: not measured (no second server port, or no answer). TypeUnknown Type = "unknown" // TypeNone: the socket's public address is a local interface address. TypeNone Type = "none" // TypeCone: endpoint-independent mapping. The public port is the same // whatever the destination, so the address the rendezvous server saw // is where the peer can reach us. Punchable. TypeCone Type = "cone" // TypeSymmetric: the public port depends on the destination, so the // peer cannot know which port our packets to it will come from. It // only works when the peer accepts packets from unexpected ports. TypeSymmetric Type = "symmetric" )