burrow

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 31 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Burrow

Burrow opens direct TCP connections between two hosts that are both behind NAT, and hands them to you as an ordinary net.Listener and net.Conn.

A small public signal server introduces the two peers; after that, every byte flows over a TCP connection established by simultaneous open (TCP hole punching). Nothing is relayed.

Features

  • Standard Go interfaces. burrow.Listen returns a net.Listener you can hand to http.Serve or a gRPC server; Dialer.Dial returns a net.Conn.
  • Several punching strategies for different NAT types, plus auto, which measures the dialer's NAT and picks one.
  • Clean connections. The first byte you read is the first byte the peer wrote. Burrow never adds framing on the data path (the optional ack selection mode exchanges a fixed-size authenticated prefix and consumes it before returning).
  • Built for real networks: binding to a physical interface when a VPN or TUN device owns the default route, IPv4 or IPv6, custom DNS resolution for the signal server, per-connection TCP statistics, back-pressure and resource budgets.
  • Batteries included: a self-hostable signal server with a one-line installer, a CLI with NAT diagnostics and a web console, a TCP port-forwarding tunnel, and an Android client.

How it works

   host A (listener)                 signal server                 host B (dialer)
        |  LISTEN room ---------------->  |                               |
        |                                 |  <------------- DIAL room     |
        |  <----------- INCOMING          |                               |
        |  echo: learn public ip:port --> |  <-- echo: learn public ip:port
        |  READY (endpoint) ------------> |  -------------> PEER (endpoint)
        |                                                                 |
        |  <==========  simultaneous TCP open, same local ports  ========>|
  1. Signaling. The listener keeps a WebSocket open to the signal server and registers a room. The dialer joins the same room with a fresh session ID.
  2. Address discovery. Each side opens a TCP connection to the server's echo endpoint from the local port it will punch with, so the server reports the public ip:port the NAT assigned to that port (STUN, but for TCP). The mapping is held open while the attempt runs.
  3. Punching. Both sides exchange endpoints through the server and dial each other from the same local port (SO_REUSEADDR/SO_REUSEPORT) while also accepting on it. Whichever TCP handshake completes first wins.

How each side dials depends on the strategy:

Strategy Use it when What happens
direct Both NATs keep the same public port for every destination (endpoint-independent mapping, "cone" NATs). Each side dials the exact endpoint the other reported.
predictive The dialer's NAT allocates ports sequentially. The listener (which must be on the stable side) dials a window of Predictive.PortScanRange ports (default 512) around the dialer's observed port.
birthday The dialer's NAT picks ports randomly (symmetric / carrier-grade NAT). The stable side pre-opens Birthday.Candidates (default 256) connections to random ports while the other side opens as many connections to the stable endpoint; a collision yields a connection, as in the birthday paradox.
auto You do not know the dialer's NAT. The dialer samples its NAT mapping behaviour against at least three echo endpoints (NATProbe.Targets) and picks direct, predictive or birthday.

Negotiated parameters (strategy, scan range, birthday settings) are chosen by the dialer and sent to the listener in the DIAL message; both sides verify a fingerprint of them, so mismatched configurations fail fast instead of punching blindly. predictive, birthday and auto assume the listener is the side with a stable mapping; birthday and auto require the listener to declare it with StableSide: true.

Burrow also contains an experimental UDP API (ListenPacket, NewPacketDialer) that punches UDP paths for use by an upper-layer protocol such as QUIC; it supports the direct and predictive strategies.

Install

go get github.com/getkiko/burrow

Burrow needs Go 1.25 or later. TCP hole punching relies on SO_REUSEPORT and works on Linux (including Android), macOS and the BSDs; on other platforms Listen and Dial return an error.

The CLI and the signal server:

go install github.com/getkiko/burrow/cmd/burrow@latest
go install github.com/getkiko/burrow/cmd/burrow-signal@latest

Prebuilt binaries are attached to each GitHub release.

SDK usage

Both peers need the same signal server address and the same room name.

Listener:

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/getkiko/burrow"
)

func main() {
	ln, err := burrow.Listen(burrow.Config{
		SignalAddr:    "signal.example.com:9960",
		Room:          "my-room",
		BindInterface: "eth0", // recommended: the physical interface to punch from
	})
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close()

	// ln is a net.Listener: every Accept returns a new punched connection.
	log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello from %s\n", r.Host)
	})))
}

Dialer:

package main

import (
	"context"
	"io"
	"log"
	"net"
	"net/http"
	"os"

	"github.com/getkiko/burrow"
)

