tunnel

package
v0.28.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 43 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.

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:

  1. 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.

  2. 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

View Source
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

View Source
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")
	// ErrUnauthorized is returned when the relay request's user/pass
	// 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

func NewHandler(opts ...handler.Option) handler.Handler

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

func ParseTunnelID(s string) (tid relay.TunnelID)

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) Close added in v0.0.3

func (c *Connector) Close() error

func (*Connector) GetConn added in v0.0.3

func (c *Connector) GetConn() (net.Conn, error)

func (*Connector) ID

func (c *Connector) ID() relay.ConnectorID

func (*Connector) IsClosed added in v0.0.3

func (c *Connector) IsClosed() bool

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) Add

func (p *ConnectorPool) Add(tid relay.TunnelID, c *Connector, ttl time.Duration)

func (*ConnectorPool) Close added in v0.0.3

func (p *ConnectorPool) Close() error

func (*ConnectorPool) Get

func (p *ConnectorPool) Get(network string, tid string) *Connector

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):

  1. 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).
  2. 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.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, network string, tid string) (conn net.Conn, node string, cid string, err error)

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 NewTunnel

func NewTunnel(node string, tid relay.TunnelID, ttl time.Duration) *Tunnel

func (*Tunnel) AddConnector

func (t *Tunnel) AddConnector(c *Connector)

func (*Tunnel) Close added in v0.0.3

func (t *Tunnel) Close() error

func (*Tunnel) CloseOnIdle

func (t *Tunnel) CloseOnIdle() bool

func (*Tunnel) GetConnector

func (t *Tunnel) GetConnector(network string) *Connector

func (*Tunnel) ID

func (t *Tunnel) ID() relay.TunnelID

func (*Tunnel) Metadata added in v0.28.1

func (t *Tunnel) Metadata() map[string]string

func (*Tunnel) SetMetadata added in v0.28.1

func (t *Tunnel) SetMetadata(md map[string]string)

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.

Jump to

Keyboard shortcuts

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