chain

package
v0.6.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: 16 Imported by: 2 modules, 21 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 chain defines the proxy chain interfaces — the core routing layer of TNET. A proxy chain consists of multiple nodes through which traffic is forwarded sequentially to reach the destination.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BindOption

type BindOption func(opts *BindOptions)

BindOption is a functional option for configuring BindOptions.

func BacklogBindOption

func BacklogBindOption(backlog int) BindOption

BacklogBindOption sets the accept backlog size.

func LoggerBindOption

func LoggerBindOption(logger logger.Logger) BindOption

LoggerBindOption sets the logger for the bind operation.

func MuxBindOption

func MuxBindOption(mux bool) BindOption

MuxBindOption sets whether multiplexing is enabled.

func UDPConnTTLBindOption

func UDPConnTTLBindOption(ttl time.Duration) BindOption

UDPConnTTLBindOption sets the UDP connection TTL.

func UDPDataBufferSizeBindOption

func UDPDataBufferSizeBindOption(size int) BindOption

UDPDataBufferSizeBindOption sets the UDP data buffer size.

func UDPDataQueueSizeBindOption

func UDPDataQueueSizeBindOption(size int) BindOption

UDPDataQueueSizeBindOption sets the UDP data queue size.

type BindOptions

type BindOptions struct {
	// Mux enables multiplexing on the bind listener.
	Mux bool
	// Backlog is the accept backlog size.
	Backlog int
	// UDPDataQueueSize is the queue size for UDP data packets.
	UDPDataQueueSize int
	// UDPDataBufferSize is the buffer size for UDP data packets.
	UDPDataBufferSize int
	// UDPConnTTL is the TTL for UDP connections.
	UDPConnTTL time.Duration
	// Logger is the logger for this bind operation.
	Logger logger.Logger
}

BindOptions holds the runtime parameters for Bind operations.

type Chainer

type Chainer interface {
	// Route returns a Route for the target network and address, or nil if
	// no suitable route is available.
	Route(ctx context.Context, network, address string, opts ...RouteOption) Route
}

Chainer selects a Route for the given target address. It represents a collection of proxy chains, from which the best matching route is chosen.

type DialOption

type DialOption func(opts *DialOptions)

DialOption is a functional option for configuring DialOptions.

func InterfaceDialOption

func InterfaceDialOption(ifName string) DialOption

InterfaceDialOption sets the network interface for the dial.

func LoggerDialOption

func LoggerDialOption(logger logger.Logger) DialOption

LoggerDialOption sets the logger for the dial.

func NetnsDialOption added in v0.3.2

func NetnsDialOption(netns string) DialOption

NetnsDialOption sets the network namespace for the dial.

func SockOptsDialOption

func SockOptsDialOption(so *SockOpts) DialOption

SockOptsDialOption sets the socket options for the dial.

type DialOptions

type DialOptions struct {
	// Interface is the network interface to bind to.
	Interface string
	// Netns is the network namespace name.
	Netns string
	// SockOpts holds socket options.
	SockOpts *SockOpts
	// Logger is the logger for this dial operation.
	Logger logger.Logger
}

DialOptions holds the runtime parameters for Dial operations.

type FailCodes added in v0.6.1

type FailCodes []int

