Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(spaces): reach macOS VMs over vsock, not Local Network or VPN routes (CUA-3139) (#6380)

cua-agents[bot]37af9dffdd0a
diff --git a/docs/content/docs/lume/reference/http-api.mdx b/docs/content/docs/lume/reference/http-api.mdx
index 0614c233f7..20b2dad7c8 100644
--- a/docs/content/docs/lume/reference/http-api.mdx
+++ b/docs/content/docs/lume/reference/http-api.mdx
@@ -378,6 +378,7 @@ POST /lume/vms/:name/run
| `storage` | `string` | | VM storage location. |
| `clipboard` | `boolean` | `false` | Enable bidirectional clipboard sync via SSH (experimental). |
| `vnc` | `string` | `enabled` | VNC server policy: 'enabled' or 'disabled'. 'disabled' requires noDisplay=true, starts no VNC listener, and reports a null vncUrl. |
+| `forwards` | `array` | | Guest ports to publish on host loopback ports over a virtio socket device, through Cua's guest vsock agent. GET reports the host ports under 'forwards' once the agent answers; these connections are not subject to macOS Local Network privacy or VPN routes. |
**Example request**
diff --git a/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml b/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml
index c89513d449..fd798d1cc0 100644
--- a/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml
+++ b/libs/cua-spacesd/crates/cua-spacesd/Cargo.toml
@@ -60,6 +60,8 @@ cua-spacesd-doctor = { path = "../cua-spacesd-doctor" }
# remote and agent cursors render on the ORIGIN desktop. See the comment on
# `main` -- the overlay NSWindow cannot live on a spawned thread.
platform-macos = { path = "../../../cua-driver/rust/crates/platform-macos" }
+# The guest end of a macOS VM's vsock host channel (`vsock_agent`).
+libc = "0.2"
[target.'cfg(all(target_os = "linux", not(target_env = "musl")))'.dependencies]
# The cua-driver tool registry behind DriverService and /mcp.
diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/lib.rs b/libs/cua-spacesd/crates/cua-spacesd/src/lib.rs
index 208c22f592..7351155840 100644
--- a/libs/cua-spacesd/crates/cua-spacesd/src/lib.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd/src/lib.rs
@@ -27,6 +27,8 @@ pub const DEFAULT_PORT: u16 = 3211;
pub mod quic;
#[cfg(not(cua_headless))]
mod remote;
+#[cfg(target_os = "macos")]
+pub mod vsock_agent;
#[cfg(not(cua_headless))]
pub use remote::{serve_remote, serve_remote_listener, RemoteShareConfig};
diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
index 07b146a00d..a51c7e8052 100644
--- a/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd/src/main.rs
@@ -937,6 +937,11 @@ async fn serve(args: ServeArgs, join: Option<JoinArgs>) -> Result<Exit, BoxError
);
let shutdown = ctx.shutdown_token();
+ // In a macOS VM, the host reaches this server over vsock as well as
+ // over the VM network (which macOS Local Network privacy and VPNs can
+ // block on the host).
+ #[cfg(target_os = "macos")]
+ cua_spacesd::vsock_agent::start();
// A direct host starts its cua daemon, which reopens the ports it
// forwards to the Spaces it provides.
if let Some(policy) = direct_host_policy {
diff --git a/libs/cua-spacesd/crates/cua-spacesd/src/vsock_agent.rs b/libs/cua-spacesd/crates/cua-spacesd/src/vsock_agent.rs
new file mode 100644
index 0000000000..429f9b5214
--- /dev/null
+++ b/libs/cua-spacesd/crates/cua-spacesd/src/vsock_agent.rs
@@ -0,0 +1,322 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The guest end of a macOS VM's host channel: a listener on the VM's
+//! virtio socket (vsock) that carries a host connection to one of the
+//! guest's own loopback ports.
+//!
+//! A macOS VM on a Mac sits on Apple's shared VM network, and a connect
+//! from the host to its address is subject to macOS Local Network privacy
+//! (per app) and to a VPN's routes. The host process that runs the VM
+//! (Lume) can instead reach the guest over vsock, which neither touches:
+//! it publishes `127.0.0.1:<port>` on the host and, for each connection,
+//! asks this agent to connect to the guest's `127.0.0.1:<guest port>`.
+//!
+//! The protocol is the Linux microVM init's (`cua_microvm_init`): one JSON
+//! line from the host, one JSON line back, then (for `forward`) raw bytes
+//! both ways. Only the host side of the VM can reach a guest's vsock.
+
+use std::fs::File;
+use std::io::{BufRead, BufReader, Read, Write};
+use std::net::{Shutdown, TcpStream};
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+
+use serde::{Deserialize, Serialize};
+
+/// The vsock port the agent listens on (`cua_microvm_init::PORT`).
+pub const PORT: u32 = 1024;
+
+/// Longest request line read.
+const MAX_LINE: usize = 4096;
+
+/// A request from the host.
+#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
+#[serde(tag = "op", rename_all = "snake_case")]
+pub enum Request {
+ /// Liveness: answered `{"ok":true}`.
+ Ping,
+ /// Connect to the guest's `127.0.0.1:port`, answer, then carry bytes.
+ Forward { port: u16 },
+}
+
+/// The answer line.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
+pub struct Reply {
+ pub ok: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+impl Reply {
+ fn ok() -> Self {
+ Self {
+ ok: true,
+ error: None,
+ }
+ }
+
+ fn err(e: impl std::fmt::Display) -> Self {
+ Self {
+ ok: false,
+ error: Some(e.to_string()),
+ }
+ }
+
+ fn line(&self) -> Vec<u8> {
+ let mut out = serde_json::to_vec(self).unwrap_or_else(|_| b"{\"ok\":false}".to_vec());
+ out.push(b'\n');
+ out
+ }
+}
+
+/// Whether this Mac is a virtual machine (`kern.hv_vmm_present`): only a
+/// guest has a host to listen for.
+pub fn in_vm() -> bool {
+ let mut value: libc::c_int = 0;
+ let mut len = std::mem::size_of::<libc::c_int>();
+ let name = c"kern.hv_vmm_present";
+ // SAFETY: a plain sysctl read into a c_int-sized buffer.
+ let rc = unsafe {
+ libc::sysctlbyname(
+ name.as_ptr(),
+ (&mut value as *mut libc::c_int).cast(),
+ &mut len,
+ std::ptr::null_mut(),
+ 0,
+ )
+ };
+ rc == 0 && value == 1
+}
+
+/// Starts the agent on a thread of its own when this Mac is a VM with a
+/// virtio socket device. Without one (an older host, or a VM started
+/// without it) the listen fails and the host reaches the guest over its
+/// network address, as before.
+pub fn start() {
+ if !in_vm() {
+ return;
+ }
+ let listener = match listen(PORT) {
+ Ok(fd) => fd,
+ Err(e) => {
+ tracing::debug!(error = %e, "no virtio socket; the host reaches this VM over its network");
+ return;
+ }
+ };
+ tracing::info!(port = PORT, "host channel listening on vsock");
+ let spawned = std::thread::Builder::new()
+ .name("vsock-agent".into())
+ .spawn(move || accept_loop(listener));
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "could not start the vsock agent");
+ }
+}
+
+fn listen(port: u32) -> std::io::Result<OwnedFd> {
+ // SAFETY: socket/bind/listen on a fresh fd that OwnedFd then owns.
+ unsafe {
+ let fd = libc::socket(libc::AF_VSOCK, libc::SOCK_STREAM, 0);
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ let fd = OwnedFd::from_raw_fd(fd);
+ libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC);
+ let mut addr: libc::sockaddr_vm = std::mem::zeroed();
+ addr.svm_len = std::mem::size_of::<libc::sockaddr_vm>() as u8;
+ addr.svm_family = libc::AF_VSOCK as libc::sa_family_t;
+ addr.svm_port = port;
+ addr.svm_cid = libc::VMADDR_CID_ANY;
+ if libc::bind(
+ fd.as_raw_fd(),
+ (&addr as *const libc::sockaddr_vm).cast(),
+ std::mem::size_of::<libc::sockaddr_vm>() as libc::socklen_t,
+ ) != 0
+ || libc::listen(fd.as_raw_fd(), 64) != 0
+ {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(fd)
+ }
+}
+
+fn accept_loop(listener: OwnedFd) {
+ loop {
+ // SAFETY: accept on a listening socket; the new fd is owned below.
+ let fd = unsafe {
+ libc::accept(
+ listener.as_raw_fd(),
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ )
+ };
+ if fd < 0 {
+ let e = std::io::Error::last_os_error();
+ if e.kind() == std::io::ErrorKind::Interrupted {
+ continue;
+ }
+ tracing::warn!(error = %e, "vsock accept failed; the agent stops");
+ return;
+ }
+ // SAFETY: `fd` is a fresh connected socket nothing else owns.
+ let conn = unsafe { File::from_raw_fd(fd) };
+ let _ = std::thread::Builder::new()
+ .name("vsock-conn".into())
+ .spawn(move || handle(conn));
+ }
+}
+
+/// Serves one host connection (any stream socket; tests use a Unix pair).
+pub fn handle(conn: File) {
+ let Ok(writer) = conn.try_clone() else {
+ return;
+ };
+ let mut reader = BufReader::new(conn);
+ let mut line = Vec::new();
+ match (&mut reader)
+ .take(MAX_LINE as u64)
+ .read_until(b'\n', &mut line)
+ {
+ Ok(0) | Err(_) => return,
+ Ok(_) => {}
+ }
+ let request = serde_json::from_slice::<Request>(trim(&line));
+ match request {
+ Ok(Request::Ping) => {
+ let _ = (&writer).write_all(&Reply::ok().line());
+ }
+ Ok(Request::Forward { port }) => forward(port, reader, writer),
+ Err(e) => {
+ let _ = (&writer).write_all(&Reply::err(format!("bad request: {e}")).line());
+ }
+ }
+}
+
+fn trim(line: &[u8]) -> &[u8] {
+ let end = line
+ .iter()
+ .rposition(|b| !b.is_ascii_whitespace())
+ .map_or(0, |i| i + 1);
+ &line[..end]
+}
+
+/// Connects to the guest's `127.0.0.1:port`, answers, then copies bytes
+/// both ways until either side closes. Bytes the host sent after its
+/// request line (already in `reader`'s buffer) go first.
+fn forward(port: u16, mut reader: BufReader<File>, mut writer: File) {
+ let tcp = match TcpStream::connect(("127.0.0.1", port)) {
+ Ok(t) => t,
+ Err(e) => {
+ let _ = writer.write_all(&Reply::err(format!("127.0.0.1:{port}: {e}")).line());
+ return;
+ }
+ };
+ let _ = tcp.set_nodelay(true);
+ if writer.write_all(&Reply::ok().line()).is_err() {
+ return;
+ }
+ let (Ok(mut to_guest), Ok(mut from_guest)) = (tcp.try_clone(), tcp.try_clone()) else {
+ return;
+ };
+ let pending = reader.buffer().to_vec();
+ let up = std::thread::spawn(move || {
+ if to_guest.write_all(&pending).is_ok() {
+ let _ = std::io::copy(reader.get_mut(), &mut to_guest);
+ }
+ let _ = to_guest.shutdown(Shutdown::Write);
+ });
+ let _ = std::io::copy(&mut from_guest, &mut writer);
+ // Half-close toward the host; the other direction may still be open.
+ // SAFETY: shutdown on a socket fd this function holds.
+ unsafe {
+ libc::shutdown(writer.as_raw_fd(), libc::SHUT_WR);
+ }
+ let _ = up.join();
+ let _ = tcp.shutdown(Shutdown::Both);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{BufRead, BufReader, Read, Write};
+ use std::os::unix::net::UnixStream;
+
+ fn pair() -> (UnixStream, File) {
+ let (host, guest) = UnixStream::pair().unwrap();
+ (host, File::from(OwnedFd::from(guest)))
+ }
+
+ fn reply(host: &UnixStream) -> String {
+ let mut line = String::new();
+ BufReader::new(host).read_line(&mut line).unwrap();
+ line
+ }
+
+ #[test]
+ fn requests_parse_as_the_microvm_init_protocol() {
+ assert_eq!(
+ serde_json::from_str::<Request>(r#"{"op":"forward","port":3211}"#).unwrap(),
+ Request::Forward { port: 3211 }
+ );
+ assert_eq!(
+ serde_json::from_str::<Request>(r#"{"op":"ping"}"#).unwrap(),
+ Request::Ping
+ );
+ assert!(serde_json::from_str::<Request>(r#"{"op":"exec"}"#).is_err());
+ assert_eq!(Reply::ok().line(), b"{\"ok\":true}\n");
+ }
+
+ #[test]
+ fn ping_answers_ok() {
+ let (mut host, guest) = pair();
+ let t = std::thread::spawn(move || handle(guest));
+ host.write_all(b"{\"op\":\"ping\"}\n").unwrap();
+ assert_eq!(reply(&host), "{\"ok\":true}\n");
+ t.join().unwrap();
+ }
+
+ #[test]
+ fn an_unknown_request_is_refused() {
+ let (mut host, guest) = pair();
+ let t = std::thread::spawn(move || handle(guest));
+ host.write_all(b"{\"op\":\"exec\"}\n").unwrap();
+ assert!(reply(&host).starts_with("{\"ok\":false"));
+ t.join().unwrap();
+ }
+
+ #[test]
+ fn forward_carries_bytes_both_ways_including_early_ones() {
+ let service = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = service.local_addr().unwrap().port();
+ let echo = std::thread::spawn(move || {
+ let (mut s, _) = service.accept().unwrap();
+ let mut got = Vec::new();
+ s.read_to_end(&mut got).unwrap();
+ s.write_all(&got).unwrap();
+ });
+ let (mut host, guest) = pair();
+ let t = std::thread::spawn(move || handle(guest));
+ // The request and the first payload bytes in one write.
+ host.write_all(format!("{{\"op\":\"forward\",\"port\":{port}}}\nhello").as_bytes())
+ .unwrap();
+ host.shutdown(Shutdown::Write).unwrap();
+ let mut all = String::new();
+ host.read_to_string(&mut all).unwrap();
+ assert_eq!(all, "{\"ok\":true}\nhello");
+ echo.join().unwrap();
+ t.join().unwrap();
+ }
+
+ #[test]
+ fn forward_to_a_closed_port_says_why() {
+ let port = {
+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ l.local_addr().unwrap().port()
+ };
+ let (mut host, guest) = pair();
+ let t = std::thread::spawn(move || handle(guest));
+ host.write_all(format!("{{\"op\":\"forward\",\"port\":{port}}}\n").as_bytes())
+ .unwrap();
+ assert!(reply(&host).starts_with("{\"ok\":false"));
+ t.join().unwrap();
+ }
+}
diff --git a/libs/cua/crates/cua-vmm/src/lume/client.rs b/libs/cua/crates/cua-vmm/src/lume/client.rs
index 79cd76068b..a4314deed8 100644
--- a/libs/cua/crates/cua-vmm/src/lume/client.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/client.rs
@@ -55,6 +55,15 @@ pub struct VmDetails {
/// saved states; older ones never report it).
#[serde(default)]
pub saved_state: bool,
+ /// The running VM forwards host loopback ports to its guest over vsock
+ /// (a run with [`RunVm::forwards`] on a Lume that supports it).
+ #[serde(default)]
+ pub vsock: bool,
+ /// Guest port to host loopback port, once the guest's vsock agent
+ /// answers ([`RunVm::forwards`]); empty before that, and on a Lume or a
+ /// guest without the agent.
+ #[serde(default)]
+ pub forwards: std::collections::BTreeMap<u16, u16>,
}
impl VmDetails {
@@ -64,6 +73,18 @@ impl VmDetails {
.as_deref()
.filter(|ip| !ip.is_empty() && *ip != "unknown" && !ip.starts_with("0.0.0.0"))
}
+
+ /// The host loopback port for each of `ports` over vsock, when every
+ /// one of them is forwarded and the guest agent answers.
+ pub fn vsock_ports(&self, ports: &[u16]) -> Option<std::collections::BTreeMap<u16, u16>> {
+ if ports.is_empty() || self.forwards.is_empty() {
+ return None;
+ }
+ ports
+ .iter()
+ .map(|p| self.forwards.get(p).map(|h| (*p, *h)))
+ .collect()
+ }
}
/// Parsed `vnc://:PASSWORD@HOST:PORT`.
@@ -141,6 +162,11 @@ pub struct RunVm {
pub storage: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub disk_path: Option<String>,
+ /// Guest ports Lume publishes on host loopback ports over a virtio
+ /// socket device (reported back in [`VmDetails::forwards`]). A Lume
+ /// without the option ignores it.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub forwards: Vec<u16>,
}
#[derive(Clone, Debug, Serialize)]
diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rs
index f6e187197f..d3e07b1227 100644
--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs
@@ -49,6 +49,16 @@ pub const MACOS_SETUP_TOKEN_FILE: &str = "env-token";
/// `setup`; [`crate::StartSpec::mounts`] add more.
pub const MACOS_SHARE_ROOT: &str = "/Volumes/My Shared Files";
+/// The host a macOS guest's published ports are dialed on once they are
+/// forwarded over vsock ([`client::VmDetails::forwards`]).
+pub const VSOCK_HOST: &str = "127.0.0.1";
+
+/// How long a start keeps waiting for a guest's vsock path after its
+/// network address turned out unreachable (Local Network privacy or a VPN)
+/// before it reports that: the agent starts with the guest's services, so
+/// a guest that has one answers well within this.
+pub const VSOCK_GRACE: Duration = Duration::from_secs(30);
+
/// Where a macOS guest sees the shared host directory `host`.
pub fn macos_share_path(host: &std::path::Path) -> String {
format!(
@@ -844,6 +854,18 @@ impl LumeRuntime {
}),
None => None,
};
+ // A macOS guest whose vsock agent answers: its published ports are
+ // host loopback ports Lume carries over vsock, which neither macOS
+ // Local Network privacy nor a VPN's routes touch.
+ if let Some(forwarded) = vm.vsock_ports(ports) {
+ return Endpoints {
+ host: VSOCK_HOST.into(),
+ ports: forwarded,
+ vnc,
+ ssh,
+ ..Default::default()
+ };
+ }
Endpoints {
host: ip,
// Lume VMs sit on a host-reachable NAT network: guest ports are
@@ -1023,6 +1045,14 @@ impl LumeRuntime {
Ok(RunVm {
no_display: true,
shared_directories,
+ // The published ports also over vsock (the IP stays the
+ // fallback for a guest without the agent). A restart publishes
+ // what the start did, so a state saved with the socket device
+ // restores into one.
+ forwards: match spec {
+ Some(s) => s.ports.clone(),
+ None => self.load_ports(name),
+ },
..Default::default()
})
}
@@ -1991,14 +2021,112 @@ impl LumeRuntime {
crate::progress::Phase::WaitingForServices,
));
}
- crate::probe::wait_all(
+ self.wait_services(
&spec.name,
- &inst.endpoints,
+ inst,
+ spec.ssh.as_ref(),
+ &spec.ports,
&spec.probes,
spec.ready_timeout,
)
- .await?;
- Ok(inst)
+ .await
+ }
+
+ /// Waits for `probes` on the VM `name` (started with `ports` forwarded
+ /// over vsock, [`Self::macos_run`]) and returns the instance to use:
+ /// the vsock path (host loopback ports) once the guest agent answers,
+ /// else the VM's address (`ip_inst`). Both are tried together; a VM
+ /// address that has no route (macOS Local Network privacy, a VPN) only
+ /// fails the wait when the vsock path also fails to come up within
+ /// [`VSOCK_GRACE`] (a guest without the agent, or a Lume without vsock).
+ async fn wait_services(
+ &self,
+ name: &str,
+ ip_inst: Instance,
+ ssh: Option<&SshAccess>,
+ ports: &[u16],
+ probes: &[Probe],
+ timeout: Duration,
+ ) -> Result<Instance> {
+ let deadline = tokio::time::Instant::now() + timeout;
+ if ip_inst.endpoints.host == VSOCK_HOST || ports.is_empty() {
+ crate::probe::wait_all(name, &ip_inst.endpoints, probes, timeout).await?;
+ return Ok(ip_inst);
+ }
+ let via_vsock = async {
+ let inst = self.vsock_instance(name, ssh, ports, deadline).await?;
+ let left = deadline.saturating_duration_since(tokio::time::Instant::now());
+ crate::probe::wait_all(name, &inst.endpoints, probes, left)
+ .await
+ .ok()?;
+ Some(inst)
+ };
+ let ip_endpoints = ip_inst.endpoints.clone();
+ let via_ip = crate::probe::wait_all(name, &ip_endpoints, probes, timeout);
+ tokio::pin!(via_vsock, via_ip);
+ let mut vsock_over = false;
+ loop {
+ tokio::select! {
+ biased;
+ r = &mut via_vsock, if !vsock_over => match r {
+ Some(inst) => return Ok(inst),
+ None => vsock_over = true,
+ },
+ ip = &mut via_ip => {
+ // Both work: prefer the path a VPN connecting later
+ // cannot break, when it is already up. No route: give
+ // the vsock path its grace before saying so.
+ let tail = match &ip {
+ Ok(()) => Duration::from_secs(2),
+ Err(_) => VSOCK_GRACE,
+ };
+ if !vsock_over
+ && let Ok(Some(inst)) = tokio::time::timeout(tail, &mut via_vsock).await
+ {
+ if let Err(e) = &ip {
+ tracing::info!(vm = name, error = %e, "reached the guest over vsock; its address did not answer");
+ }
+ return Ok(inst);
+ }
+ return ip.map(|()| ip_inst);
+ }
+ }
+ }
+ }
+
+ /// The instance on the vsock path once Lume reports `ports` forwarded
+ /// with the guest agent answering, or `None` when it never will (Lume
+ /// runs the VM without vsock) or `deadline` passes.
+ async fn vsock_instance(
+ &self,
+ name: &str,
+ ssh: Option<&SshAccess>,
+ ports: &[u16],
+ deadline: tokio::time::Instant,
+ ) -> Option<Instance> {
+ // Lume records the forwards right after the VM starts: a VM seen
+ // running without them this many times in a row has none.
+ const NO_VSOCK_POLLS: u32 = 4;
+ let mut running_without = 0;
+ while tokio::time::Instant::now() < deadline {
+ if let Ok(Some(vm)) = self.client.get(name).await {
+ if vm.vsock_ports(ports).is_some() {
+ return Some(Self::instance(&vm, ssh, ports));
+ }
+ // An older Lume, or a resume of a state saved without the
+ // socket device.
+ if map_status(&vm.status) == Status::Running && !vm.vsock {
+ running_without += 1;
+ if running_without >= NO_VSOCK_POLLS {
+ return None;
+ }
+ } else {
+ running_without = 0;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ None
}
async fn stop_vm(&self, name: &str) -> Result<()> {
@@ -2139,8 +2267,15 @@ impl LumeRuntime {
self.client.run(&building, &run).await?;
let vm = self.wait_for_ip(&building).await?;
let inst = Self::instance(&vm, None, &spec.ports);
- crate::probe::wait_all(&building, &inst.endpoints, &spec.probes, spec.ready_timeout)
- .await?;
+ self.wait_services(
+ &building,
+ inst,
+ None,
+ &spec.ports,
+ &spec.probes,
+ spec.ready_timeout,
+ )
+ .await?;
tokio::time::sleep(settle).await;
let ready = started.elapsed();
self.client.suspend(&building).await?;
@@ -3819,4 +3954,69 @@ mod tests {
assert_eq!(ep.vnc.as_ref().unwrap().port, 5905);
assert_eq!(ep.vnc.as_ref().unwrap().password.as_deref(), Some("pw"));
}
+
+ #[test]
+ fn forwarded_ports_are_dialed_on_loopback_once_every_one_is_there() {
+ let vm: VmDetails = serde_json::from_value(serde_json::json!({
+ "name": "m", "os": "macOS", "status": "running",
+ "ipAddress": "192.168.64.9",
+ "vsock": true, "forwards": { "3211": 50123, "8080": 50124 }
+ }))
+ .unwrap();
+ let ep = LumeRuntime::endpoints_from(&vm, None, &[3211, 8080]);
+ assert_eq!(ep.host, VSOCK_HOST);
+ assert_eq!(ep.addr(3211).as_deref(), Some("127.0.0.1:50123"));
+ assert_eq!(ep.host_port(22), None);
+ // SSH stays on the VM's address.
+ assert_eq!(ep.ssh.as_ref().unwrap().host, "192.168.64.9");
+ // A port Lume does not forward: the VM's address for all of them.
+ let ep = LumeRuntime::endpoints_from(&vm, None, &[3211, 9000]);
+ assert_eq!(ep.host, "192.168.64.9");
+ assert_eq!(ep.host_port(9000), Some(9000));
+ }
+
+ #[test]
+ fn forwards_count_only_once_the_agent_answers() {
+ // Lume reports the forwards only then; before, `vsock` alone.
+ let vm: VmDetails = serde_json::from_value(serde_json::json!({
+ "name": "m", "status": "running", "ipAddress": "192.168.64.9", "vsock": true
+ }))
+ .unwrap();
+ assert!(vm.vsock && vm.vsock_ports(&[3211]).is_none());
+ // An older Lume reports neither.
+ let old: VmDetails =
+ serde_json::from_value(serde_json::json!({ "name": "m", "status": "running" }))
+ .unwrap();
+ assert!(!old.vsock && old.forwards.is_empty());
+ }
+
+ #[test]
+ fn a_macos_run_forwards_its_published_ports() {
+ let dir = tempfile::tempdir().unwrap();
+ let rt = LumeRuntime::new(LumeConfig {
+ root: dir.path().to_path_buf(),
+ ..LumeConfig::default()
+ });
+ let spec = StartSpec::new("m", ImageSource::Existing)
+ .os(GuestOs::Macos)
+ .port(3211);
+ let run = rt.macos_run("m", Some(&spec)).unwrap();
+ assert_eq!(run.forwards, vec![3211]);
+ assert_eq!(
+ serde_json::to_value(&run).unwrap()["forwards"],
+ serde_json::json!([3211])
+ );
+ // A restart forwards what the start published.
+ rt.save_ports("m", &[3211]);
+ assert_eq!(rt.macos_run("m", None).unwrap().forwards, vec![3211]);
+ // Nothing published: the field is left out (an older Lume never sees it).
+ let bare = StartSpec::new("n", ImageSource::Existing).os(GuestOs::Macos);
+ let run = rt.macos_run("n", Some(&bare)).unwrap();
+ assert!(
+ serde_json::to_value(&run)
+ .unwrap()
+ .get("forwards")
+ .is_none()
+ );
+ }
}
diff --git a/libs/cua/crates/cua-vmm/tests/lume_resume.rs b/libs/cua/crates/cua-vmm/tests/lume_resume.rs
index 773319d455..e86896bb22 100644
--- a/libs/cua/crates/cua-vmm/tests/lume_resume.rs
+++ b/libs/cua/crates/cua-vmm/tests/lume_resume.rs
@@ -81,7 +81,9 @@ async fn resume_boots_a_stopped_macos_vm_with_its_setup_share() {
"noDisplay": true,
"sharedDirectories": [
{ "hostPath": setup.display().to_string(), "readOnly": true }
- ]
+ ],
+ // The ports the first start published, over vsock too.
+ "forwards": [3211]
})
);
assert_eq!(st.vms[name]["status"], "running");
diff --git a/libs/cua/crates/cua-vmm/tests/lume_vsock.rs b/libs/cua/crates/cua-vmm/tests/lume_vsock.rs
new file mode 100644
index 0000000000..04180c4a22
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/lume_vsock.rs
@@ -0,0 +1,108 @@
+//! A macOS guest's published ports go over vsock when Lume forwards them:
+//! the start asks for them, waits for its services on the host loopback
+//! ports Lume reports, and hands those out, so neither macOS Local Network
+//! privacy nor a VPN's routes stand between this Mac and its own VM.
+//! Hermetic: a fake `lume serve` and a loopback listener as the guest.
+
+#![cfg(feature = "lume")]
+
+#[allow(dead_code)]
+#[path = "support/fake_lume.rs"]
+mod fake_lume;
+
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use cua_vmm::lume::{VSOCK_HOST, base_vm_name};
+use cua_vmm::{GuestOs, ImageSource, Probe, Runtime, StartSpec};
+use fake_lume::{FakeLume, serve};
+use serde_json::{Value, json};
+
+const REF: &str = "ghcr.io/trycua/macos:26";
+
+/// A guest service as Lume's forward presents it: a loopback port that
+/// accepts and keeps connections open.
+fn guest_service() -> u16 {
+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = l.local_addr().unwrap().port();
+ std::thread::spawn(move || {
+ let mut held = Vec::new();
+ for c in l.incoming().flatten() {
+ held.push(c);
+ }
+ });
+ port
+}
+
+async fn fake(forwards: Option<Value>) -> Arc<Mutex<FakeLume>> {
+ let mut st = FakeLume {
+ vsock_forwards: forwards,
+ ..Default::default()
+ };
+ let base = base_vm_name(REF);
+ st.vms.insert(
+ base.clone(),
+ json!({
+ "name": base, "os": "macOS", "cpuCount": 4, "memorySize": 8u64 << 30,
+ "diskSize": { "allocated": 1u64 << 30, "total": 150u64 << 30 },
+ "display": "1024x768", "status": "stopped"
+ }),
+ );
+ Arc::new(Mutex::new(st))
+}
+
+fn spec(name: &str) -> StartSpec {
+ StartSpec::new(
+ name,
+ ImageSource::Oci {
+ reference: REF.into(),
+ },
+ )
+ .os(GuestOs::Macos)
+ .port(3211)
+ .probe(Probe::tcp(3211))
+ .ready_timeout(Duration::from_secs(20))
+}
+
+#[tokio::test]
+async fn a_macos_start_uses_the_vsock_forwards_lume_reports() {
+ let host_port = guest_service();
+ let state = fake(Some(json!({ "3211": host_port }))).await;
+ let rt = fake_lume::runtime(serve(state.clone()).await);
+
+ // The VM's address (TEST-NET-1) never answers; the vsock path does.
+ let inst = rt.start(&spec("cua-e2e-vsock")).await.unwrap();
+ assert_eq!(inst.endpoints.host, VSOCK_HOST);
+ assert_eq!(inst.endpoints.host_port(3211), Some(host_port));
+ assert_eq!(
+ inst.endpoints.host_port(22),
+ None,
+ "never the host's own sshd"
+ );
+
+ let run = {
+ let st = state.lock().unwrap();
+ st.calls
+ .iter()
+ .find(|(m, p, _)| m == "POST" && p.ends_with("/run"))
+ .map(|(_, _, body)| body.clone())
+ .unwrap()
+ };
+ assert_eq!(run["forwards"], json!([3211]));
+
+ // Another process reattaching by name sees the same path.
+ let again = rt.endpoints("cua-e2e-vsock").await.unwrap();
+ assert_eq!(again.host, VSOCK_HOST);
+ assert_eq!(again.host_port(3211), Some(host_port));
+}
+
+#[tokio::test]
+async fn without_vsock_a_start_keeps_the_vm_address() {
+ let state = fake(None).await;
+ let rt = fake_lume::runtime(serve(state.clone()).await);
+ let mut s = spec("cua-e2e-no-vsock");
+ s.probes.clear();
+ let inst = rt.start(&s).await.unwrap();
+ assert_eq!(inst.endpoints.host, "192.0.2.10");
+ assert_eq!(inst.endpoints.host_port(3211), Some(3211));
+}
diff --git a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
index eb9d1a542d..beda1b4615 100644
--- a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
+++ b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
@@ -45,6 +45,9 @@ pub struct FakeLume {
pub pulling: BTreeMap<String, u64>,
/// The server stopped (a killed `lume serve`): it accepts nothing more.
pub dead: bool,
+ /// A Lume with vsock forwards: a run with `forwards` reports these host
+ /// ports (guest port as a string key) with the guest agent answering.
+ pub vsock_forwards: Option<Value>,
}
/// An async pull: it reports `step` more bytes of `total` on each
@@ -187,6 +190,11 @@ fn handle(st: &mut FakeLume, method: &str, path: &str, body: Value) -> (u16, Val
} else {
vm["ipAddress"] = json!("192.0.2.10");
}
+ let wants_forwards = body["forwards"].as_array().is_some_and(|f| !f.is_empty());
+ if let (Some(forwards), true) = (&st.vsock_forwards, wants_forwards) {
+ vm["vsock"] = json!(true);
+ vm["forwards"] = forwards.clone();
+ }
(202, json!({ "message": "starting" }))
}
("POST", p) if p.ends_with("/stop") => {
diff --git a/libs/lume/src/FileSystem/Home.swift b/libs/lume/src/FileSystem/Home.swift
index 10e9b5ffc2..3e6475cfb3 100644
--- a/libs/lume/src/FileSystem/Home.swift
+++ b/libs/lume/src/FileSystem/Home.swift
@@ -279,6 +279,10 @@ final class Home {
if fileName.hasPrefix(sourceDir.statePath.name) {
guard includeSavedState, fileName == sourceDir.statePath.name else { continue }
}
+ // The state's device marker goes with the state; a running VM's
+ // forwards never go to a clone.
+ if fileName == sourceDir.stateVsockPath.name && !includeSavedState { continue }
+ if fileName == sourceDir.vsockSessionPath.name { continue }
if fileName == "disk.img" || fileName == sourceDir.statePath.name {
// Use clonefile(2) for disk.img (instant APFS copy-on-write)
diff --git a/libs/lume/src/FileSystem/VMDirectory.swift b/libs/lume/src/FileSystem/VMDirectory.swift
index b51cdc006a..1c36a18ed0 100644
--- a/libs/lume/src/FileSystem/VMDirectory.swift
+++ b/libs/lume/src/FileSystem/VMDirectory.swift
@@ -22,6 +22,8 @@ struct VMDirectory: Sendable {
static let diskBackup = "disk.img.pre-resize"
static let configBackup = "config.json.pre-resize"
static let savedState = "state.vzvmsave"
+ static let savedStateVsock = "state.vsock"
+ static let vsockSession = "vsock.json"
}
// MARK: - Properties
@@ -39,6 +41,12 @@ struct VMDirectory: Sendable {
let resizeGuardPath: Path
/// The VM's saved machine state (`lume suspend`), restored by the next run.
let statePath: Path
+ /// Present when the saved state was saved with a virtio socket device
+ /// (a run with host port forwards): a state restores only into the
+ /// devices it was saved with.
+ let stateVsockPath: Path
+ /// The running VM's host port forwards over vsock ([`VsockSession`]).
+ let vsockSessionPath: Path
/// The name of the VM directory
var name: String { dir.name }
@@ -59,6 +67,8 @@ struct VMDirectory: Sendable {
self.diskBackupPath = dir.file(FileNames.diskBackup)
self.configBackupPath = dir.file(FileNames.configBackup)
self.statePath = dir.file(FileNames.savedState)
+ self.stateVsockPath = dir.file(FileNames.savedStateVsock)
+ self.vsockSessionPath = dir.file(FileNames.vsockSession)
self.resizeGuardPath = Path(
dir.url.deletingLastPathComponent()
.appendingPathComponent(".\(dir.name).resize.guard", isDirectory: false))
@@ -105,6 +115,36 @@ extension VMDirectory {
/// disk no longer matches the memory the state holds.
func discardSavedState() {
try? FileManager.default.removeItem(atPath: statePath.path)
+ try? FileManager.default.removeItem(atPath: stateVsockPath.path)
+ }
+
+ /// Whether the saved state was saved with a virtio socket device.
+ func savedStateHasVsock() -> Bool {
+ hasSavedState() && stateVsockPath.exists()
+ }
+
+ /// Records whether the state just saved has a virtio socket device.
+ func markSavedStateVsock(_ present: Bool) {
+ if present {
+ FileManager.default.createFile(atPath: stateVsockPath.path, contents: Data())
+ } else {
+ try? FileManager.default.removeItem(atPath: stateVsockPath.path)
+ }
+ }
+
+ /// The running VM's vsock forwards, when it was started with some.
+ func loadVsockSession() -> VsockSession? {
+ guard let data = try? Data(contentsOf: vsockSessionPath.url) else { return nil }
+ return try? JSONDecoder().decode(VsockSession.self, from: data)
+ }
+
+ func saveVsockSession(_ session: VsockSession) {
+ guard let data = try? JSONEncoder().encode(session) else { return }
+ try? data.write(to: vsockSessionPath.url, options: .atomic)
+ }
+
+ func clearVsockSession() {
+ try? FileManager.default.removeItem(atPath: vsockSessionPath.path)
}
}
@@ -492,6 +532,7 @@ extension VMDirectory {
guard let config = try? loadConfig() else {
return nil
}
+ let vsockSession = status == "running" ? loadVsockSession() : nil
return VMDetails(
name: name,
@@ -511,7 +552,9 @@ extension VMDirectory {
downloadProgress: downloadProgress,
machineIdentifier: config.machineIdentifier?.base64EncodedString(),
macAddress: config.macAddress,
- savedState: hasSavedState()
+ savedState: hasSavedState(),
+ vsock: vsockSession.map { _ in true },
+ forwards: vsockSession.flatMap { $0.agent ? $0.forwards : nil }
)
}
}
diff --git a/libs/lume/src/LumeController.swift b/libs/lume/src/LumeController.swift
index cb1525d192..34c8c47994 100644
--- a/libs/lume/src/LumeController.swift
+++ b/libs/lume/src/LumeController.swift
@@ -1348,6 +1348,7 @@ final class LumeController {
networkMode: NetworkMode? = nil,
clipboard: Bool = false,
vncPolicy: VNCPolicy = .enabled,
+ forwards: [UInt16] = [],
telemetryTransport: TelemetryTransport = .cli
) async throws {
let normalizedName = normalizeVMName(name: name)
@@ -1498,7 +1499,8 @@ final class LumeController {
additionalDiskPaths: additionalDiskPaths,
networkMode: networkMode,
clipboard: clipboard,
- vncPolicy: vncPolicy)
+ vncPolicy: vncPolicy,
+ forwards: forwards)
// `run` returns once the guest has stopped, including when it shut
// itself down, so the VM no longer runs in this process.
SharedVM.shared.removeVM(name: normalizedName, ifSame: vm)
diff --git a/libs/lume/src/Server/APIDocExtractor.swift b/libs/lume/src/Server/APIDocExtractor.swift
index 04095f52b6..670025db8d 100644
--- a/libs/lume/src/Server/APIDocExtractor.swift
+++ b/libs/lume/src/Server/APIDocExtractor.swift
@@ -321,7 +321,8 @@ enum APIDocExtractor {
APIFieldDoc(name: "recoveryMode", type: "boolean", required: false, description: "Boot macOS VM in recovery mode", defaultValue: "false"),
APIFieldDoc(name: "storage", type: "string", required: false, description: "VM storage location", defaultValue: nil),
APIFieldDoc(name: "clipboard", type: "boolean", required: false, description: "Enable bidirectional clipboard sync via SSH (experimental)", defaultValue: "false"),
- APIFieldDoc(name: "vnc", type: "string", required: false, description: "VNC server policy: 'enabled' or 'disabled'. 'disabled' requires noDisplay=true, starts no VNC listener, and reports a null vncUrl", defaultValue: "enabled")
+ APIFieldDoc(name: "vnc", type: "string", required: false, description: "VNC server policy: 'enabled' or 'disabled'. 'disabled' requires noDisplay=true, starts no VNC listener, and reports a null vncUrl", defaultValue: "enabled"),
+ APIFieldDoc(name: "forwards", type: "array", required: false, description: "Guest ports to publish on host loopback ports over a virtio socket device, through Cua's guest vsock agent. GET reports the host ports under 'forwards' once the agent answers; these connections are not subject to macOS Local Network privacy or VPN routes", defaultValue: nil)
]
),
responseBody: APIResponseDoc(
diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swift
index 64bf7ad649..fcf5a067dc 100644
--- a/libs/lume/src/Server/Handlers.swift
+++ b/libs/lume/src/Server/Handlers.swift
@@ -629,7 +629,8 @@ extension Server {
nvramPath: request.nvramPath.map { Path($0) },
networkMode: networkMode,
clipboard: request.clipboard ?? false,
- vncPolicy: vncPolicy
+ vncPolicy: vncPolicy,
+ forwards: request.forwards ?? []
)
Logger.info("VM start initiated in background", metadata: ["name": name])
@@ -1106,7 +1107,8 @@ extension Server {
nvramPath: Path? = nil,
networkMode: NetworkMode? = nil,
clipboard: Bool = false,
- vncPolicy: VNCPolicy = .enabled
+ vncPolicy: VNCPolicy = .enabled,
+ forwards: [UInt16] = []
) {
Logger.info(
"Starting VM in detached task",
@@ -1142,6 +1144,7 @@ extension Server {
networkMode: networkMode,
clipboard: clipboard,
vncPolicy: vncPolicy,
+ forwards: forwards,
telemetryTransport: .http
)
Logger.info("VM run ended in background task", metadata: ["name": name])
diff --git a/libs/lume/src/Server/Requests.swift b/libs/lume/src/Server/Requests.swift
index 5a752d1a20..05e8319a3f 100644
--- a/libs/lume/src/Server/Requests.swift
+++ b/libs/lume/src/Server/Requests.swift
@@ -23,6 +23,10 @@ struct RunVMRequest: Codable {
/// "enabled" (default) or "disabled". Absent keeps the historic behavior of
/// always starting a VNC server.
let vnc: String?
+ /// Guest ports to publish on host loopback ports over vsock (the VM
+ /// gets a virtio socket device; the guest needs Cua's vsock agent).
+ /// `get` reports the host ports under `forwards` once the agent answers.
+ var forwards: [UInt16]? = nil
struct SharedDirectoryRequest: Codable {
let hostPath: String
diff --git a/libs/lume/src/VM/VM.swift b/libs/lume/src/VM/VM.swift
index f45b6de8dd..d36542d509 100644
--- a/libs/lume/src/VM/VM.swift
+++ b/libs/lume/src/VM/VM.swift
@@ -66,6 +66,10 @@ class VM {
/// because a VNC-disabled session's marker is not owned by `vncService`.
private var activeVNCPolicy: VNCPolicy = .enabled
private var activeNoVNCSession: VNCSession?
+ /// Host loopback ports carried to the guest over vsock (a run with
+ /// `forwards`), and whether this run's VM has the socket device.
+ private var vsockForwarder: VsockForwarder?
+ private var activeSocketDevice = false
internal let virtualizationServiceFactory:
(VMVirtualizationServiceContext) throws -> VMVirtualizationService
private let vncServiceFactory: (VMDirectory) -> VNCService
@@ -160,6 +164,7 @@ class VM {
// Check if SSH is available (only if we have an IP)
let sshAvailable: Bool? = ipAddress != nil ? NetworkUtils.isSSHAvailable(ipAddress: ipAddress!) : nil
+ let vsockSession = isRunning ? vmDirContext.dir.loadVsockSession() : nil
return VMDetails(
name: vmDirContext.name,
@@ -176,7 +181,9 @@ class VM {
networkMode: vmDirContext.config.networkMode.description,
machineIdentifier: vmDirContext.config.machineIdentifier?.base64EncodedString(),
macAddress: macAddress,
- savedState: vmDirContext.dir.hasSavedState()
+ savedState: vmDirContext.dir.hasSavedState(),
+ vsock: vsockSession.map { _ in true },
+ forwards: vsockSession.flatMap { $0.agent ? $0.forwards : nil }
)
}
@@ -196,7 +203,7 @@ class VM {
vncPort: Int = 0, vncPassword: String? = nil, recoveryMode: Bool = false,
usbMassStoragePaths: [Path]? = nil, additionalDiskPaths: [Path]? = nil,
networkMode: NetworkMode? = nil, clipboard: Bool = false,
- vncPolicy: VNCPolicy = .enabled
+ vncPolicy: VNCPolicy = .enabled, forwards: [UInt16] = []
) async throws {
// Defense in depth: the CLI and the controller reject these combinations
// first, but no caller may reach a VNC-dependent path with VNC disabled.
@@ -310,7 +317,7 @@ class VM {
Logger.info(
"Creating virtualization service context", metadata: ["name": vmDirContext.name])
- let config = try createVMVirtualizationServiceContext(
+ var config = try createVMVirtualizationServiceContext(
cpuCount: cpuCount,
memorySize: memorySize,
display: vmDirContext.config.display.string,
@@ -321,6 +328,15 @@ class VM {
additionalDiskPaths: additionalDiskPaths,
networkMode: networkMode
)
+ // A saved state restores only into the devices it was saved
+ // with: one saved without the socket device resumes without
+ // forwards (the client then uses the VM's address).
+ activeSocketDevice = Self.usesSocketDevice(
+ forwards: forwards,
+ hasSavedState: !recoveryMode && vmDirContext.dir.hasSavedState(),
+ savedStateHasVsock: vmDirContext.dir.savedStateHasVsock())
+ config.socketDevice = activeSocketDevice
+ vmDirContext.dir.clearVsockSession()
Logger.info(
"Successfully created virtualization service context",
metadata: ["name": vmDirContext.name])
@@ -411,6 +427,9 @@ class VM {
try await service.start()
}
Logger.info("VM started successfully", metadata: ["name": vmDirContext.name])
+ if activeSocketDevice {
+ startVsockForwards(forwards, service: service)
+ }
if let telemetryTransport {
TelemetryClient.shared.recordVMStarted(
transport: telemetryTransport,
@@ -823,6 +842,7 @@ class VM {
try await service.saveMachineState(to: partial)
try? FileManager.default.removeItem(at: state.url)
try FileManager.default.moveItem(at: partial, to: state.url)
+ vmDirContext.dir.markSavedStateVsock(activeSocketDevice)
} catch {
try? FileManager.default.removeItem(at: partial)
if wasRunning, service.state == .paused {
@@ -874,6 +894,9 @@ class VM {
scopedSharedDirectoryURLs.removeAll()
activeSharedDirectories.removeAll()
vncService.stop()
+ vsockForwarder?.stop()
+ vsockForwarder = nil
+ vmDirContext.dir.clearVsockSession()
if !activeVNCPolicy.isEnabled {
// No VNC service owns this run's marker, so drop it here. Doing it
// unconditionally also covers a failed start that never booted.
@@ -1419,6 +1442,49 @@ class VM {
return false
}
+ // MARK: - Host port forwards over vsock
+
+ /// Whether a run with `forwards` gets a virtio socket device: always on
+ /// a cold boot; on a resume only when the state was saved with one.
+ nonisolated static func usesSocketDevice(
+ forwards: [UInt16], hasSavedState: Bool, savedStateHasVsock: Bool
+ ) -> Bool {
+ !forwards.isEmpty && (!hasSavedState || savedStateHasVsock)
+ }
+
+ /// Publishes `forwards` on host loopback ports through the guest agent
+ /// and records them (`vsock.json`) for `get`. A failure leaves the VM
+ /// reachable on its address only.
+ private func startVsockForwards(_ forwards: [UInt16], service: VMVirtualizationService) {
+ guard let connect = service.vsockConnector() else {
+ Logger.error("The VM has no virtio socket device", metadata: ["name": vmDirContext.name])
+ return
+ }
+ do {
+ let forwarder = try VsockForwarder(guestPorts: forwards, connect: connect)
+ let dir = vmDirContext.dir
+ dir.saveVsockSession(forwarder.session(agent: false))
+ let ready = forwarder.session(agent: true)
+ let name = vmDirContext.name
+ forwarder.start {
+ dir.saveVsockSession(ready)
+ Logger.info("The guest agent answers over vsock", metadata: ["name": name])
+ }
+ vsockForwarder = forwarder
+ Logger.info(
+ "Forwarding host loopback ports over vsock",
+ metadata: [
+ "name": vmDirContext.name,
+ "forwards": forwarder.forwards.map { "\($0.value)->\($0.key)" }
+ .sorted().joined(separator: ","),
+ ])
+ } catch {
+ Logger.error(
+ "Could not forward ports over vsock",
+ metadata: ["name": vmDirContext.name, "error": "\(error)"])
+ }
+ }
+
// MARK: - Platform-specific Methods
func getOSType() -> String {
diff --git a/libs/lume/src/VM/VMDetails.swift b/libs/lume/src/VM/VMDetails.swift
index f67c7bd789..1435ffaa00 100644
--- a/libs/lume/src/VM/VMDetails.swift
+++ b/libs/lume/src/VM/VMDetails.swift
@@ -55,11 +55,18 @@ struct VMDetails: Codable {
/// The VM has a saved machine state (`POST /lume/vms/:name/suspend`)
/// that its next run resumes.
let savedState: Bool?
+ /// The running VM has a virtio socket device and forwards host loopback
+ /// ports to it (a run with `forwards`); absent otherwise.
+ let vsock: Bool?
+ /// Guest port to host loopback port (`127.0.0.1`), once the guest agent
+ /// answers over vsock; absent before that and for VMs without forwards.
+ let forwards: [String: UInt16]?
enum CodingKeys: String, CodingKey {
case name, os, cpuCount, memorySize, diskSize, display, status
case provisioningOperation, vncUrl, ipAddress, sshAvailable, locationName, sharedDirectories
case networkMode, downloadProgress, machineIdentifier, macAddress, savedState
+ case vsock, forwards
}
init(
@@ -80,7 +87,9 @@ struct VMDetails: Codable {
downloadProgress: Double? = nil,
machineIdentifier: String? = nil,
macAddress: String? = nil,
- savedState: Bool? = nil
+ savedState: Bool? = nil,
+ vsock: Bool? = nil,
+ forwards: [String: UInt16]? = nil
) {
self.name = name
self.os = os
@@ -100,6 +109,8 @@ struct VMDetails: Codable {
self.machineIdentifier = machineIdentifier
self.macAddress = macAddress
self.savedState = savedState
+ self.vsock = vsock
+ self.forwards = forwards
}
// Custom encoder to always include optional fields (even when nil)
@@ -123,5 +134,7 @@ struct VMDetails: Codable {
try container.encode(machineIdentifier, forKey: .machineIdentifier)
try container.encode(macAddress, forKey: .macAddress)
try container.encode(savedState ?? false, forKey: .savedState)
+ try container.encodeIfPresent(vsock, forKey: .vsock)
+ try container.encodeIfPresent(forwards, forKey: .forwards)
}
}
diff --git a/libs/lume/src/VM/VsockForwarder.swift b/libs/lume/src/VM/VsockForwarder.swift
new file mode 100644
index 0000000000..12709a0757
--- /dev/null
+++ b/libs/lume/src/VM/VsockForwarder.swift
@@ -0,0 +1,305 @@
+import Darwin
+import Foundation
+
+/// What `vsock.json` in a running VM's directory records: the host
+/// loopback ports a run with `forwards` publishes, and whether the guest's
+/// agent has answered on them yet. `get` and `list` (in any process) report
+/// it, so a client knows to dial `127.0.0.1:<host>` instead of the VM's
+/// address.
+struct VsockSession: Codable, Equatable {
+ /// Guest port (as a string, a JSON object key) to host loopback port.
+ var forwards: [String: UInt16]
+ /// The guest agent answered a ping: the forwards reach the guest.
+ var agent: Bool
+ /// The process that serves the forwards.
+ var pid: Int32
+}
+
+/// Host loopback ports carried to a guest over its virtio socket device.
+///
+/// A macOS VM sits on Apple's shared VM network, where a host app's connect
+/// to it is subject to macOS Local Network privacy and to a VPN's routes. A
+/// vsock stream between this process (which owns the VM) and the guest
+/// touches neither. For every forward this binds `127.0.0.1:0`; a
+/// connection there opens a vsock stream to the guest agent
+/// (`agentPort`), asks it to connect to the guest's own
+/// `127.0.0.1:<guest port>` (`{"op":"forward","port":N}`, the protocol of
+/// Cua's microVM init), and carries bytes both ways. A guest without the
+/// agent answers nothing, so the connection closes at once and the client
+/// keeps using the VM's address.
+final class VsockForwarder: @unchecked Sendable {
+ /// The vsock port the guest agent listens on.
+ static let agentPort: UInt32 = 1024
+
+ /// One vsock stream to the guest: its descriptor, and how to close it.
+ struct Stream {
+ let fd: Int32
+ let close: @Sendable () -> Void
+ }
+
+ /// Opens a vsock stream to a guest port, or `nil`.
+ typealias Connect = @Sendable (UInt32) -> Stream?
+
+ /// Guest port to host loopback port.
+ let forwards: [UInt16: UInt16]
+ /// Each listener and the guest port it carries.
+ private let listeners: [(fd: Int32, guest: UInt16)]
+ private let connect: Connect
+ private let lock = NSLock()
+ private var stopped = false
+ private var started = false
+
+ /// Binds a loopback port for each of `guestPorts` (none is served yet).
+ init(guestPorts: [UInt16], connect: @escaping Connect) throws {
+ var forwards: [UInt16: UInt16] = [:]
+ var listeners: [(fd: Int32, guest: UInt16)] = []
+ do {
+ for guest in Swift.Set(guestPorts) {
+ let (fd, port) = try Self.listenLoopback()
+ listeners.append((fd, guest))
+ forwards[guest] = port
+ }
+ } catch {
+ for l in listeners { Darwin.close(l.fd) }
+ throw error
+ }
+ self.forwards = forwards
+ self.listeners = listeners
+ self.connect = connect
+ }
+
+ deinit {
+ // Never served: nothing else closes the listeners.
+ if !started {
+ for l in listeners { Darwin.close(l.fd) }
+ }
+ }
+
+ /// The session record for `agent`.
+ func session(agent: Bool) -> VsockSession {
+ VsockSession(
+ forwards: Dictionary(
+ uniqueKeysWithValues: forwards.map { (String($0.key), $0.value) }),
+ agent: agent,
+ pid: getpid())
+ }
+
+ /// Serves the forwards, and calls `onAgent` once the guest agent first
+ /// answers a ping (checked every `interval` until `stop`).
+ func start(interval: TimeInterval = 0.25, onAgent: @escaping @Sendable () -> Void) {
+ lock.lock()
+ started = true
+ lock.unlock()
+ for (fd, guest) in listeners {
+ Self.serve(fd, name: "vsock forward \(guest)", stopped: { [weak self] in
+ self?.isStopped ?? true
+ }) { [weak self] c in
+ self?.serveForward(c, guest: guest)
+ }
+ }
+ let t = Thread { [weak self] in
+ while let self, !self.isStopped {
+ if self.ping() {
+ onAgent()
+ return
+ }
+ Thread.sleep(forTimeInterval: interval)
+ }
+ }
+ t.name = "vsock agent ping"
+ t.start()
+ }
+
+ /// Stops serving: each listener closes within half a second (its own
+ /// thread closes it, so no descriptor is closed under a blocked
+ /// `accept`); open connections end with the VM.
+ func stop() {
+ lock.lock()
+ stopped = true
+ lock.unlock()
+ }
+
+ private var isStopped: Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ return stopped
+ }
+
+ /// Whether the guest agent answers `{"op":"ping"}`.
+ func ping() -> Bool {
+ guard let s = connect(Self.agentPort) else { return false }
+ defer { s.close() }
+ guard Self.writeAll(s.fd, Data("{\"op\":\"ping\"}\n".utf8)),
+ let reply = Self.readLine(s.fd, limit: 4096)
+ else { return false }
+ return Self.isOK(reply)
+ }
+
+ /// One connection to a forwarded port: the agent connects to the
+ /// guest's own port, then bytes flow both ways.
+ func serveForward(_ c: Int32, guest: UInt16) {
+ var one: Int32 = 1
+ setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &one, 4)
+ guard let s = connect(Self.agentPort) else {
+ Darwin.close(c)
+ return
+ }
+ guard Self.writeAll(s.fd, Self.forwardRequest(guest)),
+ let reply = Self.readLine(s.fd, limit: 4096), Self.isOK(reply)
+ else {
+ s.close()
+ Darwin.close(c)
+ return
+ }
+ Self.splice(c, s.fd) {
+ s.close()
+ Darwin.close(c)
+ }
+ }
+
+ // MARK: - Protocol
+
+ static func forwardRequest(_ port: UInt16) -> Data {
+ Data("{\"op\":\"forward\",\"port\":\(port)}\n".utf8)
+ }
+
+ static func isOK(_ reply: String) -> Bool {
+ guard let data = reply.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ else { return false }
+ return object["ok"] as? Bool == true
+ }
+
+ // MARK: - Sockets (blocking; a thread per connection, as in cua-vz)
+
+ /// A listening TCP socket on `127.0.0.1:0` and the port it got.
+ static func listenLoopback() throws -> (Int32, UInt16) {
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
+ guard fd >= 0 else { throw VsockForwarderError.socket(errno) }
+ var a = sockaddr_in()
+ a.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ a.sin_family = sa_family_t(AF_INET)
+ a.sin_port = 0
+ a.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let bound = withUnsafePointer(to: &a) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
+ }
+ }
+ guard bound == 0, listen(fd, 128) == 0 else {
+ let e = errno
+ Darwin.close(fd)
+ throw VsockForwarderError.socket(e)
+ }
+ var got = sockaddr_in()
+ var len = socklen_t(MemoryLayout<sockaddr_in>.size)
+ let named = withUnsafeMutablePointer(to: &got) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ getsockname(fd, $0, &len)
+ }
+ }
+ guard named == 0 else {
+ let e = errno
+ Darwin.close(fd)
+ throw VsockForwarderError.socket(e)
+ }
+ return (fd, UInt16(bigEndian: got.sin_port))
+ }
+
+ /// Accepts connections on `fd` until `stopped`, each on a thread of its
+ /// own, then closes `fd`.
+ static func serve(
+ _ fd: Int32, name: String, stopped: @escaping @Sendable () -> Bool,
+ _ handle: @escaping @Sendable (Int32) -> Void
+ ) {
+ let t = Thread {
+ defer { Darwin.close(fd) }
+ while !stopped() {
+ var p = pollfd(fd: fd, events: Int16(POLLIN), revents: 0)
+ let ready = poll(&p, 1, 500)
+ if ready < 0 && errno != EINTR { return }
+ if ready <= 0 || stopped() { continue }
+ let c = accept(fd, nil, nil)
+ if c < 0 {
+ if errno == EINTR || errno == ECONNABORTED || errno == EAGAIN { continue }
+ return
+ }
+ var one: Int32 = 1
+ setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, &one, 4)
+ let worker = Thread { handle(c) }
+ worker.name = "\(name) connection"
+ worker.start()
+ }
+ }
+ t.name = name
+ t.start()
+ }
+
+ /// One `\n`-terminated line (without it), byte by byte so nothing past
+ /// it is consumed; `nil` on EOF, error or past `limit`.
+ static func readLine(_ fd: Int32, limit: Int) -> String? {
+ var bytes: [UInt8] = []
+ var b: UInt8 = 0
+ while bytes.count < limit {
+ let n = read(fd, &b, 1)
+ if n < 0 && errno == EINTR { continue }
+ if n <= 0 { return nil }
+ if b == 0x0A { return String(decoding: bytes, as: UTF8.self) }
+ bytes.append(b)
+ }
+ return nil
+ }
+
+ @discardableResult
+ static func writeAll(_ fd: Int32, _ data: Data) -> Bool {
+ data.withUnsafeBytes { (buf: UnsafeRawBufferPointer) -> Bool in
+ guard var p = buf.baseAddress else { return true }
+ var left = buf.count
+ while left > 0 {
+ let n = write(fd, p, left)
+ if n < 0 && errno == EINTR { continue }
+ if n <= 0 { return false }
+ p += n
+ left -= n
+ }
+ return true
+ }
+ }
+
+ /// Copies `a` to `b` and `b` to `a` until both directions end, passing
+ /// each end-of-stream on as a half-close; then `done`.
+ static func splice(_ a: Int32, _ b: Int32, done: @escaping @Sendable () -> Void) {
+ let group = DispatchGroup()
+ for (from, to) in [(a, b), (b, a)] {
+ group.enter()
+ let t = Thread {
+ var buf = [UInt8](repeating: 0, count: 64 * 1024)
+ while true {
+ let n = read(from, &buf, buf.count)
+ if n < 0 && errno == EINTR { continue }
+ if n <= 0 { break }
+ let ok = buf.withUnsafeBytes {
+ writeAll(to, Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress!), count: n, deallocator: .none))
+ }
+ if !ok { break }
+ }
+ shutdown(to, SHUT_WR)
+ shutdown(from, SHUT_RD)
+ group.leave()
+ }
+ t.name = "vsock splice"
+ t.start()
+ }
+ group.notify(queue: .global()) { done() }
+ }
+}
+
+enum VsockForwarderError: Error, CustomStringConvertible {
+ case socket(Int32)
+
+ var description: String {
+ switch self {
+ case .socket(let e): return "loopback listener: \(String(cString: strerror(e)))"
+ }
+ }
+}
diff --git a/libs/lume/src/Virtualization/VMVirtualizationService.swift b/libs/lume/src/Virtualization/VMVirtualizationService.swift
index 247980d863..ceeab50324 100644
--- a/libs/lume/src/Virtualization/VMVirtualizationService.swift
+++ b/libs/lume/src/Virtualization/VMVirtualizationService.swift
@@ -17,6 +17,8 @@ struct VMVirtualizationServiceContext {
let usbMassStoragePaths: [Path]?
let additionalDiskPaths: [Path]?
let networkMode: NetworkMode
+ /// Adds a virtio socket device (for host port forwards over vsock).
+ var socketDevice: Bool = false
}
/// Protocol defining the interface for virtualization operations
@@ -37,6 +39,13 @@ protocol VMVirtualizationService {
/// Loads a state written by `saveMachineState(to:)` into this stopped VM,
/// which is left paused. The configuration must match the saved one.
func restoreMachineState(from url: URL) async throws
+ /// Opens vsock streams to the guest, when the VM has a virtio socket
+ /// device.
+ func vsockConnector() -> VsockForwarder.Connect?
+}
+
+extension VMVirtualizationService {
+ func vsockConnector() -> VsockForwarder.Connect? { nil }
}
/// Base implementation of VMVirtualizationService using VZVirtualMachine
@@ -194,6 +203,35 @@ class BaseVirtualizationService: VMVirtualizationService {
try await lifecycleMonitor.waitForStop()
}
+ func vsockConnector() -> VsockForwarder.Connect? {
+ let handle = virtualMachineHandle
+ let hasDevice = handle.queue.sync { !handle.machine.socketDevices.isEmpty }
+ guard hasDevice else { return nil }
+ return { port in
+ let result = VsockConnectResult()
+ handle.queue.async {
+ guard let device = handle.machine.socketDevices.first as? VZVirtioSocketDevice
+ else {
+ result.finish(nil)
+ return
+ }
+ device.connect(toPort: port) { outcome in
+ switch outcome {
+ case .success(let connection):
+ let box = VsockConnectionBox(connection)
+ result.finish(
+ VsockForwarder.Stream(
+ fd: connection.fileDescriptor,
+ close: { box.connection.close() }))
+ case .failure:
+ result.finish(nil)
+ }
+ }
+ }
+ return result.wait(seconds: 5)
+ }
+ }
+
func saveMachineState(to url: URL) async throws {
let handle = virtualMachineHandle
try await withCheckedThrowingContinuation {
@@ -446,6 +484,9 @@ final class DarwinVirtualizationService: BaseVirtualizationService {
]
vzConfig.memoryBalloonDevices = [VZVirtioTraditionalMemoryBalloonDeviceConfiguration()]
vzConfig.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]
+ if config.socketDevice {
+ vzConfig.socketDevices = [VZVirtioSocketDeviceConfiguration()]
+ }
// Audio configuration
let soundDeviceConfiguration = VZVirtioSoundDeviceConfiguration()
@@ -668,6 +709,9 @@ final class LinuxVirtualizationService: BaseVirtualizationService {
]
vzConfig.memoryBalloonDevices = [VZVirtioTraditionalMemoryBalloonDeviceConfiguration()]
vzConfig.entropyDevices = [VZVirtioEntropyDeviceConfiguration()]
+ if config.socketDevice {
+ vzConfig.socketDevices = [VZVirtioSocketDeviceConfiguration()]
+ }
// Audio configuration
let soundDeviceConfiguration = VZVirtioSoundDeviceConfiguration()
@@ -745,3 +789,44 @@ final class LinuxVirtualizationService: BaseVirtualizationService {
)
}
}
+
+/// One vsock connect's answer, handed from the VM's queue to the waiting
+/// thread.
+final class VsockConnectResult: @unchecked Sendable {
+ private let done = DispatchSemaphore(value: 0)
+ private let lock = NSLock()
+ private var stream: VsockForwarder.Stream?
+ private var finished = false
+ private var abandoned = false
+
+ func finish(_ stream: VsockForwarder.Stream?) {
+ lock.lock()
+ let late = abandoned
+ if !late {
+ self.stream = stream
+ finished = true
+ }
+ lock.unlock()
+ // An answer after the waiter gave up: nobody will use the stream.
+ if late { stream?.close() }
+ done.signal()
+ }
+
+ func wait(seconds: Double) -> VsockForwarder.Stream? {
+ let timedOut = done.wait(timeout: .now() + seconds) == .timedOut
+ lock.lock()
+ defer { lock.unlock() }
+ if timedOut && !finished {
+ abandoned = true
+ return nil
+ }
+ return stream
+ }
+}
+
+/// Keeps a vsock connection open until its stream is closed (closing it is
+/// thread-safe).
+final class VsockConnectionBox: @unchecked Sendable {
+ let connection: VZVirtioSocketConnection
+ init(_ connection: VZVirtioSocketConnection) { self.connection = connection }
+}
diff --git a/libs/lume/tests/Mocks/MockVM.swift b/libs/lume/tests/Mocks/MockVM.swift
index 207e0f8091..31770876f3 100644
--- a/libs/lume/tests/Mocks/MockVM.swift
+++ b/libs/lume/tests/Mocks/MockVM.swift
@@ -26,7 +26,7 @@ class MockVM: VM {
vncPort: Int = 0, vncPassword: String? = nil, recoveryMode: Bool = false,
usbMassStoragePaths: [Path]? = nil, additionalDiskPaths: [Path]? = nil,
networkMode: NetworkMode? = nil, clipboard: Bool = false,
- vncPolicy: VNCPolicy = .enabled
+ vncPolicy: VNCPolicy = .enabled, forwards: [UInt16] = []
) async throws {
mockIsRunning = true
try await super.run(
@@ -35,7 +35,7 @@ class MockVM: VM {
usbMassStoragePaths: usbMassStoragePaths,
additionalDiskPaths: additionalDiskPaths,
networkMode: networkMode, clipboard: clipboard,
- vncPolicy: vncPolicy
+ vncPolicy: vncPolicy, forwards: forwards
)
}
diff --git a/libs/lume/tests/VsockForwarderTests.swift b/libs/lume/tests/VsockForwarderTests.swift
new file mode 100644
index 0000000000..330b39f6b6
--- /dev/null
+++ b/libs/lume/tests/VsockForwarderTests.swift
@@ -0,0 +1,152 @@
+import Darwin
+import Foundation
+import Testing
+
+@testable import lume
+
+/// A stand-in for the guest agent: each "vsock" connect is one end of a
+/// Unix socket pair whose other end runs `agent` on a thread.
+private func fakeConnect(
+ agent: @escaping @Sendable (Int32) -> Void
+) -> VsockForwarder.Connect {
+ return { _ in
+ var fds: [Int32] = [0, 0]
+ guard socketpair(AF_UNIX, SOCK_STREAM, 0, &fds) == 0 else { return nil }
+ let (host, guest) = (fds[0], fds[1])
+ let t = Thread {
+ agent(guest)
+ Darwin.close(guest)
+ }
+ t.start()
+ return VsockForwarder.Stream(fd: host, close: { Darwin.close(host) })
+ }
+}
+
+/// An agent that answers a ping, and a forward with an echo of what follows.
+private let echoAgent: @Sendable (Int32) -> Void = { fd in
+ guard let line = VsockForwarder.readLine(fd, limit: 4096) else { return }
+ if line.contains("\"ping\"") {
+ VsockForwarder.writeAll(fd, Data("{\"ok\":true}\n".utf8))
+ return
+ }
+ guard line == "{\"op\":\"forward\",\"port\":3211}" else {
+ VsockForwarder.writeAll(fd, Data("{\"ok\":false,\"error\":\"bad\"}\n".utf8))
+ return
+ }
+ VsockForwarder.writeAll(fd, Data("{\"ok\":true}\n".utf8))
+ var buf = [UInt8](repeating: 0, count: 1024)
+ while true {
+ let n = read(fd, &buf, buf.count)
+ if n <= 0 { break }
+ VsockForwarder.writeAll(fd, Data(buf[0..<n]))
+ }
+ shutdown(fd, SHUT_WR)
+}
+
+private func dialLoopback(_ port: UInt16) -> Int32 {
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
+ var a = sockaddr_in()
+ a.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ a.sin_family = sa_family_t(AF_INET)
+ a.sin_port = port.bigEndian
+ a.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let rc = withUnsafePointer(to: &a) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ connect(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
+ }
+ }
+ #expect(rc == 0)
+ return fd
+}
+
+private func readAll(_ fd: Int32) -> String {
+ var out: [UInt8] = []
+ var buf = [UInt8](repeating: 0, count: 1024)
+ while true {
+ let n = read(fd, &buf, buf.count)
+ if n <= 0 { break }
+ out.append(contentsOf: buf[0..<n])
+ }
+ return String(decoding: out, as: UTF8.self)
+}
+
+@Suite("Host port forwards over vsock")
+struct VsockForwarderTests {
+ @Test("A loopback connection reaches the guest port through the agent")
+ func forwardsThroughTheAgent() throws {
+ let forwarder = try VsockForwarder(guestPorts: [3211], connect: fakeConnect(agent: echoAgent))
+ defer { forwarder.stop() }
+ let host = try #require(forwarder.forwards[3211])
+ #expect(host != 0 && host != 3211)
+ forwarder.start(onAgent: {})
+ let c = dialLoopback(host)
+ defer { Darwin.close(c) }
+ #expect(VsockForwarder.writeAll(c, Data("hello".utf8)))
+ shutdown(c, SHUT_WR)
+ #expect(readAll(c) == "hello")
+ }
+
+ @Test("Without the agent a connection closes at once")
+ func noAgentClosesTheConnection() throws {
+ let forwarder = try VsockForwarder(guestPorts: [3211], connect: { _ in nil })
+ defer { forwarder.stop() }
+ forwarder.start(onAgent: { Issue.record("no agent answered") })
+ let c = dialLoopback(try #require(forwarder.forwards[3211]))
+ defer { Darwin.close(c) }
+ #expect(readAll(c) == "")
+ #expect(!forwarder.ping())
+ }
+
+ @Test("The agent's first answer to a ping is reported once")
+ func agentReadiness() throws {
+ let forwarder = try VsockForwarder(guestPorts: [3211, 22], connect: fakeConnect(agent: echoAgent))
+ defer { forwarder.stop() }
+ let seen = DispatchSemaphore(value: 0)
+ forwarder.start(interval: 0.01) { seen.signal() }
+ #expect(seen.wait(timeout: .now() + 5) == .success)
+ let session = forwarder.session(agent: true)
+ #expect(session.agent)
+ #expect(Swift.Set(session.forwards.keys) == ["3211", "22"])
+ #expect(session.pid == getpid())
+ }
+
+ @Test("Replies and requests use the microVM init's protocol")
+ func protocolLines() {
+ #expect(VsockForwarder.isOK("{\"ok\":true}"))
+ #expect(!VsockForwarder.isOK("{\"ok\":false,\"error\":\"refused\"}"))
+ #expect(!VsockForwarder.isOK("garbage"))
+ #expect(
+ String(decoding: VsockForwarder.forwardRequest(3211), as: UTF8.self)
+ == "{\"op\":\"forward\",\"port\":3211}\n")
+ }
+
+ @Test("A resume keeps the devices its state was saved with")
+ func socketDeviceFollowsTheSavedState() {
+ #expect(VM.usesSocketDevice(forwards: [3211], hasSavedState: false, savedStateHasVsock: false))
+ #expect(VM.usesSocketDevice(forwards: [3211], hasSavedState: true, savedStateHasVsock: true))
+ #expect(!VM.usesSocketDevice(forwards: [3211], hasSavedState: true, savedStateHasVsock: false))
+ #expect(!VM.usesSocketDevice(forwards: [], hasSavedState: false, savedStateHasVsock: false))
+ }
+
+ @Test("The session and the state marker live in the VM directory")
+ func directoryRecords() throws {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let dir = VMDirectory(Path(root.path))
+ #expect(dir.loadVsockSession() == nil)
+ let session = VsockSession(forwards: ["3211": 50123], agent: true, pid: 42)
+ dir.saveVsockSession(session)
+ #expect(dir.loadVsockSession() == session)
+ dir.clearVsockSession()
+ #expect(dir.loadVsockSession() == nil)
+
+ dir.markSavedStateVsock(true)
+ #expect(!dir.savedStateHasVsock(), "no state, no marker that counts")
+ FileManager.default.createFile(atPath: dir.statePath.path, contents: Data())
+ #expect(dir.savedStateHasVsock())
+ dir.discardSavedState()
+ #expect(!dir.savedStateHasVsock())
+ #expect(!dir.stateVsockPath.exists())
+ }
+}