core

package module
v0.0.0-...-83ec5f7 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

README

⚠️ Archived. This repository is no longer maintained. Development has moved to the NavLink organization:

tunnelcat-core

A Go library for SOCKS5/TUN tunnel clients: session auth, a self-healing multi-node dialer pool, SOCKS5 (TCP + UDP ASSOCIATE) and TUN bridging, DHT peer discovery, NAT hole-punching, and a uTLS transport that disguises tunnel traffic as ordinary HTTPS uploads.

An open implementation of the Tunnel Cat tunnel architecture, released as a standalone client/library. There's no tooling here to deploy your own control/exit nodes, and no public control/exit network attached to this repo — you point it at a server you run yourself, speaking the login protocol described below.

Quickstart

go build ./...
go test ./...

Run the reference CLI against a control server you operate:

go run ./cmd/demo -server https://your-control-server:443 -user U -pass P
# starts a local SOCKS5 proxy at 127.0.0.1:1080 — point any SOCKS5 client at it
# (add -tun for a TUN interface too, -apikey/-socks also available)

...or use it directly as a library:

auth := core.NewAuthenticator(serverURL, apiKey, username, password)
if err := auth.Login(); err != nil {
    log.Fatal(err)
}

dialer := core.NewTunnelDialer(auth)
socks := core.NewSOCKS5Server("127.0.0.1:1080", dialer)
log.Fatal(socks.ListenAndServe())

serverURL must point at a server that speaks this library's login/tunnel protocol: POST <server>/ with {".command": "verifyPassword", ...}, response {"session": "<token>"}, then encrypted data-plane frames over X-Session-authenticated POSTs. key.go's exported VerifySignedPayload plus SessionKey/SealFrame/OpenFrame/ParseUploadFrame/ BuildUploadResponse give you everything needed to implement a compatible server without reverse-engineering the wire format from this client.

What's inside

  • Session & transport (tunnel.go) — Authenticator (login, session token, key- or password-based auth), TunnelDialer (creates tunnel connections disguised as HTTPS media uploads via uTLS browser fingerprints).
  • SOCKS5 (socks5.go, udp_assoc.go) — TCP CONNECT and UDP ASSOCIATE (RFC 1928 §4/§7), per-IP connection limiting, an optional bypass manager for LAN/in-country direct routing.
  • TUN bridging (tun.go, tun_darwin.go, tun_linux.go) — brings up a TUN interface backed by tun2socks routed through the local SOCKS5 proxy. Windows uses the Wintun driver (see licensing note below).
  • Dialer pool & routing (dialer_pool.go, router.go) — multi-node failover: RTT-based scoring, reliability-weighted picking, liveness tracking.
  • Discovery (discovery.go, dht/) — Ed25519-signed manifest fetch/verify plus a Kademlia-style DHT for decentralized peer discovery.
  • NAT/hole-punching (nat.go, holepunch.go) and relay (relay.go, mirror.go) — UDP hole-punch coordination and a relay fallback path for peers that can't punch through.
  • cmd/demo — the minimal CLI shown above.
  • tools/fetch_wintun — pre-fetches the Wintun driver DLL into the source tree, if you'd rather not rely on the runtime auto-download.

Wintun licensing note

Windows TUN support uses the Wintun driver, which is not part of this repository — internal/wintun downloads the official build directly from wintun.net the first time it's needed. Wintun is distributed by WireGuard under its own license terms (GPLv2 / LGPLv2.1 / a commercial license, at the distributor's choice) — review those terms before redistributing a binary that bundles the driver.

License

Apache License 2.0 — see LICENSE. Third-party dependencies keep their own licenses (all permissive: BSD-3, MIT, MPL-2.0); see go.mod.

Documentation

Index

Constants

View Source
const (
	ChTunnel   byte = 0x00 // raw TCP proxy to exit; no TLS termination on control
	ChRelayAPI byte = 0x01 // relay tracker HTTP API
	ChSignal   byte = 0x02 // NAT relay reverse-tunnel (yamux)
	ChNATRelay byte = 0x03 // sender routing through a NAT relay node
	ChParaExit byte = 0x04 // para-exit yamux reverse-tunnel (on exit)
)

Channel type constants embedded in ClientHello Session ID for server-side demultiplexing. The two-byte marker {chMagic, channelType} at sid[0:2] identifies a tunnel connection; standard TLS 1.3 clients send a random 32-byte session ID so accidental collisions are negligible (p ≈ 1/256 per connection).

View Source
const (
	TUNDeviceName = "snc0"
	TUNMTU        = 1500
	TUNAddr       = "198.18.0.1"
	TUNMask       = "255.255.0.0"
	TUNIPv6Addr   = "fd00::2"
)
View Source
const (
	FrameTypeUpload     = frameTypeUpload
	FrameTypeStreamOpen = frameTypeStreamOpen
)

FrameTypeUpload and FrameTypeStreamOpen are the plaintext frame-type tags used by the decoy upload protocol (see buildUploadPlain/parseUploadFrame).

View Source
const (
	// PunchTimeout is how long Punch waits for a probe from the peer.
	PunchTimeout = 3 * time.Second
)

Variables

View Source
var ChanDepth = 64

ChanDepth controls the depth of each TunnelConn's dataChan buffer. Android sets this proportionally to available RAM via SNC_DATACHAN_DEPTH.

View Source
var ControlSNILookup func(addr string) string

ControlSNILookup, if set, is called with a control node addr (host:port) to obtain the SNI hostname to use for that TLS connection. Returns "" when no SNI is configured for that addr, preserving the current empty-SNI behaviour. Set once at startup via Discoverer.UseAsSNIProvider().

View Source
var ErrAuthRejected = errors.New("auth rejected")

ErrAuthRejected is returned by Login when the control server responded but explicitly refused the credentials (no session token in response). It is distinct from a network error where the server was unreachable entirely. Callers use errors.Is to distinguish transient network failures from definitive credential rejections.

View Source
var ErrAuthTransient = errors.New("auth transient: arbiter unavailable")

ErrAuthTransient marks a login attempt that failed because the arbiter was briefly unreachable from the node terminating the request (status 503 with "transient":true — see the server-side authenticate/deferredOrTransient logic), not because the credentials were rejected. Callers must retry (optionally via the control-cache fallback, see tryAuthViaControlCache) rather than treat this as ErrAuthRejected — the latter would make the user re-enter their key over what is, architecturally, a momentary blip.

View Source
var GlobalDNSCache = &dnsCache{m: make(map[string]dnsCacheEntry)}

GlobalDNSCache maps resolved IP addresses to their FQDN so ShouldBypass can apply TLD-based routing overrides (e.g. .ru → always tunnel for non-RU users).

View Source
var Log = log.New(os.Stderr, "[tunnelcat] ", log.LstdFlags|log.Lmsgprefix)

Log is the package-level logger. Initialised by InitLogging; falls back to stderr if InitLogging has not been called.

View Source
var LogRing = newRingBuffer(logRingSize)

LogRing is a circular buffer that captures recent log output for upload. It is populated by InitLogging and read by LogUploader.

View Source
var TunLog = log.New(io.Discard, "", log.LstdFlags)

TunLog logs every TCP/UDP connection entering the TUN interface. Initialised by InitTunLogging; discards output until then.

View Source
var Version = "dev"

Version is set at build time via -ldflags "-X github.com/kostiakhait/tunnelcat-core.Version=202604120936". Format: YYYYMMDDHHmm. Defaults to "dev" when not set.

Functions

func AllUTLSPresets

func AllUTLSPresets() []utls.ClientHelloID

AllUTLSPresets returns the distinct browser presets used by the tunnel transport. Useful for diagnostic tools that want to test each preset independently.

func BuildSignedRelayEntry

func BuildSignedRelayEntry(nodeID, addr, countryCode string) (*dht.RelayEntry, error)

BuildSignedRelayEntry creates a signed dht.RelayEntry for this node. addr is the external UDP endpoint (ip:port) from ProbeExternalEndpoint. LoadOrGenNodeID must have been called first.

func BuildUploadResponse

func BuildUploadResponse(key, data []byte) ([]byte, error)

BuildUploadResponse encrypts an upload-ACK response for data, in the same padded format TunnelDialer expects back from the server.

func DefaultRelayChunkFetcher

func DefaultRelayChunkFetcher(d *Discoverer) func(hash string) ([]byte, error)

