Documentation
¶
Overview ¶
Package portmap asks the local router to forward one UDP port to this machine, so that a host behind a NAT has a public address clients can reach whatever their own NAT does.
Hole punching needs at least one side whose NAT keeps the same public port for every destination. Between two symmetric NATs, or a symmetric one and a strict one, it fails and the session goes through the relay. Most home routers, though, let a program on the LAN open a port: through PCP (RFC 6887), its predecessor NAT-PMP (RFC 6886), or UPnP's Internet Gateway Device profile. A host that maps its punching socket's port has an address (the router's public IP and the mapped port) that answers unsolicited packets, which any client can probe.
A Mapper keeps one such mapping for the lifetime of a host: it tries PCP, then NAT-PMP, then UPnP, in the background and within a few seconds; renews the lease at half its lifetime; looks again, with backoff, when the router stops answering; and deletes the mapping when it is closed. Everything it reads from the network is treated as hostile: replies are accepted only from the gateway it asked, UPnP descriptions only from LAN addresses (see lanURL), and every read is bounded in size and time.
All three protocols are implemented here with the standard library; RemoHop links no UPnP or NAT-PMP library.
Index ¶
Constants ¶
const ( ProtoPCP = "PCP" ProtoNATPMP = "NAT-PMP" ProtoUPnP = "UPnP" )
Protocol names, as Mapping.Protocol reports them.
const Setting = "portmap"
Setting is the config key that turns router port mapping off for this machine's host. REMOHOP_PORTMAP=0 overrides it to off.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// Port is the local UDP port to forward.
Port uint16
// Logger gets one Info line per new mapping, Debug for the rest; nil
// discards.
Logger *slog.Logger
// OnChange, if set, is called (from the Mapper's goroutine) whenever
// the mapping appears, changes or goes away.
OnChange func()
}
Config says what to map and how.
type Mapper ¶
type Mapper struct {
// contains filtered or unexported fields
}
Mapper keeps one UDP port mapping on the local router; see the package comment.
func Start ¶
Start begins mapping cfg.Port in the background. It never blocks: the first attempt runs in its own goroutine.
func (*Mapper) Close ¶
Close stops the Mapper and deletes the mapping, giving the router about a second to confirm. OnChange is not called for it.
type Mapping ¶
type Mapping struct {
Protocol string // ProtoPCP, ProtoNATPMP or ProtoUPnP
External netip.AddrPort // the router's public address and the port it forwards
Internal netip.AddrPort // the LAN address and port it forwards to
Lifetime time.Duration // as granted; 0 for a UPnP mapping without expiry
}
Mapping is a port forwarding the router agreed to.