Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let the host set the guest's pinned device name through vphoned

Jacky4391dedb7e8a
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.md
index 41648d96..7f92cecb 100644
--- a/Research/vphoned_http_api.md
+++ b/Research/vphoned_http_api.md
@@ -280,7 +280,7 @@ request carries `"force": true`.
| launchd | `services.list`, `status`, `print`, `dump`, `disabled`, `start`, `enable`, `load`; `services.stop`, `disable`, `remove`, `signal`, `unload` **force**; `launchd.getenv`, `setenv`, `unsetenv` |
| Logs | `logs.syslog {seconds, process?, level?, max_lines?}` (a bounded capture of at most 60 s), `logs.crashes {bundle_id?}`, `logs.crash {path}` |
| 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` |
+| 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?}`, `device.name.get`, `device.name.set {name}` (see below), `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**, `system.shutdown` **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}` |
@@ -390,6 +390,18 @@ replaced; `set` with none or null puts that one back. A name vphoned did not set
is never changed by a null. `vphone-vm` calls `set` after every connect with the
VM's `localHostName`, or null when it has none.
+`device.name.get` and `device.name.set` read and write the device name the
+guest is pinned to, the one Xcode, `devicectl` and Finder show
+(`VPhoneDaemon/Daemon/GuestAPI+Device.swift`). Both return `{name}`, null when
+the guest shows its own; `set` adds `changed`. `set` with a `name` (not blank,
+at most 255 UTF-8 bytes, no control character) stores it as `DeviceName` in
+`/var/db/vphone/devicename.plist`; with none or null it removes the file. On a
+change vphoned applies configd's preferences unchanged, so configd publishes
+again and `libdevicename.dylib` pins the new name at once, and posts
+`com.apple.mobile.lockdown.device_name_changed`. The file outlives a reboot.
+`vphone-vm` calls `set` after every connect with the VM's name. See
+`Research/Guest/device_name_pinning.md`.
+
`network.static_names.set` replaces the names the guest resolves locally, given
as `entries: [{address, names}]` (IPv4 only; an empty list withdraws them).
vphoned registers each name as a LocalOnly, known-unique A record with the
@@ -413,7 +425,7 @@ Account passwords, boot logo rendering and package installation, removal and
repository changes are deliberately not exposed. `/v1/health` lists the new
areas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,
`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,
-`app_details`, `system_control`, `system_shutdown`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
+`app_details`, `system_control`, `system_shutdown`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `device_name`, `network_static_names`, `network_resolve`, `display_auto_lock`, `screen_unlock`) so a host can hide
panels an older agent cannot serve. icli failures reach the caller with
icli's own error `code` (`failed`, `unavailable`, `device_locked`, …) and
message.
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
index dc9c203b..c012f66c 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift
@@ -47,6 +47,15 @@ extension GuestAPI {
case "network.hostname.set":
// An absent or null name puts back the one vphoned replaced.
return try networkHostName(set: .some(params["local_host_name"] as? String))
+ case "device.name.get":
+ return deviceNameState()
+ case "device.name.set":
+ // An absent or null name gives the guest its own back.
+ let name = params["name"].flatMap { $0 is NSNull ? nil : $0 }
+ guard name == nil || name is String else {
+ throw GuestAPIError.invalidRequest("name must be a string or null")
+ }
+ return try setDeviceName(name as? String)
case "device.ioreg":
return try ioregistry(plane: optionalString(params, "plane") ?? "IOService")
case "device.environment":
@@ -170,6 +179,107 @@ extension GuestAPI {
}
}
+// MARK: - Device name
+
+/// The device name the host pins: what Xcode, devicectl and Finder show.
+/// `libdevicename.dylib` in configd and lockdownd reads it from
+/// `deviceNameConfigPath` (see `Research/Guest/device_name_pinning.md`):
+/// configd publishes it as `Setup:/System`'s ComputerName and lockdownd refuses
+/// every rename. The guest's own name stays in preferences.plist.
+///
+/// The file outlives a reboot, so configd's first publication at boot already
+/// carries the name. A change applies at once: both daemons check the file on
+/// every decision, and applying the preferences unchanged makes configd's
+/// preferences monitor publish again.
+extension GuestAPI {
+ /// Must match `VP_DEVICE_NAME_CONFIG_PATH` and `VP_DEVICE_NAME_CONFIG_KEY`
+ /// in `VPhoneGuestComponents/DeviceName/DeviceNamePolicy.h`.
+ static let deviceNameConfigPath = "/var/db/vphone/devicename.plist"
+ static let deviceNameConfigKey = "DeviceName"
+ /// What lockdownd posts after a rename; lockdown clients read the name again.
+ static let deviceNameChangedNotification = "com.apple.mobile.lockdown.device_name_changed"
+
+ /// `{name}`: the pinned name, or null when the guest shows its own.
+ static func deviceNameState() -> [String: Any] {
+ ["name": storedDeviceName() ?? NSNull()]
+ }
+
+ /// Pin `name`, or with nil give the guest its own back. Returns the state
+ /// plus `changed`.
+ static func setDeviceName(_ name: String?) throws -> [String: Any] {
+ if let name {
+ try validateDeviceName(name)
+ }
+ let changed = storedDeviceName() != name
+ if changed {
+ try writeDeviceName(name)
+ guard storedDeviceName() == name else {
+ throw GuestAPIError.operationFailed("\(deviceNameConfigPath) did not read back as written")
+ }
+ var error: NSString?
+ guard vp_preferences_apply(&error) else {
+ throw GuestAPIError.operationFailed(
+ "The name is stored but configd was not asked to publish it: \(error.map(String.init) ?? "apply failed")",
+ )
+ }
+ _ = try? postDarwinNotification(deviceNameChangedNotification, state: nil)
+ }
+ var state = deviceNameState()
+ state["changed"] = changed
+ return state
+ }
+
+ /// The host's rule (`VPhoneGuestDeviceName.validate`), which the guest's
+ /// (`VPDeviceNameCreateFromBytes`) accepts: not blank, at most 255 UTF-8
+ /// bytes, no control character.
+ private static func validateDeviceName(_ name: String) throws {
+ if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ throw GuestAPIError.invalidRequest("name must not be blank")
+ }
+ if name.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }) {
+ throw GuestAPIError.invalidRequest("name must not contain a control character")
+ }
+ if name.utf8.count > 255 {
+ throw GuestAPIError.invalidRequest("name must be at most 255 bytes in UTF-8")
+ }
+ }
+
+ private static func storedDeviceName() -> String? {
+ guard let data = FileManager.default.contents(atPath: deviceNameConfigPath),
+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let name = plist[deviceNameConfigKey] as? String, !name.isEmpty
+ else { return nil }
+ return name
+ }
+
+ /// Replaces the file in one rename, which is what the hook's stamp check
+ /// expects, or removes it.
+ private static func writeDeviceName(_ name: String?) throws {
+ guard let name else {
+ if unlink(deviceNameConfigPath) != 0, errno != ENOENT {
+ throw GuestAPIError.operationFailed("Could not remove \(deviceNameConfigPath): \(String(cString: strerror(errno)))")
+ }
+ return
+ }
+ let directory = (deviceNameConfigPath as NSString).deletingLastPathComponent
+ do {
+ try FileManager.default.createDirectory(
+ atPath: directory,
+ withIntermediateDirectories: true,
+ attributes: [.posixPermissions: 0o755],
+ )
+ let data = try PropertyListSerialization.data(
+ fromPropertyList: [deviceNameConfigKey: name], format: .binary, options: 0,
+ )
+ try data.write(to: URL(fileURLWithPath: deviceNameConfigPath), options: .atomic)
+ } catch {
+ throw GuestAPIError.operationFailed("Could not write \(deviceNameConfigPath): \(error.localizedDescription)")
+ }
+ // World-readable: the hooks only ever read it.
+ chmod(deviceNameConfigPath, 0o644)
+ }
+}
+
// MARK: - Name resolution
extension GuestAPI {
diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swift
index b68eb125..46243310 100644
--- a/VPhoneDaemon/Daemon/GuestAPI.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI.swift
@@ -126,6 +126,7 @@ enum GuestAPI {
"setup_skip",
"network_ipv4",
"network_hostname",
+ "device_name",
"network_static_names",
"network_resolve",
"timezone",
diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.h
index 2b9eb4dd..b273c184 100644
--- a/VPhoneDaemon/Native/Include/VphonedNative.h
+++ b/VPhoneDaemon/Native/Include/VphonedNative.h
@@ -78,4 +78,9 @@ NSDictionary *vp_network_hostname_get(NSString **error);
/// Set the mDNS name, or with nil put back the one vphoned replaced. Only a
/// name vphoned set is ever undone. Returns the get result plus `changed`.
NSDictionary *vp_network_hostname_set(NSString *name, NSString **error);
+
+/// Apply the preferences as they are, changing nothing: every process
+/// watching them, configd's preferences monitor first, reads them again and
+/// publishes what it derives from them.
+BOOL vp_preferences_apply(NSString **error);
#endif
diff --git a/VPhoneDaemon/Native/vphoned_network.m b/VPhoneDaemon/Native/vphoned_network.m
index de71b1f6..fa3e13be 100644
--- a/VPhoneDaemon/Native/vphoned_network.m
+++ b/VPhoneDaemon/Native/vphoned_network.m
@@ -320,3 +320,22 @@ done:
return result;
}
+
+BOOL vp_preferences_apply(NSString **error) {
+ if (!vp_network_load(error)) return NO;
+ SCPreferencesRef prefs = pCreate(NULL, CFSTR("vphoned"), NULL);
+ if (!prefs) {
+ if (error) *error = vp_sc_error(@"SCPreferencesCreate");
+ return NO;
+ }
+ BOOL applied = NO;
+ if (!pLock(prefs, true)) {
+ if (error) *error = vp_sc_error(@"SCPreferencesLock");
+ } else {
+ applied = pApply(prefs);
+ if (!applied && error) *error = vp_sc_error(@"SCPreferencesApplyChanges");
+ pUnlock(prefs);
+ }
+ CFRelease(prefs);
+ return applied;
+}