wgclient

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: May 21, 2026 License: Apache-2.0 Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
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(s string) bool

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(s string) (Config, error)

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

func FromConnStr(s string) (Config, error)

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(s string) (Config, error)

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).

func (*Config) Validate

func (c *Config) Validate() error

Validate returns an error if cfg is missing fields required by its declared Transport.

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 EventKind

type EventKind string

EventKind discriminates the union inside Event.

const (
	EventStatus EventKind = "status"
	EventLog    EventKind = "log"
)

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 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 New

func New() *Service

New returns a fresh Service in PhaseIdle.

func (*Service) BridgeStats

func (s *Service) BridgeStats() string

BridgeStats returns the live SFU bridge counters as a one-liner suitable for log diagnostics. "" if no bridge is currently active.

func (*Service) Logger

func (s *Service) Logger() *log.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

func (s *Service) RecentLogs(limit int) []LogLine

RecentLogs returns the last `limit` captured log lines (newest last). limit ≤ 0 means "all".

func (*Service) SetVerbose

func (s *Service) SetVerbose(on bool)

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

func (s *Service) Start(ctx context.Context, cfg Config) error

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

func (s *Service) Status() 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.

func (*Service) Subscribe

func (s *Service) Subscribe() (<-chan Event, func())

Subscribe returns a buffered channel of events plus a cancel func that detaches the subscription. Slow consumers have events dropped.

func (*Service) Verbose

func (s *Service) Verbose() bool

Verbose returns the current verbose flag — handy for the JS frontend to render initial UI state on first load.

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 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"`
}

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"]

	// PresharedKey — optional 32-byte base64 WG PSK. Set when the
	// 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.

func (WGParams) Valid

func (w WGParams) Valid() bool

Valid reports whether enough fields are populated to bring up an auto-WG tunnel. Endpoint is allowed to be empty — Service.Start fills it from cfg.ListenAddr in that case.

Jump to

Keyboard shortcuts

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