tunnel

package
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: 18 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

tunnel: TCP port forwarding over punched connections

Package tunnel forwards TCP connections between two hosts behind NAT using Burrow's TCP hole punching. The client listens on a local TCP address and punches one dedicated hole per accepted connection; the server accepts punched holes and forwards each one to a fixed TCP address.

Both ends are plain pipes. A hole carries the upstream connection's raw bytes: no custom header, handshake, keepalive or multiplexing, so the traffic on the wire is exactly the upper-layer protocol's own. The tunnel never parses what it carries; addressing, encryption and everything else are up to whatever protocol you run through it.

application ──TCP──> 127.0.0.1:1080
                      tunnel client      one punched TCP connection per upstream connection
                ═══════════ hole ═══════════
                      tunnel server      net.Dial("127.0.0.1:29999")
                          │
                          v
                     forward target

Both ends meet through a burrow-signal server, using the same room.

Running

The tunnel is part of the burrow CLI (make cli builds build/burrow):

burrow tunnel server -c server.json    # start the server first
burrow tunnel client -c client.json

Start the server first. Until a listener is present in the room, the client's punches fail with "no listener in the target room" and are retried every second.

Sample configurations are in example/.

Configuration

Both files are JSON. Durations are strings such as "250ms" or "3s".

Shared fields
Field Required Description
signal yes Full signal server URL, e.g. ws://signal.example.com:9960/signal
room yes Room name; must match on both ends
bind_interface yes Network interface to punch from, e.g. en0, eth0, wlan0
strategy yes direct, predictive or birthday (auto is rejected)
mode no Where signaling parameters go: empty = URL query string, header = base64 in a Cookie header
hosts no Static host-to-IPv4/IPv6 map that bypasses DNS; unmapped names still use DNS
log_level no debug, info, warn or error; default info
max_concurrent_attempts no Maximum in-flight punching attempts (SDK default 2, maximum 16)
predictive.concurrency no Parallel dial sockets for predictive; local, may differ per side
predictive.attempt_timeout no Per-attempt timeout for predictive; local, may differ per side
Client-only fields
Field Required Description
listen yes Local TCP listen address, e.g. 127.0.0.1:1080
trials no Maximum consecutive punch rounds per hole; 0 or unset = 100; negative is rejected
predictive.port_scan_range no Port prediction scan window (negotiated)
birthday.selection with birthday ack or fanout; required when strategy is birthday
birthday.candidates no Number of candidate ports per round
birthday.min_port, birthday.max_port no Candidate port range
birthday.warmup no Warm-up delay before dialing candidates
birthday.attempt_timeout no Timeout of one birthday round
birthday.success_grace no Grace period to collect more successful candidates after the first
birthday.max_success_candidates no Maximum successful candidates kept per round

Unset birthday.* and predictive.* values fall back to the SDK defaults.

Server-only fields
Field Required Description
forward yes TCP address every hole is forwarded to, e.g. 127.0.0.1:29999
stable_side with birthday Must be true when strategy is birthday
skip_nat_check no Skip the NAT self-check at startup (see below); default false
Common mistakes

Negotiated parameters belong in the client config. birthday.* and predictive.port_scan_range are sent by the client to the server during signaling. A server config that contains them is rejected at load time rather than silently ignored, so you never believe a setting took effect when it did not. predictive.concurrency and predictive.attempt_timeout are local and may be set on either side.

bind_interface is required. When bound to 0.0.0.0, the kernel may pick an unroutable source address (for example from a Docker bridge) and send SYNs out the wrong interface, so punching always fails. The interface is checked at startup; if it does not exist, the error lists the available interfaces when they can be enumerated. Sockets are also bound to the device itself (SO_BINDTOIFINDEX on Linux/Android), so a VPN or TUN proxy that owns the default route cannot capture the signaling connection.

Server NAT self-check

With strategy: "birthday" only, the server detects its NAT type over STUN before starting (timeout 30s) and refuses to start behind a symmetric NAT (NAT4). The birthday strategy needs a stable port mapping on the server; a symmetric NAT allocates a new port for every destination, and with both sides unstable the per-round hit rate is far too low to connect.

If the detection itself fails (network error, STUN server unreachable, timeout), the server also refuses to start, because starting without a result would make the check meaningless. direct and predictive do not need a stable listener-side mapping and skip the check.

The probe uses UDP STUN while the tunnel punches TCP, and a NAT may map the two differently, so the result is an approximation. If you know the detection is wrong, set skip_nat_check: true.

Behavior

One hole per connection. Each accepted client connection is forwarded over its own punched TCP connection. A hole is never shared between connections and never returned to the pool once used: the server dials the forward target as soon as it reads the first byte, so a reused hole would mix a new request into an old forwarding context.

