backend

package
v0.0.0-...-0c015a4 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MPL-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Vsep is a values separator (csv)
	Vsep = ","
	// Ksep is a key separator (csv)
	Ksep = ","
	// Kdelim is a key@csv(v) delimiter
	Kdelim = "@"
	// KVsep is a k1:v1|k2:v2 separator
	KVsep = "|"
)
View Source
const (
	// DNS transport types
	DOH      = "DNS-over-HTTPS"
	DNSCrypt = "DNSCrypt"
	DNS53    = "DNS"
	DOT      = "DNS-over-TLS"
	ODOH     = "Oblivious DNS-over-HTTPS"

	CT = "Cache" // cached transport prefix

	// Multiple DoH, DoT, ODoH resolvers
	Plus = "Plus"
	// Go determined default resolver (built-in)
	Goos = "Goos"
	// network/os provided dns (init using intra.SetSystemDNS)
	System = "System"
	// mdns; never cached! (built-in)
	Local = "mdns"
	// default (fallback) dns, used in place of special transports when unavailable
	// (init using intra.AddDefaultTransport)
	Default = "Default"
	// client preferred dns
	Preferred = "Preferred"
	// synthesizes answers from presets (built-in)
	Preset = "Preset"
	// synthesizes A/AAAA from a single fixed IP (built-in)
	Fixed = "Fixed"
	// a transport that bypasses local blocklists (dnsx.SetRdnsLocal);
	// if not set, Default is used
	BlockFree = "BlockFree"
	// all queries are blocked, answers never cached (built-in)
	BlockAll = "BlockAll"
	// Bootstrap DNS (built-in); encapsulates Default, if set; or Goos, otherwise.
	Bootstrap = "Bootstrap"
	// Application-level gateway
	Alg = "Alg"
	// dnscrypt.Proxy as a DNS Transport
	DcProxy = "DcProxy"
	// dns resolver for dns resolvers and for firestack (built-in)
	// delegates queries to Bootstrap.
	IpMapper = "IpMapper"
)
View Source
const (
	// Start: Transaction started
	Start = iota
	// Complete : Transaction completed successfully
	Complete
	// SendFailed : Failed to send query
	SendFailed
	// NoResponse : Got no response
	NoResponse
	// BadQuery : Malformed input
	BadQuery
	// BadResponse : Response was invalid
	BadResponse
	// InternalError : This should never happen
	InternalError
	// TransportError: Transport has issues
	TransportError
	// ClientError: Client has issues
	ClientError
	// Paused: Transport is paused
	Paused
	// DEnd: Transport stopped
	DEnd
)
View Source
const (
	EB32 = iota
	EB64
)
View Source
const (

	// blocks all traffic (built-in)
	Block = "Block"
	// may send traffic out via underlying network (built-in)
	// see: tun2socks.Loopback; alias for dnsx.NetNoProxy
	Base = "Base"
	// always sends traffic out via underlying network (built-in)
	// see: Controller.Protect; alias for dnsx.NetExitProxy
	Exit = "Exit"
	// proxies incoming connections (built-in)
	Ingress = "Ingress"
	// Auto uses ipn.Exit or any of the RPN proxies (built-in)
	Auto = "Auto"
	// RPN Win proxy (must be registered by Rpn.RegisterWin)
	RpnWin = WG + "y" + RPN
	// Alias for RPN Win
	RpnPro = RpnWin
	// RPN WebSockets (unused)
	RpnWs = PIPWS + RPN
	// RPN HTTP/2 (unused)
	RpnH2 = PIPH2 + RPN
	// RPN Exit hopping over NAT64 (built-in)
	Rpn64 = NAT64 + RPN
	// RPN SurfEasy (must be registered by Rpn.RegisterSE)
	RpnSE = SE + RPN
	// Orbot: Base Tor-as-a-SOCKS5 proxy
	OrbotS5 = "OrbotSocks5"
	// Orbot: Base Tor-as-a-HTTP/1.1 proxy
	OrbotH1 = "OrbotHttp1"
	// Global: HTTP/1.1 proxy if required by underlying network.
	GlobalH1 = "GlobalHttp1"

	// SOCKS5 proxy type
	SOCKS5 = "socks5"
	// HTTP/1.1 proxy type
	HTTP1 = "http1"
	// WireGuard-as-a-proxy type and prefix
	WG = "wg"
	// No proxy (uses underlying network), ex: Base, Block, Ingress
	NOOP = "noop"
	// Egress, ex: Exit
	INTERNET = "net"
	// WireGuard-as-a-proxy w/ UDP GRO/GSO prefix (experimental)
	WGFAST = "gsro"
	// PIP: HTTP/2 proxy prefix (unused)
	PIPH2 = "piph2"
	// PIP: WebSockets proxy prefix (unused)
	PIPWS = "pipws"
	// A NAT64 router (prefix)
	NAT64 = "nat64"
	// SurfEasy proxy (prefix)
	SE = "se"
	// Rethink Proxy Network (suffix)
	RPN = "rpn"

	// proxy paused until resumed; will not dial
	TPU = 3
	// proxy UP but not responding
	TNT = 2
	// proxy idle
	TZZ = 1
	// proxy UP but not yet OK
	TUP = 0
	// proxy OK
	TOK = -1
	// proxy not OK
	TKO = -2
	// proxy stopped
	END = -3
)
View Source
const (
	UidSelf   = "rethink"
	UidSystem = "system"
	Localhost = "localhost"
)
View Source
const (

	// SOCKS5
	SVCSOCKS5 = "svcsocks5"
	// HTTP
	SVCHTTP = "svchttp"
	// SOCKS5 with forwarding proxy
	PXSOCKS5 = "pxsocks5"
	// HTTP with forwarding proxy
	PXHTTP = "pxhttp"

	// svc UP
	SUP = 0
	// svc OK
	SOK = 1
	// svc not OK
	SKO = -1
	// svc stopped
	SOP = -2
)