func main() {
	d, err := burrow.NewDialer(burrow.Config{
		SignalAddr: "signal.example.com:9960",
		Room:       "my-room",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer d.Close()

	// Each Dial runs one punching round and returns an independent net.Conn.
	client := &http.Client{Transport: &http.Transport{
		DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
			return d.Dial(ctx)
		},
	}}
	resp, err := client.Get("http://peer/")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	io.Copy(os.Stdout, resp.Body)
}

Choosing a strategy on the dialer (the listener adopts it from the signal message):

d, err := burrow.NewDialer(burrow.Config{
	SignalAddr: "signal.example.com:9960",
	Room:       "my-room",
	Strategy:   burrow.StrategyAuto,
	Birthday: burrow.BirthdayOptions{
		Selection: burrow.CandidateSelectionACK, // required for birthday and auto
	},
	// auto measures the NAT against at least three distinct echo endpoints,
	// e.g. one signal server listening on several ports.
	NATProbe: burrow.NATProbeOptions{
		Targets: []string{
			"signal.example.com:9960",
			"signal.example.com:9962",
			"signal.example.com:9963",
		},
	},
})

ln, err := burrow.Listen(burrow.Config{
	SignalAddr: "signal.example.com:9960",
	Room:       "my-room",
	Strategy:   burrow.StrategyAuto,
	StableSide: true, // this host's NAT keeps a stable mapping
})

Errors can be inspected with errors.Is: ErrPunchFailed, ErrNoListener, ErrUnsupportedNATPair, ErrStrategyMismatch, ErrResourceLimit, ErrClosed. Set InfoLog/DebugLog to route logs into your logger, or set BURROW_DEBUG=1 for diagnostic output on stderr. See docs/sdk.md and docs/configuration.md for every option, and examples/ for a runnable echo server and client.

CLI

burrow bundles a port-forwarding tunnel, a punching demo and NAT diagnostics:

# Forward local port 1080 to 127.0.0.1:29999 on a host behind another NAT.
burrow tunnel server -c server.json     # on the host that runs the service
burrow tunnel client -c client.json     # on the host that wants to reach it

# One-shot TCP punch with an HTTP request on top (and an optional throughput test).
# -iface is optional; without it the kernel routing table picks the interface.
burrow punch server -signal signal.example.com:9960 -room demo [-iface eth0]
burrow punch client -signal signal.example.com:9960 -room demo [-iface en0] [-bench -size 100MB]

# Diagnose your NAT.
burrow tcpnat -server signal.example.com:9960 -ports 9960,9962,9963 -rounds 5
burrow stun                              # UDP NAT type via STUN

# The same tools in a browser: http://127.0.0.1:18083/
# It must listen on a loopback address (-listen 127.0.0.1:PORT, [::1]:PORT or
# localhost:PORT) and only accepts requests addressed to localhost or a loopback
# IP. It has no authentication; for remote use, forward the port over SSH.
burrow api

Tunnel configuration is JSON; see tunnel/README.md and the samples in tunnel/example/. burrow birthday server|client runs the birthday-collision experiment described in internal/birthdaylab/README.md.

Signal server

The signal server only introduces peers and echoes public addresses; it never sees application data. It needs a public IP and inbound TCP on the ports it listens on. Clients must reach those ports directly: the address echo reports the TCP source address the server sees, and echo tokens are bound to that address, so the server cannot run behind a reverse proxy, a load balancer or any other L7 or TCP-terminating front end.

One-line install on Linux (systemd), from the latest GitHub release:

curl -fsSL https://raw.githubusercontent.com/getkiko/burrow/main/signal-deploy/install.sh | sudo bash

Or run it yourself:

burrow-signal -listen :9960,:9962,:9963 -stat 127.0.0.1:9961
  • -listen takes several ports. Every port serves the same room registry; the extra ports let auto and burrow tcpnat observe how the NAT maps one local port to different destinations.
  • -prefix /some/path changes the HTTP path of the entry point (<prefix>?command=signal|echo|nat|health); it only renames the path and does not make the server proxy-friendly. Clients then use signal.example.com:9960/some/path as SignalAddr. The fixed paths /signal, /echo, /probe, /nat and /health are always served as well.
  • BURROW_SIGNAL_SECRET sets the key that signs echo tokens; set it to a random value so tokens survive restarts and cannot be forged.
  • -stat exposes counters at http://<addr>/stat; bind it to localhost.
  • Abuse limits: LISTEN and DIAL are rate limited per source, where a source is an IPv4 address or an IPv6 /64. -max-signal-per-ip (default 256) caps concurrent signaling connections per source, -max-nat-per-ip (default 64) caps concurrent nat mapping probes per source, and -max-rooms-per-conn (default 32) caps the rooms one connection may listen on or dial into; 0 disables a cap. -idle-timeout (default 60s) closes signaling connections that send nothing; listeners renew every 5 seconds, so only idle clients are affected and they reconnect when needed.

See signal-deploy/README.md for the installer's options.

Android

android/ is a Kotlin / Jetpack Compose client that runs the tunnel on a phone, with a NAT diagnostics screen and live statistics. It uses the gomobile bindings in mobile/:

make aar-install   # once: install gomobile and gobind
make apk           # builds build/tunnel.aar, copies it into the app and assembles a debug APK

See android/README.md.

Limitations

  • TCP only for the net.Listener / net.Conn API; the UDP packet API is experimental and supports only direct and predictive.
  • Not every NAT pair can be punched. Two randomly-mapping NATs cannot be traversed by any strategy here; predictive, birthday and auto need one side with a stable mapping. There is no relay fallback; Dial returns an error instead.
  • No encryption or authentication of the data path. Run TLS (or another authenticated protocol) over the connection.
  • Room names are not secrets, and the signal server does not authenticate listeners. Anyone who knows the room can dial your listener, and anyone who knows it can also register as the listener of that room: the room follows whichever listener renewed last (listeners renew every few seconds), so an impostor can receive some of your dialers' attempts. Authenticate both ends above Burrow, for example with mutual TLS, and treat a failed handshake as a failed attempt. With the UDP packet API, set SignProof/VerifyProof (see NewProofSigner): a peer without the shared password cannot produce a valid proof, so an impostor turns into a failed attempt instead of a connection. The signal server never holds that password, so it cannot itself decide which listener is genuine.
  • Requires SO_REUSEPORT (Linux, Android, macOS, BSD). Windows is not supported.
  • Firewalls that drop unsolicited inbound SYNs regardless of NAT state, and middleboxes that rewrite TCP sequence numbers, may defeat simultaneous open.

License

MIT

Documentation

Overview

Package burrow establishes direct TCP connections between two hosts behind NAT using TCP hole punching, coordinated through a signal server.

The API mirrors the standard library. Listen returns a net.Listener whose Accept yields a new net.Conn for every peer that dials in, and NewDialer returns a Dialer whose Dial opens a new net.Conn to the listening peer. What runs over the connection is entirely up to the caller.

Both sides need the same signal server address (Config.SignalAddr) and the same room name (Config.Room). The signal server provides WebSocket signaling and reflects each side's public TCP endpoint; it never relays application data. A typical setup:

// One side listens.
ln, err := burrow.Listen(burrow.Config{
	SignalAddr: "signal.example.com:9960",
	Room:       "my-room",
})
if err != nil {
	return err
}
defer ln.Close()
for {
	conn, err := ln.Accept()
	if err != nil {
		return err
	}
	go handle(conn)
}

// The other side dials.
d, err := burrow.NewDialer(burrow.Config{
	SignalAddr: "signal.example.com:9960",
	Room:       "my-room",
})
if err != nil {
	return err
}
defer d.Close()
conn, err := d.Dial(context.Background())

Strategies

Config.Strategy selects how the two sides punch. The Dialer decides the strategy parameters and sends them to the Listener in the DIAL request.

  • StrategyDirect: each side binds one local port, learns its public endpoint from the signal server, and both sides dial each other's endpoint while also accepting on that port (TCP simultaneous open). Works when both NATs keep a stable mapping per local port.
  • StrategyPredictive: for a NAT that allocates public ports sequentially. The Listener (the stable side) scans a window of PortScanRange ports centered on the Dialer's reflected port, while the Dialer dials the Listener's stable endpoint.
  • StrategyBirthday: for a NAT that allocates ports unpredictably. The Listener dials many random ports on the Dialer's public IP from its stable port, while the Dialer opens as many connections to the Listener's endpoint from fresh local ports, relying on a birthday collision between the two sets.
  • StrategyAuto: the Dialer probes its NAT through the targets in Config.NATProbe (at least three distinct signal servers), classifies it as stable, sequential or dispersed, and the Listener picks direct, predictive or birthday accordingly.

Birthday and auto require the Listener to sit behind a stable-mapping NAT and to set Config.StableSide. A Dialer with an empty Strategy accepts whatever strategy the Listener picks; a Listener with an empty Strategy uses direct.

Connection delivery

Direct, predictive and birthday with CandidateSelectionFanout deliver connections with no prefix: the first byte read is application data, and the upper-layer protocol is expected to detect and retry a dead candidate. Birthday with CandidateSelectionACK first exchanges a fixed-size, HMAC-authenticated selection frame so that one Dial and one Accept agree on the same connection; that frame is consumed before the connection is returned, so the caller still starts reading at the first application byte.

Packet API

ListenPacket and NewPacketDialer are an experimental UDP counterpart, configured with PacketConfig. They yield a PacketAttempt whose Commit returns a net.PacketConn for an upper-layer protocol such as QUIC. This API may change.

Index

Constants

View Source
const (
	StrategyAuto       = signalproto.StrategyAuto
	StrategyDirect     = signalproto.StrategyDirect
	StrategyPredictive = signalproto.StrategyPredictive
	StrategyBirthday   = signalproto.StrategyBirthday

	AddressFamilyIPv4 = "ipv4"
	AddressFamilyIPv6 = "ipv6"
)
View Source
const (
	CandidateSelectionACK    = signalproto.SelectionACK
	CandidateSelectionFanout = signalproto.SelectionFanout
)

Variables

View Source
var (
	// ErrPunchFailed means hole punching did not produce a usable
	// connection, usually because a NAT does not support TCP simultaneous
	// open or the peer did not punch at the same time.
	ErrPunchFailed = errors.New("burrow: hole punching failed")

	// ErrClosed means the Listener or Dialer has been closed.
	//
	// It wraps net.ErrClosed, so both errors.Is(err, ErrClosed) and
	// errors.Is(err, net.ErrClosed) hold. The latter is how standard library
	// consumers such as http.Serve recognize a normal listener shutdown.
	ErrClosed = fmt.Errorf("burrow: closed: %w", net.ErrClosed)

	// ErrNoListener means no Listener is currently registered in the room.
	//
	// It is distinct from "the peer is online but not ready yet": retrying
	// does not help here because the peer is not running at all, so callers
	// can choose to fail fast instead of backing off.
	ErrNoListener = errors.New("burrow: no listener in room")

	// ErrUnsupportedNATPair means the auto strategy could not pick a
	// strategy for this NAT combination.
	ErrUnsupportedNATPair = errors.New("burrow: NAT pair cannot be classified automatically")
	// ErrStrategyMismatch means the two sides disagree on the strategy or
	// its parameters.
	ErrStrategyMismatch = errors.New("burrow: strategy or parameters differ between peers")
	// ErrResourceLimit means the candidate socket budget is exhausted.
	ErrResourceLimit = errors.New("burrow: candidate resource budget exhausted")
	// ErrSelectionFailed means the candidate selection handshake failed.
	ErrSelectionFailed = errors.New("burrow: candidate selection failed")
	// ErrUnsupportedPlatform means the platform lacks the socket options TCP
	// hole punching needs. Burrow relies on SO_REUSEPORT to share one local
	// port between address reflection, listening and dialing. Platforms such
	// as Windows have no equivalent: the package compiles there, but fails
	// explicitly at run time instead of producing unusable connections.
	ErrUnsupportedPlatform = errors.New("burrow: TCP hole punching is not supported on this platform (requires SO_REUSEPORT)")
)

Errors returned by this package. Test for them with errors.Is.

View Source
var ErrProofMismatch = errors.New("burrow: signal proof verification failed")

ErrProofMismatch is the uniform authentication error NewProofVerifier returns when a proof is missing or wrong. Missing and wrong proofs are not distinguished, so an observer cannot tell them apart.

View Source
var ErrProofRejected = errors.New("burrow: session proof rejected")

ErrProofRejected reports a failed session proof check. It is a uniform authentication error, returned before any candidate socket is allocated.

Functions

func QueryUDPMappedAddr

func QueryUDPMappedAddr(conn net.PacketConn, server string, timeout time.Duration) (*net.UDPAddr, error)

QueryUDPMappedAddr sends one STUN Binding request to server over conn and returns the socket's public mapped address. server may be "host:port" or "stun://host:port". conn stays open and is only borrowed for the query, so the caller must not send other traffic on it meanwhile.

func SetDebug

func SetDebug(on bool)

SetDebug turns diagnostic logging on or off at run time. It only affects output when no Config.DebugLog is set.

Types

type BirthdayDialDiagnostics

type BirthdayDialDiagnostics struct {
	Requested  int
	Armed      int
	Connected  int
	DialErrors BirthdayDialErrorCounts
}

BirthdayDialDiagnostics is a point-in-time snapshot of a shared birthday dial set.

type BirthdayDialErrorCounts

type BirthdayDialErrorCounts struct {
	Timeout  int
	Canceled int
	Refused  int
	Resource int
	Other    int
}

BirthdayDialErrorCounts classifies candidate failures observed while the shared SDK dial set is running.

type BirthdayDialSet

type BirthdayDialSet struct {
	Connections <-chan net.Conn
	Armed       <-chan int
	Done        <-chan struct{}
	// contains filtered or unexported fields
}

BirthdayDialSet exposes the connection, arming and completion signals from the SDK birthday candidate launcher.

func LaunchBirthdayDialSet

func LaunchBirthdayDialSet(ctx context.Context, specs []BirthdayDialSpec, control func(network, address string, c syscall.RawConn) error) *BirthdayDialSet

LaunchBirthdayDialSet creates every TCP candidate through one socket arming barrier. The Control callback runs after each socket is created and before its connect attempt starts.

func (*BirthdayDialSet) Diagnostics

func (s *BirthdayDialSet) Diagnostics() BirthdayDialDiagnostics

Diagnostics returns a lock-free snapshot of the dial set counters.

type BirthdayDialSpec

type BirthdayDialSpec struct {
	LocalAddr string
	Target    string
}

BirthdayDialSpec describes one TCP candidate socket in a birthday dial set.

type BirthdayOptions

type BirthdayOptions struct {
	Selection            CandidateSelection
	Candidates           int
	MinPort              uint16
	MaxPort              uint16
	Warmup               time.Duration
	AttemptTimeout       time.Duration
	SuccessGrace         time.Duration
	MaxSuccessCandidates int
}

BirthdayOptions holds the birthday strategy parameters. All of them are sent by the Dialer to the Listener, so they only take effect on the Dialer; Listen rejects them if set on the Listener.

type CandidateSelection

type CandidateSelection = signalproto.Selection

CandidateSelection selects how the birthday strategy picks a connection when several candidates succeed: ack exchanges a selection handshake so both sides agree on one connection, fanout delivers every successful candidate.

type Config

type Config struct {
	// SignalAddr is the signal server address, such as
	// "signal.example.com:9960". The server provides WebSocket signaling and
	// TCP address reflection. Both sides must use the same server.
	SignalAddr string

	// Mode controls how signaling parameters are sent:
	//   ""       (default) in the URL query, e.g. ?command=nat&room=r&session=s.
	//   "header" base64-encoded in a Cookie header instead of the URL, so an
	//            on-path observer does not see command/room/session in clear.
	// The server always accepts both, so any server version works.
	Mode string

	// DebugLog optionally routes diagnostic logs to the caller's logger; the
	// caller handles level filtering. When nil, BURROW_DEBUG controls output
	// through the standard log package.
	DebugLog DebugLogFunc

	// InfoLog optionally receives info-level logs: pairing, successful
	// punches and listener reconnects. When nil, they are dropped.
	InfoLog LogFunc

	// StatsLog optionally receives structured TCP statistics for every
	// established connection once per second. The same numbers are also
	// written to DebugLog as tcp_stats lines; sampling runs only when
	// DebugLog or StatsLog is set.
	//
	// It lets a UI (such as the Android app) consume the numbers directly
	// instead of parsing log lines.
	StatsLog func(TCPStats)

	// ResolveIP optionally takes over resolution of the signal server host
	// name. The host name in the WebSocket URL is kept, so the HTTP Host and
	// TLS SNI still use the name from SignalAddr. Returned addresses matching
	// AddressFamily are tried in order. When nil, the system resolver is used.
	ResolveIP ResolveIPFunc

	// Room is the pairing room name. Both sides must use the same room.
	Room string

	// AddressFamily selects the address family for hole punching: "ipv4" or
	// "ipv6". Empty means ipv4. Address reflection, signaling, listening and
	// dialing all use this family, so one attempt reuses the same local IP and
	// port throughout.
	AddressFamily string

	// BindInterface names the physical interface that punching sockets bind
	// to, such as "en0" or "eth0". When empty the kernel picks the route, but
	// with virtual interfaces such as Docker bridges present it may pick an
	// unroutable source address and punching fails, so setting it is
	// recommended.
	BindInterface string

	// InterfaceName returns the current physical interface name at the start
	// of each attempt, for setups where the default interface changes with
	// the network. BindInterface takes precedence when set.
	InterfaceName func() string

	// InterfaceAddr optionally returns the address of the named interface in
	// the configured AddressFamily. An empty result means the caller cannot
	// provide it. In that case IPv4 tries internal/netiface.IPv4ByName (ioctl
	// on Linux and Android) and then net.InterfaceByName/Addrs; IPv6
	// enumerates global addresses through net.InterfaceByName/Addrs.
	//
	// It avoids the netlink calls behind net.InterfaceByName/Addrs: on
	// Android, SELinux denies route table reads to non-root processes
	// ("netlinkrib: permission denied"), while the caller often already has
	// the interface details from a platform API such as VpnService. The
	// netiface ioctl path solves the same problem independently; each serves
	// as a fallback for the other.
	InterfaceAddr func(name string) string

	// Control is an optional socket control callback, called for every
	// punching-related socket (address reflection, listening, dialing, port
	// allocation) after creation and before connect or bind.
	//
	// It runs after the internal SO_REUSEADDR/SO_REUSEPORT setup. The typical
	// use is binding to a physical interface (IP_BOUND_IF / SO_BINDTODEVICE):
	// when a TUN-based proxy has taken over the default route, binding the
	// source IP alone does not choose the egress interface and punching
	// traffic loops back into the TUN device. Binding to the device makes the
	// kernel bypass the routing table and avoids the loop.
	//
	// The signature matches net.Dialer.Control and net.ListenConfig.Control,
	// so existing interface-binding helpers can be passed in directly.
	Control func(network, address string, c syscall.RawConn) error

	// PairTimeout is how long to wait for the peer to appear in the room.
	// Default 60s.
	PairTimeout time.Duration

	// PunchTimeout bounds a single punching attempt. Default 45s.
	PunchTimeout time.Duration

	// AcceptQueue is the number of established connections buffered until
	// Accept takes them. Default 64.
	//
	// Concurrency is bounded by MaxConcurrentAttempts and the candidate
	// socket budget; when this queue is full, punching blocks, which
	// propagates back-pressure to the peer.
	AcceptQueue int

	// PortScanRange is the port prediction scan window. Default 0, which
	// dials only the single port the signal server reflected for the peer.
	//
	// A symmetric NAT allocates a new, usually increasing, public port for
	// every new destination, so the reflected port differs from the one the
	// peer actually punches from and single-port dialing misses. With N > 0
	// the scanning side dials a window of N ports centered on the peer's
	// reflected port; any hit succeeds. A typical value is 512. It is the
	// legacy way to request the predictive strategy (Predictive.PortScanRange
	// is the newer field) and is only accepted on the Dialer.
	//
	// No bytes are written on the connection: the first established TCP
	// connection is used, and the upper-layer protocol detects and retries
	// a connection that turns out to be unusable.
	PortScanRange int

	// Strategy selects direct, predictive, birthday or auto. Empty keeps the
	// legacy behavior: predictive when PortScanRange > 0, direct otherwise.
	Strategy Strategy

	// StableSide declares that the Listener is behind a stable-mapping NAT
	// (endpoint-independent mapping, port cone). The birthday and auto
	// strategies require it on the Listener, and predictive assumes the
	// Listener is the stable side.
	StableSide bool

	// Predictive, Birthday and NATProbe hold per-strategy parameters.
	Predictive PredictiveOptions
	Birthday   BirthdayOptions
	NATProbe   NATProbeOptions

	// MaxConcurrentAttempts limits in-flight punching attempts per Listener
	// or Dialer. Default 2, maximum 16.
	MaxConcurrentAttempts int
	// contains filtered or unexported fields
}

Config configures a Listener or Dialer. SignalAddr and Room are required; every other field has a default.

type DebugLogFunc

type DebugLogFunc = LogFunc

DebugLogFunc is an alias of LogFunc kept for existing callers.

type Dialer

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

Dialer opens connections to a Listener through TCP hole punching.

Every Dial runs a full round of signaling and punching and returns an independent net.Conn, so it can be called repeatedly to open several connections. A Dialer is safe for concurrent use.

func NewDialer

func NewDialer(cfg Config) (*Dialer, error)

NewDialer returns a Dialer for cfg. Call Close when done.

func (*Dialer) Close

func (d *Dialer) Close() error

Close closes the Dialer and aborts all in-flight Dials. Connections already returned are unaffected and must be closed by the caller. Close is idempotent.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context) (net.Conn, error)

