Run a virtual iPhone on an Apple Silicon Mac.
Swift
Answer the Mac's name from a LocalOnly record; drop the 169.254 routes
Jackyd11da1adbbc8
diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.mdindex bf621844..fe6ccebd 100644--- a/Documents/Guides/networking.md+++ b/Documents/Guides/networking.md@@ -106,23 +106,21 @@ Mac, where the Mac has no IPv4 address and answers "no such record". Whicheverlink answers first decides the lookup, so an app that wants an IPv4 addressgot 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.+vphoned registers the name with the guest's own mDNSResponder the way it+holds an `/etc/hosts` line: as a local record that answers an IPv4 lookup at+once, with that one address, without asking the network and without the+answers it has cached. It does so each time `vphone-vm` connects, and again+when vphoned starts, so the name is in place before apps run after a reboot.+The guest's system volume is read-only, so `/etc/hosts` itself is not edited,+and nothing is announced on any network. IPv6 lookups still go to mDNS.++Without it, a lookup also listed the Mac's `169.254` address on the USB link,+first. iOS routes `169.254.0.0/16` through its primary interface, so a plain+socket connecting to that address could leave through `en0`, where nothing+answers, and wait out its timeout.```sh-vphone-cli vm config <name> --mac-name off # withdraw both+vphone-cli vm config <name> --mac-name off # withdraw it```To see what the guest's resolver returns, and whether each address connects:diff --git a/Research/Guest/mac_name_resolution.md b/Research/Guest/mac_name_resolution.mdindex c05bc516..67ed38dc 100644--- a/Research/Guest/mac_name_resolution.md+++ b/Research/Guest/mac_name_resolution.md@@ -4,9 +4,11 @@ A guest process doing a plain BSD `connect("<mac>.local")` hung. What theguest's resolver returned, and what vphoned now does about it. User-facingbehaviour 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).+Measured 2026-10-03 with vphoned's `network.resolve` and a temporary in-guest+probe (register a record, then `getaddrinfo(AF_INET)` every 20 ms) on a macOS+27.0.1 host (LocalHostName `JackyMacBook-Pro`): `pcc-research-01` and the+freshly created `nettest-01` (iOS 27.0, nat and tunnel), and `ipad-mini-01`+(iOS 26.6.2, nat).## Two links to the Mac@@ -15,57 +17,65 @@ gives the Mac: `en1` (a self-assigned `169.254` address) and `anpi0` (IPv6only) in the guest, an `enN` and an `anriN` on the Mac. The Mac announces itsname 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".+and, for the A record on each `anriN`, "No Such Record" with a TTL of 1 s.## What the guest's resolver returned- Right after boot, `getaddrinfo(AF_INET)` failed in 1 ms with "nodename norservname 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.+ answer over `anpi0` arrived first and the guest took it as final.+- Later, with answers cached from the other links, IPv4 lookups returned the+ Mac's `169.254` address on `en1` first, then `192.168.64.1`. They still+ failed now and then: with nothing registered, about one lookup in a+ thousand at 20 ms intervals (1 in 748, 1 in 76, 0 in 2199), as the 1 s+ negative is queried again and again.+- The first plain connect to the `169.254` address could leave through `en0`+ (source `192.168.64.61`) and time out: iOS routes `169.254.0.0/16` through+ the primary interface. Seen against the Mac's own TCP stack too.`/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 a registered record does, by kind++mDNSResponder (`mDNSCore/mDNS.c`, mDNSResponder-2881) treats a record that is+LocalOnly *and* of a unique type as it treats an `/etc/hosts` line+(`UniqueLocalOnlyRecord`): it answers an address question at once, keeps the+question off the wire, and while it answers (`LOAddressAnswers`) cached+answers, positive or negative, are not delivered. An unverified `Unique`+record is never delivered to a question, and LocalOnly records are never+probed, so the flag that works is `kDNSServiceFlagsKnownUnique`.++What `getaddrinfo(AF_INET)` returned, with `JackyMacBook-Pro.local` →+`192.168.64.1` registered each way:++| Registration | Answer |+| --- | --- |+| none | `169.254.198.56, 192.168.64.1` |+| shared, on `lo0` | the cached answers plus `192.168.64.1`. A multicast record on loopback reaches the resolver through the cache, so the race stays, and each registration churned the cache (11 failures in the 2 s after one registration) |+| shared, LocalOnly | `169.254.198.56, 192.168.64.1, 192.168.64.1`, alongside the cache |+| known-unique, LocalOnly | `192.168.64.1` alone, from the first lookup |++With the known-unique LocalOnly record: 0 failures in 2210 and 2202 lookups+(60 s each), and 0 in each run right after registering; the answer was never+anything but `192.168.64.1`. Because the cache is not consulted, neither the+negative answer nor the `169.254` address reaches an IPv4 lookup, so nothing+needs routing over the USB link.+## 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.+1. `vphone-vm` sends `<LocalHostName>.local` → the address the guest reaches+ the Mac at after every connect (the shared NAT host address, the tunnel+ gateway, or the Mac's address on the bridged interface), and an empty list+ without a NIC. vphoned registers it as a known-unique LocalOnly A record+ (`GuestStaticNames.swift`), saves it, and registers it again as it starts,+ so it is in place before apps run after a reboot. IPv6 lookups still go to+ mDNS and get the Mac's link-local addresses, which are scoped and work.+2. 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.+`--mac-name off` withdraws the record and removes the saved file.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 1af0a15d..b7f06c1d 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), `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` |+| 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.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}` |@@ -291,21 +291,12 @@ request carries `"force": true`.`network.static_names.set` replaces the names the guest resolves locally, givenas `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.+vphoned registers each name as a LocalOnly, known-unique A record with the+guest's own mDNSResponder (`VPhoneDaemon/Daemon/GuestStaticNames.swift`), the+kind of record an `/etc/hosts` line becomes: an IPv4 lookup of the name returns+that address alone, at once, without a query on the wire or cached answers. It+saves them and registers them again when it starts; `get` lists them.+`vphone-vm` sets this Mac's `<LocalHostName>.local` after every connect.`network.resolve` runs `getaddrinfo` in the guest (`family` `ipv4`, `ipv6` orany) and returns `{host, status, elapsed_ms, addresses}`, the addresses in the@@ -321,7 +312,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`, `network_static_names`, `network_usb_link_route`, `network_resolve`) so a host can hide+`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_static_names`, `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 8faa5c62..6ae70e6d 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -37,11 +37,6 @@ extension GuestAPI {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":diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 5be12dee..2def68eb 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -98,7 +98,6 @@ enum GuestAPI {"udid_override","setup_skip","network_static_names",- "network_usb_link_route","network_resolve",],]diff --git a/VPhoneDaemon/Daemon/GuestStaticNames.swift b/VPhoneDaemon/Daemon/GuestStaticNames.swiftindex 6d8b0374..ed21eeb6 100644--- a/VPhoneDaemon/Daemon/GuestStaticNames.swift+++ b/VPhoneDaemon/Daemon/GuestStaticNames.swift@@ -2,27 +2,34 @@ import dnssdimport 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.+/// with the guest's own mDNSResponder as LocalOnly and known-unique, held for+/// as long as vphoned runs, saved, and registered again as vphoned starts so+/// they are in place before apps run after a reboot.////// 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.+/// record"; whichever answer arrives first decides the lookup, so IPv4 lookups+/// of the Mac's name failed now and then, steadily (about one in a thousand at+/// 20 ms intervals), and outright right after boot.///-/// - `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.+/// A LocalOnly record of a unique type is what mDNSResponder makes of an+/// `/etc/hosts` line (`UniqueLocalOnlyRecord` in mDNSCore/mDNS.c): it answers+/// an address question at once, the question is not sent on the wire, and+/// cached answers, the negative one included, are not delivered for it+/// (`LOAddressAnswers`). So a lookup returns exactly this address, every time:+///+/// - Known-unique, not unique: an unverified unique record is never delivered+/// to a question, and a LocalOnly record is never probed or verified.+/// - Not shared: a shared LocalOnly record answers alongside the cache, so the+/// race stays (and the Mac's `169.254` address on the USB link comes first).+/// - Not on `lo0`: that is a multicast record on the loopback interface,+/// which reaches the resolver only through the cache, with the same race,+/// and every registration churned the cache for that name./// - Nothing is written to disk: the system volume is sealed and read-only, so-/// `/etc/hosts` cannot be edited without a remount.+/// `/etc/hosts` itself cannot be edited without a remount.+///+/// Measured on iOS 27.0; see Research/Guest/mac_name_resolution.md.////// Threading: every field is touched under `lock`; the connection's replies/// are drained on `queue`. That is the invariant behind `@unchecked Sendable`.@@ -81,14 +88,13 @@ final class GuestStaticNames: @unchecked Sendable {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,+ created, &record, DNSServiceFlags(kDNSServiceFlagsKnownUnique), kDNSServiceInterfaceIndexLocalOnly,fullName, UInt16(kDNSServiceType_A), UInt16(kDNSServiceClass_IN),UInt16(address.count), &address, 120, { _, _, _, _, _ in }, nil,)diff --git a/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swift b/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swiftdeleted file mode 100644index e596f434..00000000--- a/VPhoneDaemon/Daemon/GuestUSBLinkRoute.swift+++ /dev/null@@ -1,75 +0,0 @@-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 024c7fc1..db98c05a 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -20,7 +20,6 @@ _ = 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 7b73578b..b28566b1 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -51,9 +51,4 @@ 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.mdeleted file mode 100644index ec0f530e..00000000--- a/VPhoneDaemon/Native/vphoned_network.m+++ /dev/null@@ -1,135 +0,0 @@-#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/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex f2a0aee4..48cdc69a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -51,9 +51,6 @@ final class VPhoneGuestControl {/// 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@@ -199,9 +196,6 @@ final class VPhoneGuestControl {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 {@@ -843,17 +837,4 @@ extension VPhoneGuestControl {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 4b234174..fd30390a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -277,12 +277,12 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {}/// 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.+ /// reaches the Mac at.@MainActorprivate func configureGuestNames(control: VPhoneGuestControl, configURL: URL) {+ // Sent in every mode: without a NIC the list is empty, which withdraws+ // names a previous launch left in the guest.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:))diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swiftindex 002ca994..9a0f40a3 100644--- a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift@@ -205,19 +205,6 @@ public enum VPhoneNetworking {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)./// The MAC is left framework-assigned; a forced MAC breaks guest networking./// Throws if the config cannot be realized (missing bridge interface, hostOnly).diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swiftindex 88ffacb8..32a7424f 100644--- a/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift@@ -39,16 +39,6 @@ struct MacNameTests {#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"?>