Variables

This section is empty.

Functions

func OfFunc

func OfFunc[T *Gostr2 | *Gobyte, R string | []byte](f func() (R, error)) (T, error)

Types

type Client

type Client interface {
	// IP4 returns information about this client's remote IPv4.
	IP4() (*IPMetadata, error)
	// IP6 returns information about this client's remote IPv6.
	IP6() (*IPMetadata, error)
}

type Console

type Console interface {
	Log(int32, *Gostr)
}

type Controller

type Controller interface {
	// Bind4 binds fd to any internet-capable IPv4 interface.
	Bind4(who, addrport string, fd int)
	// Bind6 binds fd to any internet-capable IPv6 interface.
	// also: github.com/lwip-tcpip/lwip/blob/239918c/src/core/ipv6/ip6.c#L68
	Bind6(who, addrport string, fd int)
	// Protect marks fd as protected.
	Protect(who string, fd int)
}

Controller provides a way to bind and protect socket file descriptors.

type DNSListener

type DNSListener interface {
	ResolverListener
	// OnQuery is called when a DNS query is received. The listener
	// can return a DNSOpts to specify how the query should be handled.
	OnQuery(uid, domain *Gostr, qtyp int) *DNSOpts
	// OnUpstreamAnswer is called before an upstream DNS answer (not blocked by firestack) is sent to the OS.
	// The listener may return DNSOpts to specify if another upstream should override that answer.
	// Another round of OnQuery is NOT called in this case, and OnResponse is called once after processing
	// DNSOpts returned by OnUpstreamAnswer if it has a non-empty TIDCSV (overriding the original TIDCSV).
	OnUpstreamAnswer(smm *DNSSummary, unmodifiedipcsv *Gostr) *DNSOpts
	// OnResponse is called when a DNS response is received. May be called twice for the same query,
	// for instance, when different options are requested through OnUpstreamAnswer.
	OnResponse(*DNSSummary)
}

DNSListener receives Summaries.

type DNSOpts

type DNSOpts struct {
	// csv of proxy ids to use for this query. Not all transports are proxied.
	// For instance, dnsx.System, dnsx.Local, dnsx.Goos, dnsx.Preset, dnsx.Default
	// are never proxied.
	PIDCSV string
	// csv of ips to answer for this query; incl unspecified ips, if any.
	// applicable only for A/AAAA queries.
	// if set, query bypasses on-device blocklists.
	IPCSV string
	// primary transport ids to use for this query.
	// dictated by user preferences (dnsx.Preferred, dnsx.System etc) or
	// or user set rules (dnsx.BlockAll, dnsx.BlockFree, dnsx.Fixed etc)
	TIDCSV string
	// secondary transport ids to use for this query.
	// usually, user-set DNS (dnsx.Preferred or dnsx.System) when primary is
	// dnsx.BlockFree or dnsx.Fixed. Mostly, left unset.
	TIDSECCSV string
	// If set, query bypasses on-device blocklists only, independent of whether TIDCSV
	// has dnsx.BlockFree or not. The difference is, dnsx.BlockFree if pointing to a
	// non-blocking resolver (like one.one.one.one or dns.google)
	// will bypass both on-device & upstream blocklists.
	NOBLOCK bool
}

type DNSSummary

type DNSSummary struct {
	// dnscrypt, dns53, doh, odoh, dot, preset, fixed, etc.
	Type string
	// DNS Transport ID
	ID string
	// owner uid that sent this request. May be empty.
	UID string
	// Response (or failure) latency in seconds
	Latency float64
	// Queried domain name
	QName string
	// Query type: A, AAAA, SVCB, HTTPS, etc. May be 0.
	QType int
	// CSV of all DNS aliases/names in the answer section (ex: CNAMEs)
	Targets string
	// Was this response returned from cache?
	Cached bool
	// DNS Response data, ex: a csv of ips for A, AAAA.
	RData string
	// DNS Response code
	RCode int
	// DNS Response TTL
	RTtl int
	// DNS Server (ip, ip:port, host, host:port)
	Server string
	// Proxy or a relay server address
	PID string
	// Relay server PID hops over, if any
	RPID string
	// Transport status (Start, Complete, SendFailed, NoResponse, BadQuery, BadResponse, etc)
	Status int
	// CSV of Rethink DNS+ blocklists (local or remote) names (if used).
	Blocklists string
	// Actual target (domain name) that was blocked (could be a CNAME or HTTPS/SVCB alias) by Blocklists
	BlockedTarget string
	// True if any among upstream transports (primary or secondary) returned blocked ans.
	// Only valid for A/AAAA queries. Unspecified IPs are considered as "blocked ans".
	UpstreamBlocks bool
	// True if DNSSEC OK bit is set.
	DO bool
	// True if DNSSEC validation was successful.
	AD bool
	// Diag message from Transport, if any. Typically, "no error"
	Msg string
	// Region of the Rethink DNS+ server (if used)
	Region string
}