Pre-punched pool (client). On start the client punches holes in the background and keeps up to 8 idle holes ready. An incoming connection takes an idle hole immediately. If the pool is empty, the connection is closed right away instead of waiting for a punch (which can take seconds to tens of seconds); the upstream application sees a reset and reconnects while the pool refills. Idle holes are retired after about 60 seconds, well below typical NAT idle timeouts, and replaced.

Retries (client). Punching is serialized: one punch runs at a time. A punch retries up to trials rounds back to back with no backoff, because the birthday strategy depends on many consecutive rounds. When the peer is not in the room or the signal server rate-limits the client, it waits a fixed 1 second before retrying.

Candidates and zombies (server). With birthday fanout, the server may accept up to max_success_candidates connections in a round while the client uses only one and closes the rest. A candidate counts as live once its first byte arrives; a candidate closed by the client is detected by EOF or RST and dropped. A 10-minute timeout reclaims candidates whose peer vanished without sending FIN or RST. The timeout is long on purpose: pooled holes legitimately stay idle until the user opens a connection. SessionCount counts only live holes.

Unreachable forward target (server). If the server cannot connect to forward, it closes that hole and does not retry; the client's upstream connection fails and the application retries.

No half-close. When one direction of a connection ends (EOF or error), both sides are closed immediately; CloseWrite semantics are not preserved. A protocol that half-closes after sending a request and then waits for the response will see the response truncated. Make sure the protocol you carry does not rely on half-close.

Status

Client.Snapshot() and Server.Snapshot() return a Status with the current state, punched addresses, hole and connection counts, traffic counters and the latest TCP quality sample. An Observer receives a full snapshot on every state transition. Fast-changing counters such as ActiveStreams are not pushed; poll Snapshot() for them.

Documentation

Overview

Package tunnel is a standalone TCP port-forwarding tunnel built on burrow's hole punching.

The client listens on a local TCP address and punches one hole per accepted connection (one-to-one); the server forwards every punched hole to a fixed local TCP address.

Both ends are plain pipes: a hole carries raw bytes with no custom header, handshake or keepalive. There is deliberately no multiplexing, because a multiplexing handshake would change the traffic pattern. The client splices each accepted TCP connection onto its hole without parsing anything. Target addressing is entirely up to the upper-layer protocol; this package knows nothing about the bytes it carries.

Index

Constants

View Source
const (
	StateIdle      = "idle"      // no hole yet (waiting for a connection to trigger punching)
	StatePunching  = "punching"  // punching in progress (birthday runs several rounds)
	StateConnected = "connected" // at least one hole is up and can carry data
	// StatePunchFailed means punchRetries consecutive rounds all failed. It is
	// not a backoff state: a failed punch is retried immediately, and only an
	// exhausted run of rounds ends up here.
	StatePunchFailed = "punch_failed"
)

Tunnel states.

Variables

This section is empty.

Functions

This section is empty.

Types

type BirthdayOptions

type BirthdayOptions struct {
	Selection            string   `json:"selection"`
	Candidates           int      `json:"candidates"`
	MinPort              uint16   `json:"min_port"`
	MaxPort              uint16   `json:"max_port"`
	Warmup               Duration `json:"warmup"`
	AttemptTimeout       Duration `json:"attempt_timeout"`
	SuccessGrace         Duration `json:"success_grace"`
	MaxSuccessCandidates int      `json:"max_success_candidates"`
}

BirthdayOptions holds the birthday strategy parameters. They may only be set on the client: the Dialer sends them to the Listener with DIAL.

type Client

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

Client listens on a local TCP address and forwards each accepted connection over its own hole (one-to-one).

func NewClient

func NewClient(cfg ClientConfig, observer Observer) (*Client, error)

NewClient builds a Client from cfg. observer may be nil.

All fallible setup (interface check, Dialer creation, listening) happens here, so configuration errors surface at startup instead of as unexplained connection failures later.

func (*Client) Close

func (c *Client) Close() error

Close shuts the Client down. It is safe to call more than once.

func (*Client) Snapshot

func (c *Client) Snapshot() Status

Snapshot returns a snapshot of the current status.

func (*Client) Start

func (c *Client) Start() error

Start begins accepting TCP connections. It does not block.

It also starts background pre-punching: a few holes are punched as soon as the tunnel is up, and incoming connections take one from the pool, saving the whole punching delay (seconds to tens of seconds with birthday).

type ClientConfig

