Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Say the bootstrap is already installed instead of failing

Jacky79de2b74d25e
diff --git a/VPhoneDaemon/Daemon/APIWire.swift b/VPhoneDaemon/Daemon/APIWire.swift
index 5a5a93d7..8f5e6db7 100644
--- a/VPhoneDaemon/Daemon/APIWire.swift
+++ b/VPhoneDaemon/Daemon/APIWire.swift
@@ -44,8 +44,10 @@ enum APIWire {
let (code, message): (String, String) =
if let error = error as? IcliError {
(error.code, error.message)
+ } else if let error = error as? GuestAPIError {
+ (error.code, error.description)
} else {
- (error is GuestAPIError ? "invalid_operation" : "operation_failed", String(describing: error))
+ ("operation_failed", String(describing: error))
}
return .json(status: 400, [
"type": "response", "id": request.id ?? NSNull(),
diff --git a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift
index af371899..3bb4b35f 100644
--- a/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift
+++ b/VPhoneDaemon/Daemon/Bootstrap/GuestIrisinInstaller.swift
@@ -11,6 +11,8 @@ import IcliSystem
/// and the firmware record, release download and payload copy beside this file.
enum GuestIrisinInstaller {
static let serviceLabel = "wiki.qaq.irisind"
+ /// Error code of `bootstrap.install` when a completed install exists.
+ static let alreadyInstalledCode = "bootstrap_already_installed"
static let installLock = NSLock()
private static let progressLock = NSLock()
private nonisolated(unsafe) static var progress: [String: Any] = ["phase": "idle"]
@@ -22,8 +24,14 @@ enum GuestIrisinInstaller {
static func install(jailbreak: [String: Any], layout: String, packagePath: String? = nil) throws -> [String: Any] {
installLock.lock()
defer { installLock.unlock() }
- guard try completedBootstrap() == nil else {
- throw GuestAPIError.operationFailed("Irisin bootstrap already completed")
+ // Installation runs once. A second request is not a failure: answer
+ // with a code the host recognizes, and leave reinstalling to
+ // uninstall followed by install.
+ if let installation = try completedBootstrap() {
+ throw GuestAPIError.alreadyDone(
+ code: alreadyInstalledCode,
+ message: "Irisin bootstrap already completed in \(installation.root) (\(installation.layout))",
+ )
}
setProgress(["phase": "preparing", "layout": layout])
do {
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 2def68eb..eceecf66 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -10,13 +10,24 @@ enum GuestAPIError: Error, CustomStringConvertible {
case invalidRequest(String)
case unsupportedMethod(String)
case operationFailed(String)
+ /// The request would repeat work the guest has already done. The code is
+ /// sent as the error code so a client can tell it apart from a failure.
+ case alreadyDone(code: String, message: String)
var description: String {
switch self {
case let .invalidRequest(message), let .operationFailed(message): message
case let .unsupportedMethod(method): "Unknown method: \(method)"
+ case let .alreadyDone(_, message): message
}
}
+
+ var code: String {
+ if case let .alreadyDone(code, _) = self {
+ return code
+ }
+ return "invalid_operation"
+ }
}
/// The API boundary is deliberately small: named operations and JSON values.
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index a109ed18..0ae942d6 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -2999,6 +2999,40 @@
}
}
},
+ "Bootstrap Already Installed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap Already Installed"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ブートストラップはインストール済みです"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "부트스트랩이 이미 설치됨"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap đã được cài đặt"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "引导环境已安装"
+ }
+ }
+ }
+ },
"Bootstrap Tools" : {
"localizations" : {
"ja" : {
@@ -3027,6 +3061,40 @@
}
}
},
+ "Bootstrap already installed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap already installed"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ブートストラップはインストール済みです"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "부트스트랩이 이미 설치됨"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap đã được cài đặt"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "引导环境已安装"
+ }
+ }
+ }
+ },
"Bootstrap installation failed" : {
"localizations" : {
"en" : {
@@ -23924,6 +23992,74 @@
}
}
},
+ "The bootstrap is already installed in %@. To reinstall it, uninstall the bootstrap first." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The bootstrap is already installed in %@. To reinstall it, uninstall the bootstrap first."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ブートストラップは %@ にインストール済みです。再インストールするには、先にブートストラップを削除してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "부트스트랩이 이미 %@에 설치되어 있습니다. 다시 설치하려면 먼저 부트스트랩을 제거하세요."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap đã được cài đặt tại %@. Để cài lại, hãy gỡ bootstrap trước."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "引导环境已安装在 %@。如需重新安装,请先卸载引导环境。"
+ }
+ }
+ }
+ },
+ "The bootstrap is already installed. To reinstall it, uninstall the bootstrap first." : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The bootstrap is already installed. To reinstall it, uninstall the bootstrap first."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ブートストラップはインストール済みです。再インストールするには、先にブートストラップを削除してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "부트스트랩이 이미 설치되어 있습니다. 다시 설치하려면 먼저 부트스트랩을 제거하세요."
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bootstrap đã được cài đặt. Để cài lại, hãy gỡ bootstrap trước."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "引导环境已安装。如需重新安装,请先卸载引导环境。"
+ }
+ }
+ }
+ },
"The guest agent is not connected. Wait for it to connect, then try again." : {
"localizations" : {
"en" : {
@@ -26141,6 +26277,40 @@
}
}
},
+ "Unable to install the bootstrap.\n\n%@" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unable to install the bootstrap.\n\n%@"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ブートストラップをインストールできません。\n\n%@"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "부트스트랩을 설치할 수 없습니다.\n\n%@"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Không thể cài đặt bootstrap.\n\n%@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "无法安装引导环境。\n\n%@"
+ }
+ }
+ }
+ },
"Unable to install the bootstrap. Check that the guest agent is connected, then try again." : {
"localizations" : {
"en" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
index 48cdc69a..6ffced27 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift
@@ -14,6 +14,8 @@ final class VPhoneGuestControl {
case unsupportedCapability(String)
case protocolError(String)
case guestError(String)
+ /// `bootstrap.install` found a completed installation in the guest.
+ case bootstrapAlreadyInstalled(String)
var description: String {
switch self {
@@ -21,7 +23,7 @@ final class VPhoneGuestControl {
VPhoneLocalization.text("The guest agent is not connected. Wait for it to connect, then try again.")
case let .unsupportedCapability(value): "guest does not support capability: \(value)"
case let .protocolError(value): "API protocol error: \(value)"
- case let .guestError(value): value
+ case let .guestError(value), let .bootstrapAlreadyInstalled(value): value
}
}
}
@@ -371,7 +373,11 @@ final class VPhoneGuestControl {
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")
+ let message = error["message"] as? String ?? "Guest operation failed"
+ if error["code"] as? String == "bootstrap_already_installed" {
+ throw ControlError.bootstrapAlreadyInstalled(message)
+ }
+ throw ControlError.guestError(message)
}
guard response.status == 200, let result = envelope["result"] as? [String: Any]
else { throw ControlError.protocolError("missing result (HTTP \(response.status))") }
@@ -465,9 +471,32 @@ final class VPhoneGuestControl {
try await createDirectory(path: "/var/root/Library/Caches")
try await uploadFile(path: path, data: data)
defer { Task { try? await deleteFile(path: path) } }
- return try await call("bootstrap.install", params: ["layout": layout, "package_path": path])
+ return try await callBootstrapInstall(["layout": layout, "package_path": path])
}
- return try await call("bootstrap.install", params: ["layout": layout])
+ return try await callBootstrapInstall(["layout": layout])
+ }
+
+ /// vphoned refuses a second install. A current guest says so with an error
+ /// code; an older one only with this message.
+ private func callBootstrapInstall(_ params: [String: Any]) async throws -> [String: Any] {
+ do {
+ return try await call("bootstrap.install", params: params)
+ } catch let ControlError.guestError(message)
+ where message.hasPrefix("Irisin bootstrap already completed")
+ {
+ throw ControlError.bootstrapAlreadyInstalled(message)
+ }
+ }
+
+ /// The completed installation vphoned would refuse to install over, or nil
+ /// when there is none or the guest cannot be asked. Only `jbroot` marks a
+ /// completed install; `roots` also lists foreign roots install may reuse.
+ func completedBootstrap() async -> (root: String, layout: String)? {
+ guard guestCapabilities.contains("bootstrap_uninstall"),
+ let installation = try? await call("bootstrap.inspect"),
+ let root = installation["jbroot"] as? String, !root.isEmpty
+ else { return nil }
+ return (root, installation["layout"] as? String ?? "")
}
func bootstrapStatus() async throws -> [String: Any] {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift
index af44d81b..337524be 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift
@@ -60,20 +60,56 @@ extension VPhoneMenuController {
}
@objc func installBootstrap() {
- chooseBootstrapLayout(localURL: nil)
+ unlessBootstrapInstalled { [weak self] in
+ self?.chooseBootstrapLayout(localURL: nil)
+ }
}
@objc func installBootstrapFromFile() {
- let panel = NSOpenPanel()
- panel.canChooseFiles = true
- panel.canChooseDirectories = false
- panel.allowsMultipleSelection = false
- panel.allowedContentTypes = [UTType(filenameExtension: "deb") ?? .data]
- panel.prompt = VPhoneLocalization.text("Install")
- panel.message = VPhoneLocalization.text("Choose an Irisin .deb package to install in the guest.")
- VPhoneAlert.present(panel) { [weak self] response in
- guard response == .OK, let url = panel.url else { return }
- self?.chooseBootstrapLayout(localURL: url)
+ unlessBootstrapInstalled { [weak self] in
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = true
+ panel.canChooseDirectories = false
+ panel.allowsMultipleSelection = false
+ panel.allowedContentTypes = [UTType(filenameExtension: "deb") ?? .data]
+ panel.prompt = VPhoneLocalization.text("Install")
+ panel.message = VPhoneLocalization.text("Choose an Irisin .deb package to install in the guest.")
+ VPhoneAlert.present(panel) { response in
+ guard response == .OK, let url = panel.url else { return }
+ self?.chooseBootstrapLayout(localURL: url)
+ }
+ }
+ }
+
+ /// vphoned installs the bootstrap once and refuses a second install, so
+ /// ask it first and explain instead of starting an install that fails.
+ /// A guest that cannot be asked goes straight on; its install answer is
+ /// handled the same way below.
+ private func unlessBootstrapInstalled(_ proceed: @escaping @MainActor () -> Void) {
+ guard !isInstallingBootstrap, !isUninstallingBootstrap else { return }
+ Task {
+ if let installation = await control.completedBootstrap() {
+ presentBootstrapAlreadyInstalled(root: installation.root)
+ } else {
+ proceed()
+ }
+ }
+ }
+
+ private func presentBootstrapAlreadyInstalled(root: String) {
+ let message = VPhoneLocalization.format(
+ "The bootstrap is already installed in %@. To reinstall it, uninstall the bootstrap first.", root,
+ )
+ let canUninstall = control.isConnected && control.guestCapabilities.contains("bootstrap_uninstall")
+ VPhoneAlert.present(
+ title: "Bootstrap Already Installed",
+ message: message,
+ style: .informational,
+ buttons: canUninstall ? ["OK", "Uninstall Bootstrap…"] : ["OK"],
+ ) { [weak self] response in
+ if canUninstall, response == .alertSecondButtonReturn {
+ self?.uninstallBootstrap()
+ }
}
}
@@ -171,6 +207,21 @@ extension VPhoneMenuController {
} else {
VPhoneLocalization.format("Installed Irisin %@ in %@.", version, root)
}
+ } catch VPhoneGuestControl.ControlError.bootstrapAlreadyInstalled {
+ poller.cancel()
+ await poller.value
+ statusLabel.stringValue = VPhoneLocalization.text("Bootstrap already installed")
+ alert.informativeText = VPhoneLocalization.text(
+ "The bootstrap is already installed. To reinstall it, uninstall the bootstrap first.",
+ )
+ } catch let VPhoneGuestControl.ControlError.guestError(message) where !message.isEmpty {
+ // vphoned answered: show its reason rather than suggest the
+ // connection is at fault.
+ poller.cancel()
+ await poller.value
+ statusLabel.stringValue = VPhoneLocalization.text("Bootstrap installation failed")
+ alert.alertStyle = .warning
+ alert.informativeText = VPhoneLocalization.format("Unable to install the bootstrap.\n\n%@", message)
} catch {
poller.cancel()
await poller.value