DNSSummary is a summary of a DNS transaction, reported when it is complete.

func (*DNSSummary) String

func (s *DNSSummary) String() string

String implements fmt.Stringer.

type DNSTransport

type DNSTransport interface {
	// uniquely identifies this transport
	ID() *Gostr
	// one of DNS53, DOH, DNSCrypt, System
	Type() *Gostr
	// Median round-trip time for this transport, in millis.
	P50() int64
	// Return the server host address used to initialize this transport.
	GetAddr() *Gostr
	// Return the proxy (relay) always used by this transport.
	// Returns nil if there isn't any.
	GetRelay() Proxy
	// State of the transport after previous query (see: queryerror.go)
	Status() int
}

DNSTransport exports necessary methods from dnsx.Transport

type DNSTransportMult

type DNSTransportMult interface {
	DNSTransportProvider
	// Add adds a transport to this multi-transport.
	Add(t DNSTransport) bool
	// Remove removes a transport from this multi-transport.
	Remove(id *Gostr) bool
	// Refresh re-registers transports and returns a csv of active ones.
	Refresh() (*Gostr, error)
	// LiveTransports returns a csv of active transports.
	LiveTransports() *Gostr
}

type DNSTransportMultProvider

type DNSTransportMultProvider interface {
	// GetMult returns a multi-transport by id.
	GetMult(id *Gostr) (DNSTransportMult, error)
}

type DNSTransportProvider

type DNSTransportProvider interface {
	// Get returns a transport from this multi-transport.
	Get(id *Gostr) (DNSTransport, error)
}

type GoStat

type GoStat struct {
	Alloc      string // bytes allocated and not yet freed
	TotalAlloc string // total bytes allocated in aggregate
	Sys        string // bytes obtained from system
	Lookups    int64  // number of pointer lookups
	Mallocs    int64  // number of mallocs
	Frees      int64  // number of frees

	HeapAlloc    string // bytes allocated on heap
	HeapSys      string // heap obtained from system
	HeapIdle     string // bytes in idle spans
	HeapInuse    string // bytes in non-idle span
	HeapReleased string // bytes released to the OS
	HeapObjects  int64  // total number of allocated objects

	StackInuse  string // bytes used by stack allocator
	StackSys    string // bytes obtained from system for stack allocator
	MSpanInuse  string // mspan allocs
	MSpanSys    string // bytes obtained from system for mspan structures
	MCacheInuse string // mcache structures
	MCacheSys   string // bytes obtained from system for mcache structures
	BuckHashSys string // bytes used by the profiling bucket hash table

	EnableGC      bool   // GC enabled
	DebugGC       bool   // GC debug
	GCSys         string // bytes used for garbage collection system metadata
	OtherSys      string // bytes used for off-heap allocations
	NextGC        string // target heap size of the next GC
	LastGC        string // last run in heap
	PauseSecs     int64  // total STW pause time
	NumGC         int32  // number of GC runs
	NumForcedGC   int32  // number of forced GC runs
	GCCPUFraction string // fraction of CPU time used by GC

	NumGoroutine int64 // number of goroutines
	NumCgo       int64 // number of cgo calls
	NumCPU       int64 // number of CPUs
}

ref: github.com/google/gops/blob/35c854fb84a/agent/agent.go

type Gobyte

type Gobyte struct {
	B []byte
}

Gostr & Gobyte are a workaround for: github.com/golang/go/issues/46893

func BytesOf

func BytesOf(v []byte) *Gobyte

func BytesOfFunc

func BytesOfFunc(f func() ([]byte, error)) (*Gobyte, error)

func (*Gobyte) Len

func (b *Gobyte) Len() int

func (*Gobyte) V

func (b *Gobyte) V() []byte

type Gostr

type Gostr struct {
	S string
}

Gostr wraps a go string.

func StrOf

func StrOf(v string) *Gostr

func StrOfFunc

func StrOfFunc(f func() (string, error)) (*Gostr, error)

func StrOfFunc1

func StrOfFunc1[P any](f func(P) (string, error), p P) (*Gostr, error)

func StrOfFunc2

func StrOfFunc2[P any, Q any](f func(P, Q) (string, error), p P, q Q) (*Gostr, error)

func (*Gostr) Len

func (st *Gostr) Len() int

func (*Gostr) String

func (s *Gostr) String() string

func (*Gostr) V

func (s *Gostr) V() string

type Gostr2

type Gostr2 struct {

	// hash of Gostr's string (exported for java/kt equals() & hashCode())
	H int64
	// length of Gostr's string (exported for java/kt equals() & hashCode())
	L int
	// contains filtered or unexported fields
}

Gostr2 is like Gostr but the raw string is not exported to Java/Kotlin.

func StrOf2

func StrOf2(v string) *Gostr2

func (*Gostr2) S

func (s *Gostr2) S() *Gostr

type ICMPStat