Dial opens a connection to the peer listening in the same room.

Each call uses its own session ID and runs the full flow, so concurrent calls open independent connections with no shared state.

ctx bounds the whole round (pairing and punching); Dial returns as soon as ctx is canceled. Use errors.Is on the error: ErrNoListener means nobody is listening (retrying is pointless), ErrPunchFailed means punching failed (retrying may help).

func (*Dialer) ResetSignal

func (d *Dialer) ResetSignal()

ResetSignal drops the shared signaling connection and the cached NAT profile; the next operation reconnects on the current network.

type Listener

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

Listener accepts connections from peers through TCP hole punching. It implements net.Listener.

It is event driven: a long-running goroutine receives connection requests from the shared signaling channel, and each request runs a punching attempt bounded by the session limit and the candidate socket budget.

Each request carries its own session and shares no state with others, so pairing never races.

func Listen

func Listen(cfg Config) (*Listener, error)

Listen starts a Listener for cfg. It returns immediately and accepts peers in the background. Call Close when done.

func (*Listener) Accept

func (l *Listener) Accept() (net.Conn, error)

Accept returns the next punched connection. After Close it returns ErrClosed.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the signaling-level address of the Listener. Every punched connection uses a different local port, so this identifies the room rather than a socket.

func (*Listener) Close

