Skip to content

Embedding in an Android or iOS app

etemenanki-ffi is a library that runs Etemenanki inside an Android or iOS app, as a client. The platform’s VPN API creates the tunnel interface and gives the app a file descriptor for it. The app passes that descriptor to the library together with a config. The library then carries the tunnel’s traffic through the outbounds and routes of that config. It is the same TOML that etemenanki-app runs, optionally with a subscribe file.

The app talks to the library through Kotlin or Swift bindings generated by UniFFI. No REST API is served and no file is written. The app keeps the config and the subscribe file and hands them over as strings. It switches routes, reads traffic and lists connections by calling the library.

flowchart LR
  apps["Apps on the phone"] -->|"packets"| tun["VPN interface, set up by the platform"]
  tun -->|"descriptor"| lib["etemenanki-ffi"]
  ui["Your app, in Kotlin or Swift"] -->|"start, setRoute, reload, stop"| lib
  lib -->|"protect, log"| ui
  lib -->|"outbound connections"| nodes["Proxy servers"]

This page is for app developers. How the library works inside is described in the developer guide, on Mobile library (etemenanki-ffi).

  • The Etemenanki source. The library lives in its ffi/ directory and is built from source; it is not published as a package.
  • Read access to the private Cargo registry that holds the QUIC crates Hysteria 2 runs on, as for etemenanki-app; see Build from source. The library also takes libsubconv, which converts subscriptions in other formats, from that registry.
  • Rust 1.98 or later, which libsubconv needs, from rustup, with the targets for your platform added (see Build the library).
  • For Android: Nix, which provides the pinned NDK and cargo-ndk. Alternatively, cargo-ndk, an NDK in ANDROID_NDK_HOME, and perl and make for the OpenSSL build.
  • For iOS: a Mac with Xcode.
  • A config that works as a client, as described in The config on a phone. Try it with etemenanki-app on a desktop first: A desktop client from a subscribe file starts from the same files.

The build scripts build release libraries with OpenSSL compiled from source, since neither platform has a system OpenSSL to link. They then generate the bindings from the built library, with a uniffi-bindgen pinned to the UniFFI version the library uses.

From the root of the Etemenanki source:

Terminal window
rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android
nix-shell ffi/shell.nix --run ffi/build-android.sh

ffi/shell.nix provides NDK r28c and cargo-ndk. It uses the Rust toolchain from rustup, which is why the targets are added first. The script takes an output directory as its only argument, target/ffi/android by default, and writes:

Output Contents
jniLibs/arm64-v8a/libetemenanki_ffi.so The library for aarch64-linux-android
jniLibs/armeabi-v7a/libetemenanki_ffi.so The library for armv7-linux-androideabi
jniLibs/x86_64/libetemenanki_ffi.so The library for x86_64-linux-android, for the emulator
kotlin/uniffi/etemenanki_ffi/etemenanki_ffi.kt The Kotlin bindings, in package uniffi.etemenanki_ffi

Copy jniLibs/ into the app module’s src/main/ and the Kotlin file into its sources. The bindings load the library through JNA, and the async calls are Kotlin suspend functions, so the module depends on both:

build.gradle.kts
dependencies {
implementation("net.java.dev.jna:jna:<version>@aar")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<version>")
}

The libraries are left unstripped, because the generator reads its metadata from their symbols. Gradle strips what it packages. The minimum API level the libraries link against is 21 by default; set CARGO_NDK_PLATFORM to raise it.

To generate bindings from a library you built some other way, run the pinned generator in library mode:

Terminal window
cargo run -p etemenanki-ffi-bindgen -- generate --library <path to the built library> --language kotlin --out-dir out/kotlin

Use --language swift for Swift. Bindings generated by another UniFFI version do not match the library.

In Kotlin (Swift has the same shape, with async throws):