type ICMPStat struct {
	Rcv4        int64 // ICMPv4 messages received
	Rcv6        int64 // ICMPv6 messages received
	Snd4        int64 // ICMPv4 messages sent
	Snd6        int64 // ICMPv6 messages sent
	UnrchRcv4   int64 // ICMPv4 unreachable received
	UnrchRcv6   int64 // ICMPv6 unreachable received
	UnrchSnd4   int64 // ICMPv4 unreachable sent
	UnrchSnd6   int64 // ICMPv6 unreachable sent
	Invalid4    int64 // ICMPv4 invalid messages
	Invalid6    int64 // ICMPv6 invalid messages
	TimeoutSnd4 int64 // ICMPv4 TTL timeouts sent
	TimeoutSnd6 int64 // ICMPv6 TTL timeouts sent
	TimeoutRcv4 int64 // ICMPv4 TTL timeouts received
	TimeoutRcv6 int64 // ICMPv6 TTL timeouts received
	Drops4      int64 // ICMPv4 messages dropped
	Drops6      int64 // ICMPv6 messages dropped
}

ICMPStat is a collection of ICMP statistics for the current tunnel.

type IPFwdStat

type IPFwdStat struct {
	// errors
	Errs int64
	// unreachable
	Unrch int64
	// no route
	NoRoute int64
	// no endpoint
	NoHop int64
	// packet too big
	PTB int64
	// TTL timeouts
	Timeouts int64
	// drops
	Drops int64
}

IPFwdStat is a collection of IP forwarding statistics for the current tunnel.

type IPMetadata

type IPMetadata struct {
	// Proxy ID used to fetch this IP metadata.
	ID string
	// Provider that provided this IP metadata.
	ProviderURL string
	// IP address, never empty.
	IP string
	// ASN number, may be empty.
	ASN string
	// ASN organization name, may be empty.
	ASNOrg string
	// ASN domain, may be empty.
	ASNDom string
	// Country code, may be empty.
	CC string
	// City name, may be empty.
	City string
	// Address, may be empty.
	Addr string
	// Latitude, may be zero.
	Lat float64
	// Longitude, may be zero.
	Lon float64
}

type IPStat

type IPStat struct {
	// invalid destination addresses
	InvalidDst int64
	// invalid source addresses
	InvalidSrc int64
	// invalid fragments
	InvalidFrag int64
	// invalid packets
	InvalidPkt int64
	// packet errors
	Errs int64
	// packets received from l2
	Rcv int64
	// packets sent to l4
	Snd int64
	// packet receive errors from l2
	ErrRcv int64
	// packet send errors to l4
	ErrSnd int64
}

IPStat is a collection of IP statistics for the current tunnel.

type IpTree

type IpTree interface {
	// Adds value v to the cidr route.
	Add(cidr, v *Gostr) error
	// Sets cidr route to v, overwriting any previous value.
	Set(cidr, v *Gostr) error
	// Removes value v, if found.
	Esc(cidr, v *Gostr) bool
	// Deletes cidr route. Returns true if cidr was found.
	Del(cidr *Gostr) bool
	// Gets the value of cidr or "" if cidr is not found.
	Get(cidr *Gostr) (*Gostr, error)
	// Returns true if the cidr route is found.
	Has(cidr *Gostr) (bool, error)
	// Returns csv of all routes matching cidr or "".
	Routes(cidr *Gostr) *Gostr
	// Returns csv of values of all routes matching cidr or "".
	Values(cidr *Gostr) *Gostr
	// Returns the route@csv(value) of any route matching cidr or "".
	GetAny(cidr *Gostr) (*Gostr, error)
	// Returns true if any route matches cidr.
	HasAny(cidr *Gostr) (bool, error)
	// Removes values like v ("*v*") for cidr.
	EscLike(cidr, likev *Gostr) int32
	// Returns csv of all routes with any value like v matching cidr.
	RoutesLike(cidr, likev *Gostr) *Gostr
	// Returns csv of all routes with values like v for cidr.
	ValuesLike(cidr, likev *Gostr) *Gostr
	// Returns csv of all values like v for cidr.
	GetLike(cidr, likev *Gostr) *Gostr
	// Returns the longest route for cidr as "r1@csv(v)|r2@csv(v2)" or "".
	GetAll(cidr *Gostr) (*Gostr, error)
	// Deletes all routes matching cidr. Returns the number of routes deleted.
	DelAll(cidr *Gostr) int32
	// Clears the trie.
	Clear()
	// Returns the number of routes.
	Len() int
}

A IpTree is a thread-safe trie that supports insertion, deletion, and route matching IP CIDRs.

func NewIpTree

func NewIpTree() IpTree

NewIpTree returns a new IpTree.

type NICInfo

type NICInfo struct {
	Name        string
	HwAddr      string
	Addrs       string
	Mtu         int32
	Up          bool
	Running     bool
	Promisc     bool
	Lo          bool
	Arp         int32
	Forwarding4 bool
	Forwarding6 bool
}

type NICStat

type NICStat struct {
	// bytes received
	Rx string
	// packets received
	RxPkts int64
	// bytes sent
	Tx string
	// packets sent
	TxPkts int64
	// invalid packets
	Invalid int64
	// unknown l4 packets
	L4Unknown int64
	// unknown l3 packets
	L3Unknown int64
	// l4 drops
	L4Drops int64
	// drops
	Drops int64
}

NICStat is a collection of network interface statistics for the current tunnel.

type NetStat

type NetStat struct {
	NICSt  NICStat
	TUNSt  TUNStat
	NICIn  NICInfo
	IPSt   IPStat
	FWDSt  IPFwdStat
	ICMPSt ICMPStat
	TCPSt  TCPStat
	UDPSt  UDPStat
	RDNSIn RDNSInfo
	GOSt   GoStat
}

