MeerMost

Xray-core in an iOS app: GPL in the binary, 14 core patches and memory

An iOS client for Xray-core looks like three parts: a UI, a NEPacketTunnelProvider and the core built with gomobile. In September we built several such clients (they are now for sale with source code, more at the end): they take links and subscriptions from panels like Remnawave, build a core config and bring up the tunnel in a Network Extension. The hard part turned out to be somewhere else.

The tunnel extension lives for hours, the core inside it restarts on every server change, and the process has little memory. Below are three things we ran into at the end of September: on the 26th, licences that arrive in the binary transitively and the memory of geo files; on the 27th, core defects on restart. Everything is on Xray-core v1.260327.0 (tag v26.3.27).

How it fits together

The clients differ in detail, but the outline is the same:

  1. The app parses a link or subscription and builds the core's JSON config. In the client that also ships on Android, parsing and config building are written in Go: one codebase for both platforms, and every server is checked with the real conf.Build at import time.
  2. The config goes as a file into the shared App Group container.
  3. The NEPacketTunnelProvider extension reads the file, resolves server addresses before the tunnel comes up, applies network settings and hands the core the utun descriptor.
  4. The core lives in the same process as the extension. gomobile builds it into an xcframework. Then there are two options: one client hands the utun descriptor straight to the core through a TUN inbound, the other routes packets through tun2socks in the same process. The extension finds the utun descriptor by walking its fds with getsockopt(SYSPROTO_CONTROL, UTUN_OPT_IFNAME). That is what the tun inbound README in Xray-core itself suggests (proxy/tun/README.md), but for Apple it is an undocumented API and may stop working.

How the client fits together: the app builds the config, the tunnel extension runs the Go bridge and Xray-core in one process and hands the core utun

Two decisions came first. The core starts with no listening inbounds, so there is no local SOCKS port for other apps to find. And "connected" in the UI lights up only after a probe through the core (generate_204 in our case), not when the interface comes up. A server can accept TCP and silently drop the traffic after that, and the user should see it.

GPL comes with the core

We wanted to keep the apps' code closed. Xray-core is published under MPL-2.0, which allows that: you only have to publish the core files you changed. So the first thing we checked was what actually gets linked into the extension binary:

GOOS=ios GOARCH=arm64 CGO_ENABLED=1 CC=$(xcrun -sdk iphoneos -f clang) \
CGO_CFLAGS="-isysroot $(xcrun -sdk iphoneos --show-sdk-path) -arch arm64" \
go list -deps -f '{{if .Module}}{{.Module.Path}} {{.Module.Version}}{{end}}' ./... | sort -u

The output had github.com/sagernet/sing v0.5.1 and github.com/sagernet/sing-shadowsocks v0.2.7, both GPL-3.0-or-later. Mandatory parts of the core pull them in: transport/internet/system_dialer.go and system_listener.go (the control.Func type from sing/common/control), app/proxyman/outbound/uot.go and the config loader infra/conf through Shadowsocks 2022.

Our first idea was to build the core with our own import list, without main/distro/all. It didn't help: even a minimal client set without infra/conf kept sing, because every transport goes through transport/internet. Only sing-shadowsocks went away.

A four-file patch to the core worked, +20/−101 lines:

  • in system_dialer.go and system_listener.go the control.Func type was replaced with our own alias of the same signature, func(network, address string, conn syscall.RawConn) error, so the public RegisterDialerController and RegisterListenerController stayed compatible;
  • the server side of UDP-over-TCP in uot.go returns os.ErrInvalid, as for any other address;
  • the 2022-blake3-* methods in infra/conf/shadowsocks.go return a named "not supported in this build" error.

After that, go list -deps for iOS is clean. juju/ratelimit stays under LGPL-3.0, but its licence has an explicit exception for static linking, and REALITY needs it. We lost only Shadowsocks 2022.

GPL arrives in the binary through mandatory parts of the core, and only a patch removes it

VLESS, REALITY, Hysteria2, WireGuard, XHTTP, Trojan and classic Shadowsocks are all still there.

The build now fails if anything under GPL, AGPL or LGPL shows up in the module list, apart from the allowed ratelimit. Without that check, the next core update would quietly bring sing back.

This is the technical picture; a lawyer may see it differently. And yes, in two of our other clients this item is still open, and their licence files say so on the first lines.

Restarting the core under traffic crashes the process

The tunnel extension doesn't restart when the user switches servers. The core is closed and created again inside the same process. We ran this on a Mac as "five core restarts under traffic", and the process crashed.

The cause was in proxy/tun/handler.go: nobody closed the tun inbound after Instance.Close. The stack kept accepting connections and handing them to a closed core, followed by a nil pointer in app/dns/fakedns. We added Handler.Close: cancel the context, close the stack and device, wait up to three seconds for accepted connections.

Then a -race run found a few more places. In total we carry 14 patches on top of the core: four for licences and ten fixes. These are the ones we didn't expect:

Someone else's utun descriptor. In iOS mode the core wraps the passed descriptor in an os.File and assumes it doesn't own it. But os.File closes the descriptor when garbage collected, so the extension's utun could close at a random moment. The bridge now hands the core a dup of the descriptor, and the core owns it: closes it in Close, and right away on error.