FailCodes defines HTTP response status codes that mark a node as failed. The response is still relayed to the client as-is; marking only affects subsequent node selection (via the selector's FailFilter). Codes < 100 are wildcard hundred-level prefixes (e.g. 5 → 5xx).

func (FailCodes) Match added in v0.6.1

func (fc FailCodes) Match(statusCode int) bool

Match reports whether statusCode matches any configured code. Exact codes are compared directly; codes < 100 match hundred-level groups (e.g. code 5 matches 500-599).

type HTTPBodyRewriteSettings added in v0.3.2

type HTTPBodyRewriteSettings struct {
	// Type is the MIME type to match, e.g. "text/html".
	Type string
	// Pattern is the regex to match against the response body.
	Pattern *regexp.Regexp
	// Replacement is the replacement bytes.
	Replacement []byte
	// Rewriter is an optional plugin-based rewriter.
	// When set, Rewrite delegates to the plugin instead of using Pattern.
	Rewriter rewriter.Rewriter
	// MaxChunkSize limits buffering for chunked/unknown-length non-streaming
	// bodies. When > 0 and the body fits within this limit, the body is
	// buffered and rewritten; if exceeded, the body passes through unchanged.
	MaxChunkSize int
}

HTTPBodyRewriteSettings defines an HTTP body rewrite rule.

type HTTPHeaderRewriteSettings added in v0.6.1

type HTTPHeaderRewriteSettings struct {
	// Name is the regex matched against the *lowercased* header name, so a
	// pattern with uppercase letters needs an explicit (?i) flag.
	// In plugin mode it gates whether the plugin is invoked.
	// Note: *regexp.Regexp (not string like HTTPBodyRewriteSettings.Type)
	// is intentional — header *names* need regex matching, while body rules
	// match a MIME prefix. Do not "align" this back to string.
	Name *regexp.Regexp
	// Pattern is the regex matched against each header value (regex mode);
	// in plugin mode it is unused.
	Pattern *regexp.Regexp
	// Replacement is the replacement bytes (regex mode).
	Replacement []byte
	// Rewriter is an optional plugin-based rewriter. When set, Rewrite
	// delegates to the plugin over the serialized header block. The plugin
	// receives a sorted, canonicalized header block (http.Header.Write
	// normalizes names and sorts keys), not the original wire bytes.
	Rewriter rewriter.Rewriter
}

HTTPHeaderRewriteSettings defines an HTTP header rewrite rule.

type HTTPNodeSettings

type HTTPNodeSettings struct {
	// Host is the HTTP Host header value. When HostPattern is set, Host is
	// treated as a replacement template: submatches captured by HostPattern
	// against req.URL.Path are expanded into it ($1, $2, ...). This restores
	// the upstream Host from the encoded path for mirror routing (e.g.
	// path "/microsoft.github.io/x" + HostPattern "^/([a-z0-9-]+\.github\.io)/"
	// + Host "$1" → Host "microsoft.github.io").
	Host string
	// HostPattern is the regex matched against req.URL.Path to derive the
	// Host. It only affects the Host header (never the dial target or TLS
	// SNI), so it is intended for Host-routed origins (GitHub Pages) rather
	// than SNI-routed origins. When nil, Host is used as a static value.
	HostPattern *regexp.Regexp
	// RequestHeader contains custom request headers to inject.
	RequestHeader map[string]string
	// ResponseHeader contains custom response headers to inject.
	ResponseHeader map[string]string
	// Auther is the HTTP authenticator for this node.
	Auther auth.Authenticator
	// RewriteURL holds the URL rewrite rules.
	RewriteURL []HTTPURLRewriteSetting
	// RewriteRequestBody holds the request body rewrite rules.
	RewriteRequestBody []HTTPBodyRewriteSettings
	// RewriteResponseBody holds the response body rewrite rules.
	RewriteResponseBody []HTTPBodyRewriteSettings
	// RewriteRequestHeader holds the request-header rewrite rules. The Host
	// header is not reachable here (net/http keeps it in Request.Host, not
	// Request.Header) — use Host above instead.
	RewriteRequestHeader []HTTPHeaderRewriteSettings
	// RewriteResponseHeader holds the response-header rewrite rules.
	RewriteResponseHeader []HTTPHeaderRewriteSettings
	// FailCodes lists response status codes that mark the node as failed.
	FailCodes FailCodes
}

HTTPNodeSettings holds HTTP-level configuration for a node.

type HTTPURLRewriteSetting

type HTTPURLRewriteSetting struct {
	// Pattern is the regex to match against the URL.
	Pattern *regexp.Regexp
	// Replacement is the replacement string.
	Replacement string
}

HTTPURLRewriteSetting defines an HTTP URL rewrite rule.

type Node

type Node struct {
	Name string
	Addr string
	// contains filtered or unexported fields
}

Node represents a single hop in a proxy chain. Each node has a name, address, transport layer, and optional filters for protocol-specific routing. Nodes implement selector.Markable so that failed nodes can be temporarily excluded from selection.

func NewNode

func NewNode(name string, addr string, opts ...NodeOption) *Node

NewNode creates a new Node with the given name and address.

func (*Node) Close added in v0.6.1

func (node *Node) Close() error

Close stops the node's probe goroutine if one is running.

func (*Node) Copy

func (node *Node) Copy() *Node

Copy returns a shallow copy of the Node.

func (*Node) Marker

func (node *Node) Marker() selector.Marker

Marker returns the Node's failure marker. Implements the selector.Markable interface.

func (*Node) Metadata

func (node *Node) Metadata() metadata.Metadata

Metadata returns the Node's metadata. Implements the metadata.Metadatable interface.

func (*Node) Options

func (node *Node) Options() *NodeOptions

Options returns the Node's configuration.

func (*Node) ProbeResult added in v0.6.1

func (node *Node) ProbeResult() *ProbeResult

ProbeResult implements chain.ProbeResultReader.

func (*Node) SetProbeCancel added in v0.6.1

func (node *Node) SetProbeCancel(c context.CancelFunc)

SetProbeCancel stores the cancel function for the node's probe goroutine.

func (*Node) SetProbeResult added in v0.6.1

func (node *Node) SetProbeResult(r *ProbeResult)

SetProbeResult stores the latest probe result.

type NodeFilterSettings added in v0.3.2

type NodeFilterSettings struct {
	// Protocol filters by proxy protocol name (e.g. "http", "socks5").
	Protocol string
	// Host filters by hostname pattern.
	Host string
	// Path filters by URL path.
	Path string
}

NodeFilterSettings defines filtering criteria used to select nodes during routing.

type NodeOption

type NodeOption func(*NodeOptions)

NodeOption is a functional option for configuring NodeOptions.

func BypassNodeOption

func BypassNodeOption(bp bypass.Bypass) NodeOption

BypassNodeOption sets the Bypass rule for the node.

func HTTPNodeOption

func HTTPNodeOption(httpSettings *HTTPNodeSettings) NodeOption

HTTPNodeOption sets the HTTP settings for the node.

func HostMapperNodeOption

func HostMapperNodeOption(m hosts.HostMapper) NodeOption

HostMapperNodeOption sets the HostMapper for the node.

func MatcherBodySizeNodeOption added in v0.6.1

func MatcherBodySizeNodeOption(size int) NodeOption

MatcherBodySizeNodeOption sets the max request body prefix (bytes) exposed to body matchers for this node. 0 disables body matching.

func MatcherNodeOption added in v0.3.2

func MatcherNodeOption(matcher routing.Matcher) NodeOption

MatcherNodeOption sets the routing Matcher for the node.

func MetadataNodeOption

func MetadataNodeOption(md metadata.Metadata) NodeOption

MetadataNodeOption sets the Metadata for the node.

func NetworkNodeOption

func NetworkNodeOption(network string) NodeOption

NetworkNodeOption sets the network type for the node.

func NodeFilterOption added in v0.3.2

func NodeFilterOption(filter *NodeFilterSettings) NodeOption

NodeFilterOption sets the filter settings for the node.

func PriorityNodeOption added in v0.3.2

func PriorityNodeOption(priority int) NodeOption

PriorityNodeOption sets the priority for the node. Higher priority nodes are selected first during routing.

func ResolverNodeOption added in v0.6.1

func ResolverNodeOption(resolver resolver.Resolver) NodeOption

ResolverNodeOption sets the Resolver for the node.

func TLSNodeOption

func TLSNodeOption(tlsSettings *TLSNodeSettings) NodeOption

TLSNodeOption sets the TLS settings for the node.

func TransportNodeOption

func TransportNodeOption(tr Transporter) NodeOption

TransportNodeOption sets the Transporter for the node.

type NodeOptions

type NodeOptions struct {
	Network         string
	Transport       Transporter
	Bypass          bypass.Bypass
	Resolver        resolver.Resolver
	HostMapper      hosts.HostMapper
	Filter          *NodeFilterSettings
	HTTP            *HTTPNodeSettings
	TLS             *TLSNodeSettings
	Metadata        metadata.Metadata
	Matcher         routing.Matcher
	MatcherBodySize int
	Priority        int
}

NodeOptions holds the initialization parameters for a Node.

type ProbeConfig added in v0.6.1

type ProbeConfig struct {
	Type           ProbeType
	Addr           string
	Interval       time.Duration
	Timeout        time.Duration
	HTTPPath       string
	HTTPHost       string
	HTTPHeaders    map[string]string
	ExpectedStatus int
	Command        string
}

ProbeConfig holds the configuration for a node-level liveness probe. It is embedded in node config and drives the per-node probe goroutine.

type ProbeResult added in v0.6.1

type ProbeResult struct {
	Success   bool
	Latency   time.Duration
	Error     string
	Timestamp time.Time
}

ProbeResult records the outcome of a single probe attempt.

type ProbeResultReader added in v0.6.1

type ProbeResultReader interface {
	ProbeResult() *ProbeResult
}

ProbeResultReader is implemented by types that expose a probe result, enabling generic latency-aware strategies and filters.

type ProbeType added in v0.6.1

type ProbeType string

ProbeType names the probing method for node liveness checks.

const (
	ProbeTypeTCP  ProbeType = "tcp"
	ProbeTypeHTTP ProbeType = "http"
	ProbeTypeCmd  ProbeType = "cmd"
)

type Route

type Route interface {
	// Dial connects to the target address through the proxy chain.
	Dial(ctx context.Context, network, address string, opts ...DialOption) (net.Conn, error)
	// Bind sets up a reverse listener through the proxy chain, allowing
	// remote clients to connect back.
	Bind(ctx context.Context, network, address string, opts ...BindOption) (net.Listener, error)
	// Nodes returns the list of nodes that make up this route.
	Nodes() []*Node
}

Route represents a path through a chain of proxy nodes to a destination. A Route knows how to Dial (forward) and Bind (reverse tunnel) traffic through the proxy chain.

type RouteOption

type RouteOption func(opts *RouteOptions)

RouteOption is a functional option for configuring RouteOptions.

func WithHostRouteOption

func WithHostRouteOption(host string) RouteOption

WithHostRouteOption sets the target hostname.

type RouteOptions

type RouteOptions struct {
	// Host is the target hostname, used for host-based routing decisions.
	Host string
}

RouteOptions holds the runtime parameters for route selection.

type Router

type Router interface {
	// Options returns the router's configuration.
	Options() *RouterOptions
	// Dial connects to the target address through the configured chain,
	// applying resolution, host mapping, recording, and retry logic.
	Dial(ctx context.Context, network, address string, opts ...DialOption) (net.Conn, error)
	// Bind creates a reverse listener through the configured chain.
	Bind(ctx context.Context, network, address string, opts ...BindOption) (net.Listener, error)
}

Router is the top-level routing interface used by both Listeners and Handlers for upstream communication. It combines chain-based routing with DNS resolution, host mapping, and retry/timeout logic.

type RouterOption

type RouterOption func(*RouterOptions)

RouterOption is a functional option for configuring RouterOptions.

func ChainRouterOption

func ChainRouterOption(chain Chainer) RouterOption

ChainRouterOption sets the Chainer.

func HostMapperRouterOption

func HostMapperRouterOption(m hosts.HostMapper) RouterOption

HostMapperRouterOption sets the HostMapper.

func InterfaceRouterOption

func InterfaceRouterOption(ifceName string) RouterOption

InterfaceRouterOption sets the network interface.

func LoggerRouterOption

func LoggerRouterOption(logger logger.Logger) RouterOption

LoggerRouterOption sets the Logger.

func NetnsRouterOption added in v0.3.2

func NetnsRouterOption(netns string) RouterOption

NetnsRouterOption sets the network namespace.

func RecordersRouterOption

func RecordersRouterOption(recorders ...recorder.RecorderObject) RouterOption

RecordersRouterOption sets the traffic Recorders.

func ResolverRouterOption

func ResolverRouterOption(resolver resolver.Resolver) RouterOption

ResolverRouterOption sets the Resolver.

func RetriesRouterOption

func RetriesRouterOption(retries int) RouterOption

RetriesRouterOption sets the number of dial retries.

func SockOptsRouterOption

func SockOptsRouterOption(so *SockOpts) RouterOption

SockOptsRouterOption sets the socket options.

func TimeoutRouterOption

func TimeoutRouterOption(timeout time.Duration) RouterOption

TimeoutRouterOption sets the dial timeout.

type RouterOptions

type RouterOptions struct {
	// Retries is the number of dial retries on failure.
	Retries int
	// Timeout is the dial timeout.
	Timeout time.Duration
	// IfceName is the network interface name to bind to.
	IfceName string
	// Netns is the network namespace name.
	Netns string
	// SockOpts holds socket options for connections.
	SockOpts *SockOpts
	// Chain is the Chainer that selects routes.
	Chain Chainer
	// Resolver resolves domain names to IP addresses.
	Resolver resolver.Resolver
	// HostMapper maps hostnames to static IP addresses.
	HostMapper hosts.HostMapper
	// Recorders records traffic data.
	Recorders []recorder.RecorderObject
	// Logger is the logger for router operations.
	Logger logger.Logger
}

RouterOptions holds the initialization parameters for a Router.

type SockOpts

type SockOpts struct {
	// Mark is the SO_MARK value for the socket.
	Mark int
}

SockOpts holds socket-level options applied to connections.

type TLSNodeSettings

type TLSNodeSettings struct {
	// ServerName is the TLS SNI server name.
	ServerName string
	// Secure indicates whether a secure connection is used.
	Secure bool
	// Options specifies TLS version and cipher suite settings.
	Options struct {
		MinVersion   string
		MaxVersion   string
		CipherSuites []string
		ALPN         []string
	}
}

TLSNodeSettings holds TLS configuration for a node.

type TransportOption

type TransportOption func(*TransportOptions)

TransportOption is a functional option for configuring TransportOptions.

func AddrTransportOption

func AddrTransportOption(addr string) TransportOption

AddrTransportOption sets the dial address.

func InterfaceTransportOption

func InterfaceTransportOption(ifceName string) TransportOption

InterfaceTransportOption sets the network interface.

func NetnsTransportOption added in v0.3.2

func NetnsTransportOption(netns string) TransportOption

NetnsTransportOption sets the network namespace.

func RouteTransportOption

func RouteTransportOption(route Route) TransportOption

RouteTransportOption sets the parent Route.

func SockOptsTransportOption

func SockOptsTransportOption(so *SockOpts) TransportOption

SockOptsTransportOption sets the socket options.

type TransportOptions

type TransportOptions struct {
	// Addr is the address to dial.
	Addr string
	// IfceName is the network interface to bind to.
	IfceName string
	// Netns is the network namespace name.
	Netns string
	// SockOpts holds socket options.
	SockOpts *SockOpts
	// Route is the route this transporter belongs to.
	Route Route
}

TransportOptions holds the runtime parameters for a Transporter.

type Transporter added in v0.3.2

type Transporter interface {
	// Dial establishes a connection to the proxy node's address.
	Dial(ctx context.Context, addr string) (net.Conn, error)
	// Handshake performs a transport-level handshake (e.g. TLS) on the connection.
	Handshake(ctx context.Context, conn net.Conn) (net.Conn, error)
	// Connect reaches the target destination through the proxy node.
	Connect(ctx context.Context, conn net.Conn, network, address string) (net.Conn, error)
	// Bind sets up a reverse listener through the proxy node.
	Bind(ctx context.Context, conn net.Conn, network, address string, opts ...connector.BindOption) (net.Listener, error)
	// Multiplex reports whether the underlying connection supports multiplexing.
	Multiplex() bool
	// Options returns the transporter's configuration.
	Options() *TransportOptions
	// Copy returns a copy of this Transporter.
	Copy() Transporter
}

Transporter combines a dialer and connector to handle one node in a proxy chain. It establishes a connection to the next proxy hop (Dial), negotiates the transport protocol (Handshake), and reaches the final destination through the hop (Connect). It also supports reverse tunnels (Bind).

Jump to

Keyboard shortcuts

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