mobile

package
v1.1.1 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.

README

Goloom Mobile SDK

Embed the Goloom tunnel into Android and iOS VPN apps. The SDK supports all three transports — Telemost, WB Stream, and VK Calls.

Pre-built artifacts

To skip the gomobile build, the latest stable Android .aar is committed at:

mobile/dist/goloom.aar

Drop it into app/libs/ of your Android project and you're good to go.

iOS .xcframework is not pre-built (requires a macOS host) — build it locally with the steps below.

Architecture

                ┌──────────────────────────────────────────────────────┐
                │              Mobile app (Kotlin / Swift)              │
                │                                                       │
                │   ┌─────────────────┐    ┌──────────────────┐         │
                │   │  WireGuard      │    │  Goloom relay    │         │
                │   │  userspace ─────────→  (gomobile .aar  │         │
                │   │   (embedded)    │    │   /xcframework)  │         │
                │   └────────┬────────┘    └────────┬─────────┘         │
                │            │ UDP to 127.0.0.1     │                   │
                │            └──────────────────────┘                   │
                │                       │                                │
                │                       │ WebRTC (Telemost / VK / LK)    │
                └───────────────────────┼───────────────────────────────┘
                                        │
                                        ▼
                                ┌─────────────────┐
                                │  goloom-wg-     │
                                │  server (VPS)   │
                                │  + WireGuard    │
                                └────────┬────────┘
                                         │
                                         ▼ Internet

The mobile app:

  1. Asks the OS for VPN permission (VpnService on Android, NETunnelProvider on iOS).
  2. Calls Mobile.NewClient().Connect(connStr, "127.0.0.1:51820") — joins the carrier service, completes the goloom handshake, starts a UDP listener.
  3. Receives back a ConnectResult carrying the WireGuard config, the local listen address, and the list of carrier IPs that must bypass the VPN.
  4. Builds the platform VpnService.Builder / NEPacketTunnelNetworkSettings, calls establish(), takes the resulting TUN file descriptor, and feeds it to the SDK via client.AdoptTun(fd, wgUserspaceConfig).

The userspace WireGuard runs inside the same .aar / .xcframework, so there is no dependency on wireguard-android or WireGuardKit.

Build

Android
export ANDROID_NDK_HOME=$HOME/Android/Sdk/ndk/26.1.10909125
go install golang.org/x/mobile/cmd/gomobile@latest
gomobile init
./scripts/build-android.sh

Output: build/android/goloom.aar (≈ 16 MB, arm64+arm). Drop it into app/libs/ of your Android Studio project, or commit it back into mobile/dist/goloom.aar to ship a new SDK version.

iOS (macOS host required)
go install golang.org/x/mobile/cmd/gomobile@latest
gomobile init
gomobile bind -target=ios -o build/ios/Goloom.xcframework ./mobile

Output: build/ios/Goloom.xcframework. Drag into your Xcode project (Frameworks group, "Embed & Sign").

Reference clients

The reference Android client lives at Pinnss/goloom-android — full Compose UI, profile import/export, per-app split tunnel, log viewer, captcha WebView, auto-reconnect.

iOS reference client is TBD.

Go API

// Package mobile (gomobile-friendly subset of types):
type Client struct{}

func NewClient() *Client
func (c *Client) SetSocketProtector(p SocketProtector)            // Android only
func (c *Client) SetLogSink(s LogSink)
func (c *Client) SetPhaseListener(l PhaseListener)                // connection-phase callbacks
func (c *Client) SetBrowserLauncher(b BrowserLauncher)            // VK captcha WebView hook
func (c *Client) SetVKTargetMeeting(url string)                   // VK lobby flow target
func (c *Client) SetVKProfileStorePath(path string)               // VK captcha replay pool

func (c *Client) Connect(connStr, listenAddr string) (string, error)  // returns ConnectResult JSON
func (c *Client) AdoptTun(fd int64, wgUserspaceConfig string) error
func (c *Client) Disconnect()
func (c *Client) IsConnected() bool
func (c *Client) StatsJSON() string

ConnectResult JSON shape:

{
  "display_name": "anonymous",
  "peer_id": "26375971-…",
  "listen_addr": "127.0.0.1:51820",
  "wg_endpoint": "127.0.0.1:51820",
  "carrier_ips": ["87.250.251.10", "..."],
  "wg_client_config": "[Interface]\nPrivateKey = …\nAddress = 10.66.1.2/24\n…",
  "wg_client_addr":   "10.66.1.2/24"
}

The admin panel embeds the client's WG private key, the server's WG public key, and the per-inbound subnet inside the goloom:// connection string, so the mobile app gets everything it needs from a single QR scan — no separate .conf import.

