Run a virtual iPhone on an Apple Silicon Mac.
Swift
Rebuild app registrations in the bootstrap, and set the time zone through IcliKit
Lakr650a8a0c3cf4
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex bea759cd..1be3719c 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -78,8 +78,11 @@ command-line executable remains unentitled and still launches `vphone-vm`.The guest links IcliKit directly. App registration refresh is available through`POST /v1/apps/refresh` or the WebSocket method `apps.refresh`. An optional-`directory` selects a bundle directory; omitted, it uses the bootstrap's-`/Applications`. IcliKit verifies registrations by reading them back.+`directory` selects a bundle directory; omitted, it uses `/Applications` under+the bootstrap vphoned installed (vphoned runs from the system volume, so+IcliKit cannot find the bootstrap itself). `system.uicache` is the same call.+IcliKit verifies registrations by reading them back; a bundle it could not+register or verify is named in the error message.`screen.screenshot` uses IcliKit's native screen capture and returns a base64JPEG with `mime_type`, `width`, and `height`; the current VM produces 1290×2796.The host's Save/Copy Screenshot menu decodes this guest image. It omits the@@ -312,8 +315,8 @@ any key is sent. It needs no private entitlement. `timeout` is 1–60 seconds,`time.timezone` (capability `timezone`; REST `GET/PUT /v1/timezone`) returns`{identifier, automatic, seconds_from_gmt}`: the Olson name`/var/db/timezone/localtime` points to under `/var/db/timezone/zoneinfo`, and-whether timed sets the zone automatically. `{identifier}` pins the zone: it turns-the automatic time zone off through CoreTime (`TMSetAutomaticTimeZoneEnabled`,+whether timed sets the zone automatically; IcliKit does the work. `{identifier}`+pins the zone: it turns the automatic time zone off through CoreTime (`TMSetAutomaticTimeZoneEnabled`,which timed accepts only with the `com.apple.timed` entitlement) and askstzlinkd to re-point the link through libutil's `tzlink` (`com.apple.tzlink.allow`);tzlinkd then posts `SignificantTimeChangeNotification`, and notifyd'sdiff --git a/VPhoneDaemon/Daemon/APIWire.swift b/VPhoneDaemon/Daemon/APIWire.swiftindex 8f5e6db7..9d2e6e35 100644--- a/VPhoneDaemon/Daemon/APIWire.swift+++ b/VPhoneDaemon/Daemon/APIWire.swift@@ -41,17 +41,23 @@ enum APIWire {let result = try GuestAPI.execute(method: request.method, params: request.params)return .json(["type": "response", "id": request.id ?? NSNull(), "result": result])} catch {- 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 {- ("operation_failed", String(describing: error))+ var body: [String: Any]+ if let error = error as? IcliError {+ body = ["code": error.code, "message": error.message]+ // A failed command's output says what failed, which the+ // generic "command exited with status 1" does not.+ if case let .commandFailed(output) = error {+ body.merge(output.filter { $0.key != "error" }) { $1 }+ if output["message"] as? String == nil { body["message"] = error.message }}+ } else if let error = error as? GuestAPIError {+ body = ["code": error.code, "message": error.description]+ } else {+ body = ["code": "operation_failed", "message": String(describing: error)]+ }return .json(status: 400, ["type": "response", "id": request.id ?? NSNull(),- "error": ["code": code, "message": message],+ "error": body,])}}diff --git a/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swiftindex c3819f7c..44d3f9ee 100644--- a/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+AppDetail.swift@@ -1,5 +1,6 @@import Foundationimport IcliKit+import IcliSystem// MARK: - App Detail and System Control@@ -31,7 +32,7 @@ extension GuestAPI {case "apps.network_policy":return try appNetworkPolicy(string(params, "bundle_id"), repair: bool(params, "repair"))case "system.uicache":- return try refreshApps(directory: optionalString(params, "directory"))+ return try refreshAppRegistrations(directory: optionalString(params, "directory"))case "system.system_apps":return try systemAppsVisibility(set: params["visible"] as? Bool)case "system.respring":@@ -46,3 +47,34 @@ extension GuestAPI {}}}++// MARK: - App Registrations++extension GuestAPI {+ /// `uicache -a`. Without a directory, IcliKit looks for the bootstrap from+ /// the running executable, and vphoned runs from the system volume, so it+ /// finds none and refreshes the system's /Applications, failing on Apple's+ /// apps. The bootstrap vphoned installed names the directory instead.+ static func refreshAppRegistrations(directory: String?) throws -> [String: Any] {+ guard let directory = try directory ?? GuestIrisinInstaller.completedBootstrap().map({ $0.root + "/Applications" })+ else {+ throw GuestAPIError.operationFailed("No bootstrap environment was found")+ }+ do {+ return try refreshApps(directory: directory)+ } catch let IcliError.commandFailed(output) {+ // The output names the bundles; the error itself gives only a status.+ let names = { (key: String) in+ (output[key] as? [String] ?? []).map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")+ }+ var sentences: [String] = []+ if !names("failed").isEmpty {+ sentences.append("LaunchServices did not register or remove \(names("failed")).")+ }+ if !names("unverified").isEmpty {+ sentences.append("LaunchServices does not list \(names("unverified")) as expected after the refresh.")+ }+ throw GuestAPIError.operationFailed(sentences.joined(separator: " "))+ }+ }+}diff --git a/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift b/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swiftindex 96deb87a..88ffe070 100644--- a/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift@@ -1,113 +1,22 @@-import Darwinimport Foundation+import IcliKit// MARK: - Time Zone-/// The system time zone is the `/var/db/timezone/localtime` symlink into-/// `/var/db/timezone/zoneinfo`. Only tzlinkd (`com.apple.tzlink`) moves it:-/// libutil's `tzlink(name)` hands it an Olson name, tzlinkd accepts the request-/// from a holder of `com.apple.tzlink.allow`, re-points the link and posts-/// `SignificantTimeChangeNotification`. timed owns the automatic time zone and-/// would put its own zone back, so a set first turns that off through-/// CoreTime, which timed accepts only from a holder of `com.apple.timed`.-/// Neither function is in the SDK headers; both are looked up at run time.+/// IcliKit owns the system time zone: tzlinkd moves the+/// `/var/db/timezone/localtime` link for a holder of `com.apple.tzlink.allow`,+/// and a set first turns timed's automatic time zone off through CoreTime,+/// which timed accepts only from a holder of `com.apple.timed`. Each answer is+/// `{identifier, automatic, seconds_from_gmt}`, plus `changed` after a set.extension GuestAPI {static func executeTimeZone(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {guard method == "time.timezone" else { return nil }- let changed: Boolif let identifier = optionalString(params, "identifier") {- changed = try pinTimeZone(identifier)- } else if let automatic = params["automatic"] as? Bool {- changed = try setAutomaticTimeZone(automatic)- } else {- return timeZoneState()+ return try setTimeZone(identifier)}- var state = timeZoneState()- state["changed"] = changed- return state- }-- private static let zoneInfoDirectory = "/var/db/timezone/zoneinfo/"- private static let localTimeLink = "/var/db/timezone/localtime"-- /// `{identifier, automatic, seconds_from_gmt}`. `automatic` is null when- /// CoreTime does not answer.- private static func timeZoneState() -> [String: Any] {- let identifier = systemTimeZoneIdentifier()- let zone = identifier.flatMap(TimeZone.init(identifier:))- return [- "identifier": identifier.map { $0 as Any } ?? NSNull(),- "automatic": automaticTimeZoneEnabled().map { $0 as Any } ?? NSNull(),- "seconds_from_gmt": zone.map { $0.secondsFromGMT() as Any } ?? NSNull(),- ]- }-- /// Read from the link, not `TimeZone.current`, which this process caches.- private static func systemTimeZoneIdentifier() -> String? {- guard let target = try? FileManager.default.destinationOfSymbolicLink(atPath: localTimeLink) else {- return nil- }- return target.hasPrefix(zoneInfoDirectory) ? String(target.dropFirst(zoneInfoDirectory.count)) : target- }-- /// Turns the automatic time zone off and links `identifier`. Returns false- /// when the guest was already pinned to it.- private static func pinTimeZone(_ identifier: String) throws -> Bool {- let components = identifier.split(separator: "/", omittingEmptySubsequences: false)- guard !components.contains(where: { $0.isEmpty || $0.hasPrefix(".") }),- FileManager.default.fileExists(atPath: zoneInfoDirectory + identifier)- else {- throw GuestAPIError.invalidRequest("\(identifier) is not a time zone in \(zoneInfoDirectory)")- }- let automaticChanged = try setAutomaticTimeZone(false)- guard systemTimeZoneIdentifier() != identifier else { return automaticChanged }- guard let tzlink = symbol("/usr/lib/libutil.dylib", "tzlink", as: TimeZoneLink.self) else {- throw GuestAPIError.operationFailed("libutil does not export tzlink")- }- let error = tzlink(identifier)- guard error == 0 else {- throw GuestAPIError.operationFailed("tzlink \(identifier) failed: \(String(cString: strerror(error)))")- }- guard systemTimeZoneIdentifier() == identifier else {- throw GuestAPIError.operationFailed("tzlinkd accepted \(identifier) but \(localTimeLink) did not change")+ if let automatic = params["automatic"] as? Bool {+ return try setAutomaticTimeZone(automatic)}- return true- }-- /// Returns false when timed already had that setting.- private static func setAutomaticTimeZone(_ enabled: Bool) throws -> Bool {- guard let current = automaticTimeZoneEnabled(),- let set = symbol(coreTimePath, "TMSetAutomaticTimeZoneEnabled", as: SetAutomaticTimeZone.self)- else {- throw GuestAPIError.operationFailed("CoreTime does not export the automatic time zone functions")- }- guard current != enabled else { return false }- // timed takes the command without a reply; ask until it reports the- // new setting so a later tzlink is not undone by the old one.- set(enabled)- var attempts = 0- while automaticTimeZoneEnabled() != enabled, attempts < 20 {- usleep(50000)- attempts += 1- }- guard automaticTimeZoneEnabled() == enabled else {- throw GuestAPIError.operationFailed("timed did not turn the automatic time zone \(enabled ? "on" : "off")")- }- return true- }-- private static func automaticTimeZoneEnabled() -> Bool? {- symbol(coreTimePath, "TMIsAutomaticTimeZoneEnabled", as: IsAutomaticTimeZone.self).map { $0() }- }-- private typealias TimeZoneLink = @convention(c) (UnsafePointer<CChar>) -> Int32- private typealias SetAutomaticTimeZone = @convention(c) (Bool) -> Void- private typealias IsAutomaticTimeZone = @convention(c) () -> Bool-- private static let coreTimePath = "/System/Library/PrivateFrameworks/CoreTime.framework/CoreTime"-- private static func symbol<Function>(_ library: String, _ name: String, as _: Function.Type) -> Function? {- guard let handle = dlopen(library, RTLD_LAZY), let address = dlsym(handle, name) else { return nil }- return unsafeBitCast(address, to: Function.self)+ return try timeZone()}}diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex a51aa401..b137f4b0 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -178,7 +178,7 @@ enum GuestAPI {case "apps.search":return try searchApps(string(params, "query"))case "apps.refresh":- return try refreshApps(directory: params["directory"] as? String)+ return try refreshAppRegistrations(directory: params["directory"] as? String)case "apps.launch":let id = try string(params, "bundle_id")if let url = params["url"] as? String {