DefaultRelayChunkFetcher returns a MirrorManager relayFetch function that asks a random known control (from d's current control list) for a chunk over the relay API (/p/v1/content/chunk) — the fallback path used only when no P2P peer has the chunk.

func FetchMyIP

func FetchMyIP(apiURL string) (string, error)

FetchMyIP asks the control server what IP it sees for this connection. Uses a randomly chosen relay-API SNI so control routes the request to the relay API handler (not the TCP proxy to exit). apiURL must be the control's HTTPS base URL (e.g. "https://1.2.3.4:443").

func InitLogging

func InitLogging(dir string) error

InitLogging opens (or creates) today's log file in dir, redirects the package logger there, and prunes old log files. Call once from main before anything else.

func InitTunLogging

func InitTunLogging(dir string) error

InitTunLogging opens a separate rotating log file for TUN traffic. Call after InitLogging.

func IsLANAddress

func IsLANAddress(target string) bool

IsLANAddress reports whether target (host:port or bare host) is a private LAN address that should bypass the tunnel: RFC1918, link-local, or loopback.

func LoadOrGenNodeID

func LoadOrGenNodeID(appDataDir string) (string, error)

LoadOrGenNodeID returns the persistent node ID for this client. NodeID = hex-encoded Ed25519 public key (64 hex chars / 32 bytes).

The private key is stored encrypted (platform-specific) in appDataDir/nodeid.key. The public key is stored as plain hex in appDataDir/nodeid.

func NewDecoyTransport

func NewDecoyTransport(physIP string, controlFn func(string, string, syscall.RawConn) error) http.RoundTripper

newDecoyTransport returns a uTLS-backed http.RoundTripper whose TCP connections are bound to physIP (bypassing TUN routing). Unlike the tunnel transport, this one uses real TLS certificate verification because it connects to actual public servers. NewDecoyTransport is the exported variant for use on Android.

func NewDiscoveryClient

func NewDiscoveryClient() *http.Client

NewDiscoveryClient returns an http.Client suitable for talking to exit nodes that present self-signed TLS certificates. Use this when creating a Discoverer outside of an existing Authenticator context.

func NewRelayAPIH1Client

func NewRelayAPIH1Client() *http.Client

NewRelayAPIH1Client returns an *http.Client that uses uTLS (browser fingerprint + ChRelayAPI channel ID in Session ID) but HTTP/1.1 only — no h2. Use for control-node /p/v1/* endpoints that don't support HTTP/2. dialControl is applied so connections bypass the VPN TUN on Android.

func NewUTLSClientWithPreset

func NewUTLSClientWithPreset(preset utls.ClientHelloID) *http.Client

NewUTLSClientWithPreset returns an *http.Client whose TLS connections use the given uTLS browser preset. Used by diagnostic tools to test preset compatibility.

func OpenFrame

func OpenFrame(key, data []byte) ([]byte, error)

OpenFrame decrypts a [12B nonce][ciphertext+tag] blob sealed by SealFrame.

func ParseUploadFrame

func ParseUploadFrame(plain []byte) (connID string, seq uint32, target string, payload []byte, err error)

ParseUploadFrame parses a decrypted upload-frame plaintext: [1B FrameTypeUpload][16B conn_id][4B seq_be][2B target_len_be][target][payload]

func PresetName

func PresetName(p utls.ClientHelloID) string

PresetName returns a short human-readable name for a uTLS preset.

func ProbeControlE2E

func ProbeControlE2E(addr string, timeout time.Duration) (rtt time.Duration, ok bool)

ProbeControlE2E performs GET https://<addr>/p/v1/ping and returns the end-to-end RTT: the control's best measured exit latency reported in the response body. Returns ok=false when the control is unreachable or reports no alive exits (empty body). Uses the same uTLS transport as the tunnel so the probe is subject to the same DPI and dialControl constraints.

func ProbeControlUDP

func ProbeControlUDP(addr string, timeout time.Duration) (rtt time.Duration, ok bool)

ProbeControlUDP sends a single SNCU /p/v1/ping frame to addr over UDP and returns the round-trip time. ok=false when the probe times out or fails. Use instead of ProbeControlE2E when the control is in UDP-only mode (TCP probe failed but UDP is alive per ProbeDataPlane). addr is host or host:port; defaults to port 443 if no port given.

func Punch

func Punch(localIP, peerAddr string) (*net.UDPConn, error)

Punch performs UDP hole punching to peerAddr and returns a connected *net.UDPConn on success. The connection has no deadline set.

func PunchProtected

func PunchProtected(peerAddr string, dialControl func(string, string, syscall.RawConn) error) (*net.UDPConn, error)

PunchProtected is the Android variant: uses dialControl (VpnService.protect) to bypass the TUN instead of binding to a specific local IP.

func RandomReferer

func RandomReferer(rng *rand.Rand) string

RandomReferer returns a random referer from the pool (different each call).

func ReadManifestCacheControls

func ReadManifestCacheControls(cacheFile, pubkeyHex string) []string

ReadManifestCacheControls reads and verifies a cached manifest file and returns the list of control addresses it contains. Useful for augmenting bootstrap candidates before a Discoverer instance is available.

pubkeyHex is the arbiter's Ed25519 public key in hex; pass "" to skip signature verification (development only). Returns nil on any error (missing file, bad signature, etc.) — the caller should treat absence as non-fatal.

func ReadManifestCacheControlsAndRegions

func ReadManifestCacheControlsAndRegions(cacheFile, pubkeyHex string) ([]string, map[string]string)

ReadManifestCacheControlsAndRegions is like ReadManifestCacheControls but also returns the addr→country-code map from the cached manifest. The map is nil when regions are unavailable (first run, bad cache, etc.).

func SaveRelayList

func SaveRelayList(path string, relays []RelayEntry) error

SaveRelayList persists relays to path as JSON so they survive restarts.

func SealFrame

func SealFrame(key, plaintext []byte) ([]byte, error)

SealFrame encrypts plaintext with a random nonce. Wire format: [12B nonce][ChaCha20-Poly1305 ciphertext+tag].

func SessionKey

func SessionKey(token string) []byte

SessionKey derives the ChaCha20-Poly1305 key used to seal/open frames for the given session token (the value sent in the X-Session header).

func SetDialControl

func SetDialControl(fn func(network, address string, c syscall.RawConn) error)

SetDialControl installs a per-socket hook called before each outbound connection. Safe to call before any goroutine starts dialling.

func SetTunnelHealthy

func SetTunnelHealthy(healthy bool)

SetTunnelHealthy updates only the TunnelHealthy flag in the persisted state. Call with true when the tunnel pool is up and not recovering; false when entering any recovery path (data-fail, silent refresh, reconnect).

func SignNodePayload

func SignNodePayload(payload []byte) ([]byte, error)

SignNodePayload signs payload with the node's Ed25519 private key and returns the raw 64-byte signature. LoadOrGenNodeID must have been called first.

func TimezoneCC

func TimezoneCC() string

TimezoneCC returns the ISO 3166-1 alpha-2 country code derived from the device's current local timezone. Returns "" for ambiguous or unknown zones.

func TouchAlive

func TouchAlive()

TouchAlive updates the LastAlive timestamp in the persisted watchdog state. Call periodically from the main process so the watchdog can detect hangs.

func TouchLastWake

func TouchLastWake()

TouchLastWake updates the LastWake timestamp so the watchdog can suppress connectivity probes during the network-recovery window after system resume.

func VerifySignedPayload

func VerifySignedPayload(payload []byte, pubkeyHex, sigB64 string) error

VerifySignedPayload verifies an Ed25519 signature over payload.

pubkeyHex is the signer's public key, hex-encoded. sigB64 is the signature, base64url-encoded (no padding). This is the primitive used throughout the package (discovery, bypass, mirror) to authenticate manifest data signed by a control-plane server — callers are responsible for building the exact canonical payload their own signing scheme uses.

func WatchdogStatePath

func WatchdogStatePath() string

WatchdogStatePath returns the path to the watchdog state file.

func WrapWithTorrentFilter

func WrapWithTorrentFilter(ln net.Listener) net.Listener

WrapWithTorrentFilter is a no-op on non-Windows platforms.

func WriteWatchdogState

func WriteWatchdogState(s WatchdogState) error

WriteWatchdogState persists the current watchdog state to disk.

Types

type Authenticator

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

Authenticator handles login and session-token management.

func NewAuthenticator

func NewAuthenticator(serverURL, apiKey, username, password string) *Authenticator

NewAuthenticator returns an Authenticator ready to login.

func NewAuthenticatorWithToken

func NewAuthenticatorWithToken(serverURL, apiKey, token string) *Authenticator

NewAuthenticatorWithToken creates an Authenticator that already holds a session token — no Login() call required. The token was obtained externally (e.g. via ProxyValidate on behalf of a SOCKS5 user in BlackBadger mode).

func (*Authenticator) AdoptToken

func (a *Authenticator) AdoptToken(tok string)

AdoptToken pre-fills the session token without calling Login. Used when migrating an existing session to a new control node — the arbiter token is valid on any control, so re-authentication is unnecessary.

func (*Authenticator) ClearDialFunc

func (a *Authenticator) ClearDialFunc()

ClearDialFunc resets auth connections to direct TCP (removes any transport override). Must be called when switching away from an external dial function.

func (*Authenticator) DrainNotifications

func (a *Authenticator) DrainNotifications() []Notification

DrainNotifications returns and clears any per-user notifications received in the most recent key-auth response. Returns nil if none are pending.

func (*Authenticator) Login

func (a *Authenticator) Login() error

Login authenticates and stores the session token. Key auth (V2) and password auth are launched in parallel; whichever succeeds first wins. Both must fail for Login to return an error.

func (*Authenticator) LoginViaUDP

func (a *Authenticator) LoginViaUDP(relay *UDPRelayConn) error

LoginViaUDP authenticates using a hole-punched UDP relay connection. The relay transparently forwards the auth request to its control via TCP. Use when direct TCP to controls is blocked but UDP relay is reachable.

func (*Authenticator) ProxyValidate

func (a *Authenticator) ProxyValidate(username, password string) (string, error)

ProxyValidate sends a proxy credential validation request to the arbiter (via the control node) on behalf of a SOCKS5 user. It uses this authenticator's own session token to authenticate the call and returns the session token issued for the validated user.

Used by BlackBadger: the BB instance authenticates the call with its own token; the returned token belongs to the end-user and is used in X-Session for all tunnel connections on their behalf.

func (*Authenticator) SetDeviceInfo

func (a *Authenticator) SetDeviceInfo(keyID, deviceID, deviceName string)

SetDeviceInfo stores the key_id and device identity so they are included in the next login request to the arbiter for device-binding enforcement.

func (*Authenticator) SetDialFunc

func (a *Authenticator) SetDialFunc(fn func(ctx context.Context, addr string) (net.Conn, error))

SetDialFunc routes the authenticator's HTTP client through fn instead of direct TCP dialing.

func (*Authenticator) SetHTTPClientForPreset

func (a *Authenticator) SetHTTPClientForPreset(preset utls.ClientHelloID)

SetHTTPClientForPreset replaces the authenticator's HTTP client with one that uses the given uTLS browser preset. Used by diagnostic tools to test each preset independently against the same server.

func (*Authenticator) SetKeyAuthParams

func (a *Authenticator) SetKeyAuthParams(p KeyAuthParams)

SetKeyAuthParams configures key-based authentication from p. If p.AuthSig is empty, password auth is used as the sole mechanism.

func (*Authenticator) Token

func (a *Authenticator) Token() string

Token returns the current session token.

type BypassManager

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

BypassManager fetches, verifies and caches the CIDR bypass set for the client's country. It calls the exit node's /api/bypass/cidr endpoint, passing the client's public IP so the exit can detect the country and return the appropriate arbiter-signed CIDR list.

ShouldBypass checks each outbound address; BypassDialer returns a dialer bound to the original NIC so packets route around the TUN.

func NewBypassManager

func NewBypassManager(exitURLs []string, pubkeyHex, cacheFile string) (*BypassManager, error)

NewBypassManager creates a BypassManager that will fetch CIDR data from the exit node at exitURL. pubkeyHex is the arbiter Ed25519 pubkey hex. Pass "" to skip signature verification (dev mode).

func (*BypassManager) BypassDialer

func (m *BypassManager) BypassDialer() *net.Dialer

BypassDialer returns a net.Dialer whose LocalAddr is set to the original NIC IP so that connections bypass the TUN routing table.

func (*BypassManager) CIDRStatus

func (m *BypassManager) CIDRStatus() string

CIDRStatus returns the current CIDR load state: "none", "cached", or "fresh". "cached" means CIDRs were loaded from the on-disk cache this session but the live fetch has not yet succeeded. "fresh" means a live fetch succeeded.

func (*BypassManager) ContainsIP

func (m *BypassManager) ContainsIP(ip net.IP) bool

ContainsIP reports whether ip falls within the client's home-country CIDRs. Unlike ShouldBypass, this ignores the enabled flag — it is used solely for determining whether a remote address (e.g. a control node) is in the same country as the client, regardless of whether bypass routing is active.

func (*BypassManager) Country

func (m *BypassManager) Country() string

Country returns the ISO country code detected for the client's IP (e.g. "RU"). Returns "" until the first successful CIDR fetch.

func (*BypassManager) DialUDP

func (m *BypassManager) DialUDP() (*net.UDPConn, error)

DialUDP opens an unconnected UDP socket bound to the original NIC IP so that datagrams bypass TUN routing. The caller is responsible for closing.

func (*BypassManager) Enabled

func (m *BypassManager) Enabled() bool

Enabled reports whether bypass is currently on.

func (*BypassManager) HasLocalIP

func (m *BypassManager) HasLocalIP() bool

HasLocalIP reports whether a local NIC IP has been set (Windows only). On Android, localIP is never set; UDP traffic goes through the tunnel.

func (*BypassManager) RecordBypassFailure

func (m *BypassManager) RecordBypassFailure(addr string)

RecordBypassFailure marks addr as tunnel-preferred for 30 minutes. Must only be called when bypass dial failed AND tunnel connection succeeded — not on genuine host unreachability (both paths fail).

func (*BypassManager) SetEnabled

func (m *BypassManager) SetEnabled(v bool)

SetEnabled toggles bypass on/off at runtime.

func (*BypassManager) SetLocalIP

func (m *BypassManager) SetLocalIP(ip string)

SetLocalIP records the original NIC IP used as source for bypass connections. Call this after RouteManager.Apply() (before Start).

func (*BypassManager) SetMyIP

func (m *BypassManager) SetMyIP(ip string)

SetMyIP records the client's public IP address used for country detection. Call this after FetchMyIP returns successfully.

func (*BypassManager) SetNodes

func (m *BypassManager) SetNodes(urls []string)

SetNodes replaces the list of control node URLs used for CIDR and country fetches. Called by the Discoverer's onChange callback so BypassManager always uses the current manifest node list instead of the bootstrap URL.

func (*BypassManager) SetToken

func (m *BypassManager) SetToken(token string)

SetToken records the current session token used to authenticate against the exit. Call this before Start, and again whenever the token is refreshed.

func (*BypassManager) ShouldBypass

func (m *BypassManager) ShouldBypass(addr string) bool

ShouldBypass reports whether addr (host:port or bare host) should bypass the tunnel. Returns false if bypass is disabled, CIDRs are not loaded, or the address was previously recorded as a bypass failure.

func (*BypassManager) Start

func (m *BypassManager) Start()

Start loads cached CIDRs and launches the refresh loop: every 30 minutes normally, but every 2 minutes after a failed fetch until one succeeds, so a transient outage doesn't leave bypass disabled for up to half an hour.

func (*BypassManager) Stop

func (m *BypassManager) Stop()

Stop shuts down the background refresh goroutine.

type CIDRSet

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

CIDRSet is an immutable set of IPv4 and IPv6 networks optimised for Contains queries via binary search — O(log n) per lookup.

Assumes non-overlapping ranges, which is guaranteed by standard RIR country allocation files (each address block belongs to exactly one country).

func ParseCIDRs

func ParseCIDRs(cidrs []string) *CIDRSet

ParseCIDRs builds a CIDRSet from a slice of CIDR strings. Invalid entries are silently skipped. Both IPv4 and IPv6 prefixes are accepted.

func (*CIDRSet) Contains

func (s *CIDRSet) Contains(ip net.IP) bool

Contains reports whether ip is covered by any network in the set.

func (*CIDRSet) Len

func (s *CIDRSet) Len() int

Len returns the total number of networks in the set (IPv4 + IPv6).

type DHTContact

type DHTContact = dht.Contact

Type aliases — core.DHTID and dht.ID are the same type.

type DHTID

type DHTID = dht.ID

Type aliases — core.DHTID and dht.ID are the same type.

func ParseDHTID

func ParseDHTID(s string) (DHTID, error)

ParseDHTID decodes a 64-char hex string into a DHTID.

type DHTNode

type DHTNode = dht.Node

Type aliases — core.DHTID and dht.ID are the same type.

func NewDHTNode

func NewDHTNode(id DHTID, conn *net.UDPConn, peersPath string) *DHTNode

NewDHTNode creates a DHT node wired to the win-client logger and DPAPI encryption.

type DHTRelayEntry

type DHTRelayEntry = dht.RelayEntry

Type aliases — core.DHTID and dht.ID are the same type.

type DecoyManager

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

DecoyManager sends background HTTPS GET requests to blend the client's TLS traffic pattern with normal browser activity:

  • Tunnel busy (activity within 500 ms): silent
  • Lightly loaded: 1–3 req/min with jitter, targeting CDN endpoints
  • Long idle (> 10 min): dormant

Outgoing connections are bound to physIP (the physical NIC address) so they bypass the TUN default route and go directly to the target server. Decoy traffic therefore does NOT consume tunnel bandwidth.

func NewDecoyManager

func NewDecoyManager(physIP string) *DecoyManager

NewDecoyManager creates a DecoyManager. physIP is the physical NIC source address used to bypass TUN routing; pass "" to use default routing (tests).

func NewDecoyManagerWithTransport

func NewDecoyManagerWithTransport(transport http.RoundTripper) *DecoyManager

NewDecoyManagerWithTransport creates a DecoyManager using a caller-supplied transport. Use on platforms where TCP bypass requires a control function rather than LocalAddr binding (e.g. Android VpnService.protect).

func (*DecoyManager) MarkActivity

func (d *DecoyManager) MarkActivity()

MarkActivity records that the tunnel just transmitted data. Call this from TunnelDialer.doPost() on every request.

func (*DecoyManager) Start

func (d *DecoyManager) Start()

Start launches the background decoy loop. Call once after creation.

func (*DecoyManager) Stop

func (d *DecoyManager) Stop()

Stop shuts down the decoy loop.

type DialerPool

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

DialerPool manages a set of TunnelDialers with RTT-weighted selection.

Pick() selects from all non-draining dialers with probability proportional to 1/RTT, so faster controls receive more connections automatically. Dialers without sufficient RTT data yet receive a default weight equivalent to defaultPickRTT so new dialers participate until real measurements arrive. Draining dialers finish in-flight connections then return to standby.

func NewDialerPool

func NewDialerPool(dialers []*TunnelDialer) *DialerPool

NewDialerPool creates a pool from the given dialers (all start as standby).

func (*DialerPool) Add

func (p *DialerPool) Add(td *TunnelDialer)

Add appends td as a standby dialer eligible for Pick().

func (*DialerPool) DrainEvictions

func (p *DialerPool) DrainEvictions() int

DrainEvictions returns and resets the eviction counter.

func (*DialerPool) Evict

func (p *DialerPool) Evict(td *TunnelDialer) int

Evict removes td from the pool.

func (*DialerPool) Get

func (p *DialerPool) Get(ctrlURL string) *TunnelDialer

Get returns the non-draining dialer for ctrlURL, or nil if not present.

func (*DialerPool) Has

func (p *DialerPool) Has(ctrlURL string) bool

Has reports whether the pool already contains a non-draining dialer for ctrlURL.

func (*DialerPool) LastDataTime

func (p *DialerPool) LastDataTime() time.Time

LastDataTime returns the most recent successful POST time across all dialers.

func (*DialerPool) NeedsRefill

func (p *DialerPool) NeedsRefill(target int) bool

NeedsRefill reports whether the pool has fewer than target non-draining dialers.

func (*DialerPool) Pick

func (p *DialerPool) Pick() *TunnelDialer

Pick selects a dialer with probability proportional to 1/RTT. Returns nil only when every slot is draining or the pool is empty.

func (*DialerPool) PickForUID

func (p *DialerPool) PickForUID(_ int) *TunnelDialer

PickForUID returns a dialer (ignores UID — exit stickiness handled by control).

func (*DialerPool) SetActivityHook

func (p *DialerPool) SetActivityHook(fn func())

SetActivityHook registers fn to be called on every tunnel POST by any dialer.

func (*DialerPool) Size

func (p *DialerPool) Size() int

Size returns the number of non-draining dialers.

func (*DialerPool) StartManagement

func (p *DialerPool) StartManagement(interval time.Duration, stopCh <-chan struct{})

StartManagement launches the drain-completion background loop.

func (*DialerPool) Swap

func (p *DialerPool) Swap(dialers []*TunnelDialer)

Swap replaces all dialers wholesale.

type Discoverer

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

Discoverer fetches the signed control-node manifest from the control's relay API (channel 0x01, /p/v1/manifest), verifies the arbiter's Ed25519 signature, and maintains a refreshed list of controls. It persists the manifest to disk so the updated list survives restarts.

func NewDiscoverer

func NewDiscoverer(serverURL, pubkeyHex string, client *http.Client, cacheFile string, onChange func([]string)) (*Discoverer, error)

NewDiscoverer creates a Discoverer for the given exit server URL.

pubkeyHex is the arbiter's Ed25519 public key in hex. Pass "" to skip signature verification (development only).

client should be the same http.Client used for tunnel requests (InsecureSkipVerify is already set there for self-signed exit certs).

cacheFile is the full path where the raw manifest JSON is persisted; pass "" to disable on-disk caching.

onChange is called whenever the control list changes; may be nil.

func (*Discoverer) AltUDPPorts

func (d *Discoverer) AltUDPPorts(ctrlAddr string) []int

AltUDPPorts returns a copy of the dynamic alternate-transport port list for the given control address, or nil if none have been received from the control-plane yet.

func (*Discoverer) Controls

func (d *Discoverer) Controls() []string

Controls returns a snapshot of the current control node addresses.

func (*Discoverer) InjectRaw

func (d *Discoverer) InjectRaw(data []byte) error

InjectRaw accepts a raw signed manifest from an external source (e.g. DHT gossip). It verifies the signature, applies the control list, and persists it — identical to a local fetch but without the HTTP round-trip. Returns an error if verification fails; the caller should not apply or re-gossip invalid data.

func (*Discoverer) LoadCached

func (d *Discoverer) LoadCached() error

LoadCached reads a previously-persisted manifest from disk and populates the in-memory control list. Returns a non-nil error if the cache is missing or the manifest fails to parse/verify — the caller should treat this as a non-fatal condition (the live fetch will fill the list shortly).

func (*Discoverer) ManifestStatus

func (d *Discoverer) ManifestStatus() string

ManifestStatus returns the current manifest load state: "none", "cached", or "fresh".

func (*Discoverer) Notifications

func (d *Discoverer) Notifications() []Notification

Notifications returns a snapshot of the most-recently-received notifications.

func (*Discoverer) ProbeManifest

func (d *Discoverer) ProbeManifest(timeout time.Duration) (nodes int, err error)

ProbeManifest fetches /p/v1/manifest once and returns (nodeCount, error). Intended for a manifest-probing diagnostic tool; not used in normal client operation.

func (*Discoverer) Regions

func (d *Discoverer) Regions() map[string]string

Regions returns a snapshot of the current addr → ISO region map. The map is advisory (not covered by the arbiter's signature).

func (*Discoverer) SNIFor

func (d *Discoverer) SNIFor(addr string) string

SNIFor returns a randomly chosen SNI hostname for the given control addr (host:port). Returns "" if no SNI list is configured for that addr.

func (*Discoverer) SetFetchCallback

func (d *Discoverer) SetFetchCallback(fn func(raw []byte, ts int64))

SetFetchCallback registers a function called after each successful manifest fetch. The callback receives the raw signed manifest JSON and the manifest ts — use this to feed the manifest into the DHT gossip layer.

func (*Discoverer) SetNotificationCallback

func (d *Discoverer) SetNotificationCallback(fn func([]Notification))

SetNotificationCallback registers a function called whenever the manifest delivers one or more new broadcast notifications. The callback receives only the advisory slice as-is; deduplication/TTL are the caller's job.

func (*Discoverer) Start

func (d *Discoverer) Start(interval time.Duration)

Start performs an immediate manifest fetch and then refreshes on interval. Errors are logged but do not stop the loop.

func (*Discoverer) Stop

func (d *Discoverer) Stop()

Stop signals the background polling goroutine started by Start to exit. Safe to call multiple times; no-op if Start was never called.

func (*Discoverer) UseAsSNIProvider

func (d *Discoverer) UseAsSNIProvider()

UseAsSNIProvider registers this discoverer as the process-wide SNI source for uTLS connections to control nodes. Call once after creating the discoverer.

type ExternalEndpoint

type ExternalEndpoint struct {
	IP   net.IP
	Port int
}

ExternalEndpoint holds the observed external UDP address of this client.

func ProbeExternalEndpoint

func ProbeExternalEndpoint(controlAddr, localIP string) (ExternalEndpoint, error)

ProbeExternalEndpoint sends a reflection request to controlAddr (host:port) and returns the observed external UDP endpoint.

localIP should be the physical NIC address (from bypass manager) so the datagram leaves on the real interface, not the TUN. Pass "" to let the OS pick the source address (works in non-TUN contexts such as tests).

func ProbeExternalEndpointProtected

func ProbeExternalEndpointProtected(controlAddr string, dialControl func(string, string, syscall.RawConn) error) (ExternalEndpoint, error)

ProbeExternalEndpointProtected is the Android variant: uses dialControl (VpnService.protect) instead of LocalAddr binding to bypass the TUN.

func (ExternalEndpoint) String

func (e ExternalEndpoint) String() string

type KeyAuthParams

type KeyAuthParams struct {
	Username      string
	Servers       []string
	ControlNodes  []string
	ArbiterPubkey string
	NodeID        string
	APIKey        string
	ClientID      string
	KeyID         string
	AuthSig       string
}

KeyAuthParams carries the fields needed for key-based authentication. Callers holding a licensed credential blob (of whatever shape their own service issues) should unpack it into this struct rather than the authenticator depending on any particular credential format.

type LogUploader

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

LogUploader periodically gzip-compresses LogRing and POSTs it to the control's /p/v1/log/upload endpoint via the relay API channel.

func NewLogUploader

func NewLogUploader(srvURL, nodeID string, auth *Authenticator) *LogUploader

NewLogUploader creates a LogUploader. Call Start to begin periodic uploads.

func (*LogUploader) Start

func (lu *LogUploader) Start()

Start launches the background upload goroutine. Uploads once immediately, then every 5 minutes. Non-blocking.

func (*LogUploader) Stop

func (lu *LogUploader) Stop()

Stop shuts down the upload goroutine.

func (*LogUploader) UploadOnce

func (lu *LogUploader) UploadOnce()

UploadOnce performs a single log upload synchronously. Useful for testing.

type MirrorConn

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

MirrorConn is a chunk-transfer channel over a hole-punched UDP connection. Create with NewMirrorConn; call Close when done.

func NewMirrorConn

func NewMirrorConn(conn *net.UDPConn, getChunk func(hash string) ([]byte, bool)) *MirrorConn

NewMirrorConn wraps conn as a bidirectional chunk-transfer transport.

func (*MirrorConn) Close

func (c *MirrorConn) Close()

Close tears down the connection.

func (*MirrorConn) RequestChunk

func (c *MirrorConn) RequestChunk(hash string) ([]byte, bool, error)

RequestChunk fetches one chunk (hex SHA-256 hash) from the peer this connection is punched to.

Returns (data, true, nil) on a hit, (nil, false, nil) if the peer explicitly reported it doesn't have the chunk (caller should try a different peer, not retry this one), or a non-nil error if the peer never responded at all (caller should treat the peer as unreachable).

func (*MirrorConn) StopCh

func (c *MirrorConn) StopCh() <-chan struct{}

StopCh returns a channel that is closed when the connection is shut down.

type MirrorManager

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

MirrorManager receives the content-manifest via DHT gossip, verifies it, downloads missing/changed files, writes them into dataDir, and deletes files no longer listed.

func NewMirrorManager

func NewMirrorManager(
	pubkeyHex, dataDir string,
	punchFn func(peerAddr string) (*net.UDPConn, error),
	completePeersFn func(ts int64) []string,
	setContentFn func(raw []byte, ts int64),
	setCompleteFn func(ts int64, complete bool),
	relayFetch func(hash string) ([]byte, error),
) (*MirrorManager, error)

NewMirrorManager creates a MirrorManager and ensures dataDir exists.

pubkeyHex is the arbiter's Ed25519 public key in hex; pass "" to skip signature verification (development only).

func (*MirrorManager) Close

func (m *MirrorManager) Close()

Close tears down all pooled peer connections. Safe to call at shutdown.

func (*MirrorManager) LoadCached

func (m *MirrorManager) LoadCached()

LoadCached loads the last successfully-applied manifest's timestamp from disk so a restarted process doesn't re-announce completeness for a version it hasn't re-verified this run (OnContentManifest still requires a newer ts to accept a fresh gossip, so this just prevents accidentally treating an old ts as "not yet seen").

func (*MirrorManager) OnContentManifest

func (m *MirrorManager) OnContentManifest(raw []byte)

OnContentManifest is the callback to register with dht.Node.SetContentHandler. It verifies the manifest, immediately re-gossips it (so this node keeps the epidemic spread going even before its own download finishes — the same reason a torrent peer announces metadata before it finishes seeding), then downloads/deletes files in the background.

func (*MirrorManager) ServeChunk

func (m *MirrorManager) ServeChunk(hash string) ([]byte, bool)

ServeChunk returns the bytes for hash if this node currently has it (i.e. is fully synced to the manifest version that included it). Wire this into NewMirrorConn's getChunk parameter for connections accepted via the platform's mirror-punch handler (SetMirrorPunchHandler) — the serving side, symmetric to the fetch-only connections peerConn creates.

type Notification

type Notification struct {
	ID        string `json:"id"`
	Message   string `json:"message"`
	CreatedAt int64  `json:"created_at"`
}

Notification is an admin broadcast message delivered in the manifest. Advisory only — not covered by the arbiter's Ed25519 signature.

type ParaExitClient

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

ParaExitClient connects this win-client to every regional exit node as a para-exit: a yamux reverse-tunnel through which the exit can route whitelisted traffic using this client's residential IP.

The client never knows which traffic it is carrying — it just pipes TCP connections to whatever target address the exit requests. All whitelist enforcement is done at the exit.

Lifecycle:

pc := NewParaExitClient(apiURL, localIP)
pc.Start()   // fetches exit list and begins connecting
pc.Stop()    // tears down all sessions

func NewParaExitClient

func NewParaExitClient(controlAPIURL, localIP string) (*ParaExitClient, error)

NewParaExitClient generates a fresh Ed25519 identity and returns a client that will connect to regional exits obtained from controlAPIURL. localIP is the physical NIC address (bypass TUN for direct target dials).

func (*ParaExitClient) Start

func (c *ParaExitClient) Start()

Start fetches the exit list and begins connecting to all regional exits.

func (*ParaExitClient) Stop

func (c *ParaExitClient) Stop()

Stop tears down all para-exit sessions.

type RelayEntry

type RelayEntry struct {
	NodeID      string `json:"id"`
	Addr        string `json:"address"`
	CountryCode string `json:"country,omitempty"`
	ExpiresAt   int64  `json:"expires_at"` // unix timestamp; 0 = unknown
}

RelayEntry is a single entry from the relay list (format version 2).

func FetchRelayList

func FetchRelayList(apiURL string) ([]RelayEntry, error)

FetchRelayList fetches the current relay list from the control's relay API. Expects format version 2: {"version":2,"relays":[{"id","address","country","expires_at"}]}. Old-format responses (version<2 or missing version) are rejected so stale clients that don't understand TTL/country filtering cannot accidentally propagate zombies.

func LoadRelayList

func LoadRelayList(path string) ([]RelayEntry, error)

LoadRelayList reads a relay list saved by SaveRelayList. Returns nil, nil when the file does not exist.

func RelaysByCountry

func RelaysByCountry(relays []RelayEntry, preferCC string) []RelayEntry

RelaysByCountry returns a copy of relays with entries matching preferCC sorted first. If preferCC is empty, the original order is preserved.

type Router

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

Router selects the best path through available relay nodes to the control.

Route structures (in priority order):

A:        Client → Relay → Control → Exit
B:        Client → Relay → Relay → Control → Exit          (future: route vector)
C:        Client → Relay → Relay → Relay → Control → Exit  (future: route vector)
Fallback: Client → Control → Exit

Multiple control nodes are supported. BuildPaths generates candidate paths across all alive controls; scoring naturally prefers lower-latency controls. Advance() cycles through paths, which may switch to a different control.

Control selection policy (see memory/project_control_routing_policy.md):

  • In-country hard filter: if any in-country control is alive, out-of-country controls are excluded entirely (not just de-prioritised).
  • RTT threshold: only controls with score ≤ best×1.5 qualify.
  • Top-5 cap.
  • RTT is measured via a real HTTP data-plane probe, not a TCP SYN/ACK, so DPI body-stripping is detected at probe time.

When myCountry is set, same-region relays are preferred. If none are alive the router falls back to all alive relays (connectivity beats policy).

func NewRouter

func NewRouter() *Router

NewRouter creates an idle router. Call SetControl + UpdateRelays + MeasureRTTs + BuildPaths before using Primary.

func (*Router) Advance

func (r *Router) Advance() bool

Advance marks the current path as failed and moves to the next candidate. Returns true if a new path is available, false if all paths are exhausted (index wraps back to 0 so the next call to Primary returns the top path).

func (*Router) AllControlAddrs

func (r *Router) AllControlAddrs() []string

AllControlAddrs returns every known control address regardless of liveness. TCP-based liveness (alive/LastSeen) is meaningless when direct TCP to controls is blocked and an external dial function is in use instead — in that case ProbeDataPlane never runs and LastSeen goes stale after 30s. Filtering through QualifyingControlAddrs (which only returns addrs present in r.paths, itself built from r.alive()) creates a one-way death spiral: a control that drops out from staleness is never retried, so it never gets marked alive again, so it never returns. Pool building over an external transport must use this instead — that transport's own auth success is the only liveness signal that matters there.

func (*Router) BuildPaths

func (r *Router) BuildPaths()

BuildPaths generates, scores, and stores the top-5 candidate paths across all alive control nodes. Call after MeasureRTTs. The result is accessible via Primary / Advance.

func (*Router) CloseAllUDPPeers

func (r *Router) CloseAllUDPPeers()

CloseAllUDPPeers closes and removes all registered UDP relay connections.

func (*Router) ControlRTT

func (r *Router) ControlRTT(addr string) time.Duration

ControlRTT returns the effective RTT for addr including any flap penalty and a large UDP-only penalty, or 0 if the address is unknown. Used to sort pool dialers by effective latency so dialers[0] is always the best available control.

func (*Router) ControlTransport

func (r *Router) ControlTransport(addr string) controlTransport

ControlTransport returns the transport protocol detected for addr by the last ProbeDataPlane call. Returns transportTCP for unknown addresses.

func (*Router) ControlTransportName

func (r *Router) ControlTransportName(addr string) string

ControlTransportName returns a human-readable transport name for addr ("tcp" or "udp").

func (*Router) HasUDPPeer

func (r *Router) HasUDPPeer(nodeID string) bool

HasUDPPeer reports whether a live UDP relay connection exists for the given node ID.

func (*Router) MarkControlAlive

func (r *Router) MarkControlAlive(addr string)

MarkControlAlive refreshes the liveness timestamp for the control at addr. Callers using an external dial function (SetDialFunc) may skip direct TCP probing (ProbeDataPlane) entirely, treating their own transport's auth success as the real liveness signal instead — so without this, LastSeen is stamped once at bootstrap and goes stale after 30s, making alive() (and therefore BuildPaths/QualifyingControlAddrs) falsely report every control as unreachable on the very next rebuild.

func (*Router) MarkControlDataDead

func (r *Router) MarkControlDataDead(addr string, until time.Time)

MarkControlDataDead temporarily excludes a control from path building even if it is TCP-reachable. Use when the data plane is blocked (e.g. DPI body stripping) so BuildPaths routes around it until the deadline.

func (*Router) MarkRelayAlive

func (r *Router) MarkRelayAlive(id string)

MarkRelayAlive marks the relay identified by id (NodeID or Addr) as alive with the current timestamp. Call this when a UDP hole-punch connection to the relay is successfully established.

func (*Router) MarkUDPDataFailed

func (r *Router) MarkUDPDataFailed(addr string)

MarkUDPDataFailed forces addr to TCP-only for 5 minutes. ProbeDataPlane will skip the UDP fallback probe during this window so a broken UDP channel is not re-created immediately. After the TTL, probing resumes: if UDP has recovered the control reverts to transportUDP; if still broken, the TTL is extended.

func (*Router) MeasureRTTs

func (r *Router) MeasureRTTs(timeout time.Duration)

MeasureRTTs probes all relays and all control nodes concurrently via TCP dial. Nodes that fail to connect within timeout are marked !IsAlive. Deprecated: use ProbeDataPlane for production use; MeasureRTTs does not detect DPI body-stripping because it only checks TCP reachability.

func (*Router) MergeDHTRelays

func (r *Router) MergeDHTRelays(entries []DHTRelayEntry)

MergeDHTRelays adds relay entries discovered via the DHT that are not already known from the control API. Existing relay RTT measurements are preserved. New entries are inserted with IsAlive=true; they will be probed on the next MeasureRTTs call.

func (*Router) NewControlDialer

func (r *Router) NewControlDialer(addr string, auth *Authenticator) (*TunnelDialer, error)

NewControlDialer creates the appropriate TunnelDialer for a qualifying control address. When ProbeDataPlane detected that addr is only reachable via UDP, the returned dialer sends all tunnel traffic over a direct UDP connection to the control. Otherwise a standard TCP-backed TunnelDialer is returned.

func (*Router) Paths

func (r *Router) Paths() []RouterPath

Paths returns a snapshot of the current candidate paths (post-BuildPaths). Used by DialerPool to determine which control addresses qualify.

func (*Router) PickRandom

func (r *Router) PickRandom() *RouterPath

PickRandom returns a random path from the current top-N candidates. Unlike Primary, it does not advance pathIdx — each call picks independently. Use this to distribute concurrent SOCKS5 connections across the qualifying pool.

func (*Router) Primary

func (r *Router) Primary() *RouterPath

Primary returns the current top-ranked path, or nil if none.

func (*Router) PrimaryIsBetter

func (r *Router) PrimaryIsBetter(currentAddr string, factor float64) (bool, *RouterPath)

PrimaryIsBetter reports whether switching to the primary path's control is warranted. It returns (true, primary) when:

  • the primary control differs from currentAddr, AND
  • the primary's score is at least `factor` times lower than the best score of the current control among the candidate paths (e.g. factor=1.5 means the current control must be ≥50% slower to trigger a switch).

If the current control is absent from all paths (dead), any alive primary is preferable and the function returns (true, primary) immediately. Returns (false, nil) when staying on the current control is correct.

func (*Router) ProbeDataPlane

func (r *Router) ProbeDataPlane(timeout time.Duration)

ProbeDataPlane probes the data plane health of control nodes:

  • Controls: HTTP GET /p/v1/ping via the uTLS ChRelayAPI channel (H1). A non-empty response body confirms the data plane is intact — a TCP-only probe would pass even when DPI strips HTTP bodies.
  • Relays are NOT probed via TCP (they are NAT-behind client nodes, not servers). Relay liveness is determined by RegisterUDPPeer / MarkRelayAlive only.

Nodes that fail are marked !IsAlive; successful probes update RTT. Call this instead of MeasureRTTs whenever reliable data-plane detection matters.

func (*Router) QualifyingControlAddrs

func (r *Router) QualifyingControlAddrs() []string

QualifyingControlAddrs returns the unique control addresses present in the current candidate paths (post-BuildPaths). The DialerPool authenticates to each of these and distributes connections randomly across them.

func (*Router) RecordControlFlap

func (r *Router) RecordControlFlap(addr string)

RecordControlFlap records one stream eviction for addr. Called from the dialer's first-fail hook so the router deprioritises controls that are under active DPI interference within the rolling flapWindow.

func (*Router) RegisterUDPPeer

func (r *Router) RegisterUDPPeer(key string, conn *UDPRelayConn)

RegisterUDPPeer registers a live UDP relay connection to a peer identified by nodeID (or addr when nodeID is unknown). The router gives this peer a score bonus so it is preferred when building paths.

func (*Router) RemoveUDPPeer

func (r *Router) RemoveUDPPeer(key string)

RemoveUDPPeer removes and closes the UDP relay connection for key.

func (*Router) Reset

func (r *Router) Reset()

Reset returns the path index to 0 (top-ranked path).

func (*Router) SetControl

func (r *Router) SetControl(addr string)

SetControl sets a single control node. Compatibility shim; prefer SetControls.

func (*Router) SetControls

func (r *Router) SetControls(addrs []string)

SetControls replaces the control node list. The first address is the preferred control; additional addresses are fallbacks. Call MeasureRTTs + BuildPaths after.

func (*Router) SetControlsWithRegions

func (r *Router) SetControlsWithRegions(addrs []string, regions map[string]string)

SetControlsWithRegions sets the control list and annotates each address with its ISO country code from the regions map (addr → cc). Use this instead of SetControls whenever region data is available (e.g. from the discoverer manifest on Windows or from bypass CIDR classification on Android).

func (*Router) SetMyCountry

func (r *Router) SetMyCountry(cc string)

SetMyCountry sets the client's ISO country code (e.g. "RU"). BuildPaths will only consider relays with a matching CountryCode. Pass "" to disable regional filtering (consider all relays).

func (*Router) SetSelfNodeID

func (r *Router) SetSelfNodeID(id string)

SetSelfNodeID tells the router its own DHT node ID so it can exclude itself from relay selection in MergeDHTRelays.

func (*Router) UnreachableControls

func (r *Router) UnreachableControls() []string

UnreachableControls returns control addresses that are known but currently not alive — i.e. candidates for relay-assisted access.

func (*Router) UpdateControlRTT

func (r *Router) UpdateControlRTT(addr string, rtt time.Duration)

UpdateControlRTT overwrites the stored RTT for addr with the given value. Used by buildPoolDialers to feed real e2e latency into path scoring after a ProbeControlE2E call, replacing the TCP-only RTT from ProbeDataPlane.

func (*Router) UpdateRelays

func (r *Router) UpdateRelays(relays []RelayEntry)

UpdateRelays replaces the relay list. Existing RTT measurements are discarded; call MeasureRTTs afterwards.

func (*Router) UpdateTrafficRTT

func (r *Router) UpdateTrafficRTT(addr string, rtt time.Duration)

UpdateTrafficRTT records a passive round-trip observation for the node at addr. addr is matched after normalisation (scheme + path stripped, :443 appended if no port is present). Silently ignored if addr does not match any known node.

type RouterPath

type RouterPath struct {
	// Relays is the ordered list of relay hops (0–3 nodes).
	// Currently only len 0 (direct) and len 1 (single relay) are executed;
	// multi-hop entries are generated for scoring but require route-vector
	// support before they can be used.
	Relays      []*RouterPathNode
	ControlAddr string
	Score       float64       // lower is better (ms-equivalent)
	UDPRelay    *UDPRelayConn // non-nil if first relay hop has a live UDP conn (M4.5)
}

RouterPath is a scored candidate path returned by BuildPaths.

func (*RouterPath) IsDirect

func (p *RouterPath) IsDirect() bool

type RouterPathNode

type RouterPathNode struct {
	ID   string
	Addr string
}

RouterPathNode is a relay node reference returned in RouterPath.

type SOCKS5Server

type SOCKS5Server struct {
	DisableUDP bool // if true, UDP ASSOCIATE returns command-not-supported
	// BlockQUIC: when true, datagrams to UDP:443 are silently dropped so that
	// QUIC/HTTP3 apps fall back to TLS/TCP. Enabled automatically for RU/CN regions
	// where QUIC-over-TCP-tunnel causes head-of-line blocking and poor media quality.
	BlockQUIC bool
	// AltDNSRouting: when true, UDP ASSOCIATE sessions send DNS queries via the
	// protected bypass socket directly (bypassing the configured relay) so
	// that browsers can resolve hostnames without the relay's added latency.
	AltDNSRouting bool
	// contains filtered or unexported fields
}

SOCKS5Server listens on a local port and proxies CONNECT requests through a DialerPool. Each new connection picks a random dialer from the pool so concurrent connections are distributed across all qualifying controls. If bypass is non-nil, in-country addresses are routed directly via the NIC. If dialFn is non-nil it overrides the pool for all CONNECT requests.

func NewSOCKS5Server

func NewSOCKS5Server(addr string, dialer *TunnelDialer) *SOCKS5Server

NewSOCKS5Server creates a server bound to addr using a single dialer. Wraps the dialer in a 1-element DialerPool for API compatibility.

func NewSOCKS5ServerWithBypass

func NewSOCKS5ServerWithBypass(addr string, dialer *TunnelDialer, bypass *BypassManager) *SOCKS5Server

NewSOCKS5ServerWithBypass creates a server with a single dialer and bypass.

func NewSOCKS5ServerWithDialFunc

func NewSOCKS5ServerWithDialFunc(dialFn func(ctx context.Context, target string) (net.Conn, error)) *SOCKS5Server

NewSOCKS5ServerWithDialFunc creates a SOCKS5 server that uses dialFn for every CONNECT request instead of a DialerPool. Used when an external transport provides its own dial function (see SetDialFunc).

func NewSOCKS5ServerWithPool

func NewSOCKS5ServerWithPool(addr string, pool *DialerPool, bypass *BypassManager) *SOCKS5Server

NewSOCKS5ServerWithPool creates a server that distributes connections across the pool. Use this to enable the multi-control parallel serving policy.

func (*SOCKS5Server) Close

func (s *SOCKS5Server) Close() error

Close shuts down the listener.

func (*SOCKS5Server) ListenAndServe

func (s *SOCKS5Server) ListenAndServe() error

ListenAndServe binds to s.addr and starts accepting SOCKS5 connections. Blocks until the listener is closed.

func (*SOCKS5Server) Serve

func (s *SOCKS5Server) Serve(ln net.Listener) error

Serve accepts connections on the given listener. Blocks until closed.

type Session

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

Session holds per-session header parameters (UA, referer) fixed for the lifetime of one tunnel connection.

func NewSession

func NewSession(rng *rand.Rand) *Session

NewSession picks a random UA and referer and returns a Session.

func (*Session) Headers

func (s *Session) Headers(host string) map[string]string

Headers returns the HTTP headers for a POST upload request in this session. The caller must also set Content-Type and Content-Length.

func (*Session) UA

func (s *Session) UA() string

UA returns the User-Agent string for this session.

type TUNBridge

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

TUNBridge bridges a Linux TUN interface to a local SOCKS5 server via tun2socks / gVisor netstack. All IP traffic entering snc0 is transparently proxied through the SOCKS5 server.

func NewTUNBridge

func NewTUNBridge(socksAddr string) *TUNBridge

NewTUNBridge returns a bridge that will forward TUN traffic to socksAddr.

func (*TUNBridge) IfaceName

func (b *TUNBridge) IfaceName() string

IfaceName returns the TUN interface name after a successful Start.

func (*TUNBridge) Start

func (b *TUNBridge) Start() error

Start creates the snc0 TUN interface and launches the gVisor netstack. Retries up to 3 times with back-off.

func (*TUNBridge) Stop

func (b *TUNBridge) Stop()

Stop tears down the gVisor netstack and brings down the TUN interface.

type TunnelConn

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

TunnelConn is a net.Conn whose Read/Write go through the HTTP tunnel. Callers use it like a regular TCP connection.

Two read modes are supported:

  • Streaming (streamFn != nil): a background goroutine holds an open HTTP response and pushes received bytes into dataChan. Read() blocks on the channel — no polling, minimal latency.
  • Polling (streamFn == nil): legacy mode; Read() sends empty POSTs to fetch buffered data from the server.

func (*TunnelConn) Close

func (c *TunnelConn) Close() error

Close sends a final empty request to let the server know, then closes.

func (*TunnelConn) ConnID

func (c *TunnelConn) ConnID() string

ConnID returns the unique ID for this tunnel connection.

func (*TunnelConn) LocalAddr

func (c *TunnelConn) LocalAddr() net.Addr

func (*TunnelConn) NextSeq

func (c *TunnelConn) NextSeq() int64

NextSeq atomically returns and increments the sequence counter.

func (*TunnelConn) Read

func (c *TunnelConn) Read(p []byte) (int, error)

Read returns data received from the tunnel target.

In streaming mode the call blocks on dataChan, which is fed by the background goroutine; no polling requests are sent. In legacy polling mode it sends empty POSTs until data arrives.

func (*TunnelConn) RemoteAddr

func (c *TunnelConn) RemoteAddr() net.Addr

func (*TunnelConn) SetDeadline

func (c *TunnelConn) SetDeadline(_ time.Time) error

func (*TunnelConn) SetReadDeadline

func (c *TunnelConn) SetReadDeadline(_ time.Time) error

func (*TunnelConn) SetWriteDeadline

func (c *TunnelConn) SetWriteDeadline(_ time.Time) error

func (*TunnelConn) Write

func (c *TunnelConn) Write(p []byte) (int, error)

Write sends payload through the tunnel and buffers any returned data.

type TunnelDialer

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

func NewTunnelDialer

func NewTunnelDialer(auth *Authenticator) *TunnelDialer

NewTunnelDialer returns a TunnelDialer with streaming enabled.

func NewTunnelDialerPolling

func NewTunnelDialerPolling(auth *Authenticator) *TunnelDialer

NewTunnelDialerPolling returns a TunnelDialer using legacy polling mode.

func NewUDPRelayDialer

func NewUDPRelayDialer(relay *UDPRelayConn, auth *Authenticator) *TunnelDialer

NewUDPRelayDialer returns a polling TunnelDialer that sends all tunnel POST requests over the hole-punched UDP relay connection instead of HTTP/TCP. The relay peer transparently forwards each request to Control and returns the response. Streaming is disabled because UDP is datagram-oriented.

func (*TunnelDialer) Auth

func (td *TunnelDialer) Auth() *Authenticator

Auth returns the authenticator used by this dialer.

func (*TunnelDialer) ClearDialFunc

func (td *TunnelDialer) ClearDialFunc()

ClearDialFunc removes a dial function override previously set by SetDialFunc, reverting to direct TCP.

func (*TunnelDialer) Dial

func (td *TunnelDialer) Dial(target string) (net.Conn, error)

Dial opens a tunnel connection to target (host:port).

func (*TunnelDialer) DrainUDPFrames

func (td *TunnelDialer) DrainUDPFrames(connIDHex string, dst *net.UDPAddr) ([][]byte, error)

DrainUDPFrames long-polls the exit for inbound datagrams on an existing UDP session without sending any outbound data. The client's drain goroutine calls this continuously to receive server-initiated datagrams (QUIC ACKs, SRTP, etc.)

func (*TunnelDialer) FailRatio

func (td *TunnelDialer) FailRatio() float64

FailRatio returns this dialer's current failure ratio over the same rolling window recordDialOutcome scores eviction against. Returns 0 (full quality) when there isn't yet enough data to judge — dialWinMinSamples/dialWinMinSpan, the same guards recordDialOutcome uses before firing eviction — so a fresh or quiet dialer is never penalized on too little information. Used by DialerPool.Pick to smoothly deprioritize a struggling-but-not-yet-evicted control instead of only the binary evict/keep decision the hooks give.

func (*TunnelDialer) LastActivity

func (td *TunnelDialer) LastActivity() time.Time

LastActivity returns the time of the most recent tunnel POST, or zero if none.

func (*TunnelDialer) LastDataTime

func (td *TunnelDialer) LastDataTime() time.Time

LastDataTime returns the last time this dialer received a successful POST response. Returns zero if no data has been received yet.

func (*TunnelDialer) OpenConns

func (td *TunnelDialer) OpenConns() int

OpenConns returns the number of currently open tunnel connections on this dialer. Used by the pool to detect when a draining dialer has fully drained.

func (*TunnelDialer) PostUDPFrame

func (td *TunnelDialer) PostUDPFrame(connIDHex string, dst *net.UDPAddr, body []byte) ([][]byte, error)

PostUDPFrame sends a UDP datagram to dst via the encrypted tunnel and returns any inbound datagrams that arrived within the server's short drain window.

func (*TunnelDialer) ServerURL

func (td *TunnelDialer) ServerURL() string

ServerURL returns the server URL this dialer POSTs to.

func (*TunnelDialer) SetActivityHook

func (td *TunnelDialer) SetActivityHook(fn func())

SetActivityHook sets a callback invoked on every tunnel POST. Intended for DecoyManager.MarkActivity; safe to call at any time.

func (*TunnelDialer) SetClientCC

func (td *TunnelDialer) SetClientCC(cc string)

SetClientCC records the device-detected country code, included in every tunnel POST as X-Client-CC so the exit can avoid routing traffic through an exit in the client's own country.

func (*TunnelDialer) SetClientIP

func (td *TunnelDialer) SetClientIP(ip string)

SetClientIP records the client's real public IP, included in every tunnel POST as X-Client-IP so the exit can look up the correct country for stats.

func (*TunnelDialer) SetDataFailHook

func (td *TunnelDialer) SetDataFailHook(threshold int, fn func())

SetDataFailHook sets a callback invoked when ≥80% of dial/stream outcomes in the rolling 30-second window fail (hard eviction tier: data-dead ban). The threshold parameter is ignored; eviction is governed by dataFailRatio.

func (*TunnelDialer) SetDialFunc

func (td *TunnelDialer) SetDialFunc(fn func(ctx context.Context, addr string) (net.Conn, error))

SetDialFunc routes all new TCP connections through fn instead of direct TCP. Used to inject an external transport's own dialer. The function is stored atomically; in-flight requests on the old path complete normally.

func (*TunnelDialer) SetFatalErrorHook

func (td *TunnelDialer) SetFatalErrorHook(fn func(error))

SetFatalErrorHook registers a callback invoked once when re-authentication is permanently exhausted. The hook is called in a new goroutine so it may block (e.g. to trigger a disconnect+reconnect cycle).

func (*TunnelDialer) SetFirstFailHook

func (td *TunnelDialer) SetFirstFailHook(fn func())

SetFirstFailHook sets a callback invoked when ≥50% of dial/stream outcomes in the rolling 30-second window fail (soft eviction tier: flap penalty, control remains eligible for future path selection).

func (*TunnelDialer) SetRTTUpdateHook

func (td *TunnelDialer) SetRTTUpdateHook(fn func(serverURL string, rtt time.Duration))

SetRTTUpdateHook registers a callback invoked after each successful POST with the server URL and the current EMA traffic RTT. The hook fires only once trafficRTTMinSamples samples have been collected so early noise is suppressed. Intended to feed live RTT measurements back into the Router.

func (*TunnelDialer) SetReAuthRecoveredHook

func (td *TunnelDialer) SetReAuthRecoveredHook(fn func())

SetReAuthRecoveredHook registers a callback invoked when re-auth succeeds after a prior warning. Intended to clear the visual warning.

func (*TunnelDialer) SetReAuthWarningHook

func (td *TunnelDialer) SetReAuthWarningHook(fn func())

SetReAuthWarningHook registers a callback invoked on the first re-auth failure. Intended to show a visual warning to the user.

func (*TunnelDialer) SetUDPFailedHook

func (td *TunnelDialer) SetUDPFailedHook(fn func())

SetUDPFailedHook registers a callback invoked once when the UDP relay exceeds its consecutive-error threshold. The router uses this to mark the control as TCP-only and trigger a pool rebuild.

func (*TunnelDialer) Token

func (td *TunnelDialer) Token() string

Token returns the current session token used by the dialer.

func (*TunnelDialer) TrafficRTT

func (td *TunnelDialer) TrafficRTT() time.Duration

TrafficRTT returns the current EMA of observed POST round-trip times, or 0 if fewer than trafficRTTMinSamples samples have been recorded.

type TunnelTrafficMonitor

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

TunnelTrafficMonitor tracks payload throughput in both directions so the watchdog can detect a one-sided outage: data sent but nothing received. Zero-payload frames and bypass-routed traffic are excluded by the callers.

var TunnelMonitor TunnelTrafficMonitor

TunnelMonitor is the package-level instance shared between tunnel.go and the tray watchdog.

func (*TunnelTrafficMonitor) IsStuck

func (m *TunnelTrafficMonitor) IsStuck() bool

IsStuck returns true when the tunnel appears one-sided: real outbound payload was sent recently but no real inbound data has arrived within the stuck-timeout window. Returns false when idle (no recent outbound traffic).

When recv has never been observed (recv.IsZero), the tunnel is considered stuck only after a full tunnelStuckTimeout has elapsed since the very first send. This prevents false positives during the cold-start period where the first round-trip is still in flight.

func (*TunnelTrafficMonitor) RecordTunnelRecv

func (m *TunnelTrafficMonitor) RecordTunnelRecv(n int)

RecordTunnelRecv notes that n bytes of real data arrived from the tunnel. n == 0 is ignored (padding-only responses where dlen == 0).

func (*TunnelTrafficMonitor) RecordTunnelSent

func (m *TunnelTrafficMonitor) RecordTunnelSent(n int)

RecordTunnelSent notes that n bytes of application payload were sent through the tunnel. n == 0 is ignored (padding / header-only frames).

func (*TunnelTrafficMonitor) Reset

func (m *TunnelTrafficMonitor) Reset()

Reset clears the traffic timestamps. Call on each successful reconnect so stale pre-reconnect timestamps don't suppress the first watchdog cycle.

type UDPRelayConn

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

UDPRelayConn is the core P2P relay transport. Create with NewUDPRelayConn; call Close when done.

func NewUDPControlConn

func NewUDPControlConn(controlAddr string) (*UDPRelayConn, error)

NewUDPControlConn dials a connected UDP socket to controlAddr and wraps it in a UDPRelayConn for use as a client-only transport (server mode disabled). The caller is responsible for closing the returned conn when done. controlAddr is host or host:port; defaults to port 443 if no port given.

func NewUDPRelayConn

func NewUDPRelayConn(conn *net.UDPConn, controlURL string) *UDPRelayConn

NewUDPRelayConn wraps conn as a bidirectional relay transport. controlURL is the base URL used when this node forwards requests on behalf of a remote peer (e.g. "https://203.0.113.1:443"). Pass "" to disable server mode.

func (*UDPRelayConn) Close

func (c *UDPRelayConn) Close()

Close tears down the relay connection.

func (*UDPRelayConn) Failed

func (c *UDPRelayConn) Failed() bool

Failed reports whether this relay has exceeded the consecutive-error threshold. When true, callers should fall back to TCP and request a pool rebuild.

func (*UDPRelayConn) RoundTrip

func (c *UDPRelayConn) RoundTrip(path, token string, body []byte) (int, []byte, error)

RoundTrip sends a tunnel POST request to the relay peer and returns the (status, body) from Control. Retries up to udpRelayRetries times on timeout.

func (*UDPRelayConn) StopCh

func (c *UDPRelayConn) StopCh() <-chan struct{}

StopCh returns a channel that is closed when the connection is shut down.

type WatchdogState

type WatchdogState struct {
	Connected     bool   `json:"connected"`
	OrigGW        string `json:"orig_gw,omitempty"`
	MainPID       int    `json:"main_pid,omitempty"`
	LastAlive     int64  `json:"last_alive,omitempty"`     // Unix seconds; written periodically by main
	LastWake      int64  `json:"last_wake,omitempty"`      // Unix seconds; written by main on each system wake
	TunnelHealthy bool   `json:"tunnel_healthy,omitempty"` // true when tunnel is up and not recovering
}

WatchdogState is persisted on disk so the watchdog process can clean up networking state after an unclean main-process exit (crash, hard reboot, kill).

func ReadWatchdogState

func ReadWatchdogState() WatchdogState

ReadWatchdogState reads the persisted state. Returns a zero-value WatchdogState if the file is absent or unreadable.

Directories

Path Synopsis
cmd
demo command
Command demo is a minimal reference client for tunnelcat-core: it logs in to a control server you supply and exposes the resulting tunnel as a local SOCKS5 proxy (optionally also as a TUN interface).
Command demo is a minimal reference client for tunnelcat-core: it logs in to a control server you supply and exposes the resulting tunnel as a local SOCKS5 proxy (optionally also as a TUN interface).
internal
wintun
Package wintun fetches the WinTun driver DLL at runtime (on first use) and extracts it to the directory of the running executable.
Package wintun fetches the WinTun driver DLL at runtime (on first use) and extracts it to the directory of the running executable.
tools
fetch_wintun command
fetch_wintun downloads wintun-0.14.1.zip from wintun.net and extracts the amd64 DLL into internal/wintun/wintun.dll.
fetch_wintun downloads wintun-0.14.1.zip from wintun.net and extracts the amd64 DLL into internal/wintun/wintun.dll.

Jump to

Keyboard shortcuts

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