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
- type BrowserLauncher
- type Client
- func (c *Client) AdoptTun(tunFd int, wgUserspaceConfig string) error
- func (c *Client) Connect(connectionString string, listenAddr string) (string, error)
- func (c *Client) Disconnect()
- func (c *Client) IsConnected() bool
- func (c *Client) LastErrorCode() int
- func (c *Client) LastErrorMessage() string
- func (c *Client) SetBrowserLauncher(l BrowserLauncher)
- func (c *Client) SetLogSink(s LogSink)
- func (c *Client) SetPhaseListener(p PhaseListener)
- func (c *Client) SetSocketProtector(p SocketProtector)
- func (c *Client) SetVKProfileStorePath(path string)
- func (c *Client) StatsJSON() string
- type ConnectResult
- type LogSink
- type MobileError
- type PhaseListener
- type SocketProtector
Constants ¶
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 ¶
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 ¶
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 ¶
IsConnected returns whether the relay goroutine is still alive.
func (*Client) LastErrorCode ¶
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 ¶
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 ¶
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 ¶
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).
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 ¶
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.