Run a virtual iPhone on an Apple Silicon Mac.
Swift
Release DHCP leases that orphaned guest MACs still hold
Jacky3567057a38d0
diff --git a/AGENTS.md b/AGENTS.mdindex 703e40da..669095df 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -58,7 +58,7 @@ The `VPhone` scheme puts host programs in `VPhone.bundle/Contents/MacOS` and eve- `vphone-cli` is the unentitled entry point. `VPhoneGuestLaunchPlanner` resolves `vphone-vm` beside the running executable, checks its entitlements, probes AMFI, and reports the exact allowlist command on refusal. It never obtains root itself.- `vphone-escalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization belongs to the user or to `vphone-launchpad`; neither `vphone-cli` nor the bundle has an SMJobBless or sudo password flow.-- `vphone-launchpad` has no private entitlements. `SignLaunchpad.sh` gives its main executable two hardened-runtime resource entitlements, microphone (`com.apple.security.device.audio-input`) and location (`com.apple.security.personal-information.location`), from `VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements`; its helper, CLI and launcher have none. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `vphone-escalator allow` for its receipt-pinned `vphone-vm`, and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Launchpad starts `vm launch` detached (own session, responsibility disclaimed) through `vphone-launchpad-launcher` in its `Contents/MacOS`, which starts `vphone-cli` as an ordinary child and stays until it exits, forwarding stop signals and exiting the same way. The launcher is therefore the responsible process for `vphone-vm`. As a tool in the app's `Contents/MacOS` it is attributed to the app, so privacy prompts, usage descriptions and grants (microphone, location) are the app's, asked once for its Developer ID signature instead of for each ad hoc signed bundle build; under the hardened runtime macOS refuses them without asking unless the app carries the matching entitlement. It refuses anything but `vm launch` of a `vphone-cli` in the root-owned store (`VPhoneLaunchpadLauncherPolicy`); without the launcher, Launchpad starts `vphone-cli` directly. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.+- `vphone-launchpad` has no private entitlements. `SignLaunchpad.sh` gives its main executable two hardened-runtime resource entitlements, microphone (`com.apple.security.device.audio-input`) and location (`com.apple.security.personal-information.location`), from `VPhoneLaunchpad/Resources/VPhoneLaunchpad.entitlements`; its helper, CLI and launcher have none. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `vphone-escalator allow` for its receipt-pinned `vphone-vm`, runs `cfw install` from that store after rechecking the recorded cdhash, and runs that store bundle's `vphone-cli vm leases --release-orphans` for the caller's own library folders. There is no generic command verb. Launchpad starts `vm launch` detached (own session, responsibility disclaimed) through `vphone-launchpad-launcher` in its `Contents/MacOS`, which starts `vphone-cli` as an ordinary child and stays until it exits, forwarding stop signals and exiting the same way. The launcher is therefore the responsible process for `vphone-vm`. As a tool in the app's `Contents/MacOS` it is attributed to the app, so privacy prompts, usage descriptions and grants (microphone, location) are the app's, asked once for its Developer ID signature instead of for each ad hoc signed bundle build; under the hardened runtime macOS refuses them without asking unless the app carries the matching entitlement. It refuses anything but `vm launch` of a `vphone-cli` in the root-owned store (`VPhoneLaunchpadLauncherPolicy`); without the launcher, Launchpad starts `vphone-cli` directly. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.- Launchpad and `VPhone.bundle` match by series, the first two numbers of the version: Launchpad 2.2.3 works with any `VPhone.bundle` 2.2.x, and the reverse. Patch releases within a series must stay interchangeable in both directions. A change to anything Launchpad relies on in the bundle (`vphone-cli` arguments or output, `vphone-escalator`, the bundle layout or receipt) needs a new minor version and a raised `minimumBundleComponents` in `VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift`. `Documents/Downloads/README.md` states this rule to users.- Host VM artifacts, caches, and archives created by vphone use mode `0777` for workstation access. Symlinks are not followed when changing permissions. Guest filesystem modes inside `Disk.img` remain unchanged.- `VPhoneRestore` runs in the CLI process over vendored libirecovery and idevicerestore. No Python or runtime Homebrew dependency is allowed.diff --git a/Documents/Downloads/README.md b/Documents/Downloads/README.mdindex 3aff9149..c428873c 100644--- a/Documents/Downloads/README.md+++ b/Documents/Downloads/README.md@@ -28,6 +28,7 @@ Use a `VPhone.bundle` from the same series as Launchpad. The series is the first| Launchpad | VPhone.bundle || --- | --- |+| 2.5.x | 2.5.x || 2.4.x | 2.4.x || 2.3.x | 2.3.x || 2.2.x | 2.2.x |diff --git a/Documents/Guides/launchpad-cli.md b/Documents/Guides/launchpad-cli.mdindex 0b30134c..42f41787 100644--- a/Documents/Guides/launchpad-cli.md+++ b/Documents/Guides/launchpad-cli.md@@ -110,6 +110,7 @@ version while a machine is bound to it; rebind or delete those machines first.| `vm wait <name>` / `vm log <name> [--kind create\|dfu\|patch]` | Wait for vphoned; read a console log || `vm create <name> [--bundle <version>] [...] [--device <product-type>] [--from <step>]` | The New Machine pipeline, bound to `--bundle` or the default; `--device` makes an iPad guest, `--from` retries from a step || `vm set-bundle <name> <version> [--update-environment]` | Bind a machine to another installed version. `--update-environment` also redeploys that version's guest environment and needs a stopped machine |+| `vm leases [--release]` | DHCP leases on the shared NAT network and the machine that owns each. `--release` frees the ones no machine in any library uses, through the helper (see [Networking](networking.md#addresses-held-by-old-macs)) || `cfw install <name>` | Install CFW into a stopped machine with its own bundle, through the helper || `cfw update-environment <name>` | Redeploy the machine's own bundle's guest resources (vphoned, hook dylibs) into it while stopped, through the helper; nothing else changes || `guest send <name> <json>` | One raw `vphone.sock` request (tap, swipe, key, screenshot) |diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.mdindex e92af6c1..cc3d59bc 100644--- a/Documents/Guides/networking.md+++ b/Documents/Guides/networking.md@@ -106,6 +106,48 @@ vphone-cli vm config <name> --mac auto # a new one at the next launchA cloned machine keeps the MAC of the original, like its machine identifier.Give the clone a new one before running both at once.+## Addresses held by old MACs++In `nat` mode the Mac's DHCP server keeps each address bound to the MAC it+was given to, even after the lease runs out. It hands that address to anyone+else only once every other address in the range is taken. Deleting a machine+or replacing its MAC leaves its address bound to a MAC nothing uses any more,+and so does every launch made before MACs were saved. New guests then get+higher and higher addresses, until they reach the fixed addresses picked high+in the range.++`vm leases` lists the leases on the shared network and who owns each. It+needs `VPhone.bundle` 2.5 or later:++```sh+vphone-cli vm leases+sudo vphone-cli vm leases --release-orphans+```++An orphan is an iOS or iPadOS guest's lease whose MAC belongs to no machine in+the library and whose lease has run out. `--release-orphans` removes the+orphans from `/var/db/dhcpd_leases` and has the DHCP server read the file+again, so it needs root. It never touches:++- a machine's own lease, even one that ran out while the machine was stopped;+- a lease that has not run out, such as a running guest's whose MAC was just+ replaced;+- leases of other VM apps, or of devices on Internet Sharing.++Machines in another library count only when that library is named too:+repeat `--library-root` for each. The release refuses to run when a library+has no machines or a machine's settings cannot be read, since every lease+there would look orphaned.++In Launchpad, Host Setup shows the count under NAT Network, and Release…+frees them after an administrator approves. It compares against every+library Launchpad lists. From the command line:++```sh+vphone-launchpad-cli vm leases+vphone-launchpad-cli vm leases --release+```+## Fixed address`--ip` gives the guest a fixed IPv4 address. Without a prefix, `/24` isdiff --git a/Research/Host/network_fixed_address.md b/Research/Host/network_fixed_address.mdindex 1db3b5d2..9421ba74 100644--- a/Research/Host/network_fixed_address.md+++ b/Research/Host/network_fixed_address.md@@ -28,6 +28,35 @@ MAC on several VMs, for example from a manifest template: two guests on oneL2 network with one MAC cannot both work. Each VM now gets its own, and a clonekeeps the original's, like its machine identifier.+## Leases held by MACs no machine uses++Read from bootp-534.120.2 (`bootpd.tproj/dhcpd.c`, `bootplib/NICache.c`) and+checked against `/var/db/dhcpd_leases` on 2026-10-04.++- bootpd looks a client up by its identifier (`1,<mac>`) first. An entry is+ a binding: an expired lease is renewed in place, with the same address.+- A new client gets an address no entry holds (`acquire_ip`). Expired entries+ are reclaimed (`DHCPLeases_reclaim`, oldest first) only when that fails, so+ a full pool reclaims a stopped machine's lease as readily as a dead one's.+- On the test Mac the file held 130 entries, `192.168.64.2` to `.131`: 125+ `iPhone`/`iPad` entries for MACs no machine had (random MACs from launches+ before `macAddress` was saved, and deleted test machines), the five+ machines' own, and four `ManagedlMachine` entries from another app.+- The `name` is the client's host name option. IPConfiguration sends the+ device type (`get_device_type`) when the network is private, which is how+ iOS treats it, so a vphone guest is always `iPhone` or `iPad`, whatever+ `--mdns` set. `vm leases` uses that, the shared subnet, and an expired lease+ to tell a guest's dead binding from another app's or a live one.+- bootpd re-reads the file on SIGHUP, before it handles the next packet, and+ writes it only while handling one (`<file>-` then `rename`). It is started+ on demand by launchd (`bootps.plist`) and exits when idle. `--release-orphans`+ checks the file did not change between read and rename, renames a copy+ with the same owner and mode over it, sends SIGHUP to any running bootpd,+ and posts `com.apple.bootpd.DHCPLeaseList` as bootpd does.+- DHCPRELEASE from the host is no substitute: bootpd answers it by setting+ the entry's lease to now (`dhcp_msgtype_release_e`), which is exactly the+ state of every orphan already.+## Fixed address in nat mode: the shared network onlyvphoned writes a manual IPv4 configuration into the guest's networkdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swiftindex dcb2ccff..2faea210 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift@@ -14,6 +14,7 @@ struct VPhoneVirtualMachineCommand: ParsableCommand {VPhoneVirtualMachineNewCommand.self,VPhoneVirtualMachineConfigCommand.self,VPhoneVirtualMachineNetworkCommand.self,+ VPhoneVirtualMachineLeasesCommand.self,VPhoneVirtualMachineRenameCommand.self,VPhoneVirtualMachineDeleteCommand.self,VPhoneVirtualMachineCloneCommand.self,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swiftnew file mode 100644index 00000000..1d5f6bf8--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift@@ -0,0 +1,169 @@+import ArgumentParser+import Darwin+import Foundation+import VPhoneCoreKit++// MARK: - leases++/// The Mac's DHCP leases on vmnet's shared network, and who owns each. bootpd+/// keeps an address bound to a MAC after the lease runs out, so a guest that+/// left with its MAC still holds one; `--release-orphans` frees those.+struct VPhoneVirtualMachineLeasesCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "leases",+ abstract: "Show the nat network's DHCP leases, or release the ones no machine owns",+ discussion: """+ The Mac's DHCP server keeps each address bound to the guest MAC it was given to, \+ even after the lease runs out. A deleted machine, a replaced MAC, or a launch from \+ before MACs were saved leaves its address held by a MAC no machine uses any more, so \+ new guests take ever higher addresses, towards the fixed ones picked high in the range.++ An orphan is an iOS or iPadOS guest's lease on the shared network whose MAC belongs to \+ no machine in the library and whose lease has run out. Leases of other VM apps, of \+ devices on Internet Sharing, and of anything still inside its lease are never released.++ --release-orphans removes the orphans from /var/db/dhcpd_leases and has the DHCP \+ server read it again. It needs root. A machine kept in another library is only known \+ if that library is named too: repeat --library-root for each.+ """,+ )++ @Option(+ name: [.customShort("l"), .long],+ help: "VM library root, repeatable (default: ~/.vphone/machines or $VPHONE_LIBRARY_ROOT)",+ )+ var libraryRoot: [String] = []+ @Flag(name: .long, help: "Remove the orphaned leases (needs sudo)")+ var releaseOrphans = false+ @Flag(name: .shortAndLong, help: "Emit JSON") var json = false++ func run() throws {+ if releaseOrphans, geteuid() != 0 {+ throw ValidationError("Releasing leases changes \(VPhoneDHCPLeaseList.path), which needs root. Run this command with sudo.")+ }+ let machines = try machineMACs()+ let subnet = VPhoneNetworkHost.current.sharedNATSubnet+ let audit = { (list: VPhoneDHCPLeaseList) in+ VPhoneDHCPLeaseAudit(list, machines: machines, sharedSubnet: subnet)+ }++ if releaseOrphans {+ let released = try VPhoneDHCPLeaseRelease.release { audit($0).orphans }+ if json {+ try printJSON(["released": released.map(Self.report)])+ return+ }+ for lease in released {+ print("released \(Self.address(lease)) \(Self.mac(lease))")+ }+ print(released.isEmpty ? "No orphaned leases." : "Released \(released.count) orphaned lease\(released.count == 1 ? "" : "s").")+ return+ }++ let entries = try audit(readList()).entries.filter { $0.owner != .foreign }+ if json {+ try printJSON(entries.map { entry in+ var report = Self.report(entry.lease)+ switch entry.owner {+ case let .machine(name):+ report["owner"] = "machine"+ report["machine"] = name+ case .foreign: report["owner"] = "foreign"+ case .active: report["owner"] = "active"+ case .orphan: report["owner"] = "orphan"+ }+ return report+ })+ return+ }+ guard !entries.isEmpty else {+ print("No guest leases on \(subnet).")+ return+ }+ let now = Date()+ for entry in entries.sorted(by: { ($0.lease.address?.raw ?? 0) < ($1.lease.address?.raw ?? 0) }) {+ let owner = switch entry.owner {+ case let .machine(name): name+ case .foreign: "foreign"+ case .active: "unowned, in use"+ case .orphan: "orphan"+ }+ let address = Self.address(entry.lease).padding(toLength: 16, withPad: " ", startingAt: 0)+ let mac = Self.mac(entry.lease).padding(toLength: 18, withPad: " ", startingAt: 0)+ let name = (entry.lease.name ?? "").padding(toLength: 7, withPad: " ", startingAt: 0)+ print("\(address) \(mac) \(name) \(owner) \(Self.expiry(entry.lease, now: now))")+ }+ let orphans = entries.count { $0.owner == .orphan }+ if orphans > 0 {+ print("\n\(orphans) orphaned lease\(orphans == 1 ? "" : "s"). Release with: sudo vphone-cli vm leases --release-orphans")+ }+ }++ // MARK: - Machines++ /// The MACs every machine in the named libraries claims. A library that+ /// could not be read in full refuses a release: a machine skipped here+ /// would have its lease taken for an orphan.+ private func machineMACs() throws -> [VPhoneMACAddress: String] {+ let roots = libraryRoot.isEmpty+ ? [VPhoneLibrary.defaultRoot()]+ : libraryRoot.map { URL(fileURLWithPath: $0, isDirectory: true) }+ var bundles: [VPhoneBundle] = []+ for root in roots {+ let scan = try VPhoneLibrary(root: root).scan()+ for skip in scan.skipped {+ FileHandle.standardError.write(Data("warning: skipping \(skip.name): \(skip.reason)\n".utf8))+ }+ if releaseOrphans {+ if let skip = scan.skipped.first {+ throw ValidationError("Unable to read \(skip.name) in \(root.path), so its lease cannot be told from an orphan. Nothing was released.")+ }+ if scan.bundles.isEmpty {+ throw ValidationError("No machines in \(root.path). Name the library with --library-root, or every machine's lease there would be released.")+ }+ }+ bundles += scan.bundles+ }+ return VPhoneDHCPLeaseAudit.machineMACs(bundles)+ }++ private func readList() throws -> VPhoneDHCPLeaseList {+ guard let data = FileManager.default.contents(atPath: VPhoneDHCPLeaseList.path) else {+ // bootpd creates it at its first lease.+ return VPhoneDHCPLeaseList(leases: [])+ }+ return try VPhoneDHCPLeaseList(text: String(decoding: data, as: UTF8.self))+ }++ // MARK: - Output++ private static func address(_ lease: VPhoneDHCPLeaseList.Lease) -> String {+ lease.address?.description ?? "?"+ }++ private static func mac(_ lease: VPhoneDHCPLeaseList.Lease) -> String {+ lease.hardwareAddress?.description ?? "?"+ }++ private static func expiry(_ lease: VPhoneDHCPLeaseList.Lease, now: Date) -> String {+ guard let expiry = lease.expiry else { return "permanent" }+ let formatter = RelativeDateTimeFormatter()+ formatter.unitsStyle = .short+ let relative = formatter.localizedString(for: expiry, relativeTo: now)+ return expiry <= now ? "expired \(relative)" : "expires \(relative)"+ }++ private static func report(_ lease: VPhoneDHCPLeaseList.Lease) -> [String: Any] {+ var report: [String: Any] = [:]+ report["address"] = lease.address?.description+ report["mac"] = lease.hardwareAddress?.description+ report["name"] = lease.name+ report["expires"] = lease.expiry.map { Int($0.timeIntervalSince1970) }+ return report+ }++ private func printJSON(_ object: Any) throws {+ let data = try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys])+ print(String(decoding: data, as: UTF8.self))+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plistindex 2a2ebd28..47a133cd 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist@@ -9,9 +9,9 @@<key>CFBundlePackageType</key><string>BNDL</string><key>CFBundleVersion</key>- <string>29</string>+ <string>30</string><key>CFBundleShortVersionString</key>- <string>2.4.2</string>+ <string>2.5.0</string><key>NSMicrophoneUsageDescription</key><string>Shares this Mac's microphone with the virtual iPhone so apps running inside it can record.</string></dict>diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swiftnew file mode 100644index 00000000..5d8a8180--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift@@ -0,0 +1,343 @@+import Darwin+import Foundation++// MARK: - Lease list++/// bootpd's lease list, `/var/db/dhcpd_leases`, which vmnet's shared NAT+/// network hands out addresses from.+///+/// bootpd binds an address to a client's MAC for good. An expired lease still+/// holds its address for that MAC, and bootpd reclaims one only when every+/// other address in the pool is taken (`DHCPLeases_reclaim` in bootp's+/// `dhcpd.c`). A guest that left with its MAC (a deleted machine, a replaced+/// MAC, or any launch before MACs were saved) leaves its address bound to+/// nobody, so new guests climb through the pool towards the fixed addresses+/// users pick high in it, and once it is full bootpd reclaims the oldest+/// expired lease, which may be a stopped machine's.+public struct VPhoneDHCPLeaseList: Equatable, Sendable {+ public static let path = "/var/db/dhcpd_leases"++ public struct Lease: Equatable, Sendable {+ /// The host name the client sent. An iOS or iPadOS guest sends its+ /// device type, `iPhone` or `iPad`, whatever its own name.+ public var name: String?+ public var address: VPhoneIPv4Address?+ public var hardwareAddress: VPhoneMACAddress?+ /// When the lease runs out. Nil when the entry has no `lease`+ /// property, which bootpd treats as permanent.+ public var expiry: Date?+ /// The lines between `{` and `}`, written back as they were read so+ /// that nothing this type does not understand is lost.+ var lines: [String]++ init(lines: [String]) {+ self.lines = lines+ for line in lines {+ let trimmed = line.drop { $0 == " " || $0 == "\t" }+ guard let separator = trimmed.firstIndex(of: "=") else { continue }+ let value = String(trimmed[trimmed.index(after: separator)...])+ switch trimmed[..<separator] {+ case "name": name = value+ case "ip_address": address = VPhoneIPv4Address(dotted: value)+ case "hw_address": hardwareAddress = Self.hardwareAddress(value)+ case "lease": expiry = Self.expiry(value)+ default: break+ }+ }+ }++ /// bootpd writes `type,address` with each byte in hex and no leading+ /// zero (`1,a:8c:c9:1e:fc:45`). Type 1 is Ethernet.+ static func hardwareAddress(_ value: String) -> VPhoneMACAddress? {+ let parts = value.split(separator: ",", maxSplits: 1)+ guard parts.count == 2, parts[0] == "1" else { return nil }+ let octets = parts[1].split(separator: ":", omittingEmptySubsequences: false)+ guard octets.count == 6 else { return nil }+ var bytes: [UInt8] = []+ for octet in octets {+ guard (1 ... 2).contains(octet.count), let byte = UInt8(octet, radix: 16) else { return nil }+ bytes.append(byte)+ }+ return VPhoneMACAddress(bytes)+ }++ /// Seconds since 1970, written as `0x…` and read with `strtol(…, 0)`.+ static func expiry(_ value: String) -> Date? {+ let seconds = value.hasPrefix("0x") || value.hasPrefix("0X")+ ? Int(value.dropFirst(2), radix: 16)+ : Int(value)+ return seconds.map { Date(timeIntervalSince1970: TimeInterval($0)) }+ }++ public func isExpired(at now: Date) -> Bool {+ expiry.map { $0 <= now } ?? false+ }+ }++ public var leases: [Lease]++ public init(leases: [Lease]) {+ self.leases = leases+ }++ /// Parses the file as bootpd's `PLCache_read` does, but refuses anything+ /// it would only skip over, so a file in an unexpected shape is never+ /// rewritten.+ public init(text: String) throws {+ var leases: [Lease] = []+ var current: [String]?+ var lineNumber = 0+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {+ lineNumber += 1+ switch line {+ case "{":+ guard current == nil else { throw VPhoneDHCPLeaseError.malformed(line: lineNumber) }+ current = []+ case "}":+ guard let lines = current else { throw VPhoneDHCPLeaseError.malformed(line: lineNumber) }+ leases.append(Lease(lines: lines))+ current = nil+ default:+ if current != nil {+ current?.append(String(line))+ } else if !line.allSatisfy({ $0 == " " || $0 == "\t" }) {+ throw VPhoneDHCPLeaseError.malformed(line: lineNumber)+ }+ }+ }+ guard current == nil else { throw VPhoneDHCPLeaseError.malformed(line: lineNumber) }+ self.leases = leases+ }++ /// The file as bootpd's `PLCache_write` would write these entries.+ public var text: String {+ leases.map { (["{"] + $0.lines + ["}"]).joined(separator: "\n") + "\n" }.joined()+ }+}++// MARK: - Errors++public enum VPhoneDHCPLeaseError: Error, Equatable {+ case malformed(line: Int)+ case changedWhileWriting+ case io(operation: String, path: String, code: Int32)+}++extension VPhoneDHCPLeaseError: CustomStringConvertible, LocalizedError {+ public var description: String {+ switch self {+ case let .malformed(line):+ "\(VPhoneDHCPLeaseList.path) is not in the format bootpd writes (line \(line)). Nothing was changed."+ case .changedWhileWriting:+ "bootpd kept changing \(VPhoneDHCPLeaseList.path) while it was being rewritten. Nothing was changed. Try again."+ case let .io(operation, path, code):+ "Unable to \(operation) \(path): \(String(cString: strerror(code)))."+ }+ }++ public var errorDescription: String? {+ description+ }+}++// MARK: - Audit++/// Who each lease on the shared network belongs to, against the MACs of the+/// machines in one or more libraries.+public struct VPhoneDHCPLeaseAudit: Sendable {+ public enum Owner: Equatable, Sendable {+ /// The current MAC of this machine.+ case machine(String)+ /// Off the shared network, or a client that is not an iOS or iPadOS+ /// guest: another VM app, or a device on Internet Sharing.+ case foreign+ /// A guest no machine claims, still inside its lease. A machine that+ /// is running while its MAC is replaced keeps its old one until it+ /// stops, so a live lease is never released.+ case active+ /// A guest no machine claims, past its lease: nobody is using the+ /// address, and only this entry keeps bootpd from handing it out.+ case orphan+ }++ public struct Entry: Equatable, Sendable {+ public let lease: VPhoneDHCPLeaseList.Lease+ public let owner: Owner+ }++ /// The device types an iOS or iPadOS guest sends as its DHCP host name+ /// (`get_device_type` in IPConfiguration, used whenever the network is+ /// private). Every vphone guest is one of these.+ public static let guestHostNames: Set<String> = ["iPhone", "iPad"]++ public let entries: [Entry]++ public init(+ _ list: VPhoneDHCPLeaseList,+ machines: [VPhoneMACAddress: String],+ sharedSubnet: VPhoneIPv4Subnet,+ now: Date = Date(),+ ) {+ entries = list.leases.map { lease in+ let owner: Owner = if let mac = lease.hardwareAddress, let name = machines[mac] {+ .machine(name)+ } else if lease.hardwareAddress == nil+ || !(lease.address.map(sharedSubnet.contains) ?? false)+ || !Self.guestHostNames.contains(lease.name ?? "")+ {+ .foreign+ } else if !lease.isExpired(at: now) {+ .active+ } else {+ .orphan+ }+ return Entry(lease: lease, owner: owner)+ }+ }++ public var orphans: [VPhoneDHCPLeaseList.Lease] {+ entries.filter { $0.owner == .orphan }.map(\.lease)+ }++ /// The machines' MACs, keyed for the audit. A machine with no saved MAC+ /// gets a new one at its next launch, so it claims nothing.+ public static func machineMACs(_ bundles: [VPhoneBundle]) -> [VPhoneMACAddress: String] {+ var macs: [VPhoneMACAddress: String] = [:]+ for bundle in bundles {+ guard let mac = VPhoneMACAddress(string: bundle.manifest.networkConfig.macAddress) else { continue }+ // A clone shares its original's MAC; either name will do.+ macs[mac] = macs[mac] ?? bundle.name+ }+ return macs+ }+}++// MARK: - Release++public enum VPhoneDHCPLeaseRelease {+ /// bootpd posts this whenever it changes the list; InternetSharing and+ /// anything else that shows leases reads the file again on it.+ static let changeNotification = "com.apple.bootpd.DHCPLeaseList"++ /// Rewrites the lease list without the entries `select` picks, then has+ /// a running bootpd read it again. Needs root, as the file is root's.+ ///+ /// bootpd writes the file only while it answers a client, so it can+ /// change between the read and the rename here. The file is compared+ /// before the rename and the whole pass retried if it moved; after the+ /// rename, SIGHUP makes bootpd read the file again before it answers the+ /// next client, so its in-memory list never writes a released entry back.+ @discardableResult+ public static func release(+ at path: String = VPhoneDHCPLeaseList.path,+ notifyServer: Bool = true,+ select: (VPhoneDHCPLeaseList) -> [VPhoneDHCPLeaseList.Lease],+ ) throws -> [VPhoneDHCPLeaseList.Lease] {+ for _ in 0 ..< 3 {+ let before = try status(of: path)+ let data = try Data(contentsOf: URL(fileURLWithPath: path))+ let list = try VPhoneDHCPLeaseList(text: String(decoding: data, as: UTF8.self))+ let released = select(list)+ guard !released.isEmpty else { return [] }++ let kept = VPhoneDHCPLeaseList(leases: list.leases.filter { !released.contains($0) })+ let staging = path + ".vphone-\(getpid())"+ try write(kept.text, to: staging, like: before)+ guard try sameFile(status(of: path), before) else {+ unlink(staging)+ continue+ }+ guard rename(staging, path) == 0 else {+ let code = errno+ unlink(staging)+ throw VPhoneDHCPLeaseError.io(operation: "replace", path: path, code: code)+ }+ if notifyServer {+ reloadServer()+ }+ return released+ }+ throw VPhoneDHCPLeaseError.changedWhileWriting+ }++ // MARK: - Server++ /// SIGHUP to every running bootpd, and the change notification. bootpd+ /// is started on demand by launchd and exits when idle; when none is+ /// running, the next one reads the file as it starts.+ static func reloadServer() {+ for pid in processes(named: "bootpd") {+ kill(pid, SIGHUP)+ }+ CFNotificationCenterPostNotification(+ CFNotificationCenterGetDarwinNotifyCenter(),+ CFNotificationName(changeNotification as CFString),+ nil,+ nil,+ true,+ )+ }++ static func processes(named name: String) -> [pid_t] {+ let count = proc_listallpids(nil, 0)+ guard count > 0 else { return [] }+ var pids = [pid_t](repeating: 0, count: Int(count) * 2)+ let filled = pids.withUnsafeMutableBytes {+ proc_listallpids($0.baseAddress, Int32($0.count))+ }+ guard filled > 0 else { return [] }+ return pids.prefix(Int(filled)).filter { pid in+ guard pid > 0 else { return false }+ var buffer = [CChar](repeating: 0, count: 256)+ guard proc_name(pid, &buffer, UInt32(buffer.count)) > 0 else { return false }+ return String(cString: buffer) == name+ }+ }++ // MARK: - Files++ private static func status(of path: String) throws -> stat {+ var info = stat()+ guard lstat(path, &info) == 0 else {+ throw VPhoneDHCPLeaseError.io(operation: "read", path: path, code: errno)+ }+ return info+ }++ private static func sameFile(_ a: stat, _ b: stat) -> Bool {+ a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size+ && a.st_mtimespec.tv_sec == b.st_mtimespec.tv_sec+ && a.st_mtimespec.tv_nsec == b.st_mtimespec.tv_nsec+ }++ /// A new file beside the list with its owner and mode, so the rename+ /// leaves the list exactly as bootpd keeps it (root:wheel 0644).+ private static func write(_ text: String, to path: String, like original: stat) throws {+ unlink(path)+ let descriptor = open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, original.st_mode & 0o777)+ guard descriptor >= 0 else {+ throw VPhoneDHCPLeaseError.io(operation: "create", path: path, code: errno)+ }+ defer { close(descriptor) }+ do {+ let bytes = Array(text.utf8)+ var offset = 0+ while offset < bytes.count {+ let written = bytes[offset...].withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) }+ guard written > 0 else {+ throw VPhoneDHCPLeaseError.io(operation: "write", path: path, code: errno)+ }+ offset += written+ }+ if geteuid() == 0, fchown(descriptor, original.st_uid, original.st_gid) != 0 {+ throw VPhoneDHCPLeaseError.io(operation: "set the owner of", path: path, code: errno)+ }+ guard fchmod(descriptor, original.st_mode & 0o777) == 0, fsync(descriptor) == 0 else {+ throw VPhoneDHCPLeaseError.io(operation: "write", path: path, code: errno)+ }+ } catch {+ unlink(path)+ throw error+ }+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneDHCPLeasesTests.swift b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneDHCPLeasesTests.swiftnew file mode 100644index 00000000..db39f239--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneDHCPLeasesTests.swift@@ -0,0 +1,165 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// bootpd's lease list: reading it as bootpd writes it, deciding which+/// entries no machine owns, and rewriting it without them.+struct VPhoneDHCPLeasesTests {+ typealias Lease = VPhoneDHCPLeaseList.Lease++ /// Seconds since 1970 that every expiry below is measured against.+ static let now = Date(timeIntervalSince1970: 0x6AC1_0000)+ static let shared = VPhoneIPv4Subnet(containing: VPhoneIPv4Address(192, 168, 64, 1), prefixLength: 24)!++ static func block(name: String, ip: String, mac: String, lease: Int) -> String {+ """+ {+ \tname=\(name)+ \tip_address=\(ip)+ \thw_address=1,\(mac)+ \tidentifier=1,\(mac)+ \tlease=0x\(String(lease, radix: 16))+ }++ """+ }++ static let sample = [+ // A machine's own lease, expired while it is stopped.+ block(name: "iPad", ip: "192.168.64.22", mac: "2:8b:e3:17:a4:a0", lease: 0x6AC0_0000),+ // An iOS guest no machine claims, long expired.+ block(name: "iPhone", ip: "192.168.64.125", mac: "3e:4d:1e:9c:61:85", lease: 0x6AC0_0000),+ // One no machine claims, still inside its lease.+ block(name: "iPhone", ip: "192.168.64.126", mac: "e:2f:62:cd:88:2f", lease: 0x6AC2_0000),+ // Another app's VM.+ block(name: "ManagedlMachine", ip: "192.168.64.2", mac: "86:44:f:12:49:26", lease: 0x6AB0_0000),+ // An iPhone on Internet Sharing, not on vmnet's network.+ block(name: "iPhone", ip: "192.168.2.5", mac: "aa:bb:cc:dd:ee:1", lease: 0x6AB0_0000),+ ].joined()++ static let machines: [VPhoneMACAddress: String] = [+ VPhoneMACAddress(string: "02:8b:e3:17:a4:a0")!: "ipad-pro-13",+ ]++ // MARK: - Parsing++ @Test func `reads each entry and writes the file back unchanged`() throws {+ let list = try VPhoneDHCPLeaseList(text: Self.sample)+ #expect(list.leases.count == 5)+ #expect(list.text == Self.sample)++ let first = list.leases[0]+ #expect(first.name == "iPad")+ #expect(first.address == VPhoneIPv4Address(192, 168, 64, 22))+ #expect(first.expiry == Date(timeIntervalSince1970: 0x6AC0_0000))+ }++ /// bootpd drops the leading zero of each byte.+ @Test func `hardware addresses without leading zeros`() {+ #expect(Lease.hardwareAddress("1,e:2f:62:cd:88:2f") == VPhoneMACAddress(string: "0e:2f:62:cd:88:2f"))+ #expect(Lease.hardwareAddress("1,86:44:f:12:49:26") == VPhoneMACAddress(string: "86:44:0f:12:49:26"))+ #expect(Lease.hardwareAddress("6,e:2f:62:cd:88:2f") == nil)+ #expect(Lease.hardwareAddress("1,e:2f:62:cd:88") == nil)+ #expect(Lease.hardwareAddress("1,e:2f:62:cd:88:2ff") == nil)+ }++ @Test func `an entry without a lease never expires`() throws {+ let list = try VPhoneDHCPLeaseList(text: "{\n\tname=iPhone\n\tip_address=192.168.64.9\n}\n")+ #expect(list.leases[0].expiry == nil)+ #expect(!list.leases[0].isExpired(at: .distantFuture))+ }++ /// Lines bootpd would merely skip are refused, so a file in a shape this+ /// reader does not expect is never rewritten.+ @Test func `refuses a file bootpd did not write`() {+ #expect(throws: VPhoneDHCPLeaseError.malformed(line: 2)) {+ try VPhoneDHCPLeaseList(text: "{\n{\n}\n")+ }+ #expect(throws: VPhoneDHCPLeaseError.malformed(line: 1)) {+ try VPhoneDHCPLeaseList(text: "}\n")+ }+ #expect(throws: VPhoneDHCPLeaseError.malformed(line: 1)) {+ try VPhoneDHCPLeaseList(text: "name=iPhone\n")+ }+ #expect(throws: VPhoneDHCPLeaseError.self) {+ try VPhoneDHCPLeaseList(text: "{\n\tname=iPhone\n")+ }+ }++ @Test func `an empty file has no entries`() throws {+ #expect(try VPhoneDHCPLeaseList(text: "").leases.isEmpty)+ }++ // MARK: - Audit++ @Test func `only an expired guest no machine claims is an orphan`() throws {+ let audit = try VPhoneDHCPLeaseAudit(+ VPhoneDHCPLeaseList(text: Self.sample),+ machines: Self.machines,+ sharedSubnet: Self.shared,+ now: Self.now,+ )+ #expect(audit.entries.map(\.owner) == [.machine("ipad-pro-13"), .orphan, .active, .foreign, .foreign])+ #expect(audit.orphans.map(\.address) == [VPhoneIPv4Address(192, 168, 64, 125)])+ }++ /// A stopped machine's lease runs out like any other; it must still be+ /// kept, or the machine comes back on another address.+ @Test func `a machine's expired lease is kept`() throws {+ let audit = try VPhoneDHCPLeaseAudit(+ VPhoneDHCPLeaseList(text: Self.sample),+ machines: Self.machines,+ sharedSubnet: Self.shared,+ now: .distantFuture,+ )+ #expect(audit.entries[0].owner == .machine("ipad-pro-13"))+ #expect(audit.orphans.count == 2)+ }++ // MARK: - Release++ @Test func `release rewrites the file without the selected entries`() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("vphone-leases-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let path = directory.appendingPathComponent("dhcpd_leases").path+ try Self.sample.write(toFile: path, atomically: false, encoding: .utf8)+ chmod(path, 0o644)++ let released = try VPhoneDHCPLeaseRelease.release(at: path, notifyServer: false) { list in+ VPhoneDHCPLeaseAudit(list, machines: Self.machines, sharedSubnet: Self.shared, now: Self.now).orphans+ }+ #expect(released.map(\.address) == [VPhoneIPv4Address(192, 168, 64, 125)])++ let rewritten = try VPhoneDHCPLeaseList(text: String(contentsOfFile: path, encoding: .utf8))+ #expect(rewritten.leases.count == 4)+ #expect(!rewritten.leases.contains { $0.address == VPhoneIPv4Address(192, 168, 64, 125) })+ let attributes = try FileManager.default.attributesOfItem(atPath: path)+ #expect((attributes[.posixPermissions] as? Int) == 0o644)+ #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path) == ["dhcpd_leases"])++ // Nothing left to release: the file is not touched again.+ let before = try FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date+ let again = try VPhoneDHCPLeaseRelease.release(at: path, notifyServer: false) { list in+ VPhoneDHCPLeaseAudit(list, machines: Self.machines, sharedSubnet: Self.shared, now: Self.now).orphans+ }+ #expect(again.isEmpty)+ #expect(try FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date == before)+ }++ @Test func `release leaves a malformed file alone`() throws {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("vphone-leases-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let path = directory.appendingPathComponent("dhcpd_leases").path+ let text = Self.sample + "{\n"+ try text.write(toFile: path, atomically: false, encoding: .utf8)++ #expect(throws: VPhoneDHCPLeaseError.self) {+ try VPhoneDHCPLeaseRelease.release(at: path, notifyServer: false) { $0.leases }+ }+ #expect(try String(contentsOfFile: path, encoding: .utf8) == text)+ }+}diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfigindex 1c592691..2066de5a 100644--- a/VPhoneLaunchpad/Configuration/Version.xcconfig+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig@@ -1,4 +1,4 @@-MARKETING_VERSION = 2.4.1+MARKETING_VERSION = 2.5.0// Bump whenever the helper changes. The app blesses the helper again when the// installed helper's version or bytes differ from the copy it embeds.-CURRENT_PROJECT_VERSION = 11+CURRENT_PROJECT_VERSION = 12diff --git a/VPhoneLaunchpad/Tests/BundleNamesTests.swift b/VPhoneLaunchpad/Tests/BundleNamesTests.swiftindex f2fe8c05..14bd8e7b 100644--- a/VPhoneLaunchpad/Tests/BundleNamesTests.swift+++ b/VPhoneLaunchpad/Tests/BundleNamesTests.swift@@ -17,14 +17,14 @@ struct BundleNamesTests {// `-local` (legacy), `-local.<8+ lowercase hex>` or `-ci.<7+ hex>`.// Anything else is kept whole, so it never parses as a version.let expectations: [Expectation] = [- Expectation(name: "2.4.2", bundleVersion: "2.4.2", isLocalBuild: false, isCompatible: true, isValid: true),- Expectation(name: "2.4.2-local", bundleVersion: "2.4.2", isLocalBuild: true, isCompatible: true, isValid: true),- Expectation(name: "2.4.2-local.ab12cd34", bundleVersion: "2.4.2", isLocalBuild: true, isCompatible: true, isValid: true),+ Expectation(name: "2.5.2", bundleVersion: "2.5.2", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.5.2-local", bundleVersion: "2.5.2", isLocalBuild: true, isCompatible: true, isValid: true),+ Expectation(name: "2.5.2-local.ab12cd34", bundleVersion: "2.5.2", isLocalBuild: true, isCompatible: true, isValid: true),// The build identifier is lowercase hex; uppercase is no build.- Expectation(name: "2.4.2-local.AB12CD34", bundleVersion: "2.4.2-local.AB12CD34", isLocalBuild: false, isCompatible: false, isValid: true),- Expectation(name: "2.4.2-local.ab12", bundleVersion: "2.4.2-local.ab12", isLocalBuild: false, isCompatible: false, isValid: true),- Expectation(name: "2.4.2-ci.abcdef1", bundleVersion: "2.4.2", isLocalBuild: false, isCompatible: true, isValid: true),- Expectation(name: "2.3.9-local.ab12cd34", bundleVersion: "2.3.9", isLocalBuild: true, isCompatible: false, isValid: true),+ Expectation(name: "2.5.2-local.AB12CD34", bundleVersion: "2.5.2-local.AB12CD34", isLocalBuild: false, isCompatible: false, isValid: true),+ Expectation(name: "2.5.2-local.ab12", bundleVersion: "2.5.2-local.ab12", isLocalBuild: false, isCompatible: false, isValid: true),+ Expectation(name: "2.5.2-ci.abcdef1", bundleVersion: "2.5.2", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.4.9-local.ab12cd34", bundleVersion: "2.4.9", isLocalBuild: true, isCompatible: false, isValid: true),Expectation(name: "../x", bundleVersion: "../x", isLocalBuild: false, isCompatible: false, isValid: false),Expectation(name: "", bundleVersion: "", isLocalBuild: false, isCompatible: false, isValid: false),]diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swiftindex 4b6057ea..a8b6505d 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift@@ -32,6 +32,7 @@ final class VPhoneLaunchpadModel {let host: VPhoneLaunchpadHostSetuplet bundles: VPhoneLaunchpadCoreBundlelet machines: VPhoneLaunchpadMachineLibrary+ let leases: VPhoneLaunchpadLeasesvar panel: Panel?/// The panel to open once the sheet on screen has closed.@@ -43,6 +44,7 @@ final class VPhoneLaunchpadModel {host = VPhoneLaunchpadHostSetup(helper: helper, libraryRoot: libraryRoot)bundles = VPhoneLaunchpadCoreBundle(helper: helper, history: history)machines = VPhoneLaunchpadMachineLibrary(bundles: bundles, helper: helper)+ leases = VPhoneLaunchpadLeases(bundles: bundles, machines: machines, helper: helper)bundles.boundMachines = { [machines] version in machines.machineNames(boundTo: version) }}@@ -90,6 +92,15 @@ final class VPhoneLaunchpadModel {return host.isDeveloperToolAuthorized && !bundles.isInstalling}+ /// Releasing DHCP leases runs through the helper; an outdated one is+ /// replaced on the way.+ var canReleaseLeases: Bool {+ switch helper.state {+ case .ready, .outdated: true+ default: false+ }+ }+// MARK: - Lifecyclefunc start() async {@@ -151,6 +162,7 @@ final class VPhoneLaunchpadModel {func refreshHost() async {await host.refresh()+ await leases.refresh()}// MARK: - Bundle installdiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swiftindex 063120bb..bf992041 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadPreview.swift@@ -50,6 +50,7 @@model.helper.applyPreview(.notInstalled)model.host.applyPreview(blocked: true)+ model.leases.applyPreview(orphans: 0)model.bundles.applyPreview(installing: false)await panel(model, .hostSetup, "01-host-setup-first-run", suffix)@@ -64,6 +65,7 @@await panel(model, .coreBundle, "03b-core-bundle-actions", suffix)coreBundleSource = .releases+ model.leases.applyPreview(orphans: 119)await panel(model, .hostSetup, "04-host-setup-passed", suffix)await standalone("04b-skill-install", suffix, size: NSSize(width: 520, height: 460)) {VPhoneLaunchpadSkillInstallView()diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swiftindex e8ed17dd..37c4b08e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Control/VPhoneLaunchpadControlCommands.swift@@ -57,6 +57,7 @@ struct VPhoneLaunchpadControlCommands {case "vm.log": return try await log(request)case "vm.create": return try await create(request, emit: emit)case "vm.set-bundle": return try await setBundle(request, emit: emit)+ case "vm.leases": return try await leases(request)case "cfw.install": return try await installCustomFirmware(request, emit: emit)case "cfw.update-environment": return try await updateGuestEnvironment(request, emit: emit)case "guest.send": return try await sendToGuest(request)@@ -695,6 +696,35 @@ struct VPhoneLaunchpadControlCommands {return ["name": machine.name, "bundle": version, "status": status]}+ // MARK: - DHCP leases++ private func leases(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {+ let leases = model.leases+ // The release compares against the machines listed now, so list first.+ await refreshMachines()+ if request.flag("release") {+ let released = try await leases.release()+ return ["released": released.map(report)]+ }+ await leases.refresh()+ switch leases.state {+ case let .unavailable(reason), let .failed(reason):+ throw VPhoneLaunchpadError(reason)+ default:+ return leases.leases.map(report)+ }+ }++ private func report(_ lease: VPhoneLaunchpadLeases.Lease) -> [String: Any] {+ var report: [String: Any] = [:]+ report["address"] = lease.address+ report["mac"] = lease.mac+ report["name"] = lease.name+ report["owner"] = lease.owner+ report["machine"] = lease.machine+ return report+ }+// MARK: - Guestprivate func sendToGuest(_ request: VPhoneLaunchpadControlRequest) async throws -> Any {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swiftindex fe4a813d..00d1c43b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift@@ -308,6 +308,32 @@ final class VPhoneLaunchpadHelperClient {}}+ /// Runs `vm leases --release-orphans --json` as root against the machines+ /// of `libraryRoots`, and returns the command's JSON output.+ func releaseOrphanedLeases(bundleVersion: String, libraryRoots: [String]) async throws -> Data {+ await refresh()+ if case .outdated = state {+ try await install()+ }+ guard case .ready = state else {+ throw VPhoneLaunchpadError(String(localized: "Update the privileged helper in Host Setup, then try again."))+ }+ let authorization = try await authorizationSession.externalForm()+ return try await request { proxy, done in+ proxy.releaseOrphanedLeases(+ authorization: authorization,+ bundleVersion: bundleVersion,+ libraryRoots: libraryRoots,+ ) { output, message in+ if let message {+ done(.failure(VPhoneLaunchpadError(message)))+ } else {+ done(.success(Data((output ?? "").utf8)))+ }+ }+ }+ }+/// Never prompts. The helper stops only an install this user started.func cancelCustomFirmware() {let proxy = currentConnection().remoteObjectProxy as? VPhoneLaunchpadHelperProtocoldiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swiftindex 00a348ab..0536a2ea 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetupView.swift@@ -5,6 +5,7 @@ struct VPhoneLaunchpadHostSetupView: View {@Environment(\.dismiss) private var dismiss@AppStorage(VPhoneLaunchpadMenuBar.key) private var showsInMenuBar = false@State private var showsSkillInstall = false+ @State private var confirmsRelease = falseprivate var host: VPhoneLaunchpadHostSetup {model.host@@ -12,6 +13,7 @@ struct VPhoneLaunchpadHostSetupView: View {var body: some View {@Bindable var host = host+ @Bindable var leases = model.leasesVPhoneLaunchpadSheet(Text("Host Setup")) {form} accessory: {@@ -40,6 +42,18 @@ struct VPhoneLaunchpadHostSetupView: View {host.refreshDeveloperTools()}.errorAlert($host.actionError)+ .errorAlert($leases.actionError)+ .task { await model.leases.refresh() }+ .confirmationDialog(+ "Release \(model.leases.orphans.count) Addresses?",+ isPresented: $confirmsRelease,+ ) {+ Button("Release") {+ Task { await model.leases.releaseFromUI() }+ }+ } message: {+ Text("Their leases have run out and no machine in your libraries has their MAC. A guest that comes back with one of these MACs gets a new address.")+ }}private var form: some View {@@ -78,6 +92,15 @@ struct VPhoneLaunchpadHostSetupView: View {.foregroundStyle(.secondary)}+ Section {+ leasesRow+ } header: {+ Text("NAT Network")+ } footer: {+ Text("The Mac’s DHCP server keeps an address for every guest MAC it has seen, even after the lease runs out. Release frees the addresses of iOS guests no machine uses any more, such as deleted machines. It needs an administrator.")+ .foregroundStyle(.secondary)+ }+Section {Toggle("Keep in Menu Bar", isOn: $showsInMenuBar)} footer: {@@ -141,4 +164,47 @@ struct VPhoneLaunchpadHostSetupView: View {}}}++ // MARK: - NAT leases++ private var leasesRow: some View {+ let leases = model.leases+ let (status, detail) = leasesStatus+ return HStack(spacing: 8) {+ VPhoneLaunchpadStatusIcon(status: status)+ Text("Addresses held by old guests")+ .layoutPriority(1)+ Spacer(minLength: 16)+ Text(detail)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ .help(detail)+ if !leases.orphans.isEmpty {+ Button("Release…") { confirmsRelease = true }+ .disabled(leases.isReleasing || !model.canReleaseLeases)+ .fixedSize()+ }+ }+ }++ private var leasesStatus: (VPhoneLaunchpadStatus, String) {+ let leases = model.leases+ if leases.isReleasing {+ return (.running, String(localized: "Waiting for administrator approval…"))+ }+ switch leases.state {+ case .unknown, .checking:+ return (.running, String(localized: "Checking…"))+ case let .unavailable(reason):+ return (.pending, reason)+ case let .failed(reason):+ return (.warning, reason)+ case .listed:+ let count = leases.orphans.count+ return count == 0+ ? (.passed, String(localized: "None"))+ : (.warning, String(localized: "\(count) addresses no machine uses"))+ }+ }}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadLeases.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadLeases.swiftnew file mode 100644index 00000000..49e99e37--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadLeases.swift@@ -0,0 +1,159 @@+import Foundation+import Observation++/// The DHCP leases of the Mac's shared NAT network, as `vphone-cli vm leases`+/// reports them against every library Launchpad lists.+///+/// The Mac's DHCP server keeps an address bound to each guest MAC it has+/// seen, even after the lease runs out. A deleted machine, a replaced MAC,+/// or any launch from before MACs were saved leaves an address held by a MAC+/// nothing uses, and new guests climb through the range. Listing needs no+/// root; releasing goes through the helper.+@MainActor+@Observable+final class VPhoneLaunchpadLeases {+ nonisolated struct Lease: Decodable, Equatable, Sendable {+ let address: String?+ let mac: String?+ let name: String?+ /// `machine`, `active` or `orphan`; absent in a release report.+ let owner: String?+ let machine: String?+ }++ enum State: Equatable {+ case unknown+ case checking+ /// Nothing to compare against yet, with the reason.+ case unavailable(String)+ case listed+ case failed(String)+ }++ private(set) var state = State.unknown+ private(set) var leases: [Lease] = []+ private(set) var isReleasing = false+ var actionError: VPhoneLaunchpadError?++ private let bundles: VPhoneLaunchpadCoreBundle+ private let machines: VPhoneLaunchpadMachineLibrary+ private let helper: VPhoneLaunchpadHelperClient++ init(bundles: VPhoneLaunchpadCoreBundle, machines: VPhoneLaunchpadMachineLibrary, helper: VPhoneLaunchpadHelperClient) {+ self.bundles = bundles+ self.machines = machines+ self.helper = helper+ }++ var orphans: [Lease] {+ leases.filter { $0.owner == "orphan" }+ }++ /// The libraries that hold machines. `vm leases --release-orphans`+ /// refuses a library with none, since every lease would look orphaned+ /// against it; one without machines has nothing to keep anyway.+ var libraryRoots: [String] {+ var roots: [String] = []+ for machine in machines.machines where !roots.contains(machine.libraryRoot) {+ roots.append(machine.libraryRoot)+ }+ return roots+ }++ private var libraryArguments: [String] {+ libraryRoots.flatMap { ["--library-root", $0] }+ }++ // MARK: - Listing++ func refresh() async {+ #if DEBUG+ if VPhoneLaunchpadPreview.isActive {+ return+ }+ #endif+ guard state != .checking, !isReleasing else {+ return+ }+ if !machines.hasListed {+ await machines.refresh()+ }+ guard let commandLine = bundles.commandLine() else {+ state = .unavailable(String(localized: "Needs a Core Bundle"))+ return+ }+ guard !libraryRoots.isEmpty else {+ leases = []+ state = .unavailable(String(localized: "No machines"))+ return+ }+ state = .checking+ do {+ let result = try await commandLine.run(["vm", "leases", "--json"] + libraryArguments, recordInHistory: false)+ guard result.succeeded, let data = result.jsonData else {+ state = .failed(result.lines.last ?? String(localized: "vm leases failed"))+ return+ }+ leases = try JSONDecoder().decode([Lease].self, from: data)+ state = .listed+ } catch {+ state = .failed(error.localizedDescription)+ }+ }++ // MARK: - Release++ /// Releases the orphans through the helper, which asks for an+ /// administrator, and lists again. Returns what was released.+ @discardableResult+ func release() async throws -> [Lease] {+ guard !isReleasing else {+ throw VPhoneLaunchpadError(String(localized: "Already releasing DHCP leases."))+ }+ guard let version = bundles.defaultVersion else {+ throw VPhoneLaunchpadError(String(localized: "Install a Core Bundle first."))+ }+ if !machines.hasListed {+ await machines.refresh()+ }+ let roots = libraryRoots+ guard !roots.isEmpty else {+ throw VPhoneLaunchpadError(+ String(localized: "No machines to compare against."),+ detail: String(localized: "With no machine listed, every guest's lease would look orphaned."),+ )+ }+ isReleasing = true+ defer { isReleasing = false }+ let output = try await helper.releaseOrphanedLeases(bundleVersion: version, libraryRoots: roots)+ let report = try JSONDecoder().decode([String: [Lease]].self, from: output)+ isReleasing = false+ await refresh()+ return report["released"] ?? []+ }++ /// For a button: errors land in `actionError`, a cancelled+ /// administrator prompt in nothing.+ func releaseFromUI() async {+ do {+ try await release()+ } catch is CancellationError {+ } catch let error as VPhoneLaunchpadError {+ actionError = error+ } catch {+ actionError = VPhoneLaunchpadError(String(localized: "Unable to Release DHCP Leases"), detail: error.localizedDescription)+ }+ }+}++#if DEBUG+ extension VPhoneLaunchpadLeases {+ func applyPreview(orphans: Int) {+ leases = [Lease(address: "192.168.64.22", mac: "02:8b:e3:17:a4:a0", name: "iPad", owner: "machine", machine: "research-01")]+ + (0 ..< orphans).map { index in+ Lease(address: "192.168.64.\(100 + index)", mac: "0e:2f:62:cd:88:\(String(format: "%02x", index))", name: "iPhone", owner: "orphan", machine: nil)+ }+ state = .listed+ }+ }+#endifdiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex 20947cb8..87528d71 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -103,6 +103,159 @@}}},+ "NAT Network" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "NAT Network" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "NAT ネットワーク" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "NAT 네트워크" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Mạng NAT" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "NAT 网络" } }+ }+ },+ "The Mac’s DHCP server keeps an address for every guest MAC it has seen, even after the lease runs out. Release frees the addresses of iOS guests no machine uses any more, such as deleted machines. It needs an administrator." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The Mac’s DHCP server keeps an address for every guest MAC it has seen, even after the lease runs out. Release frees the addresses of iOS guests no machine uses any more, such as deleted machines. It needs an administrator." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "Mac の DHCP サーバーは、一度見たゲストの MAC ごとにアドレスを確保し、リースが切れても手放しません。「解放」は、削除したマシンなど、どのマシンも使っていない iOS ゲストのアドレスを解放します。管理者の承認が必要です。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "Mac의 DHCP 서버는 한 번 본 게스트 MAC마다 주소를 잡아 두며, 임대가 만료된 뒤에도 놓지 않습니다. 해제는 삭제한 머신처럼 더 이상 어떤 머신도 쓰지 않는 iOS 게스트의 주소를 풀어 줍니다. 관리자 승인이 필요합니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Máy chủ DHCP của Mac giữ một địa chỉ cho mỗi MAC máy khách từng thấy, kể cả khi hợp đồng thuê đã hết hạn. Giải phóng sẽ thu hồi địa chỉ của các máy khách iOS không còn máy nào dùng, chẳng hạn máy đã xoá. Cần quyền quản trị viên." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "Mac 的 DHCP 服务器会为见过的每个客户机 MAC 保留一个地址,租约到期后也不放手。“释放”会收回已经没有机器使用的 iOS 客户机的地址,例如已删除的机器。需要管理员权限。" } }+ }+ },+ "Addresses held by old guests" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Addresses held by old guests" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "古いゲストが保持しているアドレス" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이전 게스트가 점유한 주소" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Địa chỉ do máy khách cũ giữ" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "旧客户机占用的地址" } }+ }+ },+ "Release…" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Release…" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "解放…" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "해제…" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Giải phóng…" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "释放…" } }+ }+ },+ "Release %lld Addresses?" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Release %lld Addresses?" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%lld 個のアドレスを解放しますか?" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "주소 %lld개를 해제하시겠습니까?" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Giải phóng %lld địa chỉ?" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "释放 %lld 个地址?" } }+ }+ },+ "Release" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Release" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "解放" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "해제" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Giải phóng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "释放" } }+ }+ },+ "Their leases have run out and no machine in your libraries has their MAC. A guest that comes back with one of these MACs gets a new address." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Their leases have run out and no machine in your libraries has their MAC. A guest that comes back with one of these MACs gets a new address." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "これらのリースは期限切れで、ライブラリのどのマシンもその MAC を使っていません。これらの MAC で戻ってきたゲストには新しいアドレスが割り当てられます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 임대는 만료되었고 라이브러리의 어떤 머신도 해당 MAC을 쓰지 않습니다. 이 MAC으로 다시 나타나는 게스트는 새 주소를 받습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Các hợp đồng thuê này đã hết hạn và không máy nào trong thư viện dùng MAC của chúng. Máy khách quay lại với một trong các MAC này sẽ nhận địa chỉ mới." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "这些租约已经到期,资料库中也没有机器使用对应的 MAC。之后若有客户机以这些 MAC 回来,会分配到新地址。" } }+ }+ },+ "%lld addresses no machine uses" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "%lld addresses no machine uses" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "どのマシンも使っていないアドレス %lld 個" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "어떤 머신도 쓰지 않는 주소 %lld개" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "%lld địa chỉ không máy nào dùng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "%lld 个地址无机器使用" } }+ }+ },+ "Needs a Core Bundle" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Needs a Core Bundle" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "Core Bundle が必要です" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "Core Bundle이 필요합니다" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cần Core Bundle" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "需要 Core Bundle" } }+ }+ },+ "No machines" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "No machines" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "マシンがありません" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "머신 없음" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không có máy" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "没有机器" } }+ }+ },+ "vm leases failed" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "vm leases failed" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "vm leases に失敗しました" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "vm leases 실패" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "vm leases thất bại" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "vm leases 执行失败" } }+ }+ },+ "Already releasing DHCP leases." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Already releasing DHCP leases." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "DHCP リースを解放中です。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이미 DHCP 임대를 해제하는 중입니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đang giải phóng hợp đồng thuê DHCP." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "正在释放 DHCP 租约。" } }+ }+ },+ "Install a Core Bundle first." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Install a Core Bundle first." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "先に Core Bundle をインストールしてください。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "먼저 Core Bundle을 설치하십시오." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hãy cài Core Bundle trước." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "请先安装 Core Bundle。" } }+ }+ },+ "No machines to compare against." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "No machines to compare against." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "比較するマシンがありません。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "비교할 머신이 없습니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không có máy nào để đối chiếu." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "没有可用于比对的机器。" } }+ }+ },+ "With no machine listed, every guest's lease would look orphaned." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "With no machine listed, every guest's lease would look orphaned." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "一覧にマシンがないと、すべてのゲストのリースが孤立したものに見えてしまいます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "목록에 머신이 없으면 모든 게스트의 임대가 고아로 보입니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Khi không có máy nào trong danh sách, mọi hợp đồng thuê của máy khách đều trông như mồ côi." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "没有列出任何机器时,所有客户机的租约都会被当作孤儿。" } }+ }+ },+ "Unable to Release DHCP Leases" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Unable to Release DHCP Leases" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "DHCP リースを解放できません" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "DHCP 임대를 해제할 수 없음" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Không thể giải phóng hợp đồng thuê DHCP" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "无法释放 DHCP 租约" } }+ }+ },+ "Update the privileged helper in Host Setup, then try again." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Update the privileged helper in Host Setup, then try again." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "「ホスト設定」で特権ヘルパーをアップデートしてから、もう一度お試しください。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "호스트 설정에서 권한 있는 도우미를 업데이트한 후 다시 시도하십시오." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hãy cập nhật trình trợ giúp đặc quyền trong Thiết lập máy chủ, rồi thử lại." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "请在“主机设置”中更新特权辅助工具,然后重试。" } }+ }+ },"" : {},diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swiftindex b4862b02..c23dc0e7 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift@@ -47,12 +47,6 @@ struct VPhoneLaunchpadHelperFirmwareRequest {let machine = URL(fileURLWithPath: libraryRoot, isDirectory: true).appendingPathComponent(machineName, isDirectory: true)- guard let account = getpwuid(callerUID) else {- throw VPhoneLaunchpadHelperError("Unable to find the user account with ID \(callerUID).")- }- let userName = String(cString: account.pointee.pw_name)- let home = String(cString: account.pointee.pw_dir)-var arguments: [String]switch operation {case let .install(keepArtifacts):@@ -70,24 +64,15 @@ struct VPhoneLaunchpadHelperFirmwareRequest {// The same environment `sudo vphone-cli cfw install` sees: SUDO_UID// and SUDO_GID are how the installer hands root-created files back// to the user afterwards.- environment = [- "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",- "HOME": home,- "USER": userName,- "LOGNAME": userName,- "SUDO_USER": userName,- "SUDO_UID": String(callerUID),- "SUDO_GID": String(callerGID),- "LANG": "en_US.UTF-8",- ]+ environment = try VPhoneLaunchpadHelperLibraryPath.environment(callerUID: callerUID, callerGID: callerGID)}// MARK: - Machine directoryprivate static func requireMachine(libraryRoot: String, machineName: String, ownedBy uid: uid_t) throws {- let root = try openDirectory(libraryRoot)+ let root = try VPhoneLaunchpadHelperLibraryPath.openDirectory(libraryRoot)defer { close(root) }- try requireOwner(root, libraryRoot, uid)+ try VPhoneLaunchpadHelperLibraryPath.requireOwner(root, libraryRoot, uid)let machinePath = libraryRoot + "/" + machineNamelet machine = openat(root, machineName, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)@@ -95,7 +80,7 @@ struct VPhoneLaunchpadHelperFirmwareRequest {throw VPhoneLaunchpadHelperError("\(machinePath) is not a folder, or is a symbolic link.")}defer { close(machine) }- try requireOwner(machine, machinePath, uid)+ try VPhoneLaunchpadHelperLibraryPath.requireOwner(machine, machinePath, uid)var disk = stat()guard fstatat(machine, "Disk.img", &disk, AT_SYMLINK_NOFOLLOW) == 0,@@ -108,43 +93,4 @@ struct VPhoneLaunchpadHelperFirmwareRequest {throw VPhoneLaunchpadHelperError("\(machinePath)/Disk.img is not owned by your user account.")}}-- /// Opens an absolute, canonical directory path one component at a time- /// from "/", refusing a symbolic link anywhere in it.- private static func openDirectory(_ path: String) throws -> Int32 {- let components = path.split(separator: "/", omittingEmptySubsequences: false).dropFirst()- guard path.hasPrefix("/"),- !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." })- else {- throw VPhoneLaunchpadHelperError("The library path \(path) must be an absolute path without . or .. components.")- }- var directory = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)- guard directory >= 0 else {- throw VPhoneLaunchpadHelperError("The library folder \(path) does not exist.")- }- for component in components {- let next = openat(directory, String(component), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)- let failure = errno- close(directory)- guard next >= 0 else {- throw VPhoneLaunchpadHelperError(- failure == ELOOP || failure == ENOTDIR- ? "The library path cannot include symbolic links."- : "The library folder \(path) does not exist.",- )- }- directory = next- }- return directory- }-- private static func requireOwner(_ descriptor: Int32, _ path: String, _ uid: uid_t) throws {- var info = stat()- guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {- throw VPhoneLaunchpadHelperError("\(path) is not a folder.")- }- guard info.st_uid == uid else {- throw VPhoneLaunchpadHelperError("\(path) is not owned by your user account.")- }- }}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLeasesRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLeasesRequest.swiftnew file mode 100644index 00000000..fd07848b--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLeasesRequest.swift@@ -0,0 +1,53 @@+import Darwin+import Foundation++/// A validated `vphone-cli vm leases --release-orphans` invocation. Built only+/// from a store bundle whose cdhash still matches its receipt, and only for+/// library folders the calling user owns.+///+/// The command rewrites `/var/db/dhcpd_leases` without the entries of iOS+/// guests whose MAC no machine in these libraries has, and only once their+/// lease has run out. The libraries are what it compares against, so a+/// library left out makes its machines' expired leases look orphaned; the+/// command refuses one with no machines or an unreadable machine itself.+struct VPhoneLaunchpadHelperLeasesRequest {+ /// More libraries than anyone keeps; a longer list is not a real request.+ static let maximumLibraries = 32++ let executable: URL+ let arguments: [String]+ let environment: [String: String]++ init(bundleVersion: String, libraryRoots: [String], callerUID: uid_t, callerGID: gid_t) throws {+ guard VPhoneLaunchpadNames.isCompatibleBundleVersion(bundleVersion) else {+ throw VPhoneLaunchpadHelperError("VPhone.bundle \(bundleVersion) is not supported. Use \(VPhoneLaunchpadNames.minimumBundleVersion) or newer.")+ }+ guard let receipt = VPhoneLaunchpadBundleReceipt.load(version: bundleVersion) else {+ throw VPhoneLaunchpadHelperError("VPhone.bundle \(bundleVersion) is not installed. Install it in Core Bundle, then try again.")+ }+ let executable = VPhoneLaunchpadBundleStore.executable(version: bundleVersion, named: "vphone-cli")+ try VPhoneLaunchpadHelperCodeCheck.requireCDHash(executable, receipt.cdhashes["vphone-cli"])++ var roots: [String] = []+ for root in libraryRoots where !roots.contains(root) {+ roots.append(root)+ }+ guard !roots.isEmpty else {+ throw VPhoneLaunchpadHelperError("Name at least one machine library.")+ }+ guard roots.count <= Self.maximumLibraries else {+ throw VPhoneLaunchpadHelperError("Too many machine libraries.")+ }+ // Checked as for a CFW install: walked from "/" without following a+ // link, and owned by the caller.+ for root in roots {+ let descriptor = try VPhoneLaunchpadHelperLibraryPath.openDirectory(root)+ defer { close(descriptor) }+ try VPhoneLaunchpadHelperLibraryPath.requireOwner(descriptor, root, callerUID)+ }++ self.executable = executable+ arguments = ["vm", "leases", "--release-orphans", "--json"] + roots.flatMap { ["--library-root", $0] }+ environment = try VPhoneLaunchpadHelperLibraryPath.environment(callerUID: callerUID, callerGID: callerGID)+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLibraryPath.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLibraryPath.swiftnew file mode 100644index 00000000..0c670954--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperLibraryPath.swift@@ -0,0 +1,67 @@+import Darwin+import Foundation++/// Checks on the library folders a request names, and the environment a+/// root `vphone-cli` child runs with. Shared by every verb that runs the+/// bundle's command line for the caller.+enum VPhoneLaunchpadHelperLibraryPath {+ /// Opens an absolute, canonical directory path one component at a time+ /// from "/", refusing a symbolic link anywhere in it.+ static func openDirectory(_ path: String) throws -> Int32 {+ let components = path.split(separator: "/", omittingEmptySubsequences: false).dropFirst()+ guard path.hasPrefix("/"),+ !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." })+ else {+ throw VPhoneLaunchpadHelperError("The library path \(path) must be an absolute path without . or .. components.")+ }+ var directory = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)+ guard directory >= 0 else {+ throw VPhoneLaunchpadHelperError("The library folder \(path) does not exist.")+ }+ for component in components {+ let next = openat(directory, String(component), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ let failure = errno+ close(directory)+ guard next >= 0 else {+ throw VPhoneLaunchpadHelperError(+ failure == ELOOP || failure == ENOTDIR+ ? "The library path cannot include symbolic links."+ : "The library folder \(path) does not exist.",+ )+ }+ directory = next+ }+ return directory+ }++ static func requireOwner(_ descriptor: Int32, _ path: String, _ uid: uid_t) throws {+ var info = stat()+ guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {+ throw VPhoneLaunchpadHelperError("\(path) is not a folder.")+ }+ guard info.st_uid == uid else {+ throw VPhoneLaunchpadHelperError("\(path) is not owned by your user account.")+ }+ }++ /// The environment `sudo vphone-cli …` sees for the caller. SUDO_UID and+ /// SUDO_GID are how the command line finds the caller's home and hands+ /// root-created files back afterwards.+ static func environment(callerUID: uid_t, callerGID: gid_t) throws -> [String: String] {+ guard let account = getpwuid(callerUID) else {+ throw VPhoneLaunchpadHelperError("Unable to find the user account with ID \(callerUID).")+ }+ let userName = String(cString: account.pointee.pw_name)+ let home = String(cString: account.pointee.pw_dir)+ return [+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",+ "HOME": home,+ "USER": userName,+ "LOGNAME": userName,+ "SUDO_USER": userName,+ "SUDO_UID": String(callerUID),+ "SUDO_GID": String(callerGID),+ "LANG": "en_US.UTF-8",+ ]+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swiftindex 89a3dfa2..aeb019ba 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift@@ -177,6 +177,71 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco}}+ // MARK: - DHCP leases++ func releaseOrphanedLeases(+ authorization: Data,+ bundleVersion: String,+ libraryRoots: [String],+ reply: @escaping @Sendable (String?, String?) -> Void,+ ) {+ let callerUID = callerUID+ let callerGID = callerGID+ // Not on `work`: a bundle install queued there would hold it up, and+ // the lease list has its own guard against a concurrent writer.+ DispatchQueue.global(qos: .userInitiated).async {+ let request: VPhoneLaunchpadHelperLeasesRequest+ do {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)+ request = try VPhoneLaunchpadHelperLeasesRequest(+ bundleVersion: bundleVersion,+ libraryRoots: libraryRoots,+ callerUID: callerUID,+ callerGID: callerGID,+ )+ } catch {+ reply(nil, error.localizedDescription)+ return+ }++ let process = Process()+ process.executableURL = request.executable+ process.arguments = request.arguments+ process.environment = request.environment+ process.currentDirectoryURL = URL(fileURLWithPath: "/", isDirectory: true)+ process.standardInput = FileHandle.nullDevice+ let output = Pipe()+ let errors = Pipe()+ process.standardOutput = output+ process.standardError = errors+ do {+ try process.run()+ } catch {+ reply(nil, "Unable to start vphone-cli. \(error.localizedDescription)")+ return+ }+ // stderr is drained alongside, so a full pipe cannot stall the child.+ nonisolated(unsafe) var errorData = Data()+ let drained = DispatchGroup()+ DispatchQueue.global().async(group: drained) {+ errorData = errors.fileHandleForReading.readDataToEndOfFile()+ }+ let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)+ drained.wait()+ process.waitUntilExit()+ guard process.terminationReason == .exit, process.terminationStatus == 0 else {+ // ArgumentParser puts the reason on an "Error: " line, then usage.+ let message = String(decoding: errorData, as: UTF8.self)+ .split(separator: "\n")+ .first { $0.hasPrefix("Error: ") }+ .map { String($0.dropFirst("Error: ".count)) }+ reply(nil, message ?? "Unable to release the DHCP leases (vphone-cli exited with \(process.terminationStatus)).")+ return+ }+ reply(text, nil)+ }+ }+func cancelCustomFirmware(reply: @escaping @Sendable () -> Void) {let callerUID = callerUID// Not on `work`: a bundle install queued there must not delay a cancel.diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swiftindex c98c2c4d..33901784 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift@@ -75,8 +75,9 @@ nonisolated enum VPhoneLaunchpadNames {/// reports the identifiers the patch table reads nor takes the arguments/// the helper passes. 2.4.0 added the network options of `vm config`/// (`--ip`, `--mac`, `--forward`, `--mdns`, `--mac-name`), which a- /// machine's Settings pass.- private static let minimumBundleComponents = (2, 4, 0)+ /// machine's Settings pass. 2.5.0 added `vm leases`, which Host Setup+ /// lists and the helper runs to release orphaned DHCP leases.+ private static let minimumBundleComponents = (2, 5, 0)static let minimumBundleVersion ="\(minimumBundleComponents.0).\(minimumBundleComponents.1).\(minimumBundleComponents.2)"diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swiftindex 6aaea4bb..c418be84 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadControl.swift@@ -172,6 +172,8 @@ nonisolated struct VPhoneLaunchpadControlCommand: Sendable {summary: "Create a machine through every step, as New Machine does, bound to --bundle (default: the default bundle). --from <step> retries a failed creation from that step."),Self(name: "vm.set-bundle", arguments: ["name", "version"], options: ["root"], flags: ["update-environment"],summary: "Bind a machine to another installed version; its host programs change at the next start. --update-environment also redeploys that version's guest environment into the stopped machine. The boot chain stays as created."),+ Self(name: "vm.leases", arguments: [], options: [], flags: ["release"],+ summary: "DHCP leases on the shared NAT network and the machine that owns each. --release frees the ones iOS guests left with a MAC no machine in any library has, through the root helper."),Self(name: "cfw.install", arguments: ["name"], options: ["root"], flags: ["keep-artifacts"],summary: "Install CFW into a stopped machine with its own bundle, through the root helper."),diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swiftindex c891a178..c64f4c5b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift@@ -70,6 +70,18 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {reply: @escaping @Sendable (Int32, String?) -> Void,)+ /// Runs `vphone-cli vm leases --release-orphans --json` from a store+ /// bundle as root, against the machines of `libraryRoots`, each of which+ /// the caller must own. It removes the DHCP leases on the shared NAT+ /// network that iOS guests left behind with a MAC no machine has. Replies+ /// with the command's JSON output, or with an error message.+ func releaseOrphanedLeases(+ authorization: Data,+ bundleVersion: String,+ libraryRoots: [String],+ reply: @escaping @Sendable (String?, String?) -> Void,+ )+/// Sends SIGINT to a running CFW install started by the same user. It/// needs no authorization: it can only stop the caller's own install.func cancelCustomFirmware(reply: @escaping @Sendable () -> Void)