val proxy = Proxy.start(configToml, subscribeToml, tunFd, platform) // throws FfiException
val report: ApplyReport = proxy.reload(configToml, subscribeToml) // suspend
val change: RouteChange = proxy.setRoute("Streaming", "us-west", true) // suspend; true closes what it moved
saveConfig(change.configToml) // your storage: the library writes nothing
val routes: RouteView = proxy.routes()
val traffic: TrafficSnapshot = proxy.traffic()
val live: List<ConnectionInfo> = proxy.connections()
proxy.closeConnection(live[0].id)
val delay: HttpDelay = proxy.httpPing("us-west", null, 5000u) // suspend
val closed: ULong = proxy.closeRerouted() // after a reload that switched a node
proxy.stop() // suspend
Call Kotlin / Swift What it does
Proxy.start(configToml, subscribeToml, tunFd, platform) Synchronous, throws Starts a proxy that serves tunFd with the given files. subscribeToml is the subscribe file’s contents, given exactly when the config has a [subscribe] section, and null / nil otherwise. Returns once the proxy serves the device.
reload(configToml, subscribeToml) suspend / async throws Runs new files in place of the running ones and returns what it did. Files that do not apply are refused, and what runs is left as it was.
setRoute(group, target, closeConnections) suspend / async throws Points a route group, or the default route with "default", at a node, outbound, balancer, direct or blackhole, and applies that. With closeConnections, then closes the live connections the new pick sends to another node. Returns what it did, how many connections it closed, and the config with the pick in it.
routes() Synchronous, throws Each route group’s pick, what it inherits and where its traffic goes; the default route; every target a pick may name.
traffic() Synchronous, throws Byte totals and rates, overall and per inbound and outbound, as of the last one-second sample.
connections() Synchronous, throws The live connections, oldest first.
closeConnection(id) Synchronous, throws Ends one connection. Returns false when no live connection has that id.
closeRerouted() Synchronous, throws Closes the live connections the running routing sends to another node than the one carrying them, and returns how many. Call it after a reload that switched a node, the mode or the profile.
httpPing(tag, url, timeoutMs) suspend / async throws Tests the delay of one node, outbound or balancer with HTTP requests through it, whatever the routing says. See Testing a node’s delay.
stop() suspend / async, never throws Stops the proxy. See Stopping.

Every method may be called from any thread. start blocks its caller while it builds and applies the config, so call it off the UI thread. The async calls run on the library’s own threads and need nothing from the caller’s executor: a Kotlin coroutine or a Swift task awaits them as usual.

Six functions work on the files alone, before or beside a running proxy. They bind nothing, start nothing and read no geodata file:

Call Returns What it does
inspectSubscribe(subscribeToml) SubscribeInfo Parses a subscribe file and describes what it offers, for a node list or a route picker. Checks that span several entries, such as unique names, are checkConfig’s.
checkConfig(configToml, subscribeToml) nothing, or throws Whether start would accept these files: it parses, merges and lowers them, and refuses a server inbound, exactly as start does. Only what running alone can tell, binding ports, reading geodata and the TUN device, is left out.
routeView(configToml, subscribeToml) RouteView The routes these files pick, as routes() would report them once running.
convertSubscription(subscription) ConvertedSubscription A provider’s subscription in another client’s format, made into a subscribe file. See Subscriptions in other formats.
withoutGeo(subscribeToml) String The subscribe file without its geosite and geoip matchers. See Connecting before the geo files are there.
ffiVersion() String The library’s version.

SubscribeInfo describes one subscribe file:

Field Meaning
nodes Each node, in file order: its name, server, port, protocol, transport (tcp, ws, grpc or reality; quic for hysteria2, udp for wireguard), whether it uses tls, and the VLESS flow, such as xtls-rprx-vision, or none. An anytls node is tcp with tls, and a reality node counts as tls. A protocol or transport newer than the library reads unknown
groups The route groups in the order they are matched: each group’s name, what it inherits, and its matchers, every value of every matcher as a kind and a value
ruleGroups The group each route rule comes from: rule i, the index a ConnectionInfo.rule names, belongs to ruleGroups[i]
hasDns, systemDns Whether the file has a [dns] section, and whether it names the "system" resolver
resolveIpv6 The [dns] section’s resolve_ipv6, which a provider turns off when its servers carry no IPv6; absent without [dns]
usesGeoip, usesGeosite Whether a group matches by geoip or geosite, which needs that geodata file

The app implements one interface, which the library calls:

interface Platform {
fun protect(fd: Int): Boolean
fun log(level: LogLevel, message: String)
}
Method Called Implement it as
protect(fd) For every socket the proxy opens toward the network, after the socket is created and before it connects On Android, VpnService.protect(fd). On iOS, return true: a packet tunnel’s own sockets already leave outside it. Returning false closes the socket unused and fails the connection it was for.
log(level, message) For every log line at or above the config’s [log] level Hand the line to the platform’s log.

Both methods are called on the library’s threads, any of them, and log also on the thread that calls start, while start runs. They must be thread-safe and must not throw. Both run inside the work that called them, so keep them quick: a slow protect delays the connection it was called for.

A log line reads <target>: <message>, followed by key=value for each extra field, for example etemenanki_app::instance: config reloaded: built [route]; reused [dns, outbound proxy@v1, inbound tun]. The line has no timestamp. The level comes separately, as one of ERROR, WARN, INFO, DEBUG and TRACE (Swift: .error … .trace).

reload returns an ApplyReport, and setRoute a RouteChange holding one:

ApplyReport field Meaning
unchanged Nothing was applied: the files are the ones already running, or the pick was already made
built Parts built from the config: new, or changed
reused Parts kept as they were
swapped Inbounds serving new connections with new settings
drained Outbound versions taken out of service
rebound Inbounds whose listener was bound again
removed Inbounds taken out of the config
restarted Stays empty here: a change that would end an inbound’s live connections is refused instead

The entries are the same names etemenanki-app prints in its config reloaded: line, such as inbound tun, outbound proxy@v1 or route. What each change does to live connections is described in Hot reload.

RouteChange.configToml is the config with the new pick written into it, with its comments and formatting kept. Store it in place of your copy and pass it to the next start, so that the pick survives a restart. RouteChange.closed is how many connections the switch closed: always 0 without closeConnections.

TrafficSnapshot holds the sample number tick (0 before the first sample), the sample length intervalMs, and Rates for the total and for each inbound and outbound tag that has carried a connection. Rates has up and down, the payload bytes toward and back from destinations so far; upRate and downRate in bytes per second; and flows, the connections live at the sample. The DNS the proxy answers itself appears under the empty outbound tag.

ConnectionInfo describes one live connection: its id, network (TCP or UDP), the inbound it entered at, the client’s source address when known, the destination host and port, the sniffed domain if any, the outbound carrying it, the index of the route rule that matched it, startedAtMs in Unix milliseconds, and its up and down bytes. A UDP entry is one client’s traffic toward one outbound; its destination is that of its first packet.

RouteView has the default route, the groups in the order they are matched, and the targets a pick may name. Each group has its name, its pick if the user made one, what it inherits while nothing is picked, and the target its traffic goes to. It is the same view the desktop REST API returns.

Every call except stop throws the same error type. Kotlin sees it as FfiException and Swift as FfiError, with these cases:

Case Meaning
Config The files do not parse, do not fit together, or describe something the proxy refuses to run. Its message is the same text etemenanki-app prints for that file; see Errors. What runs is unchanged.
ServerInbound The config has an inbound that serves a proxy to others. Its message names the inbound and its protocol. See Only client inbounds.
UnknownGroup setRoute named a route group the files do not have.
Io Something outside the config failed: the descriptor could not be used, a file the config names could not be read, or a local port could not be bound. What runs is unchanged.
Stopped The proxy has been stopped.
Panic A bug inside the library. Stop the proxy.

A route switch to a name that is neither a node, an outbound, a balancer, direct nor blackhole is a Config error: no node, outbound or balancer is named "<target>"; the route view lists them.

The library reads the desktop config format described in The etemenanki-app configuration file, and reports errors in it with the same texts. A phone runs it as a client, which adds a few rules.

The platform’s tunnel is the phone’s inbound. Beside it, a config may have socks and http inbounds for the app’s own use, listening on loopback or on a Unix socket. An inbound with no listen listens on 127.0.0.1, so it counts as local.

Any other inbound fails with ServerInbound, both at start and on reload. That covers a trojan, vless, vmess, shadowsocks, anytls, sss or hysteria2 inbound wherever it listens, and a socks or http inbound that other hosts could reach:

inbound "vless-in" serves vless, a server protocol; only a tun inbound and local socks or http inbounds run in a client