NetStat is a collection of network engine statistics.

func (*NetStat) FWD

func (n *NetStat) FWD() *IPFwdStat

FWD returns the IP forwarding statistics.

func (*NetStat) GO

func (n *NetStat) GO() *GoStat

GO returns the Go runtime statistics.

func (*NetStat) ICMP

func (n *NetStat) ICMP() *ICMPStat

ICMP returns the ICMP statistics.

func (*NetStat) IP

func (n *NetStat) IP() *IPStat

IP returns the IP statistics.

func (*NetStat) NIC

func (n *NetStat) NIC() *NICStat

NIC returns the network interface statistics.

func (*NetStat) NICINFO

func (n *NetStat) NICINFO() *NICInfo

NICI returns the network interface info.

func (*NetStat) RDNSINFO

func (n *NetStat) RDNSINFO() *RDNSInfo

RDNS returns the RDNS settings / info.

func (*NetStat) TCP

func (n *NetStat) TCP() *TCPStat

TCP returns the TCP statistics.

func (*NetStat) TUN

func (n *NetStat) TUN() *TUNStat

TUN returns the internal tunnel statistics.

func (*NetStat) UDP

func (n *NetStat) UDP() *UDPStat

UDP returns the UDP statistics.

type PipKey

type PipKey struct {
	// hex encoded 64 byte msg+cid (random)
	Msg *PipMsg
	// hex encoded 256 byte sig (unblinded signature)
	Sig string
	// hex encoded 32 byte sha256(sig) (msg signature hash)
	SigHash string
}

func PipKeyFrom

func PipKeyFrom(v *Gostr) (*PipKey, error)

func (*PipKey) V

func (p *PipKey) V() *Gostr

type PipKeyProvider

type PipKeyProvider interface {
	// Msg returns the PipMsg that this PipKeyProvider is associated with.
	// Never nil.
	Msg() *PipMsg
	// Bid uniquely identifies a blinded PipKeyProvider.
	// PipKeyProviders created from same blinded PipKeyState have the same identity.
	// If this PipKeyProvider is not yet blinded, it returns nil.
	Bid() *Gostr
	// Blind generates id:blindMsg:blindingFactor:salt:msg
	// id is a 64 byte hmac tying blindMsg to the public key
	// blindMsg is a 256 byte blinded message
	// blindingFactor is upto 256 byte random blinding factor
	// salt is 48 bytes random salt (see: hashfn)
	// msg is a 32 byte random message (see: msgsize)
	Blind() (*PipKeyState, error)
	// Finalize calculates actual signature for given blingSig blind signature.
	Finalize(blingSig *Gostr) (*PipKey, error)
}

func NewPipKeyProvider

func NewPipKeyProvider(pubjwk *Gobyte, msgOrExistingState *Gostr) (PipKeyProvider, error)

NewPipKeyProvider creates a new PipKeyProvider instance. pubjwk: JWK string of the public key of the RSA-PSS signer (for which modulus must be 2048 bits, and hash-fn must be SHA384). msgOrExistingState: if empty, a new PipKeyProvider is created with a random message, if not empty, it's the state of an existing PipKey. Typically, msgOrExistingState is got from PipKeyState.V()

func NewPipKeyProviderFromMsg

func NewPipKeyProviderFromMsg(pubjwk *Gobyte, msg *PipMsg) (PipKeyProvider, error)

NewPipKeyProviderFromMsg creates a new PipKeyProvider instance from a JWK and a msg hex string. Generating Blind() for the same msg with the same JWK will NOT result in the same PipKeyState. To restore a previous state, use NewPipKeyProvider() with the PipKeyState.V() string.

type PipKeyState

type PipKeyState struct {
	// hex encoded 64 byte id that identifies BlindMsg.
	Bid string
	// hex encoded 256 byte blind(Msg)
	BlindMsg string
	// hex encoded blinding factor (up to 256 bytes)
	R string
	// hex encoded 48 byte salt (random)
	Salt string
	// hex encoded 32 byte (client) msg (usually, random)
	// concatenated with 32 byte (client identifier) token
	Msg *PipMsg
}

func NewPipKeyStateFrom

func NewPipKeyStateFrom(v *Gostr) (*PipKeyState, error)

func (*PipKeyState) V

func (p *PipKeyState) V() *Gostr

type PipMsg

type PipMsg Gostr

PipMsg is a 64 byte hex encoded string that contains: - first 32 bytes as message (random) - next 32 bytes as client identifier (random)

func AsPipMsg

func AsPipMsg(m *Gostr) *PipMsg

AsPipMsg typecast Gostr m to PipMsg. m must be a 64 bytes hex string (32b for msg + 32b for opaque-id). Returns nil if the string m is nil or not a valid PipMsg.

func NewPipMsgWith

func NewPipMsgWith(tok *PipToken) *PipMsg

func (*PipMsg) AsGostr

func (p *PipMsg) AsGostr() *Gostr

Returns empty Gostr if p is nil or invalid PipMsg.

func (*PipMsg) Opaque

func (p *PipMsg) Opaque() *PipToken

Opaque returns the client id part of the PipMsg as hex string.

func (*PipMsg) Rotate

func (p *PipMsg) Rotate() (new *PipMsg)

Rotate creates a new PipMsg with the same opaque identifier but a different msg.

type PipToken

