Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let NAT machines reach each other, unless one opts out

Maximilian Paßa52688cb7ffc
diff --git a/Documents/Guides/networking.md b/Documents/Guides/networking.md
index e5928929..f34b5c4d 100644
--- a/Documents/Guides/networking.md
+++ b/Documents/Guides/networking.md
@@ -280,6 +280,31 @@ To see what the guest's resolver returns, and whether each address connects:
vphone-launchpad-cli guest rpc <name> network.resolve '{"host":"<Mac>.local","family":"ipv4","port":8000}'
```
+## Machines reaching each other
+
+In `nat`, Virtualization.framework isolates each guest from the others on the
+Mac's shared network by default: a guest reaches the Mac and the internet, not
+another VM. vphone turns that isolation off, so `nat` machines reach each other
+directly, Bonjour included. A virtual Apple Watch pairs with a virtual iPhone
+this way. A machine that should stay apart opts out:
+
+```sh
+vphone-cli vm config <name> --nat-peers off # isolate this guest again
+vphone-cli vm config <name> --nat-peers on # the default
+```
+
+In Launchpad it is "Reach other NAT machines" in the machine's Network
+settings. It applies from the next launch.
+
+vmnet puts the machines that reach each other on a second shared network, the
+block after the first: 192.168.65.0/24 beside 192.168.64.0/24, with the Mac at
+192.168.65.1. A fixed address (`--ip`) goes on that network; a machine whose
+fixed address is on the first network keeps its isolation unless it asks for
+its peers, and then needs an address on the second one. Isolation is a setting of each
+machine's own attachment, so a machine that opts out keeps vmnet's isolation
+whatever the others do. The switch is private to Virtualization.framework; a
+version without it leaves every guest isolated and says so when the VM starts.
+
## Unplugging a running VM
`vm network` acts on a VM that is running, and nothing it does is saved:
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
index 54bcee57..54278947 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift
@@ -242,6 +242,10 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
bridged: the Mac's address on that interface), instead of racing mDNS answers. \
--mac-name off withdraws it. Applied each time vphone-vm connects to the guest.
+ --nat-peers (on by default) lets a nat guest and the other nat machines on this Mac \
+ reach each other, as a watch and the phone it pairs with must. --nat-peers off keeps \
+ the guest isolated: it reaches only this Mac and beyond. Applies from the next launch.
+
--unlock-at-startup on has vphone-vm wake the guest and dismiss its Lock Screen each time \
vphoned starts in it: after the VM starts and after the guest reboots. Applies from the \
next connect.
@@ -287,6 +291,8 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
var mdns: String?
@Option(name: .long, help: "Have the guest resolve this Mac's .local name locally: on (default) | off")
var macName: String?
+ @Option(name: .long, help: "Let this nat guest and the other nat machines reach each other: on (default) | off")
+ var natPeers: String?
@Option(name: .long, help: "Unlock the guest when it starts: on | off (default)")
var unlockAtStartup: String?
@Option(name: .long, help: "Forward this Mac's location to the guest: on | off (default)")
@@ -364,6 +370,12 @@ struct VPhoneVirtualMachineConfigCommand: ParsableCommand {
case "off": edit.resolvesMacName = false
default: throw ValidationError("--mac-name takes on or off.")
}
+ switch natPeers?.lowercased() {
+ case nil: break
+ case "on": edit.reachesPeers = true
+ case "off": edit.reachesPeers = false
+ default: throw ValidationError("--nat-peers takes on or off.")
+ }
switch mdns?.lowercased() {
case nil: break
case "off": edit.localHostName = .some(nil)
@@ -422,6 +434,9 @@ func describeNetwork(_ net: VPhoneVirtualMachineManifest.NetworkConfig) -> Strin
if net.resolvesMacName == false {
parts.append("mac-name off")
}
+ if net.mode == .nat, !VPhoneNetworking.reachesPeers(net) {
+ parts.append("nat-peers off")
+ }
return parts.joined(separator: ", ")
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift
index 1d5f6bf8..9679df40 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLeasesCommand.swift
@@ -42,9 +42,9 @@ struct VPhoneVirtualMachineLeasesCommand: ParsableCommand {
throw ValidationError("Releasing leases changes \(VPhoneDHCPLeaseList.path), which needs root. Run this command with sudo.")
}
let machines = try machineMACs()
- let subnet = VPhoneNetworkHost.current.sharedNATSubnet
+ let host = VPhoneNetworkHost.current
let audit = { (list: VPhoneDHCPLeaseList) in
- VPhoneDHCPLeaseAudit(list, machines: machines, sharedSubnet: subnet)
+ VPhoneDHCPLeaseAudit(list, machines: machines, sharedSubnet: host.sharedNATSubnet, peerSubnet: host.peerNATSubnet)
}
if releaseOrphans {
@@ -77,7 +77,7 @@ struct VPhoneVirtualMachineLeasesCommand: ParsableCommand {
return
}
guard !entries.isEmpty else {
- print("No guest leases on \(subnet).")
+ print("No guest leases on \(host.sharedNATSubnet) or \(host.peerNATSubnet).")
return
}
let now = Date()
diff --git a/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift b/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift
index 7060720b..257ad5b8 100644
--- a/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift
+++ b/VPhoneKit/VPhoneCoreKit/Network/VPhoneDHCPLeases.swift
@@ -176,13 +176,15 @@ public struct VPhoneDHCPLeaseAudit: Sendable {
_ list: VPhoneDHCPLeaseList,
machines: [VPhoneMACAddress: String],
sharedSubnet: VPhoneIPv4Subnet,
+ peerSubnet: VPhoneIPv4Subnet? = nil,
now: Date = Date(),
) {
+ let subnets = [sharedSubnet] + (peerSubnet.map { [$0] } ?? [])
entries = list.leases.map { lease in
let owner: Owner = if let mac = lease.hardwareAddress, let name = machines[mac] {
.machine(name)
} else if lease.hardwareAddress == nil
- || !(lease.address.map(sharedSubnet.contains) ?? false)
+ || !(lease.address.map { address in subnets.contains { $0.contains(address) } } ?? false)
|| !Self.guestHostNames.contains(lease.name ?? "")
{
.foreign
diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift
index 4b135d64..88255006 100644
--- a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift
+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift
@@ -70,7 +70,7 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {
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."
+ "\(address) is not on the Mac's shared NAT network \(shared), which nat mode uses for this machine (a machine that reaches the other NAT machines is on vmnet's second one; see --nat-peers). 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):
@@ -110,6 +110,24 @@ public struct VPhoneNetworkHost: Equatable, Sendable {
self.sharedNATHost = sharedNATHost
}
+ /// The network vmnet runs for the machines that reach each other
+ /// (`reachesPeers`): a NAT attachment without interface isolation joins a
+ /// second shared network, the block right after the first one (192.168.65.0/24
+ /// beside 192.168.64.0/24), with the Mac at its first host.
+ public var peerNATSubnet: VPhoneIPv4Subnet {
+ VPhoneIPv4Subnet(containing: VPhoneIPv4Address(sharedNATSubnet.broadcast.raw &+ 1), prefixLength: sharedNATSubnet.prefixLength)
+ ?? sharedNATSubnet
+ }
+
+ public var peerNATHost: VPhoneIPv4Address {
+ peerNATSubnet.firstHost
+ }
+
+ /// The network a `nat` guest is on, and the Mac's address there.
+ public func natNetwork(reachesPeers: Bool) -> (subnet: VPhoneIPv4Subnet, host: VPhoneIPv4Address) {
+ reachesPeers ? (peerNATSubnet, peerNATHost) : (sharedNATSubnet, sharedNATHost)
+ }
+
/// vmnet's own default, used unless the host's preferences move it.
public static let defaultSharedNATHost = VPhoneIPv4Address(192, 168, 64, 1)
@@ -194,6 +212,9 @@ public struct VPhoneNetworkPlan: Equatable, Sendable {
/// Whether vphoned registers this Mac's `.local` name with the guest's
/// mDNSResponder, pointing at `macAddressForGuest`.
public let resolvesMacName: Bool
+ /// In `nat`: whether the guest and the other machines on the shared
+ /// network reach each other (vmnet's interface isolation off).
+ public var reachesPeers = false
/// 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
@@ -237,6 +258,8 @@ public struct VPhoneNetworkEdit: Equatable, Sendable {
public var localHostName: String??
/// Turn the guest's local record for the Mac's name on or off.
public var resolvesMacName: Bool?
+ /// Let the guest reach the other machines on the shared network, or not.
+ public var reachesPeers: Bool?
public var addForwards: [PortForward]
/// Forwards to drop, named as `vm info` lists them or by host port.
public var removeForwards: [String]
@@ -251,6 +274,7 @@ public struct VPhoneNetworkEdit: Equatable, Sendable {
dns: [String]?? = nil,
localHostName: String?? = nil,
resolvesMacName: Bool? = nil,
+ reachesPeers: Bool? = nil,
addForwards: [PortForward] = [],
removeForwards: [String] = [],
clearForwards: Bool = false,
@@ -263,6 +287,7 @@ public struct VPhoneNetworkEdit: Equatable, Sendable {
self.dns = dns
self.localHostName = localHostName
self.resolvesMacName = resolvesMacName
+ self.reachesPeers = reachesPeers
self.addForwards = addForwards
self.removeForwards = removeForwards
self.clearForwards = clearForwards
@@ -570,6 +595,8 @@ public enum VPhoneNetworking {
localHostName: 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,
+ // Stored as set: its default depends on the address.
+ reachesPeers: edit.reachesPeers ?? current.reachesPeers,
)
try validate(merged, host: host)
return merged
@@ -590,7 +617,21 @@ public enum VPhoneNetworking {
let dns: [VPhoneIPv4Address]
}
- static func resolve(_ ipv4: IPv4Config, mode: NetworkMode, host: VPhoneNetworkHost) throws -> ResolvedIPv4 {
+ /// Whether `cfg` fixes the guest's address on the first shared network.
+ /// Such a machine keeps the isolation it was configured under unless it
+ /// asks to reach its peers: those are on vmnet's second shared network,
+ /// where its address does not exist.
+ static func hasFixedSharedAddress(_ cfg: NetworkConfig, host: VPhoneNetworkHost) -> Bool {
+ guard let address = cfg.ipv4.flatMap({ VPhoneIPv4Address(dotted: $0.address) }) else { return false }
+ return host.sharedNATSubnet.contains(address)
+ }
+
+ /// Whether a `nat` guest of `cfg` reaches the other NAT machines.
+ public static func reachesPeers(_ cfg: NetworkConfig, host: VPhoneNetworkHost = .current) -> Bool {
+ cfg.mode == .nat && (cfg.reachesPeers ?? !hasFixedSharedAddress(cfg, host: host))
+ }
+
+ static func resolve(_ ipv4: IPv4Config, mode: NetworkMode, host: VPhoneNetworkHost, reachesPeers: Bool = false) throws -> ResolvedIPv4 {
guard let address = VPhoneIPv4Address(dotted: ipv4.address) else {
throw VPhoneNetworkingError.invalidAddress(field: "the guest address", value: ipv4.address)
}
@@ -612,15 +653,17 @@ public enum VPhoneNetworking {
// 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.
+ // A guest that reaches its peers is on vmnet's second shared network.
var defaultRouter = subnet.firstHost
if mode == .nat {
- guard subnet == host.sharedNATSubnet else {
+ let network = host.natNetwork(reachesPeers: reachesPeers)
+ guard subnet == network.subnet else {
throw VPhoneNetworkingError.natAddressOffSharedNetwork(
address: ipv4.address,
- shared: host.sharedNATSubnet.description,
+ shared: network.subnet.description,
)
}
- defaultRouter = host.sharedNATHost
+ defaultRouter = network.host
}
let router: VPhoneIPv4Address
@@ -702,7 +745,8 @@ public enum VPhoneNetworking {
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 reachesPeers = reachesPeers(cfg, host: host)
+ let resolved = try cfg.ipv4.map { try resolve($0, mode: cfg.mode, host: host, reachesPeers: reachesPeers) }
let forwards = cfg.portForwards ?? []
try validatePortForwards(forwards, mode: cfg.mode)
let localHostName = try cfg.localHostName.map(validLocalHostName)
@@ -726,17 +770,20 @@ public enum VPhoneNetworking {
resolvesMacName: false, macAddressForGuest: nil, forwardingAddress: nil)
case .nat:
+ let natHost = host.natNetwork(reachesPeers: reachesPeers).host
guard let resolved else {
return VPhoneNetworkPlan(
attachment: .sharedNAT, macAddress: mac, guestIPv4: .dhcp,
portForwards: forwards, localHostName: localHostName,
- resolvesMacName: resolvesMacName, macAddressForGuest: host.sharedNATHost, forwardingAddress: nil,
+ resolvesMacName: resolvesMacName, reachesPeers: reachesPeers,
+ macAddressForGuest: natHost, forwardingAddress: nil,
)
}
return VPhoneNetworkPlan(
attachment: .sharedNAT, macAddress: mac, guestIPv4: manual(resolved),
portForwards: forwards, localHostName: localHostName,
- resolvesMacName: resolvesMacName, macAddressForGuest: host.sharedNATHost, forwardingAddress: resolved.address,
+ resolvesMacName: resolvesMacName, reachesPeers: reachesPeers,
+ macAddressForGuest: natHost, forwardingAddress: resolved.address,
)
case .bridged:
@@ -779,6 +826,21 @@ public enum VPhoneNetworking {
public let userspaceNetwork: VPhoneUserspaceNetwork?
}
+ /// vmnet isolates each guest on the shared network from the others, and
+ /// Virtualization has no public switch for it. A VM with isolation off
+ /// shares the bridge with the others without its private flag, so they
+ /// reach each other directly (Bonjour included). A Virtualization without
+ /// the private setter leaves the guest isolated.
+ static func setInterfaceIsolation(_ enabled: Bool, of attachment: VZNATNetworkDeviceAttachment) {
+ let selector = NSSelectorFromString("_setInterfaceIsolationEnabled:")
+ guard attachment.responds(to: selector), let method = class_getInstanceMethod(type(of: attachment), selector) else {
+ fputs("warning: this Virtualization cannot let NAT machines reach each other; the guest stays isolated\n", stderr)
+ return
+ }
+ typealias Setter = @convention(c) (AnyObject, Selector, Bool) -> Void
+ unsafeBitCast(method_getImplementation(method), to: Setter.self)(attachment, selector, enabled)
+ }
+
/// 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
@@ -796,7 +858,11 @@ public enum VPhoneNetworking {
case .none:
return NetworkDevice(configuration: nil, userspaceNetwork: nil)
case .sharedNAT:
- attachment = VZNATNetworkDeviceAttachment()
+ let nat = VZNATNetworkDeviceAttachment()
+ if plan.reachesPeers {
+ setInterfaceIsolation(false, of: nat)
+ }
+ attachment = nat
case let .tunnel(configuration):
let network = try VPhoneUserspaceNetwork(configuration: configuration)
userspaceNetwork = network
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
index e4ca80cb..43a6cbad 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift
@@ -211,6 +211,12 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
/// reaches the Mac at, through a record vphoned registers with the
/// guest's mDNSResponder. Nil means yes; see `VPhoneNetworking.plan`.
public let resolvesMacName: Bool?
+ /// Whether, in `nat`, the guest reaches the other machines on the Mac's
+ /// shared network and they reach it, as a watch and the phone it pairs
+ /// with must. Nil means yes, except for a fixed address on the first
+ /// shared network, set before this existed; false keeps vmnet's
+ /// isolation, where each guest reaches only the Mac and beyond.
+ public let reachesPeers: Bool?
public enum NetworkMode: String, Codable, Sendable {
case nat
@@ -236,6 +242,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
portForwards: [PortForward]? = nil,
localHostName: String? = nil,
resolvesMacName: Bool? = nil,
+ reachesPeers: Bool? = nil,
) {
self.mode = mode
self.macAddress = macAddress
@@ -244,6 +251,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
self.portForwards = portForwards
self.localHostName = localHostName
self.resolvesMacName = resolvesMacName
+ self.reachesPeers = reachesPeers
}
/// The same configuration with one field replaced.
@@ -255,6 +263,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
portForwards: [PortForward]?? = nil,
localHostName: String?? = nil,
resolvesMacName: Bool?? = nil,
+ reachesPeers: Bool?? = nil,
) -> NetworkConfig {
NetworkConfig(
mode: mode ?? self.mode,
@@ -264,6 +273,7 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {
portForwards: portForwards ?? self.portForwards,
localHostName: localHostName ?? self.localHostName,
resolvesMacName: resolvesMacName ?? self.resolvesMacName,
+ reachesPeers: reachesPeers ?? self.reachesPeers,
)
}
diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift
index 216a8423..7d718607 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift
@@ -1,5 +1,6 @@
import Foundation
import Testing
+import Virtualization
@testable import VPhoneCoreKit
/// Editing, validating and planning a VM's network: fixed addresses, MACs and
@@ -81,9 +82,10 @@ struct NetworkPlanTests {
}
/// Only the shared network: a subnet of the VM's own stays reserved after
- /// the VM exits, so it would work for one launch.
+ /// the VM exits, so it would work for one launch. A machine that reaches
+ /// its peers is held to vmnet's second shared network.
@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")) {
+ #expect(throws: VPhoneNetworkingError.natAddressOffSharedNetwork(address: "192.168.70.10", shared: "192.168.65.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")) {
@@ -332,9 +334,10 @@ struct NetworkPlanTests {
// MARK: - The Mac's name in the guest
@Test func `the Mac's name points where the guest reaches the Mac`() throws {
+ // A nat guest reaches its peers by default, on vmnet's second network.
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"]),
+ .init(address: VPhoneIPv4Address(192, 168, 65, 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))
@@ -356,6 +359,57 @@ struct NetworkPlanTests {
#expect(try VPhoneNetworking.plan(on, host: host).resolvesMacName)
}
+ /// NAT machines reach each other unless one opts out; the switch is
+ /// stored like the Mac's name, and only `nat` has it.
+ @Test func `nat machines reach each other unless one opts out`() throws {
+ #expect(try VPhoneNetworking.plan(.default, host: host).reachesPeers)
+ let off = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(reachesPeers: false), host: host)
+ #expect(off.reachesPeers == false)
+ #expect(try !VPhoneNetworking.plan(off, host: host).reachesPeers)
+ let on = try VPhoneNetworking.merge(into: off, edit: VPhoneNetworkEdit(reachesPeers: true), host: host)
+ #expect(on.reachesPeers == true)
+ let tunnel = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(mode: .tunnel), host: host)
+ #expect(try !VPhoneNetworking.plan(tunnel, host: host).reachesPeers)
+ }
+
+ /// Peers are on vmnet's second shared network, the block after the first.
+ @Test func `a machine that reaches its peers is on the second shared network`() throws {
+ #expect(host.peerNATSubnet.description == "192.168.65.0/24")
+ #expect(host.peerNATHost == VPhoneIPv4Address(192, 168, 65, 1))
+ #expect(try VPhoneNetworking.plan(.default, host: host).macAddressForGuest == host.peerNATHost)
+ let off = try VPhoneNetworking.merge(into: .default, edit: VPhoneNetworkEdit(reachesPeers: false), host: host)
+ #expect(try VPhoneNetworking.plan(off, host: host).macAddressForGuest == host.sharedNATHost)
+
+ // A fixed address follows: on the second network with peers, on the
+ // first without.
+ let peer = try VPhoneNetworking.merge(
+ into: .default, edit: VPhoneNetworkEdit(address: .fixed(address: "192.168.65.50", prefixLength: 24)), host: host,
+ )
+ #expect(try VPhoneNetworking.plan(peer, host: host).reachesPeers)
+ #expect(throws: VPhoneNetworkingError.self) {
+ try VPhoneNetworking.merge(into: off, edit: VPhoneNetworkEdit(address: .fixed(address: "192.168.65.50", prefixLength: 24)), host: host)
+ }
+
+ // A fixed address on the first network, set before peers existed,
+ // keeps that machine isolated, unless it asks for its peers.
+ let shared = try VPhoneNetworking.merge(
+ into: .default, edit: VPhoneNetworkEdit(address: .fixed(address: "192.168.64.50", prefixLength: 24)), host: host,
+ )
+ #expect(try !VPhoneNetworking.plan(shared, host: host).reachesPeers)
+ #expect(!VPhoneNetworking.reachesPeers(shared, host: host))
+ #expect(throws: VPhoneNetworkingError.self) {
+ try VPhoneNetworking.merge(into: shared, edit: VPhoneNetworkEdit(reachesPeers: true), host: host)
+ }
+ }
+
+ @Test func `a NAT attachment can drop its isolation`() throws {
+ let nat = VZNATNetworkDeviceAttachment()
+ #expect(nat.responds(to: NSSelectorFromString("_setInterfaceIsolationEnabled:")))
+ VPhoneNetworking.setInterfaceIsolation(false, of: nat)
+ let device = try VPhoneNetworking.makeNetworkDevice(VPhoneNetworking.plan(.default, host: host))
+ #expect(device.configuration?.attachment is VZNATNetworkDeviceAttachment)
+ }
+
// MARK: - Guest setting
@Test func `the guest setting carries what vphoned needs`() throws {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
index 334aa991..96260b35 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachine.swift
@@ -58,6 +58,8 @@ nonisolated struct VPhoneLaunchpadMachine: Decodable, Hashable, Identifiable, Se
let localHostName: String?
/// False when the guest is not given this Mac's name locally.
let resolvesMacName: Bool?
+ /// False when a nat guest is kept from the other nat machines.
+ let reachesPeers: Bool?
}
struct OSVersion: Decodable, Hashable, Sendable {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
index 25eda249..077c99c8 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineSheets.swift
@@ -11,7 +11,7 @@ import UniformTypeIdentifiers
/// offered when one is selected, on pages of their own.
struct VPhoneLaunchpadMachineSettingsView: View {
private enum Field {
- case cpu, memory, network, address, mac, forwards, mdns, macName, unlock, location
+ case cpu, memory, network, address, mac, forwards, mdns, macName, natPeers, unlock, location
}
enum Page: Hashable {
@@ -34,6 +34,7 @@ struct VPhoneLaunchpadMachineSettingsView: View {
@State private var forwards: [String]
@State private var advertisesName: Bool
@State private var resolvesMacName: Bool
+ @State private var reachesPeers: Bool
@State private var unlocksAtStartup: Bool
@State private var syncsHostLocation: Bool
@State private var newTransport = "tcp"
@@ -58,6 +59,7 @@ struct VPhoneLaunchpadMachineSettingsView: View {
_forwards = State(initialValue: first?.network.portForwards?.map(\.argument) ?? [])
_advertisesName = State(initialValue: first?.network.localHostName != nil)
_resolvesMacName = State(initialValue: first?.network.resolvesMacName != false)
+ _reachesPeers = State(initialValue: first?.network.reachesPeers != false)
_unlocksAtStartup = State(initialValue: first?.unlocksAtStartup == true)
_syncsHostLocation = State(initialValue: first?.syncsHostLocation == true)
}
@@ -162,6 +164,7 @@ struct VPhoneLaunchpadMachineSettingsView: View {
.onChange(of: forwards) { edited.insert(.forwards) }
.onChange(of: advertisesName) { edited.insert(.mdns) }
.onChange(of: resolvesMacName) { edited.insert(.macName) }
+ .onChange(of: reachesPeers) { edited.insert(.natPeers) }
.onChange(of: unlocksAtStartup) { edited.insert(.unlock) }
.onChange(of: syncsHostLocation) { edited.insert(.location) }
#if DEBUG
@@ -215,6 +218,9 @@ struct VPhoneLaunchpadMachineSettingsView: View {
if network == "bridged" {
TextField("Interface", text: $bridgeInterface, prompt: Text("First available"))
}
+ if network == "nat" {
+ Toggle("Reach other NAT machines", isOn: $reachesPeers)
+ }
} header: {
if !single {
Text("Network")
@@ -372,6 +378,9 @@ struct VPhoneLaunchpadMachineSettingsView: View {
if edited.contains(.macName) {
networkArguments += ["--mac-name", resolvesMacName ? "on" : "off"]
}
+ if edited.contains(.natPeers) {
+ networkArguments += ["--nat-peers", reachesPeers ? "on" : "off"]
+ }
if edited.contains(.mdns) {
networkArguments += ["--mdns", advertisesName ? "on" : "off"]
}