When the config has other errors as well, such as a certificate file that cannot be read, the call may report one of those first.

The platform creates and configures the interface. The library serves the descriptor it is given:

  • Without a tun inbound, the config is served on one tagged tun, with the defaults: MTU 1500, UDP on, IPv6 on, sniffing on, a 60-second UDP idle timeout and 65,536 flows at most. Do not give another inbound the tag tun in such a config; it fails with duplicate inbound tag tun.
  • With a tun inbound, its tag, mtu, udp, udp_idle_timeout, max_flows, ipv6 and sniffing apply; see TUN. The interface’s name, addresses and routes are the platform’s. Leave name, address and routes out: a config that sets them logs inbound <tag>: the platform owns the tun interface, … at warn.
  • More than one tun inbound fails: the config has more than one tun inbound; the platform supplies one device.
  • The MTU must match the one the platform set: setMtu on Android, mtu in the tunnel settings on iOS. The library cannot see the platform’s value. It must be at least 1280.

A reload that changes the tun inbound is refused, as in etemenanki-app. It fails with Config, and the log reads reload refused, keeping the running config: inbound tun: …, which would end its live connections; restart to apply it. To apply the change, stop the proxy and start a new one with the new files.

A config with a [subscribe] section needs the subscribe file’s contents as the second argument of start and reload. The library does not read [subscribe] path, so it may be left out. When the two do not agree, the call fails with Config:

  • the config has a [subscribe] section, but no subscribe file was given
  • a subscribe file was given, but the config has no [subscribe] section to pick its routes in

The file format and the route groups are described in Subscribe files. A provider update is a reload with the new subscribe file and the app’s config. For a provider in another format, convert each download again.

Many providers hand out a mihomo (Clash) profile, share links or a sing-box profile rather than a subscribe file. convertSubscription takes the body as you downloaded it and returns a subscribe file:

val converted = convertSubscription(body) // throws FfiException
showNotes(converted.leftOut, converted.changed) // your UI: the lines are shown as they are
saveSubscribe(converted.subscribeToml) // your storage
  • Formats. It reads a mihomo profile, share links (plain, or the whole list as base64), a sing-box profile, and Surge, Surfboard, Loon and Quantumult X profiles. It tries every format the text looks like and keeps the one that yields the most nodes. A subscribe file is returned as it is. sourceFormat names what was read: etemenanki, mihomo, sing-box, links, links-xray, surge, surfboard, loon or quantumultx. nodes counts the nodes in the file.

  • Node kinds. Besides the protocols every format has, a source that describes them yields AnyTLS nodes and VLESS nodes over REALITY, with or without flow = "xtls-rprx-vision", for example anytls:// links and vless:// links with security=reality. sss nodes come from sss:// share links; see sss links. What the subscribe format cannot hold is left out with a reason, for example Vision over TLS instead of REALITY, REALITY under another protocol or over a transport, or an sss chain of more than 32 expressions.

  • Only the nodes are converted. The [dns] section and the route groups come from a built-in template, never from the provider’s groups and rules: a DNS split, Private for local networks, Ads, and groups for services and regions such as AI, Telegram, YouTube, Netflix, Streaming, Google, Apple and China. Apart from Private, they match by geosite and geoip codes, so the config needs both geo files; see the next section.

  • What did not fit. leftOut has one line per node the subscribe format cannot carry and per entry that could not be read, naming it and why. changed has one line per difference in a node that was kept, such as a mihomo entry without udp, which now relays UDP. The lines name nodes and fields, never their values, so you can show them to the user:

    HK 01: udp added: no `udp` key: the client relays UDP over every protocol but Shadowsocks and HTTP, which carry none
    TU 01: no TUIC: a node's `protocol` is one of ten, and another one refuses the whole file
  • Nothing runnable. When nothing in the text can be carried, the call throws Config. Its message starts the subscription has no node this app can run; when the text had nodes but none could be carried, one line per node follows, saying why it was left out.

As for any subscribe file, checkConfig with your config tells you whether start would accept it.

An sss:// link names the user’s UUID before the @, then the server and port, and its settings as query parameters:

sss://11111111-2222-3333-4444-555555555555@proxy.example.com:443?security=tls&sni=proxy.example.com&type=ws&path=/sss&up=stuff(f%3D0x00,k%3D5)&down=baseN()%7Czstd()#SG%20sss
Parameter Meaning When absent
security none or tls none
sni With tls, the server name sent and checked The server
allowInsecure 1 turns certificate verification off Verified
type tcp, ws or grpc tcp
path, host With ws, the path and the Host header /, and the TLS name or else the server
serviceName With grpc, the service name; required
up, down Each direction’s transform chain: one expression of sss’s notation, its | written %7C, or several expressions joined by , and run in order. A comma inside an expression’s parentheses or a quoted string does not split it, and spaces outside a string are dropped The identity
udp_max_datagram The largest datagram a UDP record carries 65535

REALITY is not available to sss, so a link has no REALITY parameters. The node’s chains are the server’s, from the client’s view, as in sss.

A converted file’s groups match by geosite and geoip, so start and reload refuse it while the geo files are missing. To connect first and download them through your own tunnel:

  1. Name both files in the config’s [route] (geoip and geosite) from the start, at absolute paths in the app’s storage.

  2. While the files are missing, start with withoutGeo(subscribeToml). Every route group stays, so the config’s picks still resolve, but nothing reads a geo file. Traffic that the stripped groups would have matched takes the default route.

  3. Download the files to those paths.

  4. reload with the whole subscribe file. The groups are the same, so the picks do not move.

val full = converted.subscribeToml
proxy = Proxy.start(config, if (geoFilesPresent()) full else withoutGeo(full), tun.fd, platform)
// once the files are downloaded:
proxy.reload(config, full)

withoutGeo works on any subscribe file. It keeps the nodes and [dns] but not comments or formatting. inspectSubscribe tells you whether a file needs the geo files at all (usesGeoip, usesGeosite).

  • [api] is not served. The library logs the config's [api] is not served here: the app reads routes and traffic through this library at info; leave the section out.
  • [log] level filters what reaches Platform.log, with the syntax described in Logging, and info when it is not set. The environment variable RUST_LOG is not read. The level is set by start: a reload does not change it.

Certificates, CA files and geodata are opened by the library in the app’s own process. Put them in the app’s storage and name them with absolute paths: a relative path resolves against the process’s working directory, not against anything the app chose. They are read at start and on each reload. The table of such keys is in Files the configuration reads.

A TLS client that verifies against the system roots (a TLS outbound without ca_file, the tls and https DNS backends without ca_file, and the hysteria2 outbound) cannot count on OpenSSL or rustls to find them on a phone: neither finds any there by itself. The library supplies them instead, once per process. On both platforms a ca_file adds to these roots.

  • On Android, the library reads the system’s trusted CA store: /apex/com.android.conscrypt/cacerts, or /system/etc/security/cacerts when the first holds no certificate. When neither store can be read, the library logs tls: no system CA certificate could be read from […] at warn, and such connections fail verification.
  • On iOS, an app cannot read the system’s list of trusted CAs, so the library trusts Mozilla’s list of root CAs, built into it from the webpki-root-certs crate. A CA installed on the device through a configuration profile, by the user or by MDM, is not trusted: put it in ca_file instead. The list is fixed when the library is built, so a root that Mozilla adds or removes later takes effect only after you rebuild the app with a newer library.

Keep the proxy’s own traffic out of the tunnel

Section titled “Keep the proxy’s own traffic out of the tunnel”

A full tunnel routes every packet into the proxy, including the proxy’s own connections to its servers, unless they are kept out. That is what protect is for. It is called for each socket the proxy opens toward the network: outbound connections, direct TCP and UDP, UDP relays, Hysteria 2 and WireGuard sockets, balancer health probes, and DNS queries to the servers in [dns] or in a subscribe file’s [dns].

One kind of lookup does not pass through protect: the host resolver’s. It is used by [dns] backend = "system", which is the default, and by a "system" entry in a subscribe file’s pre_proxy. It runs inside the C library, out of the proxy’s reach.

  • On Android, name DNS servers instead: set [dns] backend to udp, tls or https (see DNS), or, when the subscribe file has a [dns], which takes the place of the config’s, keep "system" out of its pre_proxy. Alternatively, exclude the app from its own VPN with addDisallowedApplication(packageName).
  • On iOS, a packet tunnel’s own traffic already leaves outside the tunnel, so nothing is needed.

