Documentation
¶
Overview ¶
Package tunnel implements a reverse proxy tunnel handler for NAT traversal.
Architecture overview ¶
The tunnel handler is deployed on the public-facing (server) side. It acts as a bridge between external clients and internal services behind NAT/firewall.
There are two main roles:
Internal client (CmdBind) — connects to the tunnel handler and registers a multiplexed session (mux.Session via smux) as a Connector. Once bound, this client passively waits to receive streams from the public side.
Public entrypoints (CmdConnect + entrypoint) — accept incoming requests from the Internet and forward them through the tunnel to the internal client via mux streams (OpenStream).
Data flow (normal direction: public → internal):
Public request → tunnelHandler.Handle() / entrypoint.Handle()
→ Dialer.Dial()
→ ConnectorPool.Get() → Tunnel.GetConnector() → Connector.GetConn()
→ mux.Session.OpenStream() ← creates stream to internal side
→ Pipe(publicConn, muxStream)
Internal client side:
mux.Session.AcceptStream() ← receives the stream → processes request, sends response back through the same stream
Connector lifecycle (CmdBind):
Internal client sends CmdBind → handleBind() creates mux.ClientSession → NewConnector (stores session, starts waitClose goroutine) → ConnectorPool.Add() → Tunnel.AddConnector() → ingress rules + SD service registered
The waitClose goroutine (Connector.waitClose) discards unexpected inbound streams on the Connector's mux session. This is a safety guard — normal request streams arrive via OpenStream from the public side and are handled by the internal client's Accept loop, NOT by waitClose.
Entrypoint protocol dispatch (first-byte sniffing):
relay.Version1 (0x52 'R') → handleConnect (relay protocol) dissector.Handshake (0x16) → handleTLS (TLS passthrough) otherwise → handleHTTP (HTTP forward proxy)
SD fallback: when ConnectorPool.Get() returns nil (no local tunnel registered), Dialer queries service discovery for a remote node address and establishes a direct TCP connection, bypassing the mux session entirely.
Package tunnel implements the TNET relay tunnel handler for NAT traversal, connecting public entrypoints to internal services behind NAT/firewall.
See handler.go for a full architecture overview.
Index ¶
- Constants
- Variables
- func NewHandler(opts ...handler.Option) handler.Handler
- func ParseTunnelID(s string) (tid relay.TunnelID)
- type Connector
- type ConnectorOptions
- type ConnectorPool
- func (p *ConnectorPool) Add(tid relay.TunnelID, c *Connector, ttl time.Duration)
- func (p *ConnectorPool) Close() error
- func (p *ConnectorPool) Get(network string, tid string) *Connector
- func (p *ConnectorPool) GetMetadata(tid string) map[string]string
- func (p *ConnectorPool) SetMetadata(tid relay.TunnelID, md map[string]string)
- type Dialer
- type Tunnel
- func (t *Tunnel) AddConnector(c *Connector)
- func (t *Tunnel) Close() error
- func (t *Tunnel) CloseOnIdle() bool
- func (t *Tunnel) GetConnector(network string) *Connector
- func (t *Tunnel) ID() relay.TunnelID
- func (t *Tunnel) Metadata() map[string]string
- func (t *Tunnel) SetMetadata(md map[string]string)
Constants ¶
const (
MaxWeight uint8 = 0xff
)
MaxWeight is the exclusive takeover weight (255). A connector at MaxWeight triggers rw.Reset() in GetConnector, clearing all previously added connectors so that only this one is selected. If that MaxWeight connector later dies (IsClosed), GetConnector returns nil until Tunnel.clean() removes it.
Variables ¶
var ( // ErrBadVersion is returned when the relay request has an unsupported // protocol version. ErrBadVersion = errors.New("bad version") // ErrUnknownCmd is returned when the relay request command is not // CmdConnect or CmdBind. ErrUnknownCmd = errors.New("unknown command") // ErrTunnelID is returned when the relay request has a zero/invalid // tunnel ID feature. ErrTunnelID = errors.New("invalid tunnel ID") // ErrTunnelNotAvailable is returned when no local connector or SD // service is available for the requested tunnel. ErrTunnelNotAvailable = errors.New("tunnel not available") // authentication fails against the configured Auther. ErrUnauthorized = errors.New("unauthorized") // ErrTunnelRoute is returned when the tunnel route cannot be // resolved (no ingress rule matches the host). ErrTunnelRoute = errors.New("no route to host") // ErrPrivateTunnel is returned when the resolved tunnel is private // ($-prefixed) and the connection is from a public entrypoint. ErrPrivateTunnel = errors.New("private tunnel") )
Functions ¶
func NewHandler ¶
NewHandler creates a new tunnel handler.
Registered as "tunnel" in the handler registry (init()). The handler processes relay-protocol requests and supports two commands: CmdConnect (forward a public connection through a tunnel stream) and CmdBind (register an internal client as a tunnel connector).
func ParseTunnelID ¶ added in v0.28.1
ParseTunnelID parses a tunnel ID from a string. If s is empty or contains an invalid UUID, the returned tunnel ID is zero (callers must check IsZero). A leading '$' prefix marks the tunnel as private.
Types ¶
type Connector ¶
type Connector struct {
// contains filtered or unexported fields
}
Connector represents one mux-session tunnel endpoint registered by an internal client via CmdBind.
Each Connector wraps a smux.Session created by mux.ClientSession. From the server side, Connector.GetConn() calls OpenStream() to create a stream to the internal client.
Connector.waitClose is a background goroutine that accepts and discards unexpected inbound streams. This is a safety guard: the Connector's mux session is supposed to be used unidirectionally (server→client), and any stream arriving from the client side is anomalous and is safely discarded. Normal request streams are created by the server side via OpenStream and consumed by the internal client's Accept loop — they never pass through waitClose.
When the mux session is closed (client disconnect or network error), waitClose detects the Accept error, closes the Connector, and deregisters from SD if configured.
func NewConnector ¶
func NewConnector(id relay.ConnectorID, tid relay.TunnelID, node string, s mux.Session, opts *ConnectorOptions) *Connector
func (*Connector) ID ¶
func (c *Connector) ID() relay.ConnectorID
type ConnectorOptions ¶ added in v0.0.3
type ConnectorOptions struct {
// contains filtered or unexported fields
}
type ConnectorPool ¶
type ConnectorPool struct {
// contains filtered or unexported fields
}
ConnectorPool manages all Tunnel objects for this tunnel handler node.
Hierarchy:
ConnectorPool (per node) → map[tunnelID]*Tunnel → []*Connector
└── mux.Session
Each Tunnel holds Connectors sharing the same tunnel ID. Tunnels that have no active connectors for 15 minutes are removed by closeIdles.
Methods: Add (insert connector, creating Tunnel on demand), Get (select best connector by network type), Close (stop idle ticker, remove all tunnels).
func NewConnectorPool ¶
func NewConnectorPool(node string) *ConnectorPool
func (*ConnectorPool) Close ¶ added in v0.0.3
func (p *ConnectorPool) Close() error
func (*ConnectorPool) GetMetadata ¶ added in v0.28.1
func (p *ConnectorPool) GetMetadata(tid string) map[string]string
func (*ConnectorPool) SetMetadata ¶ added in v0.28.1
func (p *ConnectorPool) SetMetadata(tid relay.TunnelID, md map[string]string)
type Dialer ¶
type Dialer struct {
Node string
Pool *ConnectorPool
SD sd.SD
Retry int
Timeout time.Duration
Log logger.Logger
}
Dialer resolves a tunnel connector and returns a stream to it.
Dial strategy (two-phase):
- Local pool: try ConnectorPool.Get() up to retry times. Each attempt calls GetConn() (= mux.OpenStream) on the same connector — if the connector is dead, all retries fail until Tunnel.clean() removes it (up to TTL, default 15s).
- SD fallback: if pool returns nil AND sd is configured, query service discovery for remote nodes. Filter out self (d.Node) and mismatched networks. Establish a raw TCP connection to the remote address, bypassing the mux layer entirely.
The returned node and connector ID identify which node/hop the stream is connected to — used by callers to decide the relay protocol framing.
type Tunnel ¶
type Tunnel struct {
// contains filtered or unexported fields
}
Tunnel groups Connectors that share the same tunnel ID.
Connector selection (GetConnector):
- Single connector: fast path, no weighted random.
- Multiple connectors: weighted random selection by network type (tcp/udp).
- MaxWeight (255): exclusive — triggers Reset() and only the MaxWeight connector is added. If the MaxWeight connector closes, selection returns nil until clean() removes it.
Tunnel lifecycle:
- NewTunnel starts a clean() goroutine that runs every TTL (default 15s). Each tick removes closed connectors and renews SD registrations. A tunnel with 0 connectors gets cleaned up.
- CloseOnIdle closes the tunnel if it has 0 connectors (called by ConnectorPool.closeIdles on a 15-minute ticker).
- Close() closes all connectors and signals shutdown.
func (*Tunnel) AddConnector ¶
func (*Tunnel) CloseOnIdle ¶
func (*Tunnel) GetConnector ¶
func (*Tunnel) SetMetadata ¶ added in v0.28.1
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package entrypoint implements a public tunnel entry point that accepts external connections and routes them through the tunnel network to internal services behind NAT/firewall.
|
Package entrypoint implements a public tunnel entry point that accepts external connections and routes them through the tunnel network to internal services behind NAT/firewall. |