type PipToken Gostr

PipToken is a 32 byte random token for bespoke auth.

func Token

func Token() (*PipToken, error)

Token gnerates a 32 byte random as hex (auths dataplane ops)

type Protector

type Protector interface {
	// UIP returns ip (network-order byte) to bind given a local/remote ipp (ip:port).
	// (unused)
	UIP(ipp string) []byte
}

type Proxies

type Proxies interface {
	// Underlay creates a [NOOP] proxy (that always connects over underlying network),
	// but one that uses a custom Controller.
	// This proxy is not tracked (APIs like GetProxy won't return these).
	Underlay(id *Gostr, c Controller) Proxy
	// Add adds a proxy to this multi-transport.
	// "id" is a free-form unique identifier for this proxy, except:
	// "id" for WireGuard proxies must be prefixed with [WG]
	// "url" is WireGuard UAPI configuration.
	// For HTTP1 and SOCKS5 proxies, "url" must be of the form:
	// scheme://usr:pwd@domain.tld:port/p/a/t/h?q&u=e&r=y#f,r
	// where scheme is "http" or "socks5", usr and/or pwd are optional
	// port is the port number, and domain.tld could also be ip address.
	AddProxy(id, url *Gostr) (Proxy, error)
	// Remove removes a transport from this multi-transport.
	RemoveProxy(id *Gostr) bool
	// GetProxy returns a transport from this multi-transport.
	GetProxy(id *Gostr) (Proxy, error)
	// TestHop returns empty diag if origin can hop to via,
	// otherwise returns a diagnosis of why it couldn't.
	// Only WireGuard via & origin are supported, for now.
	TestHop(via, origin *Gostr) (diag *Gostr)
	// Hop chains two proxies in the order of origin dialing through via.
	// Only WireGuard via & origin are supported, for now.
	Hop(via, origin *Gostr) error
	// Router returns a lowest common denomination router for this multi-transport.
	Router() Router
	// RPN returns the Rethink Proxy Network api.
	Rpn() Rpn
	// Refresh re-registers proxies and returns a csv of active ones.
	RefreshProxies() *Gostr
}

type Proxy

type Proxy interface {
	// ID returns the ID of this proxy.
	ID() *Gostr
	// Type returns the type of this proxy.
	Type() *Gostr
	// Returns x.Router.
	Router() Router
	// Client returns a client that uses this proxy.
	Client() Client
	// GetAddr returns the address of this proxy.
	GetAddr() *Gostr
	// DNS returns the ip:port or doh/dot url or dnscrypt stamp for this proxy.
	DNS() *Gostr
	// Status returns the status of this proxy.
	Status() int
	// Ping pings this proxy.
	Ping() bool
	// Pause pauses this proxy.
	Pause() bool
	// Resume resumes this proxy.
	Resume() bool
	// Stop stops this proxy.
	Stop() error
	// Refresh re-registers this proxy, if necessary.
	Refresh() error
}

type ProxyListener

type ProxyListener interface {
	// OnProxyAdded is called when a proxy is added.
	OnProxyAdded(id *Gostr)
	// OnProxyRemoved is called when a proxy is removed except when all
	// proxies are stopped, in which case OnProxiesStopped is called.
	OnProxyRemoved(id *Gostr)
	// OnProxyStopped is called when a proxy is stopped instead of being
	// removed (that is, this callback is not called in all proxy stop scenarios).
	// A stopped proxy, if added again, is replaced/updated instead; and subsequently,
	// the onProxyAdded callback is invoked.
	OnProxyStopped(id *Gostr)
	// OnProxiesStopped is called when all proxies are stopped.
	// Note: OnProxyRemoved is not called for each proxy, even
	// if they are removed instead of being merely "stopped".
	OnProxiesStopped()
}

ProxyListener is a listener for proxy events.

type RDNS

type RDNS interface {
	// SetStamp sets the rethinkdns blockstamp.
	SetStamp(*Gostr) error
	// GetStamp returns the current rethinkdns blockstamp.
	GetStamp() (*Gostr, error)
	// StampToNames returns csv group:names of blocklists in the given stamp s.
	StampToNames(s *Gostr) (*Gostr, error)
	// FlagsToStamp returns a blockstamp for given csv blocklist-ids, if valid.
	FlagsToStamp(csv *Gostr, enctyp int) (*Gostr, error)
	// StampToFlags retruns csv blocklist-ids given a valid blockstamp s.
	StampToFlags(s *Gostr) (*Gostr, error)
}

type RDNSInfo

type RDNSInfo struct {
	Open      bool
	Debug     bool
	Recording bool

	Looping                 bool
	Slowdown                bool
	NewWireGuard            string
	Transparency            bool
	HappyEyeballs           bool
	PanicTest               bool
	SystemDNSForUndelegated bool
	SetUserAgent            bool
	OwnTunFd                bool
	PortForward             bool
	EIMEIF                  string

	Dialer4    bool
	Dialer6    bool
	DialerOpts string
	TunMode    string

	DNSPreferred string
	DNSDefault   string
	DNSSystem    string
	DNS          string
	ALG          string

	ProxiesHas4 bool
	ProxiesHas6 bool
	ProxyLastOK string
	ProxySince  string
	ProxyStatus string
	Proxies     string

	AutoMode          string
	AutoDialsParallel bool

	LinkMTU string

	OpenConnsTCP  string
	OpenConnsUDP  string
	OpenConnsICMP string
}

