Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Give the guest the Mac's time zone

Jacky436680a5d715
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index f3eee25f..bea759cd 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -173,7 +173,7 @@ shows every path in a destructive confirmation alert before sending the request.
## HTTP and WebSocket contract
JSON resource routes cover device state, apps, input, location, Developer Mode, low power
-mode, clipboard, file listing, and keychain. `GET/PUT
+mode, time zone, clipboard, file listing, and keychain. `GET/PUT
/v1/files/content?path=<absolute-guest-path>` transfer bytes with
`application/octet-stream`; upload writes to a temporary file in the same
directory then renames it after all chunks have been written. JSON bodies
@@ -279,7 +279,7 @@ request carries `"force": true`.
| Darwin notifications | `notify.post {name, state?}` (`postDarwinNotification`; `state` is a UInt64, as a number or a decimal string, stored before the post), `notify.state {name}` (`darwinNotificationState`) |
| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `network.static_names.get`, `network.static_names.set {entries}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` |
| Apps | `apps.list`, `search`, `refresh`, `launch`, `terminate`, `foreground`, `open_url`, `install`, `info`, `binary`, `data_dir`, `url_schemes`, `handlers`, `registration`, `register`, `network_policy {repair?}`; `apps.uninstall`, `unregister`, `unregister_dir` **force** |
-| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `diagnostics.self_test` |
+| System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `time.timezone {identifier?, automatic?}` (see below), `diagnostics.self_test` |
| Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` |
| Preferences, clipboard, location | `settings.get/set/delete`, `clipboard.get/set/clear`, `location.set/clear/current` |
| Keychain | `keychain.list {class?}`, `add`, `delete`, `get`, `update`, `database` |
@@ -309,6 +309,20 @@ at once; a dark but unlocked one is only woken. A guest with a passcode needs
any key is sent. It needs no private entitlement. `timeout` is 1–60 seconds,
10 by default. Measurements: `Research/Guest/screen_unlock.md`.
+`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`,
+which timed accepts only with the `com.apple.timed` entitlement) and asks
+tzlinkd to re-point the link through libutil's `tzlink` (`com.apple.tzlink.allow`);
+tzlinkd then posts `SignificantTimeChangeNotification`, and notifyd's
+`monitor` on the link (`/etc/notify.conf`) posts `com.apple.system.timezone`,
+so SpringBoard's clock changes at once. `{automatic: true}` hands the zone
+back to timed. Both add `changed`. `vphone-vm` sends the Mac's zone after
+every connect and whenever the Mac's zone changes (`VPhoneTimeZoneSync`), so
+the guest's clock reads the same local time as the host.
+
`network.ipv4.get` and `network.ipv4.set` read and write the IPv4 settings of
one interface (default `en0`) in configd's network preferences,
`/var/preferences/SystemConfiguration/preferences.plist`, through SCPreferences
diff --git a/Skills/vphone-guest-control/references/rpc-methods.md b/Skills/vphone-guest-control/references/rpc-methods.md
index 86bec2eb..5e75582b 100644
--- a/Skills/vphone-guest-control/references/rpc-methods.md
+++ b/Skills/vphone-guest-control/references/rpc-methods.md
@@ -181,6 +181,7 @@ size problem.
| `settings.delete` | `domain`, `key` |
| `clipboard.get` / `set` / `clear` | `set` takes `text` |
| `location.set` / `clear` / `current` | `set` takes latitude/longitude; read-back can fail on some guests |
+| `time.timezone` | none reads `{identifier, automatic, seconds_from_gmt}`; `identifier` (Olson name) pins the zone and turns automatic off; `automatic: true` hands it back to timed. The VM sends the Mac's zone on every connect |
| `notify.post` / `notify.state` | `name`, `state?` |
| `keychain.*` | Lists, adds and edits secrets; use only on request and never print values |
diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
index d51abcbe..b824a035 100644
--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements
@@ -539,6 +539,10 @@
<true/>
<key>com.apple.springboard.openurlswhenlocked</key>
<true/>
+ <key>com.apple.timed</key>
+ <true/>
+ <key>com.apple.tzlink.allow</key>
+ <true/>
<key>com.apple.usernotification.notificationregistrarproxy</key>
<true/>
<key>com.apple.usernotification.notificationschedulerproxy</key>
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
index 34a3a167..008bb6ac 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Extended.swift
@@ -16,6 +16,7 @@ extension GuestAPI {
executeEnvironment,
executeDeviceIdentity,
executeSetupAssistant,
+ executeTimeZone,
]
for area in areas {
if let result = try area(method, params) {
diff --git a/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift b/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift
new file mode 100644
index 00000000..96deb87a
--- /dev/null
+++ b/VPhoneDaemon/Daemon/GuestAPI+TimeZone.swift
@@ -0,0 +1,113 @@
+import Darwin
+import Foundation
+
+// 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.
+extension GuestAPI {
+ static func executeTimeZone(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
+ guard method == "time.timezone" else { return nil }
+ let changed: Bool
+ if let identifier = optionalString(params, "identifier") {
+ changed = try pinTimeZone(identifier)
+ } else if let automatic = params["automatic"] as? Bool {
+ changed = try setAutomaticTimeZone(automatic)
+ } else {
+ return timeZoneState()
+ }
+ 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")
+ }
+ 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)
+ }
+}
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index 667d6e35..a51aa401 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -120,6 +120,7 @@ enum GuestAPI {
"network_hostname",
"network_static_names",
"network_resolve",
+ "timezone",
],
]
}
diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
index 24497cfb..1190ca54 100644
--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift
@@ -244,6 +244,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandle
case (.GET, "/v1/developer-mode"): "developer_mode.status"
case (.POST, "/v1/developer-mode/enable"): "developer_mode.enable"
case (.GET, "/v1/low-power-mode"), (.PUT, "/v1/low-power-mode"): "power.low_power_mode"
+ case (.GET, "/v1/timezone"), (.PUT, "/v1/timezone"): "time.timezone"
case (.GET, "/v1/clipboard"), (.PUT, "/v1/clipboard"): verb == .GET ? "clipboard.get" : "clipboard.set"
case (.DELETE, "/v1/clipboard"): "clipboard.clear"
case (.GET, "/v1/files"): "files.list"
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
index cd59d1cf..f2ed33c2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControlSystem.swift
@@ -38,4 +38,14 @@ extension VPhoneGuestControl {
throw ControlError.guestError("low_power_mode: failed to set state on guest")
}
}
+
+ // MARK: - Time Zone
+
+ /// Pins the guest's system time zone to an Olson name such as
+ /// `Asia/Shanghai` and turns its automatic time zone off. Returns false
+ /// when the guest was already pinned to it.
+ func setTimeZone(_ identifier: String) async throws -> Bool {
+ let result = try await call("time.timezone", params: ["identifier": identifier])
+ return result["changed"] as? Bool ?? false
+ }
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneTimeZoneSync.swift b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneTimeZoneSync.swift
new file mode 100644
index 00000000..edf3a31e
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/HostDevices/VPhoneTimeZoneSync.swift
@@ -0,0 +1,58 @@
+import Foundation
+
+/// Keeps the guest's system time zone on the Mac's. The guest has no cellular
+/// network and at most a simulated location, so its automatic time zone has
+/// little to go on; vphoned pins the zone the host sends instead.
+///
+/// Call `start()` when the guest reports the "timezone" capability, on every
+/// connect: it sends the Mac's zone, then again whenever the Mac's changes.
+/// vphoned answers a zone it already has without touching anything.
+@MainActor
+class VPhoneTimeZoneSync {
+ private let control: VPhoneGuestControl
+ private var observer: NSObjectProtocol?
+ private var sending: Task<Void, Never>?
+
+ init(control: VPhoneGuestControl) {
+ self.control = control
+ }
+
+ func start() {
+ if observer == nil {
+ observer = NotificationCenter.default.addObserver(
+ forName: .NSSystemTimeZoneDidChange,
+ object: nil,
+ queue: .main,
+ ) { [weak self] _ in
+ Task { @MainActor in self?.send() }
+ }
+ }
+ send()
+ }
+
+ func stop() {
+ if let observer {
+ NotificationCenter.default.removeObserver(observer)
+ }
+ observer = nil
+ sending?.cancel()
+ sending = nil
+ }
+
+ private func send() {
+ NSTimeZone.resetSystemTimeZone()
+ let identifier = TimeZone.current.identifier
+ let previous = sending
+ sending = Task { [control] in
+ // Two quick changes on the Mac must reach the guest in order.
+ await previous?.value
+ guard !Task.isCancelled else { return }
+ do {
+ let changed = try await control.setTimeZone(identifier)
+ print("[timezone] guest \(changed ? "set to" : "already on") \(identifier)")
+ } catch {
+ print("[timezone] could not set the guest to \(identifier): \(error)")
+ }
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index cc96afc9..c630adac 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -13,6 +13,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
private var keychainWindowController: VPhoneKeychainWindowController?
private var appWindowController: VPhoneAppWindowController?
private var locationProvider: VPhoneLocationProvider?
+ private var timeZoneSync: VPhoneTimeZoneSync?
private var hostAutomationServer: VPhoneHostAutomationServer?
private var cameraServer: VPhoneCameraServer?
private var apiProxy: VPhoneAPIProxy?
@@ -101,6 +102,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
let provider = VPhoneLocationProvider(control: control)
locationProvider = provider
+ timeZoneSync = VPhoneTimeZoneSync(control: control)
let camServer = VPhoneCameraServer()
cameraServer = camServer
@@ -211,7 +213,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
menuController = mc
// Wire location toggle through onConnect/onDisconnect
- control.onConnect = { [weak self, weak mc, weak provider = locationProvider] caps in
+ control.onConnect = { [weak self, weak mc, weak provider = locationProvider, weak timeZoneSync] caps in
mc?.updateConnectAvailability(available: true)
mc?.updateInstallAvailability(available: caps.contains("ipa_install"))
mc?.updateBootstrapAvailability(available: caps.contains("bootstrap_install"))
@@ -234,11 +236,14 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
}
mc?.syncBatteryFromHost()
mc?.syncLowPowerModeFromHost()
+ if caps.contains("timezone") {
+ timeZoneSync?.start()
+ }
Task { @MainActor [weak self] in
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak mc, weak provider = locationProvider] in
+ control.onDisconnect = { [weak mc, weak provider = locationProvider, weak timeZoneSync] in
mc?.updateConnectAvailability(available: false)
mc?.updateInstallAvailability(available: false)
mc?.updateBootstrapAvailability(available: false)
@@ -253,22 +258,27 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
provider?.stopReplay()
provider?.stopForwarding()
mc?.updateLocationCapability(available: false)
+ timeZoneSync?.stop()
}
} else if !command.dfu {
// Headless mode: auto-start location as before (no menu exists)
- control.onConnect = { [weak self, weak provider = locationProvider] caps in
+ control.onConnect = { [weak self, weak provider = locationProvider, weak timeZoneSync] caps in
if caps.contains("location") {
provider?.startForwarding()
} else {
print("[location] guest does not support location simulation")
}
+ if caps.contains("timezone") {
+ timeZoneSync?.start()
+ }
Task { @MainActor [weak self] in
await self?.installPackageIfRequested(caps: caps)
}
}
- control.onDisconnect = { [weak provider = locationProvider] in
+ control.onDisconnect = { [weak provider = locationProvider, weak timeZoneSync] in
provider?.stopReplay()
provider?.stopForwarding()
+ timeZoneSync?.stop()
}
}
@@ -390,6 +400,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
stopControlServices()
locationProvider?.stopForwarding()
locationProvider?.stopReplay()
+ timeZoneSync?.stop()
cameraServer?.disconnect()
menuController?.stopBatteryMonitoring()
windowController?.closeForRestart()
@@ -402,6 +413,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
keychainWindowController = nil
appWindowController = nil
locationProvider = nil
+ timeZoneSync = nil
cameraServer = nil
hostAutomationServer = nil
apiProxy = nil