func (l *Listener) Close() error

Close stops listening and releases resources. It is idempotent. Connections already returned by Accept are unaffected and must be closed by the caller.

func (*Listener) ResetSignal

func (l *Listener) ResetSignal()

ResetSignal drops the shared signaling connection; the background loop reconnects on the current network and registers again.

type LogFunc

type LogFunc func(format string, args ...any)

LogFunc receives log lines from burrow. Callers can route it into their own leveled logger.

type NATProbeOptions

type NATProbeOptions struct {
	Targets        []string
	InitialSamples int
	MaxSamples     int
	Timeout        time.Duration
	CacheTTL       time.Duration
}

NATProbeOptions controls how the Dialer probes its NAT for the auto strategy. Targets defaults to the signal server.

type PacketAttempt

type PacketAttempt struct {
	Session  string
	Strategy Strategy
	// User is reserved for multi-user listeners that need to locate a
	// per-user key. It is always 0 for now (single-user listener).
	User  int
	Paths []PacketPath
	// contains filtered or unexported fields
}

PacketAttempt is the set of candidate sockets produced by one hole punching attempt.

When DialPacket or AcceptPacket returns, every socket in Paths is bound, has a STUN mapping, and the signaling-level proof check has passed. The caller probes the candidates with its own protocol's packets, calls Commit to keep the winning path and close the rest, and must eventually call Close (safe even after Commit) so that no socket leaks.

