mobile

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 9 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

mobile: Android bindings for the tunnel

Package mobile wraps the tunnel package for gomobile so the Android app (see ../android) can run a Burrow client or server, plus the STUN and TCP NAT diagnostics from diag.

Building

From the burrow/ directory:

make aar-install   # one-time: install gomobile/gobind (github.com/sagernet/gomobile)
make aar           # build build/tunnel.aar
make apk           # build the .aar, copy it into the Android project, build a debug APK

Override the API level, Java package or version:

make aar ANDROID_API=26 JAVA_PKG=com.example.tunnel MOBILE_VERSION=1.0.0

The defaults are ANDROID_API=23, JAVA_PKG=com.getkiko.burrow (so the classes are com.getkiko.burrow.mobile.Mobile and ...mobile.Observer) and MOBILE_VERSION=dev. The version is injected with -ldflags -X into mobile.version and returned by Mobile.version().

Build constraints:

  • -androidapi must be set. gomobile defaults to API 16, which current NDKs reject. It must match the app's minSdk (23).
  • The gomobile fork must stay in go.mod. The bindings are built with github.com/sagernet/gomobile, not golang.org/x/mobile. No Go code imports it, so tools.go pins it; otherwise go mod tidy drops it and gomobile bind fails.
  • -ldflags -checklinkname=0 is required. github.com/wlynxg/anet references net.zoneCache via go:linkname, which the Go 1.23+ linker rejects by default (invalid reference to net.zoneCache).
  • gomobile init is not needed, and gomobile falls back to ~/Library/Android/sdk when ANDROID_HOME is unset.

API

Config and status are passed as JSON strings: gomobile cannot bind maps, nested structs, time.Duration, uint64 or cross-package pointers, and JSON lets fields evolve without changing the binding layer and the Kotlin side in lockstep. The config JSON has the same format as the burrow tunnel client and server config files.

// Lifecycle
Mobile.startClient(String configJSON, Observer observer) throws Exception
Mobile.startServer(String configJSON, Observer observer) throws Exception
Mobile.stop() throws Exception
String Mobile.snapshot()

// Helpers
String Mobile.validateConfig(String role, String configJSON)  // "" means valid
String Mobile.version()

// Diagnostics
String Mobile.runSTUN(String server, String iface, long timeoutMillis) throws Exception
String Mobile.runTCPNAT(String server, String ports, String iface, String proxy,
                        long localPort, long rounds, long timeoutMillis) throws Exception

Go int parameters are bound as Java long. validateConfig takes the role "client" or "server" and applies the same validation as a real start.

Observer is implemented in Kotlin:

class MyObserver : Observer {
    override fun onStateChange(statusJSON: String) { ... }
    override fun onStats(statsJSON: String) { ... }
    override fun onLog(level: String, line: String) { ... }  // debug/info/warn/error
}

Things to know

Callbacks are synchronous JNI calls. The Observer methods are not delivered asynchronously; heavy work in them blocks the Go goroutine. Post UI updates to the main thread. The binding never holds its own lock while calling back, so calling snapshot() or stop() from a callback does not deadlock.

Go panics are recovered. Every exported function recovers from panics and turns them into an exception (or a fallback value). gomobile does not do this itself: an unrecovered panic kills the whole app process. Panics in your Observer implementation are also contained.

Single global instance. Only one tunnel runs at a time. A second startClient/startServer throws instead of replacing the running tunnel; call stop() before switching role or config. stop() is safe to call at any time, including while a start is still in progress (the start is then abandoned).

Status JSON

snapshot() and onStateChange return the same structure:

Field Type Description
State string stopped / idle / punching / connected / punch_failed
Room string Room name
LocalAddr / RemoteAddr string Punched connection addresses
Peers string[] Active peer addresses (always an array, never null)
UptimeMillis long Connection uptime in milliseconds
SessionCount int Open punched connections (one per upstream connection)
ActiveStreams int Connections currently being forwarded
TotalStreams long Connections forwarded so far
Queued int Connections waiting to be punched (including the current one)
PunchTrial / PunchTrials int Current trial and total trials while punching
PunchReason string Why the last punch round failed (empty for an ordinary miss)
AppRxBytes / AppTxBytes long Bytes relayed at the application level
MaxDownMbps / MaxUpMbps double Peak bandwidth since start (added by the binding)
LastError string Most recent error

onStats delivers a TCP sample every 5 seconds:

Field Type Description
Role string dialer / listener
LocalAddr / RemoteAddr string Sampled connection
IntervalMillis long Sample window
RxBytes / TxBytes long Bytes in this window
RxPackets / TxPackets / RetransPackets long Packets in this window
RetransBytes long Retransmitted bytes in this window
TotalRxBytes / TotalTxBytes / TotalRetransBytes long Cumulative bytes
RTTMillis long Round-trip time
CongestionWindow / ReceiveWindow / ReceiveSpace long Congestion window, local receive window and (Linux only) receive-buffer estimate, in bytes

Throughput for a window is RxBytes * 8 / (IntervalMillis / 1000) / 1e6 Mbps.

Diagnostics JSON

runSTUN returns NATType, NATLabel (a human-readable type name), PublicAddr, IsSymmetric and Detail; runTCPNAT returns Detail. Both throw if the diagnostic fails.

Documentation

Overview

Package mobile is the gomobile binding of the tunnel package for Android.

Design notes:

  • Config and status are passed as JSON strings. gomobile cannot bind maps, nested structs, time.Duration, uint64 or cross-package pointers; JSON lets fields evolve without changing the binding layer and the Kotlin side in lockstep.

  • Global single instance. Android never needs more than one tunnel at a time, and a singleton means Stop and Snapshot need no handle argument. A second Start returns an explicit error instead of silently replacing the running tunnel.

  • Every exported function recovers from panics. A Go panic does not become a Java exception; it kills the whole app process with a fatal crash that Kotlin's try/catch cannot catch, because the gomobile runtime never recovers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunSTUN

func RunSTUN(server, iface string, timeoutMillis int) (out string, err error)

RunSTUN runs STUN NAT type detection and returns the result as JSON.

An empty server selects the default STUN server; an empty iface lets the kernel choose the route; timeoutMillis <= 0 uses the default timeout.

Even when an error is returned, the Detail field of the JSON may contain partial output, which is worth showing to the user for troubleshooting.

func RunTCPNAT

func RunTCPNAT(server, ports, iface, proxy string, localPort, rounds, timeoutMillis int) (out string, err error)

RunTCPNAT probes TCP NAT mapping behavior and returns the result as JSON.

ports is a comma-separated list of at least two distinct ports; localPort 0 picks a fresh local port each round; timeoutMillis <= 0 uses the default timeout.

func Snapshot

func Snapshot() (out string)

Snapshot returns the current status as JSON. When nothing is running it returns a snapshot whose State is "stopped".

func StartClient

func StartClient(configJSON string, observer Observer) (err error)

StartClient starts a client from a JSON config. It returns an error if a tunnel is already running.

configJSON has the same format as the client config file. cfg.Validate() applies exactly the same rules as the tunnel package's file loader (LoadClientConfig), so its messages can be shown to the user directly and a config that validates never fails to start for validation reasons.

func StartServer

func StartServer(configJSON string, observer Observer) (err error)

StartServer starts a server from a JSON config. It returns an error if a tunnel is already running.

It runs a NAT self-check before starting: with the birthday strategy, a symmetric NAT (NAT4) makes it refuse to start.

func Stop

func Stop() (err error)

Stop stops the current instance. It is a no-op when nothing is running and is safe to call repeatedly.

If a Start is running build/Start outside the lock (current is still nil), Stop must not conclude there is nothing to stop: the user would think the tunnel stopped while it finishes starting and keeps running in the background. In that case Stop only sets stopRequested and returns at once (it does not wait, to avoid an ANR when called on the Android main thread); startRunner abandons the start and cleans up when it finishes.

func ValidateConfig

func ValidateConfig(role string, configJSON string) (out string)

ValidateConfig validates a config without starting anything; the config screen uses it as a pre-save check.

It returns an empty string if the config is valid, otherwise an error message that can be shown to the user. role is "client" or "server".

It reuses the tunnel package's validation, the same rules applied on a real start, so a config never passes here and then fails validation at start time.

func Version

func Version() string

Version returns the version of the binding layer.

Types

type Observer

type Observer interface {
	// OnStateChange delivers a full status snapshot (JSON) on every state transition.
	OnStateChange(statusJSON string)

	// OnStats delivers a TCP sample (JSON) every 5 seconds.
	OnStats(statsJSON string)

	// OnLog delivers a single log line. level is "debug", "info", "warn" or "error".
	OnLog(level string, line string)
}

Observer receives tunnel events. It is implemented on the Kotlin side.

All parameters are strings: gomobile cannot bind complex types, so status and stats are passed as JSON. OnLog takes level as a separate argument rather than inside JSON because the UI colors lines by level and should not have to parse every line.

These callbacks are synchronous, blocking JNI calls, not asynchronous deliveries. Heavy work in an implementation blocks the Go goroutine; UI updates should be posted to the main thread.

Jump to

Keyboard shortcuts

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