Limitations

  • iOS background: Apple kills the Network Extension when memory-pressured. The relay needs to be resilient to NE restarts.
  • Power: video-stream-as-tunnel keeps the radio busy → battery cost. Implement an idle sleep when WG hasn't sent in N seconds.
  • DPI: traffic blends in as video to the carrier domain — but a deep traffic analyser could spot the absence of real-camera entropy.

Documentation

Overview

Package mobile is the gomobile-friendly entry point for embedding the goloom tunnel into Android and iOS apps.

Build:

gomobile bind -target=android -o build/goloom.aar       ./mobile
gomobile bind -target=ios     -o build/Goloom.xcframework ./mobile

Usage from Kotlin (Android):

val client = Goloom.newClient()
client.setSocketProtector(object : SocketProtector { override fun protect(fd: Long) = vpnService.protect(fd.toInt()) })
val ipsJSON = client.connect("goloom://...", "127.0.0.1:51820")
// pass ipsJSON to VpnService.Builder.addDisallowedApplication / addRoute split-tunnel logic

Usage from Swift (iOS):

let client = MobileNewClient()
let ipsJSON = client?.connect("goloom://...", listenAddr: "127.0.0.1:51820", error: ...)
// pass ipsJSON to NEPacketTunnelNetworkSettings excluded routes

Constraints: gomobile only accepts basic types (string, int, bool, []byte, error) and exported pointer-to-struct types as parameters/returns. No slices of strings, no maps, no channels, no generics. We work around this by serialising structured data as JSON strings.

Index

Constants

View Source
const (
	ErrUnknown           = 0
	ErrInvalidConnString = 1 // connection string couldn't be decoded
	ErrSessionSetup      = 2 // Telemost WebRTC setup failed (network/DNS/blocked)
	ErrPeerWaitTimeout   = 3 // joined the meeting but no peer showed up
	ErrHandshake         = 4 // in-tunnel HELLO/ACK timed out
	ErrAlreadyConnected  = 5 // Connect called while a session is live
	ErrCancelled         = 6 // context cancelled (Disconnect/app shutdown)
)

Error codes classifying Connect failures. Plain int constants so gomobile exposes them to Java/Swift as static fields the native code can compare against. Values are stable across releases; new codes are appended at the end.

Variables

This section is empty.

Functions

This section is empty.

Types

type BrowserLauncher

type BrowserLauncher interface {
	Open(url string)
}

BrowserLauncher — native-side hook для открытия URL в WebView. Используется для VK captcha: Go запускает локальный reverse-proxy (см. vkcalls/captcha.go), формирует localhost URL, и просит native открыть его в WebView. Token capture происходит на Go-стороне через JS shim в proxy — native просто рендерит WebView.

На Android это обычно показ Compose Dialog'а с WebView, настроенного мобильным UA + anti-bot JS-инъекциями (см. tun/CaptchaWebViewDialog.kt). Open вызывается из Go-горутины; native должен поднять UI на main thread.

type Client

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

Client is the singleton-ish tunnel handle. One per VpnService / PacketTunnelProvider instance.

func NewClient

func NewClient() *Client

NewClient returns an idle Client. Hook up SetSocketProtector and SetLogSink before calling Connect.

func (*Client) AdoptTun

func (c *Client) AdoptTun(tunFd int, wgUserspaceConfig string) error

AdoptTun забирает уже открытый TUN-fd (полученный native-стороной из VpnService.Builder.establish()), создаёт wireguard-go device и конфигурирует его UAPI-командами из [wgUserspaceConfig].

Native-сторона вызывает этот метод сразу после Connect() — TUN-fd должен соответствовать interface'у с тем же address/peer, что в connstr (поля wga/wgsp/wgcp/wge), иначе пакеты пойдут не туда.

Возвращает nil при успехе. При ошибке tunFd закрывается изнутри.

func (*Client) Connect

func (c *Client) Connect(connectionString string, listenAddr string) (string, error)

Connect parses the connection string, establishes the Telemost session, completes handshake, and starts listening for WG packets on listenAddr. Returns a JSON-serialised ConnectResult on success.

After Connect succeeds, a background supervisor keeps the tunnel alive: if the server restarts and asks us to re-handshake, we do so transparently without the native side needing to be told. Watch IsConnected() / StatsJSON() for liveness.

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect tears down the tunnel. Idempotent.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the relay goroutine is still alive.

func (*Client) LastErrorCode

func (c *Client) LastErrorCode() int

LastErrorCode returns the code of the most recent error from this client, or ErrUnknown if the last operation succeeded. Lets the native UI render a typed message even after the original error string was passed to LogSink and lost.

func (*Client) LastErrorMessage

func (c *Client) LastErrorMessage() string

LastErrorMessage returns the human-readable message of the most recent error, or "" if none.

func (*Client) SetBrowserLauncher

func (c *Client) SetBrowserLauncher(l BrowserLauncher)

