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
- type BirthdayOptions
- type Client
- type ClientConfig
- type Duration
- type LogObserver
- type LogSink
- type Logger
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) SDKDebugFunc() func(string, ...any)
- func (l *Logger) SDKInfoFunc() func(string, ...any)
- func (l *Logger) Warnf(format string, args ...any)
- type Observer
- type PredictiveOptions
- type Server
- type ServerConfig
- type Status
Constants ¶
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.
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 ¶
Duration is a time.Duration that is written in JSON as a string such as "250ms" or "3s".
func (Duration) MarshalJSON ¶
func (*Duration) UnmarshalJSON ¶
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) SDKDebugFunc ¶
SDKDebugFunc returns a callback suitable for burrow.Config.DebugLog.
func (*Logger) SDKInfoFunc ¶
SDKInfoFunc returns a callback suitable for burrow.Config.InfoLog.
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.
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.