Documentation
¶
Index ¶
- Constants
- Variables
- func AllUTLSPresets() []utls.ClientHelloID
- func BuildSignedRelayEntry(nodeID, addr, countryCode string) (*dht.RelayEntry, error)
- func BuildUploadResponse(key, data []byte) ([]byte, error)
- func DefaultRelayChunkFetcher(d *Discoverer) func(hash string) ([]byte, error)
- func FetchMyIP(apiURL string) (string, error)
- func InitLogging(dir string) error
- func InitTunLogging(dir string) error
- func IsLANAddress(target string) bool
- func LoadOrGenNodeID(appDataDir string) (string, error)
- func NewDecoyTransport(physIP string, controlFn func(string, string, syscall.RawConn) error) http.RoundTripper
- func NewDiscoveryClient() *http.Client
- func NewRelayAPIH1Client() *http.Client
- func NewUTLSClientWithPreset(preset utls.ClientHelloID) *http.Client
- func OpenFrame(key, data []byte) ([]byte, error)
- func ParseUploadFrame(plain []byte) (connID string, seq uint32, target string, payload []byte, err error)
- func PresetName(p utls.ClientHelloID) string
- func ProbeControlE2E(addr string, timeout time.Duration) (rtt time.Duration, ok bool)
- func ProbeControlUDP(addr string, timeout time.Duration) (rtt time.Duration, ok bool)
- func Punch(localIP, peerAddr string) (*net.UDPConn, error)
- func PunchProtected(peerAddr string, dialControl func(string, string, syscall.RawConn) error) (*net.UDPConn, error)
- func RandomReferer(rng *rand.Rand) string
- func ReadManifestCacheControls(cacheFile, pubkeyHex string) []string
- func ReadManifestCacheControlsAndRegions(cacheFile, pubkeyHex string) ([]string, map[string]string)
- func SaveRelayList(path string, relays []RelayEntry) error
- func SealFrame(key, plaintext []byte) ([]byte, error)
- func SessionKey(token string) []byte
- func SetDialControl(fn func(network, address string, c syscall.RawConn) error)
- func SetTunnelHealthy(healthy bool)
- func SignNodePayload(payload []byte) ([]byte, error)
- func TimezoneCC() string
- func TouchAlive()
- func TouchLastWake()
- func VerifySignedPayload(payload []byte, pubkeyHex, sigB64 string) error
- func WatchdogStatePath() string
- func WrapWithTorrentFilter(ln net.Listener) net.Listener
- func WriteWatchdogState(s WatchdogState) error
- type Authenticator
- func (a *Authenticator) AdoptToken(tok string)
- func (a *Authenticator) ClearDialFunc()
- func (a *Authenticator) DrainNotifications() []Notification
- func (a *Authenticator) Login() error
- func (a *Authenticator) LoginViaUDP(relay *UDPRelayConn) error
- func (a *Authenticator) ProxyValidate(username, password string) (string, error)
- func (a *Authenticator) SetDeviceInfo(keyID, deviceID, deviceName string)
- func (a *Authenticator) SetDialFunc(fn func(ctx context.Context, addr string) (net.Conn, error))
- func (a *Authenticator) SetHTTPClientForPreset(preset utls.ClientHelloID)
- func (a *Authenticator) SetKeyAuthParams(p KeyAuthParams)
- func (a *Authenticator) Token() string
- type BypassManager
- func (m *BypassManager) BypassDialer() *net.Dialer
- func (m *BypassManager) CIDRStatus() string
- func (m *BypassManager) ContainsIP(ip net.IP) bool
- func (m *BypassManager) Country() string
- func (m *BypassManager) DialUDP() (*net.UDPConn, error)
- func (m *BypassManager) Enabled() bool
- func (m *BypassManager) HasLocalIP() bool
- func (m *BypassManager) RecordBypassFailure(addr string)
- func (m *BypassManager) SetEnabled(v bool)
- func (m *BypassManager) SetLocalIP(ip string)
- func (m *BypassManager) SetMyIP(ip string)
- func (m *BypassManager) SetNodes(urls []string)
- func (m *BypassManager) SetToken(token string)
- func (m *BypassManager) ShouldBypass(addr string) bool
- func (m *BypassManager) Start()
- func (m *BypassManager) Stop()
- type CIDRSet
- type DHTContact
- type DHTID
- type DHTNode
- type DHTRelayEntry
- type DecoyManager
- type DialerPool
- func (p *DialerPool) Add(td *TunnelDialer)
- func (p *DialerPool) DrainEvictions() int
- func (p *DialerPool) Evict(td *TunnelDialer) int
- func (p *DialerPool) Get(ctrlURL string) *TunnelDialer
- func (p *DialerPool) Has(ctrlURL string) bool
- func (p *DialerPool) LastDataTime() time.Time
- func (p *DialerPool) NeedsRefill(target int) bool
- func (p *DialerPool) Pick() *TunnelDialer
- func (p *DialerPool) PickForUID(_ int) *TunnelDialer
- func (p *DialerPool) SetActivityHook(fn func())
- func (p *DialerPool) Size() int
- func (p *DialerPool) StartManagement(interval time.Duration, stopCh <-chan struct{})
- func (p *DialerPool) Swap(dialers []*TunnelDialer)
- type Discoverer
- func (d *Discoverer) AltUDPPorts(ctrlAddr string) []int
- func (d *Discoverer) Controls() []string
- func (d *Discoverer) InjectRaw(data []byte) error
- func (d *Discoverer) LoadCached() error
- func (d *Discoverer) ManifestStatus() string
- func (d *Discoverer) Notifications() []Notification
- func (d *Discoverer) ProbeManifest(timeout time.Duration) (nodes int, err error)
- func (d *Discoverer) Regions() map[string]string
- func (d *Discoverer) SNIFor(addr string) string
- func (d *Discoverer) SetFetchCallback(fn func(raw []byte, ts int64))
- func (d *Discoverer) SetNotificationCallback(fn func([]Notification))
- func (d *Discoverer) Start(interval time.Duration)
- func (d *Discoverer) Stop()
- func (d *Discoverer) UseAsSNIProvider()
- type ExternalEndpoint
- type KeyAuthParams
- type LogUploader
- type MirrorConn
- type MirrorManager
- type Notification
- type ParaExitClient
- type RelayEntry
- type Router
- func (r *Router) Advance() bool
- func (r *Router) AllControlAddrs() []string
- func (r *Router) BuildPaths()
- func (r *Router) CloseAllUDPPeers()
- func (r *Router) ControlRTT(addr string) time.Duration
- func (r *Router) ControlTransport(addr string) controlTransport
- func (r *Router) ControlTransportName(addr string) string
- func (r *Router) HasUDPPeer(nodeID string) bool
- func (r *Router) MarkControlAlive(addr string)
- func (r *Router) MarkControlDataDead(addr string, until time.Time)
- func (r *Router) MarkRelayAlive(id string)
- func (r *Router) MarkUDPDataFailed(addr string)
- func (r *Router) MeasureRTTs(timeout time.Duration)
- func (r *Router) MergeDHTRelays(entries []DHTRelayEntry)
- func (r *Router) NewControlDialer(addr string, auth *Authenticator) (*TunnelDialer, error)
- func (r *Router) Paths() []RouterPath
- func (r *Router) PickRandom() *RouterPath
- func (r *Router) Primary() *RouterPath
- func (r *Router) PrimaryIsBetter(currentAddr string, factor float64) (bool, *RouterPath)
- func (r *Router) ProbeDataPlane(timeout time.Duration)
- func (r *Router) QualifyingControlAddrs() []string
- func (r *Router) RecordControlFlap(addr string)
- func (r *Router) RegisterUDPPeer(key string, conn *UDPRelayConn)
- func (r *Router) RemoveUDPPeer(key string)
- func (r *Router) Reset()
- func (r *Router) SetControl(addr string)
- func (r *Router) SetControls(addrs []string)
- func (r *Router) SetControlsWithRegions(addrs []string, regions map[string]string)
- func (r *Router) SetMyCountry(cc string)
- func (r *Router) SetSelfNodeID(id string)
- func (r *Router) UnreachableControls() []string
- func (r *Router) UpdateControlRTT(addr string, rtt time.Duration)
- func (r *Router) UpdateRelays(relays []RelayEntry)
- func (r *Router) UpdateTrafficRTT(addr string, rtt time.Duration)
- type RouterPath
- type RouterPathNode
- type SOCKS5Server
- func NewSOCKS5Server(addr string, dialer *TunnelDialer) *SOCKS5Server
- func NewSOCKS5ServerWithBypass(addr string, dialer *TunnelDialer, bypass *BypassManager) *SOCKS5Server
- func NewSOCKS5ServerWithDialFunc(dialFn func(ctx context.Context, target string) (net.Conn, error)) *SOCKS5Server
- func NewSOCKS5ServerWithPool(addr string, pool *DialerPool, bypass *BypassManager) *SOCKS5Server
- type Session
- type TUNBridge
- type TunnelConn
- func (c *TunnelConn) Close() error
- func (c *TunnelConn) ConnID() string
- func (c *TunnelConn) LocalAddr() net.Addr
- func (c *TunnelConn) NextSeq() int64
- func (c *TunnelConn) Read(p []byte) (int, error)
- func (c *TunnelConn) RemoteAddr() net.Addr
- func (c *TunnelConn) SetDeadline(_ time.Time) error
- func (c *TunnelConn) SetReadDeadline(_ time.Time) error
- func (c *TunnelConn) SetWriteDeadline(_ time.Time) error
- func (c *TunnelConn) Write(p []byte) (int, error)
- type TunnelDialer
- func (td *TunnelDialer) Auth() *Authenticator
- func (td *TunnelDialer) ClearDialFunc()
- func (td *TunnelDialer) Dial(target string) (net.Conn, error)
- func (td *TunnelDialer) DrainUDPFrames(connIDHex string, dst *net.UDPAddr) ([][]byte, error)
- func (td *TunnelDialer) FailRatio() float64
- func (td *TunnelDialer) LastActivity() time.Time
- func (td *TunnelDialer) LastDataTime() time.Time
- func (td *TunnelDialer) OpenConns() int
- func (td *TunnelDialer) PostUDPFrame(connIDHex string, dst *net.UDPAddr, body []byte) ([][]byte, error)
- func (td *TunnelDialer) ServerURL() string
- func (td *TunnelDialer) SetActivityHook(fn func())
- func (td *TunnelDialer) SetClientCC(cc string)
- func (td *TunnelDialer) SetClientIP(ip string)
- func (td *TunnelDialer) SetDataFailHook(threshold int, fn func())
- func (td *TunnelDialer) SetDialFunc(fn func(ctx context.Context, addr string) (net.Conn, error))
- func (td *TunnelDialer) SetFatalErrorHook(fn func(error))
- func (td *TunnelDialer) SetFirstFailHook(fn func())
- func (td *TunnelDialer) SetRTTUpdateHook(fn func(serverURL string, rtt time.Duration))
- func (td *TunnelDialer) SetReAuthRecoveredHook(fn func())
- func (td *TunnelDialer) SetReAuthWarningHook(fn func())
- func (td *TunnelDialer) SetUDPFailedHook(fn func())
- func (td *TunnelDialer) Token() string
- func (td *TunnelDialer) TrafficRTT() time.Duration
- type TunnelTrafficMonitor
- type UDPRelayConn
- type WatchdogState
Constants ¶
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).
const ( TUNDeviceName = "snc0" TUNMTU = 1500 TUNAddr = "198.18.0.1" TUNMask = "255.255.0.0" TUNIPv6Addr = "fd00::2" )
const ( FrameTypeUpload = frameTypeUpload FrameTypeStreamOpen = frameTypeStreamOpen )
FrameTypeUpload and FrameTypeStreamOpen are the plaintext frame-type tags used by the decoy upload protocol (see buildUploadPlain/parseUploadFrame).
const ( // PunchTimeout is how long Punch waits for a probe from the peer. PunchTimeout = 3 * time.Second )
Variables ¶
var ChanDepth = 64
ChanDepth controls the depth of each TunnelConn's dataChan buffer. Android sets this proportionally to available RAM via SNC_DATACHAN_DEPTH.
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().
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.
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.
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).
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.
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.
TunLog logs every TCP/UDP connection entering the TUN interface. Initialised by InitTunLogging; discards output until then.
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 ¶
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 ¶
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 ¶
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 ¶
InitTunLogging opens a separate rotating log file for TUN traffic. Call after InitLogging.
func IsLANAddress ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
RandomReferer returns a random referer from the pool (different each call).
func ReadManifestCacheControls ¶
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 ¶
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 ¶
SealFrame encrypts plaintext with a random nonce. Wire format: [12B nonce][ChaCha20-Poly1305 ciphertext+tag].
func SessionKey ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ParseCIDRs builds a CIDRSet from a slice of CIDR strings. Invalid entries are silently skipped. Both IPv4 and IPv6 prefixes are accepted.
type DHTContact ¶
Type aliases — core.DHTID and dht.ID are the same type.
type DHTID ¶
Type aliases — core.DHTID and dht.ID are the same type.
func ParseDHTID ¶
ParseDHTID decodes a 64-char hex string into a DHTID.
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.
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 ¶
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) 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 ¶
NewMirrorConn wraps conn as a bidirectional chunk-transfer transport.
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 ¶
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 ¶
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 ¶
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 ¶
ControlTransport returns the transport protocol detected for addr by the last ProbeDataPlane call. Returns transportTCP for unknown addresses.
func (*Router) ControlTransportName ¶
ControlTransportName returns a human-readable transport name for addr ("tcp" or "udp").
func (*Router) HasUDPPeer ¶
HasUDPPeer reports whether a live UDP relay connection exists for the given node ID.
func (*Router) MarkControlAlive ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetControl sets a single control node. Compatibility shim; prefer SetControls.
func (*Router) SetControls ¶
SetControls replaces the control node list. The first address is the preferred control; additional addresses are fallbacks. Call MeasureRTTs + BuildPaths after.
func (*Router) SetControlsWithRegions ¶
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 ¶
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 ¶
SetSelfNodeID tells the router its own DHT node ID so it can exclude itself from relay selection in MergeDHTRelays.
func (*Router) UnreachableControls ¶
UnreachableControls returns control addresses that are known but currently not alive — i.e. candidates for relay-assisted access.
func (*Router) UpdateControlRTT ¶
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 ¶
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 ¶
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) ListenAndServe ¶
func (s *SOCKS5Server) ListenAndServe() error
ListenAndServe binds to s.addr and starts accepting SOCKS5 connections. Blocks until the listener is 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 ¶
NewSession picks a random UA and referer and returns a 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 ¶
NewTUNBridge returns a bridge that will forward TUN traffic to socksAddr.
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
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 ¶
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 ¶
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) 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 ¶
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.
Source Files
¶
- bypass.go
- cidr.go
- decoy.go
- dht.go
- dht_node.go
- dht_wire.go
- dial_control.go
- dialer_pool.go
- discovery.go
- dns_cache.go
- headers.go
- holepunch.go
- key.go
- log.go
- log_upload.go
- mirror.go
- mirror_transport.go
- nat.go
- nodeid.go
- nodeid_other.go
- pacing.go
- para_exit.go
- procfilter.go
- relay.go
- router.go
- session.go
- signal.go
- socks5.go
- tls.go
- tun_linux.go
- tunnel.go
- tz_country.go
- udp_assoc.go
- udp_control.go
- udp_relay.go
- watchdog.go
- watchdog_state.go
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. |