func (*PacketAttempt) Close

func (a *PacketAttempt) Close() error

Close releases every socket held by the attempt. It is safe to call more than once and after Commit. After Commit only the winning socket is still open, and Close closes it too, so a caller that keeps using the PacketConn returned by Commit must not call Close until it is done with that connection.

func (*PacketAttempt) Commit

func (a *PacketAttempt) Commit(path int, peer netip.AddrPort) (net.PacketConn, error)

Commit keeps the socket of Paths[path], closes all other sockets and returns the winner for further use. peer records the chosen remote address for logging and diagnostics only; Commit does not validate it, because the correctness of candidate selection is the upper-layer protocol's job (for example its authenticated handshake).

The losing sockets must be released promptly (within one second). They are closed synchronously here: net.UDPConn.Close does not block, so no goroutine or timer is needed.

type PacketConfig

type PacketConfig struct {
	SignalAddr    string
	Mode          string
	Room          string
	ResolveIP     ResolveIPFunc
	BindInterface string
	InterfaceName func() string
	InterfaceAddr func(string) string
	Control       func(network, address string, c syscall.RawConn) error
	DebugLog      DebugLogFunc
	InfoLog       LogFunc

	STUN                  STUNOptions
	PairTimeout           time.Duration
	PunchTimeout          time.Duration
	Strategy              Strategy
	StableSide            bool
	Predictive            PredictiveOptions
	Birthday              BirthdayOptions
	MaxConcurrentAttempts int

	// SignProof and VerifyProof are the session proof hooks.
	//
	// The listener calls VerifyProof on the DIAL message before allocating
	// candidate sockets; the dialer calls it on the READY/PEER message
	// before sending candidate packets. Each side calls SignProof to sign
	// its own DIAL/READY message before sending it. Both hooks are
	// optional: when nil, no proof is signed or checked, which keeps hole
	// punching usable before the caller wires up its own key derivation.
	SignProof   ProofSigner
	VerifyProof ProofVerifier
}