type RDNSResolver

type RDNSResolver interface {
	// SetRdnsLocal sets the local rdns resolver.
	SetRdnsLocal(trie, rank, conf, filetag string) error
	// GetRdnsLocal returns the local rdns resolver.
	GetRdnsLocal() (RDNS, error)
	// SetRdnsRemote sets the remote rdns resolver.
	SetRdnsRemote(filetag string) error
	// GetRdnsRemote returns the remote rdns resolver.
	GetRdnsRemote() (RDNS, error)
	// Translate enables or disables ALG/fixed responses
	Translate(bool)
}

type RadixTree

type RadixTree interface {
	// Adds k to the trie. Returns true if k was not already in the trie.
	Add(k *Gostr) bool
	// Sets k to v in the trie, overwriting any previous value.
	Set(k, v *Gostr)
	// Deletes k from the trie. Returns true if k was in the trie.
	Del(k *Gostr) bool
	// Gets the value of k from the trie or "" if k is not in the trie.
	Get(k *Gostr) *Gostr
	// Returns true if k is in the trie.
	Has(k *Gostr) bool
	// Returns the value of the longest prefix of k in the trie or "".
	GetAny(prefix *Gostr) *Gostr
	// Returns true if any key in the trie has the prefix.
	HasAny(prefix *Gostr) bool
	// Deletes all keys in the trie with the prefix. Returns the number of keys deleted.
	DelAll(prefix *Gostr) int32
	// Clears the trie.
	Clear()
	// Returns the number of keys in the trie.
	Len() int
}

A RadixTree is a thread-safe trie that supports insertion, deletion, and prefix matching.

func NewRadixTree

func NewRadixTree() RadixTree

type ResolverListener

type ResolverListener interface {
	// OnDNSAdded is called when a new DNS transport with id is added.
	OnDNSAdded(id *Gostr)
	// OnDNSRemoved is called when a DNS transport with id is removed, except
	// when the transport is stopped, then OnDNSStopped is called instead.
	OnDNSRemoved(id *Gostr)
	// OnDNSStopped is called when all DNS transports are stopped. Note:
	// OnDNSRemoved is not called for each transport even if they are
	// being removed and not just stopped.
	OnDNSStopped()
}

type Router

type Router interface {
	// IP4 returns true if this router supports IPv4.
	IP4() (y bool)
	// IP6 returns true if this router supports IPv6.
	IP6() (y bool)
	// MTU returns the MTU of this router.
	MTU() (mtu int, err error)
	// Stats returns the stats of this router.
	Stat() (s *RouterStats)
	// Via returns the gateway for this router, if any.
	Via() (gw Proxy, err error)
	// Reaches returns true if any host:port or ip:port is dialable.
	Reaches(hostportOrIPPortCsv *Gostr) (y bool)
	// Contains returns true if this router can route ipprefix.
	Contains(ipprefix *Gostr) (y bool)
}

type RouterStats

type RouterStats struct {
	// addresses (csv) of the router
	Addrs string
	// bytes received
	Rx int64
	// bytes transmitted
	Tx int64
	// receive error count
	ErrRx int64
	// transmit error count
	ErrTx int64
	// last (most recent) receive in millis
	LastTx int64
	// last (most recent) transmit in millis
	LastRx int64
	// last successful receive in millis
	LastGoodRx int64
	// last successful transmit in millis
	LastGoodTx int64
	// last (most recent) handshake or ping or connect millis
	LastOK int64
	// last refresh time in millis
	LastRefresh int64
	// uptime in millis
	Since int64
	// Current proxy status
	Status string
	// Extra is extra info about this router
	Extra string
}

RouterStats lists interesting stats of a Router.

type Rpn

type Rpn interface {
	// RegisterSE registers a new SurfEasy user.
	RegisterSE() error
	// RegisterWin is alias for RegisterWin.
	RegisterWin(entitlementOrStateJson *Gobyte) (json *Gobyte, err error)
	// UnregisterWin unregisters a Windscribe installation.
	UnregisterWin() bool
	// UnregisterSE unregisters a SurfEasy user.
	UnregisterSE() bool
	// TestWin connects to the Windscribe gateway and returns its IP if reachable.
	TestWin() (ips *Gostr, errs error)
	// TestSE connects to some SurfEasy IPs and returns reachable ones.
	TestSE() (ips *Gostr, errs error)
	// TestExit64 connects to public NAT64 endpoints and returns reachable ones.
	TestExit64() (ips *Gostr, errs error)
	// Win returns a Windscribe WireGuard proxy.
	Win() (wg RpnProxy, err error)
	// Pip returns a RpnWs proxy.
	Pip() (ws RpnProxy, err error)
	// Exit64 returns a Exit proxy hopping over preset publicly-available
	// NAT64 proxies.
	Exit64() (nat64 RpnProxy, err error)
	// SE returns a SurfEasy proxy.
	SE() (se RpnProxy, err error)
}

type RpnAcc

type RpnAcc interface {
	// Who returns identifier for this account; may be empty.
	Who() *Gostr
	// State returns the state (as json) of the account.
	State() (*Gobyte, error)
	// Created returns the time (unix millis) currently active account was created.
	Created() int64
	// Expires returns the time (unix millis) currently active account expires.
	Expires() int64
	// Locations returns RpnServers encapsulating this proxy's worldwide server presence.
	Locations() (RpnServers, error)
	// Update updates the account creating new state.
	Update() (newstate *Gobyte, err error)
}