The address the tunnel gives apps as their DNS server (addDnsServer on Android, NEDNSSettings on iOS) is where their lookups go, into the tunnel:

  • With a subscribe file’s [dns], the proxy answers every query to port 53 itself, so any address the tunnel routes will do, such as one in the tunnel’s own subnet.
  • Without one, a lookup is routed like any other connection. Give the address of a real DNS server that your routes can reach.
  1. Declare a VpnService in the manifest with the android.permission.BIND_VPN_SERVICE permission, and ask the user for consent with VpnService.prepare before the first start. Both are standard Android VPN setup.

  2. Build the interface and pass its descriptor to Proxy.start:

    class EtemenankiVpn : VpnService() {
    private var tun: ParcelFileDescriptor? = null
    private var proxy: Proxy? = null
    // Call from a background thread: start blocks until the proxy serves the device.
    fun connect(config: String, subscribe: String?) {
    val tun = Builder()
    .setMtu(1500) // = the config's tun mtu
    .addAddress("172.19.0.1", 30)
    .addRoute("0.0.0.0", 0)
    .addDnsServer("172.19.0.2") // see "The phone's DNS server"
    .establish() ?: return
    this.tun = tun
    proxy = Proxy.start(config, subscribe, tun.fd, object : Platform {
    override fun protect(fd: Int) = this@EtemenankiVpn.protect(fd)
    override fun log(level: LogLevel, message: String) {
    Log.println(priority(level), "etemenanki", message)
    }
    })
    }
    suspend fun disconnect() {
    proxy?.stop()
    proxy?.destroy()
    proxy = null
    tun?.close() // the descriptor stays the app's
    tun = null
    }
    private fun priority(level: LogLevel) = when (level) {
    LogLevel.ERROR -> Log.ERROR
    LogLevel.WARN -> Log.WARN
    LogLevel.INFO -> Log.INFO
    LogLevel.DEBUG -> Log.DEBUG
    LogLevel.TRACE -> Log.VERBOSE
    }
    }
  3. Store the config, and replace it with RouteChange.configToml after every setRoute.

The library never closes the app’s descriptor. It works on its own duplicates, and the app closes its own after stop.

  1. Add a Network Extension target with a packet tunnel provider, and add the XCFramework and etemenanki_ffi.swift to it.

  2. Apply the tunnel settings, then find the tunnel’s utun descriptor. The extension is given no descriptor, so it looks for its own utun control socket among its open descriptors, the approach other packet tunnels with a native core use:

    /// The utun descriptor of this packet tunnel.
    func tunnelFileDescriptor() -> Int32? {
    var info = ctl_info()
    withUnsafeMutableBytes(of: &info.ctl_name) { name in
    _ = "com.apple.net.utun_control".withCString { strncpy(name.baseAddress!.assumingMemoryBound(to: CChar.self), $0, name.count) }
    }
    for fd: Int32 in 0...1024 {
    var addr = sockaddr_ctl()
    var len = socklen_t(MemoryLayout<sockaddr_ctl>.size)
    let ret = withUnsafeMutablePointer(to: &addr) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getpeername(fd, $0, &len) }
    }
    if ret != 0 || addr.sc_family != AF_SYSTEM { continue }
    if info.ctl_id == 0 && ioctl(fd, 0xC0644E03 /* CTLIOCGINFO */, &info) != 0 { continue }
    if addr.sc_id == info.ctl_id { return fd }
    }
    return nil
    }

    ctl_info and sockaddr_ctl are declared in <sys/kern_control.h> and <sys/sys_domain.h>, which the iOS SDK does not ship. Declare them in the extension’s bridging header instead, as the macOS headers do:

    Bridging header
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #define CTLIOCGINFO 0xc0644e03UL
    struct ctl_info {
    u_int32_t ctl_id;
    char ctl_name[96];
    };
    struct sockaddr_ctl {
    u_char sc_len;
    u_char sc_family;
    u_int16_t ss_sysaddr;
    u_int32_t sc_id;
    u_int32_t sc_unit;
    u_int32_t sc_reserved[5];
    };
  3. Start the proxy on that descriptor:

    final class Bridge: Platform {
    func protect(fd: Int32) -> Bool { true } // a packet tunnel's sockets already bypass it
    func log(level: LogLevel, message: String) {
    NSLog("etemenanki %@", message)
    }
    }
    // In the packet tunnel provider, after setTunnelNetworkSettings, with settings.mtu = 1500:
    guard let fd = tunnelFileDescriptor() else { throw TunnelError.noDescriptor }
    proxy = try Proxy.start(configToml: config, subscribeToml: subscribe, tunFd: fd, platform: Bridge())
    // In stopTunnel:
    await proxy?.stop()
    proxy = nil