PacketConfig configures UDP hole punching. Shared fields have the same meaning as in the TCP Config (see burrow.go); it is a separate type so it can carry the UDP-specific STUN, predictive and proof settings.

type PacketDialer

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

PacketDialer starts UDP hole punching attempts towards a peer.

Each DialPacket runs a full round of signaling, pairing, STUN mapping and candidate punching, and returns a *PacketAttempt: the set of prepared candidate sockets. Choosing which socket to keep is left to the caller.

func NewPacketDialer

func NewPacketDialer(cfg PacketConfig) (*PacketDialer, error)

NewPacketDialer creates a UDP hole punching dialer. Call Close when done.

func (*PacketDialer) Close

func (d *PacketDialer) Close() error

Close closes the PacketDialer and aborts all in-flight DialPacket calls. PacketAttempts already returned are not affected; the caller must close them. Close is safe to call more than once.

func (*PacketDialer) DialPacket

func (d *PacketDialer) DialPacket(ctx context.Context) (*PacketAttempt, error)

DialPacket runs one UDP hole punching attempt. ctx bounds the whole round (pairing and punching); DialPacket returns as soon as ctx is done or the PacketDialer is closed.

Errors can be tested with errors.Is: ErrNoListener means the peer is not listening, ErrProofRejected means the proof check failed (and no candidate socket was allocated), and ErrPunchFailed means punching did not succeed.

