router

package
v0.28.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 41 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 router implements the "router" handler for the TNET framework.

Overview

The router handler acts as the ingress point of a VPN-like tunnel mesh. It receives relay protocol connections (over TCP) from client-side TNET instances, authenticates them, and routes IP packets through the mesh of tunnel connectors.

Data flow

Client TCP ──► Handle() ──► [auth + relay handshake]
                    │
                    └──► handleAssociate() ──► packetConn.Read() loop
                                  │
                                  └──► handlePacket()
                                         │
                                         ├── 1. Parse IP header (v4/v6)
                                         ├── 2. getRoute() to find gateway
                                         ├── 3. pool.Get() — forward via connector
                                         └── 4. getAddrforRoute() — fallback to
                                             epConn.WriteTo() to another node

External UDP ──► handleEntrypoint() ──► pool.Get() ──► connector.Write()

Component hierarchy

ConnectorPool (node-level)
  └── Router (per tunnel ID)
        └── Connector (per host:port)
              └── lockWriter → packetConn → net.Conn (back to client)

Thread safety

Router and ConnectorPool use sync.RWMutex for all map operations. lockWriter serializes writes to the underlying connection, since handlePacket and handleEntrypoint may call Write concurrently.

Connector weighting

Each connector carries a weight embedded in its ConnectorID. When multiple connectors exist for the same host, GetConnector uses weighted random selection. A weight of MaxWeight (0xff) has special meaning: only MaxWeight connectors are selected, providing a priority mechanism.

Index

Constants

View Source
const (
	// MaxWeight is the maximum connector weight. A connector with this
	// weight takes priority over all other connectors for the same host.
	MaxWeight uint8 = 0xff
)

Variables

View Source
var (
	ErrBadVersion   = errors.New("bad version")
	ErrUnknownCmd   = errors.New("unknown command")
	ErrRouterID     = errors.New("invalid router ID")
	ErrUnauthorized = errors.New("unauthorized")
)

Error sentinel values returned by the router handler.

Functions

func LockWriter

func LockWriter(w io.Writer) io.Writer

LockWriter creates a mutex-guarded wrapper around w.

func NewHandler

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

NewHandler creates a new router handler.

Caches are initialized with a 1-minute default TTL; individual entries may override this via metadata configuration.

Types

type Connector

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

Connector represents a single tunnel endpoint bound to a remote client.

A connector is identified by its ConnectorID and associated with a TunnelID (router). It pairs a host address with an io.Writer — the framed TCP connection back to the client. When the router receives an IP packet destined for this connector's host, it writes the raw packet to the Writer, and the client-side packetConn decapsulates it.

Lifecycle:

  1. Created by NewConnector in handleAssociate after the relay handshake.
  2. Added to the ConnectorPool (and underlying Router) for routing.
  3. Removed by ConnectorPool.Del when handleAssociate exits (deferred).
  4. Closed by Router.Close when the router shuts down.

func NewConnector

func NewConnector(rid relay.TunnelID, cid relay.ConnectorID, host string, w io.Writer, opts *ConnectorOptions) *Connector

NewConnector creates a new Connector.

Parameters:

  • rid: tunnel/route identifier this connector belongs to
  • cid: unique connector identifier (embedding weight)
  • host: the destination host:port this connector forwards to
  • w: the writer for sending IP packets back to the client
  • opts: optional configuration (nil is replaced with zero value)

func (*Connector) Close

func (c *Connector) Close() error

Close closes the underlying writer if it implements io.Closer. Safe to call on nil receiver or nil writer.

func (*Connector) ID

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

ID returns the connector's unique identifier.

func (*Connector) Writer

func (c *Connector) Writer() io.Writer

Writer returns the io.Writer for sending data to the remote client. Returns nil if the receiver is nil or the writer was not set.

The returned writer is typically a lockWriter wrapping a packetConn wrapping the underlying TCP connection — so Write calls are automatically framed with a 2-byte length prefix and are mutex-protected against concurrent access.

type ConnectorOptions

type ConnectorOptions struct{}

ConnectorOptions holds optional configuration for a Connector. Currently empty but reserved for future use.

type ConnectorPool

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

ConnectorPool manages routers keyed by tunnel ID for a single node.

This is the top-level data structure for connector management. Each node has one ConnectorPool, and each pool contains one Router per active tunnel.

All methods are nil-safe — calling on a nil *ConnectorPool is valid.

func NewConnectorPool

func NewConnectorPool(node string) *ConnectorPool

NewConnectorPool creates a new ConnectorPool for the given node.

func (*ConnectorPool) Add

func (p *ConnectorPool) Add(rid relay.TunnelID, c *Connector)

Add creates or retrieves a Router for the given tunnel ID and adds the connector to it. If no router exists for the tunnel ID, one is created automatically.

func (*ConnectorPool) Close

func (p *ConnectorPool) Close() error

Close shuts down all routers and clears the pool. Safe to call on a nil pool. Subsequent calls are no-ops (delegates to Router.Close).

func (*ConnectorPool) Del

func (p *ConnectorPool) Del(rid relay.TunnelID, host string, cid relay.ConnectorID)

Del removes a connector from a specific router. Safe to call on a nil pool.

func (*ConnectorPool) Get

func (p *ConnectorPool) Get(rid relay.TunnelID, host string) *Connector

Get retrieves a connector for the given tunnel ID and host address. Returns nil if the pool is nil, the router doesn't exist, or no connector matches the host.

type Router

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

Router manages a set of connectors for a single tunnel (TunnelID).

Connectors are grouped by host address. When a packet arrives destined for a particular host, the router selects the appropriate connector using weighted random selection.

All methods are safe for concurrent use — the embedded RWMutex guards the connectors map.

func NewRouter

func NewRouter(node string, rid relay.TunnelID) *Router

NewRouter creates a new Router identified by node name and tunnel ID.

func (*Router) AddConnector

func (r *Router) AddConnector(c *Connector)

AddConnector registers a connector in the router. Nil connectors are silently ignored.

func (*Router) Close

func (r *Router) Close() error

Close shuts down the router: closes all connectors, clears the map, and marks the router as closed. Subsequent calls are no-ops.

The double-close protection uses a select on r.close — under the write lock — so it is race-free.

func (*Router) DelConnector

func (r *Router) DelConnector(host string, cid relay.ConnectorID)

DelConnector removes a connector identified by its host and connector ID. If the removed connector was the last one for the host, the host entry is deleted from the map to prevent accumulation of empty slices. If no matching connector is found, the call is a no-op.

func (*Router) GetConnector

func (r *Router) GetConnector(host string) *Connector

GetConnector selects a connector for the given host using weighted random selection.

Selection rules:

  • Single connector → returned directly.
  • Multiple connectors → weighted random selection.
  • A connector with weight == MaxWeight takes priority: only MaxWeight connectors are considered.
  • Weight 0 is treated as weight 1.

Returns nil if no connector exists for the host.

func (*Router) ID

func (r *Router) ID() relay.TunnelID

ID returns the router's tunnel identifier.

Jump to

Keyboard shortcuts

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