Documentation
¶
Overview ¶
Package tunnel is a leaf implementation of TCP tunnel protocols and data forwarding. It is used by httpapi, worker and commands and imports no job/config/wshub packages.
Index ¶
- Constants
- Variables
- func Bridge(ctx context.Context, ws *websocket.Conn, c net.Conn) (int64, int64, error)
- func CheckBindAddrs(specs []ForwardSpec) error
- func DatagramBridge(ctx context.Context, ws *websocket.Conn, pc net.PacketConn, target net.Addr) (int64, int64, error)
- func HTTPStatusForCode(c string) int
- func PipePair(ctx context.Context) (client, server *websocket.Conn, err error)
- func ProxyFailure(err error) (byte, int)
- func SplitSpecs(args []string) ([]string, error)
- func ValidateTarget(t string) error
- func WriteProxyReply(w io.Writer, proto string, dialErr error) error
- func WriteSOCKSReply(w io.Writer, rep byte) error
- type Allowlist
- type Arrival
- type Binding
- type BridgeOptions
- type BridgeResult
- type DialResult
- type ForwardSpec
- type Forwarder
- type ForwarderRegistration
- type ForwarderRegistry
- func (r *ForwarderRegistry) Delete(id, caller string) error
- func (r *ForwarderRegistry) Heartbeat(id, caller string, specs []ForwardSpec) (ForwarderRegistration, error)
- func (r *ForwarderRegistry) List() []ForwarderRegistration
- func (r *ForwarderRegistry) Lookup(id string) (ForwarderRegistration, error)
- func (r *ForwarderRegistry) Register(caller string, reg ForwarderRegistration) ForwarderRegistration
- func (r *ForwarderRegistry) RequestStop(id, caller string, asAdmin bool) (ForwarderRegistration, error)
- func (r *ForwarderRegistry) TTL() time.Duration
- type Hello
- type HostedDial
- type HostedForwarderManager
- type Info
- type Pending
- type ProxyRequest
- type Registry
- func (r *Registry) Activate(i Info) (func(int64, int64), func())
- func (r *Registry) Begin(b Binding, ttl time.Duration) (*Pending, string)
- func (r *Registry) Consume(n string, now time.Time) (Binding, bool)
- func (r *Registry) Deliver(id string, a Arrival) (<-chan struct{}, bool)
- func (r *Registry) List() []Info
- type SpliceOptions
- type SpliceResult
Constants ¶
const ( ReasonClientClosed = "client_closed" ReasonWorkerClosed = "worker_closed" ReasonIdleTimeout = "idle_timeout" ReasonContextDone = "ctx_done" ReasonError = "error" ReasonPingTimeout = "ping_timeout" )
const ( // ReasonDialFailed: the tunnel could never be opened (no session existed). ReasonDialFailed = "dial_failed" // ReasonDroppedMaxSessions: a new UDP source was refused because UDPMaxSessions // sessions were already open. ReasonDroppedMaxSessions = "dropped_max_sessions" // ReasonIdle: a UDP session was reaped after UDPIdleTimeout of silence. ReasonIdle = "idle" // ReasonWriteFailed: a datagram could not be written up the tunnel. ReasonWriteFailed = "write_failed" // ReasonHandshakeFailed: a socks listener's client never completed (or was // refused in) its SOCKS5 / HTTP CONNECT handshake; no tunnel was dialed. ReasonHandshakeFailed = "handshake_failed" )
Forwarder-side close reasons that have no Bridge counterpart. The Bridge reasons (ReasonClientClosed, ReasonWorkerClosed, ...) are reused verbatim for TCP so the three log ends speak the same vocabulary.
const ( ConnectPath = "/v1/tunnels/connect" WorkerConnectPath = "/v1/workers/tunnel-connect" )
const ( CodeDisabled = "disabled" CodeNotAllowed = "not_allowed" CodeLimit = "limit" CodeDialFailed = "dial_failed" CodeBadTarget = "bad_target" )
const ( ProxySOCKS5 = "socks5" ProxyHTTP = "http" )
Proxy protocols a handshake was read in.
const ( NetworkSOCKS = "socks" SOCKSTarget = "*" )
NetworkSOCKS is the ForwardSpec.Network of a dynamic forward (`socks/[bind:]port`): a local SOCKS5 / HTTP CONNECT listener whose target is chosen per connection. Its Target is SOCKSTarget, a display placeholder — every connection still goes through the ordinary tunnel auth and the worker's allowlist with its real target.
const CapStop = "stop"
CapStop is the capability a forwarder advertises when it understands the stop-requested heartbeat answer (HTTP 410) and exits on it.
const DefaultForwarderTTL = 90 * time.Second
DefaultForwarderTTL is how long a forwarder registration survives without a heartbeat (TUN-03). It is three times the CLI's 30s heartbeat interval, so a single dropped heartbeat does not make a live forwarder flicker out of the list.
const HeaderTunnelID = "X-Gofer-Tunnel-Id"
const MaxChunk = 32 * 1024
MaxChunk is the maximum TCP read forwarded in one websocket message.
const ReadLimit = 64 * 1024
ReadLimit is the maximum websocket message payload consumed.
Variables ¶
var ( // ErrForwarderNotFound: no such registration — never registered here, or expired // because its process stopped heartbeating (killed, host asleep, network gone). ErrForwarderNotFound = errors.New("forwarder registration not found (expired?)") // ErrForwarderNotOwner: the registration belongs to another caller. A caller may // only renew or remove its own. ErrForwarderNotOwner = errors.New("forwarder registration belongs to another caller") // ErrForwarderStopUnsupported: the registration did not advertise CapStop — an older // `gofer tun forward` that would read an unknown heartbeat answer as a warning and // keep running, so a remote stop could never reach it. ErrForwarderStopUnsupported = errors.New("forwarder does not support remote stop") // ErrForwarderHosted: a server-hosted forwarder is stopped through its own // /v1/tunnels/hosted/{name} route, not through the external-process stop request. ErrForwarderHosted = errors.New("forwarder is server-hosted; stop it through the hosted route") // ErrForwarderStopRequested: the heartbeat's answer once a stop was requested. The // registry has already removed the entry when it returns this, so the forwarder // must exit rather than re-register. ErrForwarderStopRequested = errors.New("stop requested") )
Errors a heartbeat or delete reports for an id the registry does not hold, or holds for somebody else.
var ErrRendezvousTimeout = errors.New("rendezvous timeout")
ErrRendezvousTimeout indicates no worker arrived before the rendezvous deadline.
var ErrUnsupported = errors.New("tunnel unsupported")
ErrUnsupported indicates a worker protocol older than v5 lacks tunnel support.
var ErrWorkerOffline = errors.New("worker offline")
ErrWorkerOffline indicates the selected worker is not connected.
Functions ¶
func Bridge ¶
Bridge forwards binary websocket messages and TCP bytes in both directions. toWS counts TCP bytes sent to websocket; fromWS counts websocket bytes sent to TCP.
func CheckBindAddrs ¶ added in v0.141.0
func CheckBindAddrs(specs []ForwardSpec) error
CheckBindAddrs verifies, before any listener starts, that every rule binds an address this machine actually has. A same-address rule (`=ip:port`) needs the target IP added to a local (loopback) adapter first; without this check the operator gets a bare "cannot assign requested address" — and with several rules the ones before the bad one would already be listening.
Loopback, unspecified (0.0.0.0 / ::) and host-name binds are not checked.
func DatagramBridge ¶
func DatagramBridge(ctx context.Context, ws *websocket.Conn, pc net.PacketConn, target net.Addr) (int64, int64, error)
DatagramBridge maps one UDP datagram to one binary websocket message.
The device socket is deliberately UNCONNECTED. A connected UDP socket only receives datagrams whose source is exactly the target address, and devices commonly answer from a different port than the one they were asked on — those replies are dropped by the kernel and the exchange just times out, which looks exactly like a dead tunnel. Replies are therefore accepted from any port of the target's IP; anything from another host is ignored so an unrelated sender on the device network cannot inject traffic into someone's tunnel.
func HTTPStatusForCode ¶
HTTPStatusForCode maps worker errors to HTTP status.
func PipePair ¶ added in v0.161.0
PipePair returns the two ends of an IN-PROCESS websocket pair: a client end and a server end, both real *websocket.Conn speaking the RFC 6455 framing over an in-memory pipe (net.Pipe) — no socket, no listener to bind and no bearer token involved.
It is what lets a server-side component dial the process it already runs in. The hosted forwarders use it to open their tunnels themselves instead of calling the server's own HTTP tunnel endpoint with the server's own token (design §6「托管转发改为进程内拨号,不再借 server 自己的 token 走 tunnelConnect」): the caller-side end goes to the Forwarder, the server-side end is spliced with the worker's data connection, exactly like the two ends the HTTP tunnel endpoint hands to Splice.
ctx only bounds the in-process handshake; the returned connections live until they are closed (they are NOT tied to ctx, so a dialer may cancel its request context as soon as the dial returns).
func ProxyFailure ¶ added in v0.141.0
ProxyFailure maps a tunnel dial error onto the SOCKS5 reply code and the HTTP status the proxy client sees. The connect endpoint's HTTP status is read through a TunnelStatus() method (client.TunnelError); a worker dial failure (502) is split into "refused" and "unreachable" by its message.
func SplitSpecs ¶
SplitSpecs flattens the spec arguments a command was given. Each argument may carry several rules separated by commas — the way operators naturally write them (`udp/21845:192.168.0.253:21845,1502:192.168.0.205:502`) — and the space-separated form stays valid, so `a,b`, `a b` and a mix of the two all mean the same thing. Whitespace around a rule is trimmed and empty items are dropped; the order is preserved, so `spec #N` in a parse error names the position the operator wrote.
A comma is never part of a rule: an IPv6 target is written `[::1]:port`, so no rule can be broken in half by the split.
A list with no usable entry is an error rather than an empty success — "no specs" is reported by the caller, not silently accepted here.
func ValidateTarget ¶
ValidateTarget validates host:port targets.
func WriteProxyReply ¶ added in v0.141.0
WriteProxyReply answers the handshake once the target dial finished: success, or the failure mapped by ProxyFailure.
Types ¶
type Allowlist ¶
type Allowlist struct {
// contains filtered or unexported fields
}
Allowlist contains parsed outbound target rules.
func ParseAllowlist ¶
ParseAllowlist parses host, CIDR and port rules. The port half is a single port, "*", a comma separated list, or inclusive ranges.
func (*Allowlist) AllowsNetwork ¶
type Binding ¶
type Binding struct {
TunnelID string
WorkerID string
InstanceID string
CallerID string
Target string
ClientRemote string
}
Binding associates a rendezvous with its identities.
type BridgeOptions ¶
type BridgeOptions struct{ OnFirstUp, OnFirstDown func() }
BridgeOptions observes the first successfully forwarded bytes in each direction. Up goes from websocket to device; Down goes from device to websocket.
type BridgeResult ¶
type BridgeResult struct {
ToWS, FromWS int64
// PacketsToWS / PacketsFromWS count datagrams (DatagramBridge only; zero
// for the TCP Bridge, where the stream has no packet boundary worth
// reporting). bytes / packets gives the mean datagram size and
// duration / packets the mean per-packet turnaround, which is what tells a
// chatty stop-and-wait protocol from a slow link.
PacketsToWS, PacketsFromWS int64
Reason string
Err error
}
BridgeResult retains the device-relative counters of Bridge and reports the first teardown cause using the same reason vocabulary as SpliceResult.
func BridgeWithOptions ¶
func BridgeWithOptions(ctx context.Context, ws *websocket.Conn, c net.Conn, opt BridgeOptions) BridgeResult
BridgeWithOptions is Bridge with first-byte callbacks and a teardown result.
func DatagramBridgeWithOptions ¶
func DatagramBridgeWithOptions(ctx context.Context, ws *websocket.Conn, pc net.PacketConn, target net.Addr, opt BridgeOptions) BridgeResult
DatagramBridgeWithOptions adds first-datagram callbacks and teardown cause.
type DialResult ¶
DialResult is what Dial hands back: the tunnel websocket plus the id the server assigned to it (the X-Gofer-Tunnel-Id header; empty against a server that predates it). The id is what lets a forwarder log line be matched with the server and worker lines for the same tunnel.
type ForwardSpec ¶
ForwardSpec describes a local listener and remote target.
func ParseForwardSpec ¶
func ParseForwardSpec(s string) (ForwardSpec, error)
ParseForwardSpec parses one forward rule:
[udp/][bind:]lport:host:port static forward [udp/]=ip:port same address: listen on ip:port, forward to ip:port socks/[bind:]port dynamic forward (SOCKS5 / HTTP CONNECT), loopback only
func ParseSpecs ¶
func ParseSpecs(specs []string) ([]ForwardSpec, error)
ParseSpecs parses a flattened spec list (see SplitSpecs) and names the entry that failed. A comma-joined list of four rules that answers only "invalid spec" leaves the operator bisecting the line by hand, so the error carries the position and the original text of the offending rule.
func (ForwardSpec) IsSOCKS ¶ added in v0.141.0
func (f ForwardSpec) IsSOCKS() bool
IsSOCKS reports whether f is a dynamic (SOCKS) forward.
func (ForwardSpec) ListenAddr ¶
func (f ForwardSpec) ListenAddr() string
ListenAddr returns bind:localport.
type Forwarder ¶
type Forwarder struct {
Spec ForwardSpec
// Dial opens the tunnel for a static rule (Spec.Target). DialTarget, when set,
// is used instead and receives the target: a socks rule has no fixed target, so
// it is the only dialer a dynamic forward can use.
Dial func(context.Context) (DialResult, error)
DialTarget func(ctx context.Context, network, target string) (DialResult, error)
Log func(string, ...any)
OnEvent func(string, ...any)
ActualAddr string
Ready chan error
UDPIdleTimeout time.Duration
UDPMaxSessions int
// contains filtered or unexported fields
}
Forwarder accepts local connections and bridges them to a tunnel.
Two observation surfaces coexist: Log (human one-liners, legacy) and OnEvent (structured events, see the event list below). Either may be nil. A dial failure always surfaces through slog when neither is set.
Events, with their attrs (all events also carry session_id; tunnel_id is set once the dial succeeded):
forward.started local, target, network
session.opened local, target, network
tunnel.opened tunnel_id, dial_ms
tunnel.first_up tunnel_id, first_byte_ms (first local->tunnel bytes)
tunnel.first_down tunnel_id, first_byte_ms (first tunnel->local bytes)
session.closed tunnel_id, close_reason, bytes_up, bytes_down, duration_ms[, error]
(UDP adds packets_up, packets_down)
session.rejected close_reason (dropped_max_sessions), max_sessions
tunnel.datagram tunnel_id, dir (up|down), len, gap_ms — only with GOFER_TUNNEL_TRACE=1
first_byte_ms and duration_ms count from the moment the dial started, so a slow rendezvous and a slow device answer are told apart via dial_ms.
type ForwarderRegistration ¶
type ForwarderRegistration struct {
// ID is hub-assigned ("fw-<8hex>"); a client never chooses it.
ID string
// CallerID is the authenticated caller that registered it, recorded by the hub —
// a client cannot claim another identity, nor touch another caller's entry.
CallerID string
Worker string
Specs []ForwardSpec
Host string
PID int
// Hosted marks a forwarder owned by the server process. Hosted entries are
// live as long as their manager entry, not as long as a client heartbeat.
Hosted bool
HostedName string
// Caps are the capabilities the forwarder process advertised at registration
// (CapStop). An older binary sends none.
Caps []string
// StopRequested is set by RequestStop and stays set until the forwarder's next
// heartbeat collects it (which removes the entry) or the TTL drops the entry.
StopRequested bool
StopRequestedAt time.Time
// StartedAt is when the forwarder started listening (the client's own clock).
StartedAt time.Time
// LastSeenAt is stamped by Register and refreshed by every heartbeat; the TTL
// counts from it, which is what keeps the uptime and the liveness answer separate.
LastSeenAt time.Time
}
ForwarderRegistration is one `gofer tun forward` process as the hub knows it: what it listens on, where it runs and who registered it.
It is DISPLAY state only. Registering grants no forwarding capability: a connection still goes through the ordinary tunnel auth (bearer token, can_tunnel) and the worker's own allowlist, exactly as before this registry existed.
func (ForwarderRegistration) HasCap ¶
func (reg ForwarderRegistration) HasCap(capability string) bool
HasCap reports whether the registration advertised the capability.
type ForwarderRegistry ¶
type ForwarderRegistry struct {
// contains filtered or unexported fields
}
ForwarderRegistry is the hub-side, in-memory registry of live forwarder processes.
TTL is read through a func, never cached: the value comes from server.tunnel.forwarder_ttl_sec, so a config reload applies to the next read without rebuilding the registry. Expiry is evaluated on every read and write, so no sweeper goroutine (and no shutdown ordering) is needed.
func NewForwarderRegistry ¶
func NewForwarderRegistry(ttl func() time.Duration) *ForwarderRegistry
NewForwarderRegistry builds a registry. ttl may be nil (or return <= 0), which means DefaultForwarderTTL.
func (*ForwarderRegistry) Delete ¶
func (r *ForwarderRegistry) Delete(id, caller string) error
Delete removes a registration (the forwarder's clean goodbye). An unknown id is ErrForwarderNotFound and another caller's id is ErrForwarderNotOwner.
func (*ForwarderRegistry) Heartbeat ¶
func (r *ForwarderRegistry) Heartbeat(id, caller string, specs []ForwardSpec) (ForwarderRegistration, error)
Heartbeat refreshes a registration and, when specs are given, replaces its rule list (the forwarder may have been restarted with different ports under the same id — the CLI re-registers in that case, but a heartbeat carrying rules keeps both ends honest). Callers may only renew their own.
func (*ForwarderRegistry) List ¶
func (r *ForwarderRegistry) List() []ForwarderRegistration
List returns the live registrations, oldest first, after dropping the ones whose heartbeat is older than the TTL.
func (*ForwarderRegistry) Lookup ¶ added in v0.161.0
func (r *ForwarderRegistry) Lookup(id string) (ForwarderRegistration, error)
Lookup returns one live registration, after dropping the registrations whose heartbeat is older than the TTL. An unknown (or expired) id is ErrForwarderNotFound. It is the read the stop route needs to resolve the registration's OWNER before the permission rule decides who may touch it.
func (*ForwarderRegistry) Register ¶
func (r *ForwarderRegistry) Register(caller string, reg ForwarderRegistration) ForwarderRegistration
Register stores a new registration and returns it with its hub-assigned id and caller. StartedAt defaults to now when the client did not send one.
func (*ForwarderRegistry) RequestStop ¶
func (r *ForwarderRegistry) RequestStop(id, caller string, asAdmin bool) (ForwarderRegistration, error)
RequestStop marks an external forwarder for remote stop; its next heartbeat is answered with ErrForwarderStopRequested and the entry is removed then. The owner may always ask; asAdmin lets an administrator ask for somebody else's forwarder (the same owner-or-admin rule as deleting a job). A hosted entry is ErrForwarderHosted and a registration without CapStop is ErrForwarderStopUnsupported. Asking twice is idempotent: the first request time is kept.
func (*ForwarderRegistry) TTL ¶
func (r *ForwarderRegistry) TTL() time.Duration
TTL is the effective registration lifetime: the configured value, else DefaultForwarderTTL.
type Hello ¶
type Hello struct {
TunnelID string `json:"tunnel_id"`
RelayNonce string `json:"relay_nonce"`
ErrorCode string `json:"error_code,omitempty"`
Error string `json:"error,omitempty"`
}
Hello is the worker rendezvous response.
type HostedDial ¶
type HostedDial func(ctx context.Context, callerID, worker, network, target string) (DialResult, error)
HostedDial is the server-side equivalent of the CLI's client DialTunnel call: open a tunnel on worker to network/target. The callback stays at the owner boundary so tunnel does not import httpapi or client, and Forwarder keeps the same lazy per-connection dial behavior. The target is passed per call because a socks rule picks it per connection.
callerID is the STARTER of the hosted forwarder: the dial is judged and registered as that caller, never as the server itself (design §6「判定与登记都按启动者」).
type HostedForwarderManager ¶
type HostedForwarderManager struct {
// contains filtered or unexported fields
}
HostedForwarderManager owns server-local listeners. It deliberately keeps only in-memory state: after a restart only presets marked autostart are restored by the server bootstrap path.
func NewHostedForwarderManager ¶
func NewHostedForwarderManager(ctx context.Context, registry *ForwarderRegistry, dial HostedDial) *HostedForwarderManager
func (*HostedForwarderManager) Start ¶
func (m *HostedForwarderManager) Start(name, starter, worker string, specs []ForwardSpec) (ForwarderRegistration, error)
Start binds every listener before publishing one hosted registry entry. A dial is intentionally not attempted here: Forwarder dials lazily on the first local connection, so autostart can succeed while a worker is still reconnecting.
starter is the caller the forwarder belongs to (see hostedEntry.starter).
func (*HostedForwarderManager) Starter ¶ added in v0.161.0
func (m *HostedForwarderManager) Starter(name string) (string, bool)
Starter reports the caller that started the running hosted forwarder name. It is what the stop route's permission rule compares against: the starter's own forwarder needs tunnel.hosted, anyone else's (or one whose starter is no longer a live caller — a legacy autostart row, see the httpapi starter resolution) tunnel.manage.others, which only a root administrator holds.
func (*HostedForwarderManager) Stop ¶
func (m *HostedForwarderManager) Stop(name string) error
func (*HostedForwarderManager) StopAll ¶
func (m *HostedForwarderManager) StopAll()
StopAll is used by server shutdown and is safe to call repeatedly.
type Info ¶
type Info struct {
ID, CallerID, WorkerID, Target, ClientRemote string
StartedAt time.Time
BytesUp, BytesDown int64
}
Info describes active tunnel.
type Pending ¶
type Pending struct {
// contains filtered or unexported fields
}
Pending tracks Begin -> Wait/Deliver -> Finish or Cancel; done closes when the rendezvous lifecycle ends.
type ProxyRequest ¶ added in v0.141.0
ProxyRequest is one accepted handshake: the protocol it arrived in and the host:port the client asked for.
func ReadProxyRequest ¶ added in v0.141.0
ReadProxyRequest reads one SOCKS5 or HTTP CONNECT handshake from br, answering the parts of the protocol that precede the target dial (SOCKS method selection) and any refusal. On success the caller dials the target and then answers with WriteProxyReply. br must be the reader the rest of the connection is read from: bytes a client pipelined after the handshake stay buffered in it.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry tracks pending and active tunnels.
func (*Registry) Activate ¶
Activate adds an active tunnel. Progress values are cumulative, driven by Splice OnProgress.
func (*Registry) Consume ¶
Consume validates and consumes a nonce once; expired or unknown nonces return ok=false.
type SpliceOptions ¶
type SpliceOptions struct {
PingInterval, PingTimeout time.Duration
OnProgress func(up, down int64)
// OnFirstUp fires when the first client->worker bytes are READ (before they are
// forwarded); OnFirstDown when the first worker->client bytes arrive. Reading
// the up marker early keeps the two events in causal order — nothing can come
// back down before something went up — so a log reader never sees a "response"
// logged ahead of the "request" it answers.
OnFirstUp, OnFirstDown func()
}
SpliceOptions configures websocket keepalive.
type SpliceResult ¶
SpliceResult reports forwarded byte counts and teardown reason.
func Splice ¶
func Splice(ctx context.Context, client, worker *websocket.Conn, opt SpliceOptions) SpliceResult
Splice forwards websocket messages between client and worker.