The utun device puts a 4-byte protocol header in front of each packet, which the library reads and writes itself. A packet tunnel extension has a tight memory limit; the tun inbound’s max_flows bounds how many flows the library’s network stack holds.

A route switch edits the config in memory and applies it:

val change = proxy.setRoute("Streaming", "us-west", true)
if (!change.report.unchanged) saveConfig(change.configToml)

The pick is written to [subscribe.routes] when the config has a [subscribe] section, and to [route] default otherwise. "default" names the default route. A pick that makes an invalid config is refused like any reload, and the running config keeps its old pick. The same switch in etemenanki-app is PUT /v1/routes/{group}, described in REST API.

A switch reaches new connections only. Apps keep their connections open, so without closeConnections a browser’s pages stay on the old node until those connections end. With closeConnections set to true, the library closes, once the switch applied, every live connection the new pick sends to another node; the apps reconnect through the new one. Connections whose node is unchanged keep running, and so do those whose node is a member of the balancer they would now go to. A switch whose pick was already made applies nothing and closes nothing.

For any other change, such as a new subscribe file from the provider or an edit in the app’s settings screen, call reload with the new files. Live connections survive a change unless it removes or replaces what they run on, as in etemenanki-app’s hot reload. A reload never moves an open connection to another node either: when the reload switched a node, the mode or the profile, call closeRerouted() afterwards. One reload or route switch runs at a time: a call made while another is under way waits for it.

httpPing(tag, url, timeoutMs) tests one node, outbound or balancer of the running config by making HTTP requests through it, whatever the routing says, so the app can show a delay next to every node without switching to it. url is the page to request, http:// or https://; null / nil means https://www.gstatic.com/generate_204. timeoutMs bounds the whole test, the connection to the node included. The library sets no default or limit for it, so pick one, for example 5000 (in Kotlin, the unsigned 5000u).

The test opens one connection through the node and sends two HEAD requests on it. The first pays for everything a new connection costs: the connection to the node, the proxy protocol’s handshake and TLS. The second costs one round trip through the node to the site and back, which is what an app that is already connected waits for each request. That second time is the delay, as mihomo’s “unified delay” measures it.

val delay = proxy.httpPing("us-west", null, 5000u)
val label = delay.error?.let { if (delay.timedOut) "timeout" else "failed" } ?: "${delay.delayMs} ms"
HttpDelay field Meaning
delayMs The second request’s round trip: the delay to show. The first request’s time when the site would not keep the connection open (unified is then false). null / nil on failure
handshakeMs The first request, from the start of the connection. null / nil on failure
status The HTTP status the site answered; any status counts. null / nil on failure
unified Whether delayMs is the second request’s
error Why the test failed, or null / nil
timedOut The test ran out of time

A test that fails does not throw: the result carries error, and that includes a tag the config does not have and a malformed url. Only a stopped proxy throws. Tests run alongside each other and alongside a reload or a switch, and their connections do not appear in connections() or traffic(). The same test in etemenanki-app is GET /v1/outbounds/{tag}/delay, described in REST API.

stop() stops accepting new connections, gives live ones two seconds to finish, closes the rest, and shuts down the library’s threads. After it, every other call throws Stopped. It never throws.

Call stop() before you release the object: destroy() or close() in Kotlin, or dropping the last reference in Swift. A proxy released without stop() stops at once, without the two seconds of grace. Then close your own descriptor.