Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add vphone-launchpad-cli, a command line client of the running Launchpad

Lakrbe7f061ecf6a
diff --git a/AGENTS.md b/AGENTS.md
index 46db64ce..0e1cebda 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -49,7 +49,7 @@ See `Research/` for detailed firmware pipeline, component origins, patch breakdo
- `VPhoneKit`: shared core, archive, and external access kits with their tests.
- `VPhoneDaemon`: guest `vphoned`, native operations, and daemon configuration.
- `VPhoneGuestComponents`: guest dylibs built by Makefile from the bundle build phase.
-- `VPhoneLaunchpad`: `vphone-launchpad.app`, the workstation app that downloads and manages `VPhone.bundle` releases and drives VMs through the active bundle's `vphone-cli`, plus its SMJobBless helper `com.vphone.launchpad.helper`. Shipped separately from the bundle. Settings live only in `VPhoneLaunchpad/Configuration/*.xcconfig`; the pbxproj holds none.
+- `VPhoneLaunchpad`: `vphone-launchpad.app`, the workstation app that downloads and manages `VPhone.bundle` releases and drives VMs through the active bundle's `vphone-cli`, plus its SMJobBless helper `com.vphone.launchpad.helper` and `vphone-launchpad-cli`, a stateless client of the running app over a same-user Unix socket (`Documents/Guides/launchpad-cli.md`; use it to install and test a local `VPhone.bundle` build). Shipped separately from the bundle. Settings live only in `VPhoneLaunchpad/Configuration/*.xcconfig`; the pbxproj holds none.
The `VPhone` scheme puts host programs in `VPhone.bundle/Contents/MacOS` and everything installed into the guest (vphoned, guest dylibs, their plists) in `Contents/Resources/guest-resources`. Xcode targets have `CODE_SIGNING_ALLOWED=NO`; the bundle build phase signs each binary ad hoc with only its own entitlements, then seals the outer bundle. `VPhoneVirtualization.entitlements` belongs to `vphone-vm`; `VPhoneDaemon.entitlements` belongs to `vphoned`. The bundle and CLI have no private entitlements.
diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.md
new file mode 100644
index 00000000..060a8543
--- /dev/null
+++ b/Documents/Guides/launchpad-cli.md
@@ -0,0 +1,70 @@
+# Launchpad command line
+
+`vphone-launchpad-cli` ships in `vphone-launchpad.app/Contents/MacOS`. It
+drives the running Launchpad over a Unix socket at
+`~/Library/Application Support/vphone-launchpad/control.sock` (mode 0600,
+served only to the same user) and starts Launchpad in the background when it
+is not running. It has no privileges and no state of its own: bundles are
+installed through Launchpad's helper, machines run through the active
+bundle's `vphone-cli`, and every command appears in Launchpad's window and
+command history. Nothing listens on the network; reach it over ssh from
+another machine.
+
+Progress lines go to stderr as they arrive. The result is one JSON document on
+stdout. The exit status is 0 on success and 1 on failure, with the reason on
+stderr. Interrupting the CLI cancels a command that can be cancelled
+(`exec`, waits, CFW install); a bundle install or machine creation belongs to
+the window and keeps running.
+
+```sh
+ln -s /Applications/vphone-launchpad.app/Contents/MacOS/vphone-launchpad-cli /usr/local/bin/
+vphone-launchpad-cli help
+```
+
+## Testing a VPhone.bundle build
+
+```sh
+xcodebuild -workspace VPhone.xcworkspace -scheme VPhone \
+ -configuration Debug -destination 'platform=macOS,arch=arm64' \
+ -derivedDataPath .build/XcodeBundle build
+
+# Installs as <version>-local, makes it active, adds the execution policy
+# exception, allows the new vphone-vm cdhash and runs host preflight.
+vphone-launchpad-cli bundle install-local .build/XcodeBundle/Build/Products/Debug/VPhone.bundle
+
+vphone-launchpad-cli vm start research-01 --wait
+vphone-launchpad-cli guest rpc research-01 device.info
+vphone-launchpad-cli guest rpc research-01 apps.list '{}'
+vphone-launchpad-cli vm log research-01 --lines 100
+vphone-launchpad-cli vm stop research-01
+
+# The same checks against the release it replaces.
+vphone-launchpad-cli bundle use 2.0.9
+```
+
+The first step that needs the helper after its five-minute authorization
+expires asks for an administrator password on the Mac, as the window does.
+
+## Commands
+
+| Command | Does |
+| --- | --- |
+| `status` | Host checks, helper, active bundle, machine counts |
+| `bundle list` | Installed versions, receipts, cdhashes and check results |
+| `bundle install-local <path>` | Install a local `VPhone.bundle` folder or `.zip` |
+| `bundle install-release <version\|latest>` | Download and install a GitHub release |
+| `bundle use <version>` / `bundle verify <version>` | Switch to or re-check an installed version |
+| `bundle accept <version> [--off]` / `bundle remove <version>` | Skip failed checks, or remove a version |
+| `vm list` | Machines in every library with run state and log path |
+| `vm start <name> [--headless] [--wait]` / `vm stop <name>` | Launch or stop; `--wait` waits for vphoned |
+| `vm wait <name>` / `vm log <name> [--kind create\|dfu]` | Wait for vphoned; read a console log |
+| `vm create <name> [...] [--from <step>]` | The New Machine pipeline; `--from` retries from a step |
+| `cfw install <name>` | Install CFW into a stopped machine through the helper |
+| `guest send <name> <json>` | One raw `vphone.sock` request (tap, swipe, key, screenshot) |
+| `guest rpc <name> <method> [params]` | Any vphoned method, see `Research/vphoned_http_api.md` |
+| `exec <vphone-cli arguments>` | Run the active bundle's `vphone-cli`, streaming its output |
+
+Machine commands take `--root <library>` when two libraries hold a machine
+with the same name. `guest` commands and `--wait` go through the machine's
+`vphone.sock`, which every launch serves; bundles up to 2.0.9 serve it only
+for machines launched with a window.
diff --git a/VPhoneLaunchpad/Build/SignLaunchpad.sh b/VPhoneLaunchpad/Build/SignLaunchpad.sh
index 567cdd81..74054afe 100644
--- a/VPhoneLaunchpad/Build/SignLaunchpad.sh
+++ b/VPhoneLaunchpad/Build/SignLaunchpad.sh
@@ -6,8 +6,8 @@
#
# zsh VPhoneLaunchpad/Build/SignLaunchpad.sh <path/to/vphone-launchpad.app> "Developer ID Application: …"
#
-# The helper is signed before the app that seals it. Neither gets
-# entitlements. Afterwards the helper is checked against the app's
+# The helper and the command line tool are signed before the app that seals
+# them. None of them gets entitlements. Afterwards the helper is checked against the app's
# SMPrivilegedExecutables requirement, which is what SMJobBless enforces.
set -euo pipefail
@@ -23,6 +23,8 @@ if [[ $requirement == *'subject.OU] = ""'* ]]; then
fi
codesign --force --options runtime --timestamp --sign "$identity" "$helper"
+codesign --force --options runtime --timestamp --identifier com.vphone.launchpad.cli \
+ --sign "$identity" "$app/Contents/MacOS/vphone-launchpad-cli"
codesign --force --options runtime --timestamp --sign "$identity" "$app"
codesign --verify --strict --deep "$app"
diff --git a/VPhoneLaunchpad/Configuration/VPhoneLaunchpadCLI.xcconfig b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadCLI.xcconfig
new file mode 100644
index 00000000..92ced4d3
--- /dev/null
+++ b/VPhoneLaunchpad/Configuration/VPhoneLaunchpadCLI.xcconfig
@@ -0,0 +1,11 @@
+// The command line tool. It ships in the app's Contents/MacOS and talks to
+// the running app over its control socket; it links nothing but the system.
+
+PRODUCT_NAME = vphone-launchpad-cli
+PRODUCT_MODULE_NAME = VPhoneLaunchpadCLI
+PRODUCT_BUNDLE_IDENTIFIER = com.vphone.launchpad.cli
+// Embedded in the app, never installed on its own.
+SKIP_INSTALL = YES
+
+// Top-level code and blocking socket reads: nothing here is UI.
+SWIFT_DEFAULT_ACTOR_ISOLATION = nonisolated
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
index 817674c5..54d00b56 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
+++ b/VPhoneLaunchpad/VPhoneLaunchpad.xcodeproj/project.pbxproj
@@ -7,12 +7,15 @@
/* Begin PBXBuildFile section */
5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */ = {isa = PBXBuildFile; fileRef = 5A1000000000000000000032 /* com.vphone.launchpad.helper */; };
5A1000000000000000000062 /* GhosttyTerminal in Frameworks */ = {isa = PBXBuildFile; productRef = 5A10000000000000000000B1 /* GhosttyTerminal */; };
+ 5A10000000000000000000CC /* vphone-launchpad-cli in Embed Command Line Tool */ = {isa = PBXBuildFile; fileRef = 5A10000000000000000000C1 /* vphone-launchpad-cli */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5A1000000000000000000071 /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A1000000000000000000012; remoteInfo = VPhoneLaunchpadHelper; };
+ 5A10000000000000000000CA /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy; containerPortal = 5A1000000000000000000001 /* Project object */; proxyType = 1; remoteGlobalIDString = 5A10000000000000000000C4; remoteInfo = VPhoneLaunchpadCLI; };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
5A1000000000000000000053 /* Embed Privileged Helper */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = Contents/Library/LaunchServices; dstSubfolderSpec = 1; files = (5A1000000000000000000061 /* com.vphone.launchpad.helper in Embed Privileged Helper */, ); name = "Embed Privileged Helper"; runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000CD /* Embed Command Line Tool */ = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 6; files = (5A10000000000000000000CC /* vphone-launchpad-cli in Embed Command Line Tool */, ); name = "Embed Command Line Tool"; runOnlyForDeploymentPostprocessing = 0; };
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
5A1000000000000000000031 /* vphone-launchpad.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "vphone-launchpad.app"; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -26,29 +29,36 @@
5A1000000000000000000039 /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpad.xcconfig; sourceTree = "<group>"; };
5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpadHelper.xcconfig; sourceTree = "<group>"; };
+ 5A10000000000000000000C1 /* vphone-launchpad-cli */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "vphone-launchpad-cli"; sourceTree = BUILT_PRODUCTS_DIR; };
+ 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = VPhoneLaunchpadCLI.xcconfig; sourceTree = "<group>"; };
/* End PBXFileReference section */
+/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
+ 5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */ = {isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = (VPhoneLaunchpadControl.swift, ); target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; };
+/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
5A1000000000000000000021 /* VPhoneLaunchpad */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpad; sourceTree = "<group>"; };
5A1000000000000000000022 /* VPhoneLaunchpadHelper */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadHelper; sourceTree = "<group>"; };
- 5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };
+ 5A1000000000000000000023 /* VPhoneLaunchpadShared */ = {isa = PBXFileSystemSynchronizedRootGroup; exceptions = (5A10000000000000000000CE /* PBXFileSystemSynchronizedBuildFileExceptionSet */, ); explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadShared; sourceTree = "<group>"; };
+ 5A10000000000000000000C3 /* VPhoneLaunchpadCLI */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VPhoneLaunchpadCLI; sourceTree = "<group>"; };
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
5A1000000000000000000041 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (5A1000000000000000000062 /* GhosttyTerminal in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; };
5A1000000000000000000042 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000C6 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
- 5A1000000000000000000002 = {isa = PBXGroup; children = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, 5A1000000000000000000004 /* Configuration */, 5A1000000000000000000005 /* Resources */, 5A1000000000000000000003 /* Products */, ); sourceTree = "<group>"; };
- 5A1000000000000000000003 /* Products */ = {isa = PBXGroup; children = (5A1000000000000000000031 /* vphone-launchpad.app */, 5A1000000000000000000032 /* com.vphone.launchpad.helper */, ); name = Products; sourceTree = "<group>"; };
- 5A1000000000000000000004 /* Configuration */ = {isa = PBXGroup; children = (5A1000000000000000000037 /* Version.xcconfig */, 5A1000000000000000000033 /* Base.xcconfig */, 5A1000000000000000000038 /* Development.xcconfig */, 5A1000000000000000000039 /* Release.xcconfig */, 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */, 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */, ); path = Configuration; sourceTree = "<group>"; };
+ 5A1000000000000000000002 = {isa = PBXGroup; children = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000022 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C3 /* VPhoneLaunchpadCLI */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, 5A1000000000000000000004 /* Configuration */, 5A1000000000000000000005 /* Resources */, 5A1000000000000000000003 /* Products */, ); sourceTree = "<group>"; };
+ 5A1000000000000000000003 /* Products */ = {isa = PBXGroup; children = (5A1000000000000000000031 /* vphone-launchpad.app */, 5A1000000000000000000032 /* com.vphone.launchpad.helper */, 5A10000000000000000000C1 /* vphone-launchpad-cli */, ); name = Products; sourceTree = "<group>"; };
+ 5A1000000000000000000004 /* Configuration */ = {isa = PBXGroup; children = (5A1000000000000000000037 /* Version.xcconfig */, 5A1000000000000000000033 /* Base.xcconfig */, 5A1000000000000000000038 /* Development.xcconfig */, 5A1000000000000000000039 /* Release.xcconfig */, 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */, 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */, 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */, ); path = Configuration; sourceTree = "<group>"; };
5A1000000000000000000005 /* Resources */ = {isa = PBXGroup; children = (5A1000000000000000000034 /* VPhoneLaunchpad.Info.plist */, 5A1000000000000000000035 /* VPhoneLaunchpadHelper.Info.plist */, 5A1000000000000000000036 /* VPhoneLaunchpadHelper.Launchd.plist */, ); path = Resources; sourceTree = "<group>"; };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
5A1000000000000000000011 /* VPhoneLaunchpad */ = {
isa = PBXNativeTarget;
buildConfigurationList = 5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */;
- buildPhases = (5A1000000000000000000051 /* Sources */, 5A1000000000000000000041 /* Frameworks */, 5A1000000000000000000052 /* Resources */, 5A1000000000000000000053 /* Embed Privileged Helper */, );
+ buildPhases = (5A1000000000000000000051 /* Sources */, 5A1000000000000000000041 /* Frameworks */, 5A1000000000000000000052 /* Resources */, 5A1000000000000000000053 /* Embed Privileged Helper */, 5A10000000000000000000CD /* Embed Command Line Tool */, );
buildRules = ();
- dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, );
+ dependencies = (5A1000000000000000000072 /* PBXTargetDependency */, 5A10000000000000000000CB /* PBXTargetDependency */, );
fileSystemSynchronizedGroups = (5A1000000000000000000021 /* VPhoneLaunchpad */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
name = VPhoneLaunchpad;
packageProductDependencies = (5A10000000000000000000B1 /* GhosttyTerminal */, );
@@ -68,6 +78,18 @@
productReference = 5A1000000000000000000032 /* com.vphone.launchpad.helper */;
productType = "com.apple.product-type.tool";
};
+ 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 5A10000000000000000000C9 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadCLI" */;
+ buildPhases = (5A10000000000000000000C5 /* Sources */, 5A10000000000000000000C6 /* Frameworks */, );
+ buildRules = ();
+ dependencies = ();
+ fileSystemSynchronizedGroups = (5A10000000000000000000C3 /* VPhoneLaunchpadCLI */, 5A1000000000000000000023 /* VPhoneLaunchpadShared */, );
+ name = VPhoneLaunchpadCLI;
+ productName = VPhoneLaunchpadCLI;
+ productReference = 5A10000000000000000000C1 /* vphone-launchpad-cli */;
+ productType = "com.apple.product-type.tool";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
5A1000000000000000000001 /* Project object */ = {
@@ -82,7 +104,7 @@
productRefGroup = 5A1000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
- targets = (5A1000000000000000000011 /* VPhoneLaunchpad */, 5A1000000000000000000012 /* VPhoneLaunchpadHelper */, );
+ targets = (5A1000000000000000000011 /* VPhoneLaunchpad */, 5A1000000000000000000012 /* VPhoneLaunchpadHelper */, 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */, );
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
@@ -91,9 +113,11 @@
/* Begin PBXSourcesBuildPhase section */
5A1000000000000000000051 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
5A1000000000000000000054 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
+ 5A10000000000000000000C5 /* Sources */ = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5A1000000000000000000072 /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A1000000000000000000012 /* VPhoneLaunchpadHelper */; targetProxy = 5A1000000000000000000071 /* PBXContainerItemProxy */; };
+ 5A10000000000000000000CB /* PBXTargetDependency */ = {isa = PBXTargetDependency; target = 5A10000000000000000000C4 /* VPhoneLaunchpadCLI */; targetProxy = 5A10000000000000000000CA /* PBXContainerItemProxy */; };
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
5A1000000000000000000081 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A1000000000000000000038 /* Development.xcconfig */; buildSettings = {}; name = Debug; };
@@ -102,11 +126,14 @@
5A1000000000000000000084 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003A /* VPhoneLaunchpad.xcconfig */; buildSettings = {}; name = Release; };
5A1000000000000000000085 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */; buildSettings = {}; name = Debug; };
5A1000000000000000000086 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A100000000000000000003B /* VPhoneLaunchpadHelper.xcconfig */; buildSettings = {}; name = Release; };
+ 5A10000000000000000000C7 /* Debug */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */; buildSettings = {}; name = Debug; };
+ 5A10000000000000000000C8 /* Release */ = {isa = XCBuildConfiguration; baseConfigurationReference = 5A10000000000000000000C2 /* VPhoneLaunchpadCLI.xcconfig */; buildSettings = {}; name = Release; };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
5A1000000000000000000091 /* Build configuration list for PBXProject "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000081 /* Debug */, 5A1000000000000000000082 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
5A1000000000000000000092 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpad" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000083 /* Debug */, 5A1000000000000000000084 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
5A1000000000000000000093 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadHelper" */ = {isa = XCConfigurationList; buildConfigurations = (5A1000000000000000000085 /* Debug */, 5A1000000000000000000086 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
+ 5A10000000000000000000C9 /* Build configuration list for PBXNativeTarget "VPhoneLaunchpadCLI" */ = {isa = XCConfigurationList; buildConfigurations = (5A10000000000000000000C7 /* Debug */, 5A10000000000000000000C8 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
5A10000000000000000000A1 /* XCRemoteSwiftPackageReference "libghostty-spm" */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/Lakr233/libghostty-spm.git"; requirement = {kind = upToNextMajorVersion; minimumVersion = 1.6.20260928; }; };
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
index 5d7f2eb2..08d13b73 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
@@ -73,6 +73,7 @@ final class VPhoneLaunchpadModel {
return
}
#endif
+ startControl()
// Host checks, installed bundles and the helper state were read at
// init. These confirm them without holding up the machine list; the
// network probe and the GitHub lists come last.
@@ -95,6 +96,25 @@ final class VPhoneLaunchpadModel {
await bundles.fetchArtifacts()
}
+ // MARK: - Command line
+
+ /// Serves `vphone-launchpad-cli` for as long as the app runs. Without the
+ /// socket the window works as before; the CLI then says it cannot connect.
+ private var control: VPhoneLaunchpadControlServer?
+
+ private func startControl() {
+ let commands = VPhoneLaunchpadControlCommands(model: self)
+ let server = VPhoneLaunchpadControlServer { request, emit in
+ await commands.handle(request, emit: emit)
+ }
+ do {
+ try server.start()
+ control = server
+ } catch {
+ print("[control] \(VPhoneLaunchpadError.message(for: error))")
+ }
+ }
+
func refreshHost() async {
await host.refresh()
}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
new file mode 100644
index 00000000..60af43fb
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift
@@ -0,0 +1,721 @@
+import Foundation
+
+/// Runs `vphone-launchpad-cli` requests against the same model the window
+/// shows. Every command goes through the methods the UI calls, so what the
+/// CLI does appears in the window and the command history, and root still
+/// comes only from the helper's fixed verbs.
+@MainActor
+struct VPhoneLaunchpadControlCommands {
+ typealias Emit = VPhoneLaunchpadControlServer.Emit
+
+ let model: VPhoneLaunchpadModel
+
+ private var bundles: VPhoneLaunchpadCoreBundle {
+ model.bundles
+ }
+
+ private var library: VPhoneLaunchpadMachineLibrary {
+ model.machines
+ }
+
+ func handle(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async -> VPhoneLaunchpadControlEvent {
+ do {
+ let result = try await perform(request, emit: emit)
+ let data = try JSONSerialization.data(
+ withJSONObject: result,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes, .fragmentsAllowed],
+ )
+ return .success(String(decoding: data, as: UTF8.self))
+ } catch is CancellationError {
+ return .failure("Cancelled.")
+ } catch {
+ return .failure(error.localizedDescription, detail: (error as? VPhoneLaunchpadError)?.detail)
+ }
+ }
+
+ private func perform(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ guard let command = VPhoneLaunchpadControlCommand.named(request.command) else {
+ throw VPhoneLaunchpadError("Unknown command \(request.command).")
+ }
+ let minimum = command.takesRest ? command.arguments.count - 1 : command.arguments.count
+ guard request.arguments.count >= minimum else {
+ throw VPhoneLaunchpadError("Usage: \(command.usage)")
+ }
+ switch command.name {
+ case "status": return status()
+ case "bundle.list": return bundles.installed.map(report)
+ case "bundle.install-local": return try await installLocal(request, emit: emit)
+ case "bundle.install-release": return try await installRelease(request, emit: emit)
+ case "bundle.use": return try await use(request)
+ case "bundle.verify": return try await verify(request)
+ case "bundle.accept": return try accept(request)
+ case "bundle.remove": return try await remove(request)
+ case "vm.list": return await listMachines()
+ case "vm.start": return try await startMachine(request, emit: emit)
+ case "vm.stop": return try await stopMachine(request)
+ case "vm.wait": return try await waitMachine(request, emit: emit)
+ case "vm.log": return try await log(request)
+ case "vm.create": return try await create(request, emit: emit)
+ case "cfw.install": return try await installCustomFirmware(request, emit: emit)
+ case "guest.send": return try await sendToGuest(request)
+ case "guest.rpc": return try await callGuest(request)
+ case "exec": return try await exec(request, emit: emit)
+ default: throw VPhoneLaunchpadError("\(command.name) is not handled by this Launchpad.")
+ }
+ }
+
+ // MARK: - Status
+
+ private func status() -> [String: Any] {
+ let helper: String = switch model.helper.state {
+ case .unknown: "unknown"
+ case .notInstalled: "not installed"
+ case let .outdated(installed, bundled): "outdated (\(installed), app has \(bundled))"
+ case let .ready(version): "ready (\(version))"
+ case .unconfigured: "unconfigured (built without a team)"
+ }
+ return [
+ "helper": helper,
+ "hostReady": model.host.requiredPassed,
+ "developerTools": model.host.isDeveloperToolAuthorized,
+ "canInstallBundles": model.canInstallBundles,
+ "activeBundle": bundles.activeVersion ?? NSNull(),
+ "bundleReady": bundles.isReady,
+ "installing": bundles.isInstalling,
+ "machines": library.machines.count,
+ "running": library.runningCount,
+ "libraries": library.roots,
+ ]
+ }
+
+ // MARK: - Bundles
+
+ private func report(_ item: VPhoneLaunchpadCoreBundle.Installed) -> [String: Any] {
+ [
+ "version": item.version,
+ "active": item.version == bundles.activeVersion,
+ "accepted": bundles.isAccepted(item.version),
+ "policy": item.policy.rawValue,
+ "preflight": item.preflight.rawValue,
+ "preflightDetail": item.preflightDetail,
+ "sha256": item.receipt.sha256,
+ "installedAt": ISO8601DateFormatter().string(from: item.receipt.installedAt),
+ "cdhashes": item.receipt.cdhashes,
+ "path": VPhoneLaunchpadBundleStore.bundle(version: item.version).path,
+ ]
+ }
+
+ private func installed(_ version: String) throws -> VPhoneLaunchpadCoreBundle.Installed {
+ guard let item = bundles.installed.first(where: { $0.version == version }) else {
+ throw VPhoneLaunchpadError("VPhone.bundle \(version) is not installed.")
+ }
+ return item
+ }
+
+ private func requireInstallable() throws {
+ guard !model.canInstallBundles else {
+ return
+ }
+ if bundles.isInstalling {
+ throw VPhoneLaunchpadError("Another bundle install is running.")
+ }
+ guard case .ready = model.helper.state else {
+ throw VPhoneLaunchpadError("The helper is not installed or is outdated. Install it in Host Setup.")
+ }
+ throw VPhoneLaunchpadError("Launchpad does not have Developer Tools access. Allow it in Host Setup, then relaunch Launchpad.")
+ }
+
+ private func installLocal(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let path = request.arguments[0]
+ guard path.hasPrefix("/") else {
+ throw VPhoneLaunchpadError("The bundle path must be absolute.")
+ }
+ try requireInstallable()
+ return try await watchInstall(emit: emit) {
+ await model.installLocalBundle(URL(fileURLWithPath: path))
+ }
+ }
+
+ private func installRelease(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ try requireInstallable()
+ let wanted = request.arguments[0]
+ if bundles.releases.isEmpty {
+ await bundles.fetchReleases()
+ }
+ let release = wanted == "latest"
+ ? bundles.releases.first
+ : bundles.releases.first { $0.version == wanted }
+ guard let release else {
+ throw VPhoneLaunchpadError("No release \(wanted) was found.", detail: bundles.releasesError)
+ }
+ return try await watchInstall(emit: emit) {
+ await model.installBundle(release)
+ }
+ }
+
+ /// Runs an install and reports each step as it changes. The install is
+ /// the window's own, so it goes on if the CLI is interrupted.
+ private func watchInstall(emit: @escaping Emit, _ install: () async -> Void) async throws -> Any {
+ let watcher = Task { @MainActor in
+ var reported: [VPhoneLaunchpadCoreBundle.InstallStep: VPhoneLaunchpadStatus] = [:]
+ while !Task.isCancelled {
+ reportSteps(&reported, emit: emit)
+ try? await Task.sleep(for: .milliseconds(300))
+ }
+ reportSteps(&reported, emit: emit)
+ }
+ await install()
+ watcher.cancel()
+ await watcher.value
+ guard let progress = bundles.progress else {
+ throw VPhoneLaunchpadError("The install did not start.")
+ }
+ if let error = progress.error {
+ throw error
+ }
+ guard let version = progress.version else {
+ throw VPhoneLaunchpadError("The install did not report a version.")
+ }
+ return report(try installed(version))
+ }
+
+ private func reportSteps(
+ _ reported: inout [VPhoneLaunchpadCoreBundle.InstallStep: VPhoneLaunchpadStatus],
+ emit: Emit,
+ ) {
+ guard let progress = bundles.progress else {
+ return
+ }
+ for step in progress.plan where reported[step] != progress.status(step) && progress.status(step) != .pending {
+ reported[step] = progress.status(step)
+ emit("\(progress.status(step).rawValue): \(step.title)")
+ }
+ }
+
+ private func use(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let version = request.arguments[0]
+ _ = try installed(version)
+ guard VPhoneLaunchpadNames.isCompatibleBundleVersion(version) else {
+ throw VPhoneLaunchpadError("VPhone.bundle \(version) is older than \(VPhoneLaunchpadNames.minimumBundleVersion).")
+ }
+ await bundles.use(version)
+ await library.refresh()
+ return try checked(version)
+ }
+
+ private func verify(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let version = request.arguments[0]
+ _ = try installed(version)
+ await bundles.verify(version)
+ return try checked(version)
+ }
+
+ /// The bundle's report, or its preflight failure unless it was accepted.
+ private func checked(_ version: String) throws -> Any {
+ let item = try installed(version)
+ if item.preflight != .passed, !bundles.isAccepted(version) {
+ throw VPhoneLaunchpadError("VPhone.bundle \(version) did not pass its checks.", detail: item.preflightDetail)
+ }
+ return report(item)
+ }
+
+ private func accept(_ request: VPhoneLaunchpadControlRequest) throws -> Any {
+ let version = request.arguments[0]
+ let item = try installed(version)
+ bundles.setAccepted(version, !request.flag("off"))
+ return report(item)
+ }
+
+ private func remove(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let version = request.arguments[0]
+ _ = try installed(version)
+ bundles.actionError = nil
+ await model.removeBundle(version)
+ if let error = bundles.actionError {
+ bundles.actionError = nil
+ throw error
+ }
+ return ["removed": version]
+ }
+
+ // MARK: - Machines
+
+ private func listMachines() async -> Any {
+ await refreshMachines()
+ return library.machines.map(report)
+ }
+
+ /// A refresh returns at once while another is running, as the one at
+ /// launch is when the CLI has just started Launchpad; wait for the first
+ /// listing then.
+ private func refreshMachines() async {
+ await library.refresh()
+ for _ in 0 ..< 100 where !library.hasListed {
+ try? await Task.sleep(for: .milliseconds(200))
+ }
+ }
+
+ private func report(_ machine: VPhoneLaunchpadMachine) -> [String: Any] {
+ let path = machine.path
+ let state: String = switch library.state(of: path) {
+ case .stopped: "stopped"
+ case .running: "running"
+ case let .busy(activity): "busy: \(activity)"
+ }
+ var report: [String: Any] = [
+ "name": machine.name,
+ "libraryRoot": machine.libraryRoot,
+ "state": state,
+ "cpuCount": machine.cpuCount,
+ "memoryMB": machine.memoryMB,
+ "network": machine.network.mode,
+ "panicked": library.panicked.contains(path),
+ "log": VPhoneLaunchpadMachineLibrary.consoleLog(path).path,
+ "controlSocket": FileManager.default.fileExists(atPath: Self.controlSocket(path))
+ ? Self.controlSocket(path) : NSNull(),
+ ]
+ if let udid = machine.udid {
+ report["udid"] = udid
+ }
+ if let info = machine.restoreInfo {
+ report["ios"] = "\(info.ios.version) (\(info.ios.build))"
+ report["cloudOS"] = "\(info.cloudOS.version) (\(info.cloudOS.build))"
+ }
+ return report
+ }
+
+ private static func controlSocket(_ machine: VPhoneLaunchpadMachinePath) -> String {
+ machine.url.appendingPathComponent("vphone.sock").path
+ }
+
+ /// The machine named by the first argument, in `--root` when given. A
+ /// name that two libraries share needs `--root`.
+ private func machine(_ request: VPhoneLaunchpadControlRequest) async throws -> VPhoneLaunchpadMachinePath {
+ let name = request.arguments[0]
+ let root = request.option("root").map { VPhoneLaunchpadMachineLocations.canonical(URL(fileURLWithPath: $0, isDirectory: true)) }
+ func matches() -> [VPhoneLaunchpadMachinePath] {
+ library.machines.map(\.path).filter { $0.name == name && (root == nil || $0.libraryRoot == root) }
+ }
+ var found = matches()
+ if found.isEmpty {
+ await refreshMachines()
+ found = matches()
+ }
+ guard let first = found.first else {
+ throw VPhoneLaunchpadError("No machine named \(name) was found.")
+ }
+ guard found.count == 1 else {
+ throw VPhoneLaunchpadError(
+ "\(name) exists in more than one library. Pass --root.",
+ detail: found.map(\.libraryRoot).joined(separator: "\n"),
+ )
+ }
+ return first
+ }
+
+ /// Returns and clears the error an action left for the window's alert.
+ private func takeLibraryError() -> VPhoneLaunchpadError? {
+ defer { library.actionError = nil }
+ return library.actionError
+ }
+
+ private func startMachine(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let machine = try await machine(request)
+ guard library.state(of: machine) == .stopped else {
+ throw VPhoneLaunchpadError("\(machine.name) is already running or busy.")
+ }
+ guard bundles.isReady else {
+ throw VPhoneLaunchpadError("The active VPhone.bundle has not passed its checks. Run bundle verify.")
+ }
+ library.actionError = nil
+ library.start(machine, headless: request.flag("headless"))
+ guard library.launchedProcess(machine) != nil else {
+ throw takeLibraryError() ?? VPhoneLaunchpadError("\(machine.name) could not be started.")
+ }
+ emit("launched \(machine.name); console log: \(VPhoneLaunchpadMachineLibrary.consoleLog(machine).path)")
+ if request.flag("wait") {
+ try await waitReady(machine, timeout: timeout(request), emit: emit)
+ }
+ return report(machine)
+ }
+
+ private func report(_ machine: VPhoneLaunchpadMachinePath) -> Any {
+ library.machines.first { $0.path == machine }.map(report) ?? ["name": machine.name, "libraryRoot": machine.libraryRoot]
+ }
+
+ private func stopMachine(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let machine = try await machine(request)
+ library.actionError = nil
+ await library.stop(machine)
+ if let error = takeLibraryError() {
+ throw error
+ }
+ return report(machine)
+ }
+
+ private func timeout(_ request: VPhoneLaunchpadControlRequest) throws -> Int {
+ guard let text = request.option("timeout") else {
+ return 300
+ }
+ guard let seconds = Int(text), seconds > 0 else {
+ throw VPhoneLaunchpadError("--timeout takes a number of seconds.")
+ }
+ return seconds
+ }
+
+ private func waitMachine(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let machine = try await machine(request)
+ try await waitReady(machine, timeout: timeout(request), emit: emit)
+ return report(machine)
+ }
+
+ /// The first-boot probe: a ping over vphone.sock that vphoned answers.
+ private func waitReady(_ machine: VPhoneLaunchpadMachinePath, timeout: Int, emit: Emit) async throws {
+ let socket = Self.controlSocket(machine)
+ emit("waiting up to \(timeout)s for vphoned")
+ let started = Date()
+ while Date().timeIntervalSince(started) < Double(timeout) {
+ try Task.checkCancellation()
+ if library.panicked.contains(machine) {
+ throw VPhoneLaunchpadError("\(machine.name) had a kernel panic.", detail: VPhoneLaunchpadMachineLibrary.consoleLog(machine).path)
+ }
+ if let child = library.launchedProcess(machine), !child.isRunning {
+ throw VPhoneLaunchpadError("\(machine.name) stopped before vphoned answered.")
+ }
+ if await Task.detached(operation: { VPhoneLaunchpadCreationPipeline.ping(socketPath: socket) }).value {
+ emit("vphoned answered after \(Int(Date().timeIntervalSince(started)))s")
+ return
+ }
+ try await Task.sleep(for: .seconds(1))
+ }
+ throw VPhoneLaunchpadError(
+ "vphoned did not answer within \(timeout)s.",
+ detail: "Bundles up to 2.0.9 serve vphone.sock only for machines launched with a window.",
+ )
+ }
+
+ private func log(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let machine = try await machine(request)
+ let suffix = switch request.option("kind") {
+ case nil, "console": ""
+ case "create": "-create"
+ case "dfu": "-dfu"
+ case let kind?: throw VPhoneLaunchpadError("--kind is console, create or dfu, not \(kind).")
+ }
+ var count = 200
+ if let text = request.option("lines") {
+ guard let lines = Int(text), lines > 0 else {
+ throw VPhoneLaunchpadError("--lines takes a positive number.")
+ }
+ count = lines
+ }
+ let file = VPhoneLaunchpadMachineLibrary.consoleLog(machine, suffix: suffix)
+ let lines = await Task.detached { Self.tail(file, lines: count) }.value
+ guard let lines else {
+ throw VPhoneLaunchpadError("There is no log at \(file.path).")
+ }
+ return ["path": file.path, "lines": lines]
+ }
+
+ /// The last `lines` lines, read from at most the last 1 MiB.
+ private nonisolated static func tail(_ file: URL, lines: Int) -> [String]? {
+ guard let handle = try? FileHandle(forReadingFrom: file) else {
+ return nil
+ }
+ defer { try? handle.close() }
+ let end = (try? handle.seekToEnd()) ?? 0
+ try? handle.seek(toOffset: end > 1 << 20 ? end - (1 << 20) : 0)
+ let data = (try? handle.readToEnd()) ?? Data()
+ var result: [String] = []
+ var splitter = VPhoneLaunchpadLineSplitter()
+ splitter.feed(data) { result.append($0) }
+ splitter.flush { result.append($0) }
+ return Array(result.suffix(max(lines, 1)))
+ }
+
+ // MARK: - Create
+
+ private func create(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let name = request.arguments[0]
+ let root = VPhoneLaunchpadMachineLocations.canonical(URL(
+ fileURLWithPath: request.option("root") ?? library.libraryRoot,
+ isDirectory: true,
+ ))
+ let machine = VPhoneLaunchpadMachinePath(libraryRoot: root, name: name)
+
+ let pipeline: VPhoneLaunchpadCreationPipeline
+ if let from = request.option("from") {
+ guard let step = VPhoneLaunchpadCreationPipeline.Step.allCases.first(where: { "\($0)" == from }) else {
+ let steps = VPhoneLaunchpadCreationPipeline.Step.allCases.map { "\($0)" }.joined(separator: ", ")
+ throw VPhoneLaunchpadError("--from takes one of: \(steps).")
+ }
+ guard let existing = library.creations[machine] else {
+ throw VPhoneLaunchpadError("This Launchpad has not created \(name) since it started, so there is nothing to retry.")
+ }
+ guard !existing.isRunning else {
+ throw VPhoneLaunchpadError("\(name) is still being created.")
+ }
+ existing.start(from: step)
+ pipeline = existing
+ } else {
+ pipeline = try await startCreation(machine, request, emit: emit)
+ }
+
+ if request.flag("no-wait") {
+ return creationReport(pipeline)
+ }
+ try await watchCreation(pipeline, emit: emit)
+ return creationReport(pipeline)
+ }
+
+ private func startCreation(
+ _ machine: VPhoneLaunchpadMachinePath,
+ _ request: VPhoneLaunchpadControlRequest,
+ emit: Emit,
+ ) async throws -> VPhoneLaunchpadCreationPipeline {
+ guard VPhoneLaunchpadNames.isValidMachineName(machine.name) else {
+ throw VPhoneLaunchpadError("Use letters, numbers, periods, hyphens, and underscores in the name.")
+ }
+ guard !FileManager.default.fileExists(atPath: machine.url.path), library.creations[machine]?.isRunning != true else {
+ throw VPhoneLaunchpadError("\(machine.name) already exists in \(machine.libraryRoot).")
+ }
+ guard VPhoneLaunchpadMachineLocations.socketPathFits(root: machine.libraryRoot, name: machine.name) else {
+ throw VPhoneLaunchpadError("The machine path is too long for its vphone.sock. Use a shorter name or library path.")
+ }
+ guard bundles.isReady, let commandLine = bundles.commandLine() else {
+ throw VPhoneLaunchpadError("The active VPhone.bundle has not passed its checks. Run bundle verify.")
+ }
+
+ var iphone = request.option("iphone-source")
+ var cloudOS = request.option("cloudos-source")
+ if iphone == nil || cloudOS == nil {
+ let result = try await commandLine.run(["fw", "catalog", "--json"], recordInHistory: false)
+ guard result.succeeded, let data = result.jsonData,
+ let pairing = try JSONDecoder().decode(VPhoneLaunchpadFirmwareCatalog.self, from: data).pairings.last
+ else {
+ throw VPhoneLaunchpadError("Unable to read the firmware catalog. Pass --iphone-source and --cloudos-source.", detail: result.tail)
+ }
+ iphone = iphone ?? pairing.ios.url
+ cloudOS = cloudOS ?? pairing.recommendedCloudOS.url
+ emit("firmware: \(iphone ?? "") + \(cloudOS ?? "")")
+ }
+
+ func number(_ option: String, _ fallback: Int) throws -> Int {
+ guard let text = request.option(option) else {
+ return fallback
+ }
+ guard let value = Int(text), value > 0 else {
+ throw VPhoneLaunchpadError("--\(option) takes a positive number.")
+ }
+ return value
+ }
+ var patches = VPhoneLaunchpadPatchSelection()
+ if let preset = request.option("preset") {
+ patches.preset = preset
+ }
+ let options = try VPhoneLaunchpadCreationPipeline.Options(
+ name: machine.name,
+ libraryRoot: machine.libraryRoot,
+ iphoneSource: iphone ?? "",
+ cloudOSSource: cloudOS ?? "",
+ cpuCount: number("cpu", 8),
+ memoryMB: number("memory", 8192),
+ diskSizeGB: number("disk-size", 64),
+ network: request.option("network") ?? "nat",
+ patches: patches,
+ forceDyldSharedCacheMaxSlide: request.flag("force-dsc-maxslide"),
+ keepArtifacts: request.flag("keep-artifacts"),
+ )
+ return library.create(options)
+ }
+
+ /// Streams the creation log and each step until the pipeline stops. The
+ /// creation is the window's own, so interrupting the CLI only stops
+ /// watching it.
+ private func watchCreation(_ pipeline: VPhoneLaunchpadCreationPipeline, emit: @escaping Emit) async throws {
+ let follower = VPhoneLaunchpadLogFollower(url: pipeline.logFile)
+ while pipeline.isRunning {
+ try Task.checkCancellation()
+ await Task.detached { follower.drain(emit) }.value
+ try await Task.sleep(for: .milliseconds(500))
+ }
+ await Task.detached { follower.drain(emit) }.value
+ if let failure = pipeline.failure {
+ throw failure
+ }
+ }
+
+ private func creationReport(_ pipeline: VPhoneLaunchpadCreationPipeline) -> [String: Any] {
+ [
+ "name": pipeline.machine.name,
+ "libraryRoot": pipeline.machine.libraryRoot,
+ "running": pipeline.isRunning,
+ "log": pipeline.logFile.path,
+ "steps": VPhoneLaunchpadCreationPipeline.Step.allCases.map { step -> [String: Any] in
+ var item: [String: Any] = ["step": "\(step)", "status": pipeline.status(step).rawValue]
+ if let duration = pipeline.durations[step] {
+ item["seconds"] = Int(duration)
+ }
+ return item
+ },
+ ]
+ }
+
+ // MARK: - CFW
+
+ private func installCustomFirmware(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ let machine = try await machine(request)
+ guard let version = bundles.activeVersion else {
+ throw VPhoneLaunchpadError("No Core Bundle version is in use.")
+ }
+ guard library.state(of: machine) == .stopped else {
+ throw VPhoneLaunchpadError("Stop \(machine.name) before installing CFW.")
+ }
+ let status = try await model.helper.installCustomFirmware(
+ bundleVersion: version,
+ machineName: machine.name,
+ libraryRoot: machine.libraryRoot,
+ forceDyldSharedCacheMaxSlide: request.flag("force-dsc-maxslide"),
+ keepArtifacts: request.flag("keep-artifacts"),
+ onLine: emit,
+ )
+ guard status == 0 else {
+ throw VPhoneLaunchpadError("cfw install exited with status \(status).")
+ }
+ return ["name": machine.name, "bundle": version, "status": status]
+ }
+
+ // MARK: - Guest
+
+ private func sendToGuest(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let machine = try await machine(request)
+ guard let object = try? JSONSerialization.jsonObject(with: Data(request.arguments[1].utf8)) as? [String: Any] else {
+ throw VPhoneLaunchpadError("The request must be one JSON object.")
+ }
+ return try await VPhoneLaunchpadGuestSocket.send(object, socketPath: Self.controlSocket(machine))
+ }
+
+ private func callGuest(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {
+ let machine = try await machine(request)
+ let text = request.arguments.dropFirst(2).joined(separator: " ")
+ var params: [String: Any] = [:]
+ if !text.isEmpty {
+ guard let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else {
+ throw VPhoneLaunchpadError("params must be one JSON object.")
+ }
+ params = object
+ }
+ let object: [String: Any] = [
+ "t": "rpc",
+ "method": request.arguments[1],
+ "params": params,
+ "screen": request.flag("screen"),
+ ]
+ return try await VPhoneLaunchpadGuestSocket.send(object, socketPath: Self.controlSocket(machine))
+ }
+
+ // MARK: - vphone-cli
+
+ private func exec(_ request: VPhoneLaunchpadControlRequest, emit: @escaping Emit) async throws -> Any {
+ guard let commandLine = bundles.commandLine() else {
+ throw VPhoneLaunchpadError("No Core Bundle version is in use.")
+ }
+ let result = try await commandLine.run(request.arguments, onLine: emit)
+ try Task.checkCancellation()
+ guard result.succeeded else {
+ throw VPhoneLaunchpadError("vphone-cli exited with status \(result.status).")
+ }
+ return ["status": result.status, "bundle": bundles.activeVersion ?? ""]
+ }
+}
+
+// MARK: - Log follower
+
+/// Emits the lines appended to a log file since the last drain.
+final nonisolated class VPhoneLaunchpadLogFollower: @unchecked Sendable {
+ private let url: URL
+ private var offset: UInt64 = 0
+ private var splitter = VPhoneLaunchpadLineSplitter()
+
+ init(url: URL) {
+ self.url = url
+ }
+
+ func drain(_ emit: (String) -> Void) {
+ guard let handle = try? FileHandle(forReadingFrom: url) else {
+ return
+ }
+ defer { try? handle.close() }
+ try? handle.seek(toOffset: offset)
+ let data = (try? handle.readToEnd()) ?? Data()
+ offset += UInt64(data.count)
+ splitter.feed(data, emit)
+ }
+}
+
+// MARK: - Guest socket
+
+/// One request to a machine's vphone.sock: a JSON line in, a JSON line out.
+nonisolated enum VPhoneLaunchpadGuestSocket {
+ static func send(_ object: [String: Any], socketPath: String) async throws -> Any {
+ let line = try JSONSerialization.data(withJSONObject: object) + Data([0x0A])
+ let response = try await Task.detached { try exchange(line, socketPath: socketPath) }.value
+ guard let json = try? JSONSerialization.jsonObject(with: response) else {
+ throw VPhoneLaunchpadError("The machine answered with something other than JSON.", detail: String(decoding: response.prefix(512), as: UTF8.self))
+ }
+ if let dictionary = json as? [String: Any], dictionary["ok"] as? Bool == false {
+ throw VPhoneLaunchpadError("The guest refused the request.", detail: dictionary["error"] as? String)
+ }
+ return json
+ }
+
+ private static func exchange(_ line: Data, socketPath: String) throws -> Data {
+ guard FileManager.default.fileExists(atPath: socketPath) else {
+ throw VPhoneLaunchpadError(
+ "The machine has no vphone.sock.",
+ detail: "Only a running machine serves it; bundles up to 2.0.9 serve it only with a window.",
+ )
+ }
+ var address = sockaddr_un()
+ guard VPhoneLaunchpadControl.address(socketPath, into: &address) else {
+ throw VPhoneLaunchpadError("The vphone.sock path is too long.")
+ }
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else {
+ throw VPhoneLaunchpadError("Unable to open a socket.")
+ }
+ defer { close(fd) }
+ // vphone-vm waits on vphoned for up to its own limit; an rpc such as
+ // a package install can take a while.
+ var timeout = timeval(tv_sec: 120, tv_usec: 0)
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
+ _ = fcntl(fd, F_SETNOSIGPIPE, 1)
+ let connected = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ guard connected == 0 else {
+ throw VPhoneLaunchpadError("The machine's vphone.sock is not answering.", detail: String(cString: strerror(errno)))
+ }
+ guard VPhoneLaunchpadControl.write(line, to: fd) else {
+ throw VPhoneLaunchpadError("Unable to send the request to the machine.")
+ }
+ var response = Data()
+ var buffer = [UInt8](repeating: 0, count: 65536)
+ while true {
+ let count = read(fd, &buffer, buffer.count)
+ if count < 0, errno == EINTR {
+ continue
+ }
+ guard count > 0 else {
+ break
+ }
+ response.append(contentsOf: buffer[0 ..< count])
+ }
+ guard !response.isEmpty else {
+ throw VPhoneLaunchpadError("The machine closed the connection without answering.")
+ }
+ return response
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlServer.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlServer.swift
new file mode 100644
index 00000000..6d2405bb
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlServer.swift
@@ -0,0 +1,202 @@
+import Darwin
+import Foundation
+
+/// Serves `vphone-launchpad-cli` on `VPhoneLaunchpadControl.socketPath`.
+///
+/// Each connection gets its own thread: it reads the request line, runs the
+/// handler on the main actor, streams the handler's output lines back, and
+/// cancels the handler if the client hangs up first. Only peers running as
+/// this user are served, and the socket itself is mode 0600.
+final nonisolated class VPhoneLaunchpadControlServer: @unchecked Sendable {
+ typealias Emit = @Sendable (String) -> Void
+ typealias Handler = @MainActor @Sendable (VPhoneLaunchpadControlRequest, @escaping Emit) async -> VPhoneLaunchpadControlEvent
+
+ private let handler: Handler
+ private let lock = NSLock()
+ private var listenFD: Int32 = -1
+
+ init(handler: @escaping Handler) {
+ self.handler = handler
+ }
+
+ // MARK: - Listening
+
+ /// Binds the socket and starts accepting. When another Launchpad already
+ /// answers on the socket, this one leaves it alone.
+ func start() throws {
+ let path = VPhoneLaunchpadControl.socketPath
+ try FileManager.default.createDirectory(at: VPhoneLaunchpadControl.directory, withIntermediateDirectories: true)
+ var address = sockaddr_un()
+ guard VPhoneLaunchpadControl.address(path, into: &address) else {
+ throw VPhoneLaunchpadError("The control socket path is too long.", detail: path)
+ }
+ if Self.isServed(&address) {
+ throw VPhoneLaunchpadError("Another Launchpad is already serving the command line tool.", detail: path)
+ }
+ unlink(path)
+
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else {
+ throw Self.posixError("socket")
+ }
+ let bound = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ // Owner only before anyone can connect: connect fails until listen.
+ guard bound == 0, chmod(path, 0o600) == 0, listen(fd, 8) == 0 else {
+ let error = Self.posixError("bind")
+ close(fd)
+ throw error
+ }
+ lock.withLock { listenFD = fd }
+ Thread.detachNewThread { [self] in
+ acceptLoop(fd)
+ }
+ }
+
+ func stop() {
+ let fd = lock.withLock {
+ defer { listenFD = -1 }
+ return listenFD
+ }
+ if fd >= 0 {
+ close(fd)
+ unlink(VPhoneLaunchpadControl.socketPath)
+ }
+ }
+
+ private static func isServed(_ address: inout sockaddr_un) -> Bool {
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else {
+ return false
+ }
+ defer { close(fd) }
+ return withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) == 0
+ }
+ }
+ }
+
+ private static func posixError(_ call: String) -> VPhoneLaunchpadError {
+ VPhoneLaunchpadError(
+ "Unable to open the control socket.",
+ detail: "\(call): \(String(cString: strerror(errno)))",
+ )
+ }
+
+ private func acceptLoop(_ listenFD: Int32) {
+ while true {
+ let fd = accept(listenFD, nil, nil)
+ if fd < 0 {
+ if errno == EINTR || errno == ECONNABORTED {
+ continue
+ }
+ return
+ }
+ Thread.detachNewThread { [self] in
+ serve(fd)
+ }
+ }
+ }
+
+ // MARK: - Connection
+
+ private func serve(_ fd: Int32) {
+ defer { close(fd) }
+ var uid: uid_t = 0
+ var gid: gid_t = 0
+ guard getpeereid(fd, &uid, &gid) == 0, uid == getuid(),
+ fcntl(fd, F_SETNOSIGPIPE, 1) != -1
+ else {
+ return
+ }
+ var timeout = timeval(tv_sec: 15, tv_usec: 0)
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))
+
+ let writer = VPhoneLaunchpadControlWriter(fd: fd)
+ // A reader thread may still emit after the command returns; the fd
+ // number must not be written once it is closed and reused.
+ defer { writer.close() }
+ guard let line = Self.readLine(fd) else {
+ writer.send(.failure("The request was empty, too long, or did not arrive in time."))
+ return
+ }
+ guard let request = try? JSONDecoder().decode(VPhoneLaunchpadControlRequest.self, from: line) else {
+ writer.send(.failure("The request is not valid JSON."))
+ return
+ }
+
+ let finished = DispatchSemaphore(value: 0)
+ let emit: Emit = { writer.send(.line($0)) }
+ let task = Task { @MainActor [handler] in
+ let event = await handler(request, emit)
+ writer.send(event)
+ finished.signal()
+ }
+ // The request is read in full, so anything readable now is the
+ // client closing its end: the CLI was interrupted.
+ while finished.wait(timeout: .now() + .milliseconds(250)) == .timedOut {
+ var pollFD = pollfd(fd: fd, events: Int16(POLLIN), revents: 0)
+ guard poll(&pollFD, 1, 0) > 0 else {
+ continue
+ }
+ var byte: UInt8 = 0
+ if recv(fd, &byte, 1, MSG_DONTWAIT) <= 0 {
+ task.cancel()
+ finished.wait()
+ return
+ }
+ }
+ }
+
+ /// One line, without its newline, of at most the request limit.
+ private static func readLine(_ fd: Int32) -> Data? {
+ var data = Data()
+ var buffer = [UInt8](repeating: 0, count: 4096)
+ while data.count <= VPhoneLaunchpadControl.maximumRequestLength {
+ let count = read(fd, &buffer, buffer.count)
+ if count < 0, errno == EINTR {
+ continue
+ }
+ guard count > 0 else {
+ return nil
+ }
+ if let newline = buffer[0 ..< count].firstIndex(of: 0x0A) {
+ data.append(contentsOf: buffer[0 ..< newline])
+ return data
+ }
+ data.append(contentsOf: buffer[0 ..< count])
+ }
+ return nil
+ }
+}
+
+/// Serializes events onto one connection. Output lines arrive from reader
+/// threads while the final event comes from the main actor.
+final nonisolated class VPhoneLaunchpadControlWriter: @unchecked Sendable {
+ private let fd: Int32
+ private let lock = NSLock()
+ private var isClosed = false
+
+ init(fd: Int32) {
+ self.fd = fd
+ }
+
+ func send(_ event: VPhoneLaunchpadControlEvent) {
+ lock.withLock {
+ guard !isClosed else {
+ return
+ }
+ if !VPhoneLaunchpadControl.write(event.encodedLine(), to: fd) {
+ isClosed = true
+ }
+ }
+ }
+
+ func close() {
+ lock.withLock { isClosed = true }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift
new file mode 100644
index 00000000..501ea4ee
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadCLI/main.swift
@@ -0,0 +1,210 @@
+import Darwin
+import Foundation
+
+// vphone-launchpad-cli: drives a running vphone-launchpad over its control
+// socket. It holds no state and no privileges of its own: the app installs
+// bundles through its helper, runs the active bundle's vphone-cli, and shows
+// every command in its window. Output lines go to stderr as they arrive; the
+// result, a JSON document, goes to stdout. The exit status is 0 on success.
+
+// MARK: - Arguments
+
+func usage() -> String {
+ var text = """
+ usage: vphone-launchpad-cli <command> [arguments] [options]
+
+ Drives a running vphone-launchpad, starting it if needed. Progress goes to
+ stderr; the result is JSON on stdout.
+
+ """
+ for command in VPhoneLaunchpadControlCommand.all {
+ text += "\n \(command.usage)\n \(command.summary)\n"
+ }
+ return text
+}
+
+func fail(_ message: String, detail: String? = nil) -> Never {
+ FileHandle.standardError.write(Data("error: \(message)\n".utf8))
+ if let detail, !detail.isEmpty {
+ FileHandle.standardError.write(Data("\(detail)\n".utf8))
+ }
+ exit(1)
+}
+
+func parse(_ words: [String]) -> VPhoneLaunchpadControlRequest {
+ // Two words name a grouped command ("vm start"), one word the others.
+ var rest = words
+ var command: VPhoneLaunchpadControlCommand?
+ if rest.count >= 2, let grouped = VPhoneLaunchpadControlCommand.named("\(rest[0]).\(rest[1])") {
+ command = grouped
+ rest.removeFirst(2)
+ } else if let single = VPhoneLaunchpadControlCommand.named(rest[0]) {
+ command = single
+ rest.removeFirst()
+ }
+ guard let command else {
+ let group = VPhoneLaunchpadControlCommand.all.filter { $0.name.hasPrefix("\(words[0]).") }
+ if !group.isEmpty {
+ fail("\(words[0]) needs a command.", detail: group.map { " \($0.usage)" }.joined(separator: "\n"))
+ }
+ fail("unknown command \(words.prefix(2).joined(separator: " ")). Run vphone-launchpad-cli help.")
+ }
+ var request = VPhoneLaunchpadControlRequest(command: command.name)
+ // exec hands everything after it to vphone-cli untouched.
+ if command.name == "exec" {
+ request.arguments = rest
+ return request
+ }
+
+ var positional: [String] = []
+ var index = 0
+ while index < rest.count {
+ let word = rest[index]
+ index += 1
+ if word == "--" {
+ positional += rest[index...]
+ break
+ }
+ guard word.hasPrefix("--"), word.count > 2 else {
+ positional.append(word)
+ continue
+ }
+ var name = String(word.dropFirst(2))
+ var value: String?
+ if let equals = name.firstIndex(of: "=") {
+ value = String(name[name.index(after: equals)...])
+ name = String(name[..<equals])
+ }
+ if command.flags.contains(name), value == nil {
+ request.options[name] = "true"
+ } else if command.options.contains(name) {
+ if value == nil, index < rest.count {
+ value = rest[index]
+ index += 1
+ }
+ guard let value else {
+ fail("--\(name) needs a value.")
+ }
+ request.options[name] = value
+ } else {
+ fail("unknown option --\(name).", detail: "usage: vphone-launchpad-cli \(command.usage)")
+ }
+ }
+
+ // A trailing `...` argument may be empty.
+ let named = command.takesRest ? command.arguments.count - 1 : command.arguments.count
+ guard positional.count >= named, command.takesRest || positional.count == named else {
+ fail("wrong number of arguments.", detail: "usage: vphone-launchpad-cli \(command.usage)")
+ }
+ // The app runs elsewhere; a relative path means nothing to it.
+ if command.name == "bundle.install-local" {
+ positional[0] = URL(fileURLWithPath: positional[0]).standardizedFileURL.path
+ }
+ if let root = request.options["root"] {
+ request.options["root"] = URL(fileURLWithPath: root).standardizedFileURL.path
+ }
+ request.arguments = positional
+ return request
+}
+
+// MARK: - Connection
+
+func connectControl() -> Int32? {
+ var address = sockaddr_un()
+ guard VPhoneLaunchpadControl.address(VPhoneLaunchpadControl.socketPath, into: &address) else {
+ fail("the control socket path is too long: \(VPhoneLaunchpadControl.socketPath)")
+ }
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else {
+ return nil
+ }
+ let connected = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ guard connected == 0 else {
+ close(fd)
+ return nil
+ }
+ _ = fcntl(fd, F_SETNOSIGPIPE, 1)
+ return fd
+}
+
+/// Opens the Launchpad this tool ships in, in the background, else the one
+/// Launch Services knows, and waits for its socket.
+func launchAndConnect() -> Int32 {
+ let executable = Bundle.main.executableURL?.resolvingSymlinksInPath()
+ let app = executable?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let open = Process()
+ open.executableURL = URL(fileURLWithPath: "/usr/bin/open")
+ open.arguments = app?.pathExtension == "app" ? ["-g", app!.path] : ["-g", "-b", "com.vphone.launchpad"]
+ open.standardOutput = FileHandle.nullDevice
+ open.standardError = FileHandle.nullDevice
+ FileHandle.standardError.write(Data("starting vphone-launchpad…\n".utf8))
+ do {
+ try open.run()
+ open.waitUntilExit()
+ } catch {
+ fail("unable to start vphone-launchpad.", detail: error.localizedDescription)
+ }
+ for _ in 0 ..< 120 {
+ if let fd = connectControl() {
+ return fd
+ }
+ usleep(250_000)
+ }
+ fail("vphone-launchpad did not open its control socket.", detail: VPhoneLaunchpadControl.socketPath)
+}
+
+// MARK: - Main
+
+let words = Array(CommandLine.arguments.dropFirst())
+if words.isEmpty || ["help", "-h", "--help"].contains(words[0]) {
+ print(usage(), terminator: "")
+ exit(words.isEmpty ? 1 : 0)
+}
+let request = parse(words)
+let fd = connectControl() ?? launchAndConnect()
+
+guard var line = try? JSONEncoder().encode(request) else {
+ fail("unable to encode the request.")
+}
+line.append(0x0A)
+guard VPhoneLaunchpadControl.write(line, to: fd) else {
+ fail("vphone-launchpad closed the connection.")
+}
+
+// Interrupting this process closes the socket, which cancels the command in
+// the app where the command can be cancelled.
+var splitter = Data()
+var buffer = [UInt8](repeating: 0, count: 65536)
+while true {
+ let count = read(fd, &buffer, buffer.count)
+ if count < 0, errno == EINTR {
+ continue
+ }
+ guard count > 0 else {
+ break
+ }
+ splitter.append(contentsOf: buffer[0 ..< count])
+ while let newline = splitter.firstIndex(of: 0x0A) {
+ let data = splitter[splitter.startIndex ..< newline]
+ splitter.removeSubrange(splitter.startIndex ... newline)
+ guard let event = try? JSONDecoder().decode(VPhoneLaunchpadControlEvent.self, from: data) else {
+ continue
+ }
+ if let output = event.output {
+ FileHandle.standardError.write(Data("\(output)\n".utf8))
+ }
+ guard event.done == true else {
+ continue
+ }
+ guard event.ok == true else {
+ fail(event.error ?? "the command failed.", detail: event.detail)
+ }
+ print(event.result ?? "null")
+ exit(0)
+ }
+}
+fail("vphone-launchpad closed the connection before the command finished.")
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
new file mode 100644
index 00000000..dbd1ad80
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift
@@ -0,0 +1,187 @@
+import Darwin
+import Foundation
+
+// MARK: - Socket
+
+/// The local control channel between `vphone-launchpad-cli` and a running
+/// Launchpad. The app listens on a Unix socket in its Application Support
+/// folder, mode 0600, and serves only peers with its own user ID. Nothing
+/// listens on the network: a remote agent reaches it over ssh.
+///
+/// One connection carries one request. The client writes the request as one
+/// JSON line; the app answers with any number of `output` events, streamed
+/// while the command runs, and ends with one `done` event. The client closing
+/// its end cancels the command where the command supports it.
+nonisolated enum VPhoneLaunchpadControl {
+ static var directory: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/vphone-launchpad", isDirectory: true)
+ }
+
+ static var socketPath: String {
+ directory.appendingPathComponent("control.sock").path
+ }
+
+ /// Requests are small; a guest request carries at most vphoned's own
+ /// 1 MiB body limit.
+ static let maximumRequestLength = 2 << 20
+
+ /// Fills `address` with `path`, or returns false when it does not fit.
+ static func address(_ path: String, into address: inout sockaddr_un) -> Bool {
+ let bytes = path.utf8CString
+ guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else {
+ return false
+ }
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { buffer in
+ for (index, byte) in bytes.enumerated() {
+ buffer[index] = UInt8(bitPattern: byte)
+ }
+ }
+ return true
+ }
+
+ /// Writes all of `data`, retrying short writes. False once the peer is gone.
+ @discardableResult
+ static func write(_ data: Data, to fd: Int32) -> Bool {
+ data.withUnsafeBytes { buffer in
+ var offset = 0
+ while offset < buffer.count {
+ let written = Darwin.write(fd, buffer.baseAddress! + offset, buffer.count - offset)
+ if written < 0, errno == EINTR {
+ continue
+ }
+ guard written > 0 else {
+ return false
+ }
+ offset += written
+ }
+ return true
+ }
+ }
+}
+
+// MARK: - Messages
+
+nonisolated struct VPhoneLaunchpadControlRequest: Codable, Sendable {
+ /// A command name from `VPhoneLaunchpadControlCommand.all`.
+ var command: String
+ var arguments: [String] = []
+ /// Valued options by name; a flag that is set has the value "true".
+ var options: [String: String] = [:]
+
+ func option(_ name: String) -> String? {
+ options[name]
+ }
+
+ func flag(_ name: String) -> Bool {
+ options[name] == "true"
+ }
+}
+
+/// One line from the app. `output` lines stream while a command runs; the
+/// last line has `done` set, `ok`, and either a JSON `result` or an `error`.
+nonisolated struct VPhoneLaunchpadControlEvent: Codable, Sendable {
+ var output: String?
+ var done: Bool?
+ var ok: Bool?
+ /// The command's result as a JSON document.
+ var result: String?
+ var error: String?
+ var detail: String?
+
+ static func line(_ text: String) -> Self {
+ Self(output: text)
+ }
+
+ static func success(_ result: String) -> Self {
+ Self(done: true, ok: true, result: result)
+ }
+
+ static func failure(_ message: String, detail: String? = nil) -> Self {
+ Self(done: true, ok: false, error: message, detail: detail)
+ }
+
+ func encodedLine() -> Data {
+ var data = (try? JSONEncoder().encode(self)) ?? Data(#"{"done":true,"ok":false,"error":"unencodable event"}"#.utf8)
+ data.append(0x0A)
+ return data
+ }
+}
+
+// MARK: - Commands
+
+/// The commands both sides know. The CLI parses its arguments and prints
+/// help from this table; the app dispatches on `name`.
+nonisolated struct VPhoneLaunchpadControlCommand: Sendable {
+ let name: String
+ /// Positional arguments, in order. A trailing `...` takes the rest.
+ let arguments: [String]
+ /// Options that take a value.
+ let options: [String]
+ /// Options without a value.
+ let flags: [String]
+ let summary: String
+
+ var usage: String {
+ var parts = [name.replacingOccurrences(of: ".", with: " ")]
+ parts += arguments.map { "<\($0)>" }
+ parts += options.map { "[--\($0) <value>]" }
+ parts += flags.map { "[--\($0)]" }
+ return parts.joined(separator: " ")
+ }
+
+ var takesRest: Bool {
+ arguments.last?.hasSuffix("...") == true
+ }
+
+ static let all: [Self] = [
+ Self(name: "status", arguments: [], options: [], flags: [],
+ summary: "Host checks, helper, active bundle and machine counts."),
+
+ Self(name: "bundle.list", arguments: [], options: [], flags: [],
+ summary: "Installed VPhone.bundle versions and their checks."),
+ Self(name: "bundle.install-local", arguments: ["path"], options: [], flags: [],
+ summary: "Install a VPhone.bundle folder or .zip built on this Mac as <version>-local, make it active and check it."),
+ Self(name: "bundle.install-release", arguments: ["version"], options: [], flags: [],
+ summary: "Download and install a GitHub release (a version, or \"latest\")."),
+ Self(name: "bundle.use", arguments: ["version"], options: [], flags: [],
+ summary: "Make an installed version active and check it."),
+ Self(name: "bundle.verify", arguments: ["version"], options: [], flags: [],
+ summary: "Add the execution policy exception, allow vphone-vm if AMFI refuses it, and run host preflight."),
+ Self(name: "bundle.accept", arguments: ["version"], options: [], flags: ["off"],
+ summary: "Use a version even though its checks failed (--off takes that back)."),
+ Self(name: "bundle.remove", arguments: ["version"], options: [], flags: [],
+ summary: "Remove an installed version."),
+
+ Self(name: "vm.list", arguments: [], options: [], flags: [],
+ summary: "Machines in every library, with their run state."),
+ Self(name: "vm.start", arguments: ["name"], options: ["root", "timeout"], flags: ["headless", "wait"],
+ summary: "Launch a machine. --wait blocks until vphoned answers on vphone.sock."),
+ Self(name: "vm.stop", arguments: ["name"], options: ["root"], flags: [],
+ summary: "Stop a machine."),
+ Self(name: "vm.wait", arguments: ["name"], options: ["root", "timeout"], flags: [],
+ summary: "Wait until vphoned answers on the machine's vphone.sock."),
+ Self(name: "vm.log", arguments: ["name"], options: ["root", "lines", "kind"], flags: [],
+ summary: "The last lines of the console log (--kind create or dfu for those logs)."),
+ Self(name: "vm.create", arguments: ["name"], options: [
+ "root", "iphone-source", "cloudos-source", "cpu", "memory", "disk-size", "network", "preset", "from",
+ ], flags: ["force-dsc-maxslide", "keep-artifacts", "no-wait"],
+ summary: "Create a machine through every step, as New Machine does. --from <step> retries a failed creation from that step."),
+
+ Self(name: "cfw.install", arguments: ["name"], options: ["root"], flags: ["force-dsc-maxslide", "keep-artifacts"],
+ summary: "Install CFW into a stopped machine through the root helper."),
+
+ Self(name: "guest.send", arguments: ["name", "json"], options: ["root"], flags: [],
+ summary: "Send one raw vphone.sock request, such as {\"t\":\"tap\",\"x\":645,\"y\":1398}."),
+ Self(name: "guest.rpc", arguments: ["name", "method", "params..."], options: ["root"], flags: ["screen"],
+ summary: "Call a vphoned method; params is one JSON object."),
+
+ Self(name: "exec", arguments: ["arguments..."], options: [], flags: [],
+ summary: "Run the active bundle's vphone-cli with these arguments and stream its output."),
+ ]
+
+ static func named(_ name: String) -> Self? {
+ all.first { $0.name == name }
+ }
+}