SetBrowserLauncher регистрирует native-side hook на открытие URL в WebView. Используется для VK captcha — Go спавнит local reverse-proxy и просит native открыть localhost URL. Если launcher не задан, Go упадёт обратно на system browser (Linux: xdg-open) — на Android это не работает.

func (*Client) SetLogSink

func (c *Client) SetLogSink(s LogSink)

SetLogSink redirects log output to the native side.

func (*Client) SetPhaseListener

func (c *Client) SetPhaseListener(p PhaseListener)

SetPhaseListener регистрирует native-side hook на изменения фазы подключения. Передавай listener ДО вызова Connect, иначе ранние фазы (auth, lobby) пройдут без notification'ов.

func (*Client) SetSocketProtector

func (c *Client) SetSocketProtector(p SocketProtector)

SetSocketProtector registers the native bypass-VPN hook. Without this, our internal Telemost sockets get captured by the VpnService TUN and the WebRTC handshake never completes.

func (*Client) SetVKProfileStorePath

func (c *Client) SetVKProfileStorePath(path string)

SetVKProfileStorePath включает client-side captcha auto-replay. Путь — это полный absolute path к JSON-файлу пула browser-FP'ов (typically <files_dir>/vkcalls/profiles.json — Kotlin берёт context.filesDir.absolutePath + '/vkcalls/profiles.json'). На каждый успешный manual captcha-solve в пул захватывается device + browser_fp + UA через [vkcalls.loggingTransport]; на последующие auth ladder'ы pool replay'ится через captcha_v2 в Go без UI.

После 2-3 ручных solve'ов capt'а на этом устройстве исчезает — тот же выигрыш что у server'ского S1c-flow на VPS.

Вызывать ДО Connect; пустая строка отключает store (тогда каждый коннект = свежие captcha).

func (*Client) StatsJSON

func (c *Client) StatsJSON() string

StatsJSON returns "{tx_bytes:N, rx_bytes:N, tx_packets:N, rx_packets:N}". Cheap enough to call from a UI timer.

type ConnectResult

type ConnectResult struct {
	DisplayName string   `json:"display_name"`
	PeerID      string   `json:"peer_id"`
	ListenAddr  string   `json:"listen_addr"`
	TelemostIPs []string `json:"telemost_ips"` // /32 networks the native side should route via underlying iface, NOT through the VPN
	WGEndpoint  string   `json:"wg_endpoint"`  // matches ListenAddr — what the WG client config should set as Endpoint

	// Populated when the connection string carries a complete embedded
	// WG profile (admin-panel auto-provisioned inbounds). Native code
	// can hand WGClientConfig straight to wg-tools / WireGuardKit
	// without asking the user to import a .conf file.
	WGClientConfig string `json:"wg_client_config,omitempty"`
	WGClientAddr   string `json:"wg_client_addr,omitempty"` // e.g. "10.66.1.2/24"
}

ConnectResult is what Connect() returns serialised as JSON. Callers parse it on the native side to set up VPN routes / excluded ranges.

type LogSink

type LogSink interface {
	Write(line string)
}

LogSink lets the native side capture goloom log lines (so they appear in logcat / NSLog instead of stdout, which on mobile is /dev/null).

type MobileError

type MobileError struct {
	Code    int
	Message string
	// contains filtered or unexported fields
}

MobileError carries a typed error code alongside a human message. Through gomobile bindings the native side sees this as java.lang.Exception (Android) / NSError (iOS); the Code is also retrievable post-hoc via Client.LastErrorCode() so UIs can render translated strings without parsing English text.

func (*MobileError) Error

func (e *MobileError) Error() string

func (*MobileError) Unwrap

func (e *MobileError) Unwrap() error

type PhaseListener

type PhaseListener interface {
	// OnPhase вызывается каждый раз когда меняется состояние подключения.
	// Реентерабельно безопасен; native-side обычно проксирует в
	// StateFlow / @Published.
	OnPhase(phase string, detail string)
}

PhaseListener lets the native side observe high-level connect phases — "auth_ladder", "lobby_dial", "target_handshake" etc. — between Connect() entry and ConnectResult return. Used by mobile UIs to show сменяющиеся статусы вместо одного безмолвного "Connecting..." indicator'а.

type SocketProtector

type SocketProtector interface {
	// Protect marks the given file descriptor as outside the VPN tunnel.
	// Return true on success. Called from Go goroutines, must be
	// reentrant.
	Protect(fd int64) bool
}

SocketProtector lets the native side mark sockets as bypass-VPN. Android: VpnService.protect(int fd). iOS: usually unnecessary because NEPacketTunnelProvider handles socket scoping, but we accept the hook for parity. Implement this interface in Java/Kotlin/Swift; pass it to SetSocketProtector before calling Connect.

Jump to

Keyboard shortcuts

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