Run a virtual iPhone on an Apple Silicon Mac.
Swift
Add guest network settings: MAC, fixed IPv4, port forwards, mDNS name
Jacky9ab69f8813bf
diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.mdindex fe6ccebd..e92af6c1 100644--- a/Documents/Guides/networking.md+++ b/Documents/Guides/networking.md@@ -49,8 +49,8 @@ and the app's rules apply to it as they would to any other app.| Item | Value || --- | --- |-| Guest address | `192.168.127.3/24`, by DHCP |-| Gateway and DNS | `192.168.127.1` |+| Guest address | `192.168.127.3/24` by DHCP, or the [fixed address](#fixed-address) |+| Gateway and DNS | `192.168.127.1`, or the first address of the fixed address's subnet || 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) |@@ -58,9 +58,10 @@ and the app's rules apply to it as they would to any other app.## Limits- **IPv4 only.** The guest gets no IPv6 address, and IPv6 traffic is dropped.-- **Outbound only.** Nothing on the Mac or the LAN can connect to a port in the- guest through this network. USB access (`iproxy`, `ideviceinstaller`) and- `vphone.sock` do not use the guest network, so they still work.+- **Outbound only, apart from forwarded ports.** Nothing on the Mac or the LAN+ can reach the guest through this network except the ports listed under+ [Port forwarding](#port-forwarding). USB access (`iproxy`, `ideviceinstaller`)+ and `vphone.sock` do not use the guest network, so they still work.- **Ping reaches the gateway only.** ICMP to the internet is not forwarded,so `ping 1.1.1.1` in the guest fails even while TCP and UDP work.- **Throughput is limited by `vphone-vm`.** Every packet is handled in this@@ -89,6 +90,112 @@ and the app's rules apply to it as they would to any other app.lsof -nP -a -i -p "$(pgrep -f 'vphone-vm.*<name>')"```+## MAC address++The first launch gives the guest's network card a random, locally administered+MAC address and saves it in `config.plist`, the way it saves the machine+identifier. The guest then keeps one identity, and one DHCP lease, across+launches. To set or replace it:++```sh+vphone-cli vm config <name> --mac 02:11:22:33:44:55+vphone-cli vm config <name> --mac random # a new one now+vphone-cli vm config <name> --mac auto # a new one at the next launch+```++A cloned machine keeps the MAC of the original, like its machine identifier.+Give the clone a new one before running both at once.++## Fixed address++`--ip` gives the guest a fixed IPv4 address. Without a prefix, `/24` is+assumed. `--gateway` and `--dns` are optional; `auto` returns them to the+default, and `--ip dhcp` removes the fixed address.++```sh+vphone-cli vm config <name> --ip 192.168.64.50+vphone-cli vm config <name> --network tunnel --ip 10.20.0.5/16 --dns 1.1.1.1+vphone-cli vm config <name> --ip dhcp+```++How the address reaches the guest depends on the mode:++| Mode | Address | How it is applied |+| --- | --- | --- |+| `nat` | On the Mac's shared NAT network, normally `192.168.64.0/24` | vphoned writes it into the guest's network settings. The gateway and DNS are the Mac, `192.168.64.1`. |+| `tunnel` | Any private subnet | The tunnel's own DHCP hands it out. The gateway, which is also the DNS resolver, is the subnet's first address unless `--gateway` names another. |+| `bridged` | An address on the physical network | vphoned writes it into the guest. Set `--gateway` and `--dns` to the network's own. |++In `nat` mode the address has to be on the shared network, the one every `nat`+VM uses (vmnet's `Shared_Net_Address`, if it has been moved). For any other+subnet, use `tunnel`. macOS 26 can give a VM a NAT network of its own, but the+subnet then stays reserved after the VM stops (still so 40 minutes later in+testing), and every launch on it fails meanwhile, so vphone does not use it.++vphoned applies the address each time `vphone-vm` connects to it, so a guest+changed while the Mac was not looking is put back. It only ever undoes its own+setting: an address typed into the guest's Settings app is left alone when the+VM goes back to DHCP. An address on the shared `nat` network is not reserved in+the Mac's DHCP server, so pick one high in the range, such as `.200`, that DHCP+is unlikely to have handed to another VM.++## Port forwarding++`--forward` carries a port on the Mac into the guest, in `nat` and `tunnel`+modes. The form is `[tcp|udp:][host-address:]host-port:guest-port`. A forward+listens on `127.0.0.1` unless a host address is given; `0.0.0.0` makes it+reachable from other devices on the LAN.++```sh+vphone-cli vm config <name> --forward tcp:8022:22+vphone-cli vm config <name> --forward udp:0.0.0.0:5353:53+vphone-cli vm config <name> --remove-forward 8022+vphone-cli vm config <name> --clear-forwards+```++`vphone-vm` opens the listeners when the VM starts and closes them when it+stops. In `nat` mode it connects to the guest's address: the fixed one, or the+one vphoned reports. In `tunnel` mode the connection reaches the guest as if it+came from the gateway. A port that is already taken on the Mac is reported in+the VM's log and skipped; the rest still work. `bridged` puts the guest on the+LAN with its own address, so it needs no forwards.++## Name on the local network (mDNS)++Off by default. `--mdns on` makes the guest answer to `<vm-name>.local`, with+anything but letters and digits in the VM name turned into hyphens+(`ipad_pro.13` becomes `ipad-pro-13.local`). `--mdns <name>` picks another+name, and `--mdns off` puts the guest's own name back.++```sh+vphone-cli vm config <name> --mdns on+ping <vm-name>.local+```++vphoned sets the name in the guest's network settings (`LocalHostName`) each+time `vphone-vm` connects, and the guest's mDNSResponder announces it on every+link it has. Besides its network card, a guest has the network link a USB-connected+iPhone gives the Mac, which shows up on the Mac as an `en` interface with a+`169.254` address. So the name works in+every mode, `none` included:++| Mode | `<name>.local` resolves to |+| --- | --- |+| `nat` | The guest's address on the shared network, and its USB link address |+| `bridged` | The guest's LAN address, for every device on the LAN, and its USB link address on the Mac |+| `tunnel`, `none` | The guest's USB link address, on the Mac only |++The USB link address is link-local, but the Mac reaches the guest on it+directly, so in `tunnel` mode a connection to `<name>.local` reaches a guest+service without a port forward.++If another device already uses the name, mDNS renames the guest (`name-2`).+Renaming the VM with `vm rename` renames a name `--mdns on` derived from it;+one picked by hand stays. A VM stopped with `vm stop` or by closing its window+cannot withdraw its announcement, so the Mac's resolver keeps returning the+old address until the cached record expires, which for a host address is 75+minutes (TTL 4500 s).+## This Mac's name in the guestOn by default. The guest resolves this Mac's mDNS name (`scutil --get@@ -97,7 +204,7 @@ 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 |+| `tunnel` | The gateway, `192.168.127.1` by default. 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@@ -128,3 +235,24 @@ To see what the guest's resolver returns, and whether each address connects:```shvphone-launchpad-cli guest rpc <name> network.resolve '{"host":"<Mac>.local","family":"ipv4","port":8000}'```++## Unplugging a running VM++`vm network` acts on a VM that is running, and nothing it does is saved:++```sh+vphone-cli vm network <name> # state of the NIC+vphone-cli vm network <name> --link down # unplug the cable+vphone-cli vm network <name> --link up # plug it back in+```++The guest sees the link drop and come back. The same is available on+`vphone.sock` as `{"t":"network"}`, with `"link":"down"` or `"link":"up"`.++A running VM cannot move to another network. Virtualization accepts the+change and then stops the VM with an internal error, so `vm network` only ever+puts back the network the VM started on. Change the mode with `vm config` and+restart.++In Launchpad, Settings… has Address and Port Forwarding sections when one+machine is selected.diff --git a/Research/Host/network_fixed_address.md b/Research/Host/network_fixed_address.mdnew file mode 100644index 00000000..1db3b5d2--- /dev/null+++ b/Research/Host/network_fixed_address.md@@ -0,0 +1,201 @@+# Guest MAC, fixed address, port forwarding and names++What was tried on a real guest before settling the design in+`VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift`, and why some of it+was taken out again. User-facing behaviour is in+`Documents/Guides/networking.md`.++Tested on 2026-10-02: macOS 27.0.1 (26A434) host, `pcc-research-01` guest+(iOS 27.0, 24A435, cloudOS 26.4), launched headless from a local bundle.++## A fixed MAC does not break guest networking++`c6fa19e` left the MAC to Virtualization, noting that forcing one broke guest+networking. Without a fixed MAC every launch gets a new random one, so a NAT+guest takes a new DHCP lease, and usually a new address, each time.++`vphone-vm` now generates a random, locally administered, unicast MAC on first+launch and saves it in `config.plist` (`networkConfig.macAddress`), the way it+saves `machineIdentifier`. With `aa:73:76:98:a7:06`:++- the guest got `192.168.64.20` from vmnet's DHCP on `en0`;+- the Mac's ARP table showed the guest at that MAC on the shared bridge;+- ping from the Mac, and DNS and HTTPS from the guest (Safari opening+ `https://example.com`, seen with `network.capture`), all worked.++Whatever broke before was not a fixed MAC as such. One likely cause is the same+MAC on several VMs, for example from a manifest template: two guests on one+L2 network with one MAC cannot both work. Each VM now gets its own, and a clone+keeps the original's, like its machine identifier.++## Fixed address in nat mode: the shared network only++vphoned writes a manual IPv4 configuration into the guest's network+preferences (`network.ipv4.set`, `VPhoneDaemon/Native/vphoned_network.m`).+With `--ip 192.168.64.210`:++- `network.ipv4.get` reported `method: manual`, `managed: true`, router+ `192.168.64.1`, and `en0` carried `192.168.64.210`;+- ping from the Mac, and DNS (now sent to `192.168.64.1`) and HTTPS from the+ guest worked.++### vmnet networks of the VM's own were tried and dropped++macOS 26 added `vmnet_network_configuration_create` and+`VZVmnetNetworkDeviceAttachment`, which give a VM a NAT network on a subnet of+its choosing. Three findings:++1. **The subnet address is the host's address.**+ `vmnet_network_configuration_set_ipv4_subnet` with `192.168.70.0` creates a+ network, but the VM's interface then fails at start with+ `VZErrorDomain Code=1` "internal network error", and the attachment is+ detached. A default network reports `192.168.65.1` from+ `vmnet_network_get_ipv4_subnet`. Passing `192.168.71.1` works: the Mac gets+ a `bridgeN` at `192.168.71.1`, and the guest, at `192.168.71.10`, had ping,+ DNS, HTTPS and a forwarded port.+2. **A DHCP reservation broke creation.**+ `vmnet_network_configuration_add_dhcp_reservation` returned success, and+ `vmnet_network_create` then returned `VMNET_FAILURE` (1001). (This may have+ been finding 3 instead: the reserved run came straight after a run on the+ same subnet.)+3. **A used subnet stays reserved.** Once a VM on `192.168.71.1/24` stopped+ (`vm stop`, which ends `vphone-vm` with SIGINT; Virtualization reports an+ unexpected stop, as it does for every `vm stop`), every later+ `vmnet_network_create` on that subnet failed with `VMNET_FAILURE`, retried+ every 30 seconds for six minutes. `192.168.70.0/24` was still refused 40+ minutes after its last use. Releasing the `vmnet_network_ref` explicitly+ (`CFRelease` in `applicationWillTerminate`, logged) did not help: a fresh+ `192.168.72.0/24` was refused straight after one stop too. Only+ `/usr/libexec/InternetSharing` (root) was involved; nothing in `vphone-vm`+ was still alive.++A fixed address that works for one launch is not a fixed address, so nat+accepts addresses on the shared network only (`Shared_Net_Address` and+`Shared_Net_Mask` in `/Library/Preferences/SystemConfiguration/com.apple.vmnet.plist`,+default `192.168.64.1/24`), and tunnel covers other subnets. The subnets used+in testing (`192.168.70`, `.71`, `.72`) may stay unusable for vmnet on that+Mac until whatever holds them lets go.++To revisit: check whether a clean guest power-off (`guestDidStop`) frees the+subnet, whether a restart of InternetSharing does, and whether+`vmnet_network_copy_serialization` lets one network be reused across launches.++## Port forwarding++Listeners live in `vphone-vm` (`VPhonePortForwarder`), on `127.0.0.1` unless a+host address is given.++- nat: a forward from `127.0.0.1:18078` to guest port 62078 (lockdownd) made+ vphone-vm connect from `192.168.64.1` to `192.168.64.210:62078`; a capture in+ the guest showed the handshake. lockdownd closes unpaired network+ connections at once, directly and through the forward alike, so it shows+ the connection, not data. Data both ways, half-close and UDP are covered by+ `VPhonePortForwardingTests` over loopback.+- tunnel: covered by the same tests, which drive the userspace network's frame+ loop: SYN to the guest from the gateway, SYN-ACK, data both ways, and a+ guest RST closing the client.++## Changing the attachment of a running VM++`VZNetworkDevice.attachment` is settable while the VM runs.++- Setting it to nil and then back to the attachment the VM started with works:+ ping stopped, and came back about three seconds after the replug.+ `vm network --link down|up` does exactly this.+- Setting it to a new `VZNATNetworkDeviceAttachment` stopped the VM with+ `VZErrorDomain Code=1` "internal virtualization error" within seconds. So+ there is no runtime switch to another network; a mode change needs a restart.++## mDNS name++`--mdns` sets `System/Network/HostNames/LocalHostName` in the guest's network+preferences (`network.hostname.set`); the guest's mDNSResponder picks the new+name up at once, with no restart.++- nat: `pcc-research-01.local` resolved on the Mac to the guest's shared+ network address (and its IPv6 addresses), and answered ping.+- Every mode, `none` included: the guest also announces the name over the+ network link a USB-connected iPhone gives the Mac (`en1` and `anpi0` in the+ guest; on the Mac an `enN` with a `169.254` address and an `anriN`). With no+ network device, `lab-none-test.local` resolved to `169.254.96.74`, and in+ tunnel mode the Mac pinged the guest's link address and opened TCP 62078 on+ it.+- A first design registered `<name>.local` → `127.0.0.1` with the Mac's+ mDNSResponder (`DNSServiceRegisterRecord` on `lo0`; a LocalOnly record+ registered as `kDNSServiceFlagsUnique` showed in `dns-sd` but not in+ `getaddrinfo`, since an unverified unique record is never delivered to a+ question, see "The Mac's name in the guest" below) for tunnel guests. The guest's+ own announcement over the USB link claimed the same name, the Mac's record+ lost the conflict, and it was dropped. The guest's announcement is all that+ is needed.+- `vm stop` gives the guest no chance to send mDNS goodbyes, so the Mac's+ cache keeps the last address for the record's TTL, 4500 s.+- `network.hostname.set` with a null name put back the guest's original+ `iPhone` and removed the marker; a second call reported `changed: false`.++## The Mac's name in the guest++Reported from another session: a guest process doing a plain BSD+`connect("jackymacbook-pro.local")` hung. Measured with vphoned's+`network.resolve` on `pcc-research-01` (NAT, Mac `JackyMacBook-Pro`).++### 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 Mac on the+ virtual iPhone's private USB link. The Mac does announce+ `JackyMacBook-Pro.local` → `192.168.64.1` on the NAT bridge (`dns-sd -G`+ lists it on `bridge103`), but on its `anriN` interfaces, the other end of the+ guest's `anpi0`, it answers A with "No Such Record". That link answers first,+ and the guest returns the negative.+- Minutes later the same lookup returned `192.168.64.1` and the Mac's `169.254`+ address on the USB link (`en1` in the guest), once those answers had been+ cached. So the failure is a race whose outcome 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, with no tunnel involved.++### What did not work++- `/etc/hosts`: `/private/etc` is on the sealed System volume, mounted+ read-only ("Read-only file system" on write). An earlier test that appeared+ to work was reading cached mDNS answers.++### What is in place++1. vphoned registers `<LocalHostName>.local` → the address the guest reaches+ the Mac at as a LocalOnly, known-unique A record (`GuestStaticNames.swift`),+ saves it, and registers it again when it starts. mDNSResponder+ (`mDNSCore/mDNS.c`, mDNSResponder-2881) treats a LocalOnly record 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, the negative one+ included, are not delivered. An unverified `Unique` record is never+ delivered and LocalOnly records are never probed, hence+ `kDNSServiceFlagsKnownUnique`.+2. In tunnel, 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 a refused connect after about one second+ either way, against the Mac's own stack too.++What `getaddrinfo(AF_INET)` returned on `nettest-01` (iOS 27.0, nat), with+`JackyMacBook-Pro.local` → `192.168.64.1` registered each way, polling every+20 ms:++| Registration | Answer |+| --- | --- |+| none | `169.254.198.56, 192.168.64.1`; about one failure in a thousand lookups (1 in 748, 1 in 76, 0 in 2199) |+| shared, on `lo0` (the first version) | the cached answers plus `192.168.64.1`; the race stays, and each registration churned the cache (11 failures in the 2 s after one registration on `pcc-research-01`) |+| 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; 0 failures in 2210 and 2202 lookups (60 s each) and in every run right after registering |++Since the cache no longer reaches an IPv4 lookup of the name, the `169.254`+address is not returned either. The first version also routed+`169.254.0.0/16` through the USB link (two `/17` routes) so that address+would connect; that is gone with the shared `lo0` record.++`--mac-name off` withdraws the record and removes the saved file.diff --git a/Research/README.md b/Research/README.mdindex 8e898813..2908bdd8 100644--- a/Research/README.md+++ b/Research/README.md@@ -19,7 +19,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| Kernel | [CFW overview](Kernel/kernel_jb_patch_notes.md), [patcher verification](Kernel/kernel_patcher_verification.md), [FairPlay kexts](Kernel/kernel_fairplay_kexts.md), [base validation 1–5](Kernel/kernel_patch_base_first5_validation.md), [11–15](Kernel/kernel_patch_base_11_15_validation.md), [16–20](Kernel/kernel_patch_base_16_20_validation.md), [sandbox hooks](Kernel/kernel_patch_sandbox_hooks_17_26_validation.md), [individual patch notes](KernelCustomFirmwarePatches/README.md) || 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) |+| 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 MAC, fixed address, port forwarding and names](Host/network_fixed_address.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), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.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) |diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex e1f529d7..92566d45 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.resolve {host, family?, port?, first_only?, timeout_ms?}` (see below), `security.ssl_killswitch` |+| Network, security | `network.capture {seconds, interface?, filter?}` (writes a pcap in the guest scratch directory and returns its path), `network.ipv4.get {interface?}`, `network.ipv4.set {interface?, method, address?, subnet_mask?, router?, dns?}`, `network.hostname.get`, `network.hostname.set {local_host_name?}`, `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}` |@@ -299,6 +299,29 @@ and whenever the settings change. SpringBoard reads the key when it starts, soa newly written one holds from the next boot or respring. Measurements:`Research/Guest/lock_screen_idle_timer.md`.+`network.ipv4.get` and `network.ipv4.set` read and write the IPv4 settings of+one interface (default `en0`) in configd's network preferences,+`/var/preferences/SystemConfiguration/preferences.plist`, through SCPreferences+resolved with `dlsym` (`VPhoneDaemon/Native/vphoned_network.m`). Both return+`{interface, service, method, managed, address?, subnet_mask?, router?, dns}`;+`set` adds `changed`. `set` with `method: "manual"` needs `address`,+`subnet_mask` and `router`, and takes `dns` as an array; it commits and applies+the preferences, so the address changes at once and survives a reboot. A+manual configuration vphoned writes is marked `VPhoneManaged` in the service's+`IPv4` and `DNS` dictionaries. `method: "dhcp"` undoes only a marked one; an+address the user set in the guest's own Settings is left alone and reported+with `changed: false`. `vphone-vm` calls `set` after every connect with the+setting its network plan derived from the VM's `config.plist`+(`VPhoneNetworking.plan`), so the guest is held to that address.++`network.hostname.get` and `network.hostname.set` read and write the guest's+mDNS name, `System/Network/HostNames/LocalHostName` in the same preferences;+both return `{local_host_name, managed}`, and `set` adds `changed`. `set` with a+`local_host_name` (one DNS label) replaces the name and records the one it+replaced; `set` with none or null puts that one back. A name vphoned did not set+is never changed by a null. `vphone-vm` calls `set` after every connect with the+VM's `localHostName`, or null when it has none.+`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 LocalOnly, known-unique A record with the@@ -322,7 +345,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_resolve`, `display_auto_lock`) so a host can hide+`app_details`, `system_control`, `file_tools`, `packages`, `environment_update`, `udid_override`, `setup_skip`, `network_ipv4`, `network_hostname`, `network_static_names`, `network_resolve`, `display_auto_lock`) 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 572e0382..3020c2f2 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Device.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Device.swift@@ -1,6 +1,7 @@import Foundationimport IcliKitimport IcliSystem+import VphonedNative// MARK: - Device, Display, Audio, Network@@ -21,6 +22,10 @@ extension GuestAPI {return infocase "device.network":return networkInfo()+ case "network.ipv4.get":+ return try networkIPv4(interface: optionalString(params, "interface") ?? "en0", set: nil)+ case "network.ipv4.set":+ return try networkIPv4(interface: optionalString(params, "interface") ?? "en0", set: params)case "network.resolve":let port = (params["port"] as? NSNumber).map { $0.intValue }let family: Int32 = switch optionalString(params, "family") {@@ -37,6 +42,11 @@ extension GuestAPI {return GuestStaticNames.shared.describe()case "network.static_names.set":return try GuestStaticNames.shared.set(params["entries"] as? [[String: Any]] ?? [])+ case "network.hostname.get":+ return try networkHostName(set: nil)+ case "network.hostname.set":+ // An absent or null name puts back the one vphoned replaced.+ return try networkHostName(set: .some(params["local_host_name"] as? String))case "device.ioreg":return try ioregistry(plane: optionalString(params, "plane") ?? "IOService")case "device.environment":@@ -120,6 +130,41 @@ extension GuestAPI {}}+// MARK: - Network configuration++extension GuestAPI {+ /// Read, or with `set` write, the interface's IPv4 settings in configd's+ /// network preferences. The host calls `set` after every connect to hold+ /// the guest to the address in its manifest.+ static func networkIPv4(interface: String, set params: [String: Any]?) throws -> [String: Any] {+ var error: NSString?+ let result = if let params {+ vp_network_ipv4_set(interface, params, &error)+ } else {+ vp_network_ipv4_get(interface, &error)+ }+ guard let result = result as? [String: Any] else {+ throw GuestAPIError.operationFailed(error.map(String.init) ?? "network configuration failed")+ }+ return result+ }++ /// Read the guest's mDNS name, or with `set` change it (`.some(nil)` puts+ /// back the one vphoned replaced).+ static func networkHostName(set name: String??) throws -> [String: Any] {+ var error: NSString?+ let result = if let name {+ vp_network_hostname_set(name, &error)+ } else {+ vp_network_hostname_get(&error)+ }+ guard let result = result as? [String: Any] else {+ throw GuestAPIError.operationFailed(error.map(String.init) ?? "host name change failed")+ }+ return result+ }+}+// MARK: - Name resolutionextension GuestAPI {diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex 22399e74..e8b420ac 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -41,14 +41,20 @@ enum GuestAPI {}/// The address the host shows for the guest, from icli's- /// `"<interface> <address>"` strings: a 192.x IPv4 address (the NAT- /// network), then any other routable IPv4, then a routable IPv6. Loopback- /// and link-local addresses, which sort first, never qualify.+ /// `"<interface> <address>"` strings: the NIC's (`en0`) IPv4 address,+ /// which is where the host forwards ports to, then a 192.x IPv4 address+ /// (the NAT network), then any other routable IPv4, then a routable IPv6.+ /// Loopback and link-local addresses, which sort first, never qualify.static func preferredAddress(_ addresses: [String]) -> String? {- let hosts = addresses.compactMap { $0.split(separator: " ", maxSplits: 1).last.map(String.init) }- let ipv4 = hosts.filter { !$0.contains(":") && !$0.hasPrefix("127.") && !$0.hasPrefix("169.254.") }+ func routableIPv4(_ host: String) -> Bool {+ !host.contains(":") && !host.hasPrefix("127.") && !host.hasPrefix("169.254.")+ }+ let entries = addresses.map { $0.split(separator: " ", maxSplits: 1).map(String.init) }+ let nic = entries.first { $0.count == 2 && $0[0] == "en0" && routableIPv4($0[1]) }?[1]+ let hosts = entries.compactMap(\.last)+ let ipv4 = hosts.filter(routableIPv4)let ipv6 = hosts.filter { $0.contains(":") && $0 != "::1" && !$0.contains("%") && !$0.hasPrefix("fe80:") }- return ipv4.first { $0.hasPrefix("192.") } ?? ipv4.first ?? ipv6.first+ return nic ?? ipv4.first { $0.hasPrefix("192.") } ?? ipv4.first ?? ipv6.first}static func health() -> [String: Any] {@@ -98,6 +104,8 @@ enum GuestAPI {"environment_update","udid_override","setup_skip",+ "network_ipv4",+ "network_hostname","network_static_names","network_resolve",],diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex b28566b1..906aec95 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -51,4 +51,23 @@ 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);++/// `interface`'s IPv4 settings in configd's network preferences: `method`+/// (dhcp or manual), `address`, `subnet_mask`, `router`, `dns`, and `managed`+/// when vphoned wrote them. Nil with `*error` set when there is no such service.+NSDictionary *vp_network_ipv4_get(NSString *interface, NSString **error);++/// Set `interface` to `params` (`method` dhcp, or manual with `address`,+/// `subnet_mask`, `router` and `dns`), commit and apply. DHCP only undoes a+/// manual setting vphoned made. Returns the result of `vp_network_ipv4_get`+/// plus `changed`.+NSDictionary *vp_network_ipv4_set(NSString *interface, NSDictionary *params, NSString **error);++/// The guest's mDNS name (`local_host_name`, null when unset) and whether+/// vphoned set it (`managed`).+NSDictionary *vp_network_hostname_get(NSString **error);++/// Set the mDNS name, or with nil put back the one vphoned replaced. Only a+/// name vphoned set is ever undone. Returns the get result plus `changed`.+NSDictionary *vp_network_hostname_set(NSString *name, NSString **error);#endifdiff --git a/VPhoneDaemon/Native/vphoned_network.m b/VPhoneDaemon/Native/vphoned_network.mnew file mode 100644index 00000000..de71b1f6--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_network.m@@ -0,0 +1,322 @@+/*+ * The guest NIC's IPv4 configuration, read and written through configd's+ * network preferences (/var/preferences/SystemConfiguration/preferences.plist).+ *+ * iOS ships SCPreferences but its SDK marks the calls unavailable, so every+ * entry point is resolved with dlsym, as vphoned_touch.m does for IOKit.+ * Writing needs com.apple.SystemConfiguration.SCPreferences-write-access,+ * which vphoned already carries.+ *+ * A manual configuration written here is marked with kManagedKey. Only a+ * marked one is ever turned back into DHCP, so an address the user typed in+ * the guest's own Settings survives a host that asks for DHCP.+ */++#import <Foundation/Foundation.h>+#import <SystemConfiguration/SystemConfiguration.h>+#include <dlfcn.h>+#include <arpa/inet.h>++#import "VphonedNative.h"++static NSString *const kManagedKey = @"VPhoneManaged";++typedef SCPreferencesRef (*CreateFn)(CFAllocatorRef, CFStringRef, CFStringRef);+typedef Boolean (*LockFn)(SCPreferencesRef, Boolean);+typedef Boolean (*PrefsFn)(SCPreferencesRef);+typedef CFPropertyListRef (*GetValueFn)(SCPreferencesRef, CFStringRef);+typedef Boolean (*SetValueFn)(SCPreferencesRef, CFStringRef, CFPropertyListRef);+typedef int (*ErrorFn)(void);++static CreateFn pCreate;+static LockFn pLock;+static PrefsFn pUnlock, pCommit, pApply;+static GetValueFn pGetValue;+static SetValueFn pSetValue;+static ErrorFn pError;++static BOOL vp_network_load(NSString **error) {+ static BOOL loaded;+ static dispatch_once_t once;+ dispatch_once(&once, ^{+ void *sc = dlopen("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration", RTLD_NOW);+ if (!sc) return;+ pCreate = (CreateFn)dlsym(sc, "SCPreferencesCreate");+ pLock = (LockFn)dlsym(sc, "SCPreferencesLock");+ pUnlock = (PrefsFn)dlsym(sc, "SCPreferencesUnlock");+ pCommit = (PrefsFn)dlsym(sc, "SCPreferencesCommitChanges");+ pApply = (PrefsFn)dlsym(sc, "SCPreferencesApplyChanges");+ pGetValue = (GetValueFn)dlsym(sc, "SCPreferencesGetValue");+ pSetValue = (SetValueFn)dlsym(sc, "SCPreferencesSetValue");+ pError = (ErrorFn)dlsym(sc, "SCError");+ loaded = pCreate && pLock && pUnlock && pCommit && pApply && pGetValue && pSetValue && pError;+ });+ if (!loaded && error) *error = @"SCPreferences is not available on this guest";+ return loaded;+}++static NSString *vp_sc_error(NSString *step) {+ return [NSString stringWithFormat:@"%@ failed (SCError %d)", step, pError ? pError() : -1];+}++/// The service ID whose interface is `interface`, from a NetworkServices dict.+static NSString *vp_service_for_interface(NSDictionary *services, NSString *interface) {+ for (NSString *serviceID in services) {+ NSDictionary *service = services[serviceID];+ if (![service isKindOfClass:NSDictionary.class]) continue;+ NSDictionary *iface = service[@"Interface"];+ if ([iface isKindOfClass:NSDictionary.class] && [iface[@"DeviceName"] isEqual:interface]) {+ return serviceID;+ }+ }+ return nil;+}++static NSDictionary *vp_describe(NSString *interface, NSString *serviceID, NSDictionary *service) {+ NSDictionary *ipv4 = [service[@"IPv4"] isKindOfClass:NSDictionary.class] ? service[@"IPv4"] : @{};+ NSDictionary *dns = [service[@"DNS"] isKindOfClass:NSDictionary.class] ? service[@"DNS"] : @{};+ NSString *method = ipv4[@"ConfigMethod"] ?: @"";+ NSMutableDictionary *out = [@{+ @"interface": interface,+ @"service": serviceID,+ @"method": [method isEqualToString:@"Manual"] ? @"manual" : ([method isEqualToString:@"DHCP"] ? @"dhcp" : method),+ @"managed": @([ipv4[kManagedKey] boolValue]),+ } mutableCopy];+ NSArray *addresses = ipv4[@"Addresses"];+ NSArray *masks = ipv4[@"SubnetMasks"];+ if ([addresses isKindOfClass:NSArray.class] && addresses.count) out[@"address"] = addresses.firstObject;+ if ([masks isKindOfClass:NSArray.class] && masks.count) out[@"subnet_mask"] = masks.firstObject;+ if ([ipv4[@"Router"] isKindOfClass:NSString.class]) out[@"router"] = ipv4[@"Router"];+ NSArray *servers = dns[@"ServerAddresses"];+ out[@"dns"] = [servers isKindOfClass:NSArray.class] ? servers : @[];+ return out;+}++static BOOL vp_is_ipv4(id value) {+ struct in_addr parsed;+ return [value isKindOfClass:NSString.class] && inet_pton(AF_INET, [value UTF8String], &parsed) == 1;+}++NSDictionary *vp_network_ipv4_get(NSString *interface, NSString **error) {+ if (!vp_network_load(error)) return nil;+ SCPreferencesRef prefs = pCreate(NULL, CFSTR("vphoned"), NULL);+ if (!prefs) {+ if (error) *error = vp_sc_error(@"SCPreferencesCreate");+ return nil;+ }+ NSDictionary *services = (__bridge NSDictionary *)pGetValue(prefs, CFSTR("NetworkServices"));+ NSString *serviceID = [services isKindOfClass:NSDictionary.class] ? vp_service_for_interface(services, interface) : nil;+ NSDictionary *result = nil;+ if (serviceID) {+ result = vp_describe(interface, serviceID, services[serviceID]);+ } else if (error) {+ *error = [NSString stringWithFormat:@"no network service for %@", interface];+ }+ CFRelease(prefs);+ return result;+}++NSDictionary *vp_network_ipv4_set(NSString *interface, NSDictionary *params, NSString **error) {+ if (!vp_network_load(error)) return nil;++ NSString *method = params[@"method"];+ BOOL manual = [method isEqual:@"manual"];+ if (!manual && ![method isEqual:@"dhcp"]) {+ if (error) *error = @"method must be manual or dhcp";+ return nil;+ }+ NSArray *dns = params[@"dns"] ?: @[];+ if (manual) {+ BOOL dnsValid = [dns isKindOfClass:NSArray.class];+ for (id server in dnsValid ? dns : @[]) dnsValid = dnsValid && vp_is_ipv4(server);+ if (!vp_is_ipv4(params[@"address"]) || !vp_is_ipv4(params[@"subnet_mask"]) || !vp_is_ipv4(params[@"router"]) || !dnsValid) {+ if (error) *error = @"manual needs address, subnet_mask, router and dns as dotted IPv4 addresses";+ return nil;+ }+ }++ SCPreferencesRef prefs = pCreate(NULL, CFSTR("vphoned"), NULL);+ if (!prefs) {+ if (error) *error = vp_sc_error(@"SCPreferencesCreate");+ return nil;+ }+ if (!pLock(prefs, true)) {+ if (error) *error = vp_sc_error(@"SCPreferencesLock");+ CFRelease(prefs);+ return nil;+ }++ NSDictionary *result = nil;+ NSDictionary *services = (__bridge NSDictionary *)pGetValue(prefs, CFSTR("NetworkServices"));+ NSString *serviceID = [services isKindOfClass:NSDictionary.class] ? vp_service_for_interface(services, interface) : nil;+ if (!serviceID) {+ if (error) *error = [NSString stringWithFormat:@"no network service for %@", interface];+ goto done;+ }++ {+ NSDictionary *service = services[serviceID];+ NSDictionary *oldIPv4 = [service[@"IPv4"] isKindOfClass:NSDictionary.class] ? service[@"IPv4"] : @{};+ NSDictionary *oldDNS = [service[@"DNS"] isKindOfClass:NSDictionary.class] ? service[@"DNS"] : @{};+ BOOL managed = [oldIPv4[kManagedKey] boolValue];++ NSDictionary *ipv4;+ NSDictionary *dnsEntry;+ if (manual) {+ ipv4 = @{+ @"ConfigMethod": @"Manual",+ @"Addresses": @[params[@"address"]],+ @"SubnetMasks": @[params[@"subnet_mask"]],+ @"Router": params[@"router"],+ kManagedKey: @YES,+ };+ dnsEntry = dns.count ? @{@"ServerAddresses": dns, kManagedKey: @YES} : @{};+ } else if (managed) {+ ipv4 = @{@"ConfigMethod": @"DHCP"};+ dnsEntry = [oldDNS[kManagedKey] boolValue] ? @{} : oldDNS;+ } else {+ // DHCP asked for, and nothing of ours to undo.+ ipv4 = oldIPv4;+ dnsEntry = oldDNS;+ }++ BOOL changed = ![ipv4 isEqualToDictionary:oldIPv4] || ![dnsEntry isEqualToDictionary:oldDNS];+ if (changed) {+ NSMutableDictionary *newService = [service mutableCopy];+ newService[@"IPv4"] = ipv4;+ newService[@"DNS"] = dnsEntry;+ NSMutableDictionary *newServices = [services mutableCopy];+ newServices[serviceID] = newService;+ if (!pSetValue(prefs, CFSTR("NetworkServices"), (__bridge CFDictionaryRef)newServices)) {+ if (error) *error = vp_sc_error(@"SCPreferencesSetValue");+ goto done;+ }+ if (!pCommit(prefs)) {+ if (error) *error = vp_sc_error(@"SCPreferencesCommitChanges");+ goto done;+ }+ if (!pApply(prefs)) {+ if (error) *error = vp_sc_error(@"SCPreferencesApplyChanges");+ goto done;+ }+ }+ NSMutableDictionary *described = [vp_describe(interface, serviceID, @{@"IPv4": ipv4, @"DNS": dnsEntry}) mutableCopy];+ described[@"changed"] = @(changed);+ result = described;+ }++done:+ pUnlock(prefs);+ CFRelease(prefs);+ return result;+}++/*+ * The guest's mDNS name, System/Network/HostNames/LocalHostName in the same+ * preferences. mDNSResponder announces it as <name>.local. The name in place+ * before vphoned first set one is kept under kOriginalNameKey, so turning the+ * feature off puts it back, and only a name vphoned set is ever undone.+ */++static NSString *const kOriginalNameKey = @"VPhoneOriginalLocalHostName";++static NSDictionary *vp_host_names(SCPreferencesRef prefs) {+ NSDictionary *system = (__bridge NSDictionary *)pGetValue(prefs, CFSTR("System"));+ NSDictionary *network = [system isKindOfClass:NSDictionary.class] ? system[@"Network"] : nil;+ NSDictionary *names = [network isKindOfClass:NSDictionary.class] ? network[@"HostNames"] : nil;+ return [names isKindOfClass:NSDictionary.class] ? names : @{};+}++static NSDictionary *vp_describe_host_names(NSDictionary *names) {+ NSString *name = names[@"LocalHostName"];+ return @{+ @"local_host_name": [name isKindOfClass:NSString.class] ? name : NSNull.null,+ @"managed": names[kOriginalNameKey] != nil ? @YES : @NO,+ };+}++static BOOL vp_is_host_label(NSString *name) {+ if (name.length < 1 || name.length > 63 || [name hasPrefix:@"-"] || [name hasSuffix:@"-"]) return NO;+ NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:+ @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"];+ return [name rangeOfCharacterFromSet:allowed.invertedSet].location == NSNotFound;+}++NSDictionary *vp_network_hostname_get(NSString **error) {+ if (!vp_network_load(error)) return nil;+ SCPreferencesRef prefs = pCreate(NULL, CFSTR("vphoned"), NULL);+ if (!prefs) {+ if (error) *error = vp_sc_error(@"SCPreferencesCreate");+ return nil;+ }+ NSDictionary *result = vp_describe_host_names(vp_host_names(prefs));+ CFRelease(prefs);+ return result;+}++NSDictionary *vp_network_hostname_set(NSString *name, NSString **error) {+ if (!vp_network_load(error)) return nil;+ if (name && !vp_is_host_label(name)) {+ if (error) *error = @"local_host_name must be 1-63 letters, digits and hyphens";+ return nil;+ }+ SCPreferencesRef prefs = pCreate(NULL, CFSTR("vphoned"), NULL);+ if (!prefs) {+ if (error) *error = vp_sc_error(@"SCPreferencesCreate");+ return nil;+ }+ if (!pLock(prefs, true)) {+ if (error) *error = vp_sc_error(@"SCPreferencesLock");+ CFRelease(prefs);+ return nil;+ }++ NSDictionary *result = nil;+ NSDictionary *old = vp_host_names(prefs);+ NSMutableDictionary *names = [old mutableCopy];+ BOOL managed = names[kOriginalNameKey] != nil;+ if (name) {+ if (!managed) names[kOriginalNameKey] = names[@"LocalHostName"] ?: @"";+ names[@"LocalHostName"] = name;+ } else if (managed) {+ NSString *original = names[kOriginalNameKey];+ if ([original isKindOfClass:NSString.class] && original.length) {+ names[@"LocalHostName"] = original;+ } else {+ [names removeObjectForKey:@"LocalHostName"];+ }+ [names removeObjectForKey:kOriginalNameKey];+ }++ BOOL changed = ![names isEqualToDictionary:old];+ if (changed) {+ NSDictionary *oldSystem = (__bridge NSDictionary *)pGetValue(prefs, CFSTR("System"));+ NSMutableDictionary *system = [oldSystem isKindOfClass:NSDictionary.class] ? [oldSystem mutableCopy] : [NSMutableDictionary dictionary];+ NSMutableDictionary *network = [system[@"Network"] isKindOfClass:NSDictionary.class] ? [system[@"Network"] mutableCopy] : [NSMutableDictionary dictionary];+ network[@"HostNames"] = names;+ system[@"Network"] = network;+ if (!pSetValue(prefs, CFSTR("System"), (__bridge CFDictionaryRef)system)) {+ if (error) *error = vp_sc_error(@"SCPreferencesSetValue");+ goto done;+ }+ if (!pCommit(prefs)) {+ if (error) *error = vp_sc_error(@"SCPreferencesCommitChanges");+ goto done;+ }+ if (!pApply(prefs)) {+ if (error) *error = vp_sc_error(@"SCPreferencesApplyChanges");+ goto done;+ }+ }+ {+ NSMutableDictionary *described = [vp_describe_host_names(names) mutableCopy];+ described[@"changed"] = @(changed);+ result = described;+ }++done:+ pUnlock(prefs);+ CFRelease(prefs);+ return result;+}+diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swiftindex a0100dfd..a610fe36 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Host/VPhoneHostAutomationProbe.swift@@ -1,13 +1,20 @@import Darwinimport Foundation-/// Ask the GUI VM's local control socket to perform a real vphoned ping.-/// `vm create` uses this instead of parsing the VM process's buffered stdout.+/// Requests to a running VM's control socket, `vphone.sock`. `vm create` pings+/// through it instead of parsing the VM process's buffered stdout, and+/// `vm network` drives the NIC through it.enum VPhoneHostAutomationProbe {static func ping(socketPath: String) -> Bool {+ send(["t": "ping", "screen": false], socketPath: socketPath)?["ok"] as? Bool == true+ }++ /// One request, one reply line. Nil when the socket is not there or the+ /// reply is not JSON.+ static func send(_ request: [String: Any], socketPath: String, timeout seconds: Int = 2) -> [String: Any]? {let path = socketPath.utf8CStringvar address = sockaddr_un()- guard path.count <= MemoryLayout.size(ofValue: address.sun_path) else { return false }+ guard path.count <= MemoryLayout.size(ofValue: address.sun_path) else { return nil }address.sun_family = sa_family_t(AF_UNIX)withUnsafeMutablePointer(to: &address.sun_path) { pointer inpointer.withMemoryRebound(to: CChar.self, capacity: path.count) { destination in@@ -18,10 +25,10 @@ enum VPhoneHostAutomationProbe {}let fd = socket(AF_UNIX, SOCK_STREAM, 0)- guard fd >= 0 else { return false }+ guard fd >= 0 else { return nil }defer { close(fd) }- var timeout = timeval(tv_sec: 2, tv_usec: 0)+ var timeout = timeval(tv_sec: seconds, tv_usec: 0)_ = withUnsafePointer(to: &timeout) {setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, $0, socklen_t(MemoryLayout<timeval>.size))}@@ -34,28 +41,29 @@ enum VPhoneHostAutomationProbe {connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size))}}- guard connected == 0 else { return false }-- let request = Data("{\"t\":\"ping\",\"screen\":false}\n".utf8)+ guard connected == 0,+ var request = try? JSONSerialization.data(withJSONObject: request)+ else { return nil }+ request.append(0x0A)let written = request.withUnsafeBytes { bytes inDarwin.write(fd, bytes.baseAddress, bytes.count)}- guard written == request.count else { return false }+ guard written == request.count else { return nil }var reply = Data()var buffer = [UInt8](repeating: 0, count: 512)- while reply.count < 4096 {+ while reply.count < 1 << 20 {let count = buffer.withUnsafeMutableBytes { bytes inDarwin.read(fd, bytes.baseAddress, bytes.count)}- guard count > 0 else { return false }+ guard count > 0 else { return nil }reply.append(contentsOf: buffer.prefix(count))if let newline = reply.firstIndex(of: 0x0A),let json = try? JSONSerialization.jsonObject(with: Data(reply[..<newline])) as? [String: Any]{- return json["ok"] as? Bool == true+ return json}}- return false+ return nil}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swiftindex c31ec17c..884b238f 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift@@ -13,6 +13,7 @@ struct VPhoneVirtualMachineCommand: ParsableCommand {VPhoneVirtualMachineInfoCommand.self,VPhoneVirtualMachineNewCommand.self,VPhoneVirtualMachineConfigCommand.self,+ VPhoneVirtualMachineNetworkCommand.self,VPhoneVirtualMachineRenameCommand.self,VPhoneVirtualMachineDeleteCommand.self,VPhoneVirtualMachineCloneCommand.self,@@ -207,6 +208,20 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {commandName: "config",abstract: "Edit VM manifest fields (cpu/memory/network)",discussion: """+ Network settings are read when the VM starts, so a change applies from the next launch.++ --ip fixes the guest's address. In nat mode it must be on the Mac's shared NAT network \+ (usually 192.168.64.0/24), and vphoned writes it into the guest. In tunnel mode, any \+ private subnet, handed out by the VM's own DHCP. In bridged mode vphoned writes it into \+ the guest, so give --gateway and --dns for the LAN.++ --forward carries a host port into the guest (nat and tunnel): tcp:8022:22 listens on \+ 127.0.0.1:8022, tcp:0.0.0.0:8022:22 on every address. Repeat it for more ports.++ --mdns on makes the guest answer to <vm-name>.local over mDNS (or --mdns <name> for \+ another name), in every network mode: the guest also announces it over its USB link to \+ this Mac. --mdns off puts the guest's own name back.+--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; \@@ -222,26 +237,34 @@ 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: "Guest NIC MAC address: aa:bb:cc:dd:ee:ff | random | auto (a new one at next boot)")+ var mac: String?+ @Option(name: .long, help: "Fixed guest IPv4 address, address[/prefix] (default /24), or dhcp")+ var ip: String?+ @Option(name: .long, help: "Guest default gateway with a fixed address, or auto")+ var gateway: String?+ @Option(name: .long, help: "Guest DNS servers with a fixed address, comma separated, or auto")+ var dns: String?+ @Option(name: .long, help: "Forward a host port: [tcp|udp:][host-address:]host-port:guest-port (repeatable)")+ var forward: [String] = []+ @Option(name: .long, help: "Remove a forward, as vm info lists it or by host port (repeatable)")+ var removeForward: [String] = []+ @Flag(name: .long, help: "Remove every port forward")+ var clearForwards = false+ @Option(name: .long, help: "mDNS name: on (<vm-name>.local), off, or a name")+ var mdns: 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 edit = try networkEdit(vmName: name)let updated = try VPhoneBundleOperations.updateConfig(bundleNamed: name,in: lib.library,cpuCount: cpu,memoryMB: memory,- networkMode: mode,- bridgeInterface: bridgeInterface,- resolvesMacName: resolvesMacName,+ networkEdit: edit,)let m = updated.manifestprint(@@ -250,6 +273,53 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {)}+ private func networkEdit(vmName: String) throws -> VPhoneNetworkEdit {+ var edit = VPhoneNetworkEdit(+ mode: try network.map(Self.parseMode),+ bridgeInterface: bridgeInterface,+ removeForwards: removeForward,+ clearForwards: clearForwards,+ )+ switch mac?.lowercased() {+ case nil: break+ case "auto": edit.mac = .automatic+ case "random": edit.mac = .random+ case let value?: edit.mac = .fixed(value)+ }+ if let ip {+ if ip.lowercased() == "dhcp" {+ edit.address = .dhcp+ } else {+ let parsed = try VPhoneNetworking.parseAddress(ip)+ edit.address = .fixed(address: parsed.address, prefixLength: parsed.prefixLength)+ }+ }+ if let gateway {+ edit.router = .some(gateway.lowercased() == "auto" ? nil : gateway)+ }+ if let dns {+ edit.dns = .some(+ dns.lowercased() == "auto"+ ? nil+ : dns.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) },+ )+ }+ edit.addForwards = try forward.map(VPhoneNetworking.parsePortForward)+ switch macName?.lowercased() {+ case nil: break+ case "on": edit.resolvesMacName = true+ case "off": edit.resolvesMacName = false+ default: throw ValidationError("--mac-name takes on or off.")+ }+ switch mdns?.lowercased() {+ case nil: break+ case "off": edit.localHostName = .some(nil)+ case "on": edit.localHostName = .some(VPhoneNetworking.localHostName(forVMName: vmName))+ default: edit.localHostName = .some(mdns)+ }+ return edit+ }+private static func parseMode(_ s: String)throws -> VPhoneVirtualMachineManifest.NetworkConfig.NetworkMode{@@ -266,15 +336,32 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {}}-private func describeNetwork(_ net: VPhoneVirtualMachineManifest.NetworkConfig) -> String {- var text = net.mode.rawValue- if net.mode == .bridged, let iface = net.bridgeInterface {- text += "(\(iface))"+/// One line: mode, then whatever is set beyond it.+func describeNetwork(_ net: VPhoneVirtualMachineManifest.NetworkConfig) -> String {+ var parts = [net.mode == .bridged ? "bridged(\(net.bridgeInterface ?? "?"))" : net.mode.rawValue]+ if !net.macAddress.isEmpty {+ parts.append("mac \(net.macAddress)")+ }+ if let ipv4 = net.ipv4 {+ var address = "ip \(ipv4.address)/\(ipv4.prefixLength)"+ if let router = ipv4.router {+ address += " gw \(router)"+ }+ if let dns = ipv4.dns, !dns.isEmpty {+ address += " dns \(dns.joined(separator: ","))"+ }+ parts.append(address)+ }+ if let forwards = net.portForwards, !forwards.isEmpty {+ parts.append("forward \(forwards.map(\.description).joined(separator: " "))")+ }+ if let name = net.localHostName {+ parts.append("mdns \(name).local")}if net.resolvesMacName == false {- text += ", mac-name off"+ parts.append("mac-name off")}- return text+ return parts.joined(separator: ", ")}// MARK: - renamediff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineNetworkCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineNetworkCommand.swiftnew file mode 100644index 00000000..85cdb088--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineNetworkCommand.swift@@ -0,0 +1,67 @@+import ArgumentParser+import Foundation+import VPhoneCoreKit++// MARK: - network++/// The NIC of a running VM: show it, or unplug and replug it. Nothing here is+/// saved; `vm config` changes what the next launch uses, and moving to another+/// network needs a restart (see `VPhoneVirtualMachine.setNetworkLink`).+struct VPhoneVirtualMachineNetworkCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "network",+ abstract: "Show a running VM's network link, or unplug and replug it",+ discussion: """+ Without options, prints the NIC's state. --link down unplugs the guest's cable and \+ --link up plugs it back in; the guest sees the link drop and come back. Nothing is \+ saved. To move the VM to another network, change it with vm config and restart it.+ """,+ )++ @OptionGroup var lib: VPhoneLibraryOption+ @Argument(help: "VM name") var name: String?+ @Option(name: .long, help: "up | down") var link: String?+ @Flag(name: .shortAndLong, help: "Emit JSON") var json = false++ func run() throws {+ if let link, link != "up", link != "down" {+ throw ValidationError("--link must be up or down.")+ }+ let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)+ let bundle = try lib.library.bundle(named: name)+ let socketPath = bundle.url.appendingPathComponent("vphone.sock").path++ var request: [String: Any] = ["t": "network"]+ request["link"] = link+ guard let reply = VPhoneHostAutomationProbe.send(request, socketPath: socketPath, timeout: 10) else {+ throw ValidationError("\(name) is not running, or its control socket does not answer. Start it with vm launch.")+ }+ guard reply["ok"] as? Bool == true, let status = reply["result"] as? [String: Any] else {+ throw ValidationError(reply["error"] as? String ?? "the VM refused the request")+ }++ if json {+ let data = try JSONSerialization.data(withJSONObject: status, options: [.prettyPrinted, .sortedKeys])+ print(String(decoding: data, as: UTF8.self))+ return+ }+ guard status["device"] as? Bool == true else {+ print("\(name): no network device")+ return+ }+ print("link: \(status["link"] as? String ?? "?")")+ print("attached: \(status["attachment"] as? String ?? "?")")+ if let configured = status["configured"] as? String {+ print("configured: \(configured)")+ }+ if let guest = status["guest_ipv4"] as? String, !guest.isEmpty {+ print("guest: \(guest)")+ }+ for forward in status["forwards"] as? [String] ?? [] {+ print("forward: \(forward)")+ }+ if let name = status["local_host_name"] as? String, !name.isEmpty {+ print("mdns: \(name)")+ }+ }+}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 48cdc69a..bfe48a8a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -47,10 +47,18 @@ 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.+ /// What en0 should be configured as, from the manifest. Applied on every+ /// connect, so a guest that was changed while the host was away is put back.+ @ObservationIgnored var guestIPv4Setting: VPhoneGuestIPv4Setting?+ /// The guest's mDNS name from the manifest, applied on every connect; nil+ /// puts back a name vphoned replaced, and leaves any other alone.+ @ObservationIgnored var guestLocalHostName: String?+ /// Names the guest resolves locally, worked out on each connect (the Mac's+ /// name or a bridged address can change while the VM runs). Nil sends+ /// nothing.@ObservationIgnored var guestStaticNames: (() -> [VPhoneNetworking.StaticName])?+ /// Called whenever the address the guest reports changes, nil on disconnect.+ @ObservationIgnored var onGuestIPAddressChange: ((String?) -> Void)?/// 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@@ -177,6 +185,7 @@ final class VPhoneGuestControl {let ip = info["ip"] as? Stringif ip != guestIPAddress {guestIPAddress = ip+ onGuestIPAddressChange?(ip)}let ios = info["ios"] as? Stringif ios != guestIOSVersion {@@ -193,8 +202,14 @@ 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_ipv4"), let setting = guestIPv4Setting {+ Task { await applyGuestIPv4(setting) }+ }+ if capabilities.contains("network_hostname") {+ Task { await applyGuestLocalHostName(guestLocalHostName) }+ }+ if capabilities.contains("network_static_names"), let entries = guestStaticNames?() {+ Task { await applyGuestStaticNames(entries) }}}} catch {@@ -212,6 +227,7 @@ final class VPhoneGuestControl {isConnected = falseguestCapabilities = []guestIPAddress = nil+ onGuestIPAddressChange?(nil)guestIOSVersion = nilinterfaceOrientation = nilisSetupAssistantPending = false@@ -821,16 +837,46 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {}}-// MARK: - The Mac's name+// MARK: - Network++extension VPhoneGuestControl {+ /// Hold en0 to `setting`. vphoned leaves a configuration the user made in+ /// the guest alone when asked for DHCP, so this only ever undoes its own.+ func applyGuestIPv4(_ setting: VPhoneGuestIPv4Setting) async {+ do {+ let result = try await call("network.ipv4.set", params: setting.parameters)+ if result["changed"] as? Bool == true {+ print("[network] guest en0 set to \(setting)")+ }+ } catch {+ print("[network] could not set guest en0 to \(setting): \(error)")+ }+ }+}++extension VPhoneGuestControl {+ /// Hold the guest's mDNS name to `name`, or with nil put back the name+ /// vphoned replaced. A name the user set in the guest is never touched.+ func applyGuestLocalHostName(_ name: String?) async {+ do {+ let result = try await call("network.hostname.set", params: ["local_host_name": name ?? NSNull()])+ if result["changed"] as? Bool == true {+ print("[network] guest mDNS name \(name.map { "set to \($0).local" } ?? "restored")")+ }+ } catch {+ print("[network] could not set the guest's mDNS name: \(error)")+ }+ }+}extension VPhoneGuestControl {/// Replace the names vphoned has the guest resolve locally; an empty list/// withdraws them.- func applyGuestStaticNames(_ names: [VPhoneNetworking.StaticName]) async {+ func applyGuestStaticNames(_ entries: [VPhoneNetworking.StaticName]) async {do {- let result = try await call("network.static_names.set", params: ["entries": names.map(\.parameters)])+ let result = try await call("network.static_names.set", params: ["entries": entries.map(\.parameters)])if result["changed"] as? Bool == true {- let lines = names.map { "\($0.names.joined(separator: " ")) -> \($0.address)" }+ let lines = entries.map { "\($0.address) \($0.names.joined(separator: " "))" }print("[network] guest resolves \(lines.isEmpty ? "no names locally" : lines.joined(separator: ", "))")}} catch {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swiftindex f3ea2b46..0a613f0e 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneHostAutomationServer.swift@@ -34,6 +34,8 @@ import ImageIO/// {"t":"ping"} → vphoned request/response/// {"t":"rpc","method":"input.type","params":{"text":"ls\n"}}/// → any vphoned method; its result is in `"result"`+/// {"t":"network"} → the NIC's state, in `"result"`+/// {"t":"network","link":"down"} → unplug (`up` replugs); not saved////// All commands except "screenshot" and "rpc" wait briefly then capture a/// compact screen image returned as `"image":"<base64>"` in the response.@@ -64,6 +66,8 @@ class VPhoneHostAutomationServer {private weak var captureView: VPhoneVirtualMachineView?private var screenRecorder = VPhoneScreenRecorder()private weak var control: VPhoneGuestControl?+ /// For the `network` command; nil until the VM exists.+ weak var virtualMachine: VPhoneVirtualMachine?/// Matches vphoned's JSON body limit, so an `rpc` line is never refused/// here that the guest would accept.@@ -237,6 +241,18 @@ class VPhoneHostAutomationServer {let image = wantRPCScreen ? await settledCompactScreenshot(delayMs: screenDelay) : nilreturn Self.reply(ok: true, image: image, result: result)+ case "network":+ guard let virtualMachine else {+ return Self.reply(ok: false, error: "the VM is not running")+ }+ if let link = json["link"] as? String {+ guard link == "up" || link == "down" else {+ return Self.reply(ok: false, error: "link must be up or down")+ }+ try virtualMachine.setNetworkLink(up: link == "up")+ }+ return Self.reply(ok: true, result: virtualMachine.networkStatus)+default:return Self.reply(ok: false, error: "unknown command: \(type)")}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex fd30390a..6ae5f4d0 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -16,6 +16,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {private var hostAutomationServer: VPhoneHostAutomationServer?private var cameraServer: VPhoneCameraServer?private var apiProxy: VPhoneAPIProxy?+ private var portForwarder: VPhonePortForwarder?private var sigintSource: DispatchSourceSignal?private var didAttemptAutoInstall = false@@ -87,7 +88,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {let control = VPhoneGuestControl()self.control = controlif !command.dfu {- configureGuestNames(control: control, configURL: options.configURL)+ startNetworkServices(vm: vm, control: control)let vphonedURL = URL(fileURLWithPath: command.vphonedBin)if FileManager.default.fileExists(atPath: vphonedURL.path) {control.guestBinaryURL = vphonedURL@@ -273,27 +274,51 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {screenWidth: options.screenWidth,screenHeight: options.screenHeight,)+ server.virtualMachine = vmhostAutomationServer = server}- /// Have the guest resolve this Mac's `.local` name to the address it- /// reaches the Mac at.+ /// Hold the guest to its configured address and open its forwarded ports.@MainActor- private 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 }+ private func startNetworkServices(vm: VPhoneVirtualMachine, control: VPhoneGuestControl) {+ guard let plan = vm.networkPlan else { return }+ control.guestIPv4Setting = plan.guestIPv4+ control.guestLocalHostName = plan.localHostNamecontrol.guestStaticNames = {- let bridged = network.mode == .bridged- ? network.bridgeInterface.flatMap(VPhoneNetworking.ipv4Address(ofInterface:))- : nil+ let bridged: VPhoneIPv4Address? = if case let .bridged(interface) = plan.attachment {+ VPhoneNetworking.ipv4Address(ofInterface: interface)+ } else {+ nil+ }return VPhoneNetworking.macStaticNames(- network,+ plan: plan,macName: VPhoneNetworking.macLocalHostName(),- sharedNATHost: VPhoneNetworking.sharedNATHostAddress(),bridgedAddress: bridged,)}+ guard !plan.portForwards.isEmpty else { return }++ let destination: VPhonePortForwarder.Destination+ if case .tunnel = plan.attachment, let network = vm.tunnelNetwork {+ destination = .tunnel(network)+ } else {+ destination = .direct(plan.forwardingAddress)+ }+ let forwarder = VPhonePortForwarder(forwards: plan.portForwards, destination: destination)+ for failure in forwarder.start() {+ print("[network] port forward not opened: \(failure)")+ }+ print("[network] forwarding \(plan.portForwards.map(\.description).joined(separator: ", "))")+ // A DHCP guest's address is learned from vphoned, and can change. A+ // dropped connection to vphoned says nothing about the guest's address,+ // so the last one known is kept.+ if case .direct(nil) = destination {+ control.onGuestIPAddressChange = { [weak forwarder] ip in+ guard let address = ip.flatMap(VPhoneIPv4Address.init(dotted:)) else { return }+ forwarder?.updateGuestAddress(address)+ }+ }+ portForwarder = forwarder}@MainActor@@ -334,6 +359,7 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {func applicationWillTerminate(_: Notification) {hostAutomationServer?.stop()+ portForwarder?.stop()apiProxy?.stop()control?.stop()}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swiftindex 0d4b59b2..f1fc9f88 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift@@ -16,6 +16,12 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {/// The in-process network backing `.tunnel` mode; nil for every other mode./// Held because the sockets live only as long as this reference does.private var userspaceNetwork: VPhoneUserspaceNetwork?+ /// How the manifest's network was realized: attachment, MAC, the address+ /// vphoned should hold the guest to, and the ports forwarded into it.+ private(set) var networkPlan: VPhoneNetworkPlan?+ /// The attachment the VM booted with, put back by `setNetworkLink(up: true)`+ /// after a runtime change.+ private var bootAttachment: VZNetworkDeviceAttachment?struct Options {var configURL: URL@@ -83,6 +89,17 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {print("[vphone] \(reason)")}+ // --- MAC: generated once, then kept, like the machine identifier ---+ // A fixed MAC keeps the guest on one DHCP lease and is what a custom+ // NAT network reserves its address for.+ if manifest.networkConfig.mode != .off, manifest.networkConfig.macAddress.isEmpty {+ let mac = VPhoneMACAddress.randomLocallyAdministered()+ manifest = manifest.updating(networkConfig: manifest.networkConfig.with(macAddress: mac.description))+ try manifest.write(to: options.configURL)+ try VPhoneHostFilePermissions.makeAccessible(at: options.configURL)+ print("[vphone] Created MAC address \(mac) -> saved to config.plist")+ }+// --- Platform ---let platform = VZMacPlatformConfiguration()platform.machineIdentifier = machineIdentifier@@ -174,14 +191,13 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {let attachment = try VZDiskImageStorageDeviceAttachment(url: options.diskURL, readOnly: false)config.storageDevices = [VZVirtioBlockDeviceConfiguration(attachment: attachment)]- // Network (mode + MAC from the bundle manifest; nat/bridged/tunnel/none)- let (networkDevice, networkBackend) = try VPhoneNetworking.makeNetworkDevice(manifest.networkConfig)- if let networkDevice {- config.networkDevices = [networkDevice]- } else {- config.networkDevices = []- }- userspaceNetwork = networkBackend+ // Network (mode, MAC, address and forwards from the bundle manifest)+ let plan = try VPhoneNetworking.plan(manifest.networkConfig)+ let network = try VPhoneNetworking.makeNetworkDevice(plan)+ config.networkDevices = network.configuration.map { [$0] } ?? []+ networkPlan = plan+ userspaceNetwork = network.userspaceNetwork+ print("[vphone] Network: \(Self.describe(plan))")// Serial port (PL011 UART - pipes for input/output with boot detection)if let serialPort = Dynamic._VZPL011SerialPortConfiguration().asObject@@ -285,6 +301,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {print("[vphone] Configuration validated")virtualMachine = VZVirtualMachine(configuration: config)+ bootAttachment = virtualMachine.networkDevices.first?.attachmentsuper.init()virtualMachine.delegate = self@@ -361,6 +378,91 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {Dynamic(source).setConnectivity(connectivity)}+ // MARK: - Network++ enum NetworkControlError: Error, CustomStringConvertible {+ case noNetworkDevice++ var description: String {+ "This VM has no network device (network mode none)."+ }+ }++ /// The in-process network when the VM runs in `tunnel` mode.+ var tunnelNetwork: VPhoneUserspaceNetwork? {+ userspaceNetwork+ }++ /// The NIC as it is now, for `vphone.sock`'s `network` command.+ var networkStatus: [String: Any] {+ var status: [String: Any] = [:]+ if let plan = networkPlan {+ status["configured"] = Self.describe(plan)+ status["mac"] = plan.macAddress?.description ?? ""+ status["guest_ipv4"] = plan.guestIPv4?.description ?? ""+ status["forwards"] = plan.portForwards.map(\.description)+ status["local_host_name"] = plan.localHostName.map { "\($0).local" } ?? ""+ }+ guard let device = virtualMachine.networkDevices.first else {+ status["device"] = false+ return status+ }+ status["device"] = true+ status["link"] = device.attachment == nil ? "down" : "up"+ status["attachment"] = Self.describe(device.attachment)+ return status+ }++ /// Unplug or replug the guest's cable without stopping it. Down detaches+ /// the NIC from every network; up puts back the attachment it booted with.+ /// Neither is saved: the next launch reads config.plist again.+ ///+ /// Only that one attachment ever goes back. Handing a running VM a new+ /// attachment, even another `VZNATNetworkDeviceAttachment`, stopped it with+ /// an internal virtualization error (macOS 27 host, iOS 27 guest), so+ /// switching networks needs a restart.+ func setNetworkLink(up: Bool) throws {+ guard let device = virtualMachine.networkDevices.first else {+ throw NetworkControlError.noNetworkDevice+ }+ device.attachment = up ? bootAttachment : nil+ print("[vphone] Network link \(up ? "up" : "down")")+ }+++ static func describe(_ plan: VPhoneNetworkPlan) -> String {+ var parts: [String] = switch plan.attachment {+ case .none: ["none"]+ case .sharedNAT: ["nat"]+ case let .bridged(interface): ["bridged(\(interface))"]+ case let .tunnel(configuration):+ ["tunnel(\(configuration.guestAddress)/\(configuration.prefixLength) via \(configuration.hostAddress))"]+ }+ if let mac = plan.macAddress {+ parts.append("mac \(mac)")+ }+ if case .manual = plan.guestIPv4 {+ parts.append("guest \(plan.guestIPv4!)")+ }+ if !plan.portForwards.isEmpty {+ parts.append("forwards \(plan.portForwards.map(\.description).joined(separator: ", "))")+ }+ if let name = plan.localHostName {+ parts.append("mdns \(name).local")+ }+ return parts.joined(separator: " ")+ }++ static func describe(_ attachment: VZNetworkDeviceAttachment?) -> String {+ switch attachment {+ case nil: "none"+ case is VZNATNetworkDeviceAttachment: "nat"+ case let bridged as VZBridgedNetworkDeviceAttachment: "bridged(\(bridged.interface.identifier))"+ case is VZFileHandleNetworkDeviceAttachment: "tunnel"+ case let other?: String(describing: type(of: other))+ }+ }+// MARK: - Start@MainActordiff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swiftindex 18f0c31d..d2c40d34 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift@@ -107,18 +107,15 @@ public enum VPhoneBundleOperations {memoryMB: UInt64?,networkMode: VPhoneVirtualMachineManifest.NetworkConfig.NetworkMode? = nil,bridgeInterface: String? = nil,- resolvesMacName: Bool? = nil,+ networkEdit: VPhoneNetworkEdit = VPhoneNetworkEdit(),) throws -> VPhoneBundle {let bundle = try library.bundle(named: name)- let editsNetwork = networkMode != nil || bridgeInterface != nil || resolvesMacName != nil- let network = editsNetwork- ? try VPhoneNetworking.merge(- into: bundle.manifest.networkConfig,- mode: networkMode,- bridgeInterface: bridgeInterface,- resolvesMacName: resolvesMacName,- )- : nil+ var edit = networkEdit+ edit.mode = networkMode ?? edit.mode+ edit.bridgeInterface = bridgeInterface ?? edit.bridgeInterface+ let network = edit.isEmpty+ ? nil+ : try VPhoneNetworking.merge(into: bundle.manifest.networkConfig, edit: edit)let updated = bundle.manifest.updating(cpuCount: cpuCount,memorySize: memoryMB.map { $0 * 1024 * 1024 },@@ -143,7 +140,17 @@ public enum VPhoneBundleOperations {throw VPhoneLibraryError.alreadyExists(name: newName)}try FileManager.default.moveItem(at: src, to: dst)- return try VPhoneBundle.load(at: dst)+ let renamed = try VPhoneBundle.load(at: dst)+ // An mDNS name that `--mdns on` derived from the old name follows it;+ // one chosen by hand stays.+ let network = renamed.manifest.networkConfig+ guard network.localHostName == VPhoneNetworking.localHostName(forVMName: name) else { return renamed }+ let updated = renamed.manifest.updating(+ networkConfig: network.with(localHostName: .some(VPhoneNetworking.localHostName(forVMName: newName))),+ )+ try updated.write(to: renamed.configURL)+ try VPhoneHostFilePermissions.makeAccessible(at: renamed.configURL)+ return VPhoneBundle(url: renamed.url, manifest: updated)}public static func delete(bundleNamed name: String, in library: VPhoneLibrary) throws {diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneInternetProtocol.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneInternetProtocol.swiftindex edb7e01b..a98ac5bc 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneInternetProtocol.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneInternetProtocol.swift@@ -30,20 +30,95 @@ public struct VPhoneIPv4Address: Sendable, Equatable, Hashable, CustomStringConvpublic static let any = VPhoneIPv4Address(0, 0, 0, 0)}+// MARK: - Subnet++/// An IPv4 network, `network/prefixLength`.+public struct VPhoneIPv4Subnet: Sendable, Equatable, Hashable, CustomStringConvertible {+ /// The network address, with every host bit clear.+ public let network: VPhoneIPv4Address+ public let prefixLength: Int++ /// The subnet `address` sits in. Nil for a prefix outside 0...32.+ public init?(containing address: VPhoneIPv4Address, prefixLength: Int) {+ guard (0 ... 32).contains(prefixLength) else { return nil }+ self.prefixLength = prefixLength+ network = VPhoneIPv4Address(address.raw & Self.mask(prefixLength))+ }++ /// The subnet named by an address and a dotted mask, nil when the mask's+ /// bits are not contiguous.+ public init?(containing address: VPhoneIPv4Address, mask: VPhoneIPv4Address) {+ let length = mask.raw.nonzeroBitCount+ guard Self.mask(length) == mask.raw else { return nil }+ self.init(containing: address, prefixLength: length)+ }++ private static func mask(_ length: Int) -> UInt32 {+ length == 0 ? 0 : UInt32.max << UInt32(32 - length)+ }++ public var mask: VPhoneIPv4Address {+ VPhoneIPv4Address(Self.mask(prefixLength))+ }++ public var broadcast: VPhoneIPv4Address {+ VPhoneIPv4Address(network.raw | ~Self.mask(prefixLength))+ }++ /// The first assignable address, where `nat` and `tunnel` put the host.+ public var firstHost: VPhoneIPv4Address {+ VPhoneIPv4Address(network.raw &+ 1)+ }++ public func contains(_ address: VPhoneIPv4Address) -> Bool {+ address.raw & Self.mask(prefixLength) == network.raw+ }++ /// Whether `address` can be given to a node: inside, and neither the+ /// network nor the broadcast address.+ public func isAssignable(_ address: VPhoneIPv4Address) -> Bool {+ contains(address) && address != network && address != broadcast+ }++ public func overlaps(_ other: VPhoneIPv4Subnet) -> Bool {+ contains(other.network) || other.contains(network)+ }++ /// RFC 1918 space, the only addresses `nat` and `tunnel` hand out.+ public static let privateRanges = [+ VPhoneIPv4Subnet(containing: VPhoneIPv4Address(10, 0, 0, 0), prefixLength: 8)!,+ VPhoneIPv4Subnet(containing: VPhoneIPv4Address(172, 16, 0, 0), prefixLength: 12)!,+ VPhoneIPv4Subnet(containing: VPhoneIPv4Address(192, 168, 0, 0), prefixLength: 16)!,+ ]++ public var isPrivate: Bool {+ Self.privateRanges.contains { $0.contains(network) && $0.prefixLength <= prefixLength }+ }++ public var description: String {+ "\(network)/\(prefixLength)"+ }+}+// MARK: - Configuration/// Addressing for the userspace network.///-/// The subnet deliberately differs from vmnet's `192.168.64.0/24` so `tunnel`-/// and `nat` can coexist on one host without their DHCP servers answering each-/// other. It also sits inside `192.168.0.0/16`, which every mainstream VPN keeps-/// out of its tunnel.+/// The default subnet deliberately differs from vmnet's `192.168.64.0/24` so+/// `tunnel` and `nat` can coexist on one host without their DHCP servers+/// answering each other. It also sits inside `192.168.0.0/16`, which every+/// mainstream VPN keeps out of its tunnel. A VM's `ipv4` setting replaces it.public struct VPhoneUserspaceNetworkConfiguration: Sendable, Equatable {/// The address the host answers ARP for, serves DHCP from, and later/// appears to be the DNS resolver. Also the DHCP `server-id`.public var hostAddress: VPhoneIPv4Address/// The lease handed to the guest. One address is enough: one guest per VM.public var guestAddress: VPhoneIPv4Address+ /// The guest's subnet, advertised as DHCP option 1.+ public var prefixLength: Int+ /// Resolvers advertised as DHCP option 6. Empty means `hostAddress`, whose+ /// port 53 is answered by the host's own resolver.+ public var dnsServers: [VPhoneIPv4Address]/// Advertised through DHCP option 26, and the ceiling for everything we send/// the guest.///@@ -63,30 +138,82 @@ public struct VPhoneUserspaceNetworkConfiguration: Sendable, Equatable {mtu: 1500,)- public init(hostAddress: VPhoneIPv4Address, guestAddress: VPhoneIPv4Address, mtu: Int = 1500) {+ public init(+ hostAddress: VPhoneIPv4Address,+ guestAddress: VPhoneIPv4Address,+ prefixLength: Int = 24,+ dnsServers: [VPhoneIPv4Address] = [],+ mtu: Int = 1500,+ ) {self.hostAddress = hostAddressself.guestAddress = guestAddress+ self.prefixLength = prefixLength+ self.dnsServers = dnsServersself.mtu = mtu}++ /// The guest's subnet.+ public var subnet: VPhoneIPv4Subnet {+ VPhoneIPv4Subnet(containing: guestAddress, prefixLength: prefixLength)+ ?? VPhoneIPv4Subnet(containing: guestAddress, prefixLength: 24)!+ }++ /// What DHCP option 6 carries.+ public var advertisedDNSServers: [VPhoneIPv4Address] {+ dnsServers.isEmpty ? [hostAddress] : dnsServers+ }}/// A 48-bit Ethernet address. The host side uses a locally administered address-/// of its own; the guest's is learned from the first frame it sends, because-/// Virtualization.framework assigns the MAC and never tells us what it picked.-public struct VPhoneMACAddress: Sendable, Equatable, Hashable {+/// of its own; the tunnel learns the guest's from the first frame it sends, so+/// it works whether or not the manifest names one.+public struct VPhoneMACAddress: Sendable, Equatable, Hashable, CustomStringConvertible {public var bytes: [UInt8]public init(_ bytes: [UInt8]) {self.bytes = bytes}+ /// Parse `aa:bb:cc:dd:ee:ff` (or with `-`), nil for anything else.+ public init?(string: String) {+ let parts = string.split(omittingEmptySubsequences: false) { $0 == ":" || $0 == "-" }+ guard parts.count == 6 else { return nil }+ var bytes: [UInt8] = []+ for part in parts {+ guard part.count == 2, let value = UInt8(part, radix: 16) else { return nil }+ bytes.append(value)+ }+ self.init(bytes)+ }++ /// A random unicast, locally administered address: the kind no vendor+ /// assigns, so it cannot collide with real hardware.+ public static func randomLocallyAdministered() -> VPhoneMACAddress {+ var bytes = (0 ..< 6).map { _ in UInt8.random(in: 0 ... 255) }+ bytes[0] = (bytes[0] & 0xFC) | 0x02+ return VPhoneMACAddress(bytes)+ }+/// The gateway's address. Locally administered, unicast, and unlikely to/// collide with anything.public static let gateway = VPhoneMACAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01])+ /// Not a group address. A NIC with the multicast bit set is not reachable.+ public var isUnicast: Bool {+ bytes.count == 6 && bytes[0] & 0x01 == 0+ }++ public var isZero: Bool {+ bytes.allSatisfy { $0 == 0 }+ }+var hexString: String {bytes.map { String(format: "%02x", $0) }.joined(separator: ":")}++ public var description: String {+ hexString+ }}// MARK: - Checksumsdiff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhonePortForwarder.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhonePortForwarder.swiftnew file mode 100644index 00000000..196947fc--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhonePortForwarder.swift@@ -0,0 +1,462 @@+import Foundation+import os++// MARK: - Port forwarding++/// Host ports carried into the guest, for the forwards in a VM's manifest.+///+/// Listening happens here, in `vphone-vm`, as an ordinary unprivileged+/// process: no pf rules, no root, and nothing left behind when the VM stops.+/// Where an accepted client goes depends on the network:+///+/// - `nat`: the Mac reaches the guest by address over the vmnet network, so a+/// TCP client is relayed over a second socket to the guest, and a UDP client+/// gets a connected socket of its own.+/// - `tunnel`: no host route reaches the guest, so the client is handed to the+/// userspace network, which presents it to the guest as a peer at the gateway.+///+/// Threading: every field is touched only on `queue`. That is the invariant+/// behind `@unchecked Sendable`.+public final class VPhonePortForwarder: @unchecked Sendable {+ public typealias PortForward = VPhoneVirtualMachineManifest.NetworkConfig.PortForward++ public enum Destination: Sendable {+ /// The guest's address on a network the host is part of. Nil until it+ /// is known; `updateGuestAddress` fills it in for a DHCP guest.+ case direct(VPhoneIPv4Address?)+ case tunnel(VPhoneUserspaceNetwork)+ }++ /// A UDP client of a forwarded port in `direct` mode.+ private final class UDPSession {+ let socket: Int32+ let source: DispatchSourceRead+ var lastActivity = Date()++ init(socket: Int32, source: DispatchSourceRead) {+ self.socket = socket+ self.source = source+ }+ }++ private static let log = Logger(subsystem: "com.vphone.network", category: "forward")+ private static let udpIdleTimeout: TimeInterval = 60+ private static let datagramCapacity = 65535++ public let forwards: [PortForward]+ private let destination: Destination+ private let queue = DispatchQueue(label: "com.vphone.port-forward")+ private var guestAddress: VPhoneIPv4Address?+ private var listeners: [DispatchSourceRead] = []+ private var relays: [ObjectIdentifier: VPhoneStreamRelay] = [:]+ private var udpSessions: [String: UDPSession] = [:]+ private var isStopped = false++ public init(forwards: [PortForward], destination: Destination) {+ self.forwards = forwards+ self.destination = destination+ if case let .direct(address) = destination {+ guestAddress = address+ }+ }++ /// Open every listener. Returns a line for each forward that could not be+ /// opened (usually a port something else holds); the rest still work.+ @discardableResult+ public func start() -> [String] {+ queue.sync {+ var failures: [String] = []+ for forward in forwards {+ do {+ try listen(forward)+ } catch {+ failures.append("\(forward): \(error)")+ }+ }+ return failures+ }+ }++ public func stop() {+ queue.sync {+ guard !isStopped else { return }+ isStopped = true+ listeners.forEach { $0.cancel() }+ listeners.removeAll()+ relays.values.forEach { $0.close() }+ relays.removeAll()+ udpSessions.values.forEach { $0.source.cancel() }+ udpSessions.removeAll()+ }+ }++ /// Where `direct` forwards go from now on. Connections already open keep+ /// the address they were made to.+ public func updateGuestAddress(_ address: VPhoneIPv4Address?) {+ queue.async { [self] in+ guard case .direct = destination, address != guestAddress else { return }+ guestAddress = address+ Self.log.info("forwarding to \(address?.description ?? "nothing", privacy: .public)")+ }+ }++ // MARK: - Listening++ private struct SocketError: Error, CustomStringConvertible {+ let call: String+ let code: Int32++ var description: String {+ "\(call): \(String(cString: strerror(code)))"+ }+ }++ private func listen(_ forward: PortForward) throws {+ guard let address = VPhoneIPv4Address(dotted: forward.listenAddress) else {+ throw SocketError(call: "address", code: EINVAL)+ }+ let tcp = forward.transport == .tcp+ let descriptor = socket(AF_INET, tcp ? SOCK_STREAM : SOCK_DGRAM, 0)+ guard descriptor >= 0 else { throw SocketError(call: "socket", code: errno) }+ var one: Int32 = 1+ _ = setsockopt(descriptor, SOL_SOCKET, SO_REUSEADDR, &one, socklen_t(MemoryLayout<Int32>.size))+ _ = fcntl(descriptor, F_SETNOSIGPIPE, 1)++ var socketAddress = Self.socketAddress(address, port: UInt16(forward.hostPort))+ let bound = withUnsafePointer(to: &socketAddress) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ bind(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ guard bound == 0 else {+ let code = errno+ Darwin.close(descriptor)+ throw SocketError(call: "bind \(forward.listenAddress):\(forward.hostPort)", code: code)+ }+ if tcp, Darwin.listen(descriptor, 64) != 0 {+ let code = errno+ Darwin.close(descriptor)+ throw SocketError(call: "listen", code: code)+ }+ _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) | O_NONBLOCK)++ let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: queue)+ let guestPort = UInt16(forward.guestPort)+ source.setEventHandler { [weak self] in+ if tcp {+ self?.acceptClients(listener: descriptor, guestPort: guestPort)+ } else {+ self?.receiveDatagrams(listener: descriptor, guestPort: guestPort)+ }+ }+ source.setCancelHandler { Darwin.close(descriptor) }+ source.resume()+ listeners.append(source)+ Self.log.info("forwarding \(forward.description, privacy: .public)")+ }++ static func socketAddress(_ address: VPhoneIPv4Address, port: UInt16) -> sockaddr_in {+ var socketAddress = sockaddr_in()+ socketAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)+ socketAddress.sin_family = sa_family_t(AF_INET)+ socketAddress.sin_port = port.bigEndian+ socketAddress.sin_addr = in_addr(s_addr: address.raw.bigEndian)+ return socketAddress+ }++ // MARK: - TCP++ private func acceptClients(listener: Int32, guestPort: UInt16) {+ while !isStopped {+ let client = accept(listener, nil, nil)+ guard client >= 0 else { return } // EAGAIN: none left+ _ = fcntl(client, F_SETNOSIGPIPE, 1)+ switch destination {+ case let .tunnel(network):+ network.acceptInbound(tcp: client, guestPort: guestPort)+ case .direct:+ relay(client, toGuestPort: guestPort)+ }+ }+ }++ private func relay(_ client: Int32, toGuestPort guestPort: UInt16) {+ guard let guestAddress else {+ Self.log.error("dropping a client of guest port \(guestPort, privacy: .public): guest address not known yet")+ Darwin.close(client)+ return+ }+ let upstream = socket(AF_INET, SOCK_STREAM, 0)+ guard upstream >= 0 else {+ Darwin.close(client)+ return+ }+ _ = fcntl(upstream, F_SETNOSIGPIPE, 1)+ for descriptor in [client, upstream] {+ _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) | O_NONBLOCK)+ var one: Int32 = 1+ _ = setsockopt(descriptor, IPPROTO_TCP, TCP_NODELAY, &one, socklen_t(MemoryLayout<Int32>.size))+ }+ var target = Self.socketAddress(guestAddress, port: guestPort)+ let result = withUnsafePointer(to: &target) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ connect(upstream, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ guard result == 0 || errno == EINPROGRESS else {+ Darwin.close(client)+ Darwin.close(upstream)+ return+ }+ let relay = VPhoneStreamRelay(client: client, upstream: upstream, queue: queue)+ let id = ObjectIdentifier(relay)+ relay.onClose = { [weak self] in self?.relays[id] = nil }+ relays[id] = relay+ relay.start(connecting: result != 0)+ }++ // MARK: - UDP++ private func receiveDatagrams(listener: Int32, guestPort: UInt16) {+ var buffer = [UInt8](repeating: 0, count: Self.datagramCapacity)+ while !isStopped {+ var client = sockaddr_in()+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)+ let received = buffer.withUnsafeMutableBytes { raw in+ withUnsafeMutablePointer(to: &client) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ recvfrom(listener, raw.baseAddress, raw.count, 0, $0, &length)+ }+ }+ }+ guard received >= 0 else { return } // EAGAIN: none left+ let payload = Array(buffer[0 ..< received])+ switch destination {+ case let .tunnel(network):+ network.receiveInbound(udp: payload, from: client, listener: listener, guestPort: guestPort)+ case .direct:+ sendDirect(payload, from: client, listener: listener, guestPort: guestPort)+ }+ }+ }++ private func sendDirect(_ payload: [UInt8], from client: sockaddr_in, listener: Int32, guestPort: UInt16) {+ let now = Date()+ for (key, session) in udpSessions where now.timeIntervalSince(session.lastActivity) >= Self.udpIdleTimeout {+ session.source.cancel()+ udpSessions[key] = nil+ }+ let key = "\(listener)|\(client.sin_addr.s_addr)|\(client.sin_port)"+ let session: UDPSession+ if let existing = udpSessions[key] {+ session = existing+ } else {+ guard let created = openUDPSession(client: client, listener: listener, guestPort: guestPort) else { return }+ udpSessions[key] = created+ session = created+ }+ session.lastActivity = now+ _ = payload.withUnsafeBytes { Darwin.send(session.socket, $0.baseAddress, $0.count, 0) }+ }++ /// A socket connected to the guest, so its answers can only come from+ /// there, relayed back to `client` through the listener.+ private func openUDPSession(client: sockaddr_in, listener: Int32, guestPort: UInt16) -> UDPSession? {+ guard let guestAddress else { return nil }+ let descriptor = socket(AF_INET, SOCK_DGRAM, 0)+ guard descriptor >= 0 else { return nil }+ var target = Self.socketAddress(guestAddress, port: guestPort)+ let connected = withUnsafePointer(to: &target) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ guard connected == 0 else {+ Darwin.close(descriptor)+ return nil+ }+ _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) | O_NONBLOCK)+ let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: queue)+ let session = UDPSession(socket: descriptor, source: source)+ source.setEventHandler { [weak session] in+ var buffer = [UInt8](repeating: 0, count: Self.datagramCapacity)+ var client = client+ while true {+ let received = buffer.withUnsafeMutableBytes { recv(descriptor, $0.baseAddress, $0.count, 0) }+ guard received >= 0 else { return }+ session?.lastActivity = Date()+ _ = buffer.withUnsafeBytes { raw in+ withUnsafePointer(to: &client) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ sendto(listener, raw.baseAddress, received, 0, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ }+ }+ }+ source.setCancelHandler { Darwin.close(descriptor) }+ source.resume()+ return session+ }+}++// MARK: - Stream relay++/// Copies bytes both ways between two connected stream sockets until both+/// directions have ended, with backpressure: a side is not read while the+/// other cannot take more. Every call is on `queue`.+final class VPhoneStreamRelay {+ /// Bytes queued toward one side before its peer stops being read.+ private static let pendingLimit = 1 << 20+ private static let readCapacity = 65536++ private let queue: DispatchQueue+ /// `[client, upstream]`. Index `i` reads from `ends[i]`, writes to `ends[1 - i]`.+ private let ends: [Int32]+ private var readSources: [DispatchSourceRead] = []+ private var readSuspended = [false, false]+ private var writeSources: [DispatchSourceWrite?] = [nil, nil]+ /// `pending[i]` waits to be written to `ends[i]`.+ private var pending: [[UInt8]] = [[], []]+ /// `ended[i]`: `ends[i]` will send nothing more.+ private var ended = [false, false]+ private var connectSource: DispatchSourceWrite?+ private var isClosed = false+ private var started = false+ var onClose: (() -> Void)?++ init(client: Int32, upstream: Int32, queue: DispatchQueue) {+ ends = [client, upstream]+ self.queue = queue+ }++ /// Begin relaying, after the upstream connect completes when `connecting`.+ func start(connecting: Bool) {+ guard connecting else {+ begin()+ return+ }+ let source = DispatchSource.makeWriteSource(fileDescriptor: ends[1], queue: queue)+ source.setEventHandler { [weak self] in+ guard let self else { return }+ connectSource?.cancel()+ connectSource = nil+ var error: Int32 = 0+ var length = socklen_t(MemoryLayout<Int32>.size)+ _ = getsockopt(ends[1], SOL_SOCKET, SO_ERROR, &error, &length)+ if error == 0 {+ begin()+ } else {+ close()+ }+ }+ source.resume()+ connectSource = source+ }++ private func begin() {+ guard !isClosed else { return }+ started = true+ for index in 0 ..< 2 {+ let descriptor = ends[index]+ let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: queue)+ source.setEventHandler { [weak self] in self?.read(index) }+ source.setCancelHandler { Darwin.close(descriptor) }+ source.resume()+ readSources.append(source)+ }+ }++ private func read(_ index: Int) {+ let other = 1 - index+ var buffer = [UInt8](repeating: 0, count: Self.readCapacity)+ while !isClosed {+ if pending[other].count >= Self.pendingLimit {+ suspendRead(index)+ return+ }+ let received = buffer.withUnsafeMutableBytes { recv(ends[index], $0.baseAddress, $0.count, 0) }+ if received > 0 {+ pending[other] += buffer[0 ..< received]+ flush(other)+ continue+ }+ if received == 0 {+ // Half-close: pass the end along once what came before it has.+ ended[index] = true+ suspendRead(index)+ flush(other)+ return+ }+ if errno != EAGAIN, errno != EINTR {+ close()+ }+ return+ }+ }++ /// Write what `ends[index]` will take; wait for writability for the rest.+ private func flush(_ index: Int) {+ while !pending[index].isEmpty {+ let written = pending[index].withUnsafeBytes { Darwin.send(ends[index], $0.baseAddress, $0.count, 0) }+ if written > 0 {+ pending[index].removeFirst(written)+ continue+ }+ if written < 0, errno == EAGAIN || errno == EINTR {+ if writeSources[index] == nil {+ let source = DispatchSource.makeWriteSource(fileDescriptor: ends[index], queue: queue)+ source.setEventHandler { [weak self] in self?.flush(index) }+ source.resume()+ writeSources[index] = source+ }+ return+ }+ close()+ return+ }+ writeSources[index]?.cancel()+ writeSources[index] = nil+ let source = 1 - index+ if ended[source] {+ shutdown(ends[index], SHUT_WR)+ if ended[index], pending[source].isEmpty {+ close()+ }+ return+ }+ if readSuspended[source] {+ readSources[source].resume()+ readSuspended[source] = false+ }+ }++ private func suspendRead(_ index: Int) {+ guard !readSuspended[index] else { return }+ readSources[index].suspend()+ readSuspended[index] = true+ }++ func close() {+ guard !isClosed else { return }+ isClosed = true+ connectSource?.cancel()+ connectSource = nil+ writeSources.forEach { $0?.cancel() }+ writeSources = [nil, nil]+ if started {+ // A suspended source must be resumed before it is cancelled, and+ // the cancel handlers close the descriptors.+ for index in 0 ..< readSources.count {+ if readSuspended[index] {+ readSources[index].resume()+ readSuspended[index] = false+ }+ readSources[index].cancel()+ }+ } else {+ ends.forEach { Darwin.close($0) }+ }+ onClose?()+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swiftindex fd04f858..8b9c79fd 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneTCPForwarder.swift@@ -106,6 +106,9 @@ final class VPhoneTCPForwarder: @unchecked Sendable {case established/// FIN seen from one side; the other may still have data in flight.case closing+ /// Inbound: a host client connected to a forwarded port, our SYN went+ /// to the guest, and its SYN-ACK has not come back.+ case synSent}private final class Connection {@@ -203,6 +206,9 @@ final class VPhoneTCPForwarder: @unchecked Sendable {/// Set once we have told the guest our window is shut, so a window update/// follows the moment the backlog clears.var guestWindowClosed = false+ /// Resends an inbound SYN the guest has not answered.+ var handshakeTimer: DispatchSourceTimer?+ var handshakeAttempts = 0init(flow: VPhoneTCPFlow, socket: Int32, readSource: DispatchSourceRead, state: State, localSequence: UInt32, remoteSequence: UInt32, peerMSS: Int, peerWindowScale: Int) {self.flow = flow@@ -226,6 +232,8 @@ final class VPhoneTCPForwarder: @unchecked Sendable {/// Source of initial sequence numbers. Only has to be unpredictable enough/// that two connections to the same peer do not look alike.private var sequenceCounter: UInt32 = .random(in: 0 ... UInt32.max)+ /// The last gateway-side port given to an inbound connection.+ private var inboundPortCursor: UInt16 = 40000/// Marks `queue` as ours, so `connectionCount` can tell whether it is already/// on it rather than deadlocking against itself.@@ -327,6 +335,9 @@ final class VPhoneTCPForwarder: @unchecked Sendable {connection.sendUna = segment.acknowledgmentNumberflushPending(connection)+ case .synSent:+ completeInbound(connection, segment: segment)+case .established, .closing:consume(segment, connection: connection)}@@ -806,6 +817,8 @@ final class VPhoneTCPForwarder: @unchecked Sendable {private func close(_ connection: Connection) {connection.writeSource?.cancel()connection.writeSource = nil+ connection.handshakeTimer?.cancel()+ connection.handshakeTimer = nilconnection.retransmitTimer?.cancel()connection.retransmitTimer = nil// A suspended source must be resumed before it can be cancelled;@@ -840,3 +853,150 @@ final class VPhoneTCPForwarder: @unchecked Sendable {return sequenceCounter}}++// MARK: - Inbound++/// Connections that start on the host: a client reached a forwarded port, and+/// the guest is the one being connected to. The flow keeps the guest's view,+/// so the guest's port is the source and the gateway is the far end, and once+/// the handshake is done every other path above treats it like any other.+extension VPhoneTCPForwarder {+ /// How often an unanswered SYN is sent again, and how many times. A guest+ /// still booting does not answer at all; one with nothing listening sends a+ /// RST, which ends the attempt at once.+ private static let handshakeInterval: TimeInterval = 1+ private static let handshakeAttempts = 5+ /// The gateway-side ports inbound connections use. Above the guest's own+ /// ephemeral range in practice, and only ever seen by the guest.+ private static let inboundPorts: ClosedRange<UInt16> = 40000 ... 59999++ /// Connect `socket`, accepted from a host client, to `guestPort` on the+ /// guest. Takes ownership of the descriptor. On `queue`.+ func openInbound(+ socket descriptor: Int32,+ guestAddress: VPhoneIPv4Address,+ guestPort: UInt16,+ gatewayAddress: VPhoneIPv4Address,+ guestHardware: VPhoneMACAddress,+ ) {+ dispatchPrecondition(condition: .onQueue(queue))+ guard !isStopped, connections.count < Self.maximumConnections,+ let gatewayPort = freeInboundPort(guestAddress: guestAddress, guestPort: guestPort, gatewayAddress: gatewayAddress)+ else {+ Darwin.close(descriptor)+ return+ }++ _ = fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) | O_NONBLOCK)+ _ = fcntl(descriptor, F_SETNOSIGPIPE, 1)+ var one: Int32 = 1+ _ = setsockopt(descriptor, IPPROTO_TCP, TCP_NODELAY, &one, socklen_t(MemoryLayout<Int32>.size))++ let flow = VPhoneTCPFlow(+ sourceAddress: guestAddress,+ sourcePort: guestPort,+ destinationAddress: gatewayAddress,+ destinationPort: gatewayPort,+ guestHardware: guestHardware,+ )+ let readSource = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: queue)+ let connection = Connection(+ flow: flow,+ socket: descriptor,+ readSource: readSource,+ state: .synSent,+ localSequence: nextSequence(),+ remoteSequence: 0,+ peerMSS: Self.defaultPeerMSS,+ peerWindowScale: 0,+ )+ readSource.setEventHandler { [weak self] in self?.drainHost(connection) }+ readSource.setCancelHandler { Darwin.close(descriptor) }+ // Nothing is read from the client until the guest has accepted, or+ // its FIN could reach the guest before our SYN does. Resumed and then+ // suspended, not left inactive, because `close` resumes a suspended+ // source before cancelling it.+ readSource.resume()+ readSource.suspend()+ connection.readSuspended = true+ connections[flow.key] = connection+ sendInboundSyn(connection)+ }++ private func freeInboundPort(+ guestAddress: VPhoneIPv4Address,+ guestPort: UInt16,+ gatewayAddress: VPhoneIPv4Address,+ ) -> UInt16? {+ for _ in Self.inboundPorts {+ inboundPortCursor = inboundPortCursor >= Self.inboundPorts.upperBound+ ? Self.inboundPorts.lowerBound+ : inboundPortCursor + 1+ let key = VPhoneTCPFlowKey(+ sourceAddress: guestAddress, sourcePort: guestPort,+ destinationAddress: gatewayAddress, destinationPort: inboundPortCursor,+ )+ if connections[key] == nil {+ return inboundPortCursor+ }+ }+ return nil+ }++ private func sendInboundSyn(_ connection: Connection) {+ connection.handshakeAttempts += 1+ // A resend reuses the first SYN's sequence number.+ let sequence = connection.handshakeAttempts == 1 ? connection.localSequence : connection.localSequence &- 1+ let syn = VPhoneTCPSegment(+ sourcePort: connection.flow.destinationPort,+ destinationPort: connection.flow.sourcePort,+ sequenceNumber: sequence,+ acknowledgmentNumber: 0,+ flags: VPhoneTCPFlags.syn,+ windowSize: Self.advertisedWindow,+ advertisedMSS: Self.ourMSS,+ advertisedWindowScale: Self.ourWindowScaleShift,+ )+ if connection.handshakeAttempts == 1 {+ send(syn, connection: connection)+ } else {+ deliver(connection.flow, syn)+ }++ connection.handshakeTimer?.cancel()+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.schedule(deadline: .now() + Self.handshakeInterval)+ timer.setEventHandler { [weak self, weak connection] in+ guard let self, let connection, connection.state == .synSent, !connection.isClosed else { return }+ if connection.handshakeAttempts >= Self.handshakeAttempts {+ finish(connection)+ } else {+ sendInboundSyn(connection)+ }+ }+ timer.resume()+ connection.handshakeTimer = timer+ }++ /// The guest's answer to our SYN. A SYN-ACK for it completes the+ /// handshake; anything else is ignored (a RST was handled before here).+ private func completeInbound(_ connection: Connection, segment: VPhoneTCPSegment) {+ guard segment.hasSYN, segment.hasACK, segment.acknowledgmentNumber == connection.localSequence else { return }+ connection.handshakeTimer?.cancel()+ connection.handshakeTimer = nil+ connection.remoteSequence = segment.sequenceNumber &+ 1+ connection.peerMSS = segment.maximumSegmentSize ?? Self.defaultPeerMSS+ connection.peerWindowScale = segment.windowScale ?? 0+ connection.windowScaleNegotiated = segment.windowScale != nil+ // The window in a SYN is never scaled.+ connection.sendWindowRight = segment.acknowledgmentNumber &+ UInt32(segment.windowSize)+ connection.sendUna = segment.acknowledgmentNumber+ connection.sentNotAckedSequence = segment.acknowledgmentNumber+ connection.state = .established+ sendAcknowledgment(connection)+ if connection.readSuspended {+ connection.readSource.resume()+ connection.readSuspended = false+ }+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swiftindex 30683f53..fea2f821 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetwork.swift@@ -69,6 +69,11 @@ public final class VPhoneUserspaceNetwork: @unchecked Sendable {self?.sendUDPReply(flow: flow, payload: payload)}+ /// Host clients of forwarded UDP ports, by the gateway port the guest+ /// sees them on.+ private var inboundUDP: [UInt16: InboundUDPSession] = [:]+ private var inboundUDPCursor: UInt16 = 40000+/// 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, gatewayAddress: configuration.hostAddress) { [weak self] flow, segment in@@ -192,6 +197,12 @@ public final class VPhoneUserspaceNetwork: @unchecked Sendable {case let .reply(reply):write(reply)case let .forward(flow, payload):+ if flow.destinationAddress == configuration.hostAddress,+ let session = inboundUDP[flow.destinationPort], session.guestPort == flow.sourcePort+ {+ replyInbound(payload, session: session, gatewayPort: flow.destinationPort)+ continue+ }// The answer arrives later, on this same queue.forwarder.send(payload, for: flow)case let .forwardTCP(flow, segment):@@ -273,3 +284,98 @@ public final class VPhoneUserspaceNetwork: @unchecked Sendable {}}}++// MARK: - Inbound++/// Port forwarding into the guest. The host side (`VPhonePortForwarder`) owns+/// the listening sockets; this side makes each client look, to the guest, like+/// a peer at the gateway address, which is the only address it can reach.+extension VPhoneUserspaceNetwork {+ /// One host client of a forwarded UDP port.+ struct InboundUDPSession {+ let listener: Int32+ let client: sockaddr_in+ let guestPort: UInt16+ var lastActivity: Date+ }++ /// UDP has no teardown, so a client that goes quiet is forgotten after this.+ private static let inboundUDPIdleTimeout: TimeInterval = 60+ private static let inboundUDPPorts: ClosedRange<UInt16> = 40000 ... 59999++ /// Connect an accepted host TCP client to `guestPort`. Takes ownership of+ /// the descriptor, and closes it when the guest cannot be reached: before+ /// the guest has sent its first frame there is no MAC to address it by.+ public func acceptInbound(tcp descriptor: Int32, guestPort: UInt16) {+ queue.async { [self] in+ guard !isStopped, let mac = responder.guestMAC else {+ close(descriptor)+ return+ }+ tcpForwarder.openInbound(+ socket: descriptor,+ guestAddress: configuration.guestAddress,+ guestPort: guestPort,+ gatewayAddress: configuration.hostAddress,+ guestHardware: mac,+ )+ }+ }++ /// One datagram a host client sent to a forwarded UDP port. Answers go+ /// back through `listener`, which the caller keeps open.+ public func receiveInbound(udp payload: [UInt8], from client: sockaddr_in, listener: Int32, guestPort: UInt16) {+ queue.async { [self] in+ guard !isStopped, let mac = responder.guestMAC else { return }+ let now = Date()+ inboundUDP = inboundUDP.filter { now.timeIntervalSince($0.value.lastActivity) < Self.inboundUDPIdleTimeout }++ let gatewayPort: UInt16+ if let existing = inboundUDP.first(where: { _, session in+ session.listener == listener && session.guestPort == guestPort+ && session.client.sin_addr.s_addr == client.sin_addr.s_addr+ && session.client.sin_port == client.sin_port+ }) {+ gatewayPort = existing.key+ } else {+ guard let port = nextInboundUDPPort() else { return }+ gatewayPort = port+ }+ inboundUDP[gatewayPort] = InboundUDPSession(listener: listener, client: client, guestPort: guestPort, lastActivity: now)++ let flow = VPhoneUDPFlow(+ sourceAddress: configuration.guestAddress,+ sourcePort: guestPort,+ destinationAddress: configuration.hostAddress,+ destinationPort: gatewayPort,+ guestHardware: mac,+ )+ sendUDPReply(flow: flow, payload: payload)+ }+ }++ private func nextInboundUDPPort() -> UInt16? {+ for _ in Self.inboundUDPPorts {+ inboundUDPCursor = inboundUDPCursor >= Self.inboundUDPPorts.upperBound+ ? Self.inboundUDPPorts.lowerBound+ : inboundUDPCursor + 1+ if inboundUDP[inboundUDPCursor] == nil {+ return inboundUDPCursor+ }+ }+ return nil+ }++ /// The guest answered a forwarded UDP client.+ private func replyInbound(_ payload: [UInt8], session: InboundUDPSession, gatewayPort: UInt16) {+ inboundUDP[gatewayPort]?.lastActivity = Date()+ var client = session.client+ _ = payload.withUnsafeBytes { raw in+ withUnsafePointer(to: &client) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ sendto(session.listener, raw.baseAddress, raw.count, 0, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ }+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetworkResponder.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetworkResponder.swiftindex e197f118..3454be9b 100644--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetworkResponder.swift+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneUserspaceNetworkResponder.swift@@ -124,6 +124,7 @@ struct VPhoneDHCPMessage {assigned: VPhoneIPv4Address,server: VPhoneIPv4Address,netmask: VPhoneIPv4Address,+ dnsServers: [VPhoneIPv4Address] = [],mtu: Int,leaseSeconds: UInt32 = 86400,) -> [UInt8] {@@ -152,7 +153,7 @@ struct VPhoneDHCPMessage {append(51, withUnsafeBytes(of: leaseSeconds.bigEndian, Array.init)) // lease timeappend(1, netmask.bytes) // subnet maskappend(3, server.bytes) // router- append(6, server.bytes) // DNS+ append(6, (dnsServers.isEmpty ? [server] : dnsServers).flatMap(\.bytes)) // DNSappend(26, [UInt8(mtu >> 8), UInt8(mtu & 0xFF)]) // interface MTUoptions.append(255)// Pad to the minimum BOOTP payload so short replies stay well-formed.@@ -213,14 +214,14 @@ enum VPhoneUserspaceNetworkOutcome {/// behind a serial queue rather than treating it as a free function.final class VPhoneUserspaceNetworkResponder {private let configuration: VPhoneUserspaceNetworkConfiguration- private var guestMAC: VPhoneMACAddress?+ private(set) var guestMAC: VPhoneMACAddress?init(configuration: VPhoneUserspaceNetworkConfiguration) {self.configuration = configuration}var netmask: VPhoneIPv4Address {- VPhoneIPv4Address(255, 255, 255, 0)+ configuration.subnet.mask}func handle(_ frame: [UInt8]) -> VPhoneUserspaceNetworkOutcome {@@ -352,6 +353,7 @@ final class VPhoneUserspaceNetworkResponder {assigned: configuration.guestAddress,server: configuration.hostAddress,netmask: netmask,+ dnsServers: configuration.advertisedDNSServers,mtu: configuration.mtu,)let replyDatagram = VPhoneUDPDatagram(diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swiftindex 9a0f40a3..2414f25e 100644--- a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift@@ -16,6 +16,30 @@ public enum VPhoneNetworkingError: Error, Equatable {case bridgeInterfaceMustBeNamed/// `--bridge-interface` was given without selecting bridged mode.case bridgeInterfaceWithoutBridgedMode+ /// A field that must be a dotted IPv4 address is not one.+ case invalidAddress(field: String, value: String)+ case invalidPrefixLength(Int)+ /// The address is the subnet's network or broadcast address, or outside it.+ case addressNotAssignable(address: String, subnet: String)+ /// `nat` and `tunnel` hand out RFC 1918 space only.+ case addressNotPrivate(address: String, mode: String)+ case routerNotAssignable(router: String, subnet: String)+ case routerIsGuestAddress(String)+ /// On a vmnet network the host owns the gateway address; the guest cannot+ /// pick another one.+ case natRouterFixed(expected: String, subnet: String)+ /// A `nat` address has to be on the Mac's shared NAT network.+ case natAddressOffSharedNetwork(address: String, shared: String)+ case tooManyDNSServers(Int)+ /// `--gateway` or `--dns` was given while the address is left to DHCP.+ case settingWithoutAddress(String)+ case invalidMACAddress(String)+ case invalidPortForward(String)+ case duplicatePortForward(String)+ case portForwardNotFound(String)+ case portForwardUnsupported(mode: String)+ /// Not a usable mDNS host name label.+ case invalidLocalHostName(String)}extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {@@ -31,6 +55,38 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {"Bridged mode requires an interface name because vphone-cli cannot list host interfaces. Pass one with --bridge-interface, for example --bridge-interface en0."case .bridgeInterfaceWithoutBridgedMode:"--bridge-interface is only valid with --network bridged."+ case let .invalidAddress(field, value):+ "'\(value)' is not a valid IPv4 address for \(field). Use the dotted form, for example 192.168.70.10."+ case let .invalidPrefixLength(length):+ "Prefix length \(length) is not supported. Use a value from 8 to 30, for example /24."+ case let .addressNotAssignable(address, subnet):+ "\(address) cannot be given to the guest on \(subnet): it is outside the subnet, or its network or broadcast address."+ case let .addressNotPrivate(address, mode):+ "\(address) is not a private address. \(mode) mode hands out 10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16 only."+ case let .routerNotAssignable(router, subnet):+ "Gateway \(router) is not a usable address on \(subnet)."+ case let .routerIsGuestAddress(address):+ "The gateway and the guest cannot both be \(address)."+ case let .natRouterFixed(expected, subnet):+ "In nat mode the Mac is the gateway on \(subnet), at \(expected). Leave --gateway out, or set it to \(expected)."+ case let .natAddressOffSharedNetwork(address, shared):+ "\(address) is not on the Mac's shared NAT network \(shared), which nat mode uses. Pick an address on it, or use tunnel mode for another subnet."+ case let .tooManyDNSServers(count):+ "\(count) DNS servers is more than the guest takes. Give at most 4."+ case let .settingWithoutAddress(option):+ "\(option) needs a fixed address. Set one with --ip, for example --ip 192.168.64.50/24."+ case let .invalidMACAddress(value):+ "'\(value)' is not a usable MAC address. Use aa:bb:cc:dd:ee:ff with the multicast bit clear, or 'random'."+ case let .invalidPortForward(value):+ "'\(value)' is not a valid port forward. Use [tcp|udp:][host-address:]host-port:guest-port, for example tcp:8022:22."+ case let .duplicatePortForward(value):+ "Host port \(value) is forwarded more than once."+ case let .portForwardNotFound(value):+ "No port forward matches '\(value)'. Name it as listed by vm info, or by its host port."+ case let .portForwardUnsupported(mode):+ "Port forwarding works in nat and tunnel modes, not \(mode). Remove the forwards with --clear-forwards, or choose nat or tunnel."+ case let .invalidLocalHostName(name):+ "'\(name)' cannot be an mDNS name. Use 1 to 63 letters, digits and hyphens, not starting or ending with a hyphen, or 'on' for the VM's own name."}}@@ -39,6 +95,184 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {}}+// MARK: - Host++/// What the host contributes to a network plan, separated out so tests can+/// describe a host other than the one they run on.+public struct VPhoneNetworkHost: Equatable, Sendable {+ /// The shared network vmnet runs for `VZNATNetworkDeviceAttachment`.+ public var sharedNATSubnet: VPhoneIPv4Subnet+ /// The Mac's own address on it: the guest's gateway and DNS proxy.+ public var sharedNATHost: VPhoneIPv4Address++ public init(sharedNATSubnet: VPhoneIPv4Subnet, sharedNATHost: VPhoneIPv4Address) {+ self.sharedNATSubnet = sharedNATSubnet+ self.sharedNATHost = sharedNATHost+ }++ /// vmnet's own default, used unless the host's preferences move it.+ public static let defaultSharedNATHost = VPhoneIPv4Address(192, 168, 64, 1)++ /// This Mac. The shared network can be moved with `Shared_Net_Address`+ /// and `Shared_Net_Mask` in vmnet's preferences, so they are read rather+ /// than assumed.+ public static var current: VPhoneNetworkHost {+ 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] }+ let host = (values?["Shared_Net_Address"] as? String).flatMap(VPhoneIPv4Address.init(dotted:))+ ?? defaultSharedNATHost+ let mask = (values?["Shared_Net_Mask"] as? String).flatMap(VPhoneIPv4Address.init(dotted:))+ ?? VPhoneIPv4Address(255, 255, 255, 0)+ let subnet = VPhoneIPv4Subnet(containing: host, mask: mask)+ ?? VPhoneIPv4Subnet(containing: host, prefixLength: 24)!+ return VPhoneNetworkHost(sharedNATSubnet: subnet, sharedNATHost: host)+ }+}++// MARK: - Guest IPv4++/// What vphoned should leave the guest's `en0` configured as.+public enum VPhoneGuestIPv4Setting: Equatable, Sendable, CustomStringConvertible {+ /// DHCP. Only undoes a manual configuration vphoned set itself; one the+ /// user made inside the guest is left alone.+ case dhcp+ case manual(address: VPhoneIPv4Address, subnet: VPhoneIPv4Subnet, router: VPhoneIPv4Address, dns: [VPhoneIPv4Address])++ /// The parameters of vphoned's `network.ipv4.set`.+ public var parameters: [String: Any] {+ switch self {+ case .dhcp:+ ["method": "dhcp"]+ case let .manual(address, subnet, router, dns):+ [+ "method": "manual",+ "address": address.description,+ "subnet_mask": subnet.mask.description,+ "router": router.description,+ "dns": dns.map(\.description),+ ]+ }+ }++ public var description: String {+ switch self {+ case .dhcp:+ "dhcp"+ case let .manual(address, subnet, router, dns):+ "\(address)/\(subnet.prefixLength) via \(router) dns \(dns.map(\.description).joined(separator: ","))"+ }+ }+}++// MARK: - Plan++/// Everything boot needs to build the guest's network, decided from the+/// manifest without touching Virtualization so it can be tested.+public struct VPhoneNetworkPlan: Equatable, Sendable {+ public typealias PortForward = VPhoneVirtualMachineManifest.NetworkConfig.PortForward++ public enum Attachment: Equatable, Sendable {+ case none+ /// `VZNATNetworkDeviceAttachment`, the Mac's shared vmnet network.+ case sharedNAT+ case bridged(interface: String)+ case tunnel(VPhoneUserspaceNetworkConfiguration)+ }++ public let attachment: Attachment+ /// Nil leaves the MAC to Virtualization.+ public let macAddress: VPhoneMACAddress?+ /// Nil when there is no NIC to configure.+ public let guestIPv4: VPhoneGuestIPv4Setting?+ public let portForwards: [PortForward]+ /// The guest's mDNS name, without `.local`; nil leaves the guest's own.+ /// The guest announces it in every mode, `none` included: besides its+ /// NIC it has the virtual iPhone's USB network link to the Mac (`en1` in+ /// the guest, a 169.254 address on the Mac), where mDNS runs too.+ public let localHostName: String?+ /// Whether vphoned registers this Mac's `.local` name with the guest's+ /// mDNSResponder, pointing at `macAddressForGuest`.+ public let resolvesMacName: Bool+ /// 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). Nil in `bridged`, where it is the Mac's address on the+ /// bridged interface and only known at boot, and without a NIC.+ public let macAddressForGuest: VPhoneIPv4Address?+ /// Where forwarded ports go in `nat`: the fixed address, or nil to use+ /// whatever the guest reports. In `tunnel` the guest's lease.+ public let forwardingAddress: VPhoneIPv4Address?+}++// MARK: - Edits++/// A partial change to a `NetworkConfig`, as `vm config` and Launchpad make+/// it. Nil fields are left as they are.+public struct VPhoneNetworkEdit: Equatable, Sendable {+ public typealias NetworkMode = VPhoneVirtualMachineManifest.NetworkConfig.NetworkMode+ public typealias PortForward = VPhoneVirtualMachineManifest.NetworkConfig.PortForward++ public enum MACChange: Equatable, Sendable {+ /// Clear it; the next boot generates and saves a new one.+ case automatic+ /// Generate a new one now.+ case random+ case fixed(String)+ }++ public enum AddressChange: Equatable, Sendable {+ case dhcp+ case fixed(address: String, prefixLength: Int)+ }++ public var mode: NetworkMode?+ public var bridgeInterface: String?+ public var mac: MACChange?+ public var address: AddressChange?+ /// `.some(nil)` returns the gateway to its default.+ public var router: String??+ /// `.some(nil)` returns DNS to its default.+ public var dns: [String]??+ /// `.some(nil)` stops managing the guest's mDNS name.+ public var localHostName: String??+ /// Turn the guest's local record for the Mac's name on or off.+ public var resolvesMacName: Bool?+ public var addForwards: [PortForward]+ /// Forwards to drop, named as `vm info` lists them or by host port.+ public var removeForwards: [String]+ public var clearForwards: Bool++ public init(+ mode: NetworkMode? = nil,+ bridgeInterface: String? = nil,+ mac: MACChange? = nil,+ address: AddressChange? = nil,+ router: String?? = nil,+ dns: [String]?? = nil,+ localHostName: String?? = nil,+ resolvesMacName: Bool? = nil,+ addForwards: [PortForward] = [],+ removeForwards: [String] = [],+ clearForwards: Bool = false,+ ) {+ self.mode = mode+ self.bridgeInterface = bridgeInterface+ self.mac = mac+ self.address = address+ self.router = router+ self.dns = dns+ self.localHostName = localHostName+ self.resolvesMacName = resolvesMacName+ self.addForwards = addForwards+ self.removeForwards = removeForwards+ self.clearForwards = clearForwards+ }++ public var isEmpty: Bool {+ self == VPhoneNetworkEdit()+ }+}+// MARK: - Networking helpers/// Host-side helpers for validating and realizing a VM's `NetworkConfig`.@@ -47,6 +281,11 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {public enum VPhoneNetworking {public typealias NetworkConfig = VPhoneVirtualMachineManifest.NetworkConfigpublic typealias NetworkMode = NetworkConfig.NetworkMode+ public typealias IPv4Config = NetworkConfig.IPv4Config+ public typealias PortForward = NetworkConfig.PortForward++ /// More than iOS keeps, and more than one DHCP option carries comfortably.+ static let maximumDNSServers = 4/// Identifiers of host interfaces available for bridging (empty without the/// `com.apple.vm.networking` entitlement, e.g. in unsigned test binaries).@@ -91,40 +330,87 @@ public enum VPhoneNetworking {return available[0] // non-empty, guarded above}- /// Merge partial edits onto an existing config, validating the result.- /// A nil argument leaves that field unchanged.- public static func merge(- into current: NetworkConfig,- mode: NetworkMode?,- bridgeInterface: String?,- resolvesMacName: Bool? = nil,- ) throws -> NetworkConfig {- let newMode = mode ?? current.mode- if newMode == .hostOnly {- throw VPhoneNetworkingError.hostOnlyUnsupported+ // MARK: - Parsing++ /// `192.168.70.10/24`, or a bare address, which means /24.+ public static func parseAddress(_ text: String) throws -> (address: String, prefixLength: Int) {+ let parts = text.split(separator: "/", omittingEmptySubsequences: false)+ guard parts.count <= 2, let address = parts.first.flatMap({ VPhoneIPv4Address(dotted: String($0)) }) else {+ throw VPhoneNetworkingError.invalidAddress(field: "--ip", value: text)}- let newBridge: String?- if newMode == .bridged {- newBridge = try resolveBridgeInterface(requested: bridgeInterface, current: current.bridgeInterface)- } else {- if bridgeInterface != nil {- throw VPhoneNetworkingError.bridgeInterfaceWithoutBridgedMode+ guard parts.count == 2 else { return (address.description, 24) }+ guard let length = Int(parts[1]) else {+ throw VPhoneNetworkingError.invalidAddress(field: "--ip", value: text)+ }+ return (address.description, length)+ }++ /// `[tcp|udp:][host-address:]host-port:guest-port`.+ public static func parsePortForward(_ text: String) throws -> PortForward {+ var parts = text.split(separator: ":", omittingEmptySubsequences: false).map(String.init)+ var transport = PortForward.TransportProtocol.tcp+ if let first = parts.first, let named = PortForward.TransportProtocol(rawValue: first.lowercased()) {+ transport = named+ parts.removeFirst()+ }+ var hostAddress: String?+ if parts.count == 3 {+ guard let address = VPhoneIPv4Address(dotted: parts[0]) else {+ throw VPhoneNetworkingError.invalidPortForward(text)}- newBridge = current.bridgeInterface+ hostAddress = address.description+ parts.removeFirst()}- 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,- )+ guard parts.count == 2,+ let hostPort = Int(parts[0]), (1 ... 65535).contains(hostPort),+ let guestPort = Int(parts[1]), (1 ... 65535).contains(guestPort)+ else {+ throw VPhoneNetworkingError.invalidPortForward(text)+ }+ return PortForward(transport: transport, hostAddress: hostAddress, hostPort: hostPort, guestPort: guestPort)+ }++ /// The canonical spelling of a MAC, or an error naming the value.+ public static func normalizeMACAddress(_ text: String) throws -> String {+ guard let mac = VPhoneMACAddress(string: text), mac.isUnicast, !mac.isZero, mac != .gateway else {+ throw VPhoneNetworkingError.invalidMACAddress(text)+ }+ return mac.description+ }++ // MARK: - mDNS names++ /// The mDNS name `--mdns on` gives a VM: its name with everything but+ /// letters and digits turned into hyphens, as a DNS label allows.+ public static func localHostName(forVMName name: String) -> String {+ var label = ""+ for scalar in name.unicodeScalars {+ let allowed = scalar.isASCII && CharacterSet.alphanumerics.contains(scalar)+ if allowed {+ label.unicodeScalars.append(scalar)+ } else if !label.hasSuffix("-") {+ label += "-"+ }+ }+ label = String(label.trimmingCharacters(in: CharacterSet(charactersIn: "-")).prefix(63))+ label = label.trimmingCharacters(in: CharacterSet(charactersIn: "-"))+ return label.isEmpty ? "vphone" : label+ }++ /// `name`, if it is one DNS label: 1 to 63 letters, digits and hyphens,+ /// with no hyphen at either end. A trailing `.local` is dropped.+ public static func validLocalHostName(_ name: String) throws -> String {+ let label = name.lowercased().hasSuffix(".local") ? String(name.dropLast(6)) : name+ let allowed = label.unicodeScalars.allSatisfy { $0.isASCII && (CharacterSet.alphanumerics.contains($0) || $0 == "-") }+ guard (1 ... 63).contains(label.count), allowed, !label.hasPrefix("-"), !label.hasSuffix("-") else {+ throw VPhoneNetworkingError.invalidLocalHostName(name)+ }+ return label}// MARK: - The Mac's name in the guest- /// A name vphoned has the guest resolve locally (vphoned's- /// `GuestStaticNames`).+ /// A name vphoned has the guest resolve locally (`GuestStaticNames`).public struct StaticName: Equatable, Sendable {public let address: VPhoneIPv4Addresspublic let names: [String]@@ -140,17 +426,6 @@ public enum VPhoneNetworking {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>?@@ -168,81 +443,380 @@ public enum VPhoneNetworking {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.+ /// when the plan does not resolve the Mac's name 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.+ /// wins. See Research/Host/network_fixed_address.md.public static func macStaticNames(- _ cfg: NetworkConfig,+ plan: VPhoneNetworkPlan,macName: String?,- sharedNATHost: VPhoneIPv4Address,bridgedAddress: VPhoneIPv4Address? = nil,) -> [StaticName] {- guard cfg.resolvesMacName != false, let macName, !macName.isEmpty,- let address = macAddressForGuest(cfg, sharedNATHost: sharedNATHost, bridgedAddress: bridgedAddress)+ guard plan.resolvesMacName, let macName, !macName.isEmpty,+ let address = plan.macAddressForGuest ?? bridgedAddresselse { return [] }return [StaticName(address: address, names: ["\(macName).local"])]}- /// 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).+ // MARK: - Editing++ /// Merge partial edits onto an existing config, validating the result.+ /// A nil argument leaves that field unchanged.+ public static func merge(+ into current: NetworkConfig,+ mode: NetworkMode?,+ bridgeInterface: String?,+ resolvesMacName: Bool? = nil,+ ) throws -> NetworkConfig {+ try merge(+ into: current,+ edit: VPhoneNetworkEdit(mode: mode, bridgeInterface: bridgeInterface, resolvesMacName: resolvesMacName),+ )+ }++ public static func merge(+ into current: NetworkConfig,+ edit: VPhoneNetworkEdit,+ host: VPhoneNetworkHost = .current,+ ) throws -> NetworkConfig {+ let newMode = edit.mode ?? current.mode+ if newMode == .hostOnly {+ throw VPhoneNetworkingError.hostOnlyUnsupported+ }+ let newBridge: String?+ if newMode == .bridged {+ newBridge = try resolveBridgeInterface(requested: edit.bridgeInterface, current: current.bridgeInterface)+ } else {+ if edit.bridgeInterface != nil {+ throw VPhoneNetworkingError.bridgeInterfaceWithoutBridgedMode+ }+ newBridge = current.bridgeInterface+ }++ let mac: String = switch edit.mac {+ case nil: current.macAddress+ case .automatic: ""+ case .random: VPhoneMACAddress.randomLocallyAdministered().description+ case let .fixed(value): try normalizeMACAddress(value)+ }++ var ipv4 = current.ipv4+ switch edit.address {+ case nil:+ break+ case .dhcp:+ ipv4 = nil+ case let .fixed(address, prefixLength):+ // A gateway or resolver chosen for the old subnet means nothing on+ // a new one, so they follow the address only while it stays put.+ let sameSubnet = ipv4.map { old in+ old.prefixLength == prefixLength+ && subnet(of: old.address, prefixLength) == subnet(of: address, prefixLength)+ } ?? false+ ipv4 = IPv4Config(+ address: address,+ prefixLength: prefixLength,+ router: sameSubnet ? ipv4?.router : nil,+ dns: sameSubnet ? ipv4?.dns : nil,+ )+ }+ // Returning either to its default (`auto`) changes nothing without a+ // fixed address; naming one needs the address.+ if let router = edit.router {+ if let base = ipv4 {+ ipv4 = IPv4Config(address: base.address, prefixLength: base.prefixLength, router: router, dns: base.dns)+ } else if router != nil {+ throw VPhoneNetworkingError.settingWithoutAddress("--gateway")+ }+ }+ if let dns = edit.dns {+ let servers = dns.flatMap { $0.isEmpty ? nil : $0 }+ if let base = ipv4 {+ ipv4 = IPv4Config(address: base.address, prefixLength: base.prefixLength, router: base.router, dns: servers)+ } else if servers != nil {+ throw VPhoneNetworkingError.settingWithoutAddress("--dns")+ }+ }++ var forwards = edit.clearForwards ? [] : current.portForwards ?? []+ for name in edit.removeForwards {+ let before = forwards.count+ forwards.removeAll { forward in+ forward.description == name+ || String(forward.hostPort) == name+ || "\(forward.transport.rawValue):\(forward.hostPort)" == name+ || (try? parsePortForward(name)) == forward+ }+ if forwards.count == before {+ throw VPhoneNetworkingError.portForwardNotFound(name)+ }+ }+ // Asking again for a forward that is already there changes nothing.+ for forward in edit.addForwards where !forwards.contains(forward) {+ forwards.append(forward)+ }++ let merged = NetworkConfig(+ mode: newMode,+ macAddress: mac,+ bridgeInterface: newBridge,+ ipv4: ipv4,+ portForwards: forwards.isEmpty ? nil : forwards,+ localHostName: try edit.localHostName.map { try $0.map(validLocalHostName) } ?? current.localHostName,+ // On is the default, so it is stored as an absent key.+ resolvesMacName: edit.resolvesMacName.map { $0 ? nil : false } ?? current.resolvesMacName,+ )+ try validate(merged, host: host)+ return merged+ }++ private static func subnet(of address: String, _ prefixLength: Int) -> VPhoneIPv4Subnet? {+ VPhoneIPv4Address(dotted: address).flatMap { VPhoneIPv4Subnet(containing: $0, prefixLength: prefixLength) }+ }++ // MARK: - Validation++ /// The guest's addressing once defaults are filled in.+ struct ResolvedIPv4: Equatable {+ let address: VPhoneIPv4Address+ let subnet: VPhoneIPv4Subnet+ let router: VPhoneIPv4Address+ /// Empty when none were configured, which each mode reads its own way.+ let dns: [VPhoneIPv4Address]+ }++ static func resolve(_ ipv4: IPv4Config, mode: NetworkMode, host: VPhoneNetworkHost) throws -> ResolvedIPv4 {+ guard let address = VPhoneIPv4Address(dotted: ipv4.address) else {+ throw VPhoneNetworkingError.invalidAddress(field: "the guest address", value: ipv4.address)+ }+ guard (8 ... 30).contains(ipv4.prefixLength),+ let subnet = VPhoneIPv4Subnet(containing: address, prefixLength: ipv4.prefixLength)+ else {+ throw VPhoneNetworkingError.invalidPrefixLength(ipv4.prefixLength)+ }+ guard subnet.isAssignable(address) else {+ throw VPhoneNetworkingError.addressNotAssignable(address: ipv4.address, subnet: subnet.description)+ }+ if mode == .nat || mode == .tunnel, !subnet.isPrivate {+ throw VPhoneNetworkingError.addressNotPrivate(address: ipv4.address, mode: mode.rawValue)+ }++ // `nat` stays on the Mac's shared network, the one+ // `VZNATNetworkDeviceAttachment` uses, where the Mac is the gateway. A+ // vmnet network of the VM's own (`vmnet_network_create`, macOS 26)+ // would allow any subnet, but InternetSharing keeps such a subnet+ // reserved after the VM process exits, and later launches on it fail+ // (still 40 minutes on); see Research/Host/network_fixed_address.md.+ var defaultRouter = subnet.firstHost+ if mode == .nat {+ guard subnet == host.sharedNATSubnet else {+ throw VPhoneNetworkingError.natAddressOffSharedNetwork(+ address: ipv4.address,+ shared: host.sharedNATSubnet.description,+ )+ }+ defaultRouter = host.sharedNATHost+ }++ let router: VPhoneIPv4Address+ if let text = ipv4.router {+ guard let parsed = VPhoneIPv4Address(dotted: text) else {+ throw VPhoneNetworkingError.invalidAddress(field: "the gateway", value: text)+ }+ router = parsed+ } else {+ router = defaultRouter+ }+ if mode == .nat, router != defaultRouter {+ throw VPhoneNetworkingError.natRouterFixed(expected: defaultRouter.description, subnet: subnet.description)+ }+ guard subnet.isAssignable(router) else {+ throw VPhoneNetworkingError.routerNotAssignable(router: router.description, subnet: subnet.description)+ }+ guard router != address else {+ throw VPhoneNetworkingError.routerIsGuestAddress(address.description)+ }++ let dnsText = ipv4.dns ?? []+ guard dnsText.count <= maximumDNSServers else {+ throw VPhoneNetworkingError.tooManyDNSServers(dnsText.count)+ }+ let dns = try dnsText.map { text in+ guard let server = VPhoneIPv4Address(dotted: text) else {+ throw VPhoneNetworkingError.invalidAddress(field: "DNS", value: text)+ }+ return server+ }+ return ResolvedIPv4(address: address, subnet: subnet, router: router, dns: dns)+ }++ /// Throws when `cfg` cannot be realized on `host`. Runs when a config is+ /// edited and again at boot, because a hand-edited or imported+ /// `config.plist` reaches boot without going through an edit.+ public static func validate(_ cfg: NetworkConfig, host: VPhoneNetworkHost = .current) throws {+ _ = try plan(cfg, host: host)+ }++ static func validatePortForwards(_ forwards: [PortForward], mode: NetworkMode) throws {+ guard !forwards.isEmpty else { return }+ guard mode == .nat || mode == .tunnel else {+ throw VPhoneNetworkingError.portForwardUnsupported(mode: mode == .off ? "none" : mode.rawValue)+ }+ var seen: [PortForward] = []+ for forward in forwards {+ guard (1 ... 65535).contains(forward.hostPort), (1 ... 65535).contains(forward.guestPort),+ forward.hostAddress.map({ VPhoneIPv4Address(dotted: $0) != nil }) ?? true+ else {+ throw VPhoneNetworkingError.invalidPortForward(forward.description)+ }+ // Two listeners on one port clash when either takes every address.+ let clash = seen.contains { other in+ other.transport == forward.transport && other.hostPort == forward.hostPort+ && (other.listenAddress == forward.listenAddress+ || other.listenAddress == "0.0.0.0" || forward.listenAddress == "0.0.0.0")+ }+ if clash {+ throw VPhoneNetworkingError.duplicatePortForward("\(forward.transport.rawValue):\(forward.hostPort)")+ }+ seen.append(forward)+ }+ }++ // MARK: - Planning++ /// Decide how `cfg` is realized on `host`.///- /// The returned `backend` is non-nil only for `.tunnel`, where the network is- /// implemented in this process. It is a reference type whose sockets live as- /// long as the last holder, so the caller must keep it for the whole time the- /// VM runs, and should `start()` it once the VM does.- public static func makeNetworkDevice(_ cfg: NetworkConfig) throws- -> (device: VZVirtioNetworkDeviceConfiguration?, backend: VPhoneUserspaceNetwork?)- {+ /// The fixed address reaches the guest one of two ways. `tunnel` serves it+ /// over its own DHCP, so the guest stays on DHCP. Everywhere else the host+ /// has no say in the DHCP server, so vphoned writes the address into the+ /// guest's network preferences (`guestIPv4`).+ public static func plan(_ cfg: NetworkConfig, host: VPhoneNetworkHost = .current) throws -> VPhoneNetworkPlan {+ if cfg.mode == .hostOnly {+ throw VPhoneNetworkingError.hostOnlyUnsupported+ }+ let mac: VPhoneMACAddress? = cfg.macAddress.isEmpty+ ? nil+ : try VPhoneMACAddress(string: normalizeMACAddress(cfg.macAddress))+ let resolved = try cfg.ipv4.map { try resolve($0, mode: cfg.mode, host: host) }+ let forwards = cfg.portForwards ?? []+ try validatePortForwards(forwards, mode: cfg.mode)+ let localHostName = try cfg.localHostName.map(validLocalHostName)+ let resolvesMacName = cfg.resolvesMacName ?? true++ func manual(_ ipv4: ResolvedIPv4) -> VPhoneGuestIPv4Setting {+ .manual(+ address: ipv4.address,+ subnet: ipv4.subnet,+ router: ipv4.router,+ dns: ipv4.dns.isEmpty ? [ipv4.router] : ipv4.dns,+ )+ }+switch cfg.mode {- case .off:- return (nil, nil)case .hostOnly:throw VPhoneNetworkingError.hostOnlyUnsupported++ case .off:+ return VPhoneNetworkPlan(attachment: .none, macAddress: nil, guestIPv4: nil, portForwards: [], localHostName: localHostName,+ resolvesMacName: false, macAddressForGuest: nil, forwardingAddress: nil,+ )+case .nat:- let net = VZVirtioNetworkDeviceConfiguration()- net.attachment = VZNATNetworkDeviceAttachment()- return (net, nil)- case .tunnel:- let network = try VPhoneUserspaceNetwork()- let net = VZVirtioNetworkDeviceConfiguration()- net.attachment = network.networkAttachment- return (net, network)+ guard let resolved else {+ return VPhoneNetworkPlan(+ attachment: .sharedNAT, macAddress: mac, guestIPv4: .dhcp,+ portForwards: forwards, localHostName: localHostName,+ resolvesMacName: resolvesMacName, macAddressForGuest: host.sharedNATHost, forwardingAddress: nil,+ )+ }+ return VPhoneNetworkPlan(+ attachment: .sharedNAT, macAddress: mac, guestIPv4: manual(resolved),+ portForwards: forwards, localHostName: localHostName,+ resolvesMacName: resolvesMacName, macAddressForGuest: host.sharedNATHost, forwardingAddress: resolved.address,+ )+case .bridged:- guard let id = cfg.bridgeInterface else {+ guard let interface = cfg.bridgeInterface else {throw VPhoneNetworkingError.noBridgeInterfaces}+ return VPhoneNetworkPlan(+ attachment: .bridged(interface: interface), macAddress: mac,+ guestIPv4: resolved.map(manual) ?? .dhcp, portForwards: [], localHostName: localHostName,+ resolvesMacName: resolvesMacName, macAddressForGuest: nil, forwardingAddress: nil,+ )++ case .tunnel:+ let configuration = resolved.map {+ VPhoneUserspaceNetworkConfiguration(+ hostAddress: $0.router,+ guestAddress: $0.address,+ prefixLength: $0.subnet.prefixLength,+ dnsServers: $0.dns,+ )+ } ?? .default+ return VPhoneNetworkPlan(+ attachment: .tunnel(configuration), macAddress: mac, guestIPv4: .dhcp,+ portForwards: forwards, localHostName: localHostName,+ resolvesMacName: resolvesMacName, macAddressForGuest: configuration.hostAddress, forwardingAddress: configuration.guestAddress,+ )+ }+ }++ // MARK: - Devices++ /// The guest's NIC and whatever has to outlive it.+ public struct NetworkDevice {+ /// Nil for `.off`: no NIC at all.+ public let configuration: VZVirtioNetworkDeviceConfiguration?+ /// Non-nil only for `.tunnel`, where the network is implemented in this+ /// process. Its sockets live as long as the last holder, so the caller+ /// must keep it for the whole time the VM runs, and `start()` it once+ /// the VM does.+ public let userspaceNetwork: VPhoneUserspaceNetwork?+ }++ /// Build the VZ network device for a config, or nil for `.off` (no NIC).+ /// Throws if the config cannot be realized (missing bridge interface, hostOnly).+ public static func makeNetworkDevice(_ cfg: NetworkConfig) throws+ -> (device: VZVirtioNetworkDeviceConfiguration?, backend: VPhoneUserspaceNetwork?)+ {+ let device = try makeNetworkDevice(plan(cfg))+ return (device.configuration, device.userspaceNetwork)+ }++ public static func makeNetworkDevice(_ plan: VPhoneNetworkPlan) throws -> NetworkDevice {+ let attachment: VZNetworkDeviceAttachment+ var userspaceNetwork: VPhoneUserspaceNetwork?++ switch plan.attachment {+ case .none:+ return NetworkDevice(configuration: nil, userspaceNetwork: nil)+ case .sharedNAT:+ attachment = VZNATNetworkDeviceAttachment()+ case let .tunnel(configuration):+ let network = try VPhoneUserspaceNetwork(configuration: configuration)+ userspaceNetwork = network+ attachment = network.networkAttachment+ case let .bridged(id):guard let iface = VZBridgedNetworkInterface.networkInterfaces.first(where: { $0.identifier == id }) else {throw VPhoneNetworkingError.bridgeInterfaceNotFound(requested: id,available: availableBridgeInterfaces(),)}- let net = VZVirtioNetworkDeviceConfiguration()- net.attachment = VZBridgedNetworkDeviceAttachment(interface: iface)- return (net, nil)+ attachment = VZBridgedNetworkDeviceAttachment(interface: iface)+ }++ let device = VZVirtioNetworkDeviceConfiguration()+ device.attachment = attachment+ if let mac = plan.macAddress, let address = VZMACAddress(string: mac.description) {+ device.macAddress = address}+ return NetworkDevice(configuration: device, userspaceNetwork: userspaceNetwork)}}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swiftindex bf8caa9c..fcfebad3 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift@@ -166,13 +166,23 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {public struct NetworkConfig: Codable, Equatable, Sendable {public let mode: NetworkMode+ /// The guest NIC's MAC, `aa:bb:cc:dd:ee:ff`. Empty until first boot+ /// generates one and saves it here, so the guest keeps one identity+ /// (and one DHCP lease) across launches.public let macAddress: String/// Host interface identifier to bridge (bridged mode only); nil otherwise.public let bridgeInterface: String?+ /// A fixed guest address; nil leaves the address to DHCP. How each mode+ /// realizes it is in `VPhoneNetworking.plan`.+ public let ipv4: IPv4Config?+ /// Host ports carried into the guest. Nil and empty both forward nothing.+ public let portForwards: [PortForward]?+ /// The name the guest answers to as `<name>.local` over mDNS. Nil, the+ /// default, leaves the guest's own name alone.+ public let localHostName: 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`.+ /// guest's mDNSResponder. Nil means yes; see `VPhoneNetworking.plan`.public let resolvesMacName: Bool?public enum NetworkMode: String, Codable, Sendable {@@ -191,12 +201,103 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {public static let `default` = NetworkConfig(mode: .nat, macAddress: "")- public init(mode: NetworkMode, macAddress: String, bridgeInterface: String? = nil, resolvesMacName: Bool? = nil) {+ public init(+ mode: NetworkMode,+ macAddress: String,+ bridgeInterface: String? = nil,+ ipv4: IPv4Config? = nil,+ portForwards: [PortForward]? = nil,+ localHostName: String? = nil,+ resolvesMacName: Bool? = nil,+ ) {self.mode = modeself.macAddress = macAddressself.bridgeInterface = bridgeInterface+ self.ipv4 = ipv4+ self.portForwards = portForwards+ self.localHostName = localHostNameself.resolvesMacName = resolvesMacName}++ /// The same configuration with one field replaced.+ public func with(+ mode: NetworkMode? = nil,+ macAddress: String? = nil,+ bridgeInterface: String?? = nil,+ ipv4: IPv4Config?? = nil,+ portForwards: [PortForward]?? = nil,+ localHostName: String?? = nil,+ resolvesMacName: Bool?? = nil,+ ) -> NetworkConfig {+ NetworkConfig(+ mode: mode ?? self.mode,+ macAddress: macAddress ?? self.macAddress,+ bridgeInterface: bridgeInterface ?? self.bridgeInterface,+ ipv4: ipv4 ?? self.ipv4,+ portForwards: portForwards ?? self.portForwards,+ localHostName: localHostName ?? self.localHostName,+ resolvesMacName: resolvesMacName ?? self.resolvesMacName,+ )+ }++ /// A fixed IPv4 configuration for the guest's NIC.+ ///+ /// Addresses are kept as dotted strings so `config.plist` stays readable+ /// and editable by hand. `VPhoneNetworking.validate` is what gives them+ /// meaning, and it runs both when the config is edited and at boot.+ public struct IPv4Config: Codable, Equatable, Sendable {+ public let address: String+ public let prefixLength: Int+ /// The default route. Nil means the first host of the subnet, which+ /// is where `nat` and `tunnel` put the host.+ public let router: String?+ /// Resolvers handed to the guest. Nil or empty means the router.+ public let dns: [String]?++ public init(address: String, prefixLength: Int, router: String? = nil, dns: [String]? = nil) {+ self.address = address+ self.prefixLength = prefixLength+ self.router = router+ self.dns = dns+ }+ }++ /// One host port carried to a guest port.+ public struct PortForward: Codable, Equatable, Hashable, Sendable, CustomStringConvertible {+ public enum TransportProtocol: String, Codable, Sendable, CaseIterable {+ case tcp+ case udp+ }++ public let transport: TransportProtocol+ /// The host address to listen on. Nil is loopback only, so a guest+ /// service is not on the LAN unless someone asks for that.+ public let hostAddress: String?+ public let hostPort: Int+ public let guestPort: Int++ private enum CodingKeys: String, CodingKey {+ case transport = "protocol"+ case hostAddress, hostPort, guestPort+ }++ public init(transport: TransportProtocol = .tcp, hostAddress: String? = nil, hostPort: Int, guestPort: Int) {+ self.transport = transport+ self.hostAddress = hostAddress+ self.hostPort = hostPort+ self.guestPort = guestPort+ }++ /// The address actually listened on.+ public var listenAddress: String {+ hostAddress ?? "127.0.0.1"+ }++ /// `tcp:127.0.0.1:8022:22`, the form `--forward` accepts.+ public var description: String {+ "\(transport.rawValue):\(listenAddress):\(hostPort):\(guestPort)"+ }+ }}public struct ROMImages: Codable, Sendable {@@ -252,9 +353,8 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {////// Replaces `scripts/vm_manifest.py`. Everything not named here is a/// default that the guest or the framework fills in later:- /// `machineIdentifier` is empty until first boot persists one, and- /// `macAddress` is empty so Virtualization assigns it — forcing a MAC- /// breaks guest networking.+ /// `machineIdentifier` and `macAddress` are empty until first boot+ /// generates and persists them.////// `platformFusing` stays nil unless asked for, which leaves the key out/// of the plist entirely and lets the host OS decide.diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swiftindex 6a6b9b14..6533b701 100644--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleOperationsTests.swift@@ -202,6 +202,61 @@ struct BundleOperationsTests {#expect(try lib.bundle(named: "bad").manifest.networkConfig.mode == .nat)}+ /// A fixed address and forwards are written to config.plist and read back.+ @Test func `update config saves address and forwards`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let rom = try fakeROM(); let seprom = try fakeROM()+ defer { try? FileManager.default.removeItem(at: rom); try? FileManager.default.removeItem(at: seprom) }+ let lib = VPhoneLibrary(root: root)+ _ = try VPhoneBundleOperations.create(+ .init(name: "fixed", cpuCount: 2, memoryMB: 2048, diskSizeGB: 1, romSource: rom, sepromSource: seprom),+ in: lib,+ )++ _ = try VPhoneBundleOperations.updateConfig(+ bundleNamed: "fixed",+ in: lib,+ cpuCount: nil,+ memoryMB: nil,+ networkMode: .tunnel,+ networkEdit: VPhoneNetworkEdit(+ address: .fixed(address: "10.20.0.5", prefixLength: 16),+ addForwards: [.init(hostPort: 8022, guestPort: 22)],+ ),+ )+ let network = try lib.bundle(named: "fixed").manifest.networkConfig+ #expect(network.mode == .tunnel)+ #expect(network.ipv4 == .init(address: "10.20.0.5", prefixLength: 16))+ #expect(network.portForwards == [.init(hostPort: 8022, guestPort: 22)])+ }++ /// A name `--mdns on` derived follows a rename; a hand-picked one stays.+ @Test func `rename carries a derived mDNS name`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let rom = try fakeROM(); let seprom = try fakeROM()+ defer { try? FileManager.default.removeItem(at: rom); try? FileManager.default.removeItem(at: seprom) }+ let lib = VPhoneLibrary(root: root)+ for name in ["lab_a", "lab_b"] {+ _ = try VPhoneBundleOperations.create(+ .init(name: name, cpuCount: 2, memoryMB: 2048, diskSizeGB: 1, romSource: rom, sepromSource: seprom),+ in: lib,+ )+ }+ _ = try VPhoneBundleOperations.updateConfig(+ bundleNamed: "lab_a", in: lib, cpuCount: nil, memoryMB: nil,+ networkEdit: VPhoneNetworkEdit(localHostName: .some(VPhoneNetworking.localHostName(forVMName: "lab_a"))),+ )+ _ = try VPhoneBundleOperations.updateConfig(+ bundleNamed: "lab_b", in: lib, cpuCount: nil, memoryMB: nil,+ networkEdit: VPhoneNetworkEdit(localHostName: .some("bench")),+ )+ #expect(try VPhoneBundleOperations.rename(bundleNamed: "lab_a", to: "phone_a", in: lib).manifest.networkConfig.localHostName == "phone-a")+ #expect(try VPhoneBundleOperations.rename(bundleNamed: "lab_b", to: "phone_b", in: lib).manifest.networkConfig.localHostName == "bench")+ #expect(try lib.bundle(named: "phone_a").manifest.networkConfig.localHostName == "phone-a")+ }+@Test func `rename then delete`() throws {let root = try makeRoot()defer { try? FileManager.default.removeItem(at: root) }diff --git a/VPhoneKit/VPhoneCoreKitTests/Network/VPhonePortForwardingTests.swift b/VPhoneKit/VPhoneCoreKitTests/Network/VPhonePortForwardingTests.swiftnew file mode 100644index 00000000..b382c574--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Network/VPhonePortForwardingTests.swift@@ -0,0 +1,344 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// Host ports carried into the guest, over real sockets: the direct relay+/// `nat` uses, and the tunnel's handoff of a host client into its own stack.+struct VPhonePortForwardingTests {+ typealias PortForward = VPhoneVirtualMachineManifest.NetworkConfig.PortForward++ // MARK: - Sockets++ /// A loopback port nobody holds right now.+ private func freePort(_ type: Int32) throws -> UInt16 {+ let descriptor = socket(AF_INET, type, 0)+ defer { close(descriptor) }+ var address = VPhonePortForwarder.socketAddress(VPhoneIPv4Address(127, 0, 0, 1), port: 0)+ 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)+ }+ }+ }+ return UInt16(bigEndian: address.sin_port)+ }++ private func boundSocket(_ type: Int32, port: UInt16 = 0) throws -> (Int32, UInt16) {+ let descriptor = socket(AF_INET, type, 0)+ var one: Int32 = 1+ _ = setsockopt(descriptor, SOL_SOCKET, SO_REUSEADDR, &one, socklen_t(MemoryLayout<Int32>.size))+ var address = VPhonePortForwarder.socketAddress(VPhoneIPv4Address(127, 0, 0, 1), port: port)+ 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)+ }+ }+ }+ var timeout = timeval(tv_sec: 3, tv_usec: 0)+ _ = setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ return (descriptor, UInt16(bigEndian: address.sin_port))+ }++ private func connectLoopback(_ type: Int32, port: UInt16) throws -> Int32 {+ let descriptor = socket(AF_INET, type, 0)+ var timeout = timeval(tv_sec: 3, tv_usec: 0)+ _ = setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ var address = VPhonePortForwarder.socketAddress(VPhoneIPv4Address(127, 0, 0, 1), port: port)+ let result = withUnsafePointer(to: &address) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_in>.size))+ }+ }+ guard result == 0 else {+ close(descriptor)+ throw POSIXError(.ECONNREFUSED)+ }+ return descriptor+ }++ private func sendString(_ text: String, to descriptor: Int32) {+ _ = Array(text.utf8).withUnsafeBytes { send(descriptor, $0.baseAddress, $0.count, 0) }+ }++ private func receiveString(from descriptor: Int32) -> String? {+ var buffer = [UInt8](repeating: 0, count: 4096)+ let count = recv(descriptor, &buffer, buffer.count, 0)+ return count > 0 ? String(decoding: buffer[0 ..< count], as: UTF8.self) : nil+ }++ // MARK: - Direct (nat)++ /// A client of the host port reaches the "guest" service and hears back,+ /// in both directions, and the end of the stream gets through too.+ @Test func `TCP is relayed to the guest address`() throws {+ let (server, guestPort) = try boundSocket(SOCK_STREAM)+ defer { close(server) }+ #expect(listen(server, 4) == 0)++ let hostPort = try freePort(SOCK_STREAM)+ let forwarder = VPhonePortForwarder(+ forwards: [PortForward(hostPort: Int(hostPort), guestPort: Int(guestPort))],+ destination: .direct(VPhoneIPv4Address(127, 0, 0, 1)),+ )+ #expect(forwarder.start().isEmpty)+ defer { forwarder.stop() }++ let client = try connectLoopback(SOCK_STREAM, port: hostPort)+ defer { close(client) }+ let accepted = accept(server, nil, nil)+ try #require(accepted >= 0, "the relay never reached the guest service")+ defer { close(accepted) }+ var timeout = timeval(tv_sec: 3, tv_usec: 0)+ _ = setsockopt(accepted, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))++ sendString("hello", to: client)+ #expect(receiveString(from: accepted) == "hello")+ sendString("world", to: accepted)+ #expect(receiveString(from: client) == "world")++ shutdown(client, SHUT_WR)+ var byte: UInt8 = 0+ #expect(recv(accepted, &byte, 1, 0) == 0, "the client's FIN did not reach the guest")+ }++ @Test func `UDP is relayed to the guest address and back`() throws {+ let (server, guestPort) = try boundSocket(SOCK_DGRAM)+ defer { close(server) }++ let hostPort = try freePort(SOCK_DGRAM)+ let forwarder = VPhonePortForwarder(+ forwards: [PortForward(transport: .udp, hostPort: Int(hostPort), guestPort: Int(guestPort))],+ destination: .direct(VPhoneIPv4Address(127, 0, 0, 1)),+ )+ #expect(forwarder.start().isEmpty)+ defer { forwarder.stop() }++ let client = try connectLoopback(SOCK_DGRAM, port: hostPort)+ defer { close(client) }+ sendString("ping", to: client)++ var buffer = [UInt8](repeating: 0, count: 64)+ var from = sockaddr_in()+ var length = socklen_t(MemoryLayout<sockaddr_in>.size)+ let count = withUnsafeMutablePointer(to: &from) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ recvfrom(server, &buffer, buffer.count, 0, $0, &length)+ }+ }+ try #require(count > 0, "the datagram never reached the guest service")+ #expect(String(decoding: buffer[0 ..< count], as: UTF8.self) == "ping")++ _ = Array("pong".utf8).withUnsafeBytes { raw in+ withUnsafePointer(to: &from) { pointer in+ pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {+ sendto(server, raw.baseAddress, raw.count, 0, $0, length)+ }+ }+ }+ #expect(receiveString(from: client) == "pong")+ }++ /// Before a DHCP guest reports an address there is nowhere to go, so the+ /// client is turned away instead of hanging.+ @Test func `a client is closed while the guest address is unknown`() throws {+ let hostPort = try freePort(SOCK_STREAM)+ let forwarder = VPhonePortForwarder(+ forwards: [PortForward(hostPort: Int(hostPort), guestPort: 22)],+ destination: .direct(nil),+ )+ #expect(forwarder.start().isEmpty)+ defer { forwarder.stop() }++ let client = try connectLoopback(SOCK_STREAM, port: hostPort)+ defer { close(client) }+ var byte: UInt8 = 0+ #expect(recv(client, &byte, 1, 0) <= 0)+ }++ @Test func `a port already taken is reported, not fatal`() throws {+ let (holder, port) = try boundSocket(SOCK_STREAM)+ defer { close(holder) }+ #expect(listen(holder, 1) == 0)+ let forwarder = VPhonePortForwarder(+ forwards: [PortForward(hostPort: Int(port), guestPort: 22)],+ destination: .direct(VPhoneIPv4Address(127, 0, 0, 1)),+ )+ let failures = forwarder.start()+ defer { forwarder.stop() }+ #expect(failures.count == 1)+ }++ // MARK: - Tunnel++ 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+ }+ }++ 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 host client becomes a connection the guest accepts from the gateway:+ /// SYN out, SYN-ACK back, then data both ways.+ @Test func `a forwarded client reaches the guest through the tunnel`() throws {+ let link = try GuestLink()+ link.network.start()+ defer { link.network.stop() }++ // The guest has to have said something before it can be addressed.+ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 50000, destinationPort: 9, sequenceNumber: 1, acknowledgmentNumber: 0,+ flags: VPhoneTCPFlags.rst, windowSize: 0,+ )))++ var pair: [Int32] = [-1, -1]+ try #require(socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0)+ let client = pair[0]+ defer { close(client) }+ var timeout = timeval(tv_sec: 3, tv_usec: 0)+ _ = setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ usleep(50000)+ link.network.acceptInbound(tcp: pair[1], guestPort: 22)++ let syn = try #require(link.readSegment(), "no SYN reached the guest")+ #expect(syn.hasSYN && !syn.hasACK)+ #expect(syn.destinationPort == 22)++ let guestSequence: UInt32 = 7000+ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 22, destinationPort: syn.sourcePort,+ sequenceNumber: guestSequence, acknowledgmentNumber: syn.sequenceNumber &+ 1,+ flags: VPhoneTCPFlags.syn | VPhoneTCPFlags.ack, windowSize: 65535, advertisedMSS: 1460,+ )))+ let ack = try #require(link.readSegment(), "the handshake was not completed")+ #expect(ack.hasACK && !ack.hasSYN)+ #expect(ack.acknowledgmentNumber == guestSequence &+ 1)++ sendString("hello", to: client)+ let data = try #require(link.readSegment(), "the client's bytes did not reach the guest")+ #expect(String(decoding: data.payload, as: UTF8.self) == "hello")++ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 22, destinationPort: syn.sourcePort,+ sequenceNumber: guestSequence &+ 1, acknowledgmentNumber: data.sequenceNumber &+ UInt32(data.payload.count),+ flags: VPhoneTCPFlags.ack | VPhoneTCPFlags.psh, windowSize: 65535, payload: Array("world".utf8),+ )))+ #expect(receiveString(from: client) == "world")+ }++ /// The gateway stands for the Mac: a guest connection to it lands on the+ /// Mac's loopback.+ @Test func `a guest connection to the gateway reaches the Mac's loopback`() throws {+ let (server, port) = try boundSocket(SOCK_STREAM)+ defer { close(server) }+ #expect(listen(server, 4) == 0)++ 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)+ }++ /// A refused connection is refused at once: the RST acknowledges the+ /// guest's SYN, or the guest would ignore it and retry until it timed out.+ @Test func `a refused connection resets the guest at once`() throws {+ let closedPort = try freePort(SOCK_STREAM)+ 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)+ }++ /// Nothing listening in the guest: its RST ends the client's connection.+ @Test func `a guest refusal closes the client`() throws {+ let link = try GuestLink()+ link.network.start()+ defer { link.network.stop() }+ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 50000, destinationPort: 9, sequenceNumber: 1, acknowledgmentNumber: 0,+ flags: VPhoneTCPFlags.rst, windowSize: 0,+ )))++ var pair: [Int32] = [-1, -1]+ try #require(socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0)+ let client = pair[0]+ defer { close(client) }+ var timeout = timeval(tv_sec: 3, tv_usec: 0)+ _ = setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size))+ usleep(50000)+ link.network.acceptInbound(tcp: pair[1], guestPort: 23)++ let syn = try #require(link.readSegment())+ link.write(guestFrame(VPhoneTCPSegment(+ sourcePort: 23, destinationPort: syn.sourcePort,+ sequenceNumber: 0, acknowledgmentNumber: syn.sequenceNumber &+ 1,+ flags: VPhoneTCPFlags.rst | VPhoneTCPFlags.ack, windowSize: 0,+ )))+ var byte: UInt8 = 0+ #expect(recv(client, &byte, 1, 0) == 0)+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneUserspaceNetworkIntegrationTests.swift b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneUserspaceNetworkIntegrationTests.swiftindex e704b77e..6723cf5b 100644--- a/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneUserspaceNetworkIntegrationTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Network/VPhoneUserspaceNetworkIntegrationTests.swift@@ -184,6 +184,42 @@ struct VPhoneUserspaceNetworkIntegrationTests {#expect(ackMessage.messageType == .ack)}+ /// A VM's fixed address replaces the default: the lease, the mask and the+ /// resolvers all come from its configuration.+ @Test func `a configured address is what DHCP hands out`() throws {+ let custom = VPhoneUserspaceNetworkConfiguration(+ hostAddress: VPhoneIPv4Address(10, 20, 0, 1),+ guestAddress: VPhoneIPv4Address(10, 20, 0, 5),+ prefixLength: 16,+ dnsServers: [VPhoneIPv4Address(1, 1, 1, 1), VPhoneIPv4Address(9, 9, 9, 9)],+ )+ let link = try GuestLink(configuration: custom)+ link.start()+ defer { link.stop() }++ link.write(dhcpFrame(type: .discover))+ let offer = try #require(link.read(), "no offer came back through the loop")+ let ethernet = try #require(VPhoneEthernetFrame(bytes: offer))+ let packet = try #require(VPhoneIPv4Packet(bytes: ethernet.payload))+ let datagram = try #require(VPhoneUDPDatagram(bytes: packet.payload))+ #expect(Array(datagram.payload[16 ..< 20]) == [10, 20, 0, 5])+ let options = Array(datagram.payload[240...])+ func option(_ code: UInt8) -> [UInt8]? {+ var index = 0+ while index + 1 < options.count, options[index] != 255 {+ let length = Int(options[index + 1])+ if options[index] == code {+ return Array(options[(index + 2) ..< (index + 2 + length)])+ }+ index += 2 + length+ }+ return nil+ }+ #expect(option(1) == [255, 255, 0, 0])+ #expect(option(3) == [10, 20, 0, 1])+ #expect(option(6) == [1, 1, 1, 1, 9, 9, 9, 9])+ }+/// ARP and ICMP come back too -- they are the guest's other two ways of/// finding out whether the link is alive at all.@Test func `ARP and ping are answered through the real frame loop`() throws {diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swiftindex 32a7424f..c4135ba3 100644--- a/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Support/MacNameTests.swift@@ -2,37 +2,20 @@ import Foundationimport Testing@testable import VPhoneCoreKit-/// This Mac's `.local` name in the guest: where it points in each mode, and-/// how it is turned off.+/// This Mac's `.local` name in the guest: how it is turned off and stored.+/// Where it points in each mode is in `NetworkPlanTests`.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)- }+ private static let sharedSubnet = VPhoneIPv4Subnet(containing: VPhoneIPv4Address(192, 168, 64, 1), prefixLength: 24)!+ private let host = VPhoneNetworkHost(sharedNATSubnet: sharedSubnet, sharedNATHost: VPhoneIPv4Address(192, 168, 64, 1))/// 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)+ #expect(VPhoneNetworking.macStaticNames(plan: try VPhoneNetworking.plan(off, host: host), macName: "Lab-Mac").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)diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swiftnew file mode 100644index 00000000..f856ede2--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift@@ -0,0 +1,406 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++/// Editing, validating and planning a VM's network: fixed addresses, MACs and+/// port forwards, per mode and per host.+struct NetworkPlanTests {+ typealias NetworkConfig = VPhoneVirtualMachineManifest.NetworkConfig+ typealias IPv4Config = NetworkConfig.IPv4Config+ typealias PortForward = NetworkConfig.PortForward++ private static let sharedSubnet = VPhoneIPv4Subnet(containing: VPhoneIPv4Address(192, 168, 64, 1), prefixLength: 24)!+ private let host = VPhoneNetworkHost(sharedNATSubnet: sharedSubnet, sharedNATHost: VPhoneIPv4Address(192, 168, 64, 1))++ private func config(_ mode: NetworkConfig.NetworkMode, ip: IPv4Config? = nil, forwards: [PortForward]? = nil, mac: String = "") -> NetworkConfig {+ NetworkConfig(mode: mode, macAddress: mac, bridgeInterface: mode == .bridged ? "en0" : nil, ipv4: ip, portForwards: forwards)+ }++ // MARK: - Parsing++ @Test func `addresses parse with and without a prefix`() throws {+ #expect(try VPhoneNetworking.parseAddress("192.168.64.50") == ("192.168.64.50", 24))+ #expect(try VPhoneNetworking.parseAddress("10.0.5.9/16") == ("10.0.5.9", 16))+ #expect(throws: VPhoneNetworkingError.self) { _ = try VPhoneNetworking.parseAddress("192.168.64") }+ #expect(throws: VPhoneNetworkingError.self) { _ = try VPhoneNetworking.parseAddress("192.168.64.5/x") }+ }++ @Test func `port forwards parse in every spelling`() throws {+ #expect(try VPhoneNetworking.parsePortForward("8022:22") == PortForward(hostPort: 8022, guestPort: 22))+ #expect(try VPhoneNetworking.parsePortForward("udp:5353:53") == PortForward(transport: .udp, hostPort: 5353, guestPort: 53))+ #expect(+ try VPhoneNetworking.parsePortForward("tcp:0.0.0.0:8080:80")+ == PortForward(transport: .tcp, hostAddress: "0.0.0.0", hostPort: 8080, guestPort: 80),+ )+ #expect(try VPhoneNetworking.parsePortForward("8022:22").description == "tcp:127.0.0.1:8022:22")+ for bad in ["22", "tcp:0:22", "tcp:8022:70000", "sctp:1:2", "x.y:1:2"] {+ #expect(throws: VPhoneNetworkingError.self) { _ = try VPhoneNetworking.parsePortForward(bad) }+ }+ }++ @Test func `MAC addresses are normalized and screened`() throws {+ #expect(try VPhoneNetworking.normalizeMACAddress("02-AA-bb-0C-dd-EE") == "02:aa:bb:0c:dd:ee")+ // Multicast, all zero, malformed, and the tunnel gateway's own.+ for bad in ["01:00:5e:00:00:01", "00:00:00:00:00:00", "02:aa:bb", "02:00:00:00:00:01"] {+ #expect(throws: VPhoneNetworkingError.self) { _ = try VPhoneNetworking.normalizeMACAddress(bad) }+ }+ let random = VPhoneMACAddress.randomLocallyAdministered()+ #expect(random.isUnicast)+ #expect(random.bytes[0] & 0x02 == 0x02)+ }++ @Test func `subnets know their edges`() throws {+ let subnet = try #require(VPhoneIPv4Subnet(containing: VPhoneIPv4Address(10, 1, 2, 3), prefixLength: 16))+ #expect(subnet.description == "10.1.0.0/16")+ #expect(subnet.mask == VPhoneIPv4Address(255, 255, 0, 0))+ #expect(subnet.broadcast == VPhoneIPv4Address(10, 1, 255, 255))+ #expect(subnet.firstHost == VPhoneIPv4Address(10, 1, 0, 1))+ #expect(!subnet.isAssignable(subnet.network))+ #expect(!subnet.isAssignable(subnet.broadcast))+ #expect(subnet.isPrivate)+ #expect(VPhoneIPv4Subnet(containing: VPhoneIPv4Address(8, 8, 8, 8), prefixLength: 24)?.isPrivate == false)+ #expect(VPhoneIPv4Subnet(containing: .any, mask: VPhoneIPv4Address(255, 0, 255, 0)) == nil)+ }++ // MARK: - nat++ /// On the shared network the guest keeps the shared gateway, and vphoned+ /// is asked to hold the address; no network of its own is needed.+ @Test func `a nat address on the shared network is set in the guest`() throws {+ let plan = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "192.168.64.50", prefixLength: 24)), host: host)+ #expect(plan.attachment == .sharedNAT)+ #expect(plan.forwardingAddress == VPhoneIPv4Address(192, 168, 64, 50))+ guard case let .manual(address, subnet, router, dns) = plan.guestIPv4 else {+ Issue.record("expected a manual setting, got \(String(describing: plan.guestIPv4))")+ return+ }+ #expect(address == VPhoneIPv4Address(192, 168, 64, 50))+ #expect(subnet.mask == VPhoneIPv4Address(255, 255, 255, 0))+ #expect(router == VPhoneIPv4Address(192, 168, 64, 1))+ #expect(dns == [router])+ }++ /// Only the shared network: a subnet of the VM's own stays reserved after+ /// the VM exits, so it would work for one launch.+ @Test func `a nat address off the shared network is refused`() {+ #expect(throws: VPhoneNetworkingError.natAddressOffSharedNetwork(address: "192.168.70.10", shared: "192.168.64.0/24")) {+ _ = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "192.168.70.10", prefixLength: 24)), host: host)+ }+ #expect(throws: VPhoneNetworkingError.natAddressOffSharedNetwork(address: "192.168.64.50", shared: "192.168.64.0/24")) {+ _ = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "192.168.64.50", prefixLength: 16)), host: host)+ }+ }++ /// A Mac whose shared network was moved in vmnet's preferences.+ @Test func `a moved shared network is followed`() throws {+ let moved = try VPhoneNetworkHost(+ sharedNATSubnet: #require(VPhoneIPv4Subnet(containing: VPhoneIPv4Address(10, 0, 5, 1), prefixLength: 24)),+ sharedNATHost: VPhoneIPv4Address(10, 0, 5, 1),+ )+ let plan = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "10.0.5.20", prefixLength: 24)), host: moved)+ guard case let .manual(_, _, router, _) = plan.guestIPv4 else {+ Issue.record("expected a manual setting")+ return+ }+ #expect(router == VPhoneIPv4Address(10, 0, 5, 1))+ }++ @Test func `nat refuses a gateway the host does not hold`() {+ #expect(throws: VPhoneNetworkingError.natRouterFixed(expected: "192.168.64.1", subnet: "192.168.64.0/24")) {+ _ = try VPhoneNetworking.plan(+ config(.nat, ip: IPv4Config(address: "192.168.64.50", prefixLength: 24, router: "192.168.64.2")),+ host: host,+ )+ }+ }++ @Test func `nat refuses public and unusable addresses`() {+ #expect(throws: VPhoneNetworkingError.addressNotPrivate(address: "8.8.8.8", mode: "nat")) {+ _ = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "8.8.8.8", prefixLength: 24)), host: host)+ }+ #expect(throws: VPhoneNetworkingError.addressNotAssignable(address: "192.168.64.255", subnet: "192.168.64.0/24")) {+ _ = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "192.168.64.255", prefixLength: 24)), host: host)+ }+ #expect(throws: VPhoneNetworkingError.routerIsGuestAddress("192.168.64.1")) {+ _ = try VPhoneNetworking.plan(config(.nat, ip: IPv4Config(address: "192.168.64.1", prefixLength: 24)), host: host)+ }+ }++ @Test func `nat without an address stays on DHCP`() throws {+ let plan = try VPhoneNetworking.plan(config(.nat, forwards: [PortForward(hostPort: 8022, guestPort: 22)]), host: host)+ #expect(plan.attachment == .sharedNAT)+ #expect(plan.guestIPv4 == .dhcp)+ // Forwards follow the address the guest reports.+ #expect(plan.forwardingAddress == nil)+ #expect(plan.portForwards.count == 1)+ }++ // MARK: - tunnel, bridged, none++ /// The tunnel serves the address itself, so the guest stays on DHCP.+ @Test func `a tunnel address is served by the tunnel's DHCP`() throws {+ let plan = try VPhoneNetworking.plan(+ config(.tunnel, ip: IPv4Config(address: "10.20.0.5", prefixLength: 16, dns: ["1.1.1.1"])),+ host: host,+ )+ guard case let .tunnel(configuration) = plan.attachment else {+ Issue.record("expected tunnel")+ return+ }+ #expect(configuration.guestAddress == VPhoneIPv4Address(10, 20, 0, 5))+ #expect(configuration.hostAddress == VPhoneIPv4Address(10, 20, 0, 1))+ #expect(configuration.subnet.mask == VPhoneIPv4Address(255, 255, 0, 0))+ #expect(configuration.advertisedDNSServers == [VPhoneIPv4Address(1, 1, 1, 1)])+ #expect(plan.guestIPv4 == .dhcp)+ #expect(plan.forwardingAddress == configuration.guestAddress)+ }++ @Test func `a tunnel without an address keeps the default`() throws {+ let plan = try VPhoneNetworking.plan(config(.tunnel), host: host)+ #expect(plan.attachment == .tunnel(.default))+ #expect(VPhoneUserspaceNetworkConfiguration.default.advertisedDNSServers == [VPhoneIPv4Address(192, 168, 127, 1)])+ }++ @Test func `bridged takes any address and the gateway it is given`() throws {+ let plan = try VPhoneNetworking.plan(+ config(.bridged, ip: IPv4Config(address: "203.0.113.20", prefixLength: 24, router: "203.0.113.254", dns: ["203.0.113.53"])),+ host: host,+ )+ #expect(plan.attachment == .bridged(interface: "en0"))+ guard case let .manual(_, _, router, dns) = plan.guestIPv4 else {+ Issue.record("expected a manual setting")+ return+ }+ #expect(router == VPhoneIPv4Address(203, 0, 113, 254))+ #expect(dns == [VPhoneIPv4Address(203, 0, 113, 53)])+ }++ @Test func `forwards are refused where they cannot work`() {+ let forward = [PortForward(hostPort: 8022, guestPort: 22)]+ #expect(throws: VPhoneNetworkingError.portForwardUnsupported(mode: "bridged")) {+ _ = try VPhoneNetworking.plan(config(.bridged, forwards: forward), host: host)+ }+ #expect(throws: VPhoneNetworkingError.portForwardUnsupported(mode: "none")) {+ _ = try VPhoneNetworking.plan(config(.off, forwards: forward), host: host)+ }+ }++ @Test func `a host port is forwarded once per address`() {+ let clashing = [+ PortForward(hostPort: 8022, guestPort: 22),+ PortForward(hostAddress: "0.0.0.0", hostPort: 8022, guestPort: 2222),+ ]+ #expect(throws: VPhoneNetworkingError.duplicatePortForward("tcp:8022")) {+ _ = try VPhoneNetworking.plan(config(.nat, forwards: clashing), host: host)+ }+ let distinct = [+ PortForward(hostPort: 8022, guestPort: 22),+ PortForward(transport: .udp, hostPort: 8022, guestPort: 22),+ ]+ #expect(throws: Never.self) { _ = try VPhoneNetworking.plan(config(.nat, forwards: distinct), host: host) }+ }++ @Test func `none plans no device`() throws {+ let plan = try VPhoneNetworking.plan(config(.off, ip: IPv4Config(address: "192.168.64.50", prefixLength: 24)), host: host)+ #expect(plan.attachment == .none)+ #expect(plan.guestIPv4 == nil)+ }++ // MARK: - Editing++ @Test func `edits set, keep and clear the address`() throws {+ var current = try VPhoneNetworking.merge(+ into: .default,+ edit: VPhoneNetworkEdit(address: .fixed(address: "192.168.64.50", prefixLength: 24), dns: .some(["1.1.1.1"])),+ host: host,+ )+ #expect(current.ipv4 == IPv4Config(address: "192.168.64.50", prefixLength: 24, dns: ["1.1.1.1"]))++ // A new address on the same subnet keeps the resolvers.+ current = try VPhoneNetworking.merge(+ into: current,+ edit: VPhoneNetworkEdit(address: .fixed(address: "192.168.64.60", prefixLength: 24)),+ host: host,+ )+ #expect(current.ipv4?.dns == ["1.1.1.1"])++ // A new subnet drops them (tunnel, which takes any private subnet).+ current = try VPhoneNetworking.merge(+ into: current,+ edit: VPhoneNetworkEdit(mode: .tunnel, address: .fixed(address: "192.168.70.10", prefixLength: 24)),+ host: host,+ )+ #expect(current.ipv4?.dns == nil)++ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(address: .dhcp), host: host)+ #expect(current.ipv4 == nil)+ }++ @Test func `gateway and DNS need an address`() {+ #expect(throws: VPhoneNetworkingError.settingWithoutAddress("--gateway")) {+ _ = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(router: .some("192.168.64.1")), host: host)+ }+ #expect(throws: VPhoneNetworkingError.settingWithoutAddress("--dns")) {+ _ = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(dns: .some(["1.1.1.1"])), host: host)+ }+ }++ /// `--gateway auto` and `--dns auto` on a DHCP machine have nothing to undo.+ @Test func `returning the gateway and DNS to their defaults needs no address`() throws {+ let edit = VPhoneNetworkEdit(router: .some(nil), dns: .some(nil))+ #expect(try VPhoneNetworking.merge(into: .default, edit: edit, host: host) == .default)+ }++ @Test func `a forward that is already there is not added again`() throws {+ let forward = PortForward(hostPort: 8022, guestPort: 22)+ let once = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(addForwards: [forward]), host: host)+ let twice = try VPhoneNetworking.merge(into: once, edit: VPhoneNetworkEdit(addForwards: [forward, forward]), host: host)+ #expect(twice.portForwards == [forward])+ }++ @Test func `edits add, remove and clear forwards`() throws {+ var current = try VPhoneNetworking.merge(+ into: .default,+ edit: VPhoneNetworkEdit(addForwards: [+ PortForward(hostPort: 8022, guestPort: 22),+ PortForward(transport: .udp, hostPort: 5353, guestPort: 53),+ ]),+ host: host,+ )+ #expect(current.portForwards?.count == 2)++ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(removeForwards: ["8022"]), host: host)+ #expect(current.portForwards == [PortForward(transport: .udp, hostPort: 5353, guestPort: 53)])++ #expect(throws: VPhoneNetworkingError.portForwardNotFound("9999")) {+ _ = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(removeForwards: ["9999"]), host: host)+ }++ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(clearForwards: true), host: host)+ #expect(current.portForwards == nil)+ }++ @Test func `edits set and reset the MAC`() throws {+ var current = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(mac: .fixed("02:AA:BB:CC:DD:EE")), host: host)+ #expect(current.macAddress == "02:aa:bb:cc:dd:ee")+ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(mac: .random), host: host)+ #expect(current.macAddress != "02:aa:bb:cc:dd:ee")+ #expect(VPhoneMACAddress(string: current.macAddress)?.isUnicast == true)+ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(mac: .automatic), host: host)+ #expect(current.macAddress.isEmpty)+ }++ // MARK: - mDNS name++ @Test func `VM names become DNS labels`() {+ #expect(VPhoneNetworking.localHostName(forVMName: "pcc-research-01") == "pcc-research-01")+ #expect(VPhoneNetworking.localHostName(forVMName: "ipad_pro.13") == "ipad-pro-13")+ #expect(VPhoneNetworking.localHostName(forVMName: "__lab__vm__") == "lab-vm")+ #expect(VPhoneNetworking.localHostName(forVMName: "___") == "vphone")+ #expect(VPhoneNetworking.localHostName(forVMName: String(repeating: "a", count: 80)).count == 63)+ }++ @Test func `mDNS names are single labels`() throws {+ #expect(try VPhoneNetworking.validLocalHostName("lab-phone") == "lab-phone")+ #expect(try VPhoneNetworking.validLocalHostName("lab-phone.local") == "lab-phone")+ for bad in ["", "-lab", "lab-", "lab.phone", "lab_phone", String(repeating: "a", count: 64)] {+ #expect(throws: VPhoneNetworkingError.invalidLocalHostName(bad)) {+ _ = try VPhoneNetworking.validLocalHostName(bad)+ }+ }+ }++ @Test func `edits set and clear the mDNS name`() throws {+ var current = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(localHostName: .some("lab-phone.local")), host: host)+ #expect(current.localHostName == "lab-phone")+ let plan = try VPhoneNetworking.plan(current, host: host)+ #expect(plan.localHostName == "lab-phone")+ current = try VPhoneNetworking.merge(into: current, edit: VPhoneNetworkEdit(localHostName: .some(nil)), host: host)+ #expect(current.localHostName == nil)+ #expect(throws: VPhoneNetworkingError.invalidLocalHostName("lab_phone")) {+ _ = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(localHostName: .some("lab_phone")), host: host)+ }+ }++ /// The guest also announces over its USB link to the Mac, so the name+ /// applies without a NIC too.+ @Test func `a VM without a NIC keeps its mDNS name`() throws {+ let plan = try VPhoneNetworking.plan(NetworkConfig(mode: .off, macAddress: "", localHostName: "lab-phone"), host: host)+ #expect(plan.localHostName == "lab-phone")+ }++ // MARK: - The Mac's name in the guest++ @Test func `the Mac's name points where the guest reaches the Mac`() throws {+ let nat = try VPhoneNetworking.plan(config(.nat), host: host)+ #expect(VPhoneNetworking.macStaticNames(plan: nat, macName: "Lab-Mac") == [+ .init(address: VPhoneIPv4Address(192, 168, 64, 1), names: ["Lab-Mac.local"]),+ ])+ let tunnel = try VPhoneNetworking.plan(config(.tunnel), host: host)+ #expect(VPhoneNetworking.macStaticNames(plan: tunnel, macName: "Lab-Mac").first?.address == VPhoneIPv4Address(192, 168, 127, 1))+ let bridged = try VPhoneNetworking.plan(config(.bridged), host: host)+ #expect(VPhoneNetworking.macStaticNames(plan: bridged, macName: "Lab-Mac").isEmpty)+ #expect(VPhoneNetworking.macStaticNames(plan: bridged, macName: "Lab-Mac", bridgedAddress: VPhoneIPv4Address(10, 0, 0, 7)).first?.address == VPhoneIPv4Address(10, 0, 0, 7))+ let none = try VPhoneNetworking.plan(config(.off), host: host)+ #expect(VPhoneNetworking.macStaticNames(plan: none, macName: "Lab-Mac").isEmpty)+ #expect(VPhoneNetworking.macStaticNames(plan: nat, macName: nil).isEmpty)+ }++ /// On by default and stored as an absent key, so only `off` reaches the plist.+ @Test func `the Mac's name can be turned off`() throws {+ let off = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(resolvesMacName: false), host: host)+ #expect(off.resolvesMacName == false)+ #expect(VPhoneNetworking.macStaticNames(plan: try VPhoneNetworking.plan(off, host: host), macName: "Lab-Mac").isEmpty)+ let on = try VPhoneNetworking.merge(into: off, edit: VPhoneNetworkEdit(resolvesMacName: true), host: host)+ #expect(on.resolvesMacName == nil)+ #expect(try VPhoneNetworking.plan(on, host: host).resolvesMacName)+ }++ // MARK: - Guest setting++ @Test func `the guest setting carries what vphoned needs`() throws {+ let subnet = try #require(VPhoneIPv4Subnet(containing: VPhoneIPv4Address(192, 168, 64, 0), prefixLength: 24))+ let setting = VPhoneGuestIPv4Setting.manual(+ address: VPhoneIPv4Address(192, 168, 64, 50),+ subnet: subnet,+ router: VPhoneIPv4Address(192, 168, 64, 1),+ dns: [VPhoneIPv4Address(1, 1, 1, 1)],+ )+ let parameters = setting.parameters+ #expect(parameters["method"] as? String == "manual")+ #expect(parameters["address"] as? String == "192.168.64.50")+ #expect(parameters["subnet_mask"] as? String == "255.255.255.0")+ #expect(parameters["router"] as? String == "192.168.64.1")+ #expect(parameters["dns"] as? [String] == ["1.1.1.1"])+ #expect(VPhoneGuestIPv4Setting.dhcp.parameters["method"] as? String == "dhcp")+ }++ // MARK: - Manifest++ /// A config.plist from before these fields loads, and writes them back+ /// only once they are set.+ @Test func `older network configs still decode`() throws {+ let old = 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: old)+ #expect(decoded == .default)++ let encoder = PropertyListEncoder()+ encoder.outputFormat = .xml+ let plain = String(decoding: try encoder.encode(decoded), as: UTF8.self)+ #expect(!plain.contains("ipv4"))+ #expect(!plain.contains("portForwards"))++ let full = NetworkConfig(+ mode: .nat,+ macAddress: "02:aa:bb:cc:dd:ee",+ ipv4: IPv4Config(address: "192.168.64.50", prefixLength: 24),+ portForwards: [PortForward(transport: .udp, hostPort: 5353, guestPort: 53)],+ )+ let written = try encoder.encode(full)+ #expect(String(decoding: written, as: UTF8.self).contains("<key>protocol</key>"))+ #expect(try PropertyListDecoder().decode(NetworkConfig.self, from: written) == full)+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstringsindex 49d170ca..23c531ad 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Localizable.xcstrings@@ -12670,6 +12670,240 @@}}}+ },+ "IPv4 Address" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 Address" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 アドレス" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 주소" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Địa chỉ IPv4" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 地址" } }+ }+ },+ "MAC Address" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "MAC Address" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "MAC アドレス" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "MAC 주소" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Địa chỉ MAC" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "MAC 地址" } }+ }+ },+ "Port Forward" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Port Forward" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ポートフォワード" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "포트 포워드" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuyển tiếp cổng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "端口转发" } }+ }+ },+ "Address" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Address" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "アドレス" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "주소" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Địa chỉ" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "地址" } }+ }+ },+ "Configure IPv4" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Configure IPv4" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 の構成" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "IPv4 구성" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cấu hình IPv4" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "配置 IPv4" } }+ }+ },+ "Using DHCP" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Using DHCP" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "DHCP を使用" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "DHCP 사용" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Dùng DHCP" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "使用 DHCP" } }+ }+ },+ "Manually" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Manually" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "手入力" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "수동" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Thủ công" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "手动" } }+ }+ },+ "Gateway" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Gateway" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲートウェイ" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게이트웨이" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cổng mặc định" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "网关" } }+ }+ },+ "DNS Servers" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "DNS Servers" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "DNS サーバ" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "DNS 서버" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Máy chủ DNS" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "DNS 服务器" } }+ }+ },+ "Automatic" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Automatic" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "自動" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "자동" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tự động" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "自动" } }+ }+ },+ "Generated at next start" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Generated at next start" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "次回起動時に生成" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다음 시작 시 생성" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tạo khi khởi động lần tới" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "下次启动时生成" } }+ }+ },+ "Generate" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Generate" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "生成" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "생성" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tạo" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "生成" } }+ }+ },+ "Use an address on the Mac's shared NAT network, usually 192.168.64.0/24. For another subnet, use Tunnel." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Use an address on the Mac's shared NAT network, usually 192.168.64.0/24. For another subnet, use Tunnel." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "Mac の共有 NAT ネットワーク(通常は 192.168.64.0/24)上のアドレスを使用してください。ほかのサブネットにはトンネルを使用します。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "Mac의 공유 NAT 네트워크(보통 192.168.64.0/24)의 주소를 사용하세요. 다른 서브넷에는 터널을 사용하세요." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Hãy dùng địa chỉ trên mạng NAT dùng chung của máy Mac, thường là 192.168.64.0/24. Với mạng con khác, hãy dùng Đường hầm." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "请使用 Mac 共享 NAT 网络上的地址,通常是 192.168.64.0/24。其他子网请使用隧道模式。" } }+ }+ },+ "The tunnel hands this address to the guest itself." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "The tunnel hands this address to the guest itself." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このアドレスはトンネル自身がゲストに割り当てます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 주소는 터널이 직접 게스트에 할당합니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Đường hầm tự cấp địa chỉ này cho máy khách." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "这个地址由隧道直接分配给客户机。" } }+ }+ },+ "vphoned sets this address in the guest. Use your network's gateway and DNS servers." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "vphoned sets this address in the guest. Use your network's gateway and DNS servers." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "vphoned がゲスト内にこのアドレスを設定します。ネットワークのゲートウェイと DNS サーバを指定してください。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "vphoned가 게스트에 이 주소를 설정합니다. 네트워크의 게이트웨이와 DNS 서버를 입력하세요." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "vphoned đặt địa chỉ này trong máy khách. Hãy dùng cổng mặc định và máy chủ DNS của mạng bạn." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "vphoned 会在客户机内设置这个地址。请填写所在网络的网关和 DNS 服务器。" } }+ }+ },+ "Protocol" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Protocol" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "プロトコル" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "프로토콜" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Giao thức" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "协议" } }+ }+ },+ "Mac Port" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Mac Port" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "Mac のポート" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "Mac 포트" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cổng trên Mac" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "Mac 端口" } }+ }+ },+ "Guest Port" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Guest Port" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲストのポート" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게스트 포트" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cổng máy khách" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "客户机端口" } }+ }+ },+ "Add" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Add" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "追加" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "추가" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Thêm" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "添加" } }+ }+ },+ "Reachable from other devices" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Reachable from other devices" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ほかのデバイスからアクセス可能" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다른 기기에서 접근 가능" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Thiết bị khác có thể truy cập" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "允许其他设备访问" } }+ }+ },+ "Port Forwarding" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Port Forwarding" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ポートフォワーディング" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "포트 포워딩" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chuyển tiếp cổng" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "端口转发" } }+ }+ },+ "A forwarded port listens on this Mac only, unless it is reachable from other devices." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "A forwarded port listens on this Mac only, unless it is reachable from other devices." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "転送したポートは、ほかのデバイスからのアクセスを許可しない限り、この Mac 上でのみ待ち受けます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "다른 기기에서 접근 가능으로 설정하지 않으면 전달된 포트는 이 Mac에서만 수신합니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Cổng được chuyển tiếp chỉ lắng nghe trên máy Mac này, trừ khi cho phép thiết bị khác truy cập." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "转发的端口只在这台 Mac 上监听,除非允许其他设备访问。" } }+ }+ },+ "This mode cannot forward ports, so saving removes the port forwards." : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "This mode cannot forward ports, so saving removes the port forwards." } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "このモードではポートを転送できないため、保存するとポートフォワードが削除されます。" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "이 모드는 포트를 전달할 수 없으므로 저장하면 포트 포워드가 제거됩니다." } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Chế độ này không chuyển tiếp cổng được, nên khi lưu các chuyển tiếp cổng sẽ bị xóa." } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "此模式不能转发端口,保存后会移除端口转发。" } }+ }+ },+ "mDNS Name" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "mDNS Name" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "mDNS 名" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "mDNS 이름" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Tên mDNS" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "mDNS 名称" } }+ }+ },+ "Reachable as %@.local" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Reachable as %@.local" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "%@.local でアクセス可能" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "%@.local(으)로 접근 가능" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Truy cập được qua %@.local" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "可通过 %@.local 访问" } }+ }+ },+ "Resolve this Mac's name in the guest" : {+ "localizations" : {+ "en" : { "stringUnit" : { "state" : "translated", "value" : "Resolve this Mac's name in the guest" } },+ "ja" : { "stringUnit" : { "state" : "translated", "value" : "ゲスト内でこの Mac の名前を解決" } },+ "ko" : { "stringUnit" : { "state" : "translated", "value" : "게스트에서 이 Mac의 이름 확인" } },+ "vi" : { "stringUnit" : { "state" : "translated", "value" : "Phân giải tên của máy Mac này trong máy khách" } },+ "zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "在客户机内解析这台 Mac 的名称" } }+ }}},"version" : "1.0"diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swiftindex bee6a3ff..0cefd5b5 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift@@ -24,9 +24,40 @@ nonisolated struct VPhoneLaunchpadMachinePath: Hashable, Sendable {/// `vm info --json` print.nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Sendable {struct Network: Decodable, Hashable, Sendable {+ struct IPv4: Decodable, Hashable, Sendable {+ let address: String+ let prefixLength: Int+ let router: String?+ let dns: [String]?+ }++ struct PortForward: Decodable, Hashable, Sendable {+ let transport: String+ let hostAddress: String?+ let hostPort: Int+ let guestPort: Int++ private enum CodingKeys: String, CodingKey {+ case transport = "protocol"+ case hostAddress, hostPort, guestPort+ }++ /// The spelling `vm config --forward` takes.+ var argument: String {+ "\(transport):\(hostAddress ?? "127.0.0.1"):\(hostPort):\(guestPort)"+ }+ }+let mode: Stringlet macAddress: Stringlet bridgeInterface: String?+ /// Nil from a bundle older than fixed addresses, and when DHCP decides.+ let ipv4: IPv4?+ let portForwards: [PortForward]?+ /// The guest's mDNS name without `.local`; nil when not managed.+ let localHostName: String?+ /// False when the guest is not given this Mac's name locally.+ let resolvesMacName: Bool?}struct OSVersion: Decodable, Hashable, Sendable {@@ -112,6 +143,11 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Sedefault: String(localized: "None")}}++ /// The fixed address, or nil when DHCP decides.+ var addressDescription: String? {+ network.ipv4.map { "\($0.address)/\($0.prefixLength)" }+ }}// MARK: - fw catalogdiff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swiftindex e55a7ac7..64b26e6a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineInspector.swift@@ -87,6 +87,18 @@ struct VPhoneLaunchpadMachineInspector: View {LabeledContent("Memory", value: VPhoneLaunchpadMachinesView.memory(machine.memoryMB))LabeledContent("Disk", value: VPhoneLaunchpadMachinesView.disk(machine.diskSizeBytes))LabeledContent("Network", value: machine.networkDescription)+ if let address = machine.addressDescription {+ LabeledContent("IPv4 Address", value: address)+ }+ if !machine.network.macAddress.isEmpty {+ LabeledContent("MAC Address", value: machine.network.macAddress)+ }+ if let name = machine.network.localHostName {+ LabeledContent("mDNS Name", value: "\(name).local")+ }+ ForEach(machine.network.portForwards ?? [], id: \.self) { forward in+ LabeledContent("Port Forward", value: "\(forward.transport.uppercased()) \(forward.hostAddress ?? "127.0.0.1"):\(forward.hostPort) → \(forward.guestPort)")+ }}Section("Identity") {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex a9898570..eeeb780e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -406,7 +406,16 @@ final class VPhoneLaunchpadMachineLibrary {// MARK: - Edits- func configure(_ machine: Path, cpu: Int?, memoryMB: Int?, network: String?, bridgeInterface: String?) async {+ /// `networkArguments` are further `vm config` options (address, MAC, forwards),+ /// passed as the Settings sheet built them.+ func configure(+ _ machine: Path,+ cpu: Int?,+ memoryMB: Int?,+ network: String?,+ bridgeInterface: String?,+ networkArguments: [String] = [],+ ) async {var arguments = ["vm", "config", machine.name] + machine.libraryArgumentsif let cpu {arguments += ["--cpu", String(cpu)]@@ -420,6 +429,7 @@ final class VPhoneLaunchpadMachineLibrary {if let bridgeInterface, !bridgeInterface.isEmpty {arguments += ["--bridge-interface", bridgeInterface]}+ arguments += networkArgumentsawait perform(String(localized: "Saving settings…"), on: machine, arguments)}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swiftindex 3334157f..36af2f6e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift@@ -5,10 +5,12 @@ import SwiftUI/// Hardware and network for one machine, or for several at once. The fields/// start from the first machine; only the ones edited are written, to every-/// machine, so values the machines do not share are left alone.+/// machine, so values the machines do not share are left alone. A fixed+/// address, a MAC and forwarded ports belong to one machine, so they are only+/// offered when one is selected.struct VPhoneLaunchpadMachineSettingsView: View {private enum Field {- case cpu, memory, network+ case cpu, memory, network, address, mac, forwards, mdns, macName}let machines: [VPhoneLaunchpadMachine]@@ -18,6 +20,18 @@ struct VPhoneLaunchpadMachineSettingsView: View {@State private var memoryMB: Int@State private var network: String@State private var bridgeInterface: String+ @State private var manualAddress: Bool+ @State private var address: String+ @State private var gateway: String+ @State private var dns: String+ @State private var macAddress: String+ @State private var forwards: [String]+ @State private var advertisesName: Bool+ @State private var resolvesMacName: Bool+ @State private var newTransport = "tcp"+ @State private var newHostPort = ""+ @State private var newGuestPort = ""+ @State private var newOnAllAddresses = false@State private var edited: Set<Field> = []init(machines: [VPhoneLaunchpadMachine]) {@@ -27,12 +41,65 @@ struct VPhoneLaunchpadMachineSettingsView: View {_memoryMB = State(initialValue: first?.memoryMB ?? 8192)_network = State(initialValue: first.map { $0.network.mode == "hostOnly" ? "none" : $0.network.mode } ?? "nat")_bridgeInterface = State(initialValue: first?.network.bridgeInterface ?? "")+ let ipv4 = first?.network.ipv4+ _manualAddress = State(initialValue: ipv4 != nil)+ _address = State(initialValue: ipv4.map { "\($0.address)/\($0.prefixLength)" } ?? "")+ _gateway = State(initialValue: ipv4?.router ?? "")+ _dns = State(initialValue: ipv4?.dns?.joined(separator: ", ") ?? "")+ _macAddress = State(initialValue: first?.network.macAddress ?? "")+ _forwards = State(initialValue: first?.network.portForwards?.map(\.argument) ?? [])+ _advertisesName = State(initialValue: first?.network.localHostName != nil)+ _resolvesMacName = State(initialValue: first?.network.resolvesMacName != false)}private var title: Text {machines.count == 1 ? Text("\(machines[0].name) Settings") : Text("Settings for \(machines.count) Machines")}+ private var single: Bool {+ machines.count == 1+ }++ private var forwardsSupported: Bool {+ network == "nat" || network == "tunnel"+ }++ /// The mDNS name the machine has, or the one `--mdns on` would give it:+ /// its name with everything but letters and digits turned into hyphens.+ private var localHostName: String {+ if let name = machines.first?.network.localHostName {+ return name+ }+ let name = machines.first?.name ?? ""+ var label = ""+ for character in name {+ if character.isASCII, character.isLetter || character.isNumber {+ label.append(character)+ } else if !label.hasSuffix("-") {+ label.append("-")+ }+ }+ label = String(label.trimmingCharacters(in: CharacterSet(charactersIn: "-")).prefix(63))+ label = label.trimmingCharacters(in: CharacterSet(charactersIn: "-"))+ return label.isEmpty ? "vphone" : label+ }++ /// Bridged and none have no port forwarding; switching to them drops it.+ private var dropsForwards: Bool {+ single && !forwardsSupported && !forwards.isEmpty+ }++ private var newForward: String? {+ guard let host = Int(newHostPort), (1 ... 65535).contains(host),+ let guest = Int(newGuestPort), (1 ... 65535).contains(guest)+ else { return nil }+ return "\(newTransport):\(newOnAllAddresses ? "0.0.0.0" : "127.0.0.1"):\(host):\(guest)"+ }++ private var canSave: Bool {+ !edited.isEmpty && !(manualAddress && address.trimmingCharacters(in: .whitespaces).isEmpty)+ }+var body: some View {VPhoneLaunchpadSheet(title) {Form {@@ -56,6 +123,10 @@ struct VPhoneLaunchpadMachineSettingsView: View {Text("Traffic leaves through this Mac's own connections, so it follows the Mac's VPN.").foregroundStyle(.secondary)}+ if dropsForwards {+ Text("This mode cannot forward ports, so saving removes the port forwards.")+ .foregroundStyle(.secondary)+ }} header: {Text("Network")} footer: {@@ -64,6 +135,12 @@ struct VPhoneLaunchpadMachineSettingsView: View {.foregroundStyle(.secondary)}}+ if single {+ addressSection+ }+ if single, forwardsSupported {+ forwardsSection+ }}.formStyle(.grouped)} actions: {@@ -71,14 +148,122 @@ struct VPhoneLaunchpadMachineSettingsView: View {.keyboardShortcut(.cancelAction)Button("Save") { save() }.keyboardShortcut(.defaultAction)- .disabled(edited.isEmpty)+ .disabled(!canSave)}- .frame(width: 440)+ .frame(width: 480).fixedSize(horizontal: false, vertical: true).onChange(of: cpu) { edited.insert(.cpu) }.onChange(of: memoryMB) { edited.insert(.memory) }.onChange(of: network) { edited.insert(.network) }.onChange(of: bridgeInterface) { edited.insert(.network) }+ .onChange(of: manualAddress) { edited.insert(.address) }+ .onChange(of: address) { edited.insert(.address) }+ .onChange(of: gateway) { edited.insert(.address) }+ .onChange(of: dns) { edited.insert(.address) }+ .onChange(of: macAddress) { edited.insert(.mac) }+ .onChange(of: forwards) { edited.insert(.forwards) }+ .onChange(of: advertisesName) { edited.insert(.mdns) }+ .onChange(of: resolvesMacName) { edited.insert(.macName) }+ }++ private var addressSection: some View {+ Section {+ if network != "none" {+ Picker("Configure IPv4", selection: $manualAddress) {+ Text("Using DHCP").tag(false)+ Text("Manually").tag(true)+ }+ if manualAddress {+ TextField("Address", text: $address, prompt: Text(verbatim: network == "tunnel" ? "192.168.127.3/24" : "192.168.64.50/24"))+ TextField("Gateway", text: $gateway, prompt: Text("Automatic"))+ TextField("DNS Servers", text: $dns, prompt: Text("Automatic"))+ }+ HStack {+ TextField("MAC Address", text: $macAddress, prompt: Text("Generated at next start"))+ Button("Generate") { macAddress = Self.randomMACAddress() }+ }+ Toggle("Resolve this Mac's name in the guest", isOn: $resolvesMacName)+ }+ // The guest also announces over its USB link to the Mac, so this+ // works without a network device too.+ Toggle("Reachable as \(localHostName).local", isOn: $advertisesName)+ } header: {+ Text("Address")+ } footer: {+ Group {+ switch network {+ case "none":+ EmptyView()+ case "nat":+ Text("Use an address on the Mac's shared NAT network, usually 192.168.64.0/24. For another subnet, use Tunnel.")+ case "tunnel":+ Text("The tunnel hands this address to the guest itself.")+ default:+ Text("vphoned sets this address in the guest. Use your network's gateway and DNS servers.")+ }+ }+ .foregroundStyle(.secondary)+ }+ }++ private var forwardsSection: some View {+ Section {+ ForEach(forwards, id: \.self) { forward in+ HStack {+ Text(Self.forwardLabel(forward))+ Spacer()+ Button {+ forwards.removeAll { $0 == forward }+ } label: {+ Image(systemName: "minus.circle")+ }+ .buttonStyle(.borderless)+ .help("Remove")+ }+ }+ HStack {+ Picker("Protocol", selection: $newTransport) {+ Text(verbatim: "TCP").tag("tcp")+ Text(verbatim: "UDP").tag("udp")+ }+ .labelsHidden()+ .fixedSize()+ TextField("Mac Port", text: $newHostPort)+ TextField("Guest Port", text: $newGuestPort)+ Button {+ if let newForward, !forwards.contains(newForward) {+ forwards.append(newForward)+ newHostPort = ""+ newGuestPort = ""+ }+ } label: {+ Image(systemName: "plus.circle")+ }+ .buttonStyle(.borderless)+ .disabled(newForward == nil)+ .help("Add")+ }+ Toggle("Reachable from other devices", isOn: $newOnAllAddresses)+ } header: {+ Text("Port Forwarding")+ } footer: {+ Text("A forwarded port listens on this Mac only, unless it is reachable from other devices.")+ .foregroundStyle(.secondary)+ }+ }++ /// `tcp:127.0.0.1:8022:22` as `TCP 127.0.0.1:8022 → 22`.+ private static func forwardLabel(_ argument: String) -> String {+ let parts = argument.split(separator: ":")+ guard parts.count == 4 else { return argument }+ return "\(parts[0].uppercased()) \(parts[1]):\(parts[2]) → \(parts[3])"+ }++ /// A unicast, locally administered address, the kind no vendor assigns.+ private static func randomMACAddress() -> String {+ var bytes = (0 ..< 6).map { _ in UInt8.random(in: 0 ... 255) }+ bytes[0] = (bytes[0] & 0xFC) | 0x02+ return bytes.map { String(format: "%02x", $0) }.joined(separator: ":")}private func save() {@@ -86,11 +271,49 @@ struct VPhoneLaunchpadMachineSettingsView: View {let memoryMB = edited.contains(.memory) ? memoryMB : nillet network = edited.contains(.network) ? network : nillet bridgeInterface = network == "bridged" ? bridgeInterface : nil+ var networkArguments: [String] = []+ if single {+ if edited.contains(.address) {+ if manualAddress {+ let trimmedGateway = gateway.trimmingCharacters(in: .whitespaces)+ let trimmedDNS = dns.replacingOccurrences(of: " ", with: "")+ networkArguments += [+ "--ip", address.trimmingCharacters(in: .whitespaces),+ "--gateway", trimmedGateway.isEmpty ? "auto" : trimmedGateway,+ "--dns", trimmedDNS.isEmpty ? "auto" : trimmedDNS,+ ]+ } else {+ networkArguments += ["--ip", "dhcp"]+ }+ }+ if edited.contains(.macName) {+ networkArguments += ["--mac-name", resolvesMacName ? "on" : "off"]+ }+ if edited.contains(.mdns) {+ networkArguments += ["--mdns", advertisesName ? "on" : "off"]+ }+ if edited.contains(.mac) {+ let trimmed = macAddress.trimmingCharacters(in: .whitespaces)+ networkArguments += ["--mac", trimmed.isEmpty ? "auto" : trimmed]+ }+ if dropsForwards {+ networkArguments += ["--clear-forwards"]+ } else if edited.contains(.forwards) {+ networkArguments += ["--clear-forwards"] + forwards.flatMap { ["--forward", $0] }+ }+ }let paths = machines.map(\.path)let library = model.machinesTask {for path in paths {- await library.configure(path, cpu: cpu, memoryMB: memoryMB, network: network, bridgeInterface: bridgeInterface)+ await library.configure(+ path,+ cpu: cpu,+ memoryMB: memoryMB,+ network: network,+ bridgeInterface: bridgeInterface,+ networkArguments: networkArguments,+ )}}dismiss()