init: OffScale — standalone MIT Tailscale/Headscale client
Extracted from the officer-suite monorepo into its own public repo. The app is
open source and free; the rest of the suite is not, so it could not stay in a
tree that ships an account layer.
What moved:
- apps/offscale/* -> repo root (App shell, app.json, assets)
- packages/officer-net/ -> modules/officer-net/, a `file:` dependency
- packages/core VPN closure -> src/vpn/ (screen, hook, native bridge, invite)
- packages/core shared primitives -> src/ui/ (theme, cards, tabs, backdrop, splash)
- scripts/build-{ios,android}.sh -> scripts/, cut down to this one app
What deliberately did NOT move: the platform account layer. VpnScreen used to
render core's AppSettingsScreen, which drags in ServersSection -> servers.ts,
useAuth, api.ts, shared-session, install-guard, api-keys. None of that exists
here. src/settings/SettingsScreen.tsx is a fresh replacement rendering exactly
what VpnScreen passed it — the app's own sections plus About — with no Servers
tab, no Appearance control (the app is pinned to dark) and no sign-out.
The one platform reference left in the closure was a dead `import { request }
from './api'` in officer-net.ts, unused since enrollVpn() was removed. Gone. The
app now contacts nothing but the control server you point it at, its peers, and
the enrolment sidecar named inside an invite link you tapped.
Dependencies are pinned to the exact versions the monorepo has installed, not to
ranges: this repo starts from versions already proven to build, and an unpinned
install is a supply-chain decision nobody made. react-query, react-dom,
react-native-screens, expo-secure-store, track-player, expo-audio and
expo-file-system were all declared by the old app and imported by none of this
code, so they are not here.
NOTICE carries Tailscale's BSD-3 text, names the built artifacts that contain
their compiled code, and treats the trademark question separately — including
that src/ui/TailscaleMark.tsx reproduces their logo in the attribution strip.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'OfficerNet'
|
||||
s.version = '0.1.0'
|
||||
s.summary = 'OffTail VPN engine — Tailscale core bridge'
|
||||
s.description = 'Embeds the gomobile-built Tailscale core (libtailscale) as OfficerNet.xcframework and drives it behind an NEPacketTunnelProvider. Run scripts/build-libtailscale-ios.sh to populate libs/ before pod install. Talks directly to a self-hosted Headscale control server.'
|
||||
s.author = 'André Padez'
|
||||
s.homepage = 'https://pastilhas.dev'
|
||||
s.license = { :type => 'BSD-3-Clause' }
|
||||
s.platforms = { :ios => '15.1' }
|
||||
s.source = { git: '' }
|
||||
s.static_framework = true
|
||||
|
||||
s.dependency 'ExpoModulesCore'
|
||||
|
||||
# The gomobile-built Tailscale core. Produced once by scripts/build-libtailscale-ios.sh and vendored
|
||||
# under libs/ (gitignored). Vendored ONLY when present — until the build script runs, the pod compiles
|
||||
# as a stub (the Swift references no libtailscale symbols directly), so the app still builds + installs
|
||||
# with an inert engine. Once the xcframework exists it links automatically on the next pod install.
|
||||
# TODO(libtailscale): ship OfficerNet.xcframework here (arm64 device + arm64 sim slices).
|
||||
if File.directory?(File.join(__dir__, 'libs', 'TailCore.xcframework'))
|
||||
s.vendored_frameworks = 'libs/TailCore.xcframework'
|
||||
end
|
||||
|
||||
s.pod_target_xcconfig = {
|
||||
'DEFINES_MODULE' => 'YES',
|
||||
'SWIFT_COMPILATION_MODE' => 'wholemodule'
|
||||
}
|
||||
|
||||
# Only the RN-process module compiles into this pod (the main app). PacketTunnelProvider.swift compiles
|
||||
# into the Network Extension target instead — the config plugin (plugin/withNetworkExtensionTarget.js)
|
||||
# copies it into ios/OffTailTunnel/ and adds it to that target's sources, along with TailCore.xcframework.
|
||||
s.source_files = 'OfficerNetModule.swift'
|
||||
end
|
||||
@@ -0,0 +1,740 @@
|
||||
import ExpoModulesCore
|
||||
import NetworkExtension
|
||||
import TailCore // the vendored gomobile Tailscale core (packages/officer-net/ios/libs/TailCore.xcframework)
|
||||
|
||||
// OffTail VPN engine — iOS RN-process module. Parity with android/.../OfficerNetModule.kt and the JS
|
||||
// bridge in packages/core/src/services/officer-net.ts (requireNativeModule('OfficerNet')).
|
||||
//
|
||||
// This module runs in the *main app process*. It does NOT touch packets. Its whole job is to configure
|
||||
// and drive a NETunnelProviderManager, which in turn starts/stops the Network Extension target
|
||||
// (PacketTunnelProvider.swift) that actually hosts the Tailscale core (libtailscale). The two processes
|
||||
// share config/keys through the App Group. See TAILSCALE_VPN.md → "Architecture".
|
||||
//
|
||||
// The libtailscale core is NOT linked into this process — it lives in the NE. So there are no
|
||||
// `// TODO(libtailscale):` call-sites here; the TODOs here are all about NE plumbing. The core call-
|
||||
// sites live in PacketTunnelProvider.swift.
|
||||
|
||||
/**
|
||||
The Network Extension target that embeds PacketTunnelProvider.swift + the Tailscale core.
|
||||
|
||||
DERIVED from the host app's bundle id, never hardcoded. It was `dev.officer.mobile.net` — Officer's
|
||||
extension — which is correct for Officer and wrong for every other host. The standalone app ships
|
||||
`dev.officer.tail.net`, so it was asking iOS to start an extension that is not part of it: the start
|
||||
command is accepted, nothing matches, and the tunnel silently never launches. No crash, no trace, a
|
||||
dead toggle.
|
||||
|
||||
It appeared to work only because Officer is installed on the same device, so there WAS a
|
||||
`dev.officer.mobile.net` for iOS to find — the standalone app was driving Officer's extension. The
|
||||
moment the configuration was rebuilt from scratch that stopped being honoured, which is why this
|
||||
surfaced as "it used to connect and now it will not".
|
||||
|
||||
The value is read from `OfficerNetExtensionBundleId` in Info.plist, which the Expo plugin writes from
|
||||
each app's own `neBundleId` prop — apps/tail already declared `dev.officer.tail.net` correctly, and
|
||||
this file simply never looked. Deriving from the app's bundle id is the fallback for a host that
|
||||
predates the plist key, and it matches the plugin's own `.net` convention.
|
||||
*/
|
||||
private var neBundleId: String {
|
||||
if let declared = Bundle.main.object(forInfoDictionaryKey: "OfficerNetExtensionBundleId") as? String,
|
||||
!declared.isEmpty {
|
||||
return declared
|
||||
}
|
||||
return (Bundle.main.bundleIdentifier ?? "dev.officer.mobile") + ".net"
|
||||
}
|
||||
|
||||
// Local scratch store (UserDefaults.standard) for the config the NE needs (controlUrl/hostname/authKey);
|
||||
// it's copied into the manager's providerConfiguration, which is how the NE actually receives it. No App
|
||||
// Group — see the plugin's withIosEntitlements for why.
|
||||
// Keys shared with providerConfiguration.
|
||||
private let kControlUrl = "controlUrl"
|
||||
private let kHostname = "hostname"
|
||||
private let kAuthKey = "authKey" // single-use Headscale pre-auth key; consumed by the core on first up().
|
||||
private let kRegistered = "registered" // set by the NE once the node has a persisted identity.
|
||||
|
||||
/// One-shot guard so a checked continuation is resumed exactly once when both a timeout and a real
|
||||
/// response can race (see neCoreStatus).
|
||||
private final class ResumeOnce {
|
||||
private let lock = NSLock()
|
||||
private var done = false
|
||||
func take() -> Bool {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
if done { return false }
|
||||
done = true
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
public class OfficerNetModule: Module {
|
||||
// The lazily-loaded/created tunnel manager. One per app; NE state persists in the system prefs.
|
||||
private var manager: NETunnelProviderManager?
|
||||
private var statusObserver: NSObjectProtocol?
|
||||
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("OfficerNet")
|
||||
|
||||
// Native → JS status/peer stream. Mirrors the `onStatus` event the JS bridge subscribes to.
|
||||
Events("onStatus")
|
||||
|
||||
// Proof-of-life: the embedded Tailscale core's version, read straight from the vendored gomobile
|
||||
// framework — this runs real tailscale.com code inside the app. (Called here in the main process for
|
||||
// the demo; the shipping design hosts the core in the NE.) No network.
|
||||
AsyncFunction("coreVersion") { () -> String in
|
||||
return TailcoreVersion()
|
||||
}
|
||||
|
||||
// ── Profiles ─────────────────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// Everything here round-trips through the extension, because that is where the core runs. An
|
||||
// empty reply means success; a non-empty one is the error text.
|
||||
|
||||
AsyncFunction("listProfiles") { () async -> String in
|
||||
return await neCommand("profiles:list") ?? "[]"
|
||||
}
|
||||
|
||||
AsyncFunction("switchProfile") { (id: String) async throws in
|
||||
guard let err = await neCommand("profiles:switch:\(id)", timeout: 15) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
/*
|
||||
nil is NOT success.
|
||||
|
||||
`neCommand` returns nil when the message never got a reply — no live session, or the 1.5s
|
||||
timeout. Treating that as success meant `newProfile()` could return cleanly having done nothing
|
||||
at all, and the caller would go on to `configure` + `up` believing a fresh profile existed. The
|
||||
result is a second tailnet silently REPLACING the first instead of joining it.
|
||||
|
||||
Same shape as the startTunnel optional-chaining bug: a failure that returns quietly is worse
|
||||
than one that throws.
|
||||
*/
|
||||
AsyncFunction("newProfile") { () async throws in
|
||||
guard let err = await neCommand("profiles:new", timeout: 15) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
/// Join another tailnet without restarting the tunnel. See LoginTo in tailcore.go for why both
|
||||
/// steps have to happen inside the core.
|
||||
AsyncFunction("loginToNewProfile") { (controlUrl: String, authKey: String?, hostname: String?) async throws in
|
||||
let payload: [String: Any] = [
|
||||
"controlUrl": controlUrl,
|
||||
"authKey": authKey ?? "",
|
||||
"hostname": hostname ?? "",
|
||||
]
|
||||
let json = try JSONSerialization.data(withJSONObject: payload)
|
||||
guard let err = await neCommand("profiles:login:\(json.base64EncodedString())", timeout: 20) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
// ── Live preferences ────────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// Applied with EditPrefs on the running node, so choosing an exit node does not drop the tunnel.
|
||||
|
||||
AsyncFunction("setExitNode") { (stableId: String?) async throws in
|
||||
guard let err = await neCommand("prefs:exitnode:\(stableId ?? "")", timeout: 15) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
AsyncFunction("setAcceptRoutes") { (on: Bool) async throws in
|
||||
guard let err = await neCommand("prefs:routes:\(on ? 1 : 0)", timeout: 15) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
AsyncFunction("prefs") { () async -> String in
|
||||
return await neCommand("prefs:get") ?? "{}"
|
||||
}
|
||||
|
||||
/*
|
||||
Collect a pending report about how the LAST tunnel run ended, or "" if it ended cleanly.
|
||||
|
||||
Needs a LIVE extension, because the marker lives in the extension's container and this channel is
|
||||
the only way to it. That is a real limitation: a tunnel that dies and is never started again keeps
|
||||
its report to itself. Collecting on the next successful connect is the trade — it costs the last
|
||||
crash on a permanently-broken install and keeps the app from having to hold an App Group
|
||||
entitlement solely to read one file.
|
||||
|
||||
Also a TAKE, not a get: the extension drops it once handed over, so a crash is reported once
|
||||
rather than on every launch forever.
|
||||
*/
|
||||
AsyncFunction("lastExitReport") { () async -> String in
|
||||
return await neCommand("diag:lastexit") ?? ""
|
||||
}
|
||||
|
||||
AsyncFunction("deleteProfile") { (id: String) async throws in
|
||||
guard let err = await neCommand("profiles:delete:\(id)", timeout: 15) else {
|
||||
throw NSError(domain: "officer-net", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "The VPN service did not respond. Connect first, then try again.",
|
||||
])
|
||||
}
|
||||
if !err.isEmpty { throw NSError(domain: "officer-net", code: 1, userInfo: [NSLocalizedDescriptionKey: err]) }
|
||||
}
|
||||
|
||||
OnCreate {
|
||||
// Observe NEVPNStatusDidChange so state transitions (connecting/connected/…) push to JS without
|
||||
// polling. Peer-level detail comes from the NE via the App Group / status(), emitted on change.
|
||||
self.statusObserver = NotificationCenter.default.addObserver(
|
||||
forName: .NEVPNStatusDidChange, object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
guard let self = self else { return }
|
||||
Task { self.sendEvent("onStatus", try await self.buildStatus()) }
|
||||
}
|
||||
}
|
||||
|
||||
OnDestroy {
|
||||
if let o = self.statusObserver { NotificationCenter.default.removeObserver(o) }
|
||||
}
|
||||
|
||||
// Point the node at a Headscale control server. Stored for the NE to pick up on up(). Does not
|
||||
// start anything. `hostname` overrides the node's advertised name (defaults to the device name).
|
||||
AsyncFunction("configure") { (controlUrl: String, hostname: String?) in
|
||||
let defs = Optional(UserDefaults.standard)
|
||||
defs?.set(controlUrl, forKey: kControlUrl)
|
||||
defs?.set(hostname, forKey: kHostname)
|
||||
// Also stamp it onto the manager's protocol config so the NE has it even before it reads the group.
|
||||
let mgr = try await self.loadOrCreateManager()
|
||||
try await self.applyProviderConfig(mgr)
|
||||
}
|
||||
|
||||
// Register the node with a Headscale pre-auth key. We only stash the key here; the actual
|
||||
// registration happens inside the core on the next up() (the core owns the node/WireGuard keys and
|
||||
// persists them to the Keychain). The key is single-use and short-lived.
|
||||
AsyncFunction("loginWithAuthKey") { (authKey: String) in
|
||||
Optional(UserDefaults.standard)?.set(authKey, forKey: kAuthKey)
|
||||
let mgr = try await self.loadOrCreateManager()
|
||||
try await self.applyProviderConfig(mgr)
|
||||
}
|
||||
|
||||
// Whether a node identity already exists on this device. Written by up() in THIS process — the
|
||||
// NE also writes it, but into a mismatched App Group, so that copy never arrives. See up().
|
||||
AsyncFunction("isRegistered") { () -> Bool in
|
||||
Optional(UserDefaults.standard)?.bool(forKey: kRegistered) ?? false
|
||||
}
|
||||
|
||||
/**
|
||||
Whether the OS has granted this app the right to run a tunnel.
|
||||
|
||||
On iOS the grant IS the saved VPN configuration: you cannot write one without the user approving
|
||||
the system prompt, and removing the profile in Settings deletes it again. So "does a configuration
|
||||
of ours exist" is exactly the question, and `loadAllFromPreferences` is the authority.
|
||||
|
||||
Distinct from `isRegistered`, which asks whether a node identity exists on some tailnet — that can
|
||||
be true while consent is absent, and vice versa. The first-run flow needs them separate.
|
||||
|
||||
ENABLED, not merely present — reversed 2026-08-07.
|
||||
|
||||
This used to answer "does a configuration exist", on the reasoning that a user who switched the
|
||||
VPN off in Settings had still granted permission, and that re-enabling does not prompt again. Both
|
||||
of those are true, and the result was still wrong: switch the VPN off in iOS Settings and the app
|
||||
came back saying "you're already set up on this device, turn the switch on to reconnect" over a
|
||||
tunnel the OS had disabled. Technically accurate, and useless — the one thing that would fix it
|
||||
was the one thing the screen never offered.
|
||||
|
||||
Nothing in this app ever sets `isEnabled = false`; every path here sets it true. So a disabled
|
||||
configuration means the USER disabled it, in Settings or by letting another VPN take the slot, and
|
||||
in both cases the honest answer to "are we authorised to run" is no, with Allow VPN as the way
|
||||
back. Allowing re-enables the existing configuration and does not prompt, exactly as before — the
|
||||
difference is that the screen now offers it.
|
||||
|
||||
Still distinct from `isRegistered`, which asks whether a node identity exists on some tailnet:
|
||||
that can be true while consent is absent, and vice versa. The first-run flow needs them separate.
|
||||
|
||||
Never cache this — a profile can be deleted or disabled at any moment, and a stale `true` leaves a
|
||||
connect toggle that silently does nothing.
|
||||
*/
|
||||
AsyncFunction("isAuthorized") { () async -> Bool in
|
||||
let all = (try? await NETunnelProviderManager.loadAllFromPreferences()) ?? []
|
||||
return all.contains { $0.isEnabled }
|
||||
}
|
||||
|
||||
/**
|
||||
Ask for tunnel authorisation on its own, without connecting.
|
||||
|
||||
Saving the configuration is what raises the system prompt (plus Face ID / passcode). A refusal
|
||||
surfaces as a thrown `NEVPNError`, which is a normal answer here rather than a failure, so it maps
|
||||
to `false` and the caller simply keeps showing "Allow VPN".
|
||||
|
||||
Deliberately does NOT set `onDemandRules` or start the session — that is `up()`'s job. At this
|
||||
point in the first-run flow no control URL has been chosen, so there is nothing to connect to, and
|
||||
an on-demand rule here would have the system endlessly retry a tunnel pointed at nowhere.
|
||||
*/
|
||||
AsyncFunction("requestAuthorization") { () async -> Bool in
|
||||
do {
|
||||
let mgr = try await self.loadOrCreateManager()
|
||||
try await self.applyProviderConfig(mgr)
|
||||
mgr.isEnabled = true
|
||||
try await mgr.saveToPreferences()
|
||||
try await mgr.loadFromPreferences() // re-load so the handle stays valid after save
|
||||
return true
|
||||
} catch {
|
||||
// Drop the cached manager: it may describe a configuration that was never written.
|
||||
self.manager = nil
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Bring the tunnel up: ensure the manager exists + is enabled, then start the NE session. The core
|
||||
// registers (if needed) and connects inside the NE.
|
||||
AsyncFunction("up") { () in
|
||||
let mgr = try await self.loadOrCreateManager()
|
||||
try await self.applyProviderConfig(mgr)
|
||||
mgr.isEnabled = true
|
||||
/*
|
||||
On-demand: the system keeps the tunnel up, including across reboots.
|
||||
|
||||
Without it the VPN comes back DOWN after a restart and stays down until the app is opened and
|
||||
Connect tapped — which is what Andre hit: sites behind the tailnet failed until he noticed.
|
||||
|
||||
A single "connect always" rule. `down()` turns this OFF before stopping, otherwise the system
|
||||
would immediately bring the tunnel back and a manual disconnect would be unhonourable — off
|
||||
has to mean off until the user says otherwise.
|
||||
*/
|
||||
mgr.onDemandRules = [NEOnDemandRuleConnect()]
|
||||
mgr.isOnDemandEnabled = true
|
||||
try await mgr.saveToPreferences()
|
||||
try await mgr.loadFromPreferences() // re-load so the session handle is valid after save
|
||||
/*
|
||||
Start the tunnel, and do NOT fail silently.
|
||||
|
||||
This was `try (mgr.connection as? NETunnelProviderSession)?.startTunnel(...)`. Optional chaining
|
||||
on a failed cast makes the whole statement a no-op that throws nothing, so a tap on the toggle
|
||||
did exactly nothing, reported nothing, and left the UI on "not connected" — indistinguishable
|
||||
from a lost registration.
|
||||
|
||||
The stale-configuration case is the one that actually bites, and it bites on every reinstall:
|
||||
iOS keeps the saved configuration but invalidates it against the new build's extension, so
|
||||
loadAllFromPreferences returns it happily, saveToPreferences reports "unchanged", and
|
||||
startTunnel then refuses. The recovery is to remove the configuration and write a fresh one —
|
||||
which is why this retries rather than surfacing an error the user cannot act on.
|
||||
*/
|
||||
func start(_ m: NETunnelProviderManager) throws {
|
||||
guard let session = m.connection as? NETunnelProviderSession else {
|
||||
throw NSError(domain: "OfficerNet", code: 2, userInfo: [
|
||||
NSLocalizedDescriptionKey: "VPN configuration is not usable (no provider session)",
|
||||
])
|
||||
}
|
||||
try session.startTunnel(options: nil)
|
||||
}
|
||||
|
||||
/*
|
||||
Wait out a teardown before starting.
|
||||
|
||||
stopVPNTunnel() is asynchronous: it returns at once and the session sits in .disconnecting.
|
||||
A startTunnel issued in that window is dropped by iOS, silently — which is why switching a
|
||||
profile (switch, then down, then up) reliably ended DISCONNECTED and needed the toggle pressed
|
||||
by hand to actually apply.
|
||||
*/
|
||||
if mgr.connection.status == .disconnecting {
|
||||
for _ in 0..<40 {
|
||||
if mgr.connection.status != .disconnecting { break }
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try start(mgr)
|
||||
} catch {
|
||||
// Rebuild the configuration from scratch and try once more. Anything still failing after this
|
||||
// is a real error and is allowed to propagate to JS.
|
||||
try? await mgr.removeFromPreferences()
|
||||
self.manager = nil
|
||||
let fresh = try await self.loadOrCreateManager()
|
||||
try await self.applyProviderConfig(fresh)
|
||||
fresh.isEnabled = true
|
||||
fresh.onDemandRules = [NEOnDemandRuleConnect()]
|
||||
fresh.isOnDemandEnabled = true
|
||||
try await fresh.saveToPreferences()
|
||||
try await fresh.loadFromPreferences()
|
||||
try start(fresh)
|
||||
}
|
||||
/*
|
||||
Remember that this device has a node identity.
|
||||
|
||||
The NE writes the same flag into an App Group — but into `group.pastilhas.officer.mobile`,
|
||||
while the app is entitled to `group.dev.officer.mobile`. Different name, so the write goes
|
||||
nowhere and `isRegistered` always answered false. The app then showed the enrolment form and
|
||||
asked for another pre-auth key, on a device whose identity was already valid and persisted:
|
||||
Andre was minting Headscale keys to answer a question the app was wrong about.
|
||||
|
||||
Recorded here, in the app's own storage, because the honest fix needs App Groups enabled on
|
||||
dev.officer.mobile.net in the Apple portal and a wrong move there breaks code-signing for the
|
||||
whole app. See _local_todos/OFFTAIL.md.
|
||||
|
||||
"startTunnel did not throw" is a slightly weaker claim than "the core has an identity", but the
|
||||
core only gets that far with a usable key or an existing identity, so in practice they coincide.
|
||||
*/
|
||||
UserDefaults.standard.set(true, forKey: kRegistered)
|
||||
}
|
||||
|
||||
/*
|
||||
Bring the tunnel down and KEEP it down. Node identity is untouched.
|
||||
|
||||
On-demand is disabled first and saved before stopping: with it still on, the system treats a
|
||||
stopped tunnel as something to fix and reconnects within seconds, so a manual disconnect would
|
||||
not stick. Turning it off is what makes "off" mean off until the user reconnects — and it
|
||||
survives reboots the same way "on" does.
|
||||
*/
|
||||
AsyncFunction("down") { () in
|
||||
let mgr = try await self.loadOrCreateManager()
|
||||
mgr.isOnDemandEnabled = false
|
||||
try? await mgr.saveToPreferences()
|
||||
mgr.connection.stopVPNTunnel()
|
||||
}
|
||||
|
||||
// Current status snapshot: connection state from the manager + self/peer detail from the NE.
|
||||
AsyncFunction("status") { () async throws -> [String: Any?] in
|
||||
try await self.buildStatus()
|
||||
}
|
||||
|
||||
// Debug: the NE's diagnostic ring buffer (bring-up flow), fetched via provider message. Reliable —
|
||||
// unlike idevicesyslog, which drops NE os_log lines under burst load.
|
||||
AsyncFunction("coreDiag") { () async -> String in
|
||||
if self.manager == nil {
|
||||
self.manager = try? await NETunnelProviderManager.loadAllFromPreferences().first
|
||||
}
|
||||
guard let session = self.manager?.connection as? NETunnelProviderSession else { return "(no session)" }
|
||||
return await self.neDiag(session)
|
||||
}
|
||||
|
||||
// Forget the node identity + keys (full reset): tear down, tell the NE to wipe the core's keychain
|
||||
// identity, remove the manager, and clear stored config.
|
||||
AsyncFunction("logout") { () in
|
||||
/*
|
||||
Order matters, and getting it wrong is what made logout cosmetic.
|
||||
|
||||
The node identity is `tailscaled.state` in the EXTENSION's container — nothing in this process
|
||||
can reach it, so removing the VPN configuration and our own UserDefaults left a fully valid
|
||||
node on disk. Logging out and reinstalling came back as the same machine.
|
||||
|
||||
So: ask the running extension to wipe it FIRST, while there is still a session to talk to, and
|
||||
only then stop the tunnel and remove the configuration. Tearing the tunnel down first would
|
||||
kill the only channel that can do the deletion.
|
||||
*/
|
||||
if let mgr = try? await self.loadOrCreateManager() {
|
||||
/*
|
||||
The identity can only be deleted by the extension, and the extension only exists while the
|
||||
tunnel runs. Logging out from a DISCONNECTED state therefore wiped nothing — and because the
|
||||
app-side flags below clear regardless, the UI showed a convincing first run over an identity
|
||||
that was still on disk. The next "fresh" sign-in then reconnected instantly as the same node.
|
||||
|
||||
So bring the tunnel up briefly, purely to have someone to give the order to. Ugly, but the
|
||||
alternative is a reset that quietly does not reset, which is worse than slow.
|
||||
*/
|
||||
let status = mgr.connection.status
|
||||
if status != .connected && status != .connecting {
|
||||
try? await self.applyProviderConfig(mgr)
|
||||
mgr.isEnabled = true
|
||||
// No on-demand rule here: this tunnel exists to be torn down a second later, and an
|
||||
// on-demand rule would have the system dutifully bring it straight back.
|
||||
mgr.isOnDemandEnabled = false
|
||||
try? await mgr.saveToPreferences()
|
||||
try? await mgr.loadFromPreferences()
|
||||
try? (mgr.connection as? NETunnelProviderSession)?.startTunnel(options: nil)
|
||||
// Up to ~5s. A node with a stored identity needs no network to reach `connected`, and the
|
||||
// wipe only needs the process alive, not a working tailnet.
|
||||
for _ in 0..<20 {
|
||||
if mgr.connection.status == .connected || mgr.connection.status == .disconnected { break }
|
||||
try? await Task.sleep(nanoseconds: 250_000_000)
|
||||
}
|
||||
}
|
||||
_ = await self.neCommand("wipe")
|
||||
mgr.connection.stopVPNTunnel()
|
||||
try? await mgr.removeFromPreferences()
|
||||
}
|
||||
self.manager = nil
|
||||
let defs = Optional(UserDefaults.standard)
|
||||
[kControlUrl, kHostname, kAuthKey, kRegistered].forEach { defs?.removeObject(forKey: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NETunnelProviderManager plumbing
|
||||
|
||||
/// Load the existing OffTail manager or create a fresh one. There is at most one per app.
|
||||
private func loadOrCreateManager() async throws -> NETunnelProviderManager {
|
||||
if let m = manager { return m }
|
||||
let all = try await NETunnelProviderManager.loadAllFromPreferences()
|
||||
let m = all.first ?? NETunnelProviderManager()
|
||||
manager = m
|
||||
return m
|
||||
}
|
||||
|
||||
/// Write the NETunnelProviderProtocol (which NE target + control server) and providerConfiguration
|
||||
/// (controlUrl/hostname/authKey the NE reads at startTunnel). serverAddress is display-only for iOS.
|
||||
private func applyProviderConfig(_ mgr: NETunnelProviderManager) async throws {
|
||||
let defs = Optional(UserDefaults.standard)
|
||||
let controlUrl = defs?.string(forKey: kControlUrl) ?? ""
|
||||
|
||||
let proto = (mgr.protocolConfiguration as? NETunnelProviderProtocol) ?? NETunnelProviderProtocol()
|
||||
proto.providerBundleIdentifier = neBundleId
|
||||
// Display-only on iOS: the NE gets the real control URL through providerConfiguration below, so
|
||||
// this string is free to be branding rather than a hostname. It is the likelier of the two
|
||||
// candidates for the second line iOS shows under the VPN entry in Settings.
|
||||
proto.serverAddress = "Officer Suite"
|
||||
var cfg: [String: Any] = [:]
|
||||
if let v = defs?.string(forKey: kControlUrl) { cfg[kControlUrl] = v }
|
||||
if let v = defs?.string(forKey: kHostname) { cfg[kHostname] = v }
|
||||
if let v = defs?.string(forKey: kAuthKey) { cfg[kAuthKey] = v }
|
||||
proto.providerConfiguration = cfg
|
||||
mgr.protocolConfiguration = proto
|
||||
// The name iOS shows for this VPN configuration in Settings. Was "OffTail", which predates the
|
||||
// rename and is the string users actually see in Settings > General > VPN.
|
||||
mgr.localizedDescription = "OffScale"
|
||||
}
|
||||
|
||||
/// Map the NE connection state to the JS VpnState, and merge in self/peer detail the NE publishes to
|
||||
/// the App Group. The rich peer list originates from the Tailscale core inside the NE.
|
||||
private func buildStatus() async throws -> [String: Any?] {
|
||||
// Ensure we're reading the live system VPN state even after an app relaunch / backgrounding, when
|
||||
// `self.manager` may not be cached yet — otherwise status falsely reads "stopped" while connected.
|
||||
if manager == nil {
|
||||
manager = try? await NETunnelProviderManager.loadAllFromPreferences().first
|
||||
}
|
||||
let state: String
|
||||
switch manager?.connection.status ?? .invalid {
|
||||
case .connecting, .reasserting: state = "connecting"
|
||||
case .connected: state = "connected"
|
||||
case .disconnecting, .disconnected, .invalid: state = "stopped"
|
||||
@unknown default: state = "stopped"
|
||||
}
|
||||
|
||||
// Pull self/peer detail straight from the core inside the NE via a provider message — this works
|
||||
// cross-process without an App Group (the NE's handleAppMessage returns TailcoreStatus() JSON, in
|
||||
// Tailscale's ipnstate shape: Self.TailscaleIPs / Self.DNSName / Peer{}). Only meaningful once the
|
||||
// tunnel is up.
|
||||
var selfNode: [String: Any?]? = nil
|
||||
var peers: [[String: Any?]] = []
|
||||
var authUrl: String? = nil
|
||||
var backendState = state
|
||||
// Kept outside the block below so the return value can read the exit-node health from it.
|
||||
var coreStatus: [String: Any]? = nil
|
||||
if state == "connected" || state == "connecting",
|
||||
let session = manager?.connection as? NETunnelProviderSession,
|
||||
let fetched = await neCoreStatus(session) {
|
||||
coreStatus = fetched
|
||||
let core = fetched
|
||||
if let s = core["Self"] as? [String: Any] {
|
||||
let ips = (s["TailscaleIPs"] as? [String]) ?? []
|
||||
// MagicDNS names arrive fully qualified with a trailing dot ("host.tailnet.ts.net.") — correct
|
||||
// as DNS, but it reads like a typo in a UI.
|
||||
let dns = (s["DNSName"] as? String).map { $0.hasSuffix(".") ? String($0.dropLast()) : $0 }
|
||||
let host = s["HostName"] as? String
|
||||
|
||||
/*
|
||||
The account this node was registered under.
|
||||
|
||||
`ipnstate.Status` carries a `User` map keyed by the numeric user id, and `Self.UserID` points
|
||||
into it — so the login email has been in this JSON all along, just never read. It is the one
|
||||
piece that answers "which account is this?", which matters as soon as more than one tailnet
|
||||
can be signed in.
|
||||
*/
|
||||
var login: String?
|
||||
let uid = (s["UserID"] as? NSNumber)?.stringValue ?? (s["UserID"] as? String)
|
||||
if let uid, let users = core["User"] as? [String: Any],
|
||||
let u = users[uid] as? [String: Any] {
|
||||
login = (u["LoginName"] as? String) ?? (u["DisplayName"] as? String)
|
||||
}
|
||||
|
||||
let tailnet = (core["CurrentTailnet"] as? [String: Any])?["Name"] as? String
|
||||
|
||||
/*
|
||||
The other machines on the tailnet.
|
||||
|
||||
`peers` was declared and returned empty from the day this was written, so the peer list in the
|
||||
UI — tap to copy an IP, long-press for the MagicDNS name — has never had anything to render.
|
||||
ipnstate.Status keys them by public key under "Peer".
|
||||
|
||||
ExitNodeOption / ExitNode ride along because picking an exit node needs both: which peers offer
|
||||
to be one, and which one is currently in use.
|
||||
*/
|
||||
if let peerMap = core["Peer"] as? [String: Any] {
|
||||
peers = peerMap.values.compactMap { raw in
|
||||
guard let p = raw as? [String: Any] else { return nil }
|
||||
let ips = (p["TailscaleIPs"] as? [String]) ?? []
|
||||
let dns = (p["DNSName"] as? String).map { $0.hasSuffix(".") ? String($0.dropLast()) : $0 }
|
||||
let host = p["HostName"] as? String
|
||||
return [
|
||||
// StableID is the durable identifier; the public key is the map key and changes on rekey.
|
||||
"id": (p["ID"] as? String) ?? dns ?? host ?? UUID().uuidString,
|
||||
"name": (dns ?? host ?? "") as Any?,
|
||||
"hostName": host as Any?,
|
||||
"ips": ips,
|
||||
"online": (p["Online"] as? Bool) ?? false,
|
||||
"os": p["OS"] as Any?,
|
||||
"lastSeen": p["LastSeen"] as Any?,
|
||||
"exitNodeOption": (p["ExitNodeOption"] as? Bool) ?? false,
|
||||
"exitNode": (p["ExitNode"] as? Bool) ?? false,
|
||||
]
|
||||
}
|
||||
// Online first, then by name: a tailnet of any size is unreadable in map order, which is
|
||||
// whatever the JSON decoder produced.
|
||||
.sorted {
|
||||
let (a, b) = (($0["online"] as? Bool) ?? false, ($1["online"] as? Bool) ?? false)
|
||||
if a != b { return a }
|
||||
return (($0["name"] as? String) ?? "") .localizedCaseInsensitiveCompare(($1["name"] as? String) ?? "") == .orderedAscending
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
When does this device's key expire, and has it already?
|
||||
|
||||
A node key expires on the tailnet's own schedule — often 180 days — and when it does the
|
||||
device silently stops working until re-authorised. Reporting it lets the app warn first
|
||||
rather than presenting expiry as a mysterious disconnection.
|
||||
*/
|
||||
let keyExpiry = s["KeyExpiry"] as? String
|
||||
let expired = (s["Expired"] as? Bool) ?? false
|
||||
|
||||
selfNode = [
|
||||
"keyExpiry": keyExpiry as Any?,
|
||||
"expired": expired,
|
||||
// Prefer the short host name for display; the fully-qualified one is still available.
|
||||
"name": (host ?? dns) as Any?,
|
||||
"magicDNSName": dns as Any?,
|
||||
"ips": ips,
|
||||
"hostName": host as Any?,
|
||||
"os": s["OS"] as Any?,
|
||||
"loginName": login as Any?,
|
||||
"tailnet": tailnet as Any?,
|
||||
]
|
||||
}
|
||||
|
||||
// The NE being up says nothing about whether the NODE is authorised. `state` above comes from
|
||||
// NEVPNConnection, which reports "connected" the moment the tunnel exists — while the core can
|
||||
// still be sitting in NeedsLogin waiting for a human. Android reads BackendState directly and
|
||||
// so must this, or interactive login is invisible on iOS.
|
||||
/*
|
||||
Every backend state is mapped, not just NeedsLogin.
|
||||
|
||||
Handling only NeedsLogin left `Starting` and `NoState` falling through as "connected", which is
|
||||
the window right after startTunnel — the tunnel exists, the core has not finished coming up, and
|
||||
nothing is authorised. The UI showed a connected toggle with no data for several seconds, then
|
||||
jumped to a sign-in prompt. From the outside that reads as "it connected, then changed its mind".
|
||||
|
||||
`Running` is the only state that earns "connected".
|
||||
*/
|
||||
switch core["BackendState"] as? String {
|
||||
case "NeedsLogin":
|
||||
backendState = "needsLogin"
|
||||
// Straight from ipnstate.Status.AuthURL — already in this JSON, never read until now.
|
||||
authUrl = (core["AuthURL"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
||||
case "Running":
|
||||
backendState = "connected"
|
||||
case "Starting", "NoState", "Stopped":
|
||||
backendState = "connecting"
|
||||
default:
|
||||
break // unknown state: leave the NE-derived value rather than inventing one
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
"state": backendState,
|
||||
"self": selfNode as Any?,
|
||||
"peers": peers,
|
||||
"error": nil,
|
||||
"authUrl": authUrl as Any?,
|
||||
// Which control plane this node is talking to. The app knows it because it configured it, but
|
||||
// sending it with the status keeps "who am I connected to" answerable from one object rather
|
||||
// than correlating two — and it is what distinguishes Tailscale from a self-hosted Headscale.
|
||||
"controlUrl": Optional(UserDefaults.standard)?.string(forKey: kControlUrl) as Any?,
|
||||
/*
|
||||
The exit node's own health, straight from the core.
|
||||
|
||||
When an exit node goes offline the traffic stops rather than escaping around the tunnel — the
|
||||
safe failure — but the app went on saying "Connected" with no explanation. Reported so the
|
||||
screen can say what is actually happening.
|
||||
*/
|
||||
"exitNodeOnline": (coreStatus?["ExitNodeStatus"] as? [String: Any])?["Online"] as Any?,
|
||||
/*
|
||||
Our configuration exists but iOS has deselected it — which is what happens when another VPN
|
||||
app (the official Tailscale client, say) takes the slot, since only one can be active.
|
||||
|
||||
Reported so the UI can SAY that. Without it, being superseded looks identical to a plain
|
||||
failure to connect: the toggle sits at "Not connected" with no reason given, and the honest
|
||||
explanation — something else is using the tunnel — is invisible. Last-connected-wins is fine
|
||||
as a rule; silently losing is not.
|
||||
*/
|
||||
"supersededByOtherVpn": (manager != nil && manager?.isEnabled == false),
|
||||
]
|
||||
}
|
||||
|
||||
/// Ask the running NE for the core's status JSON (self IPs + backend state) via a provider message.
|
||||
/// Returns the decoded ipnstate object, or nil if the tunnel isn't up / doesn't answer promptly.
|
||||
/**
|
||||
Send a raw command to the NE and get its reply as a string.
|
||||
|
||||
The generalisation of `neCoreStatus`, needed because the core lives in the extension: profile
|
||||
operations act on the running LocalBackend, and the app process does not have one. Calling
|
||||
`TailcoreListProfiles()` here would compile and return "[]" forever.
|
||||
*/
|
||||
/// - Parameter timeout: 1.5s suits a status read. Profile MUTATIONS need far longer — creating or
|
||||
/// switching a profile makes the backend re-key and fetch a fresh netmap, which does not finish in
|
||||
/// a second and a half. Timing out there returns nil, and nil used to be read as success.
|
||||
private func neCommand(_ command: String, timeout: TimeInterval = 1.5) async -> String? {
|
||||
guard let session = manager?.connection as? NETunnelProviderSession else { return nil }
|
||||
return await withCheckedContinuation { (cont: CheckedContinuation<String?, Never>) in
|
||||
let resumed = ResumeOnce()
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { if resumed.take() { cont.resume(returning: nil) } }
|
||||
do {
|
||||
try session.sendProviderMessage(Data(command.utf8)) { resp in
|
||||
guard resumed.take() else { return }
|
||||
cont.resume(returning: resp.flatMap { String(data: $0, encoding: .utf8) })
|
||||
}
|
||||
} catch {
|
||||
if resumed.take() { cont.resume(returning: nil) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func neCoreStatus(_ session: NETunnelProviderSession) async -> [String: Any]? {
|
||||
await withCheckedContinuation { (cont: CheckedContinuation<[String: Any]?, Never>) in
|
||||
let resumed = ResumeOnce()
|
||||
// Guard against a hung continuation if the NE never calls back.
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { if resumed.take() { cont.resume(returning: nil) } }
|
||||
do {
|
||||
try session.sendProviderMessage(Data("status".utf8)) { resp in
|
||||
guard resumed.take() else { return }
|
||||
if let resp = resp, let obj = try? JSONSerialization.jsonObject(with: resp) as? [String: Any] {
|
||||
cont.resume(returning: obj)
|
||||
} else {
|
||||
cont.resume(returning: nil)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if resumed.take() { cont.resume(returning: nil) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the running NE for its diagnostic ring buffer (a plain string) via a provider message.
|
||||
private func neDiag(_ session: NETunnelProviderSession) async -> String {
|
||||
await withCheckedContinuation { (cont: CheckedContinuation<String, Never>) in
|
||||
let resumed = ResumeOnce()
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { if resumed.take() { cont.resume(returning: "(diag timeout)") } }
|
||||
do {
|
||||
try session.sendProviderMessage(Data("diag".utf8)) { resp in
|
||||
guard resumed.take() else { return }
|
||||
cont.resume(returning: resp.flatMap { String(data: $0, encoding: .utf8) } ?? "(no diag)")
|
||||
}
|
||||
} catch {
|
||||
if resumed.take() { cont.resume(returning: "(diag err: \(error.localizedDescription))") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
import NetworkExtension
|
||||
import TailCore // the vendored gomobile Tailscale core (Tailcore{Start,Stop,Status,…})
|
||||
import os.log
|
||||
|
||||
// OffTail VPN data plane — iOS. This is the Network Extension: a SEPARATE executable bundled inside the
|
||||
// same app (NE App ID `dev.officer.mobile.net`), running in its own process. It owns the utun device and
|
||||
// hands its raw file descriptor to the embedded Tailscale core (TailCore.xcframework), which then does
|
||||
// all packet I/O + WireGuard/magicsock/DERP itself — the same fd-handoff pattern WireGuard-iOS uses, so
|
||||
// there's no Swift packet loop.
|
||||
//
|
||||
// This file compiles into the NE target (added as a manual Xcode step — see plugin/README.md) AND into
|
||||
// the OfficerNet pod, so its TailcoreStart call is compile-checked in every app build.
|
||||
//
|
||||
// ⚠️ MEMORY BUDGET: iOS gives a packet tunnel a HARD ceiling (~50 MB; jetsam-killed above it). The core
|
||||
// runs WireGuard in USERSPACE via netstack (no kernel WireGuard on iOS). Keep the peer set small. See
|
||||
// TAILSCALE_VPN.md → "Memory budget".
|
||||
//
|
||||
// LAST MILE (needs on-device testing + a reachable Headscale): the network settings below use a
|
||||
// placeholder address/route. The REAL per-node IP, routes, and MagicDNS come from the core's netmap
|
||||
// (poll TailcoreStatus / add a netmap callback) and must be applied via setTunnelNetworkSettings — the
|
||||
// router/DNS bridge. Until that's wired from the live netmap, routing won't be correct.
|
||||
|
||||
private let appGroup = "group.pastilhas.officer.mobile"
|
||||
private let log = OSLog(subsystem: "dev.officer.mobile.net", category: "PacketTunnel")
|
||||
|
||||
class PacketTunnelProvider: NEPacketTunnelProvider {
|
||||
|
||||
// In-NE diagnostic ring buffer, surfaced to the app via handleAppMessage("diag"). idevicesyslog drops
|
||||
// os_log lines under burst load, so this is the reliable way to see the bring-up flow on-device.
|
||||
private var diag: [String] = []
|
||||
private let diagLock = NSLock()
|
||||
private func d(_ s: String) {
|
||||
diagLock.lock()
|
||||
diag.append(s)
|
||||
if diag.count > 80 { diag.removeFirst() }
|
||||
diagLock.unlock()
|
||||
// .default, NOT .info: idevicesyslog drops OS_LOG_TYPE_INFO, so an .info line reads exactly like
|
||||
// code that never ran — which is how the identity wipe was nearly misdiagnosed as not executing.
|
||||
os_log("DIAG %{public}@", log: log, type: .default, s)
|
||||
}
|
||||
|
||||
override func startTunnel(options: [String: NSObject]?,
|
||||
completionHandler: @escaping (Error?) -> Void) {
|
||||
os_log("startTunnel", log: log, type: .info)
|
||||
d("startTunnel")
|
||||
markRunStarted()
|
||||
|
||||
// 1. Read config the main app stashed (providerConfiguration wins; App Group is the fallback).
|
||||
let proto = protocolConfiguration as? NETunnelProviderProtocol
|
||||
let cfg = proto?.providerConfiguration ?? [:]
|
||||
let defs = UserDefaults(suiteName: appGroup)
|
||||
let controlUrl = (cfg["controlUrl"] as? String) ?? defs?.string(forKey: "controlUrl") ?? ""
|
||||
let hostname = (cfg["hostname"] as? String) ?? defs?.string(forKey: "hostname") ?? ""
|
||||
let authKey = (cfg["authKey"] as? String) ?? defs?.string(forKey: "authKey") ?? ""
|
||||
guard !controlUrl.isEmpty else {
|
||||
completionHandler(NSError(domain: "OfficerNet", code: 1,
|
||||
userInfo: [NSLocalizedDescriptionKey: "No controlUrl configured"]))
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Apply tunnel network settings so iOS creates the utun and starts routing into it.
|
||||
// TODO(netmap): replace the placeholder IP/route with the core's assigned node IP + routes from
|
||||
// TailcoreStatus (100.64.0.0/10 + advertised subnets) and MagicDNS — the router/DNS last mile.
|
||||
// tunnelRemoteAddress MUST be a valid IP literal, not a URL — it's informational for a mesh VPN
|
||||
// (there's no single server). Passing the control URL here fails with "Invalid tunnelRemoteAddress"
|
||||
// and the tunnel dies before the core starts. Use a placeholder IP.
|
||||
//
|
||||
// KNOWN node IP → apply the REAL settings once, here, before the core starts. That is the whole
|
||||
// fix: the previous flow applied a placeholder, started the core, then re-applied real settings
|
||||
// on a live tunnel, and re-applying is a documented iOS teardown trap. The identity persists in
|
||||
// the state dir so the IP is stable — only the very first connect on a device lacks one.
|
||||
let known = savedIPs()
|
||||
let settings: NEPacketTunnelNetworkSettings
|
||||
if known.isEmpty {
|
||||
d("no saved node IP — first connect, using placeholder and refining after the netmap")
|
||||
settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1")
|
||||
let ipv4 = NEIPv4Settings(addresses: ["100.64.0.1"], subnetMasks: ["255.192.0.0"])
|
||||
ipv4.includedRoutes = [NEIPv4Route(destinationAddress: "100.64.0.0", subnetMask: "255.192.0.0")]
|
||||
settings.ipv4Settings = ipv4
|
||||
settings.mtu = 1280
|
||||
} else {
|
||||
d("saved node IP \(known) — applying real settings up front, no swap")
|
||||
settings = tunnelSettings(selfIPs: known, magicDNSSuffix: nil)
|
||||
}
|
||||
|
||||
setTunnelNetworkSettings(settings) { [weak self] error in
|
||||
guard let self = self else { return }
|
||||
if let error = error {
|
||||
os_log("setTunnelNetworkSettings failed: %{public}@", log: log, type: .error, error.localizedDescription)
|
||||
self.d("placeholder setTunnelNetworkSettings FAILED: \(error.localizedDescription)")
|
||||
completionHandler(error)
|
||||
return
|
||||
}
|
||||
self.d("placeholder settings applied")
|
||||
|
||||
// 3. Hand the utun fd to the Tailscale core and bring the node up against Headscale. The core reads
|
||||
// /writes the fd itself — no Swift packet loop. The auth key is single-use; drop it after.
|
||||
guard let fd = self.utunFileDescriptor() else {
|
||||
self.d("utun fd NOT FOUND")
|
||||
completionHandler(NSError(domain: "OfficerNet", code: 2,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Could not locate the utun file descriptor"]))
|
||||
return
|
||||
}
|
||||
self.d("utun fd = \(fd)")
|
||||
// Persist the node identity in a STABLE dir (Application Support), not NSTemporaryDirectory — else
|
||||
// the core loses its keys on every restart and registers a brand-new node each connect.
|
||||
let stateDir = self.stateDirectory()
|
||||
// gomobile exposes Start as a C function returning BOOL with an NSError out-param (not throwing).
|
||||
// NO upstream DNS here, deliberately — unlike Android. matchDomains below scopes the capture
|
||||
// to the tailnet suffix, so only short names ever reach the core's resolver and it never has
|
||||
// to forward anything. Android has no matchDomains equivalent, must route ALL DNS at the core,
|
||||
// and therefore does need TailcoreSetUpstreamDNS.
|
||||
var startErr: NSError?
|
||||
let ok = TailcoreStart(fd, controlUrl, authKey, hostname, stateDir, &startErr)
|
||||
if ok {
|
||||
self.d("TailcoreStart OK — waiting for netmap IP, then completing")
|
||||
defs?.set(true, forKey: "registered") // an identity now exists on this device
|
||||
defs?.removeObject(forKey: "authKey") // single-use pre-auth key — don't keep it
|
||||
if !known.isEmpty {
|
||||
// Settings are already correct. Complete NOW: a provider that sits on its completion
|
||||
// handler risks being torn down, and there is nothing left to wait for.
|
||||
self.d("real settings already applied — completing immediately")
|
||||
completionHandler(nil)
|
||||
// Still watch the netmap, purely to keep the saved IP current if Headscale reassigns it.
|
||||
self.refreshSavedIPs()
|
||||
} else {
|
||||
// First connect only. Complete on the placeholder rather than blocking for up to 15s —
|
||||
// the previous version waited before completing, which is its own teardown risk — and
|
||||
// refine once the netmap lands so the NEXT connect takes the fast path above.
|
||||
self.d("first connect — completing on placeholder, refining in background")
|
||||
completionHandler(nil)
|
||||
self.refineSettingsFromNetmap()
|
||||
}
|
||||
} else {
|
||||
let e = startErr ?? NSError(domain: "OfficerNet", code: 3,
|
||||
userInfo: [NSLocalizedDescriptionKey: "TailcoreStart failed"])
|
||||
os_log("TailcoreStart failed: %{public}@", log: log, type: .error, e.localizedDescription)
|
||||
self.d("TailcoreStart FAILED: \(e.localizedDescription)")
|
||||
completionHandler(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func stopTunnel(with reason: NEProviderStopReason,
|
||||
completionHandler: @escaping () -> Void) {
|
||||
os_log("stopTunnel: %{public}d", log: log, type: .info, reason.rawValue)
|
||||
d("stopTunnel reason=\(reason.rawValue)")
|
||||
markRunStopped(reason: reason.rawValue)
|
||||
TailcoreStop()
|
||||
completionHandler()
|
||||
}
|
||||
|
||||
/// Answer app-messages from the main process. "diag" → the NE's diagnostic ring buffer (reliable, since
|
||||
/// idevicesyslog drops lines); anything else → the core status JSON (self IPs + peers).
|
||||
/**
|
||||
The app's only channel to the core.
|
||||
|
||||
On iOS the Tailscale core runs in THIS process, not the app's — so anything the app wants from
|
||||
`LocalBackend` has to come through here. That is invisible until you try to add a feature: calling
|
||||
`TailcoreListProfiles()` from the app compiles perfectly and returns "[]", because the app's copy
|
||||
of the package has a nil backend. Android has no such split, which is why its module can call the
|
||||
Go directly and this one cannot.
|
||||
|
||||
The protocol is a string command. It stays deliberately dumb — a verb, optionally a colon and an
|
||||
argument — because it is a private channel between two halves of the same app, and a real
|
||||
serialisation format here would be ceremony.
|
||||
*/
|
||||
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
|
||||
let msg = String(data: messageData, encoding: .utf8) ?? ""
|
||||
|
||||
if msg == "diag" {
|
||||
diagLock.lock(); let out = diag.joined(separator: "\n"); diagLock.unlock()
|
||||
completionHandler?(out.data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy the node identity, for real.
|
||||
|
||||
`logout()` in the app could only ever remove the VPN configuration and its own UserDefaults. The
|
||||
identity is `tailscaled.state`, written by the CORE inside THIS process's container — so nothing
|
||||
the app can reach touches it, and it survived logout and reinstall alike. That is why signing out
|
||||
and installing again silently came back as the same node.
|
||||
|
||||
Only the extension can do this, and only with the core stopped: `store.New` holds the file open,
|
||||
and deleting it underneath a running backend leaves the identity in memory to be written back.
|
||||
Stop first, then delete, and let the app tear the tunnel down afterwards.
|
||||
*/
|
||||
if msg == "wipe" {
|
||||
d("wipe: stopping core and deleting persisted identity")
|
||||
TailcoreStop()
|
||||
let fm = FileManager.default
|
||||
let dir = URL(fileURLWithPath: stateDirectory())
|
||||
// The whole directory, not just tailscaled.state: the cached node IPs and MagicDNS suffix are
|
||||
// derived from the identity, and leaving them behind reapplies settings for a node that no
|
||||
// longer exists.
|
||||
for name in ["tailscaled.state", "node-ips.json", "magicdns-suffix.txt"] {
|
||||
try? fm.removeItem(at: dir.appendingPathComponent(name))
|
||||
}
|
||||
d("wipe: done")
|
||||
completionHandler?("ok".data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
// Preferences that change while running: the exit node and route acceptance. Everything else the
|
||||
// core is configured with is set once at Start; these two are chosen and changed live.
|
||||
/*
|
||||
Hand over a pending abnormal-exit report, once.
|
||||
|
||||
The app cannot read this file itself: the marker lives in the EXTENSION's container, and the two
|
||||
do not share an App Group (see the group.pastilhas.officer.mobile vs group.dev.officer.mobile
|
||||
mismatch documented above). This channel is the only way across, which is also why it is a `take`
|
||||
rather than a `get` — collected means reported, and reporting the same crash on every launch would
|
||||
be worse than not reporting it.
|
||||
*/
|
||||
if msg == "diag:lastexit" {
|
||||
let report = takeLastExitReport()
|
||||
if !report.isEmpty { d("handing over last-exit report: \(report)") }
|
||||
completionHandler?(report.data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg.hasPrefix("prefs:exitnode:") {
|
||||
let id = String(msg.dropFirst("prefs:exitnode:".count))
|
||||
d("prefs:exitnode \(id.isEmpty ? "(none)" : id)")
|
||||
var err: NSError?
|
||||
TailcoreSetExitNode(id, &err)
|
||||
d("prefs:exitnode -> \(err?.localizedDescription ?? "ok")")
|
||||
/*
|
||||
Re-apply the tunnel settings, because the ROUTES changed.
|
||||
|
||||
The preference lives in the core and the routes live in the tun; only this reconciles them.
|
||||
Without it, selecting an exit node sets a preference and the OS carries on sending everything
|
||||
but tailnet traffic straight out over Wi-Fi — the exit node never sees a packet, and on and off
|
||||
look identical.
|
||||
|
||||
Applied on the live tunnel rather than restarting it: the same path the netmap refine already
|
||||
uses, and far less disruptive than dropping the connection to change a route.
|
||||
*/
|
||||
if err == nil {
|
||||
let ips = savedIPs()
|
||||
if !ips.isEmpty {
|
||||
applySettings(selfIPs: ips, magicDNSSuffix: savedSuffix())
|
||||
} else {
|
||||
d("prefs:exitnode: no saved IPs yet — routes will follow on the next netmap")
|
||||
}
|
||||
}
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg.hasPrefix("prefs:routes:") {
|
||||
let on = msg.hasSuffix(":1")
|
||||
d("prefs:routes \(on)")
|
||||
var err: NSError?
|
||||
TailcoreSetAcceptRoutes(on, &err)
|
||||
d("prefs:routes -> \(err?.localizedDescription ?? "ok")")
|
||||
// Same reasoning as the exit node: the preference is in the core, the routes are in the tun,
|
||||
// and only re-applying reconciles them.
|
||||
if err == nil {
|
||||
let ips = savedIPs()
|
||||
if !ips.isEmpty { applySettings(selfIPs: ips, magicDNSSuffix: savedSuffix()) }
|
||||
}
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg == "prefs:get" {
|
||||
completionHandler?(TailcorePrefs().data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg == "profiles:list" {
|
||||
let json = TailcoreListProfiles()
|
||||
// Traced because an empty list is ambiguous from the app side: it looks identical whether the
|
||||
// core has no profiles, the message timed out, or the reply failed to parse. The trace says
|
||||
// which, and costs nothing.
|
||||
d("profiles:list -> \(json.count) chars: \(json.prefix(300))")
|
||||
completionHandler?(json.data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
Join another tailnet on the LIVE backend.
|
||||
|
||||
Payload is base64 JSON because a control URL and a pre-auth key both contain characters that a
|
||||
`:`-delimited command cannot carry safely.
|
||||
|
||||
This exists because NewProfile + restart cannot work: restarting drops the unregistered blank
|
||||
profile and Start then overwrites the surviving one, so a second tailnet replaced the first
|
||||
under the same profile id. Doing both steps inside the core, without a restart, is the only
|
||||
ordering where neither undoes the other.
|
||||
*/
|
||||
if msg.hasPrefix("profiles:login:") {
|
||||
let b64 = String(msg.dropFirst("profiles:login:".count))
|
||||
guard let data = Data(base64Encoded: b64),
|
||||
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
d("profiles:login -> bad payload")
|
||||
completionHandler?("bad payload".data(using: .utf8))
|
||||
return
|
||||
}
|
||||
let controlUrl = (obj["controlUrl"] as? String) ?? ""
|
||||
let authKey = (obj["authKey"] as? String) ?? ""
|
||||
let hostname = (obj["hostname"] as? String) ?? ""
|
||||
d("profiles:login control=\(controlUrl) key=\(authKey.isEmpty ? "none" : "yes")")
|
||||
var err: NSError?
|
||||
TailcoreLoginTo(controlUrl, authKey, hostname, &err)
|
||||
d("profiles:login -> \(err?.localizedDescription ?? "ok")")
|
||||
// The new profile has its own node IP; the cached one belongs to the tailnet we just left.
|
||||
if err == nil { self.forgetCachedNetmap() }
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg == "profiles:new" {
|
||||
// Errors come back as a string rather than a thrown NSError: the channel carries Data, and the
|
||||
// app only needs to know whether it worked and why not.
|
||||
d("profiles:new — creating a blank profile")
|
||||
var err: NSError?
|
||||
TailcoreNewProfile(&err)
|
||||
d("profiles:new -> \(err?.localizedDescription ?? "ok")")
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg.hasPrefix("profiles:switch:") {
|
||||
var err: NSError?
|
||||
let switchID = String(msg.dropFirst("profiles:switch:".count))
|
||||
d("profiles:switch \(switchID)")
|
||||
TailcoreSwitchProfile(switchID, &err)
|
||||
d("profiles:switch -> \(err?.localizedDescription ?? "ok")")
|
||||
if err == nil { self.forgetCachedNetmap() }
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
if msg.hasPrefix("profiles:delete:") {
|
||||
var err: NSError?
|
||||
let deleteID = String(msg.dropFirst("profiles:delete:".count))
|
||||
d("profiles:delete \(deleteID)")
|
||||
TailcoreDeleteProfile(deleteID, &err)
|
||||
d("profiles:delete -> \(err?.localizedDescription ?? "ok")")
|
||||
completionHandler?((err?.localizedDescription ?? "").data(using: .utf8))
|
||||
return
|
||||
}
|
||||
|
||||
let status = TailcoreStatus()
|
||||
completionHandler?(status.data(using: .utf8))
|
||||
}
|
||||
|
||||
// MARK: - State dir + netmap-driven settings
|
||||
|
||||
/**
|
||||
The node's tailnet IPs, remembered from the last successful netmap.
|
||||
|
||||
Kept in the NE's OWN state dir, not an App Group. The NE currently has no App Group entitlement at
|
||||
all, and adding one needs App Groups enabled on the `dev.officer.mobile.net` App ID in the Apple
|
||||
portal — requesting an entitlement the App ID does not carry fails code-signing for the WHOLE app.
|
||||
Nothing else needs to read this, so the extension's own container is both sufficient and free.
|
||||
*/
|
||||
|
||||
/*
|
||||
Forget the cached node IP and MagicDNS suffix.
|
||||
|
||||
Both describe the tailnet the node is currently in, but they live in one per-DEVICE file. Change
|
||||
profile and they become another tailnet's answers — and startTunnel trusts them, applying "real
|
||||
settings up front, no swap". After a switch the tun would come up holding an address that belongs
|
||||
to the network you just left. Clearing forces the slower first-connect path, which refines from the
|
||||
netmap and is correct.
|
||||
*/
|
||||
private func forgetCachedNetmap() {
|
||||
let fm = FileManager.default
|
||||
try? fm.removeItem(at: savedIPsURL)
|
||||
try? fm.removeItem(at: savedSuffixURL)
|
||||
d("cleared cached node IP + MagicDNS suffix (profile changed)")
|
||||
}
|
||||
|
||||
private var savedIPsURL: URL {
|
||||
URL(fileURLWithPath: stateDirectory()).appendingPathComponent("node-ips.json")
|
||||
}
|
||||
|
||||
/*
|
||||
How the LAST tunnel run ended — the only crash reporting a packet tunnel can honestly do.
|
||||
|
||||
The interesting failures in this app live in the extension, and they are the ones no reporter
|
||||
catches. iOS gives a packet tunnel a hard memory ceiling (~50 MB) and jetsams it on breach: the
|
||||
process is killed outright, so no signal handler, no exception handler and no in-process crash
|
||||
library ever runs. A reporter embedded here would also be competing with the Tailscale core for the
|
||||
very budget that gets it killed.
|
||||
|
||||
So this infers rather than catches. `startTunnel` marks the run as `running`; `stopTunnel` marks it
|
||||
`stopped` with the OS's own reason. If a run STARTS and finds the previous one still marked
|
||||
`running`, that run never reached `stopTunnel` — killed, crashed, or the device rebooted. The
|
||||
distinction between a jetsam kill and a crash is not available to us, and pretending otherwise would
|
||||
be worse than saying "ended abnormally".
|
||||
|
||||
It carries no identifiers by construction — a timestamp and a numeric reason code, nothing derived
|
||||
from the tailnet, the login or any address. That is deliberate: this is the one diagnostic intended
|
||||
to leave the device, and the cheapest way to keep a crash report free of secrets is to give it
|
||||
nothing to leak.
|
||||
*/
|
||||
private var lastExitURL: URL {
|
||||
URL(fileURLWithPath: stateDirectory()).appendingPathComponent("last-exit.json")
|
||||
}
|
||||
|
||||
private func iso(_ d: Date = Date()) -> String {
|
||||
let f = ISO8601DateFormatter()
|
||||
return f.string(from: d)
|
||||
}
|
||||
|
||||
/// Called at the top of startTunnel. Returns what happened to the previous run, and claims this one.
|
||||
@discardableResult
|
||||
private func markRunStarted() -> [String: Any]? {
|
||||
let fm = FileManager.default
|
||||
var previous: [String: Any]? = nil
|
||||
if let data = try? Data(contentsOf: lastExitURL),
|
||||
let prev = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
||||
if (prev["state"] as? String) == "running" {
|
||||
// Never reached stopTunnel. Jetsam, crash or reboot — indistinguishable from in here.
|
||||
previous = [
|
||||
"kind": "abnormal",
|
||||
"startedAt": prev["startedAt"] as? String ?? "",
|
||||
"detectedAt": iso(),
|
||||
]
|
||||
} else {
|
||||
previous = [
|
||||
"kind": "clean",
|
||||
"reason": prev["reason"] as? Int ?? -1,
|
||||
"at": prev["at"] as? String ?? "",
|
||||
]
|
||||
}
|
||||
}
|
||||
let now: [String: Any] = [
|
||||
"state": "running",
|
||||
"startedAt": iso(),
|
||||
// Carried forward so the app can still collect it after a reconnect it did not witness.
|
||||
"previous": previous as Any,
|
||||
]
|
||||
if let data = try? JSONSerialization.data(withJSONObject: now) {
|
||||
try? data.write(to: lastExitURL, options: .atomic)
|
||||
}
|
||||
_ = fm
|
||||
if let previous, (previous["kind"] as? String) == "abnormal" {
|
||||
d("PREVIOUS RUN ENDED ABNORMALLY (no stopTunnel) — started \(previous["startedAt"] ?? "?")")
|
||||
}
|
||||
return previous
|
||||
}
|
||||
|
||||
/// Called from stopTunnel. Records an orderly shutdown so the next start does not report a crash.
|
||||
private func markRunStopped(reason: Int) {
|
||||
var payload: [String: Any] = ["state": "stopped", "reason": reason, "at": iso()]
|
||||
// Preserve any not-yet-collected report, so an orderly stop cannot erase the crash before it.
|
||||
if let data = try? Data(contentsOf: lastExitURL),
|
||||
let prev = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let carried = prev["previous"] {
|
||||
payload["previous"] = carried
|
||||
}
|
||||
if let data = try? JSONSerialization.data(withJSONObject: payload) {
|
||||
try? data.write(to: lastExitURL, options: .atomic)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pending abnormal-exit report, if any. Cleared once handed over, so it is reported once.
|
||||
private func takeLastExitReport() -> String {
|
||||
guard let data = try? Data(contentsOf: lastExitURL),
|
||||
var obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return "" }
|
||||
guard let previous = obj["previous"] as? [String: Any] else { return "" }
|
||||
obj["previous"] = nil
|
||||
if let out = try? JSONSerialization.data(withJSONObject: obj) {
|
||||
try? out.write(to: lastExitURL, options: .atomic)
|
||||
}
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: previous),
|
||||
let s = String(data: data, encoding: .utf8) else { return "" }
|
||||
return s
|
||||
}
|
||||
|
||||
private var savedSuffixURL: URL {
|
||||
URL(fileURLWithPath: stateDirectory()).appendingPathComponent("magicdns-suffix.txt")
|
||||
}
|
||||
|
||||
/// Remembered alongside the node IP: the fast path applies settings before any netmap arrives, so
|
||||
/// without this a reconnect would silently drop MagicDNS until the next refresh.
|
||||
private func savedSuffix() -> String? {
|
||||
try? String(contentsOf: savedSuffixURL, encoding: .utf8)
|
||||
}
|
||||
|
||||
private func saveSuffix(_ s: String) {
|
||||
try? s.write(to: savedSuffixURL, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
private func savedIPs() -> [String] {
|
||||
guard let data = try? Data(contentsOf: savedIPsURL),
|
||||
let ips = try? JSONSerialization.jsonObject(with: data) as? [String] else { return [] }
|
||||
return ips
|
||||
}
|
||||
|
||||
private func saveIPs(_ ips: [String]) {
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: ips) else { return }
|
||||
try? data.write(to: savedIPsURL, options: .atomic)
|
||||
}
|
||||
|
||||
/// A stable per-extension directory for the core's persisted node identity/keys.
|
||||
private func stateDirectory() -> String {
|
||||
let fm = FileManager.default
|
||||
let base = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
let dir = base.appendingPathComponent("offtail", isDirectory: true)
|
||||
try? fm.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
return dir.path
|
||||
}
|
||||
|
||||
/// Poll the core until it has a netmap (self Tailscale IPs), then re-apply the tunnel settings with the
|
||||
/// real per-node address + tailnet routes + MagicDNS. The initial settings in startTunnel are just
|
||||
/// placeholders to bring the utun up; this makes routing actually correct.
|
||||
private func refineSettingsFromNetmap() {
|
||||
d("refine: start polling")
|
||||
Task {
|
||||
// Poll up to ~60s at 0.5s — the netmap can be slow (esp. right after control comes back up). The
|
||||
// placeholder tun address (100.64.0.1) MUST be replaced with the real node IP or outbound packets
|
||||
// carry the wrong source and replies never come back.
|
||||
var lastBackend = ""
|
||||
for i in 0..<120 {
|
||||
if let data = TailcoreStatus().data(using: .utf8),
|
||||
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
||||
let backend = (obj["BackendState"] as? String) ?? "?"
|
||||
if backend != lastBackend { self.d("refine: poll \(i) backend=\(backend)"); lastBackend = backend }
|
||||
if let selfNode = obj["Self"] as? [String: Any],
|
||||
let ips = selfNode["TailscaleIPs"] as? [String], !ips.isEmpty {
|
||||
self.d("refine: got self IPs after \(i) polls (backend=\(backend)): \(ips)")
|
||||
self.applySettings(selfIPs: ips, magicDNSSuffix: obj["MagicDNSSuffix"] as? String)
|
||||
return
|
||||
}
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||
}
|
||||
self.d("refine: GAVE UP — no self IPs after 120 polls; tun stuck on placeholder")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The tunnel settings for a set of node IPs. Pure — builds, does not apply.
|
||||
|
||||
Extracted so `startTunnel` and the refine path cannot drift: the whole bug class here is one code
|
||||
path applying different settings than another.
|
||||
*/
|
||||
/**
|
||||
Whether an exit node is in use, so the tun knows whether to claim everything.
|
||||
|
||||
Read from the core rather than remembered, because the preference can change from the app at any
|
||||
time and the routes have to follow it.
|
||||
*/
|
||||
/**
|
||||
RFC1918 and link-local, kept out of a default-route tunnel.
|
||||
|
||||
Fixed ranges rather than the phone's actual subnet: NEPacketTunnelNetworkSettings is built before
|
||||
the tunnel is up and enumerating interfaces from inside the extension is unreliable. Excluding all
|
||||
private space is broader than strictly needed and errs the right way — a LAN address should never
|
||||
be carried to an exit node on the other side of the world.
|
||||
*/
|
||||
/**
|
||||
Subnet routes the core has accepted, as NEIPv4Routes.
|
||||
|
||||
Accepting a route in the core is only half of it: the OS decides what enters the tunnel, so unless
|
||||
the tun claims these prefixes the traffic never arrives and "use subnet routes" does nothing —
|
||||
the same gap that made choosing an exit node inert. Empty unless the preference is on.
|
||||
|
||||
IPv4 only for now: advertised v6 subnets are rare and untested here, and claiming a prefix wrongly
|
||||
is worse than not claiming it.
|
||||
*/
|
||||
private func acceptedSubnetRoutes() -> [NEIPv4Route] {
|
||||
guard let data = TailcoreSubnetRoutes().data(using: .utf8),
|
||||
let cidrs = try? JSONSerialization.jsonObject(with: data) as? [String] else { return [] }
|
||||
return cidrs.compactMap { cidr in
|
||||
let parts = cidr.split(separator: "/")
|
||||
guard parts.count == 2, let bits = Int(parts[1]), bits > 0, bits <= 32,
|
||||
parts[0].contains(".") else { return nil }
|
||||
// Prefix length to dotted mask, which is the only form NEIPv4Route takes.
|
||||
let mask = (0..<4).map { i -> String in
|
||||
let b = max(0, min(8, bits - i * 8))
|
||||
return String(256 - (1 << (8 - b)) % 256)
|
||||
}.joined(separator: ".")
|
||||
return NEIPv4Route(destinationAddress: String(parts[0]), subnetMask: mask)
|
||||
}
|
||||
}
|
||||
|
||||
private func privateIPv4Ranges() -> [NEIPv4Route] {
|
||||
[
|
||||
NEIPv4Route(destinationAddress: "10.0.0.0", subnetMask: "255.0.0.0"),
|
||||
NEIPv4Route(destinationAddress: "172.16.0.0", subnetMask: "255.240.0.0"),
|
||||
NEIPv4Route(destinationAddress: "192.168.0.0", subnetMask: "255.255.0.0"),
|
||||
NEIPv4Route(destinationAddress: "169.254.0.0", subnetMask: "255.255.0.0"),
|
||||
]
|
||||
}
|
||||
|
||||
private func exitNodeActive() -> Bool {
|
||||
guard let data = TailcorePrefs().data(using: .utf8),
|
||||
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let id = obj["exitNodeID"] as? String else { return false }
|
||||
return !id.isEmpty
|
||||
}
|
||||
|
||||
private func tunnelSettings(selfIPs: [String], magicDNSSuffix: String?) -> NEPacketTunnelNetworkSettings {
|
||||
// tunnelRemoteAddress MUST be a valid IP literal, not a URL — it is informational for a mesh VPN
|
||||
// (there is no single server). A control URL here fails with "Invalid tunnelRemoteAddress" and
|
||||
// the tunnel dies before the core starts.
|
||||
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1")
|
||||
settings.mtu = 1280
|
||||
|
||||
/*
|
||||
With an exit node, the tun must claim EVERYTHING.
|
||||
|
||||
Routing only the tailnet ranges is correct for ordinary use and useless for an exit node: iOS
|
||||
hands us tailnet packets and sends the rest straight out over Wi-Fi, so the exit node never sees
|
||||
the traffic it exists to carry. Selecting one changed the core's preference and nothing else.
|
||||
*/
|
||||
let allTraffic = exitNodeActive()
|
||||
// Advertised subnets the user has accepted. Empty unless the toggle is on; skipped entirely with
|
||||
// an exit node, whose default route already covers them.
|
||||
let subnets = allTraffic ? [] : acceptedSubnetRoutes()
|
||||
d("tun routes: \(allTraffic ? "DEFAULT (exit node active)" : "tailnet ranges + \(subnets.count) subnet route(s)")")
|
||||
|
||||
let v4 = selfIPs.filter { $0.contains(".") }
|
||||
let v6 = selfIPs.filter { $0.contains(":") }
|
||||
if !v4.isEmpty {
|
||||
let ipv4 = NEIPv4Settings(addresses: v4, subnetMasks: v4.map { _ in "255.255.255.255" })
|
||||
ipv4.includedRoutes = allTraffic
|
||||
? [NEIPv4Route.default()]
|
||||
: [NEIPv4Route(destinationAddress: "100.64.0.0", subnetMask: "255.192.0.0")] // 100.64.0.0/10
|
||||
+ subnets
|
||||
// The default route swallows the LAN as well, so the printer, the NAS and the router's own UI
|
||||
// would go dark. Prefs already set ExitNodeAllowLANAccess; this is the tun honouring it, which
|
||||
// is the half that decides where packets actually go.
|
||||
if allTraffic {
|
||||
ipv4.excludedRoutes = privateIPv4Ranges()
|
||||
}
|
||||
settings.ipv4Settings = ipv4
|
||||
}
|
||||
if !v6.isEmpty {
|
||||
let ipv6 = NEIPv6Settings(addresses: v6, networkPrefixLengths: v6.map { _ in NSNumber(value: 128) })
|
||||
ipv6.includedRoutes = allTraffic
|
||||
? [NEIPv6Route.default()]
|
||||
: [NEIPv6Route(destinationAddress: "fd7a:115c:a1e0::", networkPrefixLength: 48)] // Tailscale ULA
|
||||
settings.ipv6Settings = ipv6
|
||||
}
|
||||
/*
|
||||
DNS — scoped to the tailnet normally, everything once an exit node is carrying the traffic.
|
||||
|
||||
100.100.100.100 is the core's own resolver, which now exists: a dns.Manager is created before
|
||||
netstack.Create, where previously there was none and this address answered nothing.
|
||||
|
||||
WITHOUT an exit node, matchDomains keeps the capture to tailnet names, which is why iOS never
|
||||
lost the internet the way Android did — every other name keeps using the system resolvers
|
||||
directly. Android has no matchDomains equivalent and has to route ALL DNS at the core.
|
||||
|
||||
WITH an exit node that scoping becomes a leak, and a quiet one. Ordinary names go to whatever
|
||||
resolver the Wi-Fi handed out, which is usually the router — and the router is on the LAN, which
|
||||
`privateIPv4Ranges()` deliberately excludes from the tunnel so the printer and the NAS keep
|
||||
working. So every domain the user visits is still sent, in the clear, to the network they chose
|
||||
an exit node to get away from. The packets go through the exit node; the names never did.
|
||||
|
||||
Claiming ALL names fixes it: resolution moves to the core, which is the only component that knows
|
||||
an exit node exists, and its forwarded queries travel over WireGuard rather than out the Wi-Fi.
|
||||
The catch-all is an empty matchDomains entry — `[""]` — which is Apple's documented way to say
|
||||
"this tunnel resolves everything", not a placeholder.
|
||||
|
||||
The trade is real and worth stating: with an exit node, a core resolver that cannot forward now
|
||||
takes ALL name resolution down instead of just tailnet names — the exact failure Android hit.
|
||||
That is the right trade only because it is scoped to the case where the user has explicitly asked
|
||||
for every packet to leave through another machine. Off the exit node, the safe scoping returns.
|
||||
*/
|
||||
let suffix = magicDNSSuffix ?? savedSuffix()
|
||||
if allTraffic {
|
||||
let dns = NEDNSSettings(servers: ["100.100.100.100"])
|
||||
dns.matchDomains = [""]
|
||||
settings.dnsSettings = dns
|
||||
if let suffix, !suffix.isEmpty { saveSuffix(suffix) }
|
||||
d("DNS: ALL names via core (exit node active)")
|
||||
} else if let suffix, !suffix.isEmpty {
|
||||
let dns = NEDNSSettings(servers: ["100.100.100.100"])
|
||||
dns.matchDomains = [suffix]
|
||||
settings.dnsSettings = dns
|
||||
saveSuffix(suffix)
|
||||
d("MagicDNS on for .\(suffix)")
|
||||
}
|
||||
return settings
|
||||
}
|
||||
|
||||
/**
|
||||
Keep the saved node IP AND the MagicDNS suffix current, without touching a live tunnel's settings.
|
||||
|
||||
The suffix matters as much as the IP: the fast path applies settings before any netmap exists, so
|
||||
it can only enable MagicDNS from what a previous connect wrote down. Recording only the IP — which
|
||||
this did — meant `savedSuffix()` stayed empty forever on a device that always took the fast path,
|
||||
and short names never resolved no matter what the core was capable of.
|
||||
|
||||
Written for the NEXT connect rather than re-applied now: re-applying settings on a live tunnel is
|
||||
the teardown trap this whole file exists to avoid.
|
||||
*/
|
||||
private func refreshSavedIPs() {
|
||||
Task {
|
||||
for _ in 0..<60 {
|
||||
if let data = TailcoreStatus().data(using: .utf8),
|
||||
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
||||
if let suffix = obj["MagicDNSSuffix"] as? String, !suffix.isEmpty, suffix != self.savedSuffix() {
|
||||
self.d("saved MagicDNS suffix -> \(suffix); next connect will use it")
|
||||
self.saveSuffix(suffix)
|
||||
}
|
||||
if let selfNode = obj["Self"] as? [String: Any],
|
||||
let ips = selfNode["TailscaleIPs"] as? [String], !ips.isEmpty {
|
||||
if ips != self.savedIPs() {
|
||||
self.d("saved node IP changed -> \(ips); next connect will use it")
|
||||
self.saveIPs(ips)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: 500_000_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func applySettings(selfIPs: [String], magicDNSSuffix: String?, then: ((Error?) -> Void)? = nil) {
|
||||
d("applySettings IPs=\(selfIPs) suffix=\(magicDNSSuffix ?? "-")")
|
||||
// Remembered so the NEXT connect can apply the right settings up front and skip the two-phase
|
||||
// swap entirely — the identity is stable across connects, so this IP is too.
|
||||
saveIPs(selfIPs)
|
||||
let settings = tunnelSettings(selfIPs: selfIPs, magicDNSSuffix: magicDNSSuffix)
|
||||
let v4 = selfIPs.filter { $0.contains(".") }
|
||||
let v6 = selfIPs.filter { $0.contains(":") }
|
||||
d("refine: calling setTunnelNetworkSettings v4=\(v4) v6=\(v6)")
|
||||
setTunnelNetworkSettings(settings) { [weak self] err in
|
||||
if let err = err {
|
||||
os_log("refine settings failed: %{public}@", log: log, type: .error, err.localizedDescription)
|
||||
self?.d("refine: setTunnelNetworkSettings FAILED: \(err.localizedDescription)")
|
||||
} else {
|
||||
os_log("applied netmap settings v4=%{public}@ v6=%{public}@", log: log, type: .info, v4.description, v6.description)
|
||||
self?.d("refine: APPLIED real settings v4=\(v4) v6=\(v6) ✓")
|
||||
}
|
||||
// On the first-connect path this is startTunnel's completionHandler: the tunnel goes "connected"
|
||||
// only now, already carrying the real settings.
|
||||
then?(err)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - utun fd
|
||||
|
||||
/// The utun fd this Network Extension owns. The RELIABLE way is NEPacketTunnelFlow's underlying socket
|
||||
/// fd via KVC — that is unambiguously OUR tun (the one the OS routes into). WireGuard-iOS uses this.
|
||||
///
|
||||
/// The old approach scanned open fds for the first "utun"-named control socket, but a device can have
|
||||
/// MORE than one utun — iCloud Private Relay, a personal Tailscale/VPN — and the scan could return the
|
||||
/// wrong one. The core would then read/write a tun the OS never routes into: control plane works (the
|
||||
/// core uses its own sockets, so it registers + gets a netmap + IP), but no app traffic ever flows.
|
||||
private func utunFileDescriptor() -> Int32? {
|
||||
// NOTE: do NOT use packetFlow.value(forKeyPath: "socket.fileDescriptor") — on iOS 18 that key path
|
||||
// throws an Objective-C NSUnknownKeyException, which Swift can't catch, crashing the whole NE before
|
||||
// TailcoreStart. Scan the open fds for the utun control socket instead (WireGuard-iOS's technique).
|
||||
//
|
||||
// EVERY match is logged, not just the first one taken. A phone routinely has more than one utun —
|
||||
// iCloud Private Relay, a personal VPN, a leftover — and picking the wrong one gives a control
|
||||
// plane that works perfectly (the core registers, gets a netmap and an IP, because it uses its own
|
||||
// sockets) while no app traffic ever flows. That failure is indistinguishable from a dozen others
|
||||
// unless the candidates are on the record, so: log them all, take the first, and say which.
|
||||
var buf = [Int8](repeating: 0, count: 256)
|
||||
var found: [(Int32, String)] = []
|
||||
for fd: Int32 in 0...1024 {
|
||||
var len = socklen_t(buf.count)
|
||||
// SYSPROTO_CONTROL (2), UTUN_OPT_IFNAME (2): getsockopt succeeds only on a utun control socket.
|
||||
let ret = buf.withUnsafeMutableBytes { getsockopt(fd, 2, 2, $0.baseAddress, &len) }
|
||||
if ret == 0 && strncmp(buf, "utun", 4) == 0 {
|
||||
found.append((fd, String(cString: buf)))
|
||||
}
|
||||
}
|
||||
guard let chosen = found.first else {
|
||||
os_log("utun fd: no utun socket found", log: log, type: .error)
|
||||
d("utun fd: NONE FOUND")
|
||||
return nil
|
||||
}
|
||||
let all = found.map { "\($0.1)=fd\($0.0)" }.joined(separator: " ")
|
||||
os_log("utun candidates: %{public}@ — taking %{public}d", log: log, type: .info, all, chosen.0)
|
||||
d("utun candidates: \(all) — taking \(chosen.1)=fd\(chosen.0)\(found.count > 1 ? " ⚠️ MORE THAN ONE" : "")")
|
||||
return chosen.0
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user