Run a virtual iPhone on an Apple Silicon Mac.
Swift
Resolve the Mac's .local name in the guest without racing mDNS
Jacky3e7a2f138cd6
diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.mdindex a2b6d343..bf621844 100644--- a/Documents/Guides/networking.md+++ b/Documents/Guides/networking.md@@ -53,6 +53,7 @@ and the app's rules apply to it as they would to any other app.| Gateway and DNS | `192.168.127.1` || MTU | 1500 || DNS | Queries to `192.168.127.1` go to the Mac's resolver |+| Other connections to the gateway | The Mac's loopback, `127.0.0.1` (TCP and UDP) |## Limits@@ -87,3 +88,45 @@ and the app's rules apply to it as they would to any other app.```shlsof -nP -a -i -p "$(pgrep -f 'vphone-vm.*<name>')"```++## This Mac's name in the guest++On by default. The guest resolves this Mac's mDNS name (`scutil --get+LocalHostName`, plus `.local`) at once, to the address it reaches the Mac at:++| Mode | `<Mac>.local` in the guest |+| --- | --- |+| `nat` | The Mac on the shared network, usually `192.168.64.1` |+| `tunnel` | The gateway, `192.168.127.1`. Connections to it reach the Mac's loopback (`127.0.0.1`), the way `10.0.2.2` does in QEMU and VirtualBox |+| `bridged` | The Mac's address on the bridged interface |++Over mDNS alone, an IPv4 lookup of the Mac's name in the guest could fail. The+guest also hears the Mac on the network link a USB-connected iPhone gives the+Mac, where the Mac has no IPv4 address and answers "no such record". Whichever+link answers first decides the lookup, so an app that wants an IPv4 address+got an error until a real answer had been cached from another link.++vphoned registers the name with the guest's own mDNSResponder on its loopback+interface each time `vphone-vm` connects, and again when it starts, so it is in+place before apps run after a reboot. The guest's system volume is read-only,+so `/etc/hosts` is not used, and nothing is announced on any network.++Once the guest has also heard the Mac on the USB link, a lookup lists the+Mac's `169.254` address there first. iOS routes `169.254.0.0/16` through its+primary interface only, so a plain socket connecting to that address left+through `en0`, where nothing answers, and hung until it timed out. Apple's own+networking binds to the right interface and was not affected. In `nat` and+`tunnel`, vphoned therefore also routes `169.254.0.0/16` through the USB link+(as two `/17` routes, which win over the `/16` without touching it), and puts+the routes back if the link is re-created. In `bridged` it does not, since+`en0` may need link-local addresses on the LAN.++```sh+vphone-cli vm config <name> --mac-name off # withdraw both+```++To see what the guest's resolver returns, and whether each address connects:++```sh+vphone-launchpad-cli guest rpc <name> network.resolve '{"host":"<Mac>.local","family":"ipv4","port":8000}'+```diff --git a/Research/Guest/mac_name_resolution.md b/Research/Guest/mac_name_resolution.mdnew file mode 100644index 00000000..c05bc516--- /dev/null+++ b/Research/Guest/mac_name_resolution.md@@ -0,0 +1,71 @@+# The Mac's `.local` name in the guest++A guest process doing a plain BSD `connect("<mac>.local")` hung. What the+guest's resolver returned, and what vphoned now does about it. User-facing+behaviour is in `Documents/Guides/networking.md`.++Measured 2026-10-03 with vphoned's `network.resolve` on a macOS 27.0.1 host+(LocalHostName `JackyMacBook-Pro`): `pcc-research-01` (iOS 27.0, nat and+tunnel), and the fix again on `ipad-mini-01` (iOS 26.6.2, nat).++## Two links to the Mac++Besides its NIC (`en0`), a guest has the network link a USB-connected iPhone+gives the Mac: `en1` (a self-assigned `169.254` address) and `anpi0` (IPv6+only) in the guest, an `enN` and an `anriN` on the Mac. The Mac announces its+name on all of them: `dns-sd -G v4v6 JackyMacBook-Pro.local` on the Mac lists+`192.168.64.1` on the NAT bridge, a `169.254` address on the USB-link `enN`,+and, for the A record on each `anriN`, "No Such Record".++## What the guest's resolver returned++- Right after boot, `getaddrinfo(AF_INET)` failed in 1 ms with "nodename nor+ servname provided"; `AF_INET6` returned only `fe80::…%anpi0`. The negative+ answer over `anpi0` arrives first and the guest takes it as final.+- Minutes later the same lookup returned `192.168.64.1` and the Mac's `169.254`+ address on `en1`, once those answers had been cached. So whether an IPv4+ lookup works depends on timing.+- With both cached, the `169.254` address is listed first (link-local sorts+ first). The first connection to it left through `en0` (source+ `192.168.64.61`) and timed out: iOS routes `169.254.0.0/16` through the+ primary interface only. Later connections left through `en1` and worked.+ This was seen against the Mac's own TCP stack too, so it is not the tunnel.++`/etc/hosts` is not a way out: `/private/etc` is on the sealed System volume,+mounted read-only ("Read-only file system" on write).++## What vphoned does++1. **A local record for the Mac's name.** `vphone-vm` sends+ `<LocalHostName>.local` → the address the guest reaches the Mac at, and+ vphoned registers it as a shared A record on the guest's `lo0`+ (`GuestStaticNames.swift`). On `lo0` it is visible to `getaddrinfo` (a+ LocalOnly record is visible only to `dns-sd`, checked on the Mac) and never+ announced; shared, because the Mac announces the same name. IPv4 lookups+ then returned the address from the first lookup after boot, in either case+ of the name. For about half a second after a new registration two lookups+ still lost to the negative answer, so vphoned saves the names and registers+ them again as it starts, and an unchanged set from the host is not+ registered again.+2. **Link-local over the USB link.** In nat and tunnel, vphoned adds+ `169.254.0.0/17` and `169.254.128.0/17` as interface routes through the USB+ link (routing socket; `<net/route.h>` is not in the iOS SDK, so the message+ layout is copied from macOS's). They are more specific than the `/16` on+ `en0` and leave it alone. vphoned retries every 2 seconds until the link has+ its address and every 30 after, since the routes go with the link. On two+ cold boots of `pcc-research-01`, connecting to every IPv4 address of the+ Mac's name every 3 seconds for 2 minutes never timed out; the `169.254`+ address appeared at about t+21 s and its first connection left through+ `en1`. Not in bridged, where `en0` may use link-local on the LAN.+3. **The tunnel gateway leads to the Mac.** In tunnel mode the name points at+ the gateway, and connections to the gateway (other than DNS) are carried to+ the Mac's `127.0.0.1`. A refused connection now resets the guest with the+ acknowledgment number its SYN-SENT state requires; before, the guest dropped+ the `seq 0, ack 0` reset and retried its SYN until it timed out. iOS reports+ the refusal after about a second either way, as it does against the Mac's+ own stack.++On `ipad-mini-01` after the change: the record (`192.168.64.1`), routes via+`en1`, and every IPv4 address of `jackymacbook-pro.local` (`169.254.77.36`,+`192.168.64.1`) connected. `--mac-name off` withdrew the record and the routes+and removed both saved files.diff --git a/Research/README.md b/Research/README.mdindex 745dfe2e..860b6ff3 100644--- a/Research/README.md+++ b/Research/README.md@@ -20,7 +20,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) || Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) || Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md) |-| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md) |+| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md) || Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |`KernelSymbols/` holds symbol datasets and indexes; `Reference/` holds source references when present. They are evidence inputs, not steps for running the distributed app. The files in `History/` are preserved snapshots and may describe scripts or variants that have since been removed.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 30396dc6..1af0a15d 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -277,7 +277,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), `security.ssl_killswitch` |+| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.static_names.get`, `network.static_names.set {entries}`, `network.usb_link_route.set {enabled, primary?}`, `network.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` || Apps | `apps.list`, `search`, `refresh`, `launch`, `terminate`, `foreground`, `open_url`, `install`, `info`, `binary`, `data_dir`, `url_schemes`, `handlers`, `registration`, `register`, `network_policy {repair?}`; `apps.uninstall`, `unregister`, `unregister_dir` **force** || System | `system.uicache`, `system.system_apps {visible?}`, `system.respring` **force**, `system.reboot {userspace?}` **force**, `developer_mode.status`, `developer_mode.enable`, `power.low_power_mode`, `diagnostics.self_test` || Files | `files.list`, `mkdir`, `remove`, `rename`, `read {binary?, limit?}`, `write`, `find`, `copy`, `symlink`, `chmod`, `chown`, `plist`, `plist_set {value \| remove}` |@@ -289,6 +289,31 @@ request carries `"force": true`.| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) || Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.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 shared A record with the guest's own+mDNSResponder on `lo0` (`VPhoneDaemon/Daemon/GuestStaticNames.swift`), saves+them, and registers them again when it starts; `get` lists them. `vphone-vm`+sets this Mac's `<LocalHostName>.local` after every connect, so an IPv4 lookup+of it does not depend on which link's mDNS answer arrives first.++`network.usb_link_route.set` with `enabled: true` routes `169.254.0.0/16`, as+`169.254.0.0/17` and `169.254.128.0/17`, through the guest's USB link to the+Mac (the Ethernet interface other than `primary`, default `en0`, with a+`169.254` address), and keeps them there: every 2 seconds until the link has an+address, every 30 seconds after, and again when vphoned starts+(`GuestUSBLinkRoute.swift`; routing socket in `Native/vphoned_network.m`). It+returns `{interface, enabled, routes}`, or `{pending, reason}` while the link+has no address yet. `enabled: false` removes them. `vphone-vm` turns it on in+nat and tunnel mode unless the VM's `--mac-name` is off.++`network.resolve` runs `getaddrinfo` in the guest (`family` `ipv4`, `ipv6` or+any) and returns `{host, status, elapsed_ms, addresses}`, the addresses in the+resolver's order. With `port`, each address is also connected to for up to two+seconds and reports `connect`, `connect_ms` and the `local` address used, which+names the interface the connection left from; `first_only` connects to the+first address only, as a client that does not fall back would.+`processes.list` joins icli's kernel process list with `proc_pid_rusage`footprint, resident size and CPU time (`VPhoneDaemon/Native/vphoned_process.m`),the jetsam priority band and limit, and the RunningBoard bundle identifier.@@ -296,7 +321,7 @@ Account passwords, boot logo rendering and package installation, removal andrepository changes are deliberately not exposed. `/v1/health` lists the newareas in `capabilities` (`device_info`, `display`, `audio`, `input_gestures`,`ui_inspection`, `processes`, `services`, `logs`, `network_capture`,-`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`) so a host can hide+`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_static_names`, `network_usb_link_route`, `network_resolve`) so a host can hidepanels an older agent cannot serve. icli failures reach the caller withicli's own error `code` (`failed`, `unavailable`, `device_locked`, …) andmessage.diff --git a/VPhoneDaemon/Daemon/GuestAPI+Device.swift b/VPhoneDaemon/Daemon/GuestAPI+Device.swiftindex bd17ac96..8faa5c62 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -21,6 +21,27 @@ extension GuestAPI {return infocase "device.network":return networkInfo()+ case "network.resolve":+ let port = (params["port"] as? NSNumber).map { $0.intValue }+ let family: Int32 = switch optionalString(params, "family") {+ case "ipv4": AF_INET+ case "ipv6": AF_INET6+ default: AF_UNSPEC+ }+ return try resolveHost(+ string(params, "host"), family: family, port: port,+ firstOnly: params["first_only"] as? Bool ?? false,+ timeout: number(params, "timeout_ms", default: 5000) / 1000,+ )+ case "network.static_names.get":+ return GuestStaticNames.shared.describe()+ case "network.static_names.set":+ return try GuestStaticNames.shared.set(params["entries"] as? [[String: Any]] ?? [])+ case "network.usb_link_route.set":+ guard let enabled = params["enabled"] as? Bool else {+ throw GuestAPIError.invalidRequest("enabled must be true or false")+ }+ return GuestUSBLinkRoute.shared.set(enabled: enabled, primary: optionalString(params, "primary") ?? "en0")case "device.ioreg":return try ioregistry(plane: optionalString(params, "plane") ?? "IOService")case "device.environment":@@ -101,3 +122,138 @@ extension GuestAPI {return state}}++// MARK: - Name resolution++extension GuestAPI {+ /// One `getaddrinfo` answer, kept as the raw socket address for the+ /// connect test.+ private struct ResolvedAddress {+ let text: String+ let family: Int32+ let storage: Data+ }++ /// The results of a `getaddrinfo` that ran on another thread, which+ /// `resolveHost` stops waiting for after its timeout.+ private final class ResolutionResult: @unchecked Sendable {+ private let lock = NSLock()+ private var value: (status: Int32, addresses: [ResolvedAddress])?++ func set(_ status: Int32, _ addresses: [ResolvedAddress]) {+ lock.withLock { value = (status, addresses) }+ }++ func get() -> (status: Int32, addresses: [ResolvedAddress])? {+ lock.withLock { value }+ }+ }++ /// What the guest's own resolver makes of `host`: every address+ /// `getaddrinfo` returns, in its order, and how long it took. With `port`,+ /// each address is also connected to (two seconds each; only the first with+ /// `first_only`, as a client that does not fall back would), reporting the+ /// local address the guest used, which names the interface it went out of.+ /// For diagnosing names that resolve slowly, or to an address the guest+ /// cannot reach.+ static func resolveHost(_ host: String, family: Int32, port: Int?, firstOnly: Bool, timeout: Double) throws -> [String: Any] {+ let started = Date()+ let result = ResolutionResult()+ let finished = DispatchSemaphore(value: 0)+ DispatchQueue.global(qos: .userInitiated).async {+ var hints = addrinfo()+ hints.ai_family = family+ hints.ai_socktype = SOCK_STREAM+ var list: UnsafeMutablePointer<addrinfo>?+ let status = getaddrinfo(host, port.map(String.init), &hints, &list)+ var addresses: [ResolvedAddress] = []+ var entry = list+ while let info = entry {+ defer { entry = info.pointee.ai_next }+ guard let address = info.pointee.ai_addr else { continue }+ addresses.append(ResolvedAddress(+ text: numericHost(address, length: info.pointee.ai_addrlen),+ family: info.pointee.ai_family,+ storage: Data(bytes: address, count: Int(info.pointee.ai_addrlen)),+ ))+ }+ if let list {+ freeaddrinfo(list)+ }+ result.set(status, addresses)+ finished.signal()+ }++ let elapsed = { Int(Date().timeIntervalSince(started) * 1000) }+ guard finished.wait(timeout: .now() + max(timeout, 0.1)) == .success, let resolved = result.get() else {+ return ["host": host, "status": "timeout", "elapsed_ms": elapsed()]+ }+ var reply: [String: Any] = ["host": host, "elapsed_ms": elapsed()]+ guard resolved.status == 0 else {+ reply["status"] = "error"+ reply["error"] = String(cString: gai_strerror(resolved.status))+ return reply+ }+ reply["status"] = "resolved"+ reply["addresses"] = resolved.addresses.enumerated().map { index, address -> [String: Any] in+ var item: [String: Any] = [+ "address": address.text,+ "family": address.family == AF_INET6 ? "ipv6" : "ipv4",+ ]+ if port != nil, !firstOnly || index == 0 {+ item.merge(connectTest(address), uniquingKeysWith: { $1 })+ }+ return item+ }+ return reply+ }++ private static func numericHost(_ address: UnsafePointer<sockaddr>, length: socklen_t) -> String {+ var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))+ guard getnameinfo(address, length, &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 else { return "?" }+ return String(decoding: host.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self)+ }++ /// A non-blocking connect with a two-second limit.+ private static func connectTest(_ address: ResolvedAddress) -> [String: Any] {+ let started = Date()+ let descriptor = socket(address.family, SOCK_STREAM, 0)+ guard descriptor >= 0 else { return ["connect": "error", "connect_error": String(cString: strerror(errno))] }+ defer { close(descriptor) }+ _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) | O_NONBLOCK)+ let result = address.storage.withUnsafeBytes { raw in+ connect(descriptor, raw.baseAddress!.assumingMemoryBound(to: sockaddr.self), socklen_t(raw.count))+ }+ var outcome: [String: Any] = [:]+ if result == 0 || errno == EINPROGRESS {+ var poller = pollfd(fd: descriptor, events: Int16(POLLOUT), revents: 0)+ if poll(&poller, 1, 2000) == 1 {+ var error: Int32 = 0+ var length = socklen_t(MemoryLayout<Int32>.size)+ _ = getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &error, &length)+ outcome["connect"] = error == 0 ? "connected" : "error"+ if error != 0 {+ outcome["connect_error"] = String(cString: strerror(error))+ }+ } else {+ outcome["connect"] = "timeout"+ }+ } else {+ outcome["connect"] = "error"+ outcome["connect_error"] = String(cString: strerror(errno))+ }+ var local = sockaddr_storage()+ var length = socklen_t(MemoryLayout<sockaddr_storage>.size)+ let named = withUnsafeMutablePointer(to: &local) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(descriptor, $0, &length) }+ }+ if named == 0 {+ outcome["local"] = withUnsafePointer(to: &local) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { numericHost($0, length: length) }+ }+ }+ outcome["connect_ms"] = Int(Date().timeIntervalSince(started) * 1000)+ return outcome+ }+}+diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex df5eeb52..5be12dee 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -97,6 +97,9 @@ enum GuestAPI {"environment_update","udid_override","setup_skip",+ "network_static_names",+ "network_usb_link_route",+ "network_resolve",],]}diff --git a/VPhoneDaemon/Daemon/GuestStaticNames.swift b/VPhoneDaemon/Daemon/GuestStaticNames.swiftnew file mode 100644index 00000000..6d8b0374--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestStaticNames.swift@@ -0,0 +1,146 @@+import dnssd+import Foundation++/// Names the guest resolves locally, set by the host: A records registered+/// with the guest's own mDNSResponder on `lo0`, held for as long as vphoned+/// runs. They are also saved, and vphoned registers them again as it starts,+/// before the host has connected. That matters: for a moment after a record is+/// registered, a lookup can still lose to the Mac's negative answer (seen on+/// iOS 27 for about half a second), so the host resending the same names on+/// every connect must not register them anew.+///+/// This is how the Mac's `.local` name gets a dependable IPv4 answer. Over+/// multicast the guest also hears the Mac on the virtual iPhone's USB link,+/// where the Mac has no IPv4 address and answers an IPv4 query with "no such+/// record"; whichever link answers first wins, so an IPv4 lookup could fail+/// outright until a real answer had been cached from another link. A record+/// registered here is answered at once, from the guest itself.+///+/// - `lo0`, not LocalOnly: a LocalOnly record answers `dns-sd` but not+/// `getaddrinfo`. On `lo0` every resolver in the guest sees it, and nothing+/// is ever announced on a network.+/// - Shared, not unique: the Mac announces the same name, and a unique record+/// would lose the conflict.+/// - Nothing is written to disk: the system volume is sealed and read-only, so+/// `/etc/hosts` cannot be edited without a remount.+///+/// Threading: every field is touched under `lock`; the connection's replies+/// are drained on `queue`. That is the invariant behind `@unchecked Sendable`.+final class GuestStaticNames: @unchecked Sendable {+ static let shared = GuestStaticNames()++ private struct Entry: Equatable {+ let address: String+ let names: [String]+ }++ private let lock = NSLock()+ private let queue = DispatchQueue(label: "vphoned.static-names")+ private var connection: DNSServiceRef?+ private var entries: [Entry] = []+ /// On the data volume, which survives reboots; the system volume is sealed.+ private static let savePath = "/var/root/Library/Preferences/com.vphone.vphoned.static-names.plist"++ func describe() -> [String: Any] {+ lock.withLock { ["entries": entries.map { ["address": $0.address, "names": $0.names] }] }+ }++ /// Replace every record with `entries` (`[{address, names}]`, IPv4 only).+ /// An empty list withdraws them all.+ func set(_ list: [[String: Any]]) throws -> [String: Any] {+ var wanted: [Entry] = []+ for item in list {+ guard let address = item["address"] as? String, Self.ipv4Bytes(address) != nil,+ let names = item["names"] as? [String], !names.isEmpty,+ names.allSatisfy({ name in+ !name.isEmpty && name.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == ".") }+ })+ else {+ throw GuestAPIError.invalidRequest("entries must be [{address, names}] with an IPv4 address and plain host names")+ }+ wanted.append(Entry(address: address, names: names))+ }++ return try lock.withLock {+ guard wanted != entries else {+ return ["entries": list, "changed": false]+ }+ // Closing the connection withdraws every record registered on it.+ if let connection {+ DNSServiceRefDeallocate(connection)+ self.connection = nil+ }+ entries = []+ guard !wanted.isEmpty else {+ Self.save([])+ return ["entries": [], "changed": true]+ }++ var created: DNSServiceRef?+ var error = DNSServiceCreateConnection(&created)+ guard error == kDNSServiceErr_NoError, let created else {+ throw GuestAPIError.operationFailed("DNSServiceCreateConnection failed (\(error))")+ }+ let loopback = if_nametoindex("lo0")+ for entry in wanted {+ var address = Self.ipv4Bytes(entry.address)!+ for name in entry.names {+ var record: DNSRecordRef?+ let fullName = name.hasSuffix(".") ? name : name + "."+ error = DNSServiceRegisterRecord(+ created, &record, DNSServiceFlags(kDNSServiceFlagsShared), loopback,+ fullName, UInt16(kDNSServiceType_A), UInt16(kDNSServiceClass_IN),+ UInt16(address.count), &address, 120, { _, _, _, _, _ in }, nil,+ )+ guard error == kDNSServiceErr_NoError else {+ DNSServiceRefDeallocate(created)+ throw GuestAPIError.operationFailed("could not register \(name) (\(error))")+ }+ }+ }+ DNSServiceSetDispatchQueue(created, queue)+ connection = created+ entries = wanted+ Self.save(list)+ return ["entries": list, "changed": true]+ }+ }++ /// Register the saved names at startup. mDNSResponder can come up after+ /// vphoned, so a failure is retried for a few minutes.+ func restoreOnStartup(attempt: Int = 0) {+ guard let data = FileManager.default.contents(atPath: Self.savePath),+ let list = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [[String: Any]],+ !list.isEmpty+ else { return }+ do {+ _ = try set(list)+ NSLog("vphoned: %d static names restored", list.count)+ } catch {+ guard attempt < 60 else {+ NSLog("vphoned: static names not restored: %@", String(describing: error))+ return+ }+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) {+ self.restoreOnStartup(attempt: attempt + 1)+ }+ }+ }++ private static func save(_ list: [[String: Any]]) {+ if list.isEmpty {+ try? FileManager.default.removeItem(atPath: savePath)+ return+ }+ guard let data = try? PropertyListSerialization.data(fromPropertyList: list, format: .binary, options: 0) else { return }+ try? FileManager.default.createDirectory(atPath: (savePath as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ FileManager.default.createFile(atPath: savePath, contents: data)+ }++ private static func ipv4Bytes(_ text: String) -> [UInt8]? {+ let parts = text.split(separator: ".", omittingEmptySubsequences: false)+ guard parts.count == 4 else { return nil }+ let bytes = parts.compactMap { UInt8($0) }+ return bytes.count == 4 ? bytes : nil+ }+}diff --git a/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swift b/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swiftnew file mode 100644index 00000000..e596f434--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swift@@ -0,0 +1,75 @@+import Foundation+import VphonedNative++/// Keeps 169.254.0.0/16 routed over the virtual iPhone's USB link while the+/// host wants it (`vp_network_usb_link_route_set` explains why).+///+/// The routes go away whenever that link does (vphoned re-enumerates USB when+/// the profile UDID changes), and the link has no 169.254 address for a few+/// seconds after boot. So the wanted state is kept here and applied again: every+/// 2 seconds until it takes, then every 30; a route that already exists is left+/// alone.+///+/// Threading: every field is touched only on `queue`. That is the invariant+/// behind `@unchecked Sendable`.+final class GuestUSBLinkRoute: @unchecked Sendable {+ static let shared = GuestUSBLinkRoute()++ private let queue = DispatchQueue(label: "vphoned.usb-link-route")+ private var timer: DispatchSourceTimer?+ private var primary = "en0"+ /// Present while enabled, holding the primary interface, so vphoned turns+ /// the routes back on as it starts, before the host has connected.+ private static let savePath = "/var/root/Library/Preferences/com.vphone.vphoned.usb-link-route"++ func restoreOnStartup() {+ guard let saved = try? String(contentsOfFile: Self.savePath, encoding: .utf8) else { return }+ let primary = saved.trimmingCharacters(in: .whitespacesAndNewlines)+ _ = set(enabled: true, primary: primary.isEmpty ? "en0" : primary)+ }++ func set(enabled: Bool, primary: String) -> [String: Any] {+ queue.sync {+ self.primary = primary+ timer?.cancel()+ timer = nil+ if enabled {+ try? FileManager.default.createDirectory(atPath: (Self.savePath as NSString).deletingLastPathComponent, withIntermediateDirectories: true)+ try? primary.write(toFile: Self.savePath, atomically: true, encoding: .utf8)+ } else {+ try? FileManager.default.removeItem(atPath: Self.savePath)+ }+ let result = apply(enabled)+ if enabled {+ schedule(pending: result["pending"] as? Bool == true)+ }+ return result+ }+ }++ private func schedule(pending: Bool) {+ timer?.cancel()+ let interval: TimeInterval = pending ? 2 : 30+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.schedule(deadline: .now() + interval, repeating: interval)+ timer.setEventHandler { [weak self] in+ guard let self else { return }+ let stillPending = apply(true)["pending"] as? Bool == true+ if stillPending != pending {+ schedule(pending: stillPending)+ }+ }+ timer.resume()+ self.timer = timer+ }++ @discardableResult+ private func apply(_ enabled: Bool) -> [String: Any] {+ var error: NSString?+ guard let result = vp_network_usb_link_route_set(enabled, primary, &error) as? [String: Any] else {+ // No link address yet: the timer comes back to it.+ return ["enabled": enabled, "pending": true, "reason": error.map(String.init) ?? "unknown"]+ }+ return result+ }+}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex f20379aa..024c7fc1 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -19,6 +19,8 @@ vp_vcam_start()_ = vp_hid_load()GuestIrisinInstaller.refreshBootstrapOnStartup()GuestAPI.restoreUSBSerialOnStartup()+GuestStaticNames.shared.restoreOnStartup()+GuestUSBLinkRoute.shared.restoreOnStartup()let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)let filePool = NIOThreadPool(numberOfThreads: 2)diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex b28566b1..7b73578b 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -51,4 +51,9 @@ char *vp_usb_own_serial(void);#ifdef __OBJC__/// Snapshot-local nested accessibility tree, using actual private iOS child links.NSDictionary *vp_ax_hierarchy(int pid, int maxElements, int maxDepth, int timeoutMS);++/// Route 169.254.0.0/16 (as two /17s) through the virtual iPhone's USB link+/// rather than `primary`, or remove those routes. Returns the interface used and+/// the outcome for each route.+NSDictionary *vp_network_usb_link_route_set(BOOL enabled, NSString *primary, NSString **error);#endifdiff --git a/VPhoneDaemon/Native/vphoned_network.m b/VPhoneDaemon/Native/vphoned_network.mnew file mode 100644index 00000000..ec0f530e--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_network.m@@ -0,0 +1,135 @@+#import <Foundation/Foundation.h>++#import "VphonedNative.h"++/*+ * Link-local IPv4 over the virtual iPhone's USB link.+ *+ * Besides its NIC (en0) a guest has the network link a USB-connected iPhone+ * gives the Mac: an Ethernet interface with a self-assigned 169.254 address.+ * The Mac answers mDNS there, so a lookup of the Mac's .local name lists the+ * Mac's 169.254 address on that link, and, being link-local, first. But iOS+ * routes 169.254.0.0/16 through the primary interface only, so a plain+ * connect() to that address leaves through en0, where nothing answers, and+ * waits out its timeout. (Network.framework binds to the interface the answer+ * came from and is not affected; BSD sockets are.)+ *+ * Two /17 routes through the USB link are more specific than the /16 on en0,+ * so they win without touching it. They are interface routes, as+ * `route add -net 169.254.0.0/17 -interface enN` makes, and go away when the+ * interface does.+ */++#include <ifaddrs.h>+#include <net/if.h>+#include <net/if_dl.h>+// <net/route.h> is not in the iOS SDK. The routing socket's message layout+// is the kernel ABI, the same as macOS's (copied from its net/route.h).+struct vp_rt_metrics {+ u_int32_t rmx_locks, rmx_mtu, rmx_hopcount;+ int32_t rmx_expire;+ u_int32_t rmx_recvpipe, rmx_sendpipe, rmx_ssthresh, rmx_rtt, rmx_rttvar, rmx_pksent;+ u_int32_t rmx_filler[4];+};+struct vp_rt_msghdr {+ u_short rtm_msglen;+ u_char rtm_version;+ u_char rtm_type;+ u_short rtm_index;+ int rtm_flags;+ int rtm_addrs;+ pid_t rtm_pid;+ int rtm_seq;+ int rtm_errno;+ int rtm_use;+ u_int32_t rtm_inits;+ struct vp_rt_metrics rtm_rmx;+};+enum {+ VP_RTM_VERSION = 5, VP_RTM_ADD = 0x1, VP_RTM_DELETE = 0x2,+ VP_RTF_UP = 0x1, VP_RTF_STATIC = 0x800,+ VP_RTA_DST = 0x1, VP_RTA_GATEWAY = 0x2, VP_RTA_NETMASK = 0x4,+};+#include <netinet/in.h>+#include <sys/socket.h>+#include <unistd.h>++/// The interface other than `primary` with a 169.254 address: the USB link.+static NSString *vp_usb_link_interface(NSString *primary) {+ struct ifaddrs *list = NULL;+ if (getifaddrs(&list) != 0) return nil;+ NSString *found = nil;+ for (struct ifaddrs *entry = list; entry; entry = entry->ifa_next) {+ if (!entry->ifa_addr || entry->ifa_addr->sa_family != AF_INET) continue;+ NSString *name = @(entry->ifa_name);+ if ([name isEqualToString:primary] || ![name hasPrefix:@"en"]) continue;+ uint32_t address = ntohl(((struct sockaddr_in *)entry->ifa_addr)->sin_addr.s_addr);+ if ((address & 0xFFFF0000) == 0xA9FE0000) {+ found = name;+ break;+ }+ }+ freeifaddrs(list);+ return found;+}++/// RTM_ADD or RTM_DELETE for `network`/17 as an interface route on `index`.+/// Returns 0, or the errno.+static int vp_route_message(int type, uint32_t network, unsigned int index) {+ int fd = socket(PF_ROUTE, SOCK_RAW, AF_INET);+ if (fd < 0) return errno;++ struct {+ struct vp_rt_msghdr header;+ struct sockaddr_in destination;+ struct sockaddr_dl gateway;+ struct sockaddr_in netmask;+ } message;+ memset(&message, 0, sizeof(message));+ message.header.rtm_msglen = sizeof(message);+ message.header.rtm_version = VP_RTM_VERSION;+ message.header.rtm_type = type;+ message.header.rtm_flags = VP_RTF_UP | VP_RTF_STATIC;+ message.header.rtm_addrs = VP_RTA_DST | VP_RTA_GATEWAY | VP_RTA_NETMASK;+ message.header.rtm_pid = getpid();+ message.header.rtm_seq = 1;++ message.destination.sin_len = sizeof(struct sockaddr_in);+ message.destination.sin_family = AF_INET;+ message.destination.sin_addr.s_addr = htonl(network);+ message.gateway.sdl_len = sizeof(struct sockaddr_dl);+ message.gateway.sdl_family = AF_LINK;+ message.gateway.sdl_index = index;+ message.netmask.sin_len = sizeof(struct sockaddr_in);+ message.netmask.sin_family = AF_INET;+ message.netmask.sin_addr.s_addr = htonl(0xFFFF8000);++ int result = write(fd, &message, sizeof(message)) < 0 ? errno : 0;+ close(fd);+ return result;+}++NSDictionary *vp_network_usb_link_route_set(BOOL enabled, NSString *primary, NSString **error) {+ NSString *interface = vp_usb_link_interface(primary ?: @"en0");+ if (!interface) {+ if (error) *error = @"no USB link interface with a 169.254 address yet";+ return nil;+ }+ unsigned int index = if_nametoindex(interface.UTF8String);+ const uint32_t halves[2] = {0xA9FE0000, 0xA9FE8000};+ NSMutableArray *results = [NSMutableArray array];+ for (int i = 0; i < 2; i++) {+ int code;+ if (enabled) {+ code = vp_route_message(VP_RTM_ADD, halves[i], index);+ // Already there: an interface's routes go with it, so an existing+ // one points at the link as it is now.+ if (code == EEXIST) code = 0;+ } else {+ code = vp_route_message(VP_RTM_DELETE, halves[i], 0);+ if (code == ESRCH) code = 0;+ }+ [results addObject:code == 0 ? @"ok" : @(strerror(code))];+ }+ return @{@"interface": interface, @"enabled": @(enabled), @"routes": results};+}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swiftindex 28ad0f27..c31ec17c 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift@@ -206,6 +206,13 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "config",abstract: "Edit VM manifest fields (cpu/memory/network)",+ discussion: """+ --mac-name (on by default) has the guest resolve this Mac's <LocalHostName>.local \+ at once, to the address the guest reaches the Mac at (nat: the shared network's host \+ address, usually 192.168.64.1; tunnel: the gateway, which leads to the Mac's loopback; \+ bridged: the Mac's address on that interface), instead of racing mDNS answers. \+ --mac-name off withdraws it. Applied each time vphone-vm connects to the guest.+ """,)@OptionGroup var lib: VPhoneLibraryOption@@ -215,9 +222,17 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {@Option(name: [.customShort("n"), .long], help: "Network mode: nat | bridged | tunnel | none") var network: String?@Option(name: .long, help: "Host interface to bridge (bridged mode; auto-picks first if omitted)")var bridgeInterface: String?+ @Option(name: .long, help: "Have the guest resolve this Mac's .local name locally: on (default) | off")+ var macName: String?func run() throws {let mode = try network.map(Self.parseMode)+ let resolvesMacName: Bool? = switch macName?.lowercased() {+ case nil: nil+ case "on": true+ case "off": false+ default: throw ValidationError("--mac-name takes on or off.")+ }let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)let updated = try VPhoneBundleOperations.updateConfig(bundleNamed: name,@@ -226,6 +241,7 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {memoryMB: memory,networkMode: mode,bridgeInterface: bridgeInterface,+ resolvesMacName: resolvesMacName,)let m = updated.manifestprint(@@ -251,10 +267,14 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {}private func describeNetwork(_ net: VPhoneVirtualMachineManifest.NetworkConfig) -> String {+ var text = net.mode.rawValueif net.mode == .bridged, let iface = net.bridgeInterface {- return "\(net.mode.rawValue)(\(iface))"+ text += "(\(iface))"+ }+ if net.resolvesMacName == false {+ text += ", mac-name off"}- return net.mode.rawValue+ return text}// MARK: - renamediff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 8ef82e46..f2a0aee4 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -47,6 +47,13 @@ final class VPhoneGuestControl {@ObservationIgnored var guestBinaryURL: URL?@ObservationIgnored var onConnect: (([String]) -> Void)?@ObservationIgnored var onDisconnect: (() -> Void)?+ /// Names the guest resolves locally (this Mac's `.local` name), worked+ /// out on each connect, since the Mac's name or a bridged address can+ /// change while the VM runs. Nil sends nothing.+ @ObservationIgnored var guestStaticNames: (() -> [VPhoneNetworking.StaticName])?+ /// Route the guest's 169.254 traffic over its USB link to the Mac (see+ /// `VPhoneNetworking.routesLinkLocalOverUSB`). Nil sends nothing.+ @ObservationIgnored var guestUSBLinkRoute: Bool?/// The guest interface orientation: the one the window last read, or the/// one a menu rotation is turning to. Nil until one is known, and again@@ -189,6 +196,12 @@ final class VPhoneGuestControl {if capabilities.contains("environment_update") {Task { await syncEnvironment() }}+ if capabilities.contains("network_static_names"), let names = guestStaticNames?() {+ Task { await applyGuestStaticNames(names) }+ }+ if capabilities.contains("network_usb_link_route"), let enabled = guestUSBLinkRoute {+ Task { await applyGuestUSBLinkRoute(enabled) }+ }}} catch {if !isConnected {@@ -813,3 +826,34 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {return timeval(tv_sec: Int(seconds), tv_usec: microseconds)}}++// MARK: - The Mac's name++extension VPhoneGuestControl {+ /// Replace the names vphoned has the guest resolve locally; an empty list+ /// withdraws them.+ func applyGuestStaticNames(_ names: [VPhoneNetworking.StaticName]) async {+ do {+ let result = try await call("network.static_names.set", params: ["entries": names.map(\.parameters)])+ if result["changed"] as? Bool == true {+ let lines = names.map { "\($0.names.joined(separator: " ")) -> \($0.address)" }+ print("[network] guest resolves \(lines.isEmpty ? "no names locally" : lines.joined(separator: ", "))")+ }+ } catch {+ print("[network] could not set the guest's local names: \(error)")+ }+ }++ func applyGuestUSBLinkRoute(_ enabled: Bool) async {+ do {+ let result = try await call("network.usb_link_route.set", params: ["enabled": enabled])+ if result["pending"] as? Bool == true {+ print("[network] guest 169.254 routes pending: \(result["reason"] ?? "")")+ } else {+ print("[network] guest 169.254 routes \(enabled ? "via" : "removed from") \(result["interface"] as? String ?? "?")")+ }+ } catch {+ print("[network] guest 169.254 routes not \(enabled ? "set" : "removed"): \(error)")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 2763d640..4b234174 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -87,6 +87,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {let control = VPhoneGuestControl()self.control = controlif !command.dfu {+ configureGuestNames(control: control, configURL: options.configURL)let vphonedURL = URL(fileURLWithPath: command.vphonedBin)if FileManager.default.fileExists(atPath: vphonedURL.path) {control.guestBinaryURL = vphonedURL@@ -275,6 +276,26 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {hostAutomationServer = server}+ /// Have the guest resolve this Mac's `.local` name to the address it+ /// reaches the Mac at, and reach it over the USB link too.+ @MainActor+ private func configureGuestNames(control: VPhoneGuestControl, configURL: URL) {+ guard let network = try? VPhoneVirtualMachineManifest.load(from: configURL).networkConfig else { return }+ control.guestUSBLinkRoute = VPhoneNetworking.routesLinkLocalOverUSB(network)+ guard network.mode != .off else { return }+ control.guestStaticNames = {+ let bridged = network.mode == .bridged+ ? network.bridgeInterface.flatMap(VPhoneNetworking.ipv4Address(ofInterface:))+ : nil+ return VPhoneNetworking.macStaticNames(+ network,+ macName: VPhoneNetworking.macLocalHostName(),+ sharedNATHost: VPhoneNetworking.sharedNATHostAddress(),+ bridgedAddress: bridged,+ )+ }+ }+@MainActorprivate func installPackageIfRequested(caps: [String]) async {guard !didAttemptAutoInstall else { return }diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swiftindex 65c82bc5..18f0c31d 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift@@ -107,14 +107,16 @@ public enum VPhoneBundleOperations {memoryMB: UInt64?,networkMode: VPhoneVirtualMachineManifest.NetworkConfig.NetworkMode? = nil,bridgeInterface: String? = nil,+ resolvesMacName: Bool? = nil,) throws -> VPhoneBundle {let bundle = try library.bundle(named: name)- let editsNetwork = networkMode != nil || bridgeInterface != nil+ let editsNetwork = networkMode != nil || bridgeInterface != nil || resolvesMacName != nillet network = editsNetwork? try VPhoneNetworking.merge(into: bundle.manifest.networkConfig,mode: networkMode,bridgeInterface: bridgeInterface,+ resolvesMacName: resolvesMacName,): nillet updated = bundle.manifest.updating(diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swiftindex 7ffe2551..fd04f858 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift@@ -231,8 +231,14 @@ final class VPhoneTCPForwarder: @unchecked Sendable {/// on it rather than deadlocking against itself.private static let queueKey = DispatchSpecificKey<Void>()- init(queue: DispatchQueue, deliver: @escaping Deliver) {+ /// Connections to this address go to the Mac's loopback instead: the+ /// gateway stands for the Mac, the way 10.0.2.2 does in QEMU's and+ /// VirtualBox's NAT. Nil leaves every destination as it is.+ private let gatewayAddress: VPhoneIPv4Address?++ init(queue: DispatchQueue, gatewayAddress: VPhoneIPv4Address? = nil, deliver: @escaping Deliver) {self.queue = queue+ self.gatewayAddress = gatewayAddressself.deliver = deliverqueue.setSpecific(key: Self.queueKey, value: ())}@@ -343,7 +349,8 @@ final class VPhoneTCPForwarder: @unchecked Sendable {address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)address.sin_family = sa_family_t(AF_INET)address.sin_port = flow.destinationPort.bigEndian- let octets = flow.destinationAddress.bytes+ let destination = flow.destinationAddress == gatewayAddress ? VPhoneIPv4Address(127, 0, 0, 1) : flow.destinationAddress+ let octets = destination.bytes// Network order, as in the UDP forwarder: host order asks for a// different address entirely.let hostOrder = UInt32(octets[0]) << 24 | UInt32(octets[1]) << 16 | UInt32(octets[2]) << 8 | UInt32(octets[3])@@ -406,7 +413,7 @@ final class VPhoneTCPForwarder: @unchecked Sendable {var length = socklen_t(MemoryLayout<Int32>.size)_ = getsockopt(connection.socket, SOL_SOCKET, SO_ERROR, &error, &length)guard error == 0 else {- sendReset(for: connection.flow, inReplyTo: nil)+ resetGuest(connection)finish(connection)return}@@ -574,7 +581,7 @@ final class VPhoneTCPForwarder: @unchecked Sendable {}return}- sendReset(for: connection.flow, inReplyTo: nil)+ resetGuest(connection)finish(connection)return}@@ -651,7 +658,7 @@ final class VPhoneTCPForwarder: @unchecked Sendable {// EAGAIN. A real error is indistinguishable here from a closed peer,// so treat anything else as the end of the connection.if errno != EAGAIN, errno != EINTR {- sendReset(for: connection.flow, inReplyTo: nil)+ resetGuest(connection)finish(connection)}return@@ -743,6 +750,23 @@ final class VPhoneTCPForwarder: @unchecked Sendable {connection.retransmitTimer = timer}+ /// A RST for a connection the guest knows about, numbered so it is+ /// accepted. Before our SYN-ACK the guest is in SYN-SENT and takes a RST+ /// only if it acknowledges its SYN (RFC 793 section 3.4); after it, only if+ /// its sequence number is in the window. A bare `seq 0, ack 0` reset was+ /// dropped either way, so a refused connect left the guest retrying its+ /// SYN until it timed out.+ private func resetGuest(_ connection: Connection) {+ deliver(connection.flow, VPhoneTCPSegment(+ sourcePort: connection.flow.destinationPort,+ destinationPort: connection.flow.sourcePort,+ sequenceNumber: connection.state == .connecting ? 0 : connection.localSequence,+ acknowledgmentNumber: connection.remoteSequence,+ flags: VPhoneTCPFlags.rst | VPhoneTCPFlags.ack,+ windowSize: 0,+ ))+ }+/// A RST for a flow we are not going to serve.private func sendReset(for flow: VPhoneTCPFlow, inReplyTo segment: VPhoneTCPSegment?) {// RFC 793 section 3.4: if the offending segment carried an ACK, the resetdiff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUDPForwarder.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUDPForwarder.swiftindex c5b36d6a..4dd9c5d6 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUDPForwarder.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUDPForwarder.swift@@ -30,7 +30,7 @@ enum VPhoneHostResolver {extension VPhoneIPv4Address {/// Parse `a.b.c.d`, or nil for anything else (including IPv6, which this/// stack deliberately does not carry).- init?(dotted: String) {+ public init?(dotted: String) {let parts = dotted.split(separator: ".", omittingEmptySubsequences: false)guard parts.count == 4 else { return nil }var octets: [UInt8] = []@@ -231,10 +231,16 @@ final class VPhoneUDPForwarder: @unchecked Sendable {/// The guest is told its resolver is the gateway (`192.168.127.1`), so a/// lookup arrives addressed to us. Send it to the host's resolver instead —/// the same one the host itself would use, VPN or not.+ ///+ /// Anything else sent to the gateway goes to the Mac's loopback, as TCP+ /// does (see `VPhoneTCPForwarder.gatewayAddress`).private func resolveDestination(for flow: VPhoneUDPFlow) -> (address: VPhoneIPv4Address, port: UInt16) {- guard flow.destinationAddress == configuration.hostAddress, flow.destinationPort == 53 else {+ guard flow.destinationAddress == configuration.hostAddress else {return (flow.destinationAddress, flow.destinationPort)}+ guard flow.destinationPort == 53 else {+ return (VPhoneIPv4Address(127, 0, 0, 1), flow.destinationPort)+ }guard let resolver = VPhoneHostResolver.preferred() else {return (flow.destinationAddress, flow.destinationPort)}diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swiftindex b38a9af0..30683f53 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift@@ -71,7 +71,7 @@ public final class VPhoneUserspaceNetwork: @unchecked Sendable {/// Terminates the guest's TCP against host sockets. Owns one connection per/// flow, and emits segments of its own rather than echoing ours.- private lazy var tcpForwarder = VPhoneTCPForwarder(queue: queue) { [weak self] flow, segment in+ private lazy var tcpForwarder = VPhoneTCPForwarder(queue: queue, gatewayAddress: configuration.hostAddress) { [weak self] flow, segment inself?.sendTCPReply(flow: flow, segment: segment)}diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swiftindex cb605a31..002ca994 100644--- a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift@@ -1,4 +1,5 @@import Foundation+import SystemConfigurationimport Virtualization// MARK: - Errors@@ -96,6 +97,7 @@ public enum VPhoneNetworking {into current: NetworkConfig,mode: NetworkMode?,bridgeInterface: String?,+ resolvesMacName: Bool? = nil,) throws -> NetworkConfig {let newMode = mode ?? current.modeif newMode == .hostOnly {@@ -110,7 +112,110 @@ public enum VPhoneNetworking {}newBridge = current.bridgeInterface}- return NetworkConfig(mode: newMode, macAddress: current.macAddress, bridgeInterface: newBridge)+ return NetworkConfig(+ mode: newMode,+ macAddress: current.macAddress,+ bridgeInterface: newBridge,+ // On is the default, so it is stored as an absent key.+ resolvesMacName: resolvesMacName.map { $0 ? nil : false } ?? current.resolvesMacName,+ )+ }++ // MARK: - The Mac's name in the guest++ /// A name vphoned has the guest resolve locally (vphoned's+ /// `GuestStaticNames`).+ public struct StaticName: Equatable, Sendable {+ public let address: VPhoneIPv4Address+ public let names: [String]++ /// As vphoned's `network.static_names.set` takes it.+ public var parameters: [String: Any] {+ ["address": address.description, "names": names]+ }+ }++ /// This Mac's mDNS name, as `scutil --get LocalHostName` prints it.+ public static func macLocalHostName() -> String? {+ SCDynamicStoreCopyLocalHostName(nil) as String?+ }++ /// The Mac's address on vmnet's shared network, the one+ /// `VZNATNetworkDeviceAttachment` uses: `Shared_Net_Address` in vmnet's+ /// preferences when it has been moved, `192.168.64.1` otherwise.+ public static func sharedNATHostAddress() -> VPhoneIPv4Address {+ let plist = URL(fileURLWithPath: "/Library/Preferences/SystemConfiguration/com.apple.vmnet.plist")+ let values = (try? Data(contentsOf: plist))+ .flatMap { try? PropertyListSerialization.propertyList(from: $0, format: nil) as? [String: Any] }+ return (values?["Shared_Net_Address"] as? String).flatMap(VPhoneIPv4Address.init(dotted:))+ ?? VPhoneIPv4Address(192, 168, 64, 1)+ }++ /// The first IPv4 address of a host interface, for `bridged`.+ public static func ipv4Address(ofInterface name: String) -> VPhoneIPv4Address? {+ var list: UnsafeMutablePointer<ifaddrs>?+ guard getifaddrs(&list) == 0 else { return nil }+ defer { freeifaddrs(list) }+ var entry = list+ while let interface = entry {+ defer { entry = interface.pointee.ifa_next }+ guard String(cString: interface.pointee.ifa_name) == name,+ let address = interface.pointee.ifa_addr, address.pointee.sa_family == UInt8(AF_INET)+ else { continue }+ let raw = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr.s_addr }+ return VPhoneIPv4Address(UInt32(bigEndian: raw))+ }+ return nil+ }++ /// The address the guest reaches this Mac at: the shared network's host+ /// address in `nat`, the gateway in `tunnel` (which carries it to the+ /// Mac's loopback), the Mac's address on the bridged interface in+ /// `bridged`. Nil without a NIC.+ public static func macAddressForGuest(+ _ cfg: NetworkConfig,+ sharedNATHost: VPhoneIPv4Address,+ bridgedAddress: VPhoneIPv4Address?,+ ) -> VPhoneIPv4Address? {+ switch cfg.mode {+ case .nat: sharedNATHost+ case .tunnel: VPhoneUserspaceNetworkConfiguration.default.hostAddress+ case .bridged: bridgedAddress+ case .off, .hostOnly: nil+ }+ }++ /// The names vphoned should have the guest resolve locally: this Mac's+ /// `<LocalHostName>.local` at the address the guest reaches it at. Empty+ /// when turned off or no address is known, which withdraws them.+ ///+ /// Over mDNS alone an IPv4 lookup of the Mac's name can fail: the guest+ /// also hears the Mac on the virtual iPhone's USB link, where the Mac has+ /// no IPv4 address and answers "no such record", and the fastest answer+ /// wins. See Research/Guest/mac_name_resolution.md.+ public static func macStaticNames(+ _ cfg: NetworkConfig,+ macName: String?,+ sharedNATHost: VPhoneIPv4Address,+ bridgedAddress: VPhoneIPv4Address? = nil,+ ) -> [StaticName] {+ guard cfg.resolvesMacName != false, let macName, !macName.isEmpty,+ let address = macAddressForGuest(cfg, sharedNATHost: sharedNATHost, bridgedAddress: bridgedAddress)+ else { return [] }+ return [StaticName(address: address, names: ["\(macName).local"])]+ }++ /// Whether vphoned should route 169.254.0.0/16 over the virtual iPhone's+ /// USB link, so the Mac's link-local address there, which lookups of the+ /// Mac's name list first, is reachable from plain sockets. Not in+ /// `bridged`, where en0 may need link-local addresses on the LAN. Nil+ /// without a NIC: nothing to send.+ public static func routesLinkLocalOverUSB(_ cfg: NetworkConfig) -> Bool? {+ switch cfg.mode {+ case .off, .hostOnly: nil+ case .bridged: false+ case .nat, .tunnel: cfg.resolvesMacName != false+ }}/// Build the VZ network device for a config, or nil for `.off` (no NIC).diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swiftindex 57134fdd..bf8caa9c 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift@@ -169,6 +169,11 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {public let macAddress: String/// Host interface identifier to bridge (bridged mode only); nil otherwise.public let bridgeInterface: String?+ /// Whether the guest resolves this Mac's `.local` name to the address it+ /// reaches the Mac at, through a record vphoned registers with the+ /// guest's mDNSResponder. Nil means yes; see+ /// `VPhoneNetworking.macStaticNames`.+ public let resolvesMacName: Bool?public enum NetworkMode: String, Codable, Sendable {case nat@@ -186,10 +191,11 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {public static let `default` = NetworkConfig(mode: .nat, macAddress: "")- public init(mode: NetworkMode, macAddress: String, bridgeInterface: String? = nil) {+ public init(mode: NetworkMode, macAddress: String, bridgeInterface: String? = nil, resolvesMacName: Bool? = nil) {self.mode = modeself.macAddress = macAddressself.bridgeInterface = bridgeInterface+ self.resolvesMacName = resolvesMacName}}diff --git a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTunnelGatewayTests.swift b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTunnelGatewayTests.swiftnew file mode 100644index 00000000..020b9f9d--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneTunnelGatewayTests.swift@@ -0,0 +1,120 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// The tunnel's gateway stands for the Mac: guest connections to it reach the+/// Mac's loopback, and a refused one is refused at once.+struct VPhoneTunnelGatewayTests {+ private let guestMAC = VPhoneMACAddress([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE])++ /// The guest's end of the frame socket pair.+ private final class GuestLink: @unchecked Sendable {+ let descriptor: Int32+ let network: VPhoneUserspaceNetwork++ init() throws {+ var pair: [Int32] = [-1, -1]+ guard socketpair(AF_UNIX, SOCK_DGRAM, 0, &pair) == 0 else { throw POSIXError(.EMFILE) }+ descriptor = pair[0]+ network = try VPhoneUserspaceNetwork(configuration: .default, guestDescriptor: pair[0], hostDescriptor: pair[1])+ }++ func write(_ frame: [UInt8]) {+ _ = frame.withUnsafeBytes { Darwin.send(descriptor, $0.baseAddress, $0.count, 0) }+ }++ /// The next TCP segment toward the guest, skipping anything else.+ func readSegment(timeout: TimeInterval = 3) -> VPhoneTCPSegment? {+ var buffer = [UInt8](repeating: 0, count: 9216)+ let deadline = Date().addingTimeInterval(timeout)+ while Date() < deadline {+ let count = recv(descriptor, &buffer, buffer.count, MSG_DONTWAIT)+ if count > 0,+ let frame = VPhoneEthernetFrame(bytes: Array(buffer[0 ..< count])),+ let packet = VPhoneIPv4Packet(bytes: frame.payload),+ packet.proto == VPhoneIPProtocol.tcp.rawValue,+ let segment = VPhoneTCPSegment(bytes: packet.payload)+ {+ return segment+ }+ usleep(5000)+ }+ return nil+ }+ }++ /// A segment from the guest to the gateway.+ private func guestFrame(_ segment: VPhoneTCPSegment) -> [UInt8] {+ let configuration = VPhoneUserspaceNetworkConfiguration.default+ return VPhoneEthernetFrame(+ destination: .gateway,+ source: guestMAC,+ etherType: .ipv4,+ payload: VPhoneIPv4Packet(+ source: configuration.guestAddress,+ destination: configuration.hostAddress,+ proto: .tcp,+ payload: segment.bytes(source: configuration.guestAddress, destination: configuration.hostAddress),+ ).bytes,+ ).bytes+ }++ /// A loopback TCP socket: listening on a free port, or (with `listening`+ /// false) only bound, to find a port nothing listens on.+ private func loopbackSocket(listening: Bool) throws -> (Int32, UInt16) {+ let descriptor = socket(AF_INET, SOCK_STREAM, 0)+ var address = sockaddr_in()+ address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)+ address.sin_family = sa_family_t(AF_INET)+ address.sin_addr = in_addr(s_addr: UInt32(0x7F00_0001).bigEndian)+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)+ try withUnsafeMutablePointer(to: &address) { pointer in+ try pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ guard bind(descriptor, $0, length) == 0, getsockname(descriptor, $0, &length) == 0 else {+ throw POSIXError(.EADDRINUSE)+ }+ }+ }+ if listening {+ _ = listen(descriptor, 4)+ }+ return (descriptor, UInt16(bigEndian: address.sin_port))+ }++ @Test func `a guest connection to the gateway reaches the Mac's loopback`() throws {+ let (server, port) = try loopbackSocket(listening: true)+ defer { close(server) }+ let link = try GuestLink()+ link.network.start()+ defer { link.network.stop() }++ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 51000, destinationPort: port, sequenceNumber: 100, acknowledgmentNumber: 0,+ flags: VPhoneTCPFlags.syn, windowSize: 65535, advertisedMSS: 1460,+ )))+ let synAck = try #require(link.readSegment(), "no SYN-ACK from the gateway")+ #expect(synAck.hasSYN && synAck.hasACK)+ #expect(synAck.acknowledgmentNumber == 101)+ let accepted = accept(server, nil, nil)+ #expect(accepted >= 0, "nothing reached the Mac's loopback")+ close(accepted)+ }++ /// The RST has to acknowledge the guest's SYN, or the guest ignores it and+ /// retries until it times out.+ @Test func `a refused connection resets the guest at once`() throws {+ let (bound, closedPort) = try loopbackSocket(listening: false)+ close(bound)+ let link = try GuestLink()+ link.network.start()+ defer { link.network.stop() }++ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 51001, destinationPort: closedPort, sequenceNumber: 500, acknowledgmentNumber: 0,+ flags: VPhoneTCPFlags.syn, windowSize: 65535,+ )))+ let reset = try #require(link.readSegment(), "no answer to a SYN for a closed port")+ #expect(reset.hasRST && reset.hasACK)+ #expect(reset.acknowledgmentNumber == 501)+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swiftnew file mode 100644index 00000000..88ffacb8--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift@@ -0,0 +1,63 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// This Mac's `.local` name in the guest: where it points in each mode, and+/// how it is turned off.+struct MacNameTests {+ typealias NetworkConfig = VPhoneVirtualMachineManifest.NetworkConfig++ private let shared = VPhoneIPv4Address(192, 168, 64, 1)++ @Test func `the Mac's name points where the guest reaches the Mac`() {+ #expect(VPhoneNetworking.macStaticNames(NetworkConfig(mode: .nat, macAddress: ""), macName: "Lab-Mac", sharedNATHost: shared) == [+ .init(address: shared, names: ["Lab-Mac.local"]),+ ])+ #expect(+ VPhoneNetworking.macStaticNames(NetworkConfig(mode: .tunnel, macAddress: ""), macName: "Lab-Mac", sharedNATHost: shared).first?.address+ == VPhoneUserspaceNetworkConfiguration.default.hostAddress,+ )+ let bridged = NetworkConfig(mode: .bridged, macAddress: "", bridgeInterface: "en0")+ #expect(VPhoneNetworking.macStaticNames(bridged, macName: "Lab-Mac", sharedNATHost: shared).isEmpty)+ #expect(+ VPhoneNetworking.macStaticNames(bridged, macName: "Lab-Mac", sharedNATHost: shared, bridgedAddress: VPhoneIPv4Address(10, 0, 0, 7)).first?.address+ == VPhoneIPv4Address(10, 0, 0, 7),+ )+ #expect(VPhoneNetworking.macStaticNames(NetworkConfig(mode: .off, macAddress: ""), macName: "Lab-Mac", sharedNATHost: shared).isEmpty)+ #expect(VPhoneNetworking.macStaticNames(NetworkConfig(mode: .nat, macAddress: ""), macName: nil, sharedNATHost: shared).isEmpty)+ }++ /// On by default and stored as an absent key, so only `off` reaches the+ /// plist, and changing the mode keeps it.+ @Test func `the Mac's name can be turned off and stays off`() throws {+ let off = try VPhoneNetworking.merge(into: .default, mode: nil, bridgeInterface: nil, resolvesMacName: false)+ #expect(off.resolvesMacName == false)+ #expect(VPhoneNetworking.macStaticNames(off, macName: "Lab-Mac", sharedNATHost: shared).isEmpty)+ let tunnel = try VPhoneNetworking.merge(into: off, mode: .tunnel, bridgeInterface: nil)+ #expect(tunnel.resolvesMacName == false)+ let on = try VPhoneNetworking.merge(into: tunnel, mode: nil, bridgeInterface: nil, resolvesMacName: true)+ #expect(on.resolvesMacName == nil)+ }++ /// The USB-link routes go with the Mac's name, except where en0 may need+ /// link-local itself, and there is nothing to send without a NIC.+ @Test func `link-local is routed over USB in nat and tunnel only`() {+ #expect(VPhoneNetworking.routesLinkLocalOverUSB(NetworkConfig(mode: .nat, macAddress: "")) == true)+ #expect(VPhoneNetworking.routesLinkLocalOverUSB(NetworkConfig(mode: .tunnel, macAddress: "")) == true)+ #expect(VPhoneNetworking.routesLinkLocalOverUSB(NetworkConfig(mode: .bridged, macAddress: "")) == false)+ #expect(VPhoneNetworking.routesLinkLocalOverUSB(NetworkConfig(mode: .nat, macAddress: "", resolvesMacName: false)) == false)+ #expect(VPhoneNetworking.routesLinkLocalOverUSB(NetworkConfig(mode: .off, macAddress: "")) == nil)+ }++ @Test func `configs without the key decode with the default`() throws {+ let plist = Data("""+ <?xml version="1.0" encoding="UTF-8"?>+ <plist version="1.0"><dict><key>mode</key><string>nat</string><key>macAddress</key><string></string></dict></plist>+ """.utf8)+ let decoded = try PropertyListDecoder().decode(NetworkConfig.self, from: plist)+ #expect(decoded.resolvesMacName == nil)+ let encoder = PropertyListEncoder()+ encoder.outputFormat = .xml+ #expect(!String(decoding: try encoder.encode(decoded), as: UTF8.self).contains("resolvesMacName"))+ }+}