Run a virtual iPhone on an Apple Silicon Mac.
Swift
chore: icli + vphoned
Lakr11f9dc4cf636
diff --git a/AGENTS.md b/AGENTS.mdindex d8856fb7..135c1504 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -12,7 +12,7 @@ Virtual iPhone boot tool using Apple's Virtualization.framework with PCC researc- **Restore:** `vphone-cli restore`, in process. Vendored libirecovery + idevicerestore (`sources/MobileRecoveryCore`, `sources/MobileRestoreCore`) over the `AppleMobileDeviceLibrary` xcframeworks. No interpreter, no environment to provision, no setup step. See `research/p2_restore_off_python.md`.- **Platform:** macOS 15+ (Sequoia). `vphone-vm` needs amfid to accept its private entitlements: either SIP off with `amfi_get_out_of_my_way=1`, or SIP on (`--without debug`) plus an allowlist bypass the user runs. Both are in README's "SIP/AMFI Relaxation"; neither is installed by this project.- **Language:** Swift 6.0 (SwiftPM), private APIs via [Dynamic](https://github.com/mhdhejazi/Dynamic). This package's own manifest is `swift-tools-version:6.0`, but the **toolchain floor is Swift 6.2**: `libcapstone-spm` declares 6.2 so that it can reach `CSetting.disableWarning` instead of `.unsafeFlags`, which is what lets it be depended on by version at all.-- **Dependencies:** seven SwiftPM packages, every one resolved by URL and **every one by version** — there is no `vendor/` directory, no `branch:` requirement, and `Package.resolved` pins fourteen once transitives are counted. The only git submodule is `scripts/repos/insert_dylib`, a build-time test reference. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.+- **Dependencies:** Host and guest SwiftPM packages resolve dependencies by URL and version; `Package.resolved` pins the full graphs. The only git submodule is `scripts/repos/insert_dylib`, a build-time test reference. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.- **Tiers.** Three environments run code here and the rules differ. **build** (the machine that builds the `.app`) may use Xcode, `xcrun`, clang, swift, git and Homebrew. **dist** (the shipped `.app`, on a clean macOS) may use `/usr/lib`, `/System` and the bundle — nothing else, no `PATH` lookup. **guest** (inside the VM) is out of host self-containment scope. Every script declares its tier on **line 2** (`# vphone-tier: dist`); `scripts/dist_manifest.sh` reads those and is what `build.sh` and `make bundle` stage from, so a script that declares nothing ships nowhere. `make check-aux` gates all of it. The dist tier's registered-exception list is **empty** and a release requires it to stay that way.## Workflow Rules@@ -88,6 +88,9 @@ sources/│ ├── VPhoneArchivePaths.swift # realpath(3) — NOT the Foundation equivalents│ └── VPhoneTreeFingerprint.swift # Compare two extracted trees, field by field│+├── VPhoneKit/ # Public unentitled HTTP/WebSocket API client for vphone-ui+│ └── VPhoneAPIClient.swift # Typed JSON values, RPC, events, streaming file transfer+│├── VPhoneSign/ # Mach-O code signing — replaces ldid, byte for byte│ ├── VPhoneSigner.swift # Ad-hoc and PKCS#12 signing│ ├── VPhoneCodeSignature.swift # SuperBlob / CodeDirectory construction@@ -134,7 +137,8 @@ sources/│ └── VPhoneError.swift # Error types│├── Guest/ # Guest daemon client (vsock)- │ ├── VPhoneControl.swift # Host-side vsock client for vphoned (length-prefixed JSON)+ │ ├── VPhoneControl.swift # Host-side HTTP client over direct VSOCK 1339+ │ ├── VPhoneAPIProxy.swift # Opt-in TCP to guest VSOCK 1339 transparent proxy│ ├── VPhoneControlApps.swift # Installed apps — list and launch│ ├── VPhoneControlKeychain.swift # Keychain dump│ └── VPhoneControlSystem.swift # Device, battery, location, devmode@@ -180,7 +184,7 @@ scripts/ # Build scripts and payloads only; no runtime├── guest_binaries.mk [b] # Cross-compiles vphoned (needs the iPhoneOS SDK)├── check_aux.sh [b] # The self-containment admission gates — `make check-aux`├── setup_tools.sh [b] # Builds insert_dylib, the Mach-O byte-parity test reference-├── vphoned/ # Guest daemon source; only its plist and entitlements ship+├── vphoned/ # Guest SwiftNIO/IcliKit package plus native installer/keychain/camera code└── repos/ # Toolchain source (git submodule: insert_dylib)siblings/ # Guest component sources/provenance; separate package@@ -200,7 +204,7 @@ research/ # Detailed firmware/patch documentation- **Private API access:** Via [Dynamic](https://github.com/mhdhejazi/Dynamic) library (runtime method dispatch from pure Swift). No ObjC bridge.- **App lifecycle:** `vphone-vm/main.swift` → `VPhoneGuestApp.run()` → `NSApplication` + `VPhoneAppDelegate`. Entry points hold no logic.- **Configuration:** `ArgumentParser` → `VPhoneBootCLI` (in `VPhoneCore`, parsed by both binaries) → `VPhoneVirtualMachine.Options` → `VZVirtualMachineConfiguration`.-- **Guest daemon (vphoned):** ObjC daemon inside iOS VM, vsock port 1337, length-prefixed JSON protocol. Host side is `VPhoneControl` with auto-reconnect.+- **Guest daemon (vphoned):** SwiftNIO HTTP/WebSocket API on VSOCK 1339, using IcliKit for common device operations. The complete pinned icli CLI is installed inside the guest and available through `icli.execute` with an argv array. `VPhoneControl` reaches HTTP directly over VSOCK; the former length-prefixed service on 1337 is removed. Camera data remains on 1338. The host exposes 1339 only when boot is given `--api-listen`.- **Menu system:** `VPhoneMenuController` + per-menu extensions (Keys, Type, Location, Connect, Install, Record).- **File browser:** SwiftUI (`VPhoneFileBrowserView` + `VPhoneFileBrowserModel`) in `NSHostingController`. Search, sort, upload/download, drag-drop via `VPhoneControl`.- **IPA installation:** `VPhoneIPAInstaller` extracts + re-signs via `VPhoneSigner` + installs over vsock.diff --git a/Package.resolved b/Package.resolvedindex 11b8c0bf..121fa463 100644--- a/Package.resolved+++ b/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "cf27600e414003ad42d307bca61d24d4e4dcfa4d96f55d0778961239b9c96a68",+ "originHash" : "c91e50c349f2dafdea83e42d7561095edcba4ccc05afe62daac1f951bf2d4436","pins" : [{"identity" : "applemobiledevicelibrary",@@ -91,6 +91,15 @@"version" : "1.7.3"}},+ {+ "identity" : "swift-atomics",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-atomics.git",+ "state" : {+ "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",+ "version" : "1.3.1"+ }+ },{"identity" : "swift-binary-parse-support","kind" : "remoteSourceControl",@@ -100,6 +109,15 @@"version" : "0.2.1"}},+ {+ "identity" : "swift-collections",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-collections.git",+ "state" : {+ "revision" : "7b847a3b7008b2dc2f47ca3110d8c782fb2e5c7e",+ "version" : "1.3.0"+ }+ },{"identity" : "swift-crypto","kind" : "remoteSourceControl",@@ -126,6 +144,24 @@"revision" : "eccf765a9d90b82db55cacd260490d2fcae000fb","version" : "0.3.0"}+ },+ {+ "identity" : "swift-nio",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-nio.git",+ "state" : {+ "revision" : "34d486b01cd891297ac615e40d5999536a1e138d",+ "version" : "2.83.0"+ }+ },+ {+ "identity" : "swift-system",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-system.git",+ "state" : {+ "revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",+ "version" : "1.8.1"+ }}],"version" : 3diff --git a/Package.swift b/Package.swiftindex e9e2e4db..997cb48a 100644--- a/Package.swift+++ b/Package.swift@@ -7,7 +7,10 @@ let package = Package(platforms: [.macOS(.v15),],- products: [],+ products: [+ .library(name: "VPhoneKit", targets: ["VPhoneKit"]),+ .library(name: "VPhoneVMKit", targets: ["VPhoneVMKit"]),+ ],// Resolved by SwiftPM, not carried as submodules. Every one of these was a// `.package(path: "vendor/…")` over a checkout this repository pinned by// commit, which meant a `git submodule update` before any build and a tree@@ -35,8 +38,13 @@ let package = Package(// arrives through SwiftPM instead of a pip install into a venv, and// the C targets below include its headers directly..package(url: "https://github.com/Lakr233/AppleMobileDeviceLibrary.git", from: "1.0.1790070576"),+ // 2.84+ links libswiftCompatibilitySpan when built with Swift 6.4.+ // 2.83 keeps the guest binary self-contained on older iOS bases.+ .package(url: "https://github.com/apple/swift-nio.git", exact: "2.83.0"),+ .package(url: "https://github.com/apple/swift-collections.git", exact: "1.3.0"),],targets: [+ .target(name: "VPhoneKit", path: "sources/VPhoneKit"),.target(name: "FirmwarePatcher",dependencies: [@@ -209,7 +217,10 @@ let package = Package(dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser"),.product(name: "Dynamic", package: "Dynamic"),+ .product(name: "NIOCore", package: "swift-nio"),+ .product(name: "NIOPosix", package: "swift-nio"),"VPhoneCore",+ "VPhoneKit",],path: "sources/VPhoneVMKit",linkerSettings: [@@ -228,7 +239,12 @@ let package = Package("VPhoneCore","VPhoneVMKit",],- path: "sources/vphone-vm"+ path: "sources/vphone-vm",+ // Swift 6.4 may autolink compatibility dylibs for generic code in+ // dependencies even when this executable has no symbol references.+ // Strip those unused load commands so the shipped app remains+ // independent of the build machine's Swift toolchain.+ linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])]),// The user-facing entry point. Note it depends on neither VPhoneVMKit// nor any of the five frameworks above: it never builds a machine, itdiff --git a/README.md b/README.mdindex de5573f7..ce2fef74 100644--- a/README.md+++ b/README.md@@ -58,6 +58,17 @@ vphone-cli vm create myphone \vphone-cli vm launch myphone```+To expose the guest HTTP and WebSocket API on the host for local tools or an+app using `VPhoneKit`, opt in when launching:++```bash+vphone-cli vm launch myphone --api-listen 127.0.0.1:8765+curl http://127.0.0.1:8765/openapi.json+```++The API is off by default. See [the API contract](research/vphoned_http_api.md)+for routes, WebSocket messages, and the Swift Kit client.+The single supported firmware mode is JB. Creation installs vphoned and therequired system patches, then checks that vphoned connects. It does not installa package manager, SSH server, or user bootstrap.diff --git a/research/vphoned_http_api.md b/research/vphoned_http_api.mdnew file mode 100644index 00000000..b8d441aa--- /dev/null+++ b/research/vphoned_http_api.md@@ -0,0 +1,88 @@+# vphoned HTTP/WebSocket API++## Transport and ownership++`vphoned` listens on guest VSOCK port 1339 with SwiftNIO HTTP/1.1. A WebSocket+upgrade at `/v1/events` uses the same port. `vphone-vm` can expose that byte+stream on a host TCP address. It opens one VSOCK connection per TCP connection+and forwards bytes in both directions; it does not translate HTTP or WebSocket+messages. The host listener is absent unless boot receives `--api-listen+host:port`. Port `0` asks the OS for an available host port and the actual+address is printed after the VM starts. The API is also usable from guest and+host code that connects to VSOCK 1339 directly.++The SwiftPM `VPhoneKit` product is an unentitled HTTP/WebSocket client for+`vphone-ui` and other macOS apps. The separate public `VPhoneVMKit` product+exposes `VPhoneAPIProxy` to an app that owns a `VZVirtioSocketDevice`. The+command-line executable remains unentitled and still launches `vphone-vm`.++The guest build also includes the pinned `icli` executable, signed with+icli's entitlements and installed at `/usr/bin/icli` alongside vphoned.+`POST /v1/icli/execute` and the WebSocket method `icli.execute` accept+`{"argv":["device","info"]}`. The guest passes that array to icli directly,+captures its JSON output, and returns `exit_code`, `output`, and `stderr`.+This exposes icli's complete command tree, including newly added subcommands,+without duplicating each command in vphoned. `stdin` or `stdin_base64` supports+commands that read standard input. The process has a 120 second deadline.++## HTTP and WebSocket contract++`GET /openapi.json` is the machine-readable HTTP description. JSON resource+routes cover device state, apps, input, location, Developer Mode, low power+mode, clipboard, file listing, and keychain. `GET/PUT+/v1/files/content?path=<absolute-guest-path>` transfer bytes with+`application/octet-stream`; upload writes to a temporary file in the same+directory then renames it after all chunks have been written. JSON bodies+have a 1 MiB limit. Binary transfers stream without loading the entire file+into memory.++`POST /v1/rpc` accepts `{ "id": "...", "method": "device.snapshot",+"params": {} }`. JSON operations return+`{ "type": "response", "id": "...", "result": { ... } }` or+`{ "type": "response", "id": "...", "error": { "code": "...",+"message": "..." } }`. The WebSocket accepts the same request JSON and sends+the same response shape; requests may complete out of order, so clients+correlate them by `id`. The socket also sends+`{ "type": "event", "event": "...", "data": { ... } }`. The initial event is+`connected`; changes to screen, frontmost app, or low power mode emit+`device.state`, and completed operations emit `operation.completed`. Ping frames+receive pong frames. JSON WebSocket frames are limited to 1 MiB after+fragment reassembly.++SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.6.1+owns general device operations; they run on a serial worker queue because its+in-process bridge is synchronous. The vphone-specific IPA signing and all-app+keychain view remain in native Objective-C modules. The VM GUI uses HTTP over+VSOCK 1339 directly; host TCP forwarding is opt-in. The former length-prefixed+VSOCK 1337 protocol and duplicate ObjC command handlers have been removed.+The 1338 virtual camera stream remains. At startup, the host compares the+signed daemon hash from `/v1/health`; an update is uploaded through HTTP,+verified by SHA-256, made executable, and activated through launchd restart.+This intentionally breaks compatibility with guests that still have the old+daemon: install a guest image carrying this vphoned build before using the new+host control client.++## Usage++```sh+vphone-cli boot --config /path/to/config.plist --api-listen 127.0.0.1:8765+curl http://127.0.0.1:8765/v1/health+curl http://127.0.0.1:8765/openapi.json+```++```swift+import VPhoneKit++let client = VPhoneAPIClient(baseURL: URL(string: "http://127.0.0.1:8765")!)+let device = try await client.call("device.snapshot")+let icli = try await client.runIcli(["device", "info"])+let socket = try client.openWebSocket()+try await socket.send("input.touch", params: [+ "phase": .string("down"), "x": .number(0.5), "y": .number(0.5),+])+let message = try await socket.next()+```++The listener accepts the address specified by the user. For local-only use,+pass `127.0.0.1` or `[::1]`. The API currently has no authentication layer;+exposing it beyond a trusted host requires the caller's own access control.diff --git a/scripts/build.sh b/scripts/build.shindex a989d3d7..f029d372 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -144,6 +144,11 @@ cp .build/guest/vphoned .build/vphoned.signed--entitlements scripts/vphoned/entitlements.plist --merge \.build/vphoned.signedecho " signed → .build/vphoned.signed"+echo "=== Signing icli ==="+"$BINARY" sign \+ --entitlements .build/vphoned-swiftpm/checkouts/icli/Resources/icli.entitlements --merge \+ .build/guest/icli+echo " signed → .build/guest/icli"# --- Bundle the standalone runtime mini-repo into Contents/Resources ---RES="${BUNDLE}/Contents/Resources"@@ -172,10 +177,11 @@ zsh scripts/dist_manifest.sh | rsync -a --files-from=- scripts/ "${RES}/scripts/# binaries for the removed bootstrap and must not leak into the bundle.mkdir -p "${RES}/guest"cp -f .build/guest/vphoned "${RES}/guest/vphoned"+cp -f .build/guest/icli "${RES}/guest/icli"[[ -f .build/vphoned.signed ]] && cp -f .build/vphoned.signed "${RES}/vphoned.signed" || true# README.md holds the Tested-Environments table used by `fw prepare`.cp -f README.md "${RES}/README.md"-echo " bundled: scripts/ (dist tier), guest/vphoned, vphoned.signed, README.md"+echo " bundled: scripts/ (dist tier), guest/vphoned, guest/icli, vphoned.signed, README.md"# Re-sign: codesign seals Contents/Resources at sign time, so the earlier# bundle-step signature (made before these assets existed) is now stale —diff --git a/scripts/guest_binaries.mk b/scripts/guest_binaries.mkindex 97345b8b..551cd5d7 100644--- a/scripts/guest_binaries.mk+++ b/scripts/guest_binaries.mk@@ -7,17 +7,28 @@ GIT_HASH ?= unknown.PHONY: guest_binaries guest_binaries_clean-guest_binaries: $(GUEST_DIR)/vphoned- @echo " guest daemon → $(GUEST_DIR)/vphoned"+guest_binaries: $(GUEST_DIR)/vphoned $(GUEST_DIR)/icli+ @echo " guest binaries → $(GUEST_DIR)/vphoned, $(GUEST_DIR)/icli"$(GUEST_DIR):@mkdir -p $(GUEST_DIR)-$(GUEST_DIR)/vphoned: $(wildcard scripts/vphoned/*.m) $(wildcard scripts/vphoned/*.h) | $(GUEST_DIR)+$(GUEST_DIR)/vphoned: $(wildcard scripts/vphoned/*.m) $(wildcard scripts/vphoned/*.h) $(wildcard scripts/vphoned/Swift/*.swift) scripts/vphoned/Package.swift scripts/vphoned/Package.resolved | $(GUEST_DIR)@xcrun --sdk iphoneos --show-sdk-path >/dev/null || (echo "Error: iPhoneOS SDK is required on the build machine" >&2; exit 1)@$(MAKE) --no-print-directory -C scripts/vphoned GIT_HASH=$(GIT_HASH)@cp -f scripts/vphoned/vphoned $@+# The complete icli command surface is available to the guest API without+# reimplementing its command parser or accepting shell text.+$(GUEST_DIR)/icli: $(GUEST_DIR)/vphoned+ @swift build --package-path .build/vphoned-swiftpm/checkouts/icli \+ --scratch-path .build/icli-guest-swiftpm --triple arm64-apple-ios15.0 \+ --sdk "$$(xcrun --sdk iphoneos --show-sdk-path)" -c release --product icli \+ --jobs $(or $(SWIFT_JOBS),4)+ @cp "$$(swift build --package-path .build/vphoned-swiftpm/checkouts/icli \+ --scratch-path .build/icli-guest-swiftpm --triple arm64-apple-ios15.0 \+ --sdk "$$(xcrun --sdk iphoneos --show-sdk-path)" -c release --show-bin-path)/icli" $@+guest_binaries_clean:@rm -rf $(GUEST_DIR)@$(MAKE) --no-print-directory -C scripts/vphoned cleandiff --git a/scripts/vphoned/Makefile b/scripts/vphoned/Makefileindex 4d155407..67df8421 100644--- a/scripts/vphoned/Makefile+++ b/scripts/vphoned/Makefile@@ -1,7 +1,10 @@-# vphoned — iOS guest daemon (cross-compiled for arm64 iphoneos)+# vphoned — iOS guest daemon (SwiftNIO + IcliKit + native vphone operations)-SRCS := $(wildcard *.m)+SRCS := $(wildcard *.m) $(wildcard *.h) $(wildcard Swift/*.swift) Package.swift Package.resolvedOUT := vphoned+SDK := $(shell xcrun --sdk iphoneos --show-sdk-path)+SCRATCH := $(abspath ../../.build/vphoned-swiftpm)+SWIFT_BUILD := swift build --scratch-path $(SCRATCH) --triple arm64-apple-ios15.0 --sdk $(SDK) -c release --product vphoned --jobs $(or $(SWIFT_JOBS),4)# Passed from parent MakefileGIT_HASH ?= unknown@@ -10,18 +13,10 @@ GIT_HASH ?= unknownall: $(OUT)-$(OUT): $(SRCS) $(wildcard *.h)+$(OUT): $(SRCS)@echo "=== Building vphoned (arm64, iphoneos) ==="- xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \- -I. \- -Ivendor/libarchive \- -DVPHONED_BUILD_HASH='"$(GIT_HASH)"' \- -o $@ $(SRCS) \- -larchive \- -lsqlite3 \- -framework Foundation \- -framework Security \- -framework CoreServices+ GIT_HASH=$(GIT_HASH) $(SWIFT_BUILD)+ @cp "$$($(SWIFT_BUILD) --show-bin-path)/vphoned" $@@echo " built OK"clean:diff --git a/scripts/vphoned/Package.resolved b/scripts/vphoned/Package.resolvednew file mode 100644index 00000000..be1ea763--- /dev/null+++ b/scripts/vphoned/Package.resolved@@ -0,0 +1,69 @@+{+ "originHash" : "09ad0ce748c80361eb4b3727cde34aa0ac0436eea4e4dfd3c163dd37e803897c",+ "pins" : [+ {+ "identity" : "icli",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/owngoal-dev/icli.git",+ "state" : {+ "revision" : "c3407df5f160919b5eb7d2fefb5a5c21351314fb",+ "version" : "0.6.1"+ }+ },+ {+ "identity" : "libarchive.xcframework",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Lakr233/libarchive.xcframework.git",+ "state" : {+ "revision" : "3bda868f1868790de2dd246a9eff76eeecba3537",+ "version" : "0.1.1"+ }+ },+ {+ "identity" : "swift-argument-parser",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-argument-parser.git",+ "state" : {+ "revision" : "46989693916f56d1186bd59ac15124caef896560",+ "version" : "1.3.1"+ }+ },+ {+ "identity" : "swift-atomics",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-atomics.git",+ "state" : {+ "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",+ "version" : "1.3.1"+ }+ },+ {+ "identity" : "swift-collections",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-collections.git",+ "state" : {+ "revision" : "7b847a3b7008b2dc2f47ca3110d8c782fb2e5c7e",+ "version" : "1.3.0"+ }+ },+ {+ "identity" : "swift-nio",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-nio.git",+ "state" : {+ "revision" : "34d486b01cd891297ac615e40d5999536a1e138d",+ "version" : "2.83.0"+ }+ },+ {+ "identity" : "swift-system",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-system.git",+ "state" : {+ "revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",+ "version" : "1.8.1"+ }+ }+ ],+ "version" : 3+}diff --git a/scripts/vphoned/Package.swift b/scripts/vphoned/Package.swiftnew file mode 100644index 00000000..b8fae5c3--- /dev/null+++ b/scripts/vphoned/Package.swift@@ -0,0 +1,51 @@+// swift-tools-version:6.0+import Foundation+import PackageDescription++let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent()+let nativeSources = ["unarchive.m", "vphoned_install.m", "vphoned_keychain.m", "vphoned_vcam.m", "vphoned_native.m"]+let gitHash = ProcessInfo.processInfo.environment["GIT_HASH"] ?? "unknown"++let package = Package(+ name: "vphoned",+ platforms: [.iOS(.v15)],+ dependencies: [+ .package(url: "https://github.com/owngoal-dev/icli.git", exact: "0.6.1"),+ .package(url: "https://github.com/apple/swift-nio.git", exact: "2.83.0"),+ .package(url: "https://github.com/apple/swift-collections.git", exact: "1.3.0"),+ ],+ targets: [+ .target(+ name: "VphonedNative",+ path: ".",+ sources: nativeSources,+ publicHeadersPath: "include",+ cSettings: [+ .headerSearchPath("."),+ .headerSearchPath("vendor/libarchive"),+ .define("VPHONED_BUILD_HASH", to: "\"\(gitHash)\""),+ .unsafeFlags(["-fobjc-arc"]),+ ],+ linkerSettings: [+ .linkedLibrary("archive"),+ .linkedLibrary("sqlite3"),+ .linkedFramework("Foundation"),+ .linkedFramework("Security"),+ .linkedFramework("CoreServices"),+ ]+ ),+ .executableTarget(+ name: "vphoned",+ dependencies: [+ "VphonedNative",+ .product(name: "IcliKit", package: "icli"),+ .product(name: "NIOCore", package: "swift-nio"),+ .product(name: "NIOHTTP1", package: "swift-nio"),+ .product(name: "NIOPosix", package: "swift-nio"),+ .product(name: "NIOWebSocket", package: "swift-nio"),+ ],+ path: "Swift",+ linkerSettings: [.unsafeFlags(["-Xlinker", "-dead_strip_dylibs"])]+ ),+ ]+)diff --git a/scripts/vphoned/Swift/APIWire.swift b/scripts/vphoned/Swift/APIWire.swiftnew file mode 100644index 00000000..b2a64d12--- /dev/null+++ b/scripts/vphoned/Swift/APIWire.swift@@ -0,0 +1,94 @@+import Foundation+import NIOCore+import NIOWebSocket++struct APIReply: Sendable {+ let status: Int+ let data: Data++ static func json(status: Int = 200, _ value: [String: Any]) -> APIReply {+ let data = (try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]))+ ?? Data(#"{"error":{"code":"serialization_failed","message":"Could not encode response"}}"#.utf8)+ return APIReply(status: status, data: data)+ }+}++struct APIRequest: @unchecked Sendable {+ let method: String+ let params: [String: Any]+ let id: Any?+}++enum APIWire {+ static func decode(_ data: Data) throws -> APIRequest {+ guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let method = object["method"] as? String, !method.isEmpty,+ method.count <= 128,+ object["params"] == nil || object["params"] is [String: Any]+ else {+ throw GuestAPIError.invalidRequest("Expected {method, params?, id?}")+ }+ let id = object["id"]+ if let id, !(id is String) && !(id is NSNumber) {+ throw GuestAPIError.invalidRequest("id must be a string or number")+ }+ return APIRequest(method: method, params: object["params"] as? [String: Any] ?? [:], id: id)+ }++ static func execute(_ request: APIRequest) -> APIReply {+ do {+ let result = try GuestAPI.execute(method: request.method, params: request.params)+ return .json(["type": "response", "id": request.id ?? NSNull(), "result": result])+ } catch {+ let code = error is GuestAPIError ? "invalid_operation" : "operation_failed"+ return .json(status: 400, [+ "type": "response", "id": request.id ?? NSNull(),+ "error": ["code": code, "message": String(describing: error)],+ ])+ }+ }++ static func error(_ message: String, status: Int = 400) -> APIReply {+ .json(status: status, ["error": ["code": "bad_request", "message": message]])+ }+}++/// A client receives guest events on the same WebSocket it uses for commands.+/// Writes are always scheduled on each channel's event loop.+final class APIEventHub: @unchecked Sendable {+ private let lock = NSLock()+ private var channels: [ObjectIdentifier: Channel] = [:]++ func add(_ channel: Channel) {+ lock.lock()+ channels[ObjectIdentifier(channel)] = channel+ lock.unlock()+ }++ func remove(_ channel: Channel) {+ lock.lock()+ channels.removeValue(forKey: ObjectIdentifier(channel))+ lock.unlock()+ }++ func broadcast(name: String, data: [String: Any]) {+ let reply = APIReply.json(["type": "event", "event": name, "data": data])+ lock.lock()+ let recipients = Array(channels.values)+ lock.unlock()+ for channel in recipients {+ channel.eventLoop.execute {+ guard channel.isActive else { return }+ var buffer = channel.allocator.buffer(capacity: reply.data.count)+ buffer.writeBytes(reply.data)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .text, data: buffer), promise: nil)+ }+ }+ }++ var hasSubscribers: Bool {+ lock.lock()+ defer { lock.unlock() }+ return !channels.isEmpty+ }+}diff --git a/scripts/vphoned/Swift/GuestAPI.swift b/scripts/vphoned/Swift/GuestAPI.swiftnew file mode 100644index 00000000..0bf214cb--- /dev/null+++ b/scripts/vphoned/Swift/GuestAPI.swift@@ -0,0 +1,212 @@+import Foundation+import CryptoKit+import IcliKit+import VphonedNative++enum GuestAPIError: Error, CustomStringConvertible {+ case invalidRequest(String)+ case unsupportedMethod(String)+ case operationFailed(String)++ var description: String {+ switch self {+ case .invalidRequest(let message), .operationFailed(let message): message+ case .unsupportedMethod(let method): "Unknown method: \(method)"+ }+ }+}++/// The API boundary is deliberately small: named operations and JSON values.+/// IcliKit owns general device work; only vphone-specific installation and+/// keychain enumeration cross into the older daemon code.+enum GuestAPI {+ // IcliKit's in-process bridge is synchronous and has not been audited for+ // concurrent callers. Keep its operations off NIO loops and in one order.+ static let queue = DispatchQueue(label: "vphoned.api.operations", qos: .userInitiated)+ static let binaryHash: String = {+ guard let url = Bundle.main.executableURL,+ let data = try? Data(contentsOf: url, options: .mappedIfSafe) else { return "unknown" }+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ }()++ static func health() -> [String: Any] {+ let addresses = networkInfo()["addresses"] as? [String] ?? []+ let ip = addresses.first(where: { $0.hasPrefix("en") && !$0.contains("127.0.0.1") })?+ .split(separator: " ").last.map(String.init)+ let version = ProcessInfo.processInfo.operatingSystemVersion+ return ["name": "vphoned", "api_version": 1, "status": "ok", "binary_hash": binaryHash,+ "ios": "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)", "ip": ip ?? "",+ "capabilities": ["touch", "hid", "apps", "url", "files", "clipboard", "location", "keychain", "ipa_install", "camera"]]+ }++ static func execute(method: String, params: [String: Any]) throws -> [String: Any] {+ switch method {+ case "device.snapshot":+ return try collectDeviceSnapshot()+ case "icli.execute":+ return try IcliCommand.execute(params)+ case "device.screen":+ return screenInfo()+ case "apps.list":+ let filter = params["filter"] as? String ?? "all"+ let apps = try searchApps("")["apps"] as? [[String: Any]] ?? []+ let running = try runningApps()["apps"] as? [[String: Any]] ?? []+ let pids = Dictionary(uniqueKeysWithValues: running.compactMap { app -> (String, Int)? in+ guard let id = app["bundle_id"] as? String, let pid = app["pid"] as? Int else { return nil }+ return (id, pid)+ })+ return ["apps": apps.compactMap { app -> [String: Any]? in+ var info = app+ let id = app["bundle_id"] as? String ?? ""+ let pid = pids[id] ?? 0+ let path = app["bundle_path"] as? String ?? ""+ let type = app["type"] as? String+ ?? (path.hasPrefix("/System/") || id.hasPrefix("com.apple.") ? "system" : "user")+ if filter == "running" && pid == 0 { return nil }+ if filter == "user" && type != "user" { return nil }+ if filter == "system" && type != "system" { return nil }+ info["pid"] = pid+ info["type"] = type+ info["state"] = pid > 0 ? "running" : "not_running"+ info["path"] = path+ info["version"] = app["version"] ?? ""+ return info+ }]+ case "apps.search":+ return try searchApps(try string(params, "query"))+ case "apps.launch":+ let id = try string(params, "bundle_id")+ if let url = params["url"] as? String { _ = try openAppURL(url, bundleID: id) }+ else { _ = try launchApp(id) }+ let running = try? runningApps()["apps"] as? [[String: Any]]+ return ["pid": running?.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0]+ case "apps.terminate":+ return try killApp(try string(params, "bundle_id"), force: true)+ case "apps.foreground":+ let front = frontmostApp()+ let id = front["bundle_id"] as? String ?? ""+ let apps = try searchApps(id)["apps"] as? [[String: Any]] ?? []+ let running = try runningApps()["apps"] as? [[String: Any]] ?? []+ return ["bundle_id": id, "name": apps.first?["name"] ?? "", "pid": running.first(where: { $0["bundle_id"] as? String == id })?["pid"] ?? 0]+ case "apps.open_url":+ return try openAppURL(try string(params, "url"), bundleID: params["bundle_id"] as? String)+ case "apps.install":+ return try native([+ "t": "ipa_install",+ "path": try string(params, "path"),+ "registration": params["registration"] as? String ?? "User",+ "cert_path": params["cert_path"] as? String ?? "",+ ])+ case "input.touch":+ guard let phase = (params["phase"] as? String).flatMap(TouchPhase.init(rawValue:)) else {+ throw GuestAPIError.invalidRequest("phase must be down, move or up")+ }+ return try touch(phase, x: number(params, "x"), y: number(params, "y"),+ normalized: params["normalized"] as? Bool ?? true)+ case "input.hid":+ let page = try integer(params, "page")+ let usage = try integer(params, "usage")+ if let down = params["down"] as? Bool {+ return try hidEvent(page: page, usage: usage, down: down)+ }+ return try hidPress(page: page, usage: usage)+ case "location.set":+ return try simulateLocation(+ latitude: number(params, "latitude"),+ longitude: number(params, "longitude"),+ altitude: number(params, "altitude", default: 0),+ horizontalAccuracy: number(params, "horizontal_accuracy", default: 5),+ verticalAccuracy: number(params, "vertical_accuracy", default: 5),+ speed: (params["speed"] as? NSNumber)?.doubleValue,+ course: (params["course"] as? NSNumber)?.doubleValue+ )+ case "location.clear":+ return try clearSimulatedLocation()+ case "location.current":+ return try currentLocation(timeout: number(params, "timeout", default: 10))+ case "developer_mode.status":+ return try developerModeStatus()+ case "developer_mode.enable":+ return try enableDeveloperMode()+ case "power.low_power_mode":+ if let enabled = params["enabled"] as? Bool {+ return try setLowPowerMode(enabled)+ }+ return try lowPowerMode()+ case "clipboard.get":+ return try clipboardInfo()+ case "clipboard.set":+ return try setClipboard(try string(params, "text"))+ case "files.list":+ return try listDirectory(try string(params, "path"))+ case "files.mkdir":+ return try makeDirectory(try string(params, "path"), mode: nil)+ case "files.remove":+ return try removePath(try string(params, "path"), recursive: params["recursive"] as? Bool ?? false,+ force: true)+ case "files.rename":+ return try movePath(try string(params, "from"), to: try string(params, "to"))+ case "settings.get":+ return try readPreference(domain: try string(params, "domain"), key: params["key"] as? String)+ case "settings.set":+ let rawValue = params["value"] ?? NSNull()+ let type = params["type"] as? String ?? (rawValue is Bool ? "bool" : rawValue is NSNumber ? "float" : rawValue is String ? "string" : "json")+ let text: String+ if type == "json" {+ text = String(data: try JSONSerialization.data(withJSONObject: rawValue), encoding: .utf8) ?? ""+ } else { text = String(describing: rawValue) }+ return try writePreference(domain: try string(params, "domain"), key: try string(params, "key"), value: PreferenceValue(text: text, type: type))+ case "accessibility.tree":+ throw GuestAPIError.operationFailed("The accessibility tree is not available on this guest yet.")+ case "keychain.list":+ return try native(["t": "keychain_list", "class": params["class"] as? String ?? ""])+ case "keychain.add":+ return try native([+ "t": "keychain_add", "account": try string(params, "account"),+ "service": try string(params, "service"), "password": try string(params, "password"),+ ])+ case "agent.apply_update":+ let expected = try string(params, "sha256")+ let cache = "/var/root/Library/Caches/vphoned"+ let data = try Data(contentsOf: URL(fileURLWithPath: cache), options: .mappedIfSafe)+ let actual = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ guard actual == expected else { throw GuestAPIError.invalidRequest("Update hash mismatch") }+ guard chmod(cache, 0o755) == 0 else { throw GuestAPIError.operationFailed("Could not make update executable") }+ try Data(expected.utf8).write(to: URL(fileURLWithPath: "/var/root/Library/Caches/vphoned.api-v1"), options: .atomic)+ DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { exit(0) }+ return ["restarting": true]+ default:+ throw GuestAPIError.unsupportedMethod(method)+ }+ }++ private static func native(_ message: [String: Any]) throws -> [String: Any] {+ let result = vp_native_api_command(message) as? [String: Any] ?? [:]+ if result["t"] as? String == "err" {+ throw GuestAPIError.operationFailed(result["msg"] as? String ?? "Guest operation failed")+ }+ var payload = result+ payload.removeValue(forKey: "v")+ payload.removeValue(forKey: "t")+ payload.removeValue(forKey: "id")+ return payload+ }++ private static func string(_ params: [String: Any], _ key: String) throws -> String {+ guard let value = params[key] as? String, !value.isEmpty else {+ throw GuestAPIError.invalidRequest("\(key) is required")+ }+ return value+ }++ private static func integer(_ params: [String: Any], _ key: String) throws -> Int {+ guard let value = params[key] as? NSNumber else {+ throw GuestAPIError.invalidRequest("\(key) must be an integer")+ }+ return value.intValue+ }++ private static func number(_ params: [String: Any], _ key: String, default fallback: Double = .nan) -> Double {+ (params[key] as? NSNumber)?.doubleValue ?? fallback+ }+}diff --git a/scripts/vphoned/Swift/GuestEventPublisher.swift b/scripts/vphoned/Swift/GuestEventPublisher.swiftnew file mode 100644index 00000000..99ba2d1a--- /dev/null+++ b/scripts/vphoned/Swift/GuestEventPublisher.swift@@ -0,0 +1,35 @@+import Foundation+import IcliKit++/// Publishes the state a UI needs without requiring it to poll over HTTP.+/// The synchronous IcliKit calls share the same serial queue as commands.+final class GuestEventPublisher: @unchecked Sendable {+ private let hub: APIEventHub+ private let timer: DispatchSourceTimer+ private var previous: Data?++ init(hub: APIEventHub) {+ self.hub = hub+ timer = DispatchSource.makeTimerSource(queue: GuestAPI.queue)+ timer.schedule(deadline: .now(), repeating: .seconds(3))+ timer.setEventHandler { [weak self] in self?.publishIfChanged() }+ timer.resume()+ }++ private func publishIfChanged() {+ guard hub.hasSubscribers else {+ previous = nil+ return+ }+ let state: [String: Any] = [+ "screen": screenInfo(),+ "frontmost_app": frontmostApp(),+ "low_power_mode": (try? lowPowerMode()) ?? [:],+ ]+ guard let data = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]),+ data != previous+ else { return }+ previous = data+ hub.broadcast(name: "device.state", data: state)+ }+}diff --git a/scripts/vphoned/Swift/GuestFileTransfer.swift b/scripts/vphoned/Swift/GuestFileTransfer.swiftnew file mode 100644index 00000000..deedf6a5--- /dev/null+++ b/scripts/vphoned/Swift/GuestFileTransfer.swift@@ -0,0 +1,115 @@+import Darwin+import Foundation+import NIOCore+import NIOHTTP1+import NIOPosix++enum GuestFileTransfer {+ static func path(from uri: String) throws -> String {+ let components = URLComponents(string: "http://vphoned\(uri)")+ guard let path = components?.queryItems?.first(where: { $0.name == "path" })?.value,+ path.hasPrefix("/"), !path.contains("\0")+ else { throw GuestAPIError.invalidRequest("An absolute path query parameter is required") }+ return path+ }++ static func download(path: String, fileIO: NonBlockingFileIO, channel: Channel) {+ let fd = open(path, O_RDONLY | O_NOFOLLOW)+ guard fd >= 0 else {+ GuestHTTPHandler.send(APIWire.error("File could not be opened", status: 404), on: channel)+ return+ }+ let handle = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fd)+ do {+ var statBuffer = stat()+ guard fstat(fd, &statBuffer) == 0, (statBuffer.st_mode & S_IFMT) == S_IFREG else {+ throw GuestAPIError.invalidRequest("Path is not a regular file")+ }+ let region = try FileRegion(fileHandle: handle)+ var headers = HTTPHeaders()+ headers.add(name: "Content-Type", value: "application/octet-stream")+ headers.add(name: "Content-Length", value: String(region.readableBytes))+ headers.add(name: "Connection", value: "close")+ channel.write(HTTPServerResponsePart.head(.init(version: .http1_1, status: .ok, headers: headers)), promise: nil)+ fileIO.readChunked(fileRegion: region, chunkSize: 64 * 1024,+ allocator: channel.allocator, eventLoop: channel.eventLoop) { bytes in+ channel.writeAndFlush(HTTPServerResponsePart.body(.byteBuffer(bytes)))+ }.whenComplete { result in+ try? handle.close()+ switch result {+ case .success:+ channel.writeAndFlush(HTTPServerResponsePart.end(nil)).whenComplete { _ in+ channel.close(promise: nil)+ }+ case .failure:+ channel.close(promise: nil)+ }+ }+ } catch {+ try? handle.close()+ GuestHTTPHandler.send(APIWire.error(String(describing: error), status: 400), on: channel)+ }+ }+}++final class GuestFileUpload: @unchecked Sendable {+ private let destination: String+ private let temporary: String+ private let handle: NIOFileHandle+ private let fileIO: NonBlockingFileIO+ private var offset: Int64 = 0+ private var writes: EventLoopFuture<Void>+ private let onCommit: ((String) throws -> Void)?++ init(destination: String, fileIO: NonBlockingFileIO, channel: Channel,+ onCommit: ((String) throws -> Void)? = nil) throws {+ let temporary = destination + ".vphoned-" + UUID().uuidString + ".tmp"+ let fd = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)+ guard fd >= 0 else { throw GuestAPIError.operationFailed("Could not create upload file") }+ self.destination = destination+ self.temporary = temporary+ self.handle = NIOFileHandle(_deprecatedTakingOwnershipOfDescriptor: fd)+ self.fileIO = fileIO+ self.writes = channel.eventLoop.makeSucceededFuture(())+ self.onCommit = onCommit+ }++ func append(_ buffer: ByteBuffer, channel: Channel) {+ let start = offset+ offset += Int64(buffer.readableBytes)+ _ = channel.setOption(ChannelOptions.autoRead, value: false)+ writes = writes.flatMap { [fileIO, handle] in+ fileIO.write(fileHandle: handle, toOffset: start, buffer: buffer, eventLoop: channel.eventLoop)+ }+ writes.whenComplete { [self] _ in+ _ = self+ _ = channel.setOption(ChannelOptions.autoRead, value: true)+ }+ }++ func finish(channel: Channel) {+ writes.whenComplete { [self] result in+ do {+ try handle.close()+ switch result {+ case .failure(let error): throw error+ case .success: break+ }+ guard rename(temporary, destination) == 0 else {+ throw GuestAPIError.operationFailed("Could not replace destination file")+ }+ chmod(destination, 0o644)+ try onCommit?(destination)+ GuestHTTPHandler.send(.json(["result": ["path": destination, "size": offset]]), on: channel)+ } catch {+ unlink(temporary)+ GuestHTTPHandler.send(APIWire.error(String(describing: error), status: 500), on: channel)+ }+ }+ }++ deinit {+ if handle.isOpen { try? handle.close() }+ unlink(temporary)+ }+}diff --git a/scripts/vphoned/Swift/GuestHTTPHandler.swift b/scripts/vphoned/Swift/GuestHTTPHandler.swiftnew file mode 100644index 00000000..bf55cadb--- /dev/null+++ b/scripts/vphoned/Swift/GuestHTTPHandler.swift@@ -0,0 +1,217 @@+import Foundation+import IcliKit+import NIOCore+import NIOHTTP1+import NIOPosix++final class GuestHTTPHandler: ChannelInboundHandler, RemovableChannelHandler, @unchecked Sendable {+ typealias InboundIn = HTTPServerRequestPart+ typealias OutboundOut = HTTPServerResponsePart++ private let hub: APIEventHub+ private let fileIO: NonBlockingFileIO+ private var head: HTTPRequestHead?+ private var body = Data()+ private var exceededLimit = false+ private var upload: GuestFileUpload?+ private var uploadError: (any Error)?+ private var isBinaryUpload = false+ private let maximumJSONBody = 1 << 20++ init(hub: APIEventHub, fileIO: NonBlockingFileIO) {+ self.hub = hub+ self.fileIO = fileIO+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ switch unwrapInboundIn(data) {+ case .head(let request):+ head = request+ body.removeAll(keepingCapacity: true)+ exceededLimit = false+ upload = nil+ uploadError = nil+ let requestPath = request.uri.split(separator: "?", maxSplits: 1).first+ isBinaryUpload = request.method == .PUT && (requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image")+ if isBinaryUpload {+ do {+ upload = try GuestFileUpload(+ destination: requestPath == "/v1/clipboard/image"+ ? "/var/root/Library/Caches/vphoned-clipboard-image" : GuestFileTransfer.path(from: request.uri),+ fileIO: fileIO,+ channel: context.channel,+ onCommit: requestPath == "/v1/clipboard/image" ? { path in+ _ = try setClipboardImage(Data(contentsOf: URL(fileURLWithPath: path)))+ unlink(path)+ } : nil+ )+ } catch { uploadError = error }+ }+ case .body(var buffer):+ if isBinaryUpload {+ upload?.append(buffer, channel: context.channel)+ return+ }+ if body.count + buffer.readableBytes > maximumJSONBody {+ exceededLimit = true+ return+ }+ if let bytes = buffer.readBytes(length: buffer.readableBytes) {+ body.append(contentsOf: bytes)+ }+ case .end:+ guard let head else { return }+ self.head = nil+ let path = head.uri.split(separator: "?", maxSplits: 1).first.map(String.init) ?? head.uri+ if path == "/v1/files/content" || path == "/v1/clipboard/image" {+ if head.method == .PUT {+ if let uploadError {+ Self.send(APIWire.error(String(describing: uploadError)), on: context.channel)+ } else {+ upload?.finish(channel: context.channel)+ }+ upload = nil+ } else if head.method == .GET && path == "/v1/clipboard/image" {+ do {+ guard let image = try clipboardImagePNG() else {+ Self.send(APIWire.error("Clipboard has no image", status: 404), on: context.channel)+ return+ }+ Self.send(APIReply(status: 200, data: image), on: context.channel, contentType: "image/png")+ } catch { Self.send(APIWire.error(String(describing: error)), on: context.channel) }+ } else if head.method == .GET {+ do {+ GuestFileTransfer.download(path: try GuestFileTransfer.path(from: head.uri),+ fileIO: fileIO, channel: context.channel)+ } catch {+ Self.send(APIWire.error(String(describing: error)), on: context.channel)+ }+ } else {+ Self.send(APIWire.error("Method not allowed", status: 405), on: context.channel)+ }+ return+ }+ if exceededLimit {+ Self.send(APIWire.error("JSON body exceeds 1 MiB", status: 413), on: context.channel)+ return+ }+ handle(head, body: body, channel: context.channel)+ }+ }++ private func handle(_ head: HTTPRequestHead, body: Data, channel: Channel) {+ let path = head.uri.split(separator: "?", maxSplits: 1).first.map(String.init) ?? head.uri+ if head.method == .GET && path == "/openapi.json" {+ Self.send(APIReply(status: 200, data: OpenAPISpec.data), on: channel)+ return+ }+ if head.method == .GET && path == "/v1/health" {+ Self.send(.json(GuestAPI.health()), on: channel)+ return+ }+ if path == "/v1/events" {+ Self.send(APIWire.error("WebSocket upgrade required", status: 426), on: channel)+ return+ }++ do {+ let request: APIRequest+ if head.method == .POST && path == "/v1/rpc" {+ request = try APIWire.decode(body)+ } else {+ let method = try Self.route(head.method, path: path)+ var params = try Self.parameters(body)+ let components = URLComponents(string: "http://vphoned\(head.uri)")+ for item in components?.queryItems ?? [] {+ if let value = item.value { params[item.name] = value }+ }+ request = APIRequest(method: method, params: params, id: nil)+ }+ let job = HTTPJob(channel: channel, request: request, hub: hub)+ let queue = request.method == "icli.execute" ? IcliCommand.queue : GuestAPI.queue+ queue.async { job.run() }+ } catch {+ Self.send(APIWire.error(String(describing: error)), on: channel)+ }+ }++ private static func parameters(_ body: Data) throws -> [String: Any] {+ if body.isEmpty { return [:] }+ guard let object = try JSONSerialization.jsonObject(with: body) as? [String: Any] else {+ throw GuestAPIError.invalidRequest("Request body must be a JSON object")+ }+ return object+ }++ private static func route(_ verb: HTTPMethod, path: String) throws -> String {+ switch (verb, path) {+ case (.GET, "/v1/device"): "device.snapshot"+ case (.POST, "/v1/icli/execute"): "icli.execute"+ case (.GET, "/v1/device/screen"): "device.screen"+ case (.GET, "/v1/apps"): "apps.list"+ case (.POST, "/v1/apps/launch"): "apps.launch"+ case (.POST, "/v1/apps/terminate"): "apps.terminate"+ case (.GET, "/v1/apps/foreground"): "apps.foreground"+ case (.POST, "/v1/apps/open-url"): "apps.open_url"+ case (.POST, "/v1/apps/install"): "apps.install"+ case (.POST, "/v1/input/touch"): "input.touch"+ case (.POST, "/v1/input/hid"): "input.hid"+ case (.GET, "/v1/location"): "location.current"+ case (.PUT, "/v1/location"): "location.set"+ case (.DELETE, "/v1/location"): "location.clear"+ case (.GET, "/v1/developer-mode"): "developer_mode.status"+ case (.POST, "/v1/developer-mode/enable"): "developer_mode.enable"+ case (.GET, "/v1/low-power-mode"), (.PUT, "/v1/low-power-mode"): "power.low_power_mode"+ case (.GET, "/v1/clipboard"), (.PUT, "/v1/clipboard"): verb == .GET ? "clipboard.get" : "clipboard.set"+ case (.GET, "/v1/files"): "files.list"+ case (.POST, "/v1/files/mkdir"): "files.mkdir"+ case (.POST, "/v1/files/remove"): "files.remove"+ case (.POST, "/v1/files/rename"): "files.rename"+ case (.POST, "/v1/settings/get"): "settings.get"+ case (.POST, "/v1/settings/set"): "settings.set"+ case (.GET, "/v1/keychain"): "keychain.list"+ case (.POST, "/v1/keychain"): "keychain.add"+ default: throw GuestAPIError.invalidRequest("No route for \(verb) \(path)")+ }+ }++ static func send(_ reply: APIReply, on channel: Channel, contentType: String = "application/json; charset=utf-8") {+ let write: @Sendable () -> Void = {+ var headers = HTTPHeaders()+ headers.add(name: "Content-Type", value: contentType)+ headers.add(name: "Content-Length", value: String(reply.data.count))+ headers.add(name: "Connection", value: "close")+ let status = HTTPResponseStatus(statusCode: reply.status)+ channel.write(HTTPServerResponsePart.head(.init(version: .http1_1, status: status, headers: headers)), promise: nil)+ var buffer = channel.allocator.buffer(capacity: reply.data.count)+ buffer.writeBytes(reply.data)+ channel.write(HTTPServerResponsePart.body(.byteBuffer(buffer)), promise: nil)+ channel.writeAndFlush(HTTPServerResponsePart.end(nil)).whenComplete { _ in+ channel.close(promise: nil)+ }+ }+ if channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }+ }++ func errorCaught(context: ChannelHandlerContext, error: Error) {+ context.close(promise: nil)+ }+}++private final class HTTPJob: @unchecked Sendable {+ let channel: Channel+ let request: APIRequest+ let hub: APIEventHub++ init(channel: Channel, request: APIRequest, hub: APIEventHub) {+ self.channel = channel+ self.request = request+ self.hub = hub+ }++ func run() {+ let reply = APIWire.execute(request)+ if reply.status == 200 { hub.broadcast(name: "operation.completed", data: ["method": request.method]) }+ GuestHTTPHandler.send(reply, on: channel)+ }+}diff --git a/scripts/vphoned/Swift/GuestWebSocketHandler.swift b/scripts/vphoned/Swift/GuestWebSocketHandler.swiftnew file mode 100644index 00000000..2d064239--- /dev/null+++ b/scripts/vphoned/Swift/GuestWebSocketHandler.swift@@ -0,0 +1,80 @@+import Foundation+import NIOCore+import NIOWebSocket++final class GuestWebSocketHandler: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = WebSocketFrame+ typealias OutboundOut = WebSocketFrame++ private let hub: APIEventHub+ init(hub: APIEventHub) { self.hub = hub }++ func handlerAdded(context: ChannelHandlerContext) {+ hub.add(context.channel)+ let hello = APIReply.json(["type": "event", "event": "connected", "data": ["api_version": 1]])+ Self.send(hello.data, on: context.channel)+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ let frame = unwrapInboundIn(data)+ switch frame.opcode {+ case .text:+ var buffer = frame.unmaskedData+ guard let bytes = buffer.readBytes(length: buffer.readableBytes) else { return }+ do {+ let request = try APIWire.decode(Data(bytes))+ let job = WebSocketJob(channel: context.channel, request: request, hub: hub)+ let queue = request.method == "icli.execute" ? IcliCommand.queue : GuestAPI.queue+ queue.async { job.run() }+ } catch {+ let reply = APIReply.json(["type": "response", "id": NSNull(),+ "error": ["code": "bad_request", "message": String(describing: error)]])+ Self.send(reply.data, on: context.channel)+ }+ case .ping:+ let pong = WebSocketFrame(fin: true, opcode: .pong, data: frame.unmaskedData)+ context.writeAndFlush(wrapOutboundOut(pong), promise: nil)+ case .connectionClose:+ context.close(promise: nil)+ default:+ break+ }+ }++ func channelInactive(context: ChannelHandlerContext) {+ hub.remove(context.channel)+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error: Error) {+ context.close(promise: nil)+ }++ fileprivate static func send(_ data: Data, on channel: Channel) {+ let write: @Sendable () -> Void = {+ guard channel.isActive else { return }+ var buffer = channel.allocator.buffer(capacity: data.count)+ buffer.writeBytes(data)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .text, data: buffer), promise: nil)+ }+ if channel.eventLoop.inEventLoop { write() } else { channel.eventLoop.execute(write) }+ }+}++private final class WebSocketJob: @unchecked Sendable {+ let channel: Channel+ let request: APIRequest+ let hub: APIEventHub++ init(channel: Channel, request: APIRequest, hub: APIEventHub) {+ self.channel = channel+ self.request = request+ self.hub = hub+ }++ func run() {+ let reply = APIWire.execute(request)+ GuestWebSocketHandler.send(reply.data, on: channel)+ if reply.status == 200 { hub.broadcast(name: "operation.completed", data: ["method": request.method]) }+ }+}diff --git a/scripts/vphoned/Swift/IcliCommand.swift b/scripts/vphoned/Swift/IcliCommand.swiftnew file mode 100644index 00000000..745f662a--- /dev/null+++ b/scripts/vphoned/Swift/IcliCommand.swift@@ -0,0 +1,92 @@+import Darwin+import Foundation++/// Invokes the pinned guest icli binary with an argument vector, never a shell.+/// The caller explicitly opted into the host API via --api-listen.+enum IcliCommand {+ static let queue = DispatchQueue(label: "vphoned.icli.commands", qos: .userInitiated)++ static func execute(_ params: [String: Any]) throws -> [String: Any] {+ guard let arguments = params["argv"] as? [String], !arguments.isEmpty,+ arguments.count <= 64,+ arguments.allSatisfy({ !$0.contains("\0") && $0.utf8.count <= 4096 })+ else { throw GuestAPIError.invalidRequest("argv must be 1–64 command arguments") }+ guard FileManager.default.isExecutableFile(atPath: "/usr/bin/icli") else {+ throw GuestAPIError.operationFailed("icli is not installed in this guest image")+ }+ let input: Data+ if let encoded = params["stdin_base64"] as? String {+ guard let decoded = Data(base64Encoded: encoded) else {+ throw GuestAPIError.invalidRequest("stdin_base64 is invalid")+ }+ input = decoded+ } else {+ input = Data((params["stdin"] as? String ?? "").utf8)+ }+ guard input.count <= 1 << 20 else {+ throw GuestAPIError.invalidRequest("stdin exceeds 1 MiB")+ }++ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("vphoned-icli-" + UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)+ defer { try? FileManager.default.removeItem(at: directory) }+ let inputURL = directory.appendingPathComponent("stdin")+ let outputURL = directory.appendingPathComponent("stdout")+ let errorURL = directory.appendingPathComponent("stderr")+ try input.write(to: inputURL)+ let stdinFD = open(inputURL.path, O_RDONLY | O_NOFOLLOW)+ let stdoutFD = open(outputURL.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)+ let stderrFD = open(errorURL.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)+ guard stdinFD >= 0, stdoutFD >= 0, stderrFD >= 0 else {+ if stdinFD >= 0 { close(stdinFD) }+ if stdoutFD >= 0 { close(stdoutFD) }+ if stderrFD >= 0 { close(stderrFD) }+ throw GuestAPIError.operationFailed("Could not prepare icli output")+ }+ defer { close(stdinFD); close(stdoutFD); close(stderrFD) }++ var actions = posix_spawn_file_actions_t()+ posix_spawn_file_actions_init(&actions)+ defer { posix_spawn_file_actions_destroy(&actions) }+ posix_spawn_file_actions_adddup2(&actions, stdinFD, STDIN_FILENO)+ posix_spawn_file_actions_adddup2(&actions, stdoutFD, STDOUT_FILENO)+ posix_spawn_file_actions_adddup2(&actions, stderrFD, STDERR_FILENO)+ var argv = (["/usr/bin/icli"] + arguments).map { strdup($0) as UnsafeMutablePointer<CChar>? }+ argv.append(nil)+ defer { argv.forEach { if let value = $0 { free(value) } } }+ var pid: pid_t = 0+ let spawnStatus = argv.withUnsafeMutableBufferPointer { pointer in+ posix_spawn(&pid, "/usr/bin/icli", &actions, nil, pointer.baseAddress, environ)+ }+ guard spawnStatus == 0 else {+ throw GuestAPIError.operationFailed("Could not launch icli (errno \(spawnStatus))")+ }++ let deadline = ProcessInfo.processInfo.systemUptime + 120+ var status: Int32 = 0+ while true {+ let waited = waitpid(pid, &status, WNOHANG)+ if waited == pid { break }+ if waited < 0 { throw GuestAPIError.operationFailed("Could not wait for icli") }+ if ProcessInfo.processInfo.systemUptime >= deadline {+ kill(pid, SIGKILL)+ _ = waitpid(pid, &status, 0)+ throw GuestAPIError.operationFailed("icli timed out after 120 seconds")+ }+ Thread.sleep(forTimeInterval: 0.05)+ }+ let stdout = try Data(contentsOf: outputURL, options: .mappedIfSafe)+ let stderr = try Data(contentsOf: errorURL, options: .mappedIfSafe)+ guard stdout.count <= 64 << 20, stderr.count <= 1 << 20 else {+ throw GuestAPIError.operationFailed("icli output exceeded the API limit")+ }+ let parsed = try? JSONSerialization.jsonObject(with: stdout, options: [.fragmentsAllowed])+ let code = (status & 0x7f) == 0 ? Int((status >> 8) & 0xff) : -Int(status & 0x7f)+ return [+ "exit_code": code,+ "output": parsed ?? String(decoding: stdout, as: UTF8.self),+ "stderr": String(decoding: stderr, as: UTF8.self),+ ]+ }+}diff --git a/scripts/vphoned/Swift/OpenAPISpec.swift b/scripts/vphoned/Swift/OpenAPISpec.swiftnew file mode 100644index 00000000..30ca5cb0--- /dev/null+++ b/scripts/vphoned/Swift/OpenAPISpec.swift@@ -0,0 +1,78 @@+import Foundation++enum OpenAPISpec {+ static let data = Data(spec.utf8)++ private static let spec = #"""+ {+ "openapi": "3.1.0",+ "info": {+ "title": "vphoned API",+ "version": "1.0.0",+ "description": "Guest API over VSOCK 1339. vphone-vm can forward it to an opt-in host HTTP listener. JSON operations are also available as WebSocket requests on /v1/events."+ },+ "servers": [{"url": "/"}],+ "paths": {+ "/v1/health": {"get": {"operationId": "health", "responses": {"200": {"description": "Daemon is running"}}}},+ "/v1/icli/execute": {"post": {"operationId": "icli.execute", "description": "Run any icli command inside the guest with an argv array. The result includes exit_code, output and stderr.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["argv"], "properties": {"argv": {"type": "array", "items": {"type": "string"}}, "stdin": {"type": "string"}, "stdin_base64": {"type": "string", "contentEncoding": "base64"}}}}}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/device": {"get": {"operationId": "device.snapshot", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/device/screen": {"get": {"operationId": "device.screen", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps": {"get": {"operationId": "apps.list", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps/launch": {"post": {"operationId": "apps.launch", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps/terminate": {"post": {"operationId": "apps.terminate", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps/foreground": {"get": {"operationId": "apps.foreground", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps/open-url": {"post": {"operationId": "apps.open_url", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/apps/install": {"post": {"operationId": "apps.install", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/input/touch": {"post": {"operationId": "input.touch", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/input/hid": {"post": {"operationId": "input.hid", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/location": {+ "get": {"operationId": "location.current", "responses": {"200": {"$ref": "#/components/responses/Result"}}},+ "put": {"operationId": "location.set", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}},+ "delete": {"operationId": "location.clear", "responses": {"200": {"$ref": "#/components/responses/Result"}}}+ },+ "/v1/developer-mode": {"get": {"operationId": "developer_mode.status", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/developer-mode/enable": {"post": {"operationId": "developer_mode.enable", "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/low-power-mode": {+ "get": {"operationId": "power.low_power_mode", "responses": {"200": {"$ref": "#/components/responses/Result"}}},+ "put": {"operationId": "power.low_power_mode", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}+ },+ "/v1/clipboard": {+ "get": {"operationId": "clipboard.get", "responses": {"200": {"$ref": "#/components/responses/Result"}}},+ "put": {"operationId": "clipboard.set", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}+ },+ "/v1/clipboard/image": {+ "get": {"operationId": "clipboard.image.download", "responses": {"200": {"description": "PNG image"}}},+ "put": {"operationId": "clipboard.image.upload", "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "responses": {"200": {"description": "Clipboard image set"}}}+ },+ "/v1/files": {"get": {"operationId": "files.list", "parameters": [{"name": "path", "in": "query", "required": true, "schema": {"type": "string"}}], "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/files/content": {+ "get": {"operationId": "files.download", "parameters": [{"$ref": "#/components/parameters/FilePath"}], "responses": {"200": {"description": "File bytes", "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}}},+ "put": {"operationId": "files.upload", "parameters": [{"$ref": "#/components/parameters/FilePath"}], "requestBody": {"required": true, "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}}, "responses": {"200": {"description": "File stored"}}}+ },+ "/v1/files/mkdir": {"post": {"operationId": "files.mkdir", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/files/remove": {"post": {"operationId": "files.remove", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/files/rename": {"post": {"operationId": "files.rename", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/settings/get": {"post": {"operationId": "settings.get", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/settings/set": {"post": {"operationId": "settings.set", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/keychain": {+ "get": {"operationId": "keychain.list", "responses": {"200": {"$ref": "#/components/responses/Result"}}},+ "post": {"operationId": "keychain.add", "requestBody": {"$ref": "#/components/requestBodies/Parameters"}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}+ },+ "/v1/rpc": {"post": {"operationId": "rpc", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Request"}}}}, "responses": {"200": {"$ref": "#/components/responses/Result"}}}},+ "/v1/events": {"get": {"operationId": "websocketEvents", "description": "Upgrade to WebSocket. Send Request objects and receive Response or Event objects.", "responses": {"101": {"description": "WebSocket upgrade"}, "426": {"description": "Upgrade required"}}}}+ },+ "components": {+ "parameters": {"FilePath": {"name": "path", "in": "query", "required": true, "schema": {"type": "string", "description": "Absolute guest path"}}},+ "schemas": {+ "Request": {"type": "object", "required": ["method"], "properties": {"id": {"oneOf": [{"type": "string"}, {"type": "integer"}]}, "method": {"type": "string"}, "params": {"type": "object", "additionalProperties": true}}},+ "Response": {"type": "object", "required": ["type", "id"], "properties": {"type": {"const": "response"}, "id": {}, "result": {"type": "object", "additionalProperties": true}, "error": {"$ref": "#/components/schemas/Error"}}},+ "Event": {"type": "object", "required": ["type", "event", "data"], "properties": {"type": {"const": "event"}, "event": {"type": "string"}, "data": {"type": "object", "additionalProperties": true}}},+ "Error": {"type": "object", "required": ["code", "message"], "properties": {"code": {"type": "string"}, "message": {"type": "string"}}}+ },+ "requestBodies": {"Parameters": {"content": {"application/json": {"schema": {"type": "object", "additionalProperties": true}}}}},+ "responses": {"Result": {"description": "A Response envelope with result or error", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Response"}}}}}+ },+ "x-websocket": {"path": "/v1/events", "request": {"$ref": "#/components/schemas/Request"}, "messages": [{"$ref": "#/components/schemas/Response"}, {"$ref": "#/components/schemas/Event"}]}+ }+ """#+}diff --git a/scripts/vphoned/Swift/main.swift b/scripts/vphoned/Swift/main.swiftnew file mode 100644index 00000000..b9b0536c--- /dev/null+++ b/scripts/vphoned/Swift/main.swift@@ -0,0 +1,56 @@+import Foundation+import NIOCore+import NIOHTTP1+import NIOPosix+import NIOWebSocket+import VphonedNative++vp_native_bootstrap_cached_binary()+vp_vcam_start()++let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)+let filePool = NIOThreadPool(numberOfThreads: 2)+filePool.start()+let fileIO = NonBlockingFileIO(threadPool: filePool)+let hub = APIEventHub()+let eventPublisher = GuestEventPublisher(hub: hub)++do {+ let server = try ServerBootstrap(group: group)+ .serverChannelOption(ChannelOptions.backlog, value: 128)+ .childChannelInitializer { channel in+ let http = GuestHTTPHandler(hub: hub, fileIO: fileIO)+ let upgrader = NIOWebSocketServerUpgrader(+ maxFrameSize: 1 << 20,+ shouldUpgrade: { channel, request in+ channel.eventLoop.makeSucceededFuture(request.uri == "/v1/events" ? HTTPHeaders() : nil)+ },+ upgradePipelineHandler: { channel, _ in+ channel.pipeline.removeHandler(http).flatMap {+ channel.pipeline.addHandlers([+ NIOWebSocketFrameAggregator(+ minNonFinalFragmentSize: 1,+ maxAccumulatedFrameCount: 32,+ maxAccumulatedFrameSize: 1 << 20+ ),+ GuestWebSocketHandler(hub: hub),+ ])+ }+ }+ )+ return channel.pipeline.configureHTTPServerPipeline(+ withServerUpgrade: (upgraders: [upgrader], completionHandler: { _ in })+ ).flatMap { channel.pipeline.addHandler(http) }+ }+ .bind(to: VsockAddress(cid: .any, port: 1339))+ .wait()+ NSLog("vphoned: HTTP/WebSocket API listening on vsock 1339")+ try server.closeFuture.wait()+} catch {+ NSLog("vphoned: HTTP/WebSocket API failed: %@", String(describing: error))+ exit(1)+}++try? group.syncShutdownGracefully()+try? filePool.syncShutdownGracefully()+_ = eventPublisherdiff --git a/scripts/vphoned/include/VphonedNative.h b/scripts/vphoned/include/VphonedNative.hnew file mode 100644index 00000000..69ebc303--- /dev/null+++ b/scripts/vphoned/include/VphonedNative.h@@ -0,0 +1,7 @@+#pragma once+#import <Foundation/Foundation.h>++/// vphone-specific operations that IcliKit does not own.+NSDictionary *vp_native_api_command(NSDictionary *message);+void vp_native_bootstrap_cached_binary(void);+void vp_vcam_start(void);diff --git a/scripts/vphoned/vphoned.m b/scripts/vphoned/vphoned.mdeleted file mode 100644index 3bb618e9..00000000--- a/scripts/vphoned/vphoned.m+++ /dev/null@@ -1,500 +0,0 @@-/*- * vphoned — VM guest agent for vphone-cli.- *- * Runs inside the iOS VM as a LaunchDaemon. Communicates with the host- * over vsock using length-prefixed JSON (vphone-control protocol).- *- * Auto-update: on each handshake the host sends its binary hash. If it- * differs from our own, the host pushes a signed replacement. We write- * it to CACHE_PATH and exit — launchd restarts us, and the bootstrap- * code in main() exec's the cached binary.- *- * Build:- * make vphoned- */--#include <CommonCrypto/CommonDigest.h>-#import <Foundation/Foundation.h>-#include <arpa/inet.h>-#include <ifaddrs.h>-#include <mach-o/dyld.h>-#include <net/if.h>-#include <netinet/in.h>-#include <sys/socket.h>-#include <sys/stat.h>-#include <unistd.h>--#import "vphoned_accessibility.h"-#import "vphoned_apps.h"-#import "vphoned_clipboard.h"-#import "vphoned_devmode.h"-#import "vphoned_files.h"-#import "vphoned_hid.h"-#import "vphoned_install.h"-#import "vphoned_keychain.h"-#import "vphoned_location.h"-#import "vphoned_notify.h"-#import "vphoned_protocol.h"-#import "vphoned_settings.h"-#import "vphoned_url.h"-#import "vphoned_vcam.h"--#ifndef AF_VSOCK-#define AF_VSOCK 40-#endif--#define VMADDR_CID_ANY 0xFFFFFFFF-#define VPHONED_PORT 1337--#ifndef VPHONED_BUILD_HASH-#define VPHONED_BUILD_HASH "unknown"-#endif--static BOOL gClipboardAvailable = NO;-static BOOL gAppsAvailable = NO;--#define INSTALL_PATH "/usr/bin/vphoned"-#define CACHE_PATH "/var/root/Library/Caches/vphoned"-#define CACHE_DIR "/var/root/Library/Caches"--struct sockaddr_vm {- __uint8_t svm_len;- sa_family_t svm_family;- __uint16_t svm_reserved1;- __uint32_t svm_port;- __uint32_t svm_cid;-};--// MARK: - Self-hash--static NSString *sha256_of_file(const char *path) {- int fd = open(path, O_RDONLY);- if (fd < 0)- return nil;-- CC_SHA256_CTX ctx;- CC_SHA256_Init(&ctx);-- uint8_t buf[32768];- ssize_t n;- while ((n = read(fd, buf, sizeof(buf))) > 0)- CC_SHA256_Update(&ctx, buf, (CC_LONG)n);- close(fd);-- unsigned char digest[CC_SHA256_DIGEST_LENGTH];- CC_SHA256_Final(digest, &ctx);-- NSMutableString *hex =- [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];- for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)- [hex appendFormat:@"%02x", digest[i]];- return hex;-}--static const char *self_executable_path(void) {- static char path[4096];- uint32_t size = sizeof(path);- if (_NSGetExecutablePath(path, &size) != 0)- return NULL;- return path;-}--// MARK: - Network--/// Returns the first non-loopback IPv4 address, preferring en* interfaces-/// (Wi-Fi/cellular over virtual). Returns nil if no usable address is found.-static NSString *primary_ipv4_address(void) {- struct ifaddrs *ifap = NULL;- if (getifaddrs(&ifap) != 0 || ifap == NULL)- return nil;-- NSString *preferred = nil;- NSString *fallback = nil;-- for (struct ifaddrs *cur = ifap; cur != NULL; cur = cur->ifa_next) {- if (cur->ifa_addr == NULL || cur->ifa_addr->sa_family != AF_INET)- continue;- if ((cur->ifa_flags & IFF_UP) == 0 ||- (cur->ifa_flags & IFF_LOOPBACK) != 0)- continue;-- char buf[INET_ADDRSTRLEN] = {0};- struct sockaddr_in *sin = (struct sockaddr_in *)cur->ifa_addr;- if (!inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf)))- continue;-- NSString *addr = [NSString stringWithUTF8String:buf];- NSString *name = [NSString stringWithUTF8String:cur->ifa_name];- if ([name hasPrefix:@"en"] || [name hasPrefix:@"pdp_ip"]) {- preferred = addr;- break;- }- if (!fallback)- fallback = addr;- }-- freeifaddrs(ifap);- return preferred ?: fallback;-}--// MARK: - Auto-update--/// Receive raw binary from host, write to CACHE_PATH, chmod +x.-static BOOL receive_update(int fd, NSUInteger size) {- mkdir(CACHE_DIR, 0755);-- char tmp_path[] = CACHE_DIR "/vphoned.XXXXXX";- int tmp_fd = mkstemp(tmp_path);- if (tmp_fd < 0) {- NSLog(@"vphoned: mkstemp failed: %s", strerror(errno));- return NO;- }-- uint8_t buf[32768];- NSUInteger remaining = size;- while (remaining > 0) {- size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf);- if (!vp_read_fully(fd, buf, chunk)) {- NSLog(@"vphoned: update read failed at %lu/%lu",- (unsigned long)(size - remaining), (unsigned long)size);- close(tmp_fd);- unlink(tmp_path);- return NO;- }- if (write(tmp_fd, buf, chunk) != (ssize_t)chunk) {- NSLog(@"vphoned: update write failed: %s", strerror(errno));- close(tmp_fd);- unlink(tmp_path);- return NO;- }- remaining -= chunk;- }- close(tmp_fd);- chmod(tmp_path, 0755);-- if (rename(tmp_path, CACHE_PATH) != 0) {- NSLog(@"vphoned: rename to cache failed: %s", strerror(errno));- unlink(tmp_path);- return NO;- }-- NSLog(@"vphoned: update written to %s (%lu bytes)", CACHE_PATH,- (unsigned long)size);- return YES;-}--// MARK: - Command Dispatch--static NSDictionary *handle_command(NSDictionary *msg) {- NSString *type = msg[@"t"];- id reqId = msg[@"id"];-- if ([type isEqualToString:@"hid"]) {- uint32_t page = [msg[@"page"] unsignedIntValue];- uint32_t usage = [msg[@"usage"] unsignedIntValue];- NSNumber *downVal = msg[@"down"];- if (downVal != nil) {- vp_hid_key(page, usage, [downVal boolValue]);- } else {- vp_hid_press(page, usage);- }- return vp_make_response(@"ok", reqId);- }-- if ([type isEqualToString:@"touch"]) {- int phase = [msg[@"phase"] intValue];- double x = [msg[@"x"] doubleValue];- double y = [msg[@"y"] doubleValue];- vp_hid_touch(phase, x, y);- return vp_make_response(@"ok", reqId);- }-- if ([type isEqualToString:@"devmode"]) {- if (!vp_devmode_available()) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"Developer Mode is not available on this guest.";- return r;- }- NSString *action = msg[@"action"];- if ([action isEqualToString:@"status"]) {- BOOL enabled = vp_devmode_status();- NSMutableDictionary *r = vp_make_response(@"ok", reqId);- r[@"enabled"] = @(enabled);- return r;- }- if ([action isEqualToString:@"enable"]) {- BOOL alreadyEnabled = NO;- BOOL ok = vp_devmode_arm(&alreadyEnabled);- NSMutableDictionary *r = vp_make_response(ok ? @"ok" : @"err", reqId);- if (ok) {- r[@"already_enabled"] = @(alreadyEnabled);- r[@"msg"] = alreadyEnabled- ? @"Developer Mode is already enabled."- : @"Developer Mode will be enabled after you restart the guest.";- } else {- r[@"msg"] = @"Unable to enable Developer Mode.";- }- return r;- }- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] =- [NSString stringWithFormat:@"unknown devmode action: %@", action];- return r;- }-- if ([type isEqualToString:@"ping"]) {- return vp_make_response(@"pong", reqId);- }-- if ([type isEqualToString:@"location"]) {- double lat = [msg[@"lat"] doubleValue];- double lon = [msg[@"lon"] doubleValue];- double alt = [msg[@"alt"] doubleValue];- double hacc = [msg[@"hacc"] doubleValue];- double vacc = [msg[@"vacc"] doubleValue];- double speed = [msg[@"speed"] doubleValue];- double course = [msg[@"course"] doubleValue];- vp_location_simulate(lat, lon, alt, hacc, vacc, speed, course);- return vp_make_response(@"ok", reqId);- }-- if ([type isEqualToString:@"location_stop"]) {- vp_location_clear();- return vp_make_response(@"ok", reqId);- }-- if ([type isEqualToString:@"version"]) {- NSMutableDictionary *r = vp_make_response(@"version", reqId);- r[@"hash"] = @VPHONED_BUILD_HASH;- return r;- }-- if ([type isEqualToString:@"ipa_install"]) {- return vp_handle_custom_install(msg);- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"unknown type: %@", type];- return r;-}--// MARK: - Client Session--/// Returns YES if daemon should exit for restart (after update).-static BOOL handle_client(int fd) {- BOOL should_restart = NO;- @autoreleasepool {- NSDictionary *hello = vp_read_message(fd);- if (!hello) {- close(fd);- return NO;- }-- NSInteger version = [hello[@"v"] integerValue];- NSString *type = hello[@"t"];-- if (![type isEqualToString:@"hello"]) {- NSLog(@"vphoned: expected hello, got %@", type);- close(fd);- return NO;- }-- if (version != PROTOCOL_VERSION) {- NSLog(@"vphoned: version mismatch (client v%ld, daemon v%d)",- (long)version, PROTOCOL_VERSION);- vp_write_message(- fd, @{- @"v" : @PROTOCOL_VERSION,- @"t" : @"err",- @"msg" : @"version mismatch"- });- close(fd);- return NO;- }-- // Hash comparison for auto-update- NSString *hostHash = hello[@"bin_hash"];- BOOL needUpdate = NO;- if (hostHash.length > 0) {- const char *selfPath = self_executable_path();- NSString *selfHash = selfPath ? sha256_of_file(selfPath) : nil;- if (selfHash && ![selfHash isEqualToString:hostHash]) {- NSLog(@"vphoned: hash mismatch (self=%@ host=%@)", selfHash, hostHash);- needUpdate = YES;- } else if (selfHash) {- NSLog(@"vphoned: hash OK");- }- }-- // Build capabilities list- NSMutableArray *caps = [NSMutableArray- arrayWithObjects:@"hid", @"devmode", @"file", @"keychain", nil];- if (vp_location_available())- [caps addObject:@"location"];- if (vp_custom_installer_available())- [caps addObject:@"ipa_install"];- if (gClipboardAvailable)- [caps addObject:@"clipboard"];- if (gAppsAvailable)- [caps addObject:@"apps"];- [caps addObject:@"url"];- [caps addObject:@"settings"];- [caps addObject:@"touch"];-- NSMutableDictionary *helloResp = [@{- @"v" : @PROTOCOL_VERSION,- @"t" : @"hello",- @"name" : @"vphoned",- @"caps" : caps,- } mutableCopy];- NSOperatingSystemVersion osv =- [[NSProcessInfo processInfo] operatingSystemVersion];- helloResp[@"ios"] =- [NSString stringWithFormat:@"%ld.%ld.%ld", (long)osv.majorVersion,- (long)osv.minorVersion, (long)osv.patchVersion];- NSString *ip = primary_ipv4_address();- if (ip)- helloResp[@"ip"] = ip;- if (needUpdate)- helloResp[@"need_update"] = @YES;-- if (!vp_write_message(fd, helloResp)) {- close(fd);- return NO;- }- NSLog(@"vphoned: client connected (v%d)%s", PROTOCOL_VERSION,- needUpdate ? " [update pending]" : "");-- NSDictionary *msg;- while ((msg = vp_read_message(fd)) != nil) {- @autoreleasepool {- NSString *t = msg[@"t"];- NSLog(@"vphoned: recv cmd: %@", t);-- if ([t isEqualToString:@"update"]) {- NSUInteger size = [msg[@"size"] unsignedIntegerValue];- id reqId = msg[@"id"];- NSLog(@"vphoned: receiving update (%lu bytes)", (unsigned long)size);- if (size > 0 && size < 10 * 1024 * 1024 && receive_update(fd, size)) {- NSMutableDictionary *r = vp_make_response(@"ok", reqId);- r[@"msg"] = @"Updated. Restarting the guest agent…";- vp_write_message(fd, r);- should_restart = YES;- break;- } else {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"Unable to update the guest agent. Try again.";- vp_write_message(fd, r);- }- continue;- }-- NSDictionary *resp;- if ([t hasPrefix:@"file_"]) {- // Needs fd for inline binary transfer.- resp = vp_handle_file_command(fd, msg);- } else if ([t hasPrefix:@"keychain_"]) {- resp = vp_handle_keychain_command(msg);- } else if ([t hasPrefix:@"clipboard_"]) {- // Needs fd for inline binary transfer.- resp = vp_handle_clipboard_command(fd, msg);- } else if ([t hasPrefix:@"app_"]) {- resp = vp_handle_apps_command(msg);- } else if ([t isEqualToString:@"open_url"]) {- resp = vp_handle_url_command(msg);- } else if ([t hasPrefix:@"settings_"]) {- resp = vp_handle_settings_command(msg);- } else if ([t isEqualToString:@"accessibility_tree"]) {- resp = vp_handle_accessibility_command(msg);- } else if ([t isEqualToString:@"low_power_mode"]) {- resp = vp_handle_notify_command(msg);- } else {- resp = handle_command(msg);- }-- if (resp && !vp_write_message(fd, resp))- break;- }- }-- NSLog(@"vphoned: client disconnected%s",- should_restart ? " (restarting for update)" : "");- close(fd);- }- return should_restart;-}--// MARK: - Main--int main(int argc, char *argv[]) {- @autoreleasepool {- // Bootstrap: if running from install path and a cached update exists, exec- // it- const char *selfPath = self_executable_path();- NSLog(@"vphoned: starting (pid=%d, path=%s)", getpid(), selfPath ?: "?");--#if !LESS- if (selfPath && strcmp(selfPath, INSTALL_PATH) == 0 &&- access(CACHE_PATH, X_OK) == 0) {- NSLog(@"vphoned: found cached binary at %s, exec'ing", CACHE_PATH);- execv(CACHE_PATH, argv);- NSLog(@"vphoned: execv failed: %s — continuing with installed binary",- strerror(errno));- unlink(CACHE_PATH);- }-#endif-- if (!vp_hid_load())- return 1;- if (!vp_devmode_load())- NSLog(@"vphoned: XPC unavailable, devmode disabled");- vp_location_load();-- gClipboardAvailable = vp_clipboard_load();- gAppsAvailable = vp_apps_load();- vp_vcam_start();-- int sock = socket(AF_VSOCK, SOCK_STREAM, 0);- if (sock < 0) {- perror("vphoned: socket(AF_VSOCK)");- return 1;- }-- int one = 1;- setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));-- struct sockaddr_vm addr = {- .svm_len = sizeof(struct sockaddr_vm),- .svm_family = AF_VSOCK,- .svm_port = VPHONED_PORT,- .svm_cid = VMADDR_CID_ANY,- };-- if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {- perror("vphoned: bind");- close(sock);- return 1;- }- if (listen(sock, 2) < 0) {- perror("vphoned: listen");- close(sock);- return 1;- }-- NSLog(@"vphoned: listening on vsock port %d", VPHONED_PORT);-- for (;;) {- int client = accept(sock, NULL, NULL);- if (client < 0) {- perror("vphoned: accept");- sleep(1);- continue;- }- if (handle_client(client)) {- NSLog(@"vphoned: exiting for update restart");- close(sock);- return 0;- }- }- }-}diff --git a/scripts/vphoned/vphoned_accessibility.h b/scripts/vphoned/vphoned_accessibility.hdeleted file mode 100644index 37874fb0..00000000--- a/scripts/vphoned/vphoned_accessibility.h+++ /dev/null@@ -1,12 +0,0 @@-/*- * vphoned_accessibility — Accessibility tree query over vsock.- *- * Handles accessibility_tree. Currently a stub — requires XPC research- * to properly query the accessibility tree from a daemon context.- */--#pragma once-#import <Foundation/Foundation.h>--/// Handle an accessibility_tree command. Returns a response dict.-NSDictionary *vp_handle_accessibility_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_accessibility.m b/scripts/vphoned/vphoned_accessibility.mdeleted file mode 100644index d70affc6..00000000--- a/scripts/vphoned/vphoned_accessibility.m+++ /dev/null@@ -1,21 +0,0 @@-/*- * vphoned_accessibility — Accessibility tree query (stub).- *- * TODO: Implement proper accessibility tree retrieval.- * Options under investigation:- * 1. XPC to com.apple.accessibility.AXRuntime- * 2. AXUIElement private API (may not be available on iOS)- * 3. Dylib injection into SpringBoard- * 4. Direct UIAccessibility traversal via task_for_pid- */--#import "vphoned_accessibility.h"-#import "vphoned_protocol.h"--NSDictionary *vp_handle_accessibility_command(NSDictionary *msg) {- id reqId = msg[@"id"];-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"The accessibility tree is not available on this guest yet.";- return r;-}diff --git a/scripts/vphoned/vphoned_apps.h b/scripts/vphoned/vphoned_apps.hdeleted file mode 100644index 5272b9cc..00000000--- a/scripts/vphoned/vphoned_apps.h+++ /dev/null@@ -1,15 +0,0 @@-/*- * vphoned_apps — App lifecycle management over vsock.- *- * Handles app_list, app_launch, app_terminate, app_foreground using- * private APIs: LSApplicationWorkspace, FBSSystemService, SpringBoardServices.- */--#pragma once-#import <Foundation/Foundation.h>--/// Load private framework symbols for app management. Returns NO on failure.-BOOL vp_apps_load(void);--/// Handle an app command. Returns a response dict.-NSDictionary *vp_handle_apps_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_apps.m b/scripts/vphoned/vphoned_apps.mdeleted file mode 100644index 32b51cc2..00000000--- a/scripts/vphoned/vphoned_apps.m+++ /dev/null@@ -1,204 +0,0 @@-/*- * vphoned_apps — App lifecycle management via private APIs.- *- * Uses LSApplicationWorkspace (CoreServices) and FBSSystemService- * (FrontBoardServices).- */--#import "vphoned_apps.h"-#import "vphoned_protocol.h"-#include <dlfcn.h>-#include <objc/message.h>-#include <signal.h>-#include <unistd.h>--// MARK: - Private API Declarations--@interface LSApplicationProxy : NSObject-@property(readonly) NSString *bundleIdentifier;-@property(readonly) NSString *localizedName;-@property(readonly) NSString *shortVersionString;-@property(readonly) NSString *applicationType;-@property(readonly) NSURL *bundleURL;-@property(readonly) NSURL *dataContainerURL;-@end--@interface LSApplicationWorkspace : NSObject-+ (instancetype)defaultWorkspace;-- (NSArray *)allInstalledApplications;-- (BOOL)openApplicationWithBundleID:(NSString *)bundleID;-@end--// FBSSystemService loaded via dlsym-static Class gFBSSystemServiceClass = Nil;--static BOOL gAppsLoaded = NO;--BOOL vp_apps_load(void) {- // FrontBoardServices- void *fbs = dlopen("/System/Library/PrivateFrameworks/"- "FrontBoardServices.framework/FrontBoardServices",- RTLD_LAZY);- if (fbs) {- gFBSSystemServiceClass = NSClassFromString(@"FBSSystemService");- if (!gFBSSystemServiceClass) {- NSLog(@"vphoned: FBSSystemService class not found");- }- } else {- NSLog(@"vphoned: dlopen FrontBoardServices failed: %s", dlerror());- }-- // LSApplicationWorkspace is in CoreServices (already linked)- Class lsClass = NSClassFromString(@"LSApplicationWorkspace");- if (!lsClass) {- NSLog(@"vphoned: LSApplicationWorkspace class not found");- return NO;- }-- gAppsLoaded = YES;- NSLog(@"vphoned: apps loaded (FBS=%s)",- gFBSSystemServiceClass ? "yes" : "no");- return YES;-}--// MARK: - Helpers--static pid_t pid_for_app(NSString *bundleID) {- if (!gFBSSystemServiceClass)- return 0;- id service = ((id (*)(Class, SEL))objc_msgSend)(- gFBSSystemServiceClass, sel_registerName("sharedService"));- if (!service)- return 0;- return ((pid_t (*)(id, SEL, id))objc_msgSend)(- service, sel_registerName("pidForApplication:"), bundleID);-}--// MARK: - Command Handler--NSDictionary *vp_handle_apps_command(NSDictionary *msg) {- NSString *type = msg[@"t"];- id reqId = msg[@"id"];-- if (!gAppsLoaded) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"apps not available";- return r;- }-- // -- app_list --- if ([type isEqualToString:@"app_list"]) {- LSApplicationWorkspace *ws = [LSApplicationWorkspace defaultWorkspace];- NSArray *allApps = [ws allInstalledApplications];- NSString *filter = msg[@"filter"] ?: @"all";-- NSMutableArray *result = [NSMutableArray array];- for (LSApplicationProxy *proxy in allApps) {- NSString *appType = proxy.applicationType;- BOOL isSystem = [appType isEqualToString:@"System"];-- if ([filter isEqualToString:@"user"] && isSystem)- continue;- if ([filter isEqualToString:@"system"] && !isSystem)- continue;-- pid_t pid = pid_for_app(proxy.bundleIdentifier);-- if ([filter isEqualToString:@"running"] && pid <= 0)- continue;-- [result addObject:@{- @"bundle_id" : proxy.bundleIdentifier ?: @"",- @"name" : proxy.localizedName ?: @"",- @"version" : proxy.shortVersionString ?: @"",- @"type" : isSystem ? @"system" : @"user",- @"state" : pid > 0 ? @"running" : @"not_running",- @"pid" : @(pid > 0 ? pid : 0),- @"path" : proxy.bundleURL.path ?: @"",- @"data_container" : proxy.dataContainerURL.path ?: @"",- }];- }-- NSMutableDictionary *r = vp_make_response(@"app_list", reqId);- r[@"apps"] = result;- return r;- }-- // -- app_launch --- if ([type isEqualToString:@"app_launch"]) {- NSString *bundleID = msg[@"bundle_id"];- if (!bundleID) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing bundle_id";- return r;- }-- LSApplicationWorkspace *ws = [LSApplicationWorkspace defaultWorkspace];- NSString *url = msg[@"url"];-- // openURL:withOptions: is private and absent on some iOS versions; fall back to a plain launch.- SEL openURLSel = sel_registerName("openURL:withOptions:");- BOOL ok;- if (url && [ws respondsToSelector:openURLSel]) {- ok = ((BOOL (*)(id, SEL, id, id))objc_msgSend)(- ws, openURLSel, [NSURL URLWithString:url], nil);- } else {- ok = [ws openApplicationWithBundleID:bundleID];- }-- if (!ok) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"failed to launch %@", bundleID];- return r;- }-- // Brief wait for app to start- usleep(500000); // 500ms-- pid_t pid = pid_for_app(bundleID);- NSMutableDictionary *r = vp_make_response(@"app_launch", reqId);- r[@"ok"] = @YES;- r[@"pid"] = @(pid > 0 ? pid : 0);- return r;- }-- // -- app_terminate --- if ([type isEqualToString:@"app_terminate"]) {- NSString *bundleID = msg[@"bundle_id"];- if (!bundleID) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing bundle_id";- return r;- }-- if (gFBSSystemServiceClass) {- id service = ((id (*)(Class, SEL))objc_msgSend)(- gFBSSystemServiceClass, sel_registerName("sharedService"));- if (service) {- // terminateApplication:forReason:andReport:withDescription:- // reason 5 = user requested, report NO- ((void (*)(id, SEL, id, int, BOOL, id))objc_msgSend)(- service,- sel_registerName(- "terminateApplication:forReason:andReport:withDescription:"),- bundleID,- 5,- NO,- @"vphoned terminate request");- }- } else {- // Fallback: kill by PID- pid_t pid = pid_for_app(bundleID);- if (pid > 0)- kill(pid, SIGTERM);- }-- NSMutableDictionary *r = vp_make_response(@"app_terminate", reqId);- r[@"ok"] = @YES;- return r;- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"unknown apps command: %@", type];- return r;-}diff --git a/scripts/vphoned/vphoned_clipboard.h b/scripts/vphoned/vphoned_clipboard.hdeleted file mode 100644index 4006b19e..00000000--- a/scripts/vphoned/vphoned_clipboard.h+++ /dev/null@@ -1,16 +0,0 @@-/*- * vphoned_clipboard — Clipboard (pasteboard) read/write over vsock.- *- * Handles clipboard_get and clipboard_set using UIPasteboard via dlopen.- * Supports text and image (PNG) payloads with inline binary transfer.- */--#pragma once-#import <Foundation/Foundation.h>--/// Load UIKit symbols for clipboard access. Returns NO on failure.-BOOL vp_clipboard_load(void);--/// Handle a clipboard command. May write binary data inline for images.-/// Returns a response dict, or nil if the response was written inline.-NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_clipboard.m b/scripts/vphoned/vphoned_clipboard.mdeleted file mode 100644index 073b10e0..00000000--- a/scripts/vphoned/vphoned_clipboard.m+++ /dev/null@@ -1,168 +0,0 @@-/*- * vphoned_clipboard — Clipboard read/write via UIPasteboard (dlopen).- *- * UIPasteboard is loaded at runtime since vphoned is a daemon without UIKit.- * Uses objc_msgSend for all UIPasteboard interactions.- */--#import "vphoned_clipboard.h"-#import "vphoned_protocol.h"-#include <dlfcn.h>-#include <objc/message.h>-#include <unistd.h>--static BOOL gClipboardLoaded = NO;-static Class gPasteboardClass = Nil;-// UIImagePNGRepresentation-static NSData *(*pImagePNGRep)(id) = NULL;--BOOL vp_clipboard_load(void) {- void *h =- dlopen("/System/Library/Frameworks/UIKit.framework/UIKit", RTLD_LAZY);- if (!h) {- NSLog(@"vphoned: dlopen UIKit failed: %s", dlerror());- return NO;- }-- gPasteboardClass = NSClassFromString(@"UIPasteboard");- if (!gPasteboardClass) {- NSLog(@"vphoned: UIPasteboard class not found");- return NO;- }-- pImagePNGRep = dlsym(h, "UIImagePNGRepresentation");- if (!pImagePNGRep) {- NSLog(@"vphoned: UIImagePNGRepresentation not found (image support "- @"disabled)");- // Non-fatal: text clipboard still works- }-- gClipboardLoaded = YES;- NSLog(@"vphoned: clipboard loaded (UIKit)");- return YES;-}--static id get_general_pasteboard(void) {- return ((id (*)(Class, SEL))objc_msgSend)(- gPasteboardClass, sel_registerName("generalPasteboard"));-}--NSDictionary *vp_handle_clipboard_command(int fd, NSDictionary *msg) {- NSString *type = msg[@"t"];- id reqId = msg[@"id"];-- if (!gClipboardLoaded) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"The clipboard is unavailable on the guest.";- return r;- }-- // -- clipboard_get --- if ([type isEqualToString:@"clipboard_get"]) {- id pb = get_general_pasteboard();- if (!pb) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"The clipboard is unavailable on the guest. Try again.";- return r;- }-- NSMutableDictionary *r = vp_make_response(@"clipboard_get", reqId);-- // changeCount- NSInteger changeCount = ((NSInteger (*)(id, SEL))objc_msgSend)(- pb, sel_registerName("changeCount"));- r[@"change_count"] = @(changeCount);-- // pasteboardTypes- NSArray *types = ((id (*)(id, SEL))objc_msgSend)(- pb, sel_registerName("pasteboardTypes"));- r[@"types"] = types ?: @[];-- // string- NSString *str =- ((id (*)(id, SEL))objc_msgSend)(pb, sel_registerName("string"));- if (str)- r[@"text"] = str;-- // image- id image = ((id (*)(id, SEL))objc_msgSend)(pb, sel_registerName("image"));- NSData *pngData = nil;- if (image && pImagePNGRep) {- pngData = pImagePNGRep(image);- }-- if (pngData && pngData.length > 0) {- r[@"has_image"] = @YES;- r[@"image_size"] = @(pngData.length);-- // Write JSON header, then binary PNG data- if (!vp_write_message(fd, r))- return nil;- vp_write_fully(fd, pngData.bytes, pngData.length);- return nil; // Already written inline- } else {- r[@"has_image"] = @NO;- return r;- }- }-- // -- clipboard_set --- if ([type isEqualToString:@"clipboard_set"]) {- id pb = get_general_pasteboard();- if (!pb) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"The clipboard is unavailable on the guest. Try again.";- return r;- }-- NSString *setType = msg[@"type"];- if ([setType isEqualToString:@"image"]) {- // Image mode: read binary payload- NSUInteger size = [msg[@"size"] unsignedIntegerValue];- if (size == 0 || size > 50 * 1024 * 1024) {- if (size > 0)- vp_drain(fd, size);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"This image cannot be copied to the clipboard.";- return r;- }-- NSMutableData *imgData = [NSMutableData dataWithLength:size];- if (!vp_read_fully(fd, imgData.mutableBytes, size)) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"Unable to read the image. Try again.";- return r;- }-- // Create UIImage from PNG data and set on pasteboard- Class uiImageClass = NSClassFromString(@"UIImage");- if (uiImageClass) {- id image = ((id (*)(Class, SEL, id))objc_msgSend)(- uiImageClass, sel_registerName("imageWithData:"), imgData);- if (image) {- ((void (*)(id, SEL, id))objc_msgSend)(- pb, sel_registerName("setImage:"), image);- }- }- } else {- // Text mode- NSString *text = msg[@"text"];- if (text) {- ((void (*)(id, SEL, id))objc_msgSend)(- pb, sel_registerName("setString:"), text);- }- }-- NSInteger changeCount = ((NSInteger (*)(id, SEL))objc_msgSend)(- pb, sel_registerName("changeCount"));- NSMutableDictionary *r = vp_make_response(@"clipboard_set", reqId);- r[@"ok"] = @YES;- r[@"change_count"] = @(changeCount);- return r;- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] =- [NSString stringWithFormat:@"unknown clipboard command: %@", type];- return r;-}diff --git a/scripts/vphoned/vphoned_devmode.h b/scripts/vphoned/vphoned_devmode.hdeleted file mode 100644index ad898485..00000000--- a/scripts/vphoned/vphoned_devmode.h+++ /dev/null@@ -1,22 +0,0 @@-/*- * vphoned_devmode — Developer mode control via AMFI XPC.- *- * Talks to com.apple.amfi.xpc to query / arm developer mode.- * Reference: TrollStore RootHelper/devmode.m- * Requires entitlement: com.apple.private.amfi.developer-mode-control- */--#pragma once-#import <Foundation/Foundation.h>--/// Load XPC/CoreFoundation symbols. Returns NO on failure (devmode disabled).-BOOL vp_devmode_load(void);--/// Whether devmode XPC is available (load succeeded).-BOOL vp_devmode_available(void);--/// Query current developer mode status.-BOOL vp_devmode_status(void);--/// Arm developer mode. Returns YES on success. Sets *alreadyEnabled if already on.-BOOL vp_devmode_arm(BOOL *alreadyEnabled);diff --git a/scripts/vphoned/vphoned_devmode.m b/scripts/vphoned/vphoned_devmode.mdeleted file mode 100644index 0df931d9..00000000--- a/scripts/vphoned/vphoned_devmode.m+++ /dev/null@@ -1,107 +0,0 @@-#import "vphoned_devmode.h"-#include <dlfcn.h>--// XPC functions resolved via dlsym to avoid iOS SDK availability-// guards (xpc_connection_create_mach_service is marked unavailable-// on iOS but works at runtime with the right entitlements).--typedef void *xpc_conn_t; // opaque, avoids typedef conflict with SDK-typedef void *xpc_obj_t;--static xpc_conn_t (*pXpcCreateMach)(const char *, dispatch_queue_t, uint64_t);-static void (*pXpcSetHandler)(xpc_conn_t, void (^)(xpc_obj_t));-static void (*pXpcResume)(xpc_conn_t);-static void (*pXpcCancel)(xpc_conn_t);-static xpc_obj_t (*pXpcSendSync)(xpc_conn_t, xpc_obj_t);-static xpc_obj_t (*pXpcDictGet)(xpc_obj_t, const char *);-static xpc_obj_t (*pCFToXPC)(CFTypeRef);-static CFTypeRef (*pXPCToCF)(xpc_obj_t);--static BOOL gXPCLoaded = NO;--BOOL vp_devmode_load(void) {- void *libxpc = dlopen("/usr/lib/system/libxpc.dylib", RTLD_NOW);- if (!libxpc) { NSLog(@"vphoned: dlopen libxpc failed"); return NO; }-- void *libcf = dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", RTLD_NOW);- if (!libcf) { NSLog(@"vphoned: dlopen CoreFoundation failed"); return NO; }-- pXpcCreateMach = dlsym(libxpc, "xpc_connection_create_mach_service");- pXpcSetHandler = dlsym(libxpc, "xpc_connection_set_event_handler");- pXpcResume = dlsym(libxpc, "xpc_connection_resume");- pXpcCancel = dlsym(libxpc, "xpc_connection_cancel");- pXpcSendSync = dlsym(libxpc, "xpc_connection_send_message_with_reply_sync");- pXpcDictGet = dlsym(libxpc, "xpc_dictionary_get_value");- pCFToXPC = dlsym(libcf, "_CFXPCCreateXPCMessageWithCFObject");- pXPCToCF = dlsym(libcf, "_CFXPCCreateCFObjectFromXPCMessage");-- if (!pXpcCreateMach || !pXpcSetHandler || !pXpcResume || !pXpcCancel ||- !pXpcSendSync || !pXpcDictGet || !pCFToXPC || !pXPCToCF) {- NSLog(@"vphoned: missing XPC/CF symbols");- return NO;- }-- NSLog(@"vphoned: XPC loaded");- gXPCLoaded = YES;- return YES;-}--BOOL vp_devmode_available(void) {- return gXPCLoaded;-}--// MARK: - AMFI XPC--typedef enum {- kAMFIActionArm = 0, // arm developer mode (prompts on next reboot)- kAMFIActionDisable = 1, // disable developer mode immediately- kAMFIActionStatus = 2, // query: {success, status, armed}-} AMFIXPCAction;--static NSDictionary *amfi_send(AMFIXPCAction action) {- xpc_conn_t conn = pXpcCreateMach("com.apple.amfi.xpc", NULL, 0);- if (!conn) {- NSLog(@"vphoned: amfi xpc connection failed");- return nil;- }- pXpcSetHandler(conn, ^(xpc_obj_t event) {});- pXpcResume(conn);-- xpc_obj_t msg = pCFToXPC((__bridge CFDictionaryRef)@{@"action": @(action)});- xpc_obj_t reply = pXpcSendSync(conn, msg);- pXpcCancel(conn);- if (!reply) {- NSLog(@"vphoned: amfi xpc no reply");- return nil;- }-- xpc_obj_t cfReply = pXpcDictGet(reply, "cfreply");- if (!cfReply) {- NSLog(@"vphoned: amfi xpc no cfreply");- return nil;- }-- NSDictionary *dict = (__bridge_transfer NSDictionary *)pXPCToCF(cfReply);- NSLog(@"vphoned: amfi reply: %@", dict);- return dict;-}--BOOL vp_devmode_status(void) {- NSDictionary *reply = amfi_send(kAMFIActionStatus);- if (!reply) return NO;- NSNumber *success = reply[@"success"];- if (!success || ![success boolValue]) return NO;- NSNumber *status = reply[@"status"];- return [status boolValue];-}--BOOL vp_devmode_arm(BOOL *alreadyEnabled) {- BOOL enabled = vp_devmode_status();- if (alreadyEnabled) *alreadyEnabled = enabled;- if (enabled) return YES;-- NSDictionary *reply = amfi_send(kAMFIActionArm);- if (!reply) return NO;- NSNumber *success = reply[@"success"];- return success && [success boolValue];-}diff --git a/scripts/vphoned/vphoned_files.h b/scripts/vphoned/vphoned_files.hdeleted file mode 100644index 87581476..00000000--- a/scripts/vphoned/vphoned_files.h+++ /dev/null@@ -1,13 +0,0 @@-/*- * vphoned_files — Remote file operations over vsock.- *- * Handles file_list, file_get, file_put, file_mkdir, file_delete, file_rename.- * file_get and file_put perform inline binary I/O on the socket.- */--#pragma once-#import <Foundation/Foundation.h>--/// Handle a file command. Returns a response dict, or nil if the response-/// was already written inline (e.g. file_get with streaming data).-NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_files.m b/scripts/vphoned/vphoned_files.mdeleted file mode 100644index 76178b64..00000000--- a/scripts/vphoned/vphoned_files.m+++ /dev/null@@ -1,233 +0,0 @@-#import "vphoned_files.h"-#import "vphoned_protocol.h"-#include <sys/stat.h>-#include <unistd.h>--static NSMutableDictionary *vp_missing_path_error(id reqId) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing path";- return r;-}--NSDictionary *vp_handle_file_command(int fd, NSDictionary *msg) {- NSString *type = msg[@"t"];- id reqId = msg[@"id"];-- // -- file_list: list directory contents --- if ([type isEqualToString:@"file_list"]) {- NSString *path = msg[@"path"];- if (!path) return vp_missing_path_error(reqId);-- NSFileManager *fm = [NSFileManager defaultManager];- NSError *err = nil;- NSArray *contents = [fm contentsOfDirectoryAtPath:path error:&err];- if (!contents) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = err.localizedDescription ?: @"list failed";- return r;- }-- NSMutableArray *entries = [NSMutableArray arrayWithCapacity:contents.count];- for (NSString *name in contents) {- NSString *full = [path stringByAppendingPathComponent:name];-- struct stat st;- if (lstat([full fileSystemRepresentation], &st) != 0) continue;-- NSString *typeStr = @"file";- if (S_ISDIR(st.st_mode)) typeStr = @"dir";- else if (S_ISLNK(st.st_mode)) typeStr = @"link";-- BOOL linkTargetsDirectory = NO;- if (S_ISLNK(st.st_mode)) {- struct stat resolved;- if (stat([full fileSystemRepresentation], &resolved) == 0) {- linkTargetsDirectory = S_ISDIR(resolved.st_mode);- }- }-- NSNumber *size = @(st.st_size);- NSDate *mtime = [NSDate dateWithTimeIntervalSince1970:st.st_mtimespec.tv_sec];- NSNumber *posixPerms = @((unsigned long)st.st_mode & 0777);-- [entries addObject:@{- @"name": name,- @"type": typeStr,- @"link_target_dir": @(linkTargetsDirectory),- @"size": size,- @"perm": [NSString stringWithFormat:@"%lo", [posixPerms unsignedLongValue]],- @"mtime": @(mtime ? [mtime timeIntervalSince1970] : 0),- }];- }-- NSMutableDictionary *r = vp_make_response(@"ok", reqId);- r[@"entries"] = entries;- return r;- }-- // -- file_get: download file from guest to host --- if ([type isEqualToString:@"file_get"]) {- NSString *path = msg[@"path"];- if (!path) return vp_missing_path_error(reqId);-- int fileFd = open([path fileSystemRepresentation], O_RDONLY);- if (fileFd < 0) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"Unable to open the file (%s).", strerror(errno)];- return r;- }-- struct stat st;- if (fstat(fileFd, &st) != 0) {- close(fileFd);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"Unable to read the file (%s).", strerror(errno)];- return r;- }- if (!S_ISREG(st.st_mode)) {- close(fileFd);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"Only files can be downloaded. This path is not a file.";- return r;- }-- // Send header with file size- NSMutableDictionary *header = vp_make_response(@"file_data", reqId);- header[@"size"] = @((unsigned long long)st.st_size);- if (!vp_write_message(fd, header)) {- close(fileFd);- return nil;- }-- // Stream file data in chunks- uint8_t buf[32768];- ssize_t n;- while ((n = read(fileFd, buf, sizeof(buf))) > 0) {- if (!vp_write_fully(fd, buf, (size_t)n)) {- NSLog(@"vphoned: file_get write failed for %@", path);- close(fileFd);- return nil;- }- }- close(fileFd);- return nil; // Response already written inline- }-- // -- file_put: upload file from host to guest --- if ([type isEqualToString:@"file_put"]) {- NSString *path = msg[@"path"];- NSUInteger size = [msg[@"size"] unsignedIntegerValue];- NSString *perm = msg[@"perm"];-- if (!path) {- // Must still drain the raw bytes to keep protocol in sync- if (size > 0) vp_drain(fd, size);- return vp_missing_path_error(reqId);- }-- // Create parent directories if needed- NSString *parent = [path stringByDeletingLastPathComponent];- [[NSFileManager defaultManager] createDirectoryAtPath:parent- withIntermediateDirectories:YES- attributes:nil- error:nil];-- // Write to temp file, then rename (atomic)- char tmp_path[PATH_MAX];- snprintf(tmp_path, sizeof(tmp_path), "%s.XXXXXX", [path fileSystemRepresentation]);- int tmp_fd = mkstemp(tmp_path);- if (tmp_fd < 0) {- vp_drain(fd, size);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"Unable to create a temporary file (%s).", strerror(errno)];- return r;- }-- uint8_t buf[32768];- NSUInteger remaining = size;- BOOL ok = YES;- while (remaining > 0) {- size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf);- if (!vp_read_fully(fd, buf, chunk)) { ok = NO; break; }- if (write(tmp_fd, buf, chunk) != (ssize_t)chunk) { ok = NO; break; }- remaining -= chunk;- }- close(tmp_fd);-- if (!ok) {- unlink(tmp_path);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"The file transfer was interrupted. Try again.";- return r;- }-- // Set permissions- if (perm) {- unsigned long mode = strtoul([perm UTF8String], NULL, 8);- chmod(tmp_path, (mode_t)mode);- } else {- chmod(tmp_path, 0644);- }-- if (rename(tmp_path, [path fileSystemRepresentation]) != 0) {- unlink(tmp_path);- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"Unable to save the file (%s).", strerror(errno)];- return r;- }-- NSLog(@"vphoned: file_put %@ (%lu bytes)", path, (unsigned long)size);- return vp_make_response(@"ok", reqId);- }-- // -- file_mkdir --- if ([type isEqualToString:@"file_mkdir"]) {- NSString *path = msg[@"path"];- if (!path) return vp_missing_path_error(reqId);- NSError *err = nil;- if (![[NSFileManager defaultManager] createDirectoryAtPath:path- withIntermediateDirectories:YES- attributes:nil- error:&err]) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = err.localizedDescription ?: @"mkdir failed";- return r;- }- return vp_make_response(@"ok", reqId);- }-- // -- file_delete --- if ([type isEqualToString:@"file_delete"]) {- NSString *path = msg[@"path"];- if (!path) return vp_missing_path_error(reqId);- NSError *err = nil;- if (![[NSFileManager defaultManager] removeItemAtPath:path error:&err]) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = err.localizedDescription ?: @"delete failed";- return r;- }- return vp_make_response(@"ok", reqId);- }-- // -- file_rename --- if ([type isEqualToString:@"file_rename"]) {- NSString *from = msg[@"from"];- NSString *to = msg[@"to"];- if (!from || !to) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing from/to";- return r;- }- NSError *err = nil;- if (![[NSFileManager defaultManager] moveItemAtPath:from toPath:to error:&err]) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = err.localizedDescription ?: @"rename failed";- return r;- }- return vp_make_response(@"ok", reqId);- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"unknown file command: %@", type];- return r;-}diff --git a/scripts/vphoned/vphoned_hid.h b/scripts/vphoned/vphoned_hid.hdeleted file mode 100644index 093e4bf7..00000000--- a/scripts/vphoned/vphoned_hid.h+++ /dev/null@@ -1,24 +0,0 @@-/*- * vphoned_hid — HID event injection via IOKit private API.- *- * Matches TrollVNC's STHIDEventGenerator approach: create an- * IOHIDEventSystemClient, fabricate keyboard events, and dispatch.- */--#pragma once-#import <Foundation/Foundation.h>--/// Load IOKit symbols and create HID event client. Returns NO on failure.-BOOL vp_hid_load(void);--/// Send a full key press (down + 100ms delay + up).-void vp_hid_press(uint32_t page, uint32_t usage);--/// Send a single key down or key up event.-void vp_hid_key(uint32_t page, uint32_t usage, BOOL down);--/// Inject a single-finger digitizer touch event.-/// phase: 0 = down, 1 = move, 3 = up. x/y are normalized 0..1 with the-/// origin at the top-left. Used for iOS 18 bases where the VZ USB touchscreen-/// dext produces no digitizer events on the 26.x kernel.-void vp_hid_touch(int phase, double x, double y);diff --git a/scripts/vphoned/vphoned_hid.m b/scripts/vphoned/vphoned_hid.mdeleted file mode 100644index d0f6f5dd..00000000--- a/scripts/vphoned/vphoned_hid.m+++ /dev/null@@ -1,141 +0,0 @@-#import "vphoned_hid.h"-#include <dlfcn.h>-#include <mach/mach_time.h>-#include <unistd.h>--typedef void *IOHIDEventSystemClientRef;-typedef void *IOHIDEventRef;-typedef double IOHIDFloat;--static IOHIDEventSystemClientRef (*pCreate)(CFAllocatorRef);-static IOHIDEventRef (*pKeyboard)(CFAllocatorRef, uint64_t,- uint32_t, uint32_t, int, int);-static void (*pSetSender)(IOHIDEventRef, uint64_t);-static void (*pDispatch)(IOHIDEventSystemClientRef, IOHIDEventRef);--// Digitizer (touch) event symbols — resolved lazily; touch is a no-op if absent.-static IOHIDEventRef (*pDigitizer)(CFAllocatorRef, uint64_t, uint32_t, uint32_t,- uint32_t, uint32_t, uint32_t, IOHIDFloat,- IOHIDFloat, IOHIDFloat, IOHIDFloat, IOHIDFloat,- boolean_t, boolean_t, uint32_t);-static IOHIDEventRef (*pFinger)(CFAllocatorRef, uint64_t, uint32_t, uint32_t,- uint32_t, IOHIDFloat, IOHIDFloat, IOHIDFloat,- IOHIDFloat, IOHIDFloat, boolean_t, boolean_t, uint32_t);-static void (*pAppend)(IOHIDEventRef, IOHIDEventRef, uint32_t);-static void (*pSetInt)(IOHIDEventRef, uint32_t, int);--static IOHIDEventSystemClientRef gClient;-static dispatch_queue_t gHIDQueue;--// Digitizer event-mask bits and transducer types (IOHIDEventTypes.h).-#define VP_DIG_TOUCH 0x00000002u-#define VP_DIG_POSITION 0x00000004u-#define VP_DIG_IDENTITY 0x00000020u-#define VP_TRANSDUCER_HAND 1-#define VP_TRANSDUCER_FINGER 2-// kIOHIDEventFieldDigitizerIsDisplayIntegrated: (kIOHIDEventTypeDigitizer<<16)|offset.-#define VP_FIELD_IS_DISPLAY_INTEGRATED ((((uint32_t)11) << 16) | 25)--BOOL vp_hid_load(void) {- void *h = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);- if (!h) { NSLog(@"vphoned: dlopen IOKit failed"); return NO; }-- pCreate = dlsym(h, "IOHIDEventSystemClientCreate");- pKeyboard = dlsym(h, "IOHIDEventCreateKeyboardEvent");- pSetSender = dlsym(h, "IOHIDEventSetSenderID");- pDispatch = dlsym(h, "IOHIDEventSystemClientDispatchEvent");-- pDigitizer = dlsym(h, "IOHIDEventCreateDigitizerEvent");- pFinger = dlsym(h, "IOHIDEventCreateDigitizerFingerEvent");- pAppend = dlsym(h, "IOHIDEventAppendEvent");- pSetInt = dlsym(h, "IOHIDEventSetIntegerValue");-- if (!pCreate || !pKeyboard || !pSetSender || !pDispatch) {- NSLog(@"vphoned: missing IOKit symbols");- return NO;- }- if (!pDigitizer || !pFinger || !pAppend || !pSetInt)- NSLog(@"vphoned: digitizer symbols missing, touch injection disabled");-- gClient = pCreate(kCFAllocatorDefault);- if (!gClient) { NSLog(@"vphoned: IOHIDEventSystemClientCreate returned NULL"); return NO; }-- dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(- DISPATCH_QUEUE_SERIAL,- QOS_CLASS_USER_INTERACTIVE,- 0);- gHIDQueue = dispatch_queue_create("com.vphone.vphoned.hid", attr);-- NSLog(@"vphoned: IOKit loaded");- return YES;-}--static void send_hid_event(IOHIDEventRef event) {- IOHIDEventRef strong = (IOHIDEventRef)CFRetain(event);- dispatch_async(gHIDQueue, ^{- pSetSender(strong, 0x8000000817319372);- pDispatch(gClient, strong);- CFRelease(strong);- });-}--void vp_hid_press(uint32_t page, uint32_t usage) {- IOHIDEventRef down = pKeyboard(kCFAllocatorDefault, mach_absolute_time(),- page, usage, 1, 0);- if (!down) return;- send_hid_event(down);- CFRelease(down);-- usleep(100000);-- IOHIDEventRef up = pKeyboard(kCFAllocatorDefault, mach_absolute_time(),- page, usage, 0, 0);- if (!up) return;- send_hid_event(up);- CFRelease(up);-}--void vp_hid_key(uint32_t page, uint32_t usage, BOOL down) {- IOHIDEventRef ev = pKeyboard(kCFAllocatorDefault, mach_absolute_time(),- page, usage, down ? 1 : 0, 0);- if (ev) { send_hid_event(ev); CFRelease(ev); }-}--// Build a display-integrated hand digitizer event carrying one finger and-// dispatch it. Mirrors WebKit's HIDEventGenerator single-touch path.-static void dispatch_digitizer(double x, double y, boolean_t range,- boolean_t touch, uint32_t mask) {- if (!pDigitizer || !pFinger || !pAppend || !pSetInt) return;-- uint64_t ts = mach_absolute_time();- IOHIDEventRef parent = pDigitizer(kCFAllocatorDefault, ts, VP_TRANSDUCER_HAND,- 0, 0, mask, 0, x, y, 0, 0, 0, range, touch, 0);- if (!parent) return;- pSetInt(parent, VP_FIELD_IS_DISPLAY_INTEGRATED, 1);-- IOHIDEventRef finger = pFinger(kCFAllocatorDefault, ts, 1, VP_TRANSDUCER_FINGER,- mask, x, y, 0, 0, 0, range, touch, 0);- if (finger) {- pSetInt(finger, VP_FIELD_IS_DISPLAY_INTEGRATED, 1);- pAppend(parent, finger, 0);- CFRelease(finger);- }-- send_hid_event(parent);- CFRelease(parent);-}--void vp_hid_touch(int phase, double x, double y) {- switch (phase) {- case 0: // down- dispatch_digitizer(x, y, 1, 1, VP_DIG_TOUCH | VP_DIG_IDENTITY);- break;- case 1: // move- dispatch_digitizer(x, y, 1, 1, VP_DIG_POSITION);- break;- case 3: // up- default:- dispatch_digitizer(x, y, 0, 0, VP_DIG_TOUCH | VP_DIG_IDENTITY);- break;- }-}diff --git a/scripts/vphoned/vphoned_install.m b/scripts/vphoned/vphoned_install.mindex 573af592..2296faf0 100644--- a/scripts/vphoned/vphoned_install.m+++ b/scripts/vphoned/vphoned_install.m@@ -12,7 +12,7 @@#include <sys/wait.h>#include <unistd.h>-#import "vphoned_protocol.h"+#import "vphoned_response.h"typedef struct __SecCode const *SecStaticCodeRef;typedef CF_OPTIONS(uint32_t, SecCSFlags) {diff --git a/scripts/vphoned/vphoned_keychain.m b/scripts/vphoned/vphoned_keychain.mindex 2a97130b..9265bf68 100644--- a/scripts/vphoned/vphoned_keychain.m+++ b/scripts/vphoned/vphoned_keychain.m@@ -7,7 +7,7 @@*/#import "vphoned_keychain.h"-#import "vphoned_protocol.h"+#import "vphoned_response.h"#import <Security/Security.h>#import <sqlite3.h>diff --git a/scripts/vphoned/vphoned_location.h b/scripts/vphoned/vphoned_location.hdeleted file mode 100644index 62fb7ff7..00000000--- a/scripts/vphoned/vphoned_location.h+++ /dev/null@@ -1,24 +0,0 @@-/*- * vphoned_location — CoreLocation simulation via CLSimulationManager.- *- * Uses private CLSimulationManager API to inject simulated GPS coordinates- * into the guest. Probes available selectors at runtime since the API- * varies across iOS versions.- */--#pragma once-#import <Foundation/Foundation.h>--/// Load CoreLocation and probe CLSimulationManager selectors. Returns NO on failure.-BOOL vp_location_load(void);--/// Whether location simulation is available (load succeeded).-BOOL vp_location_available(void);--/// Simulate a GPS location update.-void vp_location_simulate(double lat, double lon, double alt,- double hacc, double vacc,- double speed, double course);--/// Clear simulated location.-void vp_location_clear(void);diff --git a/scripts/vphoned/vphoned_location.m b/scripts/vphoned/vphoned_location.mdeleted file mode 100644index e27bf84e..00000000--- a/scripts/vphoned/vphoned_location.m+++ /dev/null@@ -1,164 +0,0 @@-#import "vphoned_location.h"-#include <dlfcn.h>-#include <objc/runtime.h>-#include <objc/message.h>--static id gSimManager = nil;-static SEL gSetLocationSel = NULL;-static SEL gClearLocationsSel = NULL;-static SEL gFlushSel = NULL;-static SEL gStartSimSel = NULL;-static BOOL gLocationLoaded = NO;--BOOL vp_location_load(void) {- void *h = dlopen("/System/Library/Frameworks/CoreLocation.framework/CoreLocation", RTLD_NOW);- if (!h) { NSLog(@"vphoned: dlopen CoreLocation failed"); return NO; }-- Class cls = NSClassFromString(@"CLSimulationManager");- if (!cls) { NSLog(@"vphoned: CLSimulationManager not found"); return NO; }-- gSimManager = [[cls alloc] init];- if (!gSimManager) { NSLog(@"vphoned: CLSimulationManager alloc/init failed"); return NO; }-- // Probe available selectors for setting location- SEL candidates[] = {- NSSelectorFromString(@"setSimulatedLocation:"),- NSSelectorFromString(@"appendSimulatedLocation:"),- NSSelectorFromString(@"setLocation:"),- };- for (int i = 0; i < 3; i++) {- if ([gSimManager respondsToSelector:candidates[i]]) {- gSetLocationSel = candidates[i];- break;- }- }- if (!gSetLocationSel) {- NSLog(@"vphoned: no set-location selector found, dumping methods:");- unsigned int count = 0;- Method *methods = class_copyMethodList([gSimManager class], &count);- for (unsigned int i = 0; i < count; i++) {- NSLog(@" %s", sel_getName(method_getName(methods[i])));- }- free(methods);- return NO;- }-- // Probe clear selector- SEL clearCandidates[] = {- NSSelectorFromString(@"clearSimulatedLocations"),- NSSelectorFromString(@"stopLocationSimulation"),- };- for (int i = 0; i < 2; i++) {- if ([gSimManager respondsToSelector:clearCandidates[i]]) {- gClearLocationsSel = clearCandidates[i];- break;- }- }-- // Probe flush selector- SEL flushCandidates[] = {- NSSelectorFromString(@"flush"),- NSSelectorFromString(@"flushSimulatedLocations"),- };- for (int i = 0; i < 2; i++) {- if ([gSimManager respondsToSelector:flushCandidates[i]]) {- gFlushSel = flushCandidates[i];- break;- }- }-- // Probe startLocationSimulation selector- SEL startCandidates[] = {- NSSelectorFromString(@"startLocationSimulation"),- NSSelectorFromString(@"startSimulation"),- };- for (int i = 0; i < 2; i++) {- if ([gSimManager respondsToSelector:startCandidates[i]]) {- gStartSimSel = startCandidates[i];- break;- }- }-- // Start simulation session if available- if (gStartSimSel) {-#pragma clang diagnostic push-#pragma clang diagnostic ignored "-Warc-performSelector-leaks"- [gSimManager performSelector:gStartSimSel];-#pragma clang diagnostic pop- }-- NSLog(@"vphoned: CoreLocation simulation loaded (set=%s, clear=%s, flush=%s, start=%s)",- sel_getName(gSetLocationSel),- gClearLocationsSel ? sel_getName(gClearLocationsSel) : "(none)",- gFlushSel ? sel_getName(gFlushSel) : "(none)",- gStartSimSel ? sel_getName(gStartSimSel) : "(none)");- gLocationLoaded = YES;- return YES;-}--BOOL vp_location_available(void) {- return gLocationLoaded;-}--void vp_location_simulate(double lat, double lon, double alt,- double hacc, double vacc,- double speed, double course) {- if (!gLocationLoaded || !gSimManager || !gSetLocationSel) return;-- @try {- typedef struct { double latitude; double longitude; } CLCoord2D;- CLCoord2D coord = {lat, lon};-- Class locClass = NSClassFromString(@"CLLocation");- id locInst = [locClass alloc];-- // Try full init including speed and course- SEL initSel = NSSelectorFromString(- @"initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:course:speed:timestamp:");- if (![locInst respondsToSelector:initSel]) {- // Fallback to simpler init- initSel = NSSelectorFromString(- @"initWithCoordinate:altitude:horizontalAccuracy:verticalAccuracy:timestamp:");- typedef id (*InitFunc5)(id, SEL, CLCoord2D, double, double, double, id);- id location = ((InitFunc5)objc_msgSend)(locInst, initSel, coord, alt, hacc, vacc, [NSDate date]);--#pragma clang diagnostic push-#pragma clang diagnostic ignored "-Warc-performSelector-leaks"- [gSimManager performSelector:gSetLocationSel withObject:location];- if (gFlushSel) [gSimManager performSelector:gFlushSel];-#pragma clang diagnostic pop-- NSLog(@"vphoned: simulate_location lat=%.6f lon=%.6f (fallback init)", lat, lon);- return;- }-- typedef id (*InitFunc7)(id, SEL, CLCoord2D, double, double, double, double, double, id);- id location = ((InitFunc7)objc_msgSend)(locInst, initSel, coord, alt, hacc, vacc, course, speed, [NSDate date]);--#pragma clang diagnostic push-#pragma clang diagnostic ignored "-Warc-performSelector-leaks"- [gSimManager performSelector:gSetLocationSel withObject:location];- if (gFlushSel) [gSimManager performSelector:gFlushSel];-#pragma clang diagnostic pop-- NSLog(@"vphoned: simulate_location lat=%.6f lon=%.6f alt=%.1f spd=%.1f crs=%.1f",- lat, lon, alt, speed, course);- } @catch (NSException *e) {- NSLog(@"vphoned: simulate_location exception: %@", e);- }-}--void vp_location_clear(void) {- if (!gLocationLoaded || !gSimManager) return;- @try {- if (gClearLocationsSel) {-#pragma clang diagnostic push-#pragma clang diagnostic ignored "-Warc-performSelector-leaks"- [gSimManager performSelector:gClearLocationsSel];-#pragma clang diagnostic pop- NSLog(@"vphoned: cleared simulated location");- }- } @catch (NSException *e) {- NSLog(@"vphoned: clear_simulated_location exception: %@", e);- }-}diff --git a/scripts/vphoned/vphoned_native.m b/scripts/vphoned/vphoned_native.mnew file mode 100644index 00000000..d7692042--- /dev/null+++ b/scripts/vphoned/vphoned_native.m@@ -0,0 +1,36 @@+#import "include/VphonedNative.h"+#import "vphoned_install.h"+#import "vphoned_keychain.h"+#import <CommonCrypto/CommonDigest.h>+#include <mach-o/dyld.h>+#include <unistd.h>++NSDictionary *vp_native_api_command(NSDictionary *message) {+ NSString *type = message[@"t"];+ if ([type isEqualToString:@"ipa_install"]) return vp_handle_custom_install(message);+ if ([type isEqualToString:@"keychain_list"] || [type isEqualToString:@"keychain_add"])+ return vp_handle_keychain_command(message);+ return @{@"t": @"err", @"msg": @"Unknown native operation"};+}++void vp_native_bootstrap_cached_binary(void) {+ static const char *cache = "/var/root/Library/Caches/vphoned";+ // Pre-HTTP daemon builds also used this cache path. Their binaries lack+ // the marker, so a new firmware daemon must not exec an old protocol.+ static const char *marker = "/var/root/Library/Caches/vphoned.api-v1";+ if (access(cache, X_OK) != 0 || access(marker, R_OK) != 0) return;+ NSData *binary = [NSData dataWithContentsOfFile:@(cache) options:NSDataReadingMappedIfSafe error:nil];+ NSString *expected = [NSString stringWithContentsOfFile:@(marker) encoding:NSUTF8StringEncoding error:nil];+ if (!binary || expected.length != CC_SHA256_DIGEST_LENGTH * 2) return;+ unsigned char digest[CC_SHA256_DIGEST_LENGTH];+ CC_SHA256(binary.bytes, (CC_LONG)binary.length, digest);+ NSMutableString *actual = [NSMutableString string];+ for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) [actual appendFormat:@"%02x", digest[i]];+ if (![actual isEqualToString:expected]) return;+ char current[4096];+ uint32_t size = sizeof(current);+ if (_NSGetExecutablePath(current, &size) != 0 || strcmp(current, cache) == 0) return;+ char *const arguments[] = {(char *)cache, NULL};+ execv(cache, arguments);+ NSLog(@"vphoned: cached binary launch failed: %s", strerror(errno));+}diff --git a/scripts/vphoned/vphoned_notify.h b/scripts/vphoned/vphoned_notify.hdeleted file mode 100644index 4fce53d4..00000000--- a/scripts/vphoned/vphoned_notify.h+++ /dev/null@@ -1,4 +0,0 @@-#pragma once-#import <Foundation/Foundation.h>--NSDictionary *vp_handle_notify_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_notify.m b/scripts/vphoned/vphoned_notify.mdeleted file mode 100644index 76223b1a..00000000--- a/scripts/vphoned/vphoned_notify.m+++ /dev/null@@ -1,32 +0,0 @@-/*- * vphoned_notify — Low power mode state sync.- *- * Sets LPM state via notify_set_state("com.apple.system.lowpowermode") + notify_post.- * All registrations for a notification name share one state value, so this- * updates what NSProcessInfo and SpringBoard read via notify_get_state —- * mirroring what powerd does internally when the user toggles Low Power Mode.- */--#import "vphoned_notify.h"-#import "vphoned_protocol.h"-#include <notify.h>--NSDictionary *vp_handle_notify_command(NSDictionary *msg) {- id reqId = msg[@"id"];- BOOL enabled = [msg[@"enabled"] boolValue];-- int token = 0;- BOOL ok = (notify_register_check("com.apple.system.lowpowermode", &token) ==- NOTIFY_STATUS_OK);- if (ok) {- notify_set_state(token, enabled ? 1 : 0);- ok = (notify_post("com.apple.system.lowpowermode") == NOTIFY_STATUS_OK);- notify_cancel(token);- }-- NSLog(@"vphoned: low_power_mode %s -> %s", enabled ? "on" : "off",- ok ? "ok" : "failed");- NSMutableDictionary *r = vp_make_response(@"low_power_mode", reqId);- r[@"ok"] = @(ok);- return r;-}diff --git a/scripts/vphoned/vphoned_protocol.h b/scripts/vphoned/vphoned_protocol.hdeleted file mode 100644index 1d41a394..00000000--- a/scripts/vphoned/vphoned_protocol.h+++ /dev/null@@ -1,22 +0,0 @@-/*- * vphoned_protocol — Length-prefixed JSON framing over vsock.- *- * Each message: [uint32 big-endian length][UTF-8 JSON payload]- */--#pragma once-#import <Foundation/Foundation.h>--#define PROTOCOL_VERSION 1--BOOL vp_read_fully(int fd, void *buf, size_t count);-BOOL vp_write_fully(int fd, const void *buf, size_t count);--/// Discard exactly `size` bytes from fd. Used to keep protocol in sync on error paths.-void vp_drain(int fd, size_t size);--NSDictionary *vp_read_message(int fd);-BOOL vp_write_message(int fd, NSDictionary *dict);--/// Build a response dict with protocol version, type, and optional request ID echo.-NSMutableDictionary *vp_make_response(NSString *type, id reqId);diff --git a/scripts/vphoned/vphoned_protocol.m b/scripts/vphoned/vphoned_protocol.mdeleted file mode 100644index c7edf283..00000000--- a/scripts/vphoned/vphoned_protocol.m+++ /dev/null@@ -1,64 +0,0 @@-#import "vphoned_protocol.h"-#include <unistd.h>--BOOL vp_read_fully(int fd, void *buf, size_t count) {- size_t offset = 0;- while (offset < count) {- ssize_t n = read(fd, (uint8_t *)buf + offset, count - offset);- if (n <= 0) return NO;- offset += n;- }- return YES;-}--BOOL vp_write_fully(int fd, const void *buf, size_t count) {- size_t offset = 0;- while (offset < count) {- ssize_t n = write(fd, (const uint8_t *)buf + offset, count - offset);- if (n <= 0) return NO;- offset += n;- }- return YES;-}--void vp_drain(int fd, size_t size) {- uint8_t buf[32768];- size_t remaining = size;- while (remaining > 0) {- size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf);- if (!vp_read_fully(fd, buf, chunk)) break;- remaining -= chunk;- }-}--NSDictionary *vp_read_message(int fd) {- uint32_t header = 0;- if (!vp_read_fully(fd, &header, 4)) return nil;- uint32_t length = ntohl(header);- if (length == 0 || length > 4 * 1024 * 1024) return nil;-- NSMutableData *payload = [NSMutableData dataWithLength:length];- if (!vp_read_fully(fd, payload.mutableBytes, length)) return nil;-- NSError *err = nil;- id obj = [NSJSONSerialization JSONObjectWithData:payload options:0 error:&err];- if (![obj isKindOfClass:[NSDictionary class]]) return nil;- return obj;-}--BOOL vp_write_message(int fd, NSDictionary *dict) {- NSError *err = nil;- NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&err];- if (!json) return NO;-- uint32_t header = htonl((uint32_t)json.length);- if (!vp_write_fully(fd, &header, 4)) return NO;- if (!vp_write_fully(fd, json.bytes, json.length)) return NO;- return YES;-}--NSMutableDictionary *vp_make_response(NSString *type, id reqId) {- NSMutableDictionary *r = [@{@"v": @PROTOCOL_VERSION, @"t": type} mutableCopy];- if (reqId) r[@"id"] = reqId;- return r;-}diff --git a/scripts/vphoned/vphoned_response.h b/scripts/vphoned/vphoned_response.hnew file mode 100644index 00000000..53c0037a--- /dev/null+++ b/scripts/vphoned/vphoned_response.h@@ -0,0 +1,8 @@+#pragma once+#import <Foundation/Foundation.h>++static inline NSMutableDictionary *vp_make_response(NSString *type, id reqId) {+ NSMutableDictionary *response = [@{@"t": type} mutableCopy];+ if (reqId) response[@"id"] = reqId;+ return response;+}diff --git a/scripts/vphoned/vphoned_settings.h b/scripts/vphoned/vphoned_settings.hdeleted file mode 100644index 39b94820..00000000--- a/scripts/vphoned/vphoned_settings.h+++ /dev/null@@ -1,12 +0,0 @@-/*- * vphoned_settings — System preferences read/write over vsock.- *- * Handles settings_get and settings_set using CFPreferences.- * No extra frameworks needed — CFPreferences is in CoreFoundation.- */--#pragma once-#import <Foundation/Foundation.h>--/// Handle a settings command. Returns a response dict.-NSDictionary *vp_handle_settings_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_settings.m b/scripts/vphoned/vphoned_settings.mdeleted file mode 100644index a48f6f3f..00000000--- a/scripts/vphoned/vphoned_settings.m+++ /dev/null@@ -1,177 +0,0 @@-/*- * vphoned_settings — System preferences read/write via CFPreferences.- *- * Reads and writes preference domains using CFPreferences API.- * No additional frameworks required.- */--#import "vphoned_settings.h"-#import "vphoned_protocol.h"--// MARK: - Helpers--/// Map a CFPropertyList value to a JSON-safe representation with type info.-static NSDictionary *serialize_value(id value) {- if (!value || value == (id)kCFNull) {- return @{@"value" : [NSNull null], @"type" : @"null"};- }- if ([value isKindOfClass:[NSNumber class]]) {- // Distinguish boolean from number- if (strcmp([value objCType], @encode(BOOL)) == 0 ||- strcmp([value objCType], @encode(char)) == 0) {- return @{@"value" : value, @"type" : @"boolean"};- }- // Check for float/double- if (strcmp([value objCType], @encode(float)) == 0 ||- strcmp([value objCType], @encode(double)) == 0) {- return @{@"value" : value, @"type" : @"float"};- }- return @{@"value" : value, @"type" : @"integer"};- }- if ([value isKindOfClass:[NSString class]]) {- return @{@"value" : value, @"type" : @"string"};- }- if ([value isKindOfClass:[NSData class]]) {- return @{- @"value" : [(NSData *)value base64EncodedStringWithOptions:0],- @"type" : @"data"- };- }- if ([value isKindOfClass:[NSDate class]]) {- return @{- @"value" : @([(NSDate *)value timeIntervalSince1970]),- @"type" : @"date"- };- }- if ([value isKindOfClass:[NSArray class]] ||- [value isKindOfClass:[NSDictionary class]]) {- // Try JSON serialization- if ([NSJSONSerialization isValidJSONObject:value]) {- return @{@"value" : value, @"type" : @"plist"};- }- return @{@"value" : [value description], @"type" : @"plist"};- }- return @{@"value" : [value description], @"type" : @"unknown"};-}--/// Deserialize a value from the request based on type hint.-static id deserialize_value(id rawValue, NSString *typeHint) {- if (!rawValue || rawValue == (id)[NSNull null])- return nil;-- if ([typeHint isEqualToString:@"boolean"]) {- return @([rawValue boolValue]);- }- if ([typeHint isEqualToString:@"integer"]) {- return @([rawValue longLongValue]);- }- if ([typeHint isEqualToString:@"float"]) {- return @([rawValue doubleValue]);- }- if ([typeHint isEqualToString:@"string"]) {- return [rawValue description];- }- if ([typeHint isEqualToString:@"data"]) {- if ([rawValue isKindOfClass:[NSString class]]) {- return [[NSData alloc] initWithBase64EncodedString:rawValue options:0];- }- }- // Default: pass through (JSON types map naturally)- return rawValue;-}--// MARK: - Command Handler--NSDictionary *vp_handle_settings_command(NSDictionary *msg) {- NSString *type = msg[@"t"];- id reqId = msg[@"id"];-- // -- settings_get --- if ([type isEqualToString:@"settings_get"]) {- NSString *domain = msg[@"domain"];- NSString *key = msg[@"key"];-- if (!domain) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing domain";- return r;- }-- if (key && key.length > 0) {- // Single key- CFPropertyListRef value = CFPreferencesCopyAppValue(- (__bridge CFStringRef)key, (__bridge CFStringRef)domain);- NSMutableDictionary *r = vp_make_response(@"settings_get", reqId);- if (value) {- NSDictionary *serialized = serialize_value((__bridge id)value);- r[@"value"] = serialized[@"value"];- r[@"type"] = serialized[@"type"];- CFRelease(value);- } else {- r[@"value"] = [NSNull null];- r[@"type"] = @"null";- }- return r;- } else {- // All keys in domain- CFArrayRef keys = CFPreferencesCopyKeyList((__bridge CFStringRef)domain,- kCFPreferencesCurrentUser,- kCFPreferencesAnyHost);-- NSMutableDictionary *r = vp_make_response(@"settings_get", reqId);- if (keys) {- CFDictionaryRef allValues = CFPreferencesCopyMultiple(- keys,- (__bridge CFStringRef)domain,- kCFPreferencesCurrentUser,- kCFPreferencesAnyHost);- if (allValues) {- // Convert to serializable dict- NSDictionary *dict = (__bridge NSDictionary *)allValues;- NSMutableDictionary *serialized = [NSMutableDictionary dictionary];- for (NSString *k in dict) {- NSDictionary *entry = serialize_value(dict[k]);- serialized[k] = entry;- }- r[@"value"] = serialized;- r[@"type"] = @"dictionary";- CFRelease(allValues);- }- CFRelease(keys);- } else {- r[@"value"] = @{};- r[@"type"] = @"dictionary";- }- return r;- }- }-- // -- settings_set --- if ([type isEqualToString:@"settings_set"]) {- NSString *domain = msg[@"domain"];- NSString *key = msg[@"key"];- id rawValue = msg[@"value"];- NSString *typeHint = msg[@"type"];-- if (!domain || !key) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing domain or key";- return r;- }-- id value = deserialize_value(rawValue, typeHint);-- CFPreferencesSetAppValue((__bridge CFStringRef)key,- (__bridge CFPropertyListRef)value,- (__bridge CFStringRef)domain);- CFPreferencesAppSynchronize((__bridge CFStringRef)domain);-- NSMutableDictionary *r = vp_make_response(@"settings_set", reqId);- r[@"ok"] = @YES;- return r;- }-- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"unknown settings command: %@", type];- return r;-}diff --git a/scripts/vphoned/vphoned_url.h b/scripts/vphoned/vphoned_url.hdeleted file mode 100644index ff364fdd..00000000--- a/scripts/vphoned/vphoned_url.h+++ /dev/null@@ -1,11 +0,0 @@-/*- * vphoned_url — URL opening over vsock.- *- * Handles open_url using LSApplicationWorkspace.- */--#pragma once-#import <Foundation/Foundation.h>--/// Handle an open_url command. Returns a response dict.-NSDictionary *vp_handle_url_command(NSDictionary *msg);diff --git a/scripts/vphoned/vphoned_url.m b/scripts/vphoned/vphoned_url.mdeleted file mode 100644index 2f53ab42..00000000--- a/scripts/vphoned/vphoned_url.m+++ /dev/null@@ -1,59 +0,0 @@-/*- * vphoned_url — URL opening via LSApplicationWorkspace.- *- * Uses LSApplicationWorkspace (CoreServices) to open URLs.- * Does not require UIKit — works from daemon context.- */--#import "vphoned_url.h"-#import "vphoned_protocol.h"-#include <objc/message.h>--@interface LSApplicationWorkspace : NSObject-+ (instancetype)defaultWorkspace;-- (BOOL)openURL:(NSURL *)url withOptions:(NSDictionary *)options;-- (BOOL)openSensitiveURL:(NSURL *)url withOptions:(NSDictionary *)options;-@end--NSDictionary *vp_handle_url_command(NSDictionary *msg) {- id reqId = msg[@"id"];- NSString *urlStr = msg[@"url"];-- if (!urlStr) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = @"missing url";- return r;- }-- NSURL *url = [NSURL URLWithString:urlStr];- if (!url) {- NSMutableDictionary *r = vp_make_response(@"err", reqId);- r[@"msg"] = [NSString stringWithFormat:@"invalid url: %@", urlStr];- return r;- }-- LSApplicationWorkspace *ws = [LSApplicationWorkspace defaultWorkspace];- BOOL ok = NO;-- // Try openURL:withOptions: first- SEL openURLSel = sel_registerName("openURL:withOptions:");- if ([ws respondsToSelector:openURLSel]) {- ok = ((BOOL (*)(id, SEL, id, id))objc_msgSend)(ws, openURLSel, url, nil);- }-- if (!ok) {- // Fallback: try openSensitiveURL:withOptions: (requires entitlement)- SEL sensitiveSel = sel_registerName("openSensitiveURL:withOptions:");- if ([ws respondsToSelector:sensitiveSel]) {- ok =- ((BOOL (*)(id, SEL, id, id))objc_msgSend)(ws, sensitiveSel, url, nil);- }- }-- NSMutableDictionary *r = vp_make_response(@"open_url", reqId);- r[@"ok"] = @(ok);- if (!ok) {- r[@"msg"] = [NSString stringWithFormat:@"failed to open url: %@", urlStr];- }- return r;-}diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swiftindex d102b823..827d0914 100644--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -85,6 +85,10 @@ extension CryptexFilesystemPatcher {))try setMode(0o755, at: targetBin)+ let icli = try VPhoneGuestBinaries.resolve("icli")+ let targetIcli = target.appending(path: "/usr/bin/icli")+ try FileManager.default.copyItem(at: icli, to: targetIcli)+ try setMode(0o755, at: targetIcli)}/// Copy in the prebuilt guest daemon.diff --git a/sources/VPhoneCore/VPhoneBootCLI.swift b/sources/VPhoneCore/VPhoneBootCLI.swiftindex ae224cd1..09ec65bb 100644--- a/sources/VPhoneCore/VPhoneBootCLI.swift+++ b/sources/VPhoneCore/VPhoneBootCLI.swift@@ -57,6 +57,9 @@ public struct VPhoneBootCLI: ParsableCommand {@Flag(name: .customLong("headless"), help: "Boot without a VM window or menu bar")public var headless: Bool = false+ @Option(help: "Expose the guest HTTP/WebSocket API on the host, for example 127.0.0.1:8765")+ public var apiListen: String?+@Option(help: "Kernel GDB debug stub port on host (omit for system-assigned port; valid: 6000...65535)")public var kernelDebugPort: Int?@@ -96,6 +99,19 @@ public struct VPhoneBootCLI: ParsableCommand {)}+ if dfu, apiListen != nil {+ throw ValidationError("`--api-listen` is unavailable with `--dfu`.")+ }+ if let apiListen {+ let address = URLComponents(string: "tcp://\(apiListen)")+ guard let address, let host = address.host, !host.isEmpty,+ let port = address.port, (0...65535).contains(port),+ address.path.isEmpty, address.query == nil, address.fragment == nil+ else {+ throw ValidationError("`--api-listen` requires host:port, for example 127.0.0.1:8765.")+ }+ }+guard let packageURL = installPackageURL else { return }guard FileManager.default.fileExists(atPath: packageURL.path) else {@@ -125,6 +141,7 @@ public struct VPhoneBootCLI: ParsableCommand {var args = ["--config", config.path]if dfu { args.append("--dfu") }if headless { args.append("--headless") }+ if let apiListen { args += ["--api-listen", apiListen] }if vphonedBin != ".vphoned.signed" { args += ["--vphoned-bin", vphonedBin] }if let port = kernelDebugPort { args += ["--kernel-debug-port", String(port)] }if let ipa = installIPA { args += ["--install-ipa", ipa.path] }diff --git a/sources/VPhoneKit/VPhoneAPIClient.swift b/sources/VPhoneKit/VPhoneAPIClient.swiftnew file mode 100644index 00000000..9c800791--- /dev/null+++ b/sources/VPhoneKit/VPhoneAPIClient.swift@@ -0,0 +1,207 @@+import Foundation++/// JSON values used by the public API, so callers do not need `[String: Any]`.+public indirect enum VPhoneJSONValue: Codable, Sendable, Equatable {+ case object([String: VPhoneJSONValue])+ case array([VPhoneJSONValue])+ case string(String)+ case number(Double)+ case bool(Bool)+ case null++ public init(from decoder: any Decoder) throws {+ let value = try decoder.singleValueContainer()+ if value.decodeNil() { self = .null }+ else if let bool = try? value.decode(Bool.self) { self = .bool(bool) }+ else if let number = try? value.decode(Double.self) { self = .number(number) }+ else if let string = try? value.decode(String.self) { self = .string(string) }+ else if let object = try? value.decode([String: VPhoneJSONValue].self) { self = .object(object) }+ else { self = .array(try value.decode([VPhoneJSONValue].self)) }+ }++ public func encode(to encoder: any Encoder) throws {+ var value = encoder.singleValueContainer()+ switch self {+ case .object(let object): try value.encode(object)+ case .array(let array): try value.encode(array)+ case .string(let string): try value.encode(string)+ case .number(let number): try value.encode(number)+ case .bool(let bool): try value.encode(bool)+ case .null: try value.encodeNil()+ }+ }+}++public struct VPhoneAPIError: Error, Codable, Sendable, CustomStringConvertible {+ public let code: String+ public let message: String+ public var description: String { "\(code): \(message)" }+}++public struct VPhoneAPIResponse: Codable, Sendable {+ public let type: String+ public let id: VPhoneJSONValue?+ public let result: VPhoneJSONValue?+ public let error: VPhoneAPIError?+}++public struct VPhoneAPIEvent: Codable, Sendable {+ public let type: String+ public let event: String+ public let data: VPhoneJSONValue+}++public enum VPhoneAPIMessage: Sendable {+ case response(VPhoneAPIResponse)+ case event(VPhoneAPIEvent)+}++/// An unentitled client for the optional host proxy. vphone-ui can import this+/// product without linking Virtualization.framework or running the CLI.+public struct VPhoneAPIClient: Sendable {+ public let baseURL: URL+ private let session: URLSession++ public init(baseURL: URL, session: URLSession = .shared) {+ self.baseURL = baseURL+ self.session = session+ }++ public func call(+ _ method: String,+ params: [String: VPhoneJSONValue] = [:],+ id: VPhoneJSONValue = .string(UUID().uuidString)+ ) async throws -> VPhoneJSONValue {+ let request = Request(id: id, method: method, params: params)+ var http = URLRequest(url: baseURL.appending(path: "v1/rpc"))+ http.httpMethod = "POST"+ http.setValue("application/json", forHTTPHeaderField: "Content-Type")+ http.httpBody = try JSONEncoder().encode(request)+ let (data, response) = try await session.data(for: http)+ guard let response = response as? HTTPURLResponse else {+ throw VPhoneAPIError(code: "transport", message: "No HTTP response")+ }+ let value = try JSONDecoder().decode(VPhoneAPIResponse.self, from: data)+ if let error = value.error { throw error }+ guard (200..<300).contains(response.statusCode), let result = value.result else {+ throw VPhoneAPIError(code: "protocol", message: "Missing result (HTTP \(response.statusCode))")+ }+ return result+ }++ public func openWebSocket() throws -> VPhoneAPIWebSocket {+ guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else {+ throw VPhoneAPIError(code: "url", message: "Invalid API URL")+ }+ switch components.scheme {+ case "http": components.scheme = "ws"+ case "https": components.scheme = "wss"+ default: throw VPhoneAPIError(code: "url", message: "API URL must use HTTP or HTTPS")+ }+ components.path = (components.path as NSString).appendingPathComponent("v1/events")+ guard let url = components.url else {+ throw VPhoneAPIError(code: "url", message: "Invalid WebSocket URL")+ }+ let task = session.webSocketTask(with: url)+ task.resume()+ return VPhoneAPIWebSocket(task: task)+ }++ /// Runs any icli subcommand inside the guest. Arguments are passed as an+ /// array to the pinned icli executable, without a shell. The result holds+ /// its exit code, decoded JSON output (or text), and stderr.+ public func runIcli(_ arguments: [String], stdin: String? = nil) async throws -> VPhoneJSONValue {+ var params: [String: VPhoneJSONValue] = ["argv": .array(arguments.map(VPhoneJSONValue.string))]+ if let stdin { params["stdin"] = .string(stdin) }+ return try await call("icli.execute", params: params)+ }++ /// Streams a guest file to a new temporary host file. The caller owns the+ /// returned file and should move or delete it when finished.+ public func downloadFile(at guestPath: String) async throws -> URL {+ let url = try fileURL(guestPath)+ let (temporary, response) = try await session.download(from: url)+ guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {+ throw VPhoneAPIError(code: "download", message: "Guest file download failed")+ }+ let destination = FileManager.default.temporaryDirectory+ .appendingPathComponent("vphone-" + UUID().uuidString)+ try FileManager.default.moveItem(at: temporary, to: destination)+ return destination+ }++ /// Sends a host file to an absolute guest path without loading it into+ /// memory. The guest stages it beside the destination and renames it.+ public func uploadFile(from localURL: URL, toGuestPath guestPath: String) async throws -> VPhoneJSONValue {+ var request = URLRequest(url: try fileURL(guestPath))+ request.httpMethod = "PUT"+ request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")+ let (data, response) = try await session.upload(for: request, fromFile: localURL)+ let object = try JSONDecoder().decode([String: VPhoneJSONValue].self, from: data)+ if let error = object["error"] {+ let encoded = try JSONEncoder().encode(error)+ throw try JSONDecoder().decode(VPhoneAPIError.self, from: encoded)+ }+ guard let response = response as? HTTPURLResponse,+ response.statusCode == 200, let result = object["result"]+ else { throw VPhoneAPIError(code: "upload", message: "Guest file upload failed") }+ return result+ }++ private func fileURL(_ guestPath: String) throws -> URL {+ guard guestPath.hasPrefix("/"), !guestPath.contains("\0"),+ var components = URLComponents(url: baseURL.appending(path: "v1/files/content"),+ resolvingAgainstBaseURL: false)+ else { throw VPhoneAPIError(code: "path", message: "Guest path must be absolute") }+ components.queryItems = [URLQueryItem(name: "path", value: guestPath)]+ guard let url = components.url else { throw VPhoneAPIError(code: "url", message: "Invalid file URL") }+ return url+ }++ private struct Request: Encodable {+ let id: VPhoneJSONValue+ let method: String+ let params: [String: VPhoneJSONValue]+ }+}++public actor VPhoneAPIWebSocket {+ private let task: URLSessionWebSocketTask++ init(task: URLSessionWebSocketTask) { self.task = task }++ public func send(+ _ method: String,+ params: [String: VPhoneJSONValue] = [:],+ id: VPhoneJSONValue = .string(UUID().uuidString)+ ) async throws {+ let object: [String: VPhoneJSONValue] = [+ "id": id, "method": .string(method), "params": .object(params),+ ]+ let data = try JSONEncoder().encode(object)+ try await task.send(.string(String(decoding: data, as: UTF8.self)))+ }++ public func next() async throws -> VPhoneAPIMessage {+ let message = try await task.receive()+ let data: Data+ switch message {+ case .data(let bytes): data = bytes+ case .string(let text): data = Data(text.utf8)+ @unknown default: throw VPhoneAPIError(code: "protocol", message: "Unknown WebSocket message")+ }+ let object = try JSONDecoder().decode([String: VPhoneJSONValue].self, from: data)+ switch object["type"] {+ case .string("response"):+ return .response(try JSONDecoder().decode(VPhoneAPIResponse.self, from: data))+ case .string("event"):+ return .event(try JSONDecoder().decode(VPhoneAPIEvent.self, from: data))+ default:+ throw VPhoneAPIError(code: "protocol", message: "Unknown WebSocket envelope")+ }+ }++ public func close() {+ task.cancel(with: .normalClosure, reason: nil)+ }+}diff --git a/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swift b/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swiftnew file mode 100644index 00000000..31f9a630--- /dev/null+++ b/sources/VPhoneVMKit/Guest/VPhoneAPIProxy.swift@@ -0,0 +1,150 @@+import Darwin+import Foundation+import NIOCore+import NIOPosix+import Virtualization++/// Transparent TCP-to-VSOCK forwarding for the guest's HTTP/WebSocket API.+/// Each host connection gets its own guest connection, so HTTP upgrades,+/// streaming bodies, and future protocol changes pass through unchanged.+@MainActor+public final class VPhoneAPIProxy {+ public enum ProxyError: Error, CustomStringConvertible {+ case invalidListenAddress(String)++ public var description: String {+ switch self {+ case .invalidListenAddress(let value):+ "Invalid API listen address '\(value)'; use host:port, for example 127.0.0.1:8765"+ }+ }+ }++ private let host: String+ private let port: Int+ private let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)+ private let provider: GuestSocketProvider+ private var server: Channel?++ public init(device: VZVirtioSocketDevice, listen: String) throws {+ guard let components = URLComponents(string: "tcp://\(listen)"),+ let host = components.host, !host.isEmpty,+ let port = components.port, (0...65535).contains(port),+ components.path.isEmpty, components.query == nil, components.fragment == nil+ else { throw ProxyError.invalidListenAddress(listen) }+ self.host = host+ self.port = port+ self.provider = GuestSocketProvider(device: device, group: group)+ }++ /// Starts only when the boot command explicitly supplied `--api-listen`.+ /// The returned URL contains the actual port when the caller requested 0.+ @discardableResult+ public func start() async throws -> URL {+ let provider = self.provider+ let channel = try await ServerBootstrap(group: group)+ .serverChannelOption(ChannelOptions.backlog, value: 128)+ .childChannelOption(ChannelOptions.autoRead, value: false)+ .childChannelInitializer { channel in provider.attach(channel) }+ .bind(host: host, port: port)+ .get()+ server = channel+ let actualPort = channel.localAddress?.port ?? port+ var url = URLComponents()+ url.scheme = "http"+ url.host = host+ url.port = actualPort+ return url.url!+ }++ public func stop() {+ server?.close(promise: nil)+ server = nil+ group.shutdownGracefully { error in+ if let error { print("[api] proxy shutdown: \(error)") }+ }+ }+}++private final class GuestSocketProvider: @unchecked Sendable {+ private let device: VZVirtioSocketDevice+ private let group: EventLoopGroup+ private let guestPort: UInt32 = 1339++ init(device: VZVirtioSocketDevice, group: EventLoopGroup) {+ self.device = device+ self.group = group+ }++ func attach(_ host: Channel) -> EventLoopFuture<Void> {+ let promise = host.eventLoop.makePromise(of: Void.self)+ Task { @MainActor in+ device.connect(toPort: guestPort) { result in+ Task { @MainActor in+ switch result {+ case .failure(let error):+ promise.fail(error)+ case .success(let connection):+ let fd = dup(connection.fileDescriptor)+ guard fd >= 0 else {+ promise.fail(POSIXError(.EBADF))+ return+ }+ let guestRelay = ByteRelay(connection: connection)+ let hostRelay = ByteRelay(connection: connection)+ ClientBootstrap(group: self.group)+ .channelInitializer { guest in guest.pipeline.addHandler(guestRelay) }+ .withConnectedSocket(fd)+ .flatMap { guest in+ guestRelay.peer = host+ hostRelay.peer = guest+ return host.pipeline.addHandler(hostRelay)+ }+ .whenComplete { result in+ switch result {+ case .success:+ host.setOption(ChannelOptions.autoRead, value: true).cascade(to: promise)+ case .failure(let error):+ promise.fail(error)+ }+ }+ }+ }+ }+ }+ return promise.futureResult+ }+}++private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = ByteBuffer+ typealias OutboundOut = ByteBuffer++ // Keeping this object alive also keeps Virtualization.framework's original+ // socket descriptor alive while NIO owns its duplicated descriptor.+ private let connection: VZVirtioSocketConnection+ var peer: Channel?++ init(connection: VZVirtioSocketConnection) { self.connection = connection }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ guard let peer else { return }+ peer.writeAndFlush(unwrapInboundIn(data), promise: nil)+ }++ func channelWritabilityChanged(context: ChannelHandlerContext) {+ _ = peer?.setOption(ChannelOptions.autoRead, value: context.channel.isWritable)+ context.fireChannelWritabilityChanged()+ }++ func channelInactive(context: ChannelHandlerContext) {+ let other = peer+ peer = nil+ other?.close(promise: nil)+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error: Error) {+ context.close(promise: nil)+ }+}diff --git a/sources/VPhoneVMKit/Guest/VPhoneControl.swift b/sources/VPhoneVMKit/Guest/VPhoneControl.swiftindex 2c6e4ed6..239d1dc8 100644--- a/sources/VPhoneVMKit/Guest/VPhoneControl.swift+++ b/sources/VPhoneVMKit/Guest/VPhoneControl.swift@@ -1,849 +1,400 @@import CryptoKit+import Darwinimport Foundationimport Virtualization-import VPhoneCore--/// Host-side client for the vphoned guest agent.-///-/// Communicates over vsock using length-prefixed JSON (vphone-control protocol).-/// Each message is `[uint32 big-endian length][UTF-8 JSON]` where JSON-/// always carries `"v"` (protocol version), `"t"` (message type), and-/// optionally `"id"` (request ID, echoed in responses).-///-/// Auto-update: if `guestBinaryURL` is set, the hello message includes-/// its SHA-256 hash. When the guest replies with `need_update`, we push-/// the binary as a raw transfer (`{"t":"update","size":N}` + N bytes).-@MainActor-class VPhoneControl {- private static let protocolVersion = 1- private static let vsockPort: UInt32 = 1337- private static let reconnectDelay: TimeInterval = 3- private static let handshakeTimeout: TimeInterval = 8- private static let defaultRequestTimeout: TimeInterval = 10- private static let slowRequestTimeout: TimeInterval = 30- private static let transferRequestTimeout: TimeInterval = 180-- private var connection: VZVirtioSocketConnection?- private weak var device: VZVirtioSocketDevice?- private(set) var isConnected = false- private(set) var guestCaps: [String] = []- private(set) var guestIP: String?- /// Guest userland iOS version reported at handshake (e.g. "18.6.2"), if known.- private(set) var guestIOSVersion: String?-- /// Whether touches should be injected guest-side via vphoned rather than the- /// VZ USB touchscreen. True for iOS 18 bases: on the 26.x kernel their USB- /// touchscreen dext receives reports but emits no digitizer events, so the- /// UI never sees touches. 26.x bases keep the native VZ multitouch path.- var useGuestTouchInjection: Bool {- guard isConnected, guestCaps.contains("touch"),- let major = guestIOSVersion.flatMap({ Int($0.split(separator: ".").first ?? "") })- else { return false }- return major < 26- }- /// Path to the signed vphoned binary. When set, enables auto-update.- var guestBinaryURL: URL?-- /// Called when guest is ready (not updating). Receives guest capabilities.- var onConnect: (([String]) -> Void)?-- /// Called when the guest disconnects (before reconnect attempt).- var onDisconnect: (() -> Void)?-- private var guestBinaryData: Data?- private var guestBinaryHash: String?- private var nextRequestId: UInt64 = 0- private var connectionAttemptToken: UInt64 = 0- private var reconnectWorkItem: DispatchWorkItem?- init() {}-- // MARK: - Pending Requests-- /// Callback for a pending request. Called on the read-loop queue.- private struct PendingRequest: @unchecked Sendable {- let handler: (Result<([String: Any], Data?), any Error>) -> Void- }-- private let pendingLock = NSLock()- private nonisolated(unsafe) var pendingRequests: [String: PendingRequest] = [:]-- private nonisolated func addPending(- id: String,- handler: @escaping (Result<([String: Any], Data?), any Error>) -> Void- ) {- pendingLock.lock()- pendingRequests[id] = PendingRequest(handler: handler)- pendingLock.unlock()- }-- private nonisolated func removePending(id: String) -> PendingRequest? {- pendingLock.lock()- defer { pendingLock.unlock() }- return pendingRequests.removeValue(forKey: id)- }-- private nonisolated func failAllPending(with error: ControlError = .notConnected) {- pendingLock.lock()- let pending = pendingRequests- pendingRequests.removeAll()- pendingLock.unlock()- for (_, req) in pending {- req.handler(.failure(error))- }- }+/// The VM UI's direct HTTP client over VSOCK. It does not open a host TCP+/// listener; only --api-listen creates one through VPhoneAPIProxy.+@MainActor+final class VPhoneControl {enum ControlError: Error, CustomStringConvertible {case notConnectedcase unsupportedCapability(String)- case requestTimedOut(type: String, seconds: Int)case protocolError(String)case guestError(String)var description: String {switch self {case .notConnected: "not connected to vphoned"- case let .unsupportedCapability(capability):- "guest does not support capability: \(capability)"- case let .requestTimedOut(type, seconds):- "request timed out (\(type), \(seconds)s)"- case let .protocolError(msg): "protocol error: \(msg)"- case let .guestError(msg): msg+ case .unsupportedCapability(let value): "guest does not support capability: \(value)"+ case .protocolError(let value): "API protocol error: \(value)"+ case .guestError(let value): value}}}- // MARK: - Guest Binary Hash-- private func loadGuestBinary() {- guard let url = guestBinaryURL,- let data = try? Data(contentsOf: url, options: .mappedIfSafe)- else {- guestBinaryData = nil- guestBinaryHash = nil- return- }- guestBinaryData = data- guestBinaryHash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()- print(- "[control] vphoned binary: \(url.lastPathComponent) (\(data.count) bytes, \(guestBinaryHash!.prefix(12))...)"- )+ struct ClipboardContent {+ let text: String?+ let types: [String]+ let hasImage: Bool+ let changeCount: Int+ let imageData: Data?}- // MARK: - Connect+ private weak var device: VZVirtioSocketDevice?+ private var monitor: Task<Void, Never>?+ private var orderedInput: Task<Void, Never>?+ private(set) var isConnected = false+ private(set) var guestCaps: [String] = []+ private(set) var guestIP: String?+ private(set) var guestIOSVersion: String?+ var guestBinaryURL: URL?+ var onConnect: (([String]) -> Void)?+ var onDisconnect: (() -> Void)?++ var useGuestTouchInjection: Bool {+ guard isConnected, guestCaps.contains("touch"),+ let major = guestIOSVersion.flatMap({ Int($0.split(separator: ".").first ?? "") })+ else { return false }+ return major < 26+ }func connect(device: VZVirtioSocketDevice) {self.device = device- cancelReconnect()- loadGuestBinary()- attemptConnect()- }-- private func attemptConnect() {- guard let device else { return }- connectionAttemptToken += 1- let attemptToken = connectionAttemptToken- device.connect(toPort: Self.vsockPort) {- [weak self] (result: Result<VZVirtioSocketConnection, any Error>) in- Task { @MainActor in- guard let self else { return }- guard self.isCurrentAttempt(attemptToken) else { return }- switch result {- case let .success(conn):- self.connection = conn- self.performHandshake(fd: conn.fileDescriptor, attemptToken: attemptToken)- case let .failure(error):- print("[control] connect failed: \(error)")- self.scheduleReconnect(for: attemptToken, reason: "connect failed")- }+ monitor?.cancel()+ monitor = Task { [weak self] in+ while !Task.isCancelled {+ await self?.probe()+ try? await Task.sleep(for: .seconds(3))}}}- // MARK: - Handshake+ func stop() {+ monitor?.cancel()+ monitor = nil+ orderedInput?.cancel()+ orderedInput = nil+ device = nil+ setDisconnected()+ }- private func performHandshake(fd: Int32, attemptToken: UInt64) {- var hello: [String: Any] = ["v": Self.protocolVersion, "t": "hello"]- if let hash = guestBinaryHash {- hello["bin_hash"] = hash- }- guard writeMessage(fd: fd, dict: hello) else {- print("[control] handshake: failed to send hello")- disconnect(ifCurrentAttempt: attemptToken)- return- }- armHandshakeTimeout(fd: fd, attemptToken: attemptToken)-- DispatchQueue.global(qos: .userInteractive).async { [weak self] in- guard let resp = Self.readMessage(fd: fd) else {- Task { @MainActor in- guard let self else { return }- guard self.isCurrentAttempt(attemptToken, fd: fd) else { return }- print("[control] handshake: no response")- self.disconnect(ifCurrentAttempt: attemptToken)- }- return+ private func probe() async {+ do {+ let response = try await http(method: "GET", path: "/v1/health")+ guard response.status == 200,+ let info = try JSONSerialization.jsonObject(with: response.body) as? [String: Any],+ info["api_version"] as? Int == 1 else {+ throw ControlError.protocolError("incompatible guest API")}-- let version = resp["v"] as? Int ?? 0- let type = resp["t"] as? String ?? ""- let name = resp["name"] as? String ?? "unknown"- let caps = resp["caps"] as? [String] ?? []- let ip = resp["ip"] as? String- let iosVersion = resp["ios"] as? String- let needUpdate = resp["need_update"] as? Bool ?? false-- Task { @MainActor in- guard let self else { return }- guard self.isCurrentAttempt(attemptToken, fd: fd) else { return }- guard type == "hello", version == Self.protocolVersion else {- print(- "[control] handshake: version mismatch (guest v\(version), host v\(Self.protocolVersion))"- )- self.disconnect(ifCurrentAttempt: attemptToken)+ if let binary = guestBinaryURL,+ let data = try? Data(contentsOf: binary, options: .mappedIfSafe) {+ let hash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ if hash != info["binary_hash"] as? String {+ print("[control] updating vphoned over HTTP...")+ try await createDirectory(path: "/var/root/Library/Caches")+ try await uploadFile(path: "/var/root/Library/Caches/vphoned", data: data)+ _ = try await call("agent.apply_update", params: ["sha256": hash])+ setDisconnected()return}- self.guestCaps = caps- self.guestIP = ip- self.guestIOSVersion = iosVersion- self.isConnected = true- let ipSuffix = ip.map { " (\($0))" } ?? ""- let iosSuffix = iosVersion.map { " iOS \($0)" } ?? ""- print("[control] connected to \(name) v\(version)\(ipSuffix)\(iosSuffix), caps: \(caps)")- if self.useGuestTouchInjection {- print("[control] guest-side touch injection enabled (iOS \(iosVersion ?? "?"))")- }-- if needUpdate {- self.pushUpdate(fd: fd)- } else {- self.startReadLoop(fd: fd, attemptToken: attemptToken)- self.onConnect?(caps)- }}+ guestCaps = info["capabilities"] as? [String] ?? []+ guestIP = info["ip"] as? String+ guestIOSVersion = info["ios"] as? String+ if !isConnected {+ isConnected = true+ print("[control] connected to vphoned HTTP API (iOS \(guestIOSVersion ?? "?"))")+ onConnect?(guestCaps)+ }+ } catch {+ setDisconnected()}}- // MARK: - Auto-update Push-- private func pushUpdate(fd: Int32) {- guard let data = guestBinaryData else {- print("[control] update requested but no binary available")- startReadLoop(fd: fd, attemptToken: connectionAttemptToken)- return- }-- print("[control] pushing update (\(data.count) bytes)...")- nextRequestId += 1- let header: [String: Any] = [- "v": Self.protocolVersion, "t": "update", "id": String(nextRequestId, radix: 16),- "size": data.count,- ]- guard writeMessage(fd: fd, dict: header) else {- print("[control] update: failed to send header")- disconnect()- return- }-- let ok = data.withUnsafeBytes { buf in- Self.writeFully(fd: fd, buf: buf.baseAddress!, count: data.count)- }- guard ok else {- print("[control] update: failed to send binary data")- disconnect()- return- }-- print("[control] update sent, waiting for ack...")- startReadLoop(fd: fd, attemptToken: connectionAttemptToken)- }-- // MARK: - Send Commands-- func sendHIDPress(page: UInt32, usage: UInt32) {- sendHID(page: page, usage: usage, down: nil)- }-- func sendHIDDown(page: UInt32, usage: UInt32) {- sendHID(page: page, usage: usage, down: true)+ private func setDisconnected() {+ let wasConnected = isConnected+ isConnected = false+ guestCaps = []+ guestIP = nil+ guestIOSVersion = nil+ if wasConnected { onDisconnect?() }}- func sendHIDUp(page: UInt32, usage: UInt32) {- sendHID(page: page, usage: usage, down: false)- }+ func sendHIDPress(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: nil) }+ func sendHIDDown(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: true) }+ func sendHIDUp(page: UInt32, usage: UInt32) { sendHID(page: page, usage: usage, down: false) }private func sendHID(page: UInt32, usage: UInt32, down: Bool?) {- nextRequestId += 1- var msg: [String: Any] = [- "v": Self.protocolVersion,- "t": "hid",- "id": String(nextRequestId, radix: 16),- "page": page,- "usage": usage,- ]- if let down { msg["down"] = down }- guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else {- print("[control] send failed (not connected)")- return- }- let suffix = down.map { $0 ? " down" : " up" } ?? ""- print(- "[control] hid page=0x\(String(page, radix: 16)) usage=0x\(String(usage, radix: 16))\(suffix)"- )+ var params: [String: Any] = ["page": page, "usage": usage]+ if let down { params["down"] = down }+ enqueueInput("input.hid", params: params)}- /// Inject a single-finger digitizer touch guest-side (bypasses VZ USB touch).- /// phase: 0 = down, 1 = move, 3 = up. x/y are normalized 0..1, top-left origin.func sendTouch(phase: Int, x: Double, y: Double) {- nextRequestId += 1- let msg: [String: Any] = [- "v": Self.protocolVersion,- "t": "touch",- "id": String(nextRequestId, radix: 16),- "phase": phase,- "x": x,- "y": y,- ]- guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else {- print("[control] touch send failed (not connected)")- return- }+ let name = switch phase { case 0: "down"; case 1: "move"; default: "up" }+ enqueueInput("input.touch", params: ["phase": name, "x": x, "y": y, "normalized": true])}- // MARK: - Developer Mode+ private func enqueueInput(_ method: String, params: [String: Any]) {+ let previous = orderedInput+ orderedInput = Task {+ await previous?.value+ guard !Task.isCancelled else { return }+ do { _ = try await call(method, params: params) }+ catch { print("[control] \(method): \(error)") }+ }+ }func sendDevModeStatus() async throws -> Bool {- let (resp, _) = try await sendRequest(["t": "devmode", "action": "status"])- return resp["enabled"] as? Bool ?? false+ try await call("developer_mode.status")["enabled"] as? Bool ?? false}- func sendPing() async throws {- _ = try await sendRequest(["t": "ping"])- }+ func sendPing() async throws { _ = try await http(method: "GET", path: "/v1/health") }func sendVersion() async throws -> String {- let (resp, _) = try await sendRequest(["t": "version"])- return resp["hash"] as? String ?? "unknown"+ let response = try await http(method: "GET", path: "/v1/health")+ let value = try JSONSerialization.jsonObject(with: response.body) as? [String: Any]+ return value?["binary_hash"] as? String ?? "unknown"}- // MARK: - Async Request-Response-- /// Send a request and await the response. Returns the response dict and optional raw data.- func sendRequest(_ dict: [String: Any]) async throws -> ([String: Any], Data?) {- guard let fd = connection?.fileDescriptor else {- throw ControlError.notConnected+ /// Retains the UI-facing request shape while all transport and guest+ /// operations use the versioned HTTP API.+ func sendRequest(_ request: [String: Any]) async throws -> ([String: Any], Data?) {+ guard let type = request["t"] as? String else {+ throw ControlError.protocolError("missing operation")}-- nextRequestId += 1- let reqId = String(nextRequestId, radix: 16)- var msg = dict- msg["v"] = Self.protocolVersion- msg["id"] = reqId- let requestType = msg["t"] as? String ?? "unknown"- let timeout = Self.timeoutForRequest(type: requestType)-- return try await withCheckedThrowingContinuation { continuation in- addPending(id: reqId) { result in- nonisolated(unsafe) let r = result- continuation.resume(with: r)- }- armRequestTimeout(id: reqId, type: requestType, timeout: timeout)- guard writeMessage(fd: fd, dict: msg) else {- _ = removePending(id: reqId)- continuation.resume(throwing: ControlError.notConnected)- return- }+ if type == "file_get" {+ return ([:], try await downloadFile(path: request["path"] as? String ?? ""))+ }+ if type == "clipboard_get" {+ var info = try await call("clipboard.get")+ let image = (info["has_image"] as? Bool == true)+ ? try await http(method: "GET", path: "/v1/clipboard/image").body : nil+ info["ok"] = true+ return (info, image)}+ let method: String+ switch type {+ case "devmode": method = "developer_mode.status"+ case "file_list": method = "files.list"+ case "file_mkdir": method = "files.mkdir"+ case "file_delete": method = "files.remove"+ case "file_rename": method = "files.rename"+ case "ipa_install": method = "apps.install"+ case "clipboard_set": method = "clipboard.set"+ case "app_list": method = "apps.list"+ case "app_launch": method = "apps.launch"+ case "app_terminate": method = "apps.terminate"+ case "app_foreground": method = "apps.foreground"+ case "keychain_list": method = "keychain.list"+ case "keychain_add": method = "keychain.add"+ case "open_url": method = "apps.open_url"+ case "settings_get": method = "settings.get"+ case "settings_set": method = "settings.set"+ case "low_power_mode": method = "power.low_power_mode"+ case "accessibility_tree": method = "accessibility.tree"+ default: throw ControlError.protocolError("unknown operation \(type)")+ }+ var params = request+ params.removeValue(forKey: "t")+ var result = try await call(method, params: params)+ if result["ok"] == nil { result["ok"] = true }+ return (result, nil)+ }++ private func call(_ method: String, params: [String: Any] = [:]) async throws -> [String: Any] {+ let object: [String: Any] = ["id": UUID().uuidString, "method": method, "params": params]+ let body = try JSONSerialization.data(withJSONObject: object)+ let response = try await http(method: "POST", path: "/v1/rpc", body: body)+ guard let envelope = try JSONSerialization.jsonObject(with: response.body) as? [String: Any]+ else { throw ControlError.protocolError("invalid JSON response") }+ if let error = envelope["error"] as? [String: Any] {+ throw ControlError.guestError(error["message"] as? String ?? "Guest operation failed")+ }+ guard response.status == 200, let result = envelope["result"] as? [String: Any]+ else { throw ControlError.protocolError("missing result (HTTP \(response.status))") }+ return result}- // MARK: - File Operations-func listFiles(path: String) async throws -> [[String: Any]] {- let (resp, _) = try await sendRequest(["t": "file_list", "path": path])- guard let entries = resp["entries"] as? [[String: Any]] else {- throw ControlError.protocolError("missing entries in response")+ let (value, _) = try await sendRequest(["t": "file_list", "path": path])+ guard let entries = value["entries"] as? [[String: Any]] else {+ throw ControlError.protocolError("missing file entries")}return entries}func downloadFile(path: String) async throws -> Data {- let (_, data) = try await sendRequest(["t": "file_get", "path": path])- guard let data else {- throw ControlError.protocolError("no file data received")- }- return data+ let response = try await http(method: "GET", path: try filePath(path))+ guard response.status == 200 else { throw try httpError(response) }+ return response.body}func uploadFile(path: String, data: Data, permissions: String = "644") async throws {- guard let fd = connection?.fileDescriptor else {- throw ControlError.notConnected- }-- nextRequestId += 1- let reqId = String(nextRequestId, radix: 16)- let header: [String: Any] = [- "v": Self.protocolVersion,- "t": "file_put",- "id": reqId,- "path": path,- "size": data.count,- "perm": permissions,- ]- let timeout = Self.timeoutForRequest(type: "file_put")-- try await withCheckedThrowingContinuation {- (continuation: CheckedContinuation<Void, any Error>) in- addPending(id: reqId) { result in- switch result {- case .success: continuation.resume()- case let .failure(error): continuation.resume(throwing: error)- }- }- armRequestTimeout(id: reqId, type: "file_put", timeout: timeout)-- // Write header + raw data atomically (same pattern as pushUpdate)- guard writeMessage(fd: fd, dict: header) else {- _ = removePending(id: reqId)- continuation.resume(throwing: ControlError.notConnected)- return- }- let ok = data.withUnsafeBytes { buf in- Self.writeFully(fd: fd, buf: buf.baseAddress!, count: data.count)- }- guard ok else {- _ = removePending(id: reqId)- continuation.resume(throwing: ControlError.protocolError("failed to write file data"))- return- }- }+ let response = try await http(method: "PUT", path: try filePath(path), body: data,+ contentType: "application/octet-stream")+ guard response.status == 200 else { throw try httpError(response) }}func createDirectory(path: String) async throws {- _ = try await sendRequest(["t": "file_mkdir", "path": path])+ _ = try await call("files.mkdir", params: ["path": path])}func deleteFile(path: String) async throws {- _ = try await sendRequest(["t": "file_delete", "path": path])+ _ = try await call("files.remove", params: ["path": path, "recursive": true])}func renameFile(from: String, to: String) async throws {- _ = try await sendRequest(["t": "file_rename", "from": from, "to": to])+ _ = try await call("files.rename", params: ["from": from, "to": to])}func installIPA(localURL: URL) async throws -> String {- do {- return try await installIPAWithBuiltInInstaller(localURL: localURL)- } catch let ControlError.guestError(message) where message == "unknown type: ipa_install" {- throw ControlError.guestError(- "Guest vphoned does not support ipa_install yet. Reconnect or reboot the guest so the updated daemon can take over."- )- }- }-- private func installIPAWithBuiltInInstaller(localURL: URL) async throws -> String {- let data: Data- do {- // Mapped: an IPA is whatever the user dropped on the window, and- // some are gigabytes. The bytes are handed straight to the upload,- // which chunks them, so nothing needs them resident at once.- data = try Data(contentsOf: localURL, options: .mappedIfSafe)- } catch {- throw ControlError.protocolError("failed to read IPA: \(error)")- }-- let remoteDir = "/var/mobile/Documents/vphone-installs"- let remoteName = "\(UUID().uuidString)-\(localURL.lastPathComponent)"- let remotePath = "\(remoteDir)/\(remoteName)"-- defer {- Task {- try? await deleteFile(path: remotePath)- }- }-- try await createDirectory(path: remoteDir)- try await uploadFile(path: remotePath, data: data)-- let request: [String: Any] = [- "t": "ipa_install",- "path": remotePath,- "registration": "User",- ]-- let (resp, _) = try await sendRequest(request)- if let detail = resp["msg"] as? String, !detail.isEmpty {- return detail- }- return "Installed \(localURL.lastPathComponent) through the built-in IPA installer."- }-- // MARK: - Clipboard-- struct ClipboardContent {- let text: String?- let types: [String]- let hasImage: Bool- let changeCount: Int- let imageData: Data?+ let data = try Data(contentsOf: localURL, options: .mappedIfSafe)+ let path = "/var/mobile/Documents/vphone-installs/\(UUID().uuidString)-\(localURL.lastPathComponent)"+ try await createDirectory(path: "/var/mobile/Documents/vphone-installs")+ try await uploadFile(path: path, data: data)+ defer { Task { try? await deleteFile(path: path) } }+ let result = try await call("apps.install", params: ["path": path, "registration": "User"])+ return result["msg"] as? String ?? "Installed \(localURL.lastPathComponent)."}func clipboardGet() async throws -> ClipboardContent {- let (resp, data) = try await sendRequest(["t": "clipboard_get"])- let text = resp["text"] as? String- let types = resp["types"] as? [String] ?? []- let hasImage = resp["has_image"] as? Bool ?? false- let changeCount = resp["change_count"] as? Int ?? 0- return ClipboardContent(- text: text,- types: types,- hasImage: hasImage,- changeCount: changeCount,- imageData: data- )+ let (info, image) = try await sendRequest(["t": "clipboard_get"])+ return ClipboardContent(text: info["text"] as? String, types: info["types"] as? [String] ?? [],+ hasImage: info["has_image"] as? Bool ?? false,+ changeCount: info["change_count"] as? Int ?? 0, imageData: image)}func clipboardSet(text: String) async throws {- _ = try await sendRequest(["t": "clipboard_set", "text": text])+ _ = try await call("clipboard.set", params: ["text": text])}func clipboardSet(imageData: Data) async throws {- guard let fd = connection?.fileDescriptor else {- throw ControlError.notConnected- }-- nextRequestId += 1- let reqId = String(nextRequestId, radix: 16)- let header: [String: Any] = [- "v": Self.protocolVersion,- "t": "clipboard_set",- "id": reqId,- "type": "image",- "size": imageData.count,- ]- let timeout = Self.timeoutForRequest(type: "clipboard_set")-- try await withCheckedThrowingContinuation {- (continuation: CheckedContinuation<Void, any Error>) in- addPending(id: reqId) { result in- switch result {- case .success: continuation.resume()- case let .failure(error): continuation.resume(throwing: error)- }- }- armRequestTimeout(id: reqId, type: "clipboard_set", timeout: timeout)-- guard writeMessage(fd: fd, dict: header) else {- _ = removePending(id: reqId)- continuation.resume(throwing: ControlError.notConnected)- return- }- let ok = imageData.withUnsafeBytes { buf in- Self.writeFully(fd: fd, buf: buf.baseAddress!, count: imageData.count)- }- guard ok else {- _ = removePending(id: reqId)- continuation.resume(throwing: ControlError.protocolError("failed to write image data"))- return- }- }+ let response = try await http(method: "PUT", path: "/v1/clipboard/image", body: imageData,+ contentType: "application/octet-stream")+ guard response.status == 200 else { throw try httpError(response) }}- // MARK: - Location-- func sendLocation(- latitude: Double,- longitude: Double,- altitude: Double,- horizontalAccuracy: Double,- verticalAccuracy: Double,- speed: Double,- course: Double- ) {- nextRequestId += 1- let msg: [String: Any] = [- "v": Self.protocolVersion,- "t": "location",- "id": String(nextRequestId, radix: 16),- "lat": latitude,- "lon": longitude,- "alt": altitude,- "hacc": horizontalAccuracy,- "vacc": verticalAccuracy,- "speed": speed,- "course": course,- "ts": Date().timeIntervalSince1970,- ]- guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else {- print("[control] sendLocation failed (not connected)")- return+ func sendLocation(latitude: Double, longitude: Double, altitude: Double,+ horizontalAccuracy: Double, verticalAccuracy: Double,+ speed: Double, course: Double) {+ Task {+ do { _ = try await call("location.set", params: [+ "latitude": latitude, "longitude": longitude, "altitude": altitude,+ "horizontal_accuracy": horizontalAccuracy, "vertical_accuracy": verticalAccuracy,+ "speed": speed, "course": course,+ ]) } catch { print("[control] location: \(error)") }}- print("[control] location lat=\(latitude) lon=\(longitude)")}func sendLocationStop() {- nextRequestId += 1- let msg: [String: Any] = [- "v": Self.protocolVersion,- "t": "location_stop",- "id": String(nextRequestId, radix: 16),- ]- if let fd = connection?.fileDescriptor { writeMessage(fd: fd, dict: msg) }- }-- // MARK: - Disconnect & Reconnect-- private func disconnect(ifCurrentAttempt expectedAttemptToken: UInt64? = nil) {- if let expectedAttemptToken, !isCurrentAttempt(expectedAttemptToken) {- return- }-- let reconnectAttemptToken = connectionAttemptToken- let wasConnected = isConnected- let hadConnection = connection != nil- let fd = connection?.fileDescriptor- connection = nil- isConnected = false- guestCaps = []- guestIP = nil-- // Fail all pending requests- failAllPending()-- if wasConnected {- onDisconnect?()- }-- if let fd {- Self.shutdownSocket(fd: fd)- }-- if hadConnection, device != nil {- scheduleReconnect(for: reconnectAttemptToken, reason: "connection lost")- }+ Task { do { _ = try await call("location.clear") }+ catch { print("[control] location clear: \(error)") } }}- // MARK: - Background Read Loop-- private func startReadLoop(fd: Int32, attemptToken: UInt64) {- DispatchQueue.global(qos: .utility).async { [weak self] in- while let msg = Self.readMessage(fd: fd) {- guard let self else { break }- let type = msg["t"] as? String ?? ""- let reqId = msg["id"] as? String-- // Check for pending request callback- if let reqId, let pending = removePending(id: reqId) {- nonisolated(unsafe) let safeMsg = msg-- if type == "err" {- let detail = msg["msg"] as? String ?? "unknown error"- DispatchQueue.main.async { pending.handler(.failure(ControlError.guestError(detail))) }- continue- }-- // For file_data, read inline binary payload- if type == "file_data" {- let size = msg["size"] as? Int ?? 0- if size > 0 {- let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: size)- if Self.readFully(fd: fd, buf: buf, count: size) {- let data = Data(bytes: buf, count: size)- buf.deallocate()- DispatchQueue.main.async { pending.handler(.success((safeMsg, data))) }- } else {- buf.deallocate()- DispatchQueue.main.async {- pending.handler(.failure(ControlError.protocolError("failed to read file data")))- }- }- } else {- DispatchQueue.main.async { pending.handler(.success((safeMsg, Data()))) }- }- continue- }-- // For clipboard_get with image, read inline binary payload- if type == "clipboard_get", msg["has_image"] as? Bool == true {- let size = msg["image_size"] as? Int ?? 0- if size > 0 {- let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: size)- if Self.readFully(fd: fd, buf: buf, count: size) {- let data = Data(bytes: buf, count: size)- buf.deallocate()- DispatchQueue.main.async { pending.handler(.success((safeMsg, data))) }- } else {- buf.deallocate()- DispatchQueue.main.async {- pending.handler(- .failure(ControlError.protocolError("failed to read clipboard image data"))- )- }- }- } else {- DispatchQueue.main.async { pending.handler(.success((safeMsg, nil))) }- }- continue- }-- // Normal response (ok, pong, etc.)- DispatchQueue.main.async { pending.handler(.success((safeMsg, nil))) }- continue- }-- // No pending request — handle as before (fire-and-forget)- switch type {- case "ok":- let detail = msg["msg"] as? String ?? ""- if !detail.isEmpty { print("[vphoned] ok: \(detail)") }- case "pong":- print("[vphoned] pong")- case "version":- let hash = msg["hash"] as? String ?? "unknown"- print("[vphoned] build: \(hash)")- case "err":- let detail = msg["msg"] as? String ?? "unknown"- print("[vphoned] error: \(detail)")- default:- print("[vphoned] \(msg)")- }- }- Task { @MainActor in- guard let self else { return }- guard self.isCurrentAttempt(attemptToken, fd: fd) else { return }- print("[control] read loop ended")- self.disconnect(ifCurrentAttempt: attemptToken)- }+ private func filePath(_ guestPath: String) throws -> String {+ guard guestPath.hasPrefix("/"), !guestPath.contains("\0") else {+ throw ControlError.protocolError("guest path must be absolute")}+ var components = URLComponents()+ components.path = "/v1/files/content"+ components.queryItems = [URLQueryItem(name: "path", value: guestPath)]+ return components.string ?? ""}- // MARK: - Reconnect Coordination-- private func isCurrentAttempt(_ attemptToken: UInt64, fd: Int32? = nil) -> Bool {- guard connectionAttemptToken == attemptToken else { return false }- guard let fd else { return true }- return connection?.fileDescriptor == fd- }-- private func cancelReconnect() {- reconnectWorkItem?.cancel()- reconnectWorkItem = nil- }-- private func scheduleReconnect(for attemptToken: UInt64, reason: String) {- guard isCurrentAttempt(attemptToken) else { return }- guard device != nil else { return }-- cancelReconnect()- let delay = Self.reconnectDelay- print("[control] \(reason); reconnecting in \(Int(delay.rounded()))s...")-- let workItem = DispatchWorkItem { [weak self] in- Task { @MainActor in- guard let self else { return }- guard self.isCurrentAttempt(attemptToken) else { return }- self.reconnectWorkItem = nil- self.loadGuestBinary()- self.attemptConnect()- }- }- reconnectWorkItem = workItem- DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem)- }-- private func armHandshakeTimeout(fd: Int32, attemptToken: UInt64) {- let timeout = Self.handshakeTimeout- DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in- guard let self else { return }- guard isCurrentAttempt(attemptToken, fd: fd) else { return }- guard !isConnected else { return }- print("[control] handshake timed out after \(Int(timeout.rounded()))s")- Self.shutdownSocket(fd: fd)- disconnect(ifCurrentAttempt: attemptToken)- }+ private func httpError(_ response: VPhoneHTTPResponse) throws -> ControlError {+ let body = try JSONSerialization.jsonObject(with: response.body) as? [String: Any]+ let error = body?["error"] as? [String: Any]+ return .guestError(error?["message"] as? String ?? "HTTP \(response.status)")}- // MARK: - Request Timeout-- private static func timeoutForRequest(type: String) -> TimeInterval {- switch type {- case "file_get", "file_put", "ipa_install":- transferRequestTimeout- case "devmode", "file_list", "file_delete", "file_rename", "file_mkdir", "keychain_list",- "app_list", "app_launch", "open_url", "accessibility_tree":- slowRequestTimeout- default:- defaultRequestTimeout+ private func http(method: String, path: String, body: Data = Data(),+ contentType: String = "application/json") async throws -> VPhoneHTTPResponse {+ guard let device else { throw ControlError.notConnected }+ let socket = await withCheckedContinuation {+ (continuation: CheckedContinuation<VPhoneSocketResult, Never>) in+ device.connect(toPort: 1339) { continuation.resume(returning: VPhoneSocketResult($0)) }}- }-- private func armRequestTimeout(id: String, type: String, timeout: TimeInterval) {- guard timeout > 0 else { return }- let timeoutSeconds = max(Int(timeout.rounded()), 1)- DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout) { [weak self] in- guard let self else { return }- guard let pending = removePending(id: id) else { return }- DispatchQueue.main.async {- pending.handler(.failure(ControlError.requestTimedOut(type: type, seconds: timeoutSeconds)))+ let connection = try socket.result.get()+ let transaction = VPhoneHTTPTransaction(connection: connection, method: method, path: path,+ body: body, contentType: contentType)+ return try await withCheckedThrowingContinuation { continuation in+ DispatchQueue.global(qos: .userInitiated).async {+ do { continuation.resume(returning: try transaction.run()) }+ catch { continuation.resume(throwing: error) }}}}+}- // MARK: - Framing: Length-Prefixed JSON-- @discardableResult- private func writeMessage(fd: Int32, dict: [String: Any]) -> Bool {- guard let json = try? JSONSerialization.data(withJSONObject: dict) else { return false }- let length = UInt32(json.count)- var header = length.bigEndian- let headerOK = withUnsafeBytes(of: &header) { buf in- Darwin.write(fd, buf.baseAddress!, 4) == 4- }- guard headerOK else { return false }- return json.withUnsafeBytes { buf in- Darwin.write(fd, buf.baseAddress!, json.count) == json.count- }- }-- private nonisolated static func readMessage(fd: Int32) -> [String: Any]? {- var header: UInt32 = 0- let hRead = withUnsafeMutableBytes(of: &header) { buf in- readFully(fd: fd, buf: buf.baseAddress!, count: 4)- }- guard hRead else { return nil }-- let length = Int(UInt32(bigEndian: header))- guard length > 0, length < 4 * 1024 * 1024 else { return nil }-- let payload = UnsafeMutablePointer<UInt8>.allocate(capacity: length)- defer { payload.deallocate() }- guard readFully(fd: fd, buf: payload, count: length) else { return nil }-- let data = Data(bytes: payload, count: length)- return try? JSONSerialization.jsonObject(with: data) as? [String: Any]- }+private struct VPhoneHTTPResponse: Sendable {+ let status: Int+ let body: Data+}- private nonisolated static func readFully(fd: Int32, buf: UnsafeMutableRawPointer, count: Int)- -> Bool- {- var offset = 0- while offset < count {- let n = Darwin.read(fd, buf + offset, count - offset)- if n <= 0 { return false }- offset += n- }- return true- }+private struct VPhoneSocketResult: @unchecked Sendable {+ let result: Result<VZVirtioSocketConnection, any Error>+ init(_ result: Result<VZVirtioSocketConnection, any Error>) { self.result = result }+}- private nonisolated static func writeFully(fd: Int32, buf: UnsafeRawPointer, count: Int) -> Bool {- var offset = 0- while offset < count {- let n = Darwin.write(fd, buf + offset, count - offset)- if n <= 0 { return false }- offset += n+private final class VPhoneHTTPTransaction: @unchecked Sendable {+ let connection: VZVirtioSocketConnection+ let method: String+ let path: String+ let body: Data+ let contentType: String++ init(connection: VZVirtioSocketConnection, method: String, path: String,+ body: Data, contentType: String) {+ self.connection = connection+ self.method = method+ self.path = path+ self.body = body+ self.contentType = contentType+ }++ func run() throws -> VPhoneHTTPResponse {+ let fd = connection.fileDescriptor+ var noSigPipe: Int32 = 1+ _ = withUnsafePointer(to: &noSigPipe) {+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, $0, socklen_t(MemoryLayout<Int32>.size))+ }+ let headers = "\(method) \(path) HTTP/1.1\r\nHost: vphoned\r\nConnection: close\r\nContent-Type: \(contentType)\r\nContent-Length: \(body.count)\r\n\r\n"+ try write(fd, data: Data(headers.utf8))+ if !body.isEmpty { try write(fd, data: body) }++ var received = Data()+ let marker = Data("\r\n\r\n".utf8)+ while received.range(of: marker) == nil {+ guard received.count < 64 * 1024 else { throw VPhoneControl.ControlError.protocolError("HTTP headers too large") }+ try readMore(fd, into: &received)+ }+ let boundary = received.range(of: marker)!+ let header = String(decoding: received[..<boundary.lowerBound], as: UTF8.self)+ let lines = header.components(separatedBy: "\r\n")+ guard let first = lines.first, let status = Int(first.split(separator: " ").dropFirst().first ?? "") else {+ throw VPhoneControl.ControlError.protocolError("invalid HTTP status")+ }+ guard let lengthLine = lines.first(where: { $0.lowercased().hasPrefix("content-length:") }),+ let length = Int(lengthLine.split(separator: ":", maxSplits: 1)[1].trimmingCharacters(in: .whitespaces)),+ length >= 0, length <= 2_147_483_647 else {+ throw VPhoneControl.ControlError.protocolError("missing HTTP content length")+ }+ var payload = Data(received[boundary.upperBound...])+ while payload.count < length { try readMore(fd, into: &payload) }+ guard payload.count == length else {+ throw VPhoneControl.ControlError.protocolError("HTTP body length mismatch")+ }+ return VPhoneHTTPResponse(status: status, body: payload)+ }++ private func write(_ fd: Int32, data: Data) throws {+ try data.withUnsafeBytes { bytes in+ guard let base = bytes.baseAddress else { return }+ var offset = 0+ while offset < bytes.count {+ let sent = Darwin.write(fd, base + offset, bytes.count - offset)+ if sent <= 0 { throw VPhoneControl.ControlError.notConnected }+ offset += sent+ }}- return true}- private nonisolated static func shutdownSocket(fd: Int32) {- _ = Darwin.shutdown(fd, SHUT_RDWR)+ private func readMore(_ fd: Int32, into data: inout Data) throws {+ var bytes = [UInt8](repeating: 0, count: 32 * 1024)+ let count = Darwin.read(fd, &bytes, bytes.count)+ guard count > 0 else { throw VPhoneControl.ControlError.notConnected }+ data.append(contentsOf: bytes[..<count])}}diff --git a/sources/VPhoneVMKit/VM/VPhoneError.swift b/sources/VPhoneVMKit/VM/VPhoneError.swiftindex a24b3e2a..36e43ca3 100644--- a/sources/VPhoneVMKit/VM/VPhoneError.swift+++ b/sources/VPhoneVMKit/VM/VPhoneError.swift@@ -5,6 +5,7 @@ enum VPhoneError: Error, CustomStringConvertible {case romNotFound(String)case diskNotFound(String)case invalidKernelDebugPort(Int)+ case apiSocketUnavailablevar description: String {switch self {@@ -22,6 +23,8 @@ enum VPhoneError: Error, CustomStringConvertible {"Disk image not found: \(p)"case let .invalidKernelDebugPort(port):"Invalid kernel debug port: \(port) (expected 6000...65535)"+ case .apiSocketUnavailable:+ "VM has no VSOCK device for the API proxy"}}}diff --git a/sources/VPhoneVMKit/VPhoneAppDelegate.swift b/sources/VPhoneVMKit/VPhoneAppDelegate.swiftindex 5ae0cee4..604fcd43 100644--- a/sources/VPhoneVMKit/VPhoneAppDelegate.swift+++ b/sources/VPhoneVMKit/VPhoneAppDelegate.swift@@ -15,6 +15,7 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {private var locationProvider: VPhoneLocationProvider?private var hostControl: VPhoneHostControl?private var cameraServer: VPhoneCameraServer?+ private var apiProxy: VPhoneAPIProxy?private var sigintSource: DispatchSourceSignal?private var didAttemptAutoInstall = false@@ -95,6 +96,15 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {if let device = vm.virtualMachine.socketDevices.first as? VZVirtioSocketDevice {control.connect(device: device)camServer.connect(device: device)+ if let listen = cli.apiListen {+ let proxy = try VPhoneAPIProxy(device: device, listen: listen)+ let url = try await proxy.start()+ apiProxy = proxy+ print("[api] HTTP/WebSocket API: \(url.absoluteString)")+ print("[api] OpenAPI: \(url.appending(path: "openapi.json").absoluteString)")+ }+ } else if cli.apiListen != nil {+ throw VPhoneError.apiSocketUnavailable}}@@ -256,6 +266,8 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {func applicationWillTerminate(_: Notification) {hostControl?.stop()+ apiProxy?.stop()+ control?.stop()}func applicationShouldTerminateAfterLastWindowClosed(_: NSApplication) -> Bool {diff --git a/sources/vphone-cli/VPhoneCFWInstaller.swift b/sources/vphone-cli/VPhoneCFWInstaller.swiftindex 95484830..ac90eecc 100644--- a/sources/vphone-cli/VPhoneCFWInstaller.swift+++ b/sources/vphone-cli/VPhoneCFWInstaller.swift@@ -214,6 +214,8 @@ struct VPhoneCFWInstaller {try VPhoneSigner.sign(fileAt: staged,options: .init(entitlements: entitlements, mergesExisting: true))try replace(staged, at: system.appendingPathComponent("usr/bin/vphoned"), mode: 0o755)+ let icli = try VPhoneGuestBinaries.resolve("icli")+ try replace(icli, at: system.appendingPathComponent("usr/bin/icli"), mode: 0o755)let signed = bundle.appendingPathComponent(".vphoned.signed")if fm.fileExists(atPath: signed.path) { try fm.removeItem(at: signed) }try fm.copyItem(at: staged, to: signed)diff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swiftindex f9961e0c..f1b4d3bd 100644--- a/sources/vphone-cli/VPhoneVMLaunchCLI.swift+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift@@ -12,6 +12,8 @@ struct VPhoneVMLaunchCommand: ParsableCommand {@Argument(help: "VM name") var name: String?@Flag(name: .shortAndLong, help: "Boot into DFU mode (headless)") var dfu = false@Flag(name: .customLong("headless"), help: "Boot without a VM window or menu bar") var headless = false+ @Option(help: "Expose the guest HTTP/WebSocket API on host:port (for example 127.0.0.1:8765)")+ var apiListen: String?@Option(help: "Kernel GDB debug stub port on host (omit for system-assigned; valid: 6000...65535)")var kernelDebugPort: Int?@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")@@ -19,6 +21,12 @@ struct VPhoneVMLaunchCommand: ParsableCommand {@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")var verboseCount: Int+ func validate() throws {+ if dfu, apiListen != nil {+ throw ValidationError("`--api-listen` is unavailable with `--dfu`.")+ }+ }+func run() throws {let v = VPhoneVerbosity(count: verboseCount)let name = try VPhoneVMSelection.resolveExisting(name, in: lib.library)@@ -44,6 +52,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {var args = ["--config", bundle.configURL.path]if dfu { args.append("--dfu") }if headless { args.append("--headless") }+ if let apiListen { args += ["--api-listen", apiListen] }if let kernelDebugPort { args += ["--kernel-debug-port", String(kernelDebugPort)] }if v.tracesInternals {