type ClientConfig struct {

	// Listen is the local TCP listen address. Each accepted connection gets
	// its own hole and is forwarded as-is without any protocol parsing; what
	// runs on top (SOCKS5 or anything else) is up to the user.
	Listen string `json:"listen"`

	// Trials is the maximum number of consecutive punch rounds per
	// connection. Zero or unset means the default of 100.
	//
	// The birthday strategy relies on a birthday collision: a single round
	// succeeds far less than 100% of the time, and the overall success rate
	// comes from many rounds (compare -trials of `burrow birthday`, which
	// also defaults to 100). Raise it for difficult NAT combinations, such as
	// one side behind a strict cone NAT.
	//
	// Client only: the server accepts passively and never retries.
	Trials int `json:"trials"`

	Birthday BirthdayOptions `json:"birthday"`
	// contains filtered or unexported fields
}

ClientConfig is the client-side configuration.

func LoadClientConfig

func LoadClientConfig(path string) (ClientConfig, error)

LoadClientConfig reads and validates a client configuration file.

func (ClientConfig) ToBurrowConfig

func (c ClientConfig) ToBurrowConfig() burrow.Config

ToBurrowConfig converts the client configuration into an SDK config, including all negotiated parameters.

func (*ClientConfig) Validate

func (c *ClientConfig) Validate() error

Validate validates the configuration and fills in defaults.

It is exported so callers (such as the mobile bindings) can validate a configuration without reading a file or starting anything, using the same rules as startup, so a config never passes validation and then fails to start.

type Duration

type Duration time.Duration

Duration is a time.Duration that is written in JSON as a string such as "250ms" or "3s".

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

type LogObserver

type LogObserver struct{}

LogObserver writes state changes to the standard logger; the CLI uses it.

TCP statistics are not printed here: the SDK's InfoLog already prints the same samples, and repeating them would only flood the log.

func (LogObserver) OnStateChange

func (LogObserver) OnStateChange(status Status)

func (LogObserver) OnStats

func (LogObserver) OnStats(burrow.TCPStats)

type LogSink

type LogSink func(level, line string)

LogSink receives one log line. level is "debug", "info", "warn" or "error".

It lets a host (such as the Android bindings) feed logs into its own UI: by default Logger writes only to stderr, which is invisible on mobile.

Implementations must be safe for concurrent use; logs may come from many goroutines.

type Logger

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

Logger is a simple level-filtered logger that writes to stderr.

When a LogSink is set, every line is also passed to the sink.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...any)

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...any)

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...any)

func (*Logger) SDKDebugFunc

func (l *Logger) SDKDebugFunc() func(string, ...any)

SDKDebugFunc returns a callback suitable for burrow.Config.DebugLog.

func (*Logger) SDKInfoFunc

func (l *Logger) SDKInfoFunc() func(string, ...any)

SDKInfoFunc returns a callback suitable for burrow.Config.InfoLog.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...any)

type Observer

type Observer interface {
	// OnStateChange delivers a full snapshot on every state transition. A
	// full Status rather than just the state string lets the UI show the
	// addresses the moment a hole is punched, without another poll.
	OnStateChange(status Status)

	// OnStats delivers a TCP quality sample every 5 seconds.
	OnStats(stats burrow.TCPStats)
}

Observer receives tunnel state changes. The CLI uses it for logging and the Android app uses it to drive the UI.

ActiveStreams changes frequently and is not pushed through callbacks; consumers poll Snapshot() instead, which avoids high-frequency callbacks across the gomobile JNI boundary.

type PredictiveOptions

type PredictiveOptions struct {
	PortScanRange  int      `json:"port_scan_range"`
	Concurrency    int      `json:"concurrency"`
	AttemptTimeout Duration `json:"attempt_timeout"`
}

PredictiveOptions holds the predictive strategy parameters.

PortScanRange is negotiated and may only be set on the client. Concurrency and AttemptTimeout are purely local resource limits; each side may set its own values.

type Server

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

Server forwards every punched hole, unchanged, to a fixed local TCP address.

It does not parse what flows through the hole: the forward target is fixed by configuration and the payload is handled by the upper-layer protocol at the target. Each hole carries exactly one upstream connection (the client punches one hole per connection) as a raw byte stream.

func NewServer

func NewServer(cfg ServerConfig, observer Observer) (*Server, error)

NewServer builds a Server from cfg. observer may be nil.

func (*Server) Close

func (s *Server) Close() error

Close shuts down the Server. It is safe to call more than once.

func (*Server) Snapshot

func (s *Server) Snapshot() Status

Snapshot returns a snapshot of the current status.

func (*Server) Start

func (s *Server) Start() error

Start begins accepting punched connections. It does not block.

type ServerConfig

