Documentation
¶
Overview ¶
Package wgclient encapsulates the goloom client-side tunnel (Telemost / WB-Stream LiveKit → local UDP for WireGuard userspace) behind an event-driven Service API. The same package backs both the CLI (cmd/goloom-wg-client) and the GUI (cmd/goloom-wg-gui), so client behaviour stays in one place.
Lifecycle:
svc := wgclient.New()
defer svc.Stop()
events, cancel := svc.Subscribe()
defer cancel()
go func() {
for ev := range events {
// ev.Status — phase/transport/tx/rx changes
// ev.Log — log lines emitted by the running session
}
}()
svc.Start(ctx, cfg) // returns immediately; runs in background
<-ctx.Done() // user wants to quit
svc.Stop() // graceful tunnel teardown
Concurrency: all public methods are safe to call from any goroutine. Subscribe channels are non-blocking — slow consumers drop events rather than back-pressure the producer.
Index ¶
- Variables
- func IsVKTurnProxyLink(s string) bool
- type Config
- type Event
- type EventKind
- type LivenessSnapshot
- type LogLine
- type Phase
- type SRTPBind
- func (b *SRTPBind) BatchSize() int
- func (b *SRTPBind) Close() error
- func (b *SRTPBind) Liveness() LivenessSnapshot
- func (b *SRTPBind) Open(uint16) ([]conn.ReceiveFunc, uint16, error)
- func (b *SRTPBind) ParseEndpoint(string) (conn.Endpoint, error)
- func (b *SRTPBind) Send(bufs [][]byte, _ conn.Endpoint) error
- func (b *SRTPBind) SetLogger(lg *log.Logger)
- func (b *SRTPBind) SetMark(uint32) error
- type Service
- func (s *Service) BridgeStats() string
- func (s *Service) Logger() *log.Logger
- func (s *Service) RecentLogs(limit int) []LogLine
- func (s *Service) SetVerbose(on bool)
- func (s *Service) Start(ctx context.Context, cfg Config) error
- func (s *Service) Status() Status
- func (s *Service) Stop()
- func (s *Service) Subscribe() (<-chan Event, func())
- func (s *Service) Verbose() bool
- type Status
- type TURNAllocation
- type TURNCreds
- type VKTurnSRTPParams
- type WGParams
Constants ¶
This section is empty.
Variables ¶
var ErrAlreadyRunning = errors.New("wgclient: session already running")
ErrAlreadyRunning is returned by Service.Start when a session is already active. Stop the existing session first.
Functions ¶
func IsVKTurnProxyLink ¶ added in v1.0.4
IsVKTurnProxyLink reports whether s looks like a vkturnproxy:// connection link the caller can pass to FromVKTurnProxyLink. Cheap prefix check — full parsing happens in From… below.
Types ¶
type Config ¶
type Config struct {
Transport string `json:"transport"` // empty == "telemost"
Meeting string `json:"meeting"`
LiveKitRoomURL string `json:"livekit_room_url"`
LiveKitAccessToken string `json:"livekit_access_token"`
LiveKitCookies string `json:"livekit_cookies"`
VKCallsRole string `json:"vk_calls_role"` // empty == "caller" for clients
VKCallsCodec string `json:"vk_calls_codec"`
DisplayName string `json:"display_name"`
ListenAddr string `json:"listen_addr"` // default 127.0.0.1:51820
// AutoWG, when true and WG is populated, makes the service bring
// up a wintun adapter and run a wireguard-go userspace tunnel
// itself instead of expecting an external WireGuard for Windows
// install to dial 127.0.0.1:51820. Implemented on Windows only.
AutoWG bool `json:"auto_wg"`
// WG carries the per-client WireGuard parameters that the admin
// panel embeds in a connstr. Used only when AutoWG is on; the
// classic flow still works without these because the user's own
// WG client knows the keys via the wg.conf they downloaded.
WG WGParams `json:"wg"`
// VKTurnSRTP carries the relay-family knobs that arrive in a
// vkturnproxy:// link. Honoured only when Transport=="vk-turn-srtp"
// (or "vk-turn" for the legacy path); ignored otherwise.
VKTurnSRTP VKTurnSRTPParams `json:"vk_turn_srtp,omitzero"`
}
Config is the input to Service.Start. Mirrors the YAML/connstr schema used by the standalone client. Per Transport:
"telemost" — Meeting required
"livekit-wb-stream" — LiveKit* fields required (run admin webview-auth)
"vk-calls" — Meeting required (VK call link); VKCallsRole
optional ("caller" default for clients).
ListenAddr defaults to 127.0.0.1:51820.
func FromAnyLink ¶ added in v1.0.4
FromAnyLink dispatches between goloom:// (via FromConnStr) and vkturnproxy:// (via FromVKTurnProxyLink) by inspecting the prefix. Used by the CLI / GUI entry points so the operator can paste either form into the same input.
func FromConnStr ¶
FromConnStr decodes a goloom:// connection string into a Config. Connstrs created before multi-transport implicitly resolve to transport=telemost (Params.Transport == ""); newer connstrs carry the transport explicitly. WB-Stream credentials still arrive out-of-band (admin webview-auth flow) — they're never embedded in the connstr.
If the connstr embeds WG client params (admin panel's auto-provision flow), they're carried into Config.WG so the GUI can offer auto-WG without requiring a separate wg.conf import.
func FromVKTurnProxyLink ¶ added in v1.0.4
FromVKTurnProxyLink decodes a vkturnproxy://import?data=<base64> URL into a wgclient.Config. Sets Transport to "vk-turn-srtp" when the payload's useSrtp is true; otherwise "vk-turn" (the legacy DTLS+WG path).
Validation: only fields strictly required by the chosen transport are checked here; the rest is deferred to Config.Validate. Errors are shaped to be useful to the operator (mentions which JSON field).
type Event ¶
type Event struct {
Kind EventKind `json:"kind"`
Status *Status `json:"status,omitempty"`
Log *LogLine `json:"log,omitempty"`
}
Event is the wire format pushed to subscribers. Exactly one of Status / Log is non-nil per event.
type LivenessSnapshot ¶ added in v1.1.1
type LivenessSnapshot struct {
NumConns int
Alive int
Dead int
ServerProbed bool
LastPongAgoMs []int64 // -1 = never pong'd
}
LivenessSnapshot reports per-conn state — used by diagnostic callers (admin UI / Service status). All counters are read with atomic.Load so the snapshot is point-in-time consistent within each conn (no cross-conn ordering guarantee).
type LogLine ¶
type LogLine struct {
Time time.Time `json:"time"`
Level string `json:"level"` // "info" | "warn" | "error"
Text string `json:"text"`
}
LogLine is one line captured from the underlying session logger.
type Phase ¶
type Phase string
Phase is a coarse-grained tunnel state suitable for surfacing in a UI.
const ( PhaseIdle Phase = "idle" // never started, or after Stop() PhaseConnecting Phase = "connecting" // transport.Connect in flight PhaseHandshaking Phase = "handshaking" // peer found, in-band handshake PhaseRelaying Phase = "relaying" // bridge.Run live PhaseReconnecting Phase = "reconnecting" // backoff window between sessions PhaseError Phase = "error" // fatal: bad config, no transport, etc. )
type SRTPBind ¶ added in v1.1.0
type SRTPBind struct {
// contains filtered or unexported fields
}
SRTPBind implements conn.Bind over one-or-many SRTP-wrapped conns.
func NewSRTPBind ¶ added in v1.1.0
NewSRTPBind takes ownership of conns — Close() will close them all. Empty or nil slice is a programmer error. logger may be nil (silent probe loop); usually you want to wire it to the session's *log.Logger.
func (*SRTPBind) Liveness ¶ added in v1.1.1
func (b *SRTPBind) Liveness() LivenessSnapshot
Liveness returns a point-in-time snapshot of the probe state.
func (*SRTPBind) ParseEndpoint ¶ added in v1.1.0
func (*SRTPBind) Send ¶ added in v1.1.0
Send round-robins each buf over the pool. Dead conns are skipped; if every conn is dead, returns net.ErrClosed so WG's retry loop surfaces it as a handshake failure (which the session supervisor then handles).
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service manages a single tunnel session lifecycle. Construct one per process — concurrent sessions aren't supported (one bridge, one local UDP port).
func (*Service) BridgeStats ¶
BridgeStats returns the live SFU bridge counters as a one-liner suitable for log diagnostics. "" if no bridge is currently active.
func (*Service) Logger ¶
Logger exposes the captured *log.Logger so external code can pipe through the same capture pipeline (e.g. the CLI tool reusing this package).
func (*Service) RecentLogs ¶
RecentLogs returns the last `limit` captured log lines (newest last). limit ≤ 0 means "all".
func (*Service) SetVerbose ¶
SetVerbose toggles whether trace-classified lines flow through the log pipeline. When false (default), they're dropped at the entry point — no ring-buffer growth, no event broadcast, zero CPU spent formatting them per line. When true, every captured line goes through normally.
Switching the flag at runtime affects only future lines; lines already in the ring buffer keep their original level so a later RecentLogs call still surfaces what was captured at that level.
func (*Service) Start ¶
Start spawns the supervise loop in the background. Returns immediately. Subsequent Start calls while a session is active are rejected with ErrAlreadyRunning.
func (*Service) Status ¶
Status returns a snapshot of the current state, augmented with live byte counters from the running bridge if any.
func (*Service) Stop ¶
func (s *Service) Stop()
Stop signals graceful shutdown of any running session and blocks until the supervise loop has exited. Safe to call when idle.
type Status ¶
type Status struct {
Phase Phase `json:"phase"`
// SubPhase — finer-grained step внутри coarse Phase. Например
// под Phase=Connecting может быть SubPhase="captcha". UI рендерит
// как secondary caption рядом с phase chip. Совпадает по семантике
// с mobile/api.go::emitPhase.
SubPhase string `json:"sub_phase,omitempty"`
Detail string `json:"detail,omitempty"`
Transport string `json:"transport"` // "telemost" | "livekit-wb-stream"
Meeting string `json:"meeting,omitempty"`
PeerID string `json:"peer_id,omitempty"`
LocalAddr string `json:"local_addr,omitempty"` // "127.0.0.1:51820"
StartedAt time.Time `json:"started_at,omitempty"`
LastError string `json:"last_error,omitempty"`
TxPackets uint64 `json:"tx_packets"`
TxBytes uint64 `json:"tx_bytes"`
RxPackets uint64 `json:"rx_packets"`
RxBytes uint64 `json:"rx_bytes"`
}
Status snapshots the running session. Returned by Service.Status and pushed inside Event.Status on every change.
type TURNAllocation ¶ added in v1.1.0
type TURNAllocation struct {
// contains filtered or unexported fields
}
TURNAllocation owns the underlying TURN client + the conn it runs over (UDP or TCP, see TURNCreds.UseTCP). Closing it tears both down in the right order.
func AllocateTURN ¶ added in v1.1.0
func AllocateTURN(ctx context.Context, turnAddr, peerAddrStr string, creds TURNCreds) (*TURNAllocation, error)
AllocateTURN dials turnAddr, runs the TURN ALLOCATE handshake using creds, and returns a handle whose Relay() can be wrapped by vkturnsrtp.Client. peerAddrStr is resolved up front so wrappers downstream don't have to.
ctx bounds the dial + handshake setup; once the returned handle is in hand, its lifetime is decoupled from ctx (call Close()).
Transport (UDP vs TCP) is taken from creds.UseTCP.
func (*TURNAllocation) Close ¶ added in v1.1.0
func (a *TURNAllocation) Close()
func (*TURNAllocation) PeerAddr ¶ added in v1.1.0
func (a *TURNAllocation) PeerAddr() *net.UDPAddr
PeerAddr is the resolved goloom-server address that wrapped senders should target via relay.WriteTo.
func (*TURNAllocation) Relay ¶ added in v1.1.0
func (a *TURNAllocation) Relay() net.PacketConn
Relay is the TURN-relayed net.PacketConn. Reads return packets already de-framed (no ChannelData header); writes need a destination addr — typically [PeerAddr] for the production path.
type TURNCreds ¶ added in v1.1.0
TURNCreds is the long-term auth bundle returned by VK's calls.getAnonymousToken + joinConversationByLink chain.
UseTCP selects the iOS↔TURN-relay control transport. TCP is the anton48 build128+ default and is strongly recommended: empirically VK applies a per-credential allocation-rate throttle that hits 36-58% of UDP allocate attempts but ~0% on TCP (introduced 2026-05-18). UDP path is kept as an escape hatch for networks that block TCP-to-relay altogether.
type VKTurnSRTPParams ¶ added in v1.0.4
type VKTurnSRTPParams struct {
// PeerAddress — goloom server's vk-turn(-srtp) listener
// (e.g. "vps.example.com:56001"). Required.
PeerAddress string `json:"peer_address"`
// UseWrap (legacy vk-turn only): toggle the ChaCha20-XOR
// obfuscation layer. Ignored when Transport=="vk-turn-srtp".
UseWrap bool `json:"use_wrap,omitempty"`
// WrapKeyHex (legacy vk-turn only): 64-hex-char shared key for
// the WRAP layer. Required when UseWrap is true; otherwise unused.
WrapKeyHex string `json:"wrap_key_hex,omitempty"`
// NumConnections — parallel TURN allocations to keep open. Anton48
// defaults to 10; effective per-allocation throughput stays at the
// VK-shaped cap (~9 KB/s on legacy DTLS+WG, much higher on SRTP).
// Zero falls back to the implementation default.
NumConnections int `json:"num_connections,omitempty"`
// MTU for the WG interface. Zero → impl default (1280 for SRTP).
MTU int `json:"mtu,omitempty"`
// UseUDPForTURN forces the iOS↔TURN control channel onto UDP.
// Default false → TCP, which matches anton48 build128+ default
// and bypasses VK's per-credential allocation-rate throttle
// (introduced 2026-05-18): empirically ~0% quota-errors on TCP
// vs 36-58% on UDP for the same cred. Flip to true only if your
// network blocks or throttles TCP-to-relay and you'd rather take
// the allocation-rate hit than fail outright.
//
// Independent of the SRTP / DTLS+WG transport choice — this
// controls only the leg between the goloom client and the VK
// TURN node.
UseUDPForTURN bool `json:"use_udp_for_turn,omitempty"`
}
VKTurnSRTPParams is the per-session knob set for the vk-turn / vk-turn-srtp client paths. Populated from a vkturnproxy:// link or set manually by an operator running the CLI client.
type WGParams ¶
type WGParams struct {
ClientPrivateKey string `json:"client_private_key"` // base64
ServerPublicKey string `json:"server_public_key"` // base64
ClientAddr string `json:"client_addr"` // CIDR like 10.66.1.2/24
Endpoint string `json:"endpoint"` // typically same as ListenAddr
DNS []string `json:"dns,omitempty"` // ["1.1.1.1","8.8.8.8"]
// server side has a PSK on its peer (vk-turn / vk-turn-srtp
// inbounds always do; classic Telemost / VK Calls don't).
PresharedKey string `json:"preshared_key,omitempty"`
}
WGParams is the embedded WireGuard config for the auto-WG path. Field names match the connstr schema in internal/connstr.