Reused UDP ports. tun flows in udp_fullcone.go were keyed only by source. iOS reuses ports: QUIC can open from the same port as a recent DNS query, and its datagrams went into the old flow to the DNS server. Flows are now keyed by source and destination, with at most 16 flows per source. Without that limit a test with 300 destinations added 1,200 goroutines.

A silent device failure. If utun stopped delivering packets on its own, the core's read loop just ended. The core "ran" with no traffic, and nothing outside could tell. Now the read error goes into a channel, and the bridge stops the core with a cause code.

And a small one that went unnoticed for a while: burstObservatory timers kept pinging servers through an already closed core and kept it in memory.

Patches 05 and 10–14 have tests that fail on the core without them; the races in 07–09 were found by -race. Every core update means carrying the patches over and rerunning the tests. If upstream fixes a spot itself, we drop the patch.

Where the memory goes

Apple doesn't publish the memory limit for a tunnel extension. An Apple developer support engineer on the forums cited 50 MiB for iOS 15 and 16, and developers see limit=50 MB in crash logs. Older versions had 15 MB. We plan for 50 and verify on a device.

The numbers below were measured on a Mac (arm64, Go heap), so they are a lower bound. Device numbers are still in progress.

Geo files. We expected the 23 MB geoip.dat to eat memory whole. It turns out the core doesn't load the file: it streams through it with a 64 KiB buffer and copies only the record for the code it needs (infra/conf/router.go). Memory depends on which codes the config uses:

Rules in the configLoadHeap peak
no geo1 ms2.3 MiB
geoip:ru18 ms9.1 MiB
geosite:geolocation-!cn30 ms12.6 MiB
ads + geolocation-!cn + geosite:cn + geoip:private,cn,ru,ir106 ms22.0 MiB

The last row is a set similar to a heavy panel config with per-country routing. A 22 MiB peak at start against a limit of about 50 is already a lot.

FakeDNS. If dns.servers has "fakedns" but the config has no fakedns block, the core creates pools of 32,768 entries on its own (infra/conf/fakedns.go). Each name across both pools costs about 1.4 KB. Measured: 2,048 names add 4.1 MiB, 4,096 add 6.9 MiB, 65,535 add 85.4 MiB. With default pools the extension simply won't survive. Our config builder sets 2,048.

How much memory FakeDNS pools take at 2,048, 4,096 and 65,535 names

DNS flows. Every DNS query through tun is a separate UDP flow with a new source port. The dns outbound keeps a flow open for the connIdle of its policy level, 300 seconds by default: three goroutines and about 25 KiB per query. A thousand queries in five minutes is tens of megabytes. The bridge moves every dns outbound to its own policy level with an 8-second connIdle. In a test of 500 queries through tun the goroutine count went from 32 to 2,012 and back to 32 within 16 seconds.

What we'd recommend

If you're building an Xray-core client for iOS too:

  • check licences with go list -deps for GOOS=ios and keep that check in the build: go.mod doesn't show what ends up in the binary;
  • write a "restart the core under traffic" test on day one, because in an extension that path runs on every server change;
  • set FakeDNS pools and DNS flow lifetimes yourself, since the defaults are tuned for desktop;
  • measure memory on configs your users' panels actually serve. We'll recheck our own numbers on an iPhone.

One question is still open for us. We capped flows per source at 16 and close the oldest when a new one opens. If you've seen iOS apps that need more, tell us which ones and we'll test them.

Where these clients are now

We sell the code of all four clients with full source: Cavaler, Sheleste, Kluch 17 and Dostup. We tell buyers what has been verified and what hasn't (the same GPL item and the iPhone measurements) before the deal. What to check in any ready-made VPN app is in our separate checklist, and you can estimate launching a whole service on the VPN business page.

Frequently asked

Can you ship a closed-source iOS app on Xray-core?

The core itself is MPL-2.0, which allows closed source. But a default build links sagernet/sing modules under GPL-3.0 into the binary. We removed them with a four-file patch to the core, at the cost of Shadowsocks 2022 support.

How much memory does an iOS packet tunnel extension get?

Apple doesn't document it. An Apple developer support engineer on the forums cited 50 MiB for iOS 15 and 16; older versions had 15 MB. We plan for 50 and verify on a device.

What uses the memory of Xray-core in a Network Extension?

Not the size of geo files: the core streams them. The big ones are default FakeDNS pools (65,535 names take about 85 MiB) and DNS flows, which live for 300 seconds by default.

All articles

Related articles

White label VPN, reseller or your own code: who owns the customers
Business

White label VPN, reseller or your own code: who owns the customers

White label, VPN reseller programs and owning the code compared on what matters after launch: pricing control, customer data, servers and leaving.

4 min read
Your Own App or Happ: What to Give VPN Service Customers
Business

Your Own App or Happ: What to Give VPN Service Customers

Happ is free and installs in a minute, but it keeps getting pulled from the Russian App Store. Your own app can take months to pass review. What to give subscribers, and when.

8 min read
App Promotion with No Ad Budget: ASO Step by Step
Marketing

App Promotion with No Ad Budget: ASO Step by Step

How to promote an app in the App Store and Google Play without ads: where to find keywords for free, what to put in the three fields, and why you need to get it done before release.

6 min read