type ServerConfig struct {
	Forward    string `json:"forward"`
	StableSide bool   `json:"stable_side"`

	// SkipNATCheck skips the NAT self-check performed before startup.
	//
	// The self-check refuses to run a server behind a symmetric NAT, where
	// hole punching almost never succeeds. Set it to true only if you know
	// the detection is wrong or want to try anyway.
	SkipNATCheck bool `json:"skip_nat_check"`
	// contains filtered or unexported fields
}

ServerConfig is the server-side configuration.

It has no Birthday field: negotiated parameters come from the client, and burrow.Listen rejects them on the listener side. LoadServerConfig first parses the file into a map to catch such misconfiguration with a clear error.

func LoadServerConfig

func LoadServerConfig(path string) (ServerConfig, error)

LoadServerConfig reads and validates a server configuration file.

func (ServerConfig) ToBurrowConfig

func (c ServerConfig) ToBurrowConfig() burrow.Config

ToBurrowConfig converts the server configuration into an SDK config.

It deliberately sets no negotiated fields (Birthday, Predictive.PortScanRange): burrow.Listen rejects configs that carry them.

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

Validate validates the configuration and fills in defaults.

It is exported so callers (such as the mobile bindings) can validate a configuration without reading a file or starting anything, using the same rules as startup, so a config never passes validation and then fails to start.

type Status

type Status struct {
	State string
	Room  string

	// The next four fields are only meaningful when State == StateConnected.
	LocalAddr  string        // local ip:port of the punched socket
	RemoteAddr string        // peer ip:port of the punched hole
	PunchedAt  time.Time     // when the hole was established
	Uptime     time.Duration // computed by Snapshot() at call time, not stored

	// SessionCount is the number of holes currently up.
	//
	// Each upstream connection has its own hole (one-to-one, no
	// multiplexing), so this is the number of connections currently running
	// through the tunnel. On the client it equals the number of local
	// connections being forwarded. On the server, birthday fanout may accept
	// several candidates, but only those that have received bytes are counted
	// here; zombie candidates are reaped and never show up.
	//
	// The name stays SessionCount rather than HoleCount because the Android
	// app parses this JSON field by name (TunnelState.kt); renaming it would
	// require a coordinated release on both sides.
	SessionCount int

	// ActiveStreams/TotalStreams largely overlap with the hole count now that
	// multiplexing is gone, but they must not be merged with SessionCount
	// because they count different things:
	//   - SessionCount only counts connections whose hole is up, and on the
	//     server only after the first byte arrives;
	//   - ActiveStreams counts every connection being forwarded, including
	//     client connections still waiting for a hole and server connections
	//     whose forward target is unreachable.
	// A mismatch is itself a useful signal (for example, ActiveStreams staying
	// above SessionCount means upstreams connect but holes do not come up).
	//
	// TotalStreams is cumulative and only increases; it shows how many
	// connections the tunnel has carried in total.
	ActiveStreams int    // connections currently being forwarded
	TotalStreams  uint64 // connections forwarded so far

	Stats *burrow.TCPStats // latest 5-second sample; nil if none yet

	// Peers lists the currently active peer addresses (ip:port).
	//
	// A server can serve several clients, each over its own punched
	// connection. A bare count is not enough: users need to know who is
	// connected (for troubleshooting and to confirm the peer's identity).
	Peers []string

	// Cumulative application-level traffic: bytes actually forwarded through
	// the tunnel.
	//
	// Unlike Stats (kernel TCP_INFO samples), which is tied to a single
	// punched socket and gets mixed up when the server holds several fanout
	// candidates, these counters count the bytes relay actually moved,
	// independent of the number of candidates. They replace Stats for traffic
	// and speed figures on the server.
	//
	// Directions are relative to this end: Rx is received from the tunnel
	// (download), Tx is sent into the tunnel (upload).
	AppRxBytes uint64
	AppTxBytes uint64

	// Punch retry progress: round PunchTrial of PunchTrials. PunchReason is
	// why the current round failed (for example "no listener in the target
	// room"); empty means an ordinary miss.
	//
	// Punching can take a long time (birthday defaults to 100 rounds).
	// Without progress the user only sees "punching" with no idea how long it
	// will take, or whether the peer is offline versus collisions simply
	// missing so far. The two call for completely different actions.
	PunchTrial  int
	PunchTrials int
	PunchReason string

	// Queued is the number of upstream connections waiting for a hole,
	// including the one currently being punched.
	//
	// Punching is serialized (see punchMu in session.go), so concurrent
	// connections take turns. Queued connections have not entered punch() and
	// do not move PunchTrial; without this number the user would see several
	// connections stuck with no indication, indistinguishable from a fault.
	Queued int

	LastError string
}

Status is a snapshot of the tunnel state.

Jump to

Keyboard shortcuts

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