type RpnProxy

type RpnProxy interface {
	Proxy
	RpnAcc
	// Fork adds proxy for country code, cc.
	Fork(cc *Gostr) (Proxy, error)
	// Purge removes proxy for country code, cc.
	Purge(cc *Gostr) bool
	// Get returns proxy for country code, cc.
	Get(cc *Gostr) (Proxy, error)
	// Kids returns csv of forked proxy PIDs, excluding this one.
	Kids() (csvpids *Gostr)
}

type RpnServer

type RpnServer struct {
	// Name of the server, if any.
	Name string
	// CSV of IP:Port and/or Domain:Port
	Addrs string
	// Country code of the location.
	CC string
	// City name of the location.
	City string
	// Key for RpnProxy.Fork() to get an RpnProxy instance for this RpnServer.
	Key string
	// Load score of this server (lower is better)
	Load int32
	// Link speed in Mbps (higher is better).
	Link int32
	// Number of active servers in this CC+City.
	Count int32
}

type RpnServers

type RpnServers interface {
	// Get returns the RpnServer at index i; errors if i is out of bounds.
	Get(i int) (*RpnServer, error)
	// Len returns the number of RpnServers.
	Len() int
	// Json returns the RpnServer struct as JSON bytes.
	Json() (*Gobyte, error)
}

type Server

type Server interface {
	// Sets the proxy as the next hop.
	Hop(p Proxy) error
	// ID returns the ID of the server.
	ID() string
	// Start starts the server.
	Start() error
	// Type returns the type of the server.
	Type() string
	// Addr returns the address of the server.
	GetAddr() string
	// Status returns the status of the server.
	Status() int
	// Stop stops the server.
	Stop() error
	// Refresh re-registers the server.
	Refresh() error
}

type ServerListener

type ServerListener interface {
	// SvcRoute decides how to forward an incoming connection over service (sid).
	SvcRoute(sid, pid, network, sipport, dipport string) *Tab
	// OnSvcComplete reports summary after a connection closes.
	OnSvcComplete(*ServerSummary)
}

ServerListener receives Server events.

type ServerSummary

type ServerSummary struct {
	// http1, socks5, etc.
	Type string
	// Server ID.
	SID string
	// Proxy ID (hop) that handled egress, if any.
	PID string
	// Connection id
	CID string
	// Total uploaded (bytes).
	Tx int64
	// Total downloaded (bytes).
	Rx int64
	// Conn open duration (millis).
	Duration int64
	// Error messages, if any.
	Msg string
}

type Services

type Services interface {
	// Add adds a server.
	AddServer(id, url string) (Server, error)
	// Bridge bridges or unbridges server with proxy.
	Bridge(serverid, proxyid string) error
	// Remove removes a server.
	RemoveServer(id string) (ok bool)
	// RemoveAll removes all servers.
	RemoveAll()
	// Get returns a Server.
	GetServer(id string) (Server, error)
	// Refresh re-registers servces and returns a csv of active ones.
	RefreshServers() (active string)
}

type TCPStat

type TCPStat struct {
	Active      int64 // connecting
	Passive     int64 // listening
	Est         int64 // current established
	EstClo      int64 // established but closed
	EstRst      int64 // established but RST
	EstTo       int64 // established but timeout
	Con         int64 // current connected
	ConFail     int64 // failed connect attempts
	PortFail    int64 // failed port reservations
	SynDrop     int64 // syns dropped
	AckDrop     int64 // acks dropped
	ErrChecksum int64 // bad checksums
	ErrRcv      int64 // invalid recv segments
	ErrSnd      int64 // segment send errors
	Rcv         int64 // segments received
	Snd         int64 // segments sent
	Retrans     int64 // retransmissions
	Timeouts    int64 // connection timeouts
	Drops       int64 // drops by max inflight threshold
}

TCPStat is a collection of TCP statistics for the current tunnel.

type TUNStat

type TUNStat struct {
	Open     bool
	Up       bool
	Mtu      int32
	Sid      int
	EpStats  string
	PcapMode string
}

type Tab

type Tab struct {
	// CID is the ID of this connection.
	CID string
	// Block is true if this connection should be blocked.
	Block bool
}

type UDPStat

type UDPStat struct {
	ErrChecksum int64 // bad checksums
	ErrRcv      int64 // recv errors
	ErrSnd      int64 // send errors
	Snd         int64 // packets sent
	Rcv         int64 // packets received
	PortFail    int64 // unknown port
	Drops       int64 // rcv buffer errors
}

UDPStat is a collection of UDP statistics for the current tunnel.

type WgKey

type WgKey interface {
	// IsZero returns true if the key is all zeros.
	IsZero() bool
	// Base64 returns the key as a base64-encoded string.
	Base64() *Gostr
	// Hex returns the key as a hex-encoded string.
	Hex() *Gostr
	// Mult returns the key multiplied by the basepoint (curve25519).
	Mult() WgKey
}

func NewWgPrivateKey

func NewWgPrivateKey() (WgKey, error)

func NewWgPrivateKeyFrom

func NewWgPrivateKeyFrom(k [klen]byte) WgKey

func NewWgPrivateKeyOf

func NewWgPrivateKeyOf(b64 string) (WgKey, error)