func (*PacketDialer) ResetSignal

func (d *PacketDialer) ResetSignal()

ResetSignal drops the reused signaling connection; the next operation reconnects on the current network.

type PacketListener

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

PacketListener accepts UDP hole punching attempts from peers.

Unlike the TCP Listener it has no net.Listener semantics (UDP has no connection setup). AcceptPacket returns a whole *PacketAttempt: the set of candidate sockets that finished STUN, pairing and punching. Choosing a candidate is left to the caller.

func ListenPacket

func ListenPacket(cfg PacketConfig) (*PacketListener, error)

ListenPacket starts a UDP hole punching listener. It returns immediately and accepts peer attempts in the background. The caller must call Close when done.

func (*PacketListener) AcceptPacket

func (l *PacketListener) AcceptPacket(ctx context.Context) (*PacketAttempt, error)

AcceptPacket returns the next successful UDP candidate set. It returns ErrClosed after the PacketListener is closed.

func (*PacketListener) Close

func (l *PacketListener) Close() error

Close stops listening and releases resources. It is safe to call more than once. PacketAttempts already returned by AcceptPacket are not affected; the caller must close them.

func (*PacketListener) ResetSignal

func (l *PacketListener) ResetSignal()

ResetSignal drops the reused signaling connection; the background loop reconnects and re-registers on the current network.

type PacketPath

type PacketPath struct {
	// Conn is the bound local UDP socket.
	Conn *net.UDPConn

	// PublicAddr is the public mapping of Conn as reported by STUN.
	PublicAddr netip.AddrPort

	// Remotes are the peer candidate addresses to try on this path:
	//   - direct: exactly one address (the peer's only STUN mapping).
	//   - predictive, scanning side: one exact address (the peer's stable
	//     mapped endpoint).
	//   - predictive, stable side: the whole port window produced by
	//     predictivePortSequence (expanding outward from the center, see
	//     packet_predictive.go).
	Remotes []netip.AddrPort
}

PacketPath is a candidate path: a bound local UDP socket whose public mapping is known from STUN.

type PredictiveOptions

type PredictiveOptions struct {
	PortScanRange  int
	Concurrency    int
	AttemptTimeout time.Duration
}

PredictiveOptions holds the predictive strategy parameters.

PortScanRange is sent by the Dialer to the Listener, so it only takes effect on the Dialer; Listen rejects it if set on the Listener.

Concurrency (the number of sockets this side dials in parallel) and AttemptTimeout are local settings that are not negotiated, so each side may set its own values.

type ProofContext

type ProofContext struct {
	Transport   string
	Room        string
	Session     string
	Endpoint    string
	Strategy    Strategy
	Fingerprint string
	// Profile is the serialized local UDP NAT profile for the auto strategy.
	// It is empty when no profile was collected or the strategy is not
	// auto. Its canonical encoding is up to the implementation.
	Profile string
}

ProofContext is the set of signaling fields a proof covers: transport, room, session, endpoint, profile, strategy and fingerprint. It is a plain value type so the hook signatures do not depend on internal/signalproto.Message.

type ProofSigner

type ProofSigner func(ctx ProofContext) (string, error)

ProofSigner produces the proof for a signaling message. Returning an empty string attaches no proof, as if the hook were not set.

func NewProofSigner

func NewProofSigner(password string) ProofSigner

NewProofSigner returns a ProofSigner that signs signaling messages with a key derived from password: proof = hex(HMAC-SHA256(signalKey, canonical(ctx))[:16]).

type ProofVerifier

type ProofVerifier func(ctx ProofContext, proof string) error

ProofVerifier checks the proof carried by a peer's signaling message. It is called even when the proof is empty, so an implementation can require one. A bad proof must produce a uniform authentication error and must not trigger port scanning or candidate socket allocation.

func NewProofVerifier

func NewProofVerifier(password string) ProofVerifier

NewProofVerifier returns a ProofVerifier that checks peer proofs with a key derived from password. A missing or wrong proof yields ErrProofMismatch. The comparison is constant time (hmac.Equal).

type ResolveIPFunc

type ResolveIPFunc func(ctx context.Context, host string) ([]netip.Addr, error)

ResolveIPFunc resolves the signal server host name to IP addresses. Burrow still creates and configures the sockets itself, so source port reuse, interface binding and hole punching behave the same.

type STUNOptions

type STUNOptions struct {
	// Servers lists STUN servers such as "stun.example.com:3478". The
	// explicit strategies (direct, predictive) need at least one. Auto will
	// need at least three covering two distinct public IPs once it is
	// supported by the packet API.
	Servers []string

	// InitialSamples and MaxSamples bound how many samples
	// collectUDPProfileSample takes while trying to converge on a definite
	// NAT class.
	InitialSamples int
	MaxSamples     int

	// Timeout bounds a single STUN Binding query.
	Timeout time.Duration

	// CacheTTL is how long a cached UDP NAT profile stays valid. The
	// default is 10 minutes.
	CacheTTL time.Duration
}

STUNOptions configures the STUN servers used to collect the UDP NAT profile and to query address mappings.

type Strategy

type Strategy = signalproto.Strategy

Strategy selects the hole punching strategy. See the package documentation for a description of each value.

type TCPStats

type TCPStats struct {
	Role       string // "dialer" or "listener"
	Session    string // burrow session ID (unrelated to any multiplexer session)
	LocalAddr  string
	RemoteAddr string
	Interval   time.Duration // length of this sampling interval

	// Deltas within the interval.
	TxBytes        uint64
	RetransBytes   uint64
	TxPackets      uint64
	RetransPackets uint64
	RxBytes        uint64
	RxPackets      uint64

	// Cumulative values.
	TotalTxBytes      uint64
	TotalRetransBytes uint64
	TotalRxBytes      uint64

	// Instantaneous values.
	RTT              time.Duration
	CongestionWindow uint64 // congestion window in bytes
	ReceiveWindow    uint64 // local receive window in bytes; 0 if the kernel does not report it (Linux < 6.2)
	ReceiveSpace     uint64 // receive buffer auto-tuning estimate in bytes (Linux only)
}

TCPStats is a snapshot of connection quality for one sampling interval.

Interval fields (TxBytes, RxBytes and so on) are deltas within the interval; Total* fields are cumulative since the connection was established; RTT, CongestionWindow and Receive* are instantaneous values at sampling time.

Derived metrics such as retransmission rate or Mbps are left to the consumer.

Directories

Path Synopsis
cmd
burrow command
burrow-signal command
Command burrow-signal is the signaling server used for hole punching.
Command burrow-signal is the signaling server used for hole punching.
Package diag provides NAT diagnostics: STUN NAT type detection and TCP NAT mapping behavior probing.
Package diag provides NAT diagnostics: STUN NAT type detection and TCP NAT mapping behavior probing.
examples
echo-client command
Command echo-client shows that a burrow.Dialer returns ordinary net.Conns by plugging it into the standard library's http.Transport.
Command echo-client shows that a burrow.Dialer returns ordinary net.Conns by plugging it into the standard library's http.Transport.
echo-server command
Command echo-server shows that a burrow.Listener is an ordinary net.Listener by serving HTTP on it with the standard library.
Command echo-server shows that a burrow.Listener is an ordinary net.Listener by serving HTTP on it with the standard library.
internal
birthdaylab
Package birthday contains the portable state and probability model for the birthday-collision TCP hole-punch prototype.
Package birthday contains the portable state and probability model for the birthday-collision TCP hole-punch prototype.
netiface
Package netiface provides cross-platform lookup of network interfaces by name.
Package netiface provides cross-platform lookup of network interfaces by name.
signalproto
Package signalproto defines the wire protocol spoken between burrow peers and the burrow-signal server.
Package signalproto defines the wire protocol spoken between burrow peers and the burrow-signal server.
Package mobile is the gomobile binding of the tunnel package for Android.
Package mobile is the gomobile binding of the tunnel package for Android.
Package tunnel is a standalone TCP port-forwarding tunnel built on burrow's hole punching.
Package tunnel is a standalone TCP port-forwarding tunnel built on burrow's hole punching.

Jump to

Keyboard shortcuts

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