From a0e4710ed2bf09c91ce363f5072a245ea814f91a Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:11:08 +0000 Subject: [PATCH 01/26] ci: boot Firecracker microVMs on GitHub's x86_64 runners The firecracker driver's test that boots a VM only ran by hand, on aarch64 under QEMU. GitHub's x86_64 runners have KVM: a CI job builds a static fctl-agent and runs the driver's ignored tests there, with Ubuntu's passt and its AppArmor profile, and the kernel hosts pull, which the test now takes unless FCTL_TEST_FIRECRACKER_KERNEL names one. Refs #345 --- .github/workflows/ci.yml | 31 +++++++++++++++++-- .../fctl-host/src/driver/firecracker/mod.rs | 15 ++++----- ...s-run-sandboxes-in-firecracker-microvms.md | 9 ++++-- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c997886..918236bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,6 @@ -# Checks every pull request and push, and runs a session through the local -# stack; on main (also when started by hand), deploys app.fctl.sh and pins +# Checks every pull request and push, runs a session through the local +# stack, and boots the firecracker driver's microVMs on a runner with KVM; +# on main (also when started by hand), deploys app.fctl.sh and pins # fctl.sh (hyperstructure/fctl-site) to main's docs when they differ from the # ones it shows. Pull request titles are checked in commits.yml; the # standalone control plane's image in standalone-image.yml, on pull requests @@ -112,6 +113,32 @@ jobs: # No npm ci: like a fresh clone, cargo xtask dev installs what it needs. - run: xtask dev --smoke + # The firecracker driver's tests that boot microVMs (`--ignored` ones in + # crates/fctl-host/src/driver/firecracker), which need KVM: GitHub's x86_64 + # runners have it, for root only. They pull an image from Docker Hub, the + # kernel hosts pull and Firecracker's release, and run passt under the + # AppArmor profile Ubuntu gives it. + firecracker: + name: Firecracker sandboxes + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ./.github/actions/rust + - name: KVM for the runner's user, passt and a static fctl-agent + run: | + sudo chmod 666 /dev/kvm + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends passt e2fsprogs + # What confines passt, which runs as the host's user. + sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" + rustup target add x86_64-unknown-linux-musl + cargo build --release --locked -p fctl-agent --target x86_64-unknown-linux-musl + - name: Boot sandboxes + env: + FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + run: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that # leaves its crates, the manifests, the toolchain and this workflow as they diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 071f39a9..b97d7365 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1160,20 +1160,21 @@ mod tests { /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's - /// needs and a static fctl-agent: + /// needs and a static fctl-agent, with the kernel hosts pull (or the + /// file `FCTL_TEST_FIRECRACKER_KERNEL`). CI runs it on GitHub's x86_64 + /// runners, which have KVM (the `firecracker` job of ci.yml): /// /// ```sh /// cargo build --release -p fctl-agent --target "$(uname -m)-unknown-linux-musl" /// FCTL_TEST_FIRECRACKER_AGENT=$PWD/target/$(uname -m)-unknown-linux-musl/release/fctl-agent \ - /// FCTL_TEST_FIRECRACKER_KERNEL=/path/to/vmlinux \ /// cargo test -p fctl-host boots_a_sandbox -- --ignored --nocapture /// ``` /// - /// `FCTL_TEST_FIRECRACKER_DATA` keeps the host's files (the image, and - /// Firecracker) between runs, and `FCTL_TEST_FIRECRACKER_RUN` is a - /// command whose output it shows (`claude --version`, say). + /// `FCTL_TEST_FIRECRACKER_DATA` keeps the host's files (the image, the + /// kernel and Firecracker) between runs, and `FCTL_TEST_FIRECRACKER_RUN` + /// is a command whose output it shows (`claude --version`, say). #[tokio::test] - #[ignore = "needs KVM, passt, a kernel and a static fctl-agent"] + #[ignore = "needs KVM, passt and a static fctl-agent"] async fn boots_a_sandbox() -> Result<()> { use super::super::Driver; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -1187,7 +1188,7 @@ mod tests { agent_bin: Some(var("FCTL_TEST_FIRECRACKER_AGENT")?.into()), ..HostConfig::default() }; - cfg.firecracker.kernel = Some(var("FCTL_TEST_FIRECRACKER_KERNEL")?); + cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; diff --git a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md index ecc6565c..b2a3cede 100644 --- a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md +++ b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md @@ -87,6 +87,9 @@ microVM of its own. reports free. - The VM's clock follows the host's at boot and at each request of the host, not between them, after the host sleeps. -- CI has no KVM: the driver's test that boots a VM runs only by hand, with - `--ignored`. Session #536 ran it, and sessions end to end, on Firecracker - in a VM under QEMU's emulation of a CPU with virtualization. +- The driver's tests that boot VMs need KVM, so they are `--ignored` in + `cargo test`. Session #536 ran them, and sessions end to end, on + Firecracker in a VM under QEMU's emulation of a CPU with virtualization + (aarch64); CI runs them on GitHub's x86_64 runners, which have KVM, with + Ubuntu's passt and its AppArmor profile (the `firecracker` job of + `ci.yml`). From 976785e3720fff0d69defbea289d23412fa4bdbd Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:14:37 +0000 Subject: [PATCH 02/26] ci: quote the firecracker job's test filter, which YAML read as a mapping --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 918236bc..e181f00e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,7 +137,8 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent - run: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + run: | + cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that From 616cd0fb331f43c7a92f40d4f3d7555fb897e59f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:18:19 +0000 Subject: [PATCH 03/26] fix(host): start passt without --hostname, which Ubuntu 24.04's passt lacks Ubuntu 24.04's passt (0.0~git20240220) refuses --hostname, which came later, so no Firecracker VM got a network there. The VM names itself, so passt's DHCP needs no hostname. --- crates/fctl-host/src/driver/firecracker/vm.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 80271f48..4d476368 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -173,7 +173,7 @@ impl Vm { std::fs::create_dir_all(&self.run)?; if spec.network { let passt = passt.context("the VM needs passt for its network")?; - self.start_passt(passt, &spec.boot.name).await?; + self.start_passt(passt).await?; } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; @@ -196,10 +196,10 @@ impl Vm { /// connections of the host's: the VM gets [`ADDRESS`], the gateway and /// a DNS forwarder, and reaches neither the host's loopback nor other /// VMs. Nothing reaches the VM from outside. - async fn start_passt(&self, passt: &Path, name: &str) -> Result<()> { + async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net(), name)) + cmd.args(passt_args(&self.net())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,9 +430,11 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM named `name` whose frames come to -/// `socket`. -fn passt_args(socket: &Path, name: &str) -> Vec { +/// The arguments of `passt` for a VM whose frames come to `socket`: the +/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 +/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which +/// came later. +fn passt_args(socket: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ "--foreground".into(), @@ -449,8 +451,6 @@ fn passt_args(socket: &Path, name: &str) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - "--hostname".into(), - name.into(), ] } @@ -563,10 +563,10 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), "fctl-ses-1").join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); assert_eq!( args, - "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw --hostname fctl-ses-1" + "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } From fbf92f5ba2f774bf7b0d8851c3d8869a8a0ad0ad Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:22:54 +0000 Subject: [PATCH 04/26] test(host): say what passt and the VM's network say when a sandbox has no DNS --- .github/workflows/ci.yml | 3 ++ .../fctl-host/src/driver/firecracker/mod.rs | 30 +++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e181f00e..550168e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,6 +139,9 @@ jobs: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + - name: What AppArmor and the kernel said + if: failure() + run: sudo dmesg | grep -iE 'apparmor|passt|firecracker|kvm' | tail -50 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index b97d7365..e80b097c 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -966,7 +966,11 @@ impl FirecrackerDriver { after: super::COMMAND_TIMEOUT, })??; if out.code != 0 { - bail!("{}", String::from_utf8_lossy(&out.stderr).trim()); + let said = String::from_utf8_lossy(&out.stderr); + match said.trim() { + "" => bail!("the command exited with {} in {}", out.code, sb.name), + said => bail!("{said}"), + } } Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } @@ -1222,8 +1226,28 @@ mod tests { if let Ok(command) = std::env::var("FCTL_TEST_FIRECRACKER_RUN") { eprintln!("{command}: {}", d.exec(&sb, &command).await?.trim()); } - let resolved = d.exec(&sb, "getent hosts example.com").await?; - assert!(!resolved.trim().is_empty()); + // The network, through passt: what it and the VM say when it + // doesn't work. + let resolved = d.exec(&sb, "getent hosts example.com").await; + if resolved.as_ref().is_ok_and(|r| !r.trim().is_empty()) { + eprintln!("example.com is {}", resolved.unwrap_or_default().trim()); + } else { + let passt = std::fs::read_to_string( + cfg.data_dir() + .join("firecracker/sandboxes") + .join(&name) + .join("passt.log"), + ); + let net = d + .exec( + &sb, + "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; ls -l /etc/resolv.conf", + ) + .await; + bail!( + "no address for example.com in the sandbox ({resolved:?}); passt said {passt:?}; the VM's network: {net:?}" + ); + } let fetched = d .exec( &sb, From 8f88b35e07fc2236c2ba7792e4c377e69bef31a9 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:28:29 +0000 Subject: [PATCH 05/26] fix(host): give Firecracker VMs DNS past systemd-resolved's stub, as Docker does Ubuntu's /etc/resolv.conf names only systemd-resolved's 127.0.0.53, and the passt Ubuntu 24.04 has forwards no DNS to a resolver on the host's loopback with --no-map-gw, so VMs resolved nothing there. Where the host's resolv.conf names only loopback resolvers, the host passes passt the servers systemd-resolved asks, as Docker does for its containers. --- crates/fctl-host/src/driver/firecracker/vm.rs | 89 +++++++++++++++++-- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 4d476368..862b60b5 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, anyhow, bail}; use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::net::Ipv4Addr; +use std::net::{IpAddr, Ipv4Addr}; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::{Duration, Instant}; @@ -199,7 +199,7 @@ impl Vm { async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net())) + cmd.args(passt_args(&self.net(), &host_dns())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,13 +430,14 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`: the +/// The arguments of `passt` for a VM whose frames come to `socket`, whose +/// DNS queries go to `dns` (when empty, to the host's resolver): the /// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 /// have. The VM names itself, so passt's DHCP needs no `--hostname`, which /// came later. -fn passt_args(socket: &Path) -> Vec { +fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { let mask = PREFIX.to_string(); - vec![ + let mut args: Vec = vec![ "--foreground".into(), "--quiet".into(), "--socket".into(), @@ -451,7 +452,51 @@ fn passt_args(socket: &Path) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - ] + ]; + for addr in dns { + args.extend(["--dns".into(), addr.to_string()]); + } + args +} + +/// Where the VMs' DNS queries go, when passt can't find it alone: as Docker +/// does, the servers systemd-resolved asks, where the host's +/// `/etc/resolv.conf` names only a resolver on its loopback (systemd-resolved's +/// 127.0.0.53). passt before 2024's summer forwards no queries to a resolver +/// on the loopback with `--no-map-gw` (Ubuntu 24.04's says "Couldn't get any +/// nameserver address"). Empty when the host names another resolver, or +/// nothing else is known: passt finds it then, or newer passt forwards to the +/// loopback's. +fn host_dns() -> Vec { + let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); + dns_for_vms( + &read("/etc/resolv.conf"), + &read("/run/systemd/resolve/resolv.conf"), + ) +} + +/// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 +/// ones only without any, at most three. +fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { + let servers = |text: &str| -> Vec { + text.lines() + .filter_map(|l| l.trim().strip_prefix("nameserver")) + .filter_map(|rest| rest.split_whitespace().next()) + // A link-local IPv6 server carries its interface: `fe80::1%eth0`. + .filter_map(|a| a.split('%').next().and_then(|a| a.parse().ok())) + .collect() + }; + let host = servers(resolv_conf); + if host.is_empty() || host.iter().any(|a| !a.is_loopback()) { + return Vec::new(); + } + let upstream: Vec = servers(resolved_upstream) + .into_iter() + .filter(|a| !a.is_loopback()) + .collect(); + let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); + let pick = if v4.is_empty() { upstream } else { v4 }; + pick.into_iter().take(3).collect() } /// Starts `cmd` in a process group of its own, writes its id to @@ -563,11 +608,41 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), &[]).join(" "); assert_eq!( args, "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); + let dns = [IpAddr::from([168, 63, 129, 16])]; + let args = passt_args(Path::new("/s"), &dns).join(" "); + assert!(args.ends_with("--no-map-gw --dns 168.63.129.16"), "{args}"); + } + + /// systemd-resolved's stub on the loopback, as Ubuntu has it, and its + /// upstream servers, which passt gets; any other resolver passt finds + /// itself. + #[test] + fn dns_goes_past_a_resolver_on_the_hosts_loopback() { + let stub = "# This is /run/systemd/resolve/stub-resolv.conf\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch .\n"; + let upstream = "nameserver 168.63.129.16\nnameserver fe80::1%eth0\nnameserver 10.0.0.2\nnameserver 1.1.1.1\nnameserver 8.8.8.8\nsearch example.internal\n"; + let v4 = |a: [u8; 4]| IpAddr::from(a); + assert_eq!( + dns_for_vms(stub, upstream), + [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] + ); + // IPv6 servers only where there is no IPv4 one. + let only_v6 = "nameserver 2001:4860:4860::8888\nnameserver ::1\n"; + assert_eq!( + dns_for_vms(stub, only_v6), + [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] + ); + // A resolver passt can reach, or nothing to go past to. + assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); + assert!( + dns_for_vms("nameserver 127.0.0.53\nnameserver 192.168.1.1\n", upstream).is_empty() + ); + assert!(dns_for_vms(stub, "").is_empty()); + assert!(dns_for_vms("", upstream).is_empty()); } #[test] From e88ee76a5077ed825f78188866e997fae6e535ef Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:32:53 +0000 Subject: [PATCH 06/26] fix(host): leave link-local DNS servers out of passt's, which it can't reach systemd-resolved lists a link-local IPv6 server with its interface (fe80::1%eth0), which --dns can't carry: without it, passt finds a server itself rather than get one it can't reach. --- crates/fctl-host/src/driver/firecracker/vm.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 862b60b5..383851a3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -476,7 +476,8 @@ fn host_dns() -> Vec { } /// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 -/// ones only without any, at most three. +/// ones only without any, at most three. Link-local IPv6 servers are left +/// out: `--dns` can't say which interface reaches them (`fe80::1%eth0`). fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { let servers = |text: &str| -> Vec { text.lines() @@ -492,7 +493,10 @@ fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { } let upstream: Vec = servers(resolved_upstream) .into_iter() - .filter(|a| !a.is_loopback()) + .filter(|a| match a { + IpAddr::V4(a) => !a.is_loopback(), + IpAddr::V6(a) => !a.is_loopback() && !a.is_unicast_link_local(), + }) .collect(); let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); let pick = if v4.is_empty() { upstream } else { v4 }; @@ -630,12 +634,14 @@ mod tests { dns_for_vms(stub, upstream), [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] ); - // IPv6 servers only where there is no IPv4 one. - let only_v6 = "nameserver 2001:4860:4860::8888\nnameserver ::1\n"; + // IPv6 servers only where there is no IPv4 one, and no link-local + // one, which passt can't reach without its interface. + let only_v6 = "nameserver fe80::1%eth0\nnameserver 2001:4860:4860::8888\nnameserver ::1\n"; assert_eq!( dns_for_vms(stub, only_v6), [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] ); + assert!(dns_for_vms(stub, "nameserver fe80::1%eth0\nnameserver fe80::2\n").is_empty()); // A resolver passt can reach, or nothing to go past to. assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); assert!( From 681768baeed2d5a99785a3438e0eb759538c64fb Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:38:49 +0000 Subject: [PATCH 07/26] fix(host): give Firecracker VMs the host's nameservers, past systemd-resolved's stub The --dns passt took doesn't set where its forwarder sends queries in Ubuntu 24.04's passt, so VMs still resolved nothing there. As Docker gives its containers, the VM now asks the host's nameservers itself (fctl.dns= on its kernel's command line), but for those on the host's loopback, and where only those are left, the servers systemd-resolved asks. With none, it asks passt's forwarder, as before. --- crates/fctl-agent/src/vm/boot.rs | 16 ++- .../fctl-host/src/driver/firecracker/mod.rs | 3 +- crates/fctl-host/src/driver/firecracker/vm.rs | 119 ++++++++---------- crates/fctl-proto/src/vm.rs | 20 ++- 4 files changed, 82 insertions(+), 76 deletions(-) diff --git a/crates/fctl-agent/src/vm/boot.rs b/crates/fctl-agent/src/vm/boot.rs index dfa69358..316bc71c 100644 --- a/crates/fctl-agent/src/vm/boot.rs +++ b/crates/fctl-agent/src/vm/boot.rs @@ -264,11 +264,17 @@ fn system(boot: &Boot) { "127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n127.0.1.1\t{}\n", boot.name ); - let dns = std::net::Ipv4Addr::from(fctl_proto::vm::DNS); - for (file, text) in [ - ("/etc/hosts", hosts), - ("/etc/resolv.conf", format!("nameserver {dns}\n")), - ] { + // The host's nameservers, which passt reaches as the host does, or the + // address where passt forwards queries to the host's resolver. + let servers = match boot.dns.as_slice() { + [] => vec![std::net::Ipv4Addr::from(fctl_proto::vm::DNS)], + some => some.to_vec(), + }; + let resolv: String = servers + .iter() + .map(|s| format!("nameserver {s}\n")) + .collect(); + for (file, text) in [("/etc/hosts", hosts), ("/etc/resolv.conf", resolv)] { if let Err(e) = replace(file, &text) { say(&format!("writing {file}: {e}")); } diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index e80b097c..08172802 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -752,6 +752,7 @@ impl FirecrackerDriver { mode: Mode::Sandbox, name: spec.name.clone(), time_ms: Some(vsock::now_ms()), + dns: vm::vm_dns(), }, drives: vec![ Drive { @@ -1241,7 +1242,7 @@ mod tests { let net = d .exec( &sb, - "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; ls -l /etc/resolv.conf", + "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", ) .await; bail!( diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 383851a3..196c96f0 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, anyhow, bail}; use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::net::{IpAddr, Ipv4Addr}; +use std::net::Ipv4Addr; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::{Duration, Instant}; @@ -199,7 +199,7 @@ impl Vm { async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net(), &host_dns())) + cmd.args(passt_args(&self.net())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,14 +430,13 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`, whose -/// DNS queries go to `dns` (when empty, to the host's resolver): the +/// The arguments of `passt` for a VM whose frames come to `socket`: the /// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 /// have. The VM names itself, so passt's DHCP needs no `--hostname`, which /// came later. -fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { +fn passt_args(socket: &Path) -> Vec { let mask = PREFIX.to_string(); - let mut args: Vec = vec![ + vec![ "--foreground".into(), "--quiet".into(), "--socket".into(), @@ -452,55 +451,46 @@ fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - ]; - for addr in dns { - args.extend(["--dns".into(), addr.to_string()]); - } - args + ] } -/// Where the VMs' DNS queries go, when passt can't find it alone: as Docker -/// does, the servers systemd-resolved asks, where the host's -/// `/etc/resolv.conf` names only a resolver on its loopback (systemd-resolved's -/// 127.0.0.53). passt before 2024's summer forwards no queries to a resolver -/// on the loopback with `--no-map-gw` (Ubuntu 24.04's says "Couldn't get any -/// nameserver address"). Empty when the host names another resolver, or -/// nothing else is known: passt finds it then, or newer passt forwards to the -/// loopback's. -fn host_dns() -> Vec { +/// The nameservers a VM asks, which passt reaches as the host does: as +/// Docker gives its containers, the host's own, but for those on its +/// loopback, which the VM can't reach, and where only those are left +/// (systemd-resolved's 127.0.0.53, as Ubuntu has it) the servers +/// systemd-resolved asks. Empty when there are none: the VM asks passt's +/// forwarder then, which passes its queries to the host's resolver, but in +/// passt's releases before the summer of 2024 (Ubuntu 24.04's) not to one on +/// the loopback. +pub fn vm_dns() -> Vec { let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); - dns_for_vms( + dns_for_vm( &read("/etc/resolv.conf"), &read("/run/systemd/resolve/resolv.conf"), ) } -/// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 -/// ones only without any, at most three. Link-local IPv6 servers are left -/// out: `--dns` can't say which interface reaches them (`fe80::1%eth0`). -fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { - let servers = |text: &str| -> Vec { +/// [`vm_dns`], from the files' text: at most three IPv4 servers (the VM +/// has no IPv6), and none of the addresses that mean something else in the +/// VM's network, where the gateway and passt's forwarder are. +fn dns_for_vm(resolv_conf: &str, resolved_upstream: &str) -> Vec { + let usable = |text: &str| -> Vec { text.lines() .filter_map(|l| l.trim().strip_prefix("nameserver")) .filter_map(|rest| rest.split_whitespace().next()) - // A link-local IPv6 server carries its interface: `fe80::1%eth0`. - .filter_map(|a| a.split('%').next().and_then(|a| a.parse().ok())) + .filter_map(|a| a.parse::().ok()) + .filter(|a| { + !a.is_loopback() + && !a.is_unspecified() + && ![ADDRESS, GATEWAY, DNS].contains(&a.octets()) + }) + .take(3) .collect() }; - let host = servers(resolv_conf); - if host.is_empty() || host.iter().any(|a| !a.is_loopback()) { - return Vec::new(); - } - let upstream: Vec = servers(resolved_upstream) - .into_iter() - .filter(|a| match a { - IpAddr::V4(a) => !a.is_loopback(), - IpAddr::V6(a) => !a.is_loopback() && !a.is_unicast_link_local(), - }) - .collect(); - let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); - let pick = if v4.is_empty() { upstream } else { v4 }; - pick.into_iter().take(3).collect() + match usable(resolv_conf) { + none if none.is_empty() => usable(resolved_upstream), + some => some, + } } /// Starts `cmd` in a process group of its own, writes its id to @@ -547,6 +537,7 @@ pub fn unpack_spec(kernel: PathBuf, initrd: PathBuf, name: &str, rootfs: &Path) mode: Mode::Unpack, name: name.into(), time_ms: Some(vsock::now_ms()), + dns: Vec::new(), }, drives: vec![Drive { path: rootfs.to_owned(), @@ -575,6 +566,7 @@ mod tests { mode: Mode::Sandbox, name: "fctl-ses-1".into(), time_ms: Some(5), + dns: vec![[168, 63, 129, 16].into()], }, drives: vec![ Drive { @@ -594,7 +586,7 @@ mod tests { assert_eq!( c["boot-source"]["boot_args"], format!( - "{} fctl.mode=sandbox fctl.name=fctl-ses-1 fctl.time=5", + "{} fctl.mode=sandbox fctl.name=fctl-ses-1 fctl.time=5 fctl.dns=168.63.129.16", kernel_args() ) ); @@ -612,43 +604,34 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), &[]).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); assert_eq!( args, "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); - let dns = [IpAddr::from([168, 63, 129, 16])]; - let args = passt_args(Path::new("/s"), &dns).join(" "); - assert!(args.ends_with("--no-map-gw --dns 168.63.129.16"), "{args}"); } - /// systemd-resolved's stub on the loopback, as Ubuntu has it, and its - /// upstream servers, which passt gets; any other resolver passt finds - /// itself. + /// The host's nameservers, past systemd-resolved's stub on its loopback + /// as Ubuntu has it, to the servers it asks. #[test] - fn dns_goes_past_a_resolver_on_the_hosts_loopback() { + fn vms_ask_the_hosts_nameservers_and_none_on_its_loopback() { let stub = "# This is /run/systemd/resolve/stub-resolv.conf\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch .\n"; let upstream = "nameserver 168.63.129.16\nnameserver fe80::1%eth0\nnameserver 10.0.0.2\nnameserver 1.1.1.1\nnameserver 8.8.8.8\nsearch example.internal\n"; - let v4 = |a: [u8; 4]| IpAddr::from(a); + let v4 = |a: [u8; 4]| Ipv4Addr::from(a); assert_eq!( - dns_for_vms(stub, upstream), + dns_for_vm(stub, upstream), [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] ); - // IPv6 servers only where there is no IPv4 one, and no link-local - // one, which passt can't reach without its interface. - let only_v6 = "nameserver fe80::1%eth0\nnameserver 2001:4860:4860::8888\nnameserver ::1\n"; - assert_eq!( - dns_for_vms(stub, only_v6), - [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] - ); - assert!(dns_for_vms(stub, "nameserver fe80::1%eth0\nnameserver fe80::2\n").is_empty()); - // A resolver passt can reach, or nothing to go past to. - assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); - assert!( - dns_for_vms("nameserver 127.0.0.53\nnameserver 192.168.1.1\n", upstream).is_empty() - ); - assert!(dns_for_vms(stub, "").is_empty()); - assert!(dns_for_vms("", upstream).is_empty()); + // The host's own, but for those on its loopback. + let router = "nameserver 127.0.0.1\nnameserver 192.168.1.1\n"; + assert_eq!(dns_for_vm(router, upstream), [v4([192, 168, 1, 1])]); + assert_eq!(dns_for_vm("", upstream)[0], v4([168, 63, 129, 16])); + // Nothing the VM could ask: passt's forwarder. QEMU's user network + // has its resolver where the VM's forwarder is, 10.0.2.3, and IPv6 + // doesn't reach the VM. + assert!(dns_for_vm(stub, "").is_empty()); + assert!(dns_for_vm(stub, "nameserver 2001:4860:4860::8888\n").is_empty()); + assert!(dns_for_vm("nameserver 10.0.2.3\n", "").is_empty()); } #[test] diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 504352ea..7a254cf4 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -50,13 +50,18 @@ pub enum Mode { } /// What the init reads from the kernel's command line: `fctl.mode=`, -/// `fctl.name=` (the VM's hostname) and `fctl.time=` (the host's clock at -/// boot, in milliseconds since the Unix epoch). +/// `fctl.name=` (the VM's hostname), `fctl.time=` (the host's clock at +/// boot, in milliseconds since the Unix epoch) and `fctl.dns=` (the +/// nameservers the VM asks, separated by commas). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Boot { pub mode: Mode, pub name: String, pub time_ms: Option, + /// The nameservers the VM asks: the host's own, which `passt` reaches as + /// the host does. Empty: [`DNS`], which `passt` forwards to the host's + /// resolver. + pub dns: Vec, } impl Boot { @@ -70,6 +75,10 @@ impl Boot { if let Some(t) = self.time_ms { p.push_str(&format!(" fctl.time={t}")); } + if !self.dns.is_empty() { + let dns: Vec = self.dns.iter().map(ToString::to_string).collect(); + p.push_str(&format!(" fctl.dns={}", dns.join(","))); + } p } @@ -78,12 +87,16 @@ impl Boot { let mut mode = None; let mut name = String::from("fctl"); let mut time_ms = None; + let mut dns = Vec::new(); for word in cmdline.split_whitespace() { match word.split_once('=') { Some(("fctl.mode", "sandbox")) => mode = Some(Mode::Sandbox), Some(("fctl.mode", "unpack")) => mode = Some(Mode::Unpack), Some(("fctl.name", n)) if !n.is_empty() => n.clone_into(&mut name), Some(("fctl.time", t)) => time_ms = t.parse().ok(), + Some(("fctl.dns", list)) => { + dns = list.split(',').filter_map(|a| a.parse().ok()).collect(); + } _ => {} } } @@ -91,6 +104,7 @@ impl Boot { mode: mode?, name, time_ms, + dns, }) } } @@ -223,11 +237,13 @@ mod tests { mode: Mode::Sandbox, name: "fctl-ses-01abc".into(), time_ms: Some(1_761_700_000_000), + dns: vec![[168, 63, 129, 16].into(), [10, 1, 0, 2].into()], }; let cmdline = format!( "console=ttyS0 reboot=k panic=1 {} rdinit=/init", boot.params() ); + assert!(cmdline.contains(" fctl.dns=168.63.129.16,10.1.0.2 ")); assert_eq!(Boot::parse(&cmdline), Some(boot)); let unpack = Boot::parse("fctl.mode=unpack quiet"); assert_eq!( From 5d45e3a0d952e73ab1ea3fa36e91f9f0144fe585 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:44:06 +0000 Subject: [PATCH 08/26] test(host): say what passt, the VM's console and AppArmor say when a sandbox has no network --- .github/workflows/ci.yml | 3 +- .../fctl-host/src/driver/firecracker/mod.rs | 41 ++++++++++++------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 550168e1..a85ca1ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -141,7 +141,8 @@ jobs: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - name: What AppArmor and the kernel said if: failure() - run: sudo dmesg | grep -iE 'apparmor|passt|firecracker|kvm' | tail -50 + # journald takes the kernel's audit records, AppArmor's among them. + run: sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | tail -60 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 08172802..8ba27b90 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1163,6 +1163,30 @@ mod tests { } } + /// What passt, the VM's console and the VM's network say, for a test + /// whose sandbox can't reach the network. + async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { + let dir = data.join("firecracker/sandboxes").join(&sb.name); + let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); + let passt_runs = read("passt.pid") + .trim() + .parse::() + .ok() + .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) + .map(|cmdline| cmdline.replace('\0', " ")); + let vm = d + .exec( + sb, + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", + ) + .await; + format!( + "passt runs: {passt_runs:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network: {vm:?}", + read("passt.log").trim(), + read("console.log").trim() + ) + } + /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1233,21 +1257,8 @@ mod tests { if resolved.as_ref().is_ok_and(|r| !r.trim().is_empty()) { eprintln!("example.com is {}", resolved.unwrap_or_default().trim()); } else { - let passt = std::fs::read_to_string( - cfg.data_dir() - .join("firecracker/sandboxes") - .join(&name) - .join("passt.log"), - ); - let net = d - .exec( - &sb, - "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", - ) - .await; - bail!( - "no address for example.com in the sandbox ({resolved:?}); passt said {passt:?}; the VM's network: {net:?}" - ); + let report = network_report(&d, &sb, &cfg.data_dir()).await; + bail!("no address for example.com in the sandbox ({resolved:?})\n{report}"); } let fetched = d .exec( From c0f2383e1982aa3c100c42118c26bf19de2fdb93 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:49:06 +0000 Subject: [PATCH 09/26] test(host): capture passt's frames and debug log in CI, where VMs get no network --- .github/workflows/ci.yml | 1 + .../fctl-host/src/driver/firecracker/mod.rs | 73 ++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a85ca1ed..e6224737 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,6 +137,7 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + FCTL_TEST_FIRECRACKER_PASST_DEBUG: /tmp/passt.pcap run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - name: What AppArmor and the kernel said diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 8ba27b90..12d837e2 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1168,25 +1168,77 @@ mod tests { async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { let dir = data.join("firecracker/sandboxes").join(&sb.name); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); - let passt_runs = read("passt.pid") - .trim() - .parse::() - .ok() - .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) - .map(|cmdline| cmdline.replace('\0', " ")); + let passt = read("passt.pid").trim().parse::().ok().map(|pid| { + let proc = + |f: &str| std::fs::read_to_string(format!("/proc/{pid}/{f}")).unwrap_or_default(); + let fds = std::fs::read_dir(format!("/proc/{pid}/fd")) + .map(|d| { + d.flatten() + .filter_map(|e| std::fs::read_link(e.path()).ok()) + .map(|l| l.display().to_string()) + .collect::>() + }) + .unwrap_or_default(); + format!( + "{}\n{}\nfds: {fds:?}", + proc("cmdline").replace('\0', " "), + proc("status") + .lines() + .filter(|l| l.starts_with("State")) + .collect::() + ) + }); + // Its capture, where the test asked for one (debug_passt). + let frames = std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG") + .and_then(|pcap| std::fs::read(pcap).ok()) + .map(|pcap| pcap_summary(&pcap)); let vm = d .exec( sb, - "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; format!( - "passt runs: {passt_runs:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network: {vm:?}", + "passt: {passt:?}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), - read("console.log").trim() + read("console.log").trim(), + vm.unwrap_or_else(|e| format!("{e:#}")) ) } + /// The frames in a pcap file, each as its length and first bytes. + fn pcap_summary(pcap: &[u8]) -> Vec { + let mut frames = Vec::new(); + let mut at = 24; + while let Some(header) = pcap.get(at..at + 16) { + let len = u32::from_le_bytes([header[8], header[9], header[10], header[11]]) as usize; + let frame = pcap.get(at + 16..at + 16 + len).unwrap_or_default(); + frames.push(format!( + "{len}: {}", + hex::encode(&frame[..frame.len().min(42)]) + )); + at += 16 + len; + } + frames + } + + /// passt with its debug log and a capture of its frames, in place of the + /// host's: a script that runs it so, which + /// `FCTL_TEST_FIRECRACKER_PASST_DEBUG` asks for, naming the capture's + /// file (in /tmp, where Ubuntu's AppArmor profile lets passt write). + fn debug_passt(dir: &Path) -> Result { + let passt = find_program("passt").context("passt is not installed")?; + let script = dir.join("passt-debug"); + crate::driver::fake::write_script( + &script, + &format!( + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --debug --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + passt.display() + ), + )?; + Ok(script) + } + /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1219,6 +1271,9 @@ mod tests { }; cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; + if std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG").is_some() { + cfg.firecracker.passt = Some(debug_passt(temp.path())?); + } let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; assert!(probed.available, "{probed:?}"); From b78389c39fec4cda21a811b0d87d243aed8af0e5 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:56:42 +0000 Subject: [PATCH 10/26] test(host): say where passt waits, as root, when a sandbox has no network --- .../fctl-host/src/driver/firecracker/mod.rs | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 12d837e2..7cb8906f 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1179,13 +1179,34 @@ mod tests { .collect::>() }) .unwrap_or_default(); + // passt makes itself undumpable: root sees the rest, where sudo + // asks for no password (as on CI's runners). + let sudo = |args: &[&str]| { + std::process::Command::new("sudo") + .arg("-n") + .args(args) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) + .unwrap_or_default() + }; + let p = pid.to_string(); format!( - "{}\n{}\nfds: {fds:?}", + "{}\n{}\nfds: {fds:?}\nas root: fds {}\nsyscall {}\nstack {}\nsockets: {}", proc("cmdline").replace('\0', " "), proc("status") .lines() .filter(|l| l.starts_with("State")) - .collect::() + .collect::(), + sudo(&["ls", "-l", &format!("/proc/{p}/fd")]), + sudo(&["cat", &format!("/proc/{p}/syscall")]), + sudo(&["cat", &format!("/proc/{p}/stack")]), + sudo(&["ss", "-xanp"]) + .lines() + .filter(|l| l.contains("v.sock") + || l.contains("passt") + || l.contains("firecracker")) + .collect::>() + .join("\n") ) }); // Its capture, where the test asked for one (debug_passt). From e384059193df06b26a6ca0db8faf8d73302fd6a5 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:02:09 +0000 Subject: [PATCH 11/26] test(host): passt's trace in CI, which logs each event --- crates/fctl-host/src/driver/firecracker/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 7cb8906f..8a7385c6 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1253,7 +1253,7 @@ mod tests { crate::driver::fake::write_script( &script, &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --debug --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", passt.display() ), )?; From 554c8ff37d14d68613835891e78630137c8382dd Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:06:46 +0000 Subject: [PATCH 12/26] test(host): trace passt's accept in CI --- .github/workflows/ci.yml | 6 ++++-- crates/fctl-host/src/driver/firecracker/mod.rs | 5 +++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6224737..c3fe69c6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,7 +129,7 @@ jobs: run: | sudo chmod 666 /dev/kvm sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends passt e2fsprogs + sudo apt-get install -y --no-install-recommends passt e2fsprogs strace # What confines passt, which runs as the host's user. sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" rustup target add x86_64-unknown-linux-musl @@ -143,7 +143,9 @@ jobs: - name: What AppArmor and the kernel said if: failure() # journald takes the kernel's audit records, AppArmor's among them. - run: sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | tail -60 + run: | + sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | grep -v STATUS | tail -60 + sudo dmesg | tail -30 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 8a7385c6..915a00a7 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1219,8 +1219,9 @@ mod tests { "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; + let strace = std::fs::read_to_string("/tmp/passt.strace").unwrap_or_default(); format!( - "passt: {passt:?}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", + "passt: {passt:?}\npasst's syscalls:\n{strace}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), read("console.log").trim(), vm.unwrap_or_else(|e| format!("{e:#}")) @@ -1253,7 +1254,7 @@ mod tests { crate::driver::fake::write_script( &script, &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec strace -f -tt -e trace=accept4,accept,getsockopt,setsockopt,epoll_ctl -o /tmp/passt.strace {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", passt.display() ), )?; From 19f0969fc1f0b32026d0250c06d469b9f2e62ddf Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:07:16 +0000 Subject: [PATCH 13/26] feat(host): share package caches with Firecracker VMs over 9P on their vsock Firecracker's VMs share no filesystem with the host, so projects that share package caches got none there. The host now runs fctl-agent share beside each VM, as it runs passt: a 9P2000.L server of the project's cache directory on the VM's vsock port 1026, confined to that directory (one name at a time, no symlinks followed, no devices or setuid files, locks as the host's). Once the VM is up, fctl-agent vm-mount mounts the connection at /var/cache/fctl with the kernel's 9p client (trans=fd), as the image's user's files, so several sandboxes of a project share their caches at once. --- Cargo.lock | 1 + crates/fctl-agent/Cargo.toml | 1 + crates/fctl-agent/src/main.rs | 36 + crates/fctl-agent/src/share/mod.rs | 916 ++++++++++++++++++ crates/fctl-agent/src/share/tests.rs | 438 +++++++++ crates/fctl-agent/src/share/wire.rs | 251 +++++ crates/fctl-agent/src/vm/mod.rs | 5 + crates/fctl-agent/src/vm/mount.rs | 85 ++ crates/fctl-host/src/caches.rs | 9 +- .../fctl-host/src/driver/firecracker/mod.rs | 160 +++ crates/fctl-host/src/driver/firecracker/vm.rs | 79 +- crates/fctl-host/src/driver/mod.rs | 18 +- crates/fctl-proto/src/vm.rs | 7 +- ...s-run-sandboxes-in-firecracker-microvms.md | 7 +- docs/architecture.md | 26 +- docs/cli.md | 5 +- 16 files changed, 2010 insertions(+), 34 deletions(-) create mode 100644 crates/fctl-agent/src/share/mod.rs create mode 100644 crates/fctl-agent/src/share/tests.rs create mode 100644 crates/fctl-agent/src/share/wire.rs create mode 100644 crates/fctl-agent/src/vm/mount.rs diff --git a/Cargo.lock b/Cargo.lock index 90cf6019..5cf715f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,6 +541,7 @@ dependencies = [ "fctl-domain", "fctl-proto", "flate2", + "libc", "nix", "serde", "serde_json", diff --git a/crates/fctl-agent/Cargo.toml b/crates/fctl-agent/Cargo.toml index c465aab2..076012a1 100644 --- a/crates/fctl-agent/Cargo.toml +++ b/crates/fctl-agent/Cargo.toml @@ -26,6 +26,7 @@ tracing-subscriber.workspace = true # The init of Firecracker microVMs (src/vm). [target.'cfg(target_os = "linux")'.dependencies] flate2.workspace = true +libc.workspace = true nix = { workspace = true, features = ["hostname", "mount", "net", "reboot", "resource", "socket", "time"] } tar.workspace = true tokio-tun = "0.15.2" diff --git a/crates/fctl-agent/src/main.rs b/crates/fctl-agent/src/main.rs index 284fea2c..fb5b0574 100644 --- a/crates/fctl-agent/src/main.rs +++ b/crates/fctl-agent/src/main.rs @@ -7,6 +7,9 @@ //! the host asks there (src/vm). //! - `fctl-agent run-as` runs a program as another user, for `vm-serve` and //! for a supervisor that runs as root. +//! - `fctl-agent share`, on a Firecracker host, serves a project's package +//! caches to a VM over its vsock (src/share), and `vm-mount` in the VM +//! mounts them. //! //! See docs/architecture.md and crates/fctl-proto/src/agent.rs. @@ -22,6 +25,8 @@ mod prompt; #[cfg(target_os = "linux")] mod protected; mod refresh; +#[cfg(target_os = "linux")] +mod share; mod supervisor; mod tasks; mod user; @@ -81,6 +86,30 @@ enum Command { #[cfg(target_os = "linux")] #[command(hide = true)] VmServe, + /// Serve a directory to a Firecracker VM over 9P, on the unix socket + /// where Firecracker connects the VM's vsock port (on the host). + #[cfg(target_os = "linux")] + #[command(hide = true)] + Share { + #[arg(long)] + dir: PathBuf, + #[arg(long)] + socket: PathBuf, + }, + /// Mount what the host shares on a vsock port at a directory, as a user's + /// files (in a Firecracker VM, as root). + #[cfg(target_os = "linux")] + #[command(hide = true)] + VmMount { + #[arg(long)] + port: u32, + #[arg(long)] + dir: PathBuf, + /// Whose files they are in the VM: a name or a uid, as `docker exec + /// -u` takes them. + #[arg(long)] + user: Option, + }, /// Run a program as a user, in a session of its own (for vm-serve, and /// a supervisor that runs as root). #[cfg(target_os = "linux")] @@ -154,6 +183,13 @@ fn main() -> anyhow::Result<()> { runtime()?.block_on(vm::serve()) } #[cfg(target_os = "linux")] + Command::Share { dir, socket } => { + init_logging(None)?; + share::serve(&dir, &socket) + } + #[cfg(target_os = "linux")] + Command::VmMount { port, dir, user } => vm::mount(port, &dir, user.as_deref()), + #[cfg(target_os = "linux")] Command::RunAs { .. } => Ok(()), } } diff --git a/crates/fctl-agent/src/share/mod.rs b/crates/fctl-agent/src/share/mod.rs new file mode 100644 index 00000000..697db0e6 --- /dev/null +++ b/crates/fctl-agent/src/share/mod.rs @@ -0,0 +1,916 @@ +//! `fctl-agent share`: a 9P2000.L file server for a project's package +//! caches, which the host runs beside each Firecracker VM, as it runs +//! `passt` (crates/fctl-host/src/driver/firecracker). Firecracker's VMs share +//! no filesystem with the host, so the VM's kernel mounts the caches over +//! its vsock: the host listens where Firecracker connects the VM's +//! [`fctl_proto::vm::SHARE_PORT`], and `fctl-agent vm-mount` in the VM +//! connects to it and mounts the connection (9p's `trans=fd`). Each VM has a +//! server of its own; the files are the host's, in the directory every +//! sandbox of the project shares, as Docker's volumes and Apple's +//! `container`'s mounts are. +//! +//! Anything in the VM can connect to the host's port, so the server takes +//! no request as more than the files under its directory: +//! +//! - Every file it hands out was reached from the directory one name at a +//! time, without following symlinks; names are never `.`, `..` or have a +//! `/`. The client resolves symlinks, against the VM's files. +//! - It opens only directories and regular files, and makes neither device +//! files nor setuid or setgid ones. +//! - Files belong to the host's user. The VM sees them as its user's (the +//! uid and gid the mount names), whose package managers and git check that +//! their caches are theirs, and changes of owner do nothing. +//! - Locks are the host's, on open files (`F_OFD_SETLK`), so two VMs' cargo +//! runs wait for each other as two containers' do. + +pub mod wire; + +#[cfg(test)] +mod tests; + +use anyhow::{Context, Result}; +use nix::errno::Errno; +use nix::fcntl::{AT_FDCWD, FcntlArg, OFlag, openat}; +use nix::sys::stat::{ + FchmodatFlags, FileStat, Mode, SFlag, UtimensatFlags, fchmodat, fstatat, mkdirat, utimensat, +}; +use nix::sys::time::TimeSpec; +use nix::unistd::{UnlinkatFlags, linkat, symlinkat, unlinkat}; +use std::collections::HashMap; +use std::ffi::{CString, OsStr}; +use std::fs::File; +use std::io::{self, BufReader, Read, Write}; +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{DirEntryExt, FileExt, OpenOptionsExt}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::Path; +use wire::{Qid, Reader, Writer, kind}; + +/// The largest message either side sends: the client asks for less. +pub const MAX_MSIZE: u32 = 1024 * 1024; + +/// The most fids one connection holds: each is an open file of the +/// server's. +const MAX_FIDS: usize = 1 << 16; + +/// The protocol, the one the Linux client asks for first. +const VERSION: &[u8] = b"9P2000.L"; + +/// `Rgetattr`'s fields that this server fills in (`P9_GETATTR_BASIC`). +const GETATTR_BASIC: u64 = 0x7ff; + +/// `Tsetattr`'s fields (`P9_ATTR_…`). +mod attr { + pub const MODE: u32 = 1; + pub const SIZE: u32 = 8; + pub const ATIME: u32 = 16; + pub const MTIME: u32 = 32; + pub const ATIME_SET: u32 = 128; + pub const MTIME_SET: u32 = 256; +} + +/// The open flags of 9P2000.L (`P9_DOTL_…`), which are x86's whatever the +/// machine: the client translates its own. +mod open { + pub const ACCESS: u32 = 3; + pub const WRONLY: u32 = 1; + pub const RDWR: u32 = 2; + pub const EXCL: u32 = 0o200; + pub const TRUNC: u32 = 0o1000; + pub const APPEND: u32 = 0o2000; + pub const DSYNC: u32 = 0o10000; + pub const SYNC: u32 = 0o4000000; +} + +/// `Tlock`'s types and statuses. +mod lock { + pub const RDLCK: u8 = 0; + pub const WRLCK: u8 = 1; + pub const UNLCK: u8 = 2; + pub const SUCCESS: u8 = 0; + pub const BLOCKED: u8 = 1; + pub const ERROR: u8 = 2; +} + +/// `Tunlinkat`'s flag for a directory (`AT_REMOVEDIR`). +const REMOVEDIR: u32 = 0x200; + +/// What the VM's `statfs` says the filesystem is (`V9FS_MAGIC`). +const V9FS_MAGIC: u32 = 0x0102_1997; + +/// Serves the directory `dir` on the unix socket `socket`, each connection +/// in a thread of its own, until the host stops it. +pub fn serve(dir: &Path, socket: &Path) -> Result<()> { + raise_open_files(); + let root: OwnedFd = File::options() + .read(true) + .custom_flags(libc::O_PATH | libc::O_DIRECTORY) + .open(dir) + .with_context(|| format!("opening {}", dir.display()))? + .into(); + // What a server that stopped left. + let _ = std::fs::remove_file(socket); + let listener = + UnixListener::bind(socket).with_context(|| format!("listening on {}", socket.display()))?; + tracing::info!("serving {} on {}", dir.display(), socket.display()); + for conn in listener.incoming() { + let conn = match conn { + Ok(conn) => conn, + Err(e) => { + tracing::warn!("taking a connection: {e}"); + continue; + } + }; + let root = root.try_clone()?; + std::thread::spawn(move || { + let mut session = Session::new(root); + if let Err(e) = session.run(conn) { + tracing::debug!("a connection ended: {e}"); + } + }); + } + Ok(()) +} + +/// The client may hold a fid for each file it has in use, each an open +/// file here: as many as the system lets this process have. +fn raise_open_files() { + use nix::sys::resource::{Resource, getrlimit, setrlimit}; + if let Ok((_, hard)) = getrlimit(Resource::RLIMIT_NOFILE) { + let _ = setrlimit(Resource::RLIMIT_NOFILE, hard, hard); + } +} + +/// What a fid refers to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Dir, + File, + Symlink, + /// A device, a FIFO or a socket, which the server never opens. + Other, +} + +impl Kind { + fn of(st: &FileStat) -> Self { + match SFlag::from_bits_truncate(st.st_mode & SFlag::S_IFMT.bits()) { + SFlag::S_IFDIR => Self::Dir, + SFlag::S_IFREG => Self::File, + SFlag::S_IFLNK => Self::Symlink, + _ => Self::Other, + } + } +} + +/// A file the client holds: `fd` refers to it (opened with `O_PATH`, or +/// for reading and writing), `open` once the client opened it. +struct Fid { + fd: OwnedFd, + kind: Kind, + open: Option, + /// A directory's entries, read when the client reads it from the start. + entries: Vec<(Vec, Qid, u8)>, + /// An extended attribute's: it has none, so it reads as nothing. + xattr: bool, +} + +impl Fid { + fn new(fd: OwnedFd, kind: Kind) -> Self { + Self { + fd, + kind, + open: None, + entries: Vec::new(), + xattr: false, + } + } +} + +/// One client's connection: its fids, and what it agreed to. +pub struct Session { + root: OwnedFd, + fids: HashMap, + msize: u32, + /// Who the files belong to in the VM: the uid and gid the mount names. + owner: (u32, u32), +} + +fn errno(e: Errno) -> io::Error { + io::Error::from_raw_os_error(e as i32) +} + +fn fail(e: i32) -> io::Result { + Err(io::Error::from_raw_os_error(e)) +} + +/// A name in a directory, as the client sends it: one component, never +/// `.` or `..`. +fn name(n: &[u8]) -> io::Result { + if n.is_empty() || n == b"." || n == b".." || n.contains(&b'/') || n.contains(&0) { + return fail(libc::EINVAL); + } + if n.len() > 255 { + return fail(libc::ENAMETOOLONG); + } + CString::new(n).map_err(|_| io::Error::from_raw_os_error(libc::EINVAL)) +} + +fn stat_of(fd: impl AsFd) -> io::Result { + fstatat( + fd, + c"", + nix::fcntl::AtFlags::AT_EMPTY_PATH | nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW, + ) + .map_err(errno) +} + +fn stat_at(dir: impl AsFd, n: &CString) -> io::Result { + fstatat(dir, n.as_c_str(), nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW).map_err(errno) +} + +fn qid(st: &FileStat) -> Qid { + let kind = match Kind::of(st) { + Kind::Dir => wire::QTDIR, + Kind::Symlink => wire::QTSYMLINK, + Kind::File | Kind::Other => wire::QTFILE, + }; + Qid { + kind, + // Changes when the file does, for the client's caches. + version: (st.st_mtime as u32) ^ (st.st_mtime_nsec as u32), + path: st.st_ino, + } +} + +/// The path that opens `fd`'s file again, with other flags: the file +/// itself, wherever it has moved since. +fn reopen_path(fd: &OwnedFd) -> String { + format!("/proc/self/fd/{}", fd.as_raw_fd()) +} + +/// Never more than this: the mode a client may give a file, without the +/// setuid and setgid bits. +const MODE_BITS: u32 = 0o1777; + +impl Session { + pub fn new(root: OwnedFd) -> Self { + Self { + root, + fids: HashMap::new(), + msize: 8192, + owner: (0, 0), + } + } + + /// Answers the client's requests, one after the other, until it goes. + pub fn run(&mut self, conn: UnixStream) -> io::Result<()> { + let mut reader = BufReader::with_capacity(256 * 1024, conn.try_clone()?); + let mut writer = conn; + let mut message = Vec::new(); + loop { + let mut size = [0u8; 4]; + match reader.read_exact(&mut size) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(()), + Err(e) => return Err(e), + } + let size = u32::from_le_bytes(size); + if !(wire::HEADER as u32..=MAX_MSIZE + 64).contains(&size) { + return Err(io::Error::other(format!("a message of {size} bytes"))); + } + message.resize(size as usize - 4, 0); + reader.read_exact(&mut message)?; + let reply = self.answer(&message); + writer.write_all(&reply)?; + } + } + + /// The reply to one message (its type, tag and fields). + pub fn answer(&mut self, message: &[u8]) -> Vec { + let mut r = Reader::new(message); + let (Ok(kind), Ok(tag)) = (r.u8(), r.u16()) else { + return wire::error(wire::NOTAG, libc::EPROTO); + }; + match self.handle(kind, tag, &mut r) { + Ok(reply) => reply, + Err(e) => wire::error(tag, e.raw_os_error().unwrap_or(libc::EIO)), + } + } + + fn fid(&self, fid: u32) -> io::Result<&Fid> { + self.fids + .get(&fid) + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF)) + } + + fn fid_mut(&mut self, fid: u32) -> io::Result<&mut Fid> { + self.fids + .get_mut(&fid) + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF)) + } + + /// A directory the client holds, to make or find names in. + fn dir(&self, fid: u32) -> io::Result<&OwnedFd> { + let f = self.fid(fid)?; + if f.kind != Kind::Dir { + return fail(libc::ENOTDIR); + } + Ok(&f.fd) + } + + fn insert(&mut self, fid: u32, f: Fid) -> io::Result<()> { + if self.fids.len() >= MAX_FIDS && !self.fids.contains_key(&fid) { + return fail(libc::EMFILE); + } + self.fids.insert(fid, f); + Ok(()) + } + + fn handle(&mut self, t: u8, tag: u16, r: &mut Reader) -> io::Result> { + let reply = |t: u8| Writer::new(t + 1, tag); + match t { + kind::TVERSION => { + let msize = r.u32()?; + let version = r.bytes()?; + self.fids.clear(); + self.msize = msize.clamp(4096, MAX_MSIZE); + let mut w = reply(t); + w.u32(self.msize); + w.bytes(if version.starts_with(VERSION) { + VERSION + } else { + b"unknown" + }); + Ok(w.finish()) + } + kind::TATTACH => { + let fid = r.u32()?; + // Nothing to authenticate: the VM reaches no other server. + if r.u32()? != wire::NOFID { + return fail(libc::EOPNOTSUPP); + } + let _uname = r.bytes()?; + let aname = r.bytes()?; + let n_uname = r.u32()?; + if self.fids.contains_key(&fid) { + return fail(libc::EBADF); + } + self.owner = owner(aname, n_uname); + let root = self.root.try_clone()?; + let st = stat_of(&root)?; + self.insert(fid, Fid::new(root, Kind::Dir))?; + let mut w = reply(t); + w.qid(qid(&st)); + Ok(w.finish()) + } + kind::TWALK => self.walk(tag, r), + kind::TLOPEN => { + let fid = r.u32()?; + let flags = r.u32()?; + let f = self.fid_mut(fid)?; + if f.open.is_some() { + return fail(libc::EBADF); + } + let file = match f.kind { + Kind::Dir => File::from( + openat( + &f.fd, + c".", + OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, + Mode::empty(), + ) + .map_err(errno)?, + ), + Kind::File => open_options(flags).open(reopen_path(&f.fd))?, + Kind::Symlink => return fail(libc::ELOOP), + Kind::Other => return fail(libc::EPERM), + }; + let st = stat_of(&file)?; + f.open = Some(file); + let mut w = reply(t); + w.qid(qid(&st)).u32(0); + Ok(w.finish()) + } + kind::TLCREATE => { + let fid = r.u32()?; + let n = name(r.bytes()?)?; + let flags = r.u32()?; + let mode = r.u32()?; + let _gid = r.u32()?; + let dir = self.dir(fid)?; + if self.fid(fid)?.open.is_some() { + return fail(libc::EBADF); + } + let mut oflags = open_flags(flags) | OFlag::O_CREAT | OFlag::O_NOFOLLOW; + if flags & open::EXCL != 0 { + oflags |= OFlag::O_EXCL; + } + let fd = openat(dir, n.as_c_str(), oflags, file_mode(mode)).map_err(errno)?; + let file = File::from(fd); + let st = stat_of(&file)?; + let path = OwnedFd::from(file.try_clone()?); + let f = self.fid_mut(fid)?; + *f = Fid::new(path, Kind::File); + f.open = Some(file); + let mut w = reply(t); + w.qid(qid(&st)).u32(0); + Ok(w.finish()) + } + kind::TSYMLINK => { + let fid = r.u32()?; + let n = name(r.bytes()?)?; + let target = r.bytes()?; + let _gid = r.u32()?; + if target.is_empty() || target.len() > 4095 || target.contains(&0) { + return fail(libc::EINVAL); + } + let dir = self.dir(fid)?; + symlinkat(OsStr::from_bytes(target), dir, n.as_c_str()).map_err(errno)?; + let st = stat_at(dir, &n)?; + let mut w = reply(t); + w.qid(qid(&st)); + Ok(w.finish()) + } + kind::TMKDIR => { + let fid = r.u32()?; + let n = name(r.bytes()?)?; + let mode = r.u32()?; + let _gid = r.u32()?; + let dir = self.dir(fid)?; + mkdirat(dir, n.as_c_str(), file_mode(mode)).map_err(errno)?; + let st = stat_at(dir, &n)?; + let mut w = reply(t); + w.qid(qid(&st)); + Ok(w.finish()) + } + kind::TREADLINK => { + let f = self.fid(r.u32()?)?; + if f.kind != Kind::Symlink { + return fail(libc::EINVAL); + } + let target = nix::fcntl::readlinkat(&f.fd, c"").map_err(errno)?; + let mut w = reply(t); + w.bytes(target.as_bytes()); + Ok(w.finish()) + } + kind::TGETATTR => { + let f = self.fid(r.u32()?)?; + let _mask = r.u64()?; + let st = stat_of(&f.fd)?; + let mut w = reply(t); + w.u64(GETATTR_BASIC) + .qid(qid(&st)) + .u32(st.st_mode) + .u32(self.owner.0) + .u32(self.owner.1) + .u64(u64::from(st.st_nlink)) + .u64(st.st_rdev) + .u64(u64::try_from(st.st_size).unwrap_or(0)) + .u64(u64::try_from(st.st_blksize).unwrap_or(4096)) + .u64(u64::try_from(st.st_blocks).unwrap_or(0)); + for (sec, nsec) in [ + (st.st_atime, st.st_atime_nsec), + (st.st_mtime, st.st_mtime_nsec), + (st.st_ctime, st.st_ctime_nsec), + (0, 0), + ] { + w.u64(sec as u64).u64(nsec as u64); + } + // gen and data_version. + w.u64(0).u64(0); + Ok(w.finish()) + } + kind::TSETATTR => self.setattr(tag, r), + kind::TXATTRWALK => { + let fid = r.u32()?; + let newfid = r.u32()?; + let n = r.bytes()?; + // No file has any: a list of them is empty, and each is missing. + if !n.is_empty() { + return fail(libc::ENODATA); + } + let fd = self.fid(fid)?.fd.try_clone()?; + let mut f = Fid::new(fd, Kind::Other); + f.xattr = true; + self.insert(newfid, f)?; + let mut w = reply(t); + w.u64(0); + Ok(w.finish()) + } + kind::TREADDIR => self.readdir(tag, r), + kind::TFSYNC => { + let f = self.fid(r.u32()?)?; + let datasync = r.u32()? != 0; + if let Some(file) = &f.open { + if datasync { + file.sync_data()?; + } else { + file.sync_all()?; + } + } + Ok(reply(t).finish()) + } + kind::TLOCK => { + let f = self.fid(r.u32()?)?; + let kind = r.u8()?; + let _flags = r.u32()?; + let start = r.u64()?; + let length = r.u64()?; + let file = f + .open + .as_ref() + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; + let status = match nix::fcntl::fcntl( + file, + FcntlArg::F_OFD_SETLK(&flock(kind, start, length)?), + ) { + Ok(_) => lock::SUCCESS, + Err(Errno::EAGAIN | Errno::EACCES) => lock::BLOCKED, + Err(_) => lock::ERROR, + }; + let mut w = reply(t); + w.u8(status); + Ok(w.finish()) + } + kind::TGETLOCK => { + let f = self.fid(r.u32()?)?; + let kind = r.u8()?; + let start = r.u64()?; + let length = r.u64()?; + let proc_id = r.u32()?; + let client = r.bytes()?; + let file = f + .open + .as_ref() + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; + let mut fl = flock(kind, start, length)?; + nix::fcntl::fcntl(file, FcntlArg::F_OFD_GETLK(&mut fl)).map_err(errno)?; + let mut w = reply(t); + if i32::from(fl.l_type) == libc::F_UNLCK { + w.u8(lock::UNLCK) + .u64(start) + .u64(length) + .u32(proc_id) + .bytes(client); + } else { + let kind = if i32::from(fl.l_type) == libc::F_WRLCK { + lock::WRLCK + } else { + lock::RDLCK + }; + // Another VM's: no process here holds it. + w.u8(kind) + .u64(u64::try_from(fl.l_start).unwrap_or(0)) + .u64(u64::try_from(fl.l_len).unwrap_or(0)) + .u32(u32::MAX) + .bytes(b""); + } + Ok(w.finish()) + } + kind::TLINK => { + let dfid = r.u32()?; + let fid = r.u32()?; + let n = name(r.bytes()?)?; + let f = self.fid(fid)?; + // A link to a symlink would follow it. + if f.kind != Kind::File { + return fail(libc::EPERM); + } + let dir = self.dir(dfid)?; + linkat( + AT_FDCWD, + reopen_path(&f.fd).as_str(), + dir, + n.as_c_str(), + nix::fcntl::AtFlags::AT_SYMLINK_FOLLOW, + ) + .map_err(errno)?; + Ok(reply(t).finish()) + } + kind::TRENAMEAT => { + let old_dir = r.u32()?; + let old = name(r.bytes()?)?; + let new_dir = r.u32()?; + let new = name(r.bytes()?)?; + nix::fcntl::renameat( + self.dir(old_dir)?, + old.as_c_str(), + self.dir(new_dir)?, + new.as_c_str(), + ) + .map_err(errno)?; + Ok(reply(t).finish()) + } + kind::TUNLINKAT => { + let dir = r.u32()?; + let n = name(r.bytes()?)?; + let flags = r.u32()?; + let how = if flags & REMOVEDIR != 0 { + UnlinkatFlags::RemoveDir + } else { + UnlinkatFlags::NoRemoveDir + }; + unlinkat(self.dir(dir)?, n.as_c_str(), how).map_err(errno)?; + Ok(reply(t).finish()) + } + kind::TFLUSH => { + // Requests are answered in order: the one to flush is done. + let _oldtag = r.u16()?; + Ok(reply(t).finish()) + } + kind::TREAD => { + let f = self.fid(r.u32()?)?; + let offset = r.u64()?; + let count = r.u32()?.min(self.msize - wire::READ_OVERHEAD); + let mut w = reply(t); + if f.xattr { + w.data(&[]); + return Ok(w.finish()); + } + let file = match (&f.open, f.kind) { + (Some(file), Kind::File) => file, + (Some(_), _) => return fail(libc::EISDIR), + (None, _) => return fail(libc::EBADF), + }; + let mut buf = vec![0u8; count as usize]; + let n = file.read_at(&mut buf, offset)?; + w.data(&buf[..n]); + Ok(w.finish()) + } + kind::TWRITE => { + let f = self.fid(r.u32()?)?; + let offset = r.u64()?; + let data = r.data()?; + let file = match (&f.open, f.kind) { + (Some(file), Kind::File) => file, + (Some(_), _) => return fail(libc::EISDIR), + (None, _) => return fail(libc::EBADF), + }; + let n = file.write_at(data, offset)?; + let mut w = reply(t); + w.u32(u32::try_from(n).unwrap_or(0)); + Ok(w.finish()) + } + kind::TCLUNK => { + let fid = r.u32()?; + self.fids + .remove(&fid) + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; + Ok(reply(t).finish()) + } + kind::TREMOVE => { + // The Linux client removes names with Tunlinkat; this one + // only lets the fid go, as a remove that fails must. + self.fids.remove(&r.u32()?); + fail(libc::EOPNOTSUPP) + } + kind::TSTATFS => { + let f = self.fid(r.u32()?)?; + let st = nix::sys::statfs::fstatfs(&f.fd).map_err(errno)?; + let mut w = reply(t); + w.u32(V9FS_MAGIC) + .u32(u32::try_from(st.block_size()).unwrap_or(4096)) + .u64(st.blocks()) + .u64(st.blocks_free()) + .u64(st.blocks_available()) + .u64(st.files()) + .u64(st.files_free()) + .u64(0) + .u32(u32::try_from(st.maximum_name_length()).unwrap_or(255)); + Ok(w.finish()) + } + // No device files, and no attributes to set; the old 9P2000's + // requests, authentication and renames by fid, which the Linux + // client asks only of servers that lack the 9P2000.L ones. + kind::TMKNOD => fail(libc::EPERM), + kind::TXATTRCREATE | kind::TAUTH | kind::TRENAME => fail(libc::EOPNOTSUPP), + _ => fail(libc::EOPNOTSUPP), + } + } + + fn walk(&mut self, tag: u16, r: &mut Reader) -> io::Result> { + let fid = r.u32()?; + let newfid = r.u32()?; + let count = r.u16()?; + if count > 16 { + return fail(libc::EINVAL); + } + if fid != newfid && self.fids.contains_key(&newfid) { + return fail(libc::EBADF); + } + let start = self.fid(fid)?; + let mut current = start.fd.try_clone()?; + let mut kind_now = start.kind; + let mut qids = Vec::new(); + for i in 0..count { + let step = r.bytes().and_then(name).and_then(|n| { + let fd = openat( + ¤t, + n.as_c_str(), + OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC, + Mode::empty(), + ) + .map_err(errno)?; + let st = stat_of(&fd)?; + Ok((fd, st)) + }); + match step { + Ok((fd, st)) => { + current = fd; + kind_now = Kind::of(&st); + qids.push(qid(&st)); + } + // The first name must be there; past it, the reply says how + // far the walk went. + Err(e) if i == 0 => return Err(e), + Err(_) => break, + } + } + if qids.len() == usize::from(count) { + self.insert(newfid, Fid::new(current, kind_now))?; + } + let mut w = Writer::new(kind::TWALK + 1, tag); + w.u16(u16::try_from(qids.len()).unwrap_or(0)); + for q in qids { + w.qid(q); + } + Ok(w.finish()) + } + + fn setattr(&mut self, tag: u16, r: &mut Reader) -> io::Result> { + let fid = r.u32()?; + let valid = r.u32()?; + let mode = r.u32()?; + let _uid = r.u32()?; + let _gid = r.u32()?; + let size = r.u64()?; + let atime = (r.u64()?, r.u64()?); + let mtime = (r.u64()?, r.u64()?); + let f = self.fid(fid)?; + // The client changes no symlink: chmod and truncate follow them. + if f.kind == Kind::Symlink { + return Ok(Writer::new(kind::TSETATTR + 1, tag).finish()); + } + let path = reopen_path(&f.fd); + if valid & attr::MODE != 0 { + fchmodat( + AT_FDCWD, + path.as_str(), + Mode::from_bits_truncate(mode & MODE_BITS), + FchmodatFlags::FollowSymlink, + ) + .map_err(errno)?; + } + if valid & attr::SIZE != 0 { + match (&f.open, f.kind) { + (_, Kind::Dir) => return fail(libc::EISDIR), + (_, Kind::Other) => return fail(libc::EPERM), + (Some(file), _) if file.set_len(size).is_ok() => {} + _ => File::options().write(true).open(&path)?.set_len(size)?, + } + } + if valid & (attr::ATIME | attr::MTIME) != 0 { + let time = |set: u32, given: u32, (sec, nsec): (u64, u64)| { + if valid & set == 0 { + TimeSpec::UTIME_OMIT + } else if valid & given == 0 { + TimeSpec::UTIME_NOW + } else { + TimeSpec::new(sec as i64, nsec as i64) + } + }; + utimensat( + AT_FDCWD, + path.as_str(), + &time(attr::ATIME, attr::ATIME_SET, atime), + &time(attr::MTIME, attr::MTIME_SET, mtime), + UtimensatFlags::FollowSymlink, + ) + .map_err(errno)?; + } + // Owners stay the host's user's, and ctime the kernel's. + Ok(Writer::new(kind::TSETATTR + 1, tag).finish()) + } + + /// A directory's entries from `offset`, the index after the last one + /// the client has: the directory is read anew when it starts over. + fn readdir(&mut self, tag: u16, r: &mut Reader) -> io::Result> { + let fid = r.u32()?; + let offset = r.u64()?; + let count = r.u32()?.min(self.msize - wire::READ_OVERHEAD) as usize; + let f = self.fid_mut(fid)?; + let Some(dir) = &f.open else { + return fail(libc::EBADF); + }; + if f.kind != Kind::Dir { + return fail(libc::ENOTDIR); + } + if offset == 0 || f.entries.is_empty() { + let here = qid(&stat_of(dir)?); + let mut entries = vec![ + (b".".to_vec(), here, libc::DT_DIR), + (b"..".to_vec(), here, libc::DT_DIR), + ]; + let read = std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd()))?; + for entry in read.flatten() { + let (kind, dt) = match entry.file_type() { + Ok(t) if t.is_dir() => (wire::QTDIR, libc::DT_DIR), + Ok(t) if t.is_symlink() => (wire::QTSYMLINK, libc::DT_LNK), + Ok(t) if t.is_file() => (wire::QTFILE, libc::DT_REG), + _ => (wire::QTFILE, libc::DT_UNKNOWN), + }; + let q = Qid { + kind, + version: 0, + path: entry.ino(), + }; + entries.push((entry.file_name().as_bytes().to_vec(), q, dt)); + } + f.entries = entries; + } + let mut out = Vec::new(); + let start = usize::try_from(offset).unwrap_or(usize::MAX); + for (i, (n, q, dt)) in f.entries.iter().enumerate().skip(start) { + if out.len() + wire::dirent_len(n) > count { + if out.is_empty() { + return fail(libc::EINVAL); + } + break; + } + wire::dirent(&mut out, *q, i as u64 + 1, *dt, n); + } + let mut w = Writer::new(kind::TREADDIR + 1, tag); + w.u32(u32::try_from(out.len()).unwrap_or(0)).raw(&out); + Ok(w.finish()) + } +} + +/// Who the files belong to in the VM: `aname`'s `uid:gid`, which +/// `fctl-agent vm-mount` puts there, else the attaching uid. +fn owner(aname: &[u8], n_uname: u32) -> (u32, u32) { + let parsed = std::str::from_utf8(aname).ok().and_then(|a| { + let (u, g) = a.split_once(':')?; + Some((u.parse().ok()?, g.parse().ok()?)) + }); + let uid = if n_uname == u32::MAX { 0 } else { n_uname }; + parsed.unwrap_or((uid, uid)) +} + +/// A file's mode, as the client may give it. +fn file_mode(mode: u32) -> Mode { + Mode::from_bits_truncate(mode & MODE_BITS) +} + +/// How `Tlopen`'s and `Tlcreate`'s flags open a file here. +fn open_flags(flags: u32) -> OFlag { + let mut o = match flags & open::ACCESS { + open::WRONLY => OFlag::O_WRONLY, + open::RDWR => OFlag::O_RDWR, + _ => OFlag::O_RDONLY, + }; + for (p9, here) in [ + (open::TRUNC, OFlag::O_TRUNC), + (open::APPEND, OFlag::O_APPEND), + (open::DSYNC, OFlag::O_DSYNC), + (open::SYNC, OFlag::O_SYNC), + ] { + if flags & p9 != 0 { + o |= here; + } + } + o | OFlag::O_CLOEXEC +} + +/// [`open_flags`], to open a file again through `/proc/self/fd`. +fn open_options(flags: u32) -> std::fs::OpenOptions { + let o = open_flags(flags); + let mut options = File::options(); + match flags & open::ACCESS { + open::WRONLY => options.write(true), + open::RDWR => options.read(true).write(true), + _ => options.read(true), + }; + options + .truncate(o.contains(OFlag::O_TRUNC)) + .append(o.contains(OFlag::O_APPEND)) + .custom_flags((o & (OFlag::O_DSYNC | OFlag::O_SYNC)).bits()); + options +} + +/// A lock as `fcntl` takes it, from `Tlock`'s or `Tgetlock`'s. +fn flock(kind: u8, start: u64, length: u64) -> io::Result { + let l_type = match kind { + lock::RDLCK => libc::F_RDLCK, + lock::WRLCK => libc::F_WRLCK, + lock::UNLCK => libc::F_UNLCK, + _ => return fail(libc::EINVAL), + }; + Ok(libc::flock { + l_type: l_type as libc::c_short, + l_whence: libc::SEEK_SET as libc::c_short, + l_start: i64::try_from(start).unwrap_or(i64::MAX), + l_len: i64::try_from(length).unwrap_or(0), + l_pid: 0, + }) +} diff --git a/crates/fctl-agent/src/share/tests.rs b/crates/fctl-agent/src/share/tests.rs new file mode 100644 index 00000000..f48e6773 --- /dev/null +++ b/crates/fctl-agent/src/share/tests.rs @@ -0,0 +1,438 @@ +use super::*; +use std::os::unix::fs::PermissionsExt; + +/// A 9P client that speaks to a [`Session`] directly, as the VM's kernel +/// would over its connection. +struct Client { + session: Session, + tag: u16, +} + +type Reply = std::result::Result, i32>; + +fn root_of(dir: &Path) -> io::Result { + Ok(File::options() + .read(true) + .custom_flags(libc::O_PATH | libc::O_DIRECTORY) + .open(dir)? + .into()) +} + +/// `P9_DOTL_RDWR`, `P9_DOTL_RDONLY` and `P9_DOTL_DIRECTORY`. +const RDWR: u32 = 2; +const RDONLY: u32 = 0; +const DIRECTORY: u32 = 0o200000; + +impl Client { + /// A client that agreed on the protocol and attached as the VM's user + /// 1000:1000, with the shared directory as fid 0. + fn new(dir: &Path) -> io::Result { + let mut c = Self { + session: Session::new(root_of(dir)?), + tag: 1, + }; + let v = c.call(kind::TVERSION, |w| { + w.u32(512 * 1024).bytes(b"9P2000.L"); + }); + assert_eq!(v.map(|b| b[4..].to_vec()), Ok(b"\x08\x009P2000.L".to_vec())); + let attached = c.call(kind::TATTACH, |w| { + w.u32(0) + .u32(wire::NOFID) + .bytes(b"") + .bytes(b"1000:1000") + .u32(1000); + }); + assert!(attached.is_ok()); + Ok(c) + } + + /// Sends a request and returns its reply's fields, or its errno. + fn call(&mut self, t: u8, build: impl FnOnce(&mut Writer)) -> Reply { + self.tag = self.tag.wrapping_add(1); + let mut w = Writer::new(t, self.tag); + build(&mut w); + let message = w.finish(); + let reply = self.session.answer(&message[4..]); + let size = u32::from_le_bytes([reply[0], reply[1], reply[2], reply[3]]); + assert_eq!(size as usize, reply.len()); + assert_eq!(u16::from_le_bytes([reply[5], reply[6]]), self.tag); + if reply[4] == kind::RLERROR { + return Err(i32::from_le_bytes([ + reply[7], reply[8], reply[9], reply[10], + ])); + } + assert_eq!(reply[4], t + 1); + Ok(reply[7..].to_vec()) + } + + /// How many names the walk took. + fn walk(&mut self, fid: u32, newfid: u32, names: &[&[u8]]) -> std::result::Result { + let body = self.call(kind::TWALK, |w| { + w.u32(fid) + .u32(newfid) + .u16(u16::try_from(names.len()).unwrap_or(0)); + for n in names { + w.bytes(n); + } + })?; + Ok(usize::from(u16::from_le_bytes([body[0], body[1]]))) + } + + fn lopen(&mut self, fid: u32, flags: u32) -> Reply { + self.call(kind::TLOPEN, |w| { + w.u32(fid).u32(flags); + }) + } + + fn lcreate(&mut self, fid: u32, name: &[u8], mode: u32) -> Reply { + self.call(kind::TLCREATE, |w| { + w.u32(fid).bytes(name).u32(RDWR).u32(mode).u32(0); + }) + } + + fn mkdir(&mut self, fid: u32, name: &[u8], mode: u32) -> Reply { + self.call(kind::TMKDIR, |w| { + w.u32(fid).bytes(name).u32(mode).u32(0); + }) + } + + fn write(&mut self, fid: u32, offset: u64, data: &[u8]) -> Reply { + self.call(kind::TWRITE, |w| { + w.u32(fid).u64(offset).data(data); + }) + } + + fn read(&mut self, fid: u32, offset: u64, count: u32) -> std::result::Result, i32> { + let body = self.call(kind::TREAD, |w| { + w.u32(fid).u64(offset).u32(count); + })?; + Ok(body[4..].to_vec()) + } + + /// Mode, uid, gid and size. + fn getattr(&mut self, fid: u32) -> std::result::Result<(u32, u32, u32, u64), i32> { + let body = self.call(kind::TGETATTR, |w| { + w.u32(fid).u64(GETATTR_BASIC); + })?; + let mut r = Reader::new(&body[8 + 13..]); + let mode = r.u32().map_err(|_| libc::EPROTO)?; + let uid = r.u32().map_err(|_| libc::EPROTO)?; + let gid = r.u32().map_err(|_| libc::EPROTO)?; + let _nlink = r.u64().map_err(|_| libc::EPROTO)?; + let _rdev = r.u64().map_err(|_| libc::EPROTO)?; + let size = r.u64().map_err(|_| libc::EPROTO)?; + Ok((mode, uid, gid, size)) + } + + fn setattr(&mut self, fid: u32, valid: u32, mode: u32, size: u64) -> Reply { + self.call(kind::TSETATTR, |w| { + w.u32(fid).u32(valid).u32(mode).u32(0).u32(0).u64(size); + w.u64(0).u64(0).u64(0).u64(0); + }) + } + + /// The names and next offsets of a directory's entries from `offset`. + fn readdir( + &mut self, + fid: u32, + offset: u64, + count: u32, + ) -> std::result::Result, u64)>, i32> { + let body = self.call(kind::TREADDIR, |w| { + w.u32(fid).u64(offset).u32(count); + })?; + let mut r = Reader::new(&body[4..]); + let mut out = Vec::new(); + while let Ok(_qid_kind) = r.u8() { + let parsed = (|| -> io::Result<(Vec, u64)> { + r.u32()?; + r.u64()?; + let next = r.u64()?; + r.u8()?; + Ok((r.bytes()?.to_vec(), next)) + })(); + out.push(parsed.map_err(|_| libc::EPROTO)?); + } + Ok(out) + } + + fn clunk(&mut self, fid: u32) -> Reply { + self.call(kind::TCLUNK, |w| { + w.u32(fid); + }) + } + + fn lock(&mut self, fid: u32, kind: u8) -> std::result::Result { + let body = self.call(kind::TLOCK, |w| { + w.u32(fid).u8(kind).u32(0).u64(0).u64(0).u32(1).bytes(b"vm"); + })?; + Ok(body[0]) + } +} + +#[test] +fn serves_its_directory_as_the_vms_users_files() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let mut c = Client::new(dir.path())?; + assert!(c.mkdir(0, b"npm", 0o755).is_ok()); + assert_eq!(c.walk(0, 1, &[b"npm"]), Ok(1)); + // Setuid and setgid bits are left out. + assert!(c.lcreate(1, b"a.tgz", 0o6755).is_ok()); + assert!(c.write(1, 0, b"hello").is_ok()); + assert_eq!(c.read(1, 0, 100), Ok(b"hello".to_vec())); + assert_eq!(c.read(1, 3, 100), Ok(b"lo".to_vec())); + let (mode, uid, gid, size) = c.getattr(1).map_err(io::Error::from_raw_os_error)?; + assert_eq!((mode & 0o7777, uid, gid, size), (0o755, 1000, 1000, 5)); + assert_eq!(mode & libc::S_IFMT, libc::S_IFREG); + assert!(c.clunk(1).is_ok()); + // On the host: the host's user's file, without the bits. + let host = dir.path().join("npm/a.tgz"); + assert_eq!(std::fs::read(&host)?, b"hello"); + assert_eq!( + std::fs::metadata(&host)?.permissions().mode() & 0o7777, + 0o755 + ); + // Opened again, truncated, and read from the start. + assert_eq!(c.walk(0, 2, &[b"npm", b"a.tgz"]), Ok(2)); + assert!(c.lopen(2, RDWR).is_ok()); + assert!(c.setattr(2, attr::SIZE | attr::MODE, 0o4600, 2).is_ok()); + assert_eq!(c.read(2, 0, 100), Ok(b"he".to_vec())); + assert_eq!( + std::fs::metadata(&host)?.permissions().mode() & 0o7777, + 0o600 + ); + // Files open once; a directory reads only through readdir. + assert_eq!(c.lopen(2, RDONLY), Err(libc::EBADF)); + assert_eq!(c.walk(0, 3, &[b"npm"]), Ok(1)); + assert!(c.lopen(3, RDONLY | DIRECTORY).is_ok()); + assert_eq!(c.read(3, 0, 10), Err(libc::EISDIR)); + Ok(()) +} + +#[test] +fn names_never_lead_out_of_the_directory() -> anyhow::Result<()> { + let top = tempfile::tempdir()?; + let dir = top.path().join("caches"); + std::fs::create_dir(&dir)?; + std::fs::write(top.path().join("secret"), b"the runner's token")?; + // A link the host's user left, and one the VM makes: both point out. + std::os::unix::fs::symlink(top.path(), dir.join("up"))?; + let mut c = Client::new(&dir)?; + assert!( + c.call(kind::TSYMLINK, |w| { + w.u32(0).bytes(b"etc").bytes(b"/etc").u32(0); + }) + .is_ok() + ); + for bad in [&b".."[..], b".", b"up/secret", b"", b"a\0b"] { + assert_eq!(c.walk(0, 1, &[bad]), Err(libc::EINVAL), "{bad:?}"); + assert_eq!(c.lcreate(0, bad, 0o644), Err(libc::EINVAL), "{bad:?}"); + assert_eq!(c.mkdir(0, bad, 0o755), Err(libc::EINVAL), "{bad:?}"); + } + // A symlink is a file of its own: never followed, opened or walked + // through. The VM resolves it, against its own files. + assert_eq!(c.walk(0, 1, &[b"up"]), Ok(1)); + assert_eq!(c.lopen(1, RDONLY), Err(libc::ELOOP)); + let target = c.call(kind::TREADLINK, |w| { + w.u32(1); + }); + assert_eq!( + target.map(|b| b[2..].to_vec()), + Ok(top.path().as_os_str().as_bytes().to_vec()) + ); + assert_eq!(c.walk(0, 2, &[b"up", b"secret"]), Ok(1)); + assert_eq!(c.lopen(2, RDONLY), Err(libc::EBADF)); + assert_eq!(c.walk(0, 2, &[b"etc", b"passwd"]), Ok(1)); + // Neither links to it nor devices. + assert_eq!( + c.call(kind::TLINK, |w| { + w.u32(0).u32(1).bytes(b"again"); + }), + Err(libc::EPERM) + ); + assert_eq!( + c.call(kind::TMKNOD, |w| { + w.u32(0).bytes(b"null").u32(0o20666).u32(1).u32(3).u32(0); + }), + Err(libc::EPERM) + ); + assert_eq!( + c.call(kind::TRENAMEAT, |w| { + w.u32(0).bytes(b"etc").u32(0).bytes(b"../etc"); + }), + Err(libc::EINVAL) + ); + assert_eq!( + std::fs::read(top.path().join("secret"))?, + b"the runner's token" + ); + Ok(()) +} + +#[test] +fn lists_directories_a_page_at_a_time() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let mut want = std::collections::BTreeSet::new(); + for i in 0..60 { + let name = format!("package-{i:03}-{}", "x".repeat(40)); + std::fs::write(dir.path().join(&name), b"")?; + want.insert(name.into_bytes()); + } + want.insert(b".".to_vec()); + want.insert(b"..".to_vec()); + let mut c = Client::new(dir.path())?; + assert_eq!(c.walk(0, 1, &[]), Ok(0)); + assert!(c.lopen(1, RDONLY | DIRECTORY).is_ok()); + let mut got = std::collections::BTreeSet::new(); + let mut offset = 0; + let mut pages = 0; + loop { + let page = c + .readdir(1, offset, 512) + .map_err(io::Error::from_raw_os_error)?; + let Some((_, next)) = page.last() else { break }; + offset = *next; + pages += 1; + got.extend(page.into_iter().map(|(n, _)| n)); + } + assert!(pages > 3, "{pages} pages"); + assert_eq!(got, want); + // Reading from the start again sees what changed. + std::fs::write(dir.path().join("new"), b"")?; + let first = c + .readdir(1, 0, 64 * 1024) + .map_err(io::Error::from_raw_os_error)?; + assert_eq!(first.len(), want.len() + 1); + Ok(()) +} + +#[test] +fn renames_and_removes_what_the_vm_asks() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let mut c = Client::new(dir.path())?; + assert!(c.mkdir(0, b"cargo", 0o755).is_ok()); + assert_eq!(c.walk(0, 1, &[b"cargo"]), Ok(1)); + assert!(c.lcreate(1, b"index.tmp", 0o644).is_ok()); + assert!(c.write(1, 0, b"v2").is_ok()); + assert_eq!(c.walk(0, 2, &[b"cargo"]), Ok(1)); + let renamed = c.call(kind::TRENAMEAT, |w| { + w.u32(2).bytes(b"index.tmp").u32(2).bytes(b"index"); + }); + assert!(renamed.is_ok()); + // The fid follows its file. + assert_eq!(c.read(1, 0, 10), Ok(b"v2".to_vec())); + assert_eq!(std::fs::read(dir.path().join("cargo/index"))?, b"v2"); + // A hard link, then both names go, then the directory. + let linked = c.call(kind::TLINK, |w| { + w.u32(2).u32(1).bytes(b"index.bak"); + }); + assert!(linked.is_ok()); + for name in [&b"index"[..], b"index.bak"] { + let removed = c.call(kind::TUNLINKAT, |w| { + w.u32(2).bytes(name).u32(0); + }); + assert!(removed.is_ok()); + } + let removed = c.call(kind::TUNLINKAT, |w| { + w.u32(0).bytes(b"cargo").u32(REMOVEDIR); + }); + assert!(removed.is_ok()); + assert!(!dir.path().join("cargo").exists()); + // What the VM's statfs gets. + let st = c.call(kind::TSTATFS, |w| { + w.u32(0); + }); + assert_eq!( + st.map(|b| b[..4].to_vec()), + Ok(V9FS_MAGIC.to_le_bytes().to_vec()) + ); + Ok(()) +} + +/// Two VMs' cargo runs wait for each other, as on one machine. +#[test] +fn locks_hold_between_vms() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + std::fs::write(dir.path().join(".package-cache"), b"")?; + let mut a = Client::new(dir.path())?; + let mut b = Client::new(dir.path())?; + for c in [&mut a, &mut b] { + assert_eq!(c.walk(0, 1, &[b".package-cache"]), Ok(1)); + assert!(c.lopen(1, RDWR).is_ok()); + } + assert_eq!(a.lock(1, lock::WRLCK), Ok(lock::SUCCESS)); + assert_eq!(b.lock(1, lock::WRLCK), Ok(lock::BLOCKED)); + assert_eq!(b.lock(1, lock::RDLCK), Ok(lock::BLOCKED)); + let held = b.call(kind::TGETLOCK, |w| { + w.u32(1).u8(lock::WRLCK).u64(0).u64(0).u32(7).bytes(b"vm-b"); + }); + assert_eq!(held.map(|body| body[0]), Ok(lock::WRLCK)); + assert_eq!(a.lock(1, lock::UNLCK), Ok(lock::SUCCESS)); + assert_eq!(b.lock(1, lock::WRLCK), Ok(lock::SUCCESS)); + // A lock goes with the file that held it. + assert!(b.clunk(1).is_ok()); + assert_eq!(a.lock(1, lock::WRLCK), Ok(lock::SUCCESS)); + Ok(()) +} + +#[test] +fn has_no_extended_attributes_or_old_requests() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let mut c = Client::new(dir.path())?; + let listed = c.call(kind::TXATTRWALK, |w| { + w.u32(0).u32(5).bytes(b""); + }); + assert_eq!(listed, Ok(0u64.to_le_bytes().to_vec())); + assert_eq!(c.read(5, 0, 100), Ok(Vec::new())); + let missing = c.call(kind::TXATTRWALK, |w| { + w.u32(0).u32(6).bytes(b"security.capability"); + }); + assert_eq!(missing, Err(libc::ENODATA)); + // 9P2000.u's Topen, and a version this server doesn't speak. + assert_eq!( + c.call(112, |w| { + w.u32(0).u8(0); + }), + Err(libc::EOPNOTSUPP) + ); + let v = c.call(kind::TVERSION, |w| { + w.u32(8192).bytes(b"9P2000.u"); + }); + assert_eq!(v.map(|b| b[4..].to_vec()), Ok(b"\x07\x00unknown".to_vec())); + // A message cut short. + assert_eq!( + c.session.answer(&[kind::TWALK, 1, 0, 9]), + wire::error(1, libc::EPROTO) + ); + Ok(()) +} + +/// The server on its socket, as Firecracker connects the VM to it. +#[test] +fn serves_on_a_unix_socket() -> anyhow::Result<()> { + let dir = tempfile::tempdir()?; + let shared = dir.path().join("caches"); + std::fs::create_dir(&shared)?; + let socket = dir.path().join("v.sock_1026"); + let (s, d) = (socket.clone(), shared.clone()); + std::thread::spawn(move || serve(&d, &s)); + let mut conn = loop { + match UnixStream::connect(&socket) { + Ok(conn) => break conn, + Err(_) => std::thread::sleep(std::time::Duration::from_millis(20)), + } + }; + let mut w = Writer::new(kind::TVERSION, wire::NOTAG); + w.u32(MAX_MSIZE * 4).bytes(b"9P2000.L"); + conn.write_all(&w.finish())?; + let mut reply = vec![0u8; 4 + 1 + 2 + 4 + 2 + 8]; + conn.read_exact(&mut reply)?; + assert_eq!(reply[4], kind::TVERSION + 1); + assert_eq!(&reply[7..11], &MAX_MSIZE.to_le_bytes()); + assert_eq!(&reply[13..], b"9P2000.L"); + // A message larger than any the server takes ends the connection. + conn.write_all(&(MAX_MSIZE * 2).to_le_bytes())?; + let mut rest = Vec::new(); + assert_eq!(conn.read_to_end(&mut rest)?, 0); + Ok(()) +} diff --git a/crates/fctl-agent/src/share/wire.rs b/crates/fctl-agent/src/share/wire.rs new file mode 100644 index 00000000..32fd6e17 --- /dev/null +++ b/crates/fctl-agent/src/share/wire.rs @@ -0,0 +1,251 @@ +//! 9P2000.L's messages, as the Linux kernel's 9p client sends them and a +//! server answers: a size (4 bytes), a type (1), a tag (2) and the fields, +//! all little-endian; strings after their length (2 bytes). + +use std::io; + +/// The message types this server reads (`T…`) and writes (`R…`), as the +/// Linux kernel numbers them (`include/net/9p/9p.h`). +pub mod kind { + pub const RLERROR: u8 = 7; + pub const TSTATFS: u8 = 8; + pub const TLOPEN: u8 = 12; + pub const TLCREATE: u8 = 14; + pub const TSYMLINK: u8 = 16; + pub const TMKNOD: u8 = 18; + pub const TRENAME: u8 = 20; + pub const TREADLINK: u8 = 22; + pub const TGETATTR: u8 = 24; + pub const TSETATTR: u8 = 26; + pub const TXATTRWALK: u8 = 30; + pub const TXATTRCREATE: u8 = 32; + pub const TREADDIR: u8 = 40; + pub const TFSYNC: u8 = 50; + pub const TLOCK: u8 = 52; + pub const TGETLOCK: u8 = 54; + pub const TLINK: u8 = 70; + pub const TMKDIR: u8 = 72; + pub const TRENAMEAT: u8 = 74; + pub const TUNLINKAT: u8 = 76; + pub const TVERSION: u8 = 100; + pub const TAUTH: u8 = 102; + pub const TATTACH: u8 = 104; + pub const TFLUSH: u8 = 108; + pub const TWALK: u8 = 110; + pub const TREAD: u8 = 116; + pub const TWRITE: u8 = 118; + pub const TCLUNK: u8 = 120; + pub const TREMOVE: u8 = 122; +} + +/// The tag of `Tversion`, which has none. +pub const NOTAG: u16 = 0xffff; + +/// A fid that names no file (`Tattach`'s `afid` without authentication). +pub const NOFID: u32 = u32::MAX; + +/// What a message's header and a reply's take: size, type and tag. +pub const HEADER: usize = 7; + +/// What `Rread` takes before its data: the header and the count. +pub const READ_OVERHEAD: u32 = HEADER as u32 + 4; + +/// A file's identity: its type (directory, symlink, file), a version and +/// a number unique on the server. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Qid { + pub kind: u8, + pub version: u32, + pub path: u64, +} + +pub const QTDIR: u8 = 0x80; +pub const QTSYMLINK: u8 = 0x02; +pub const QTFILE: u8 = 0x00; + +/// The fields of a message, read in order. +pub struct Reader<'a> { + buf: &'a [u8], +} + +fn short() -> io::Error { + io::Error::from_raw_os_error(libc::EPROTO) +} + +impl<'a> Reader<'a> { + pub fn new(buf: &'a [u8]) -> Self { + Self { buf } + } + + fn take(&mut self, n: usize) -> io::Result<&'a [u8]> { + if self.buf.len() < n { + return Err(short()); + } + let (head, rest) = self.buf.split_at(n); + self.buf = rest; + Ok(head) + } + + pub fn u8(&mut self) -> io::Result { + Ok(self.take(1)?[0]) + } + + pub fn u16(&mut self) -> io::Result { + let b = self.take(2)?; + Ok(u16::from_le_bytes([b[0], b[1]])) + } + + pub fn u32(&mut self) -> io::Result { + let b = self.take(4)?; + Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + } + + pub fn u64(&mut self) -> io::Result { + let b = self.take(8)?; + let mut a = [0u8; 8]; + a.copy_from_slice(b); + Ok(u64::from_le_bytes(a)) + } + + /// A string, as the bytes it is: file names are bytes on Linux. + pub fn bytes(&mut self) -> io::Result<&'a [u8]> { + let n = usize::from(self.u16()?); + self.take(n) + } + + /// What follows, as `Twrite`'s data: its count, then that many bytes. + pub fn data(&mut self) -> io::Result<&'a [u8]> { + let n = usize::try_from(self.u32()?).map_err(|_| short())?; + self.take(n) + } +} + +/// A reply: [`Writer::new`] leaves room for its size, which +/// [`Writer::finish`] fills in. +pub struct Writer { + buf: Vec, +} + +impl Writer { + pub fn new(kind: u8, tag: u16) -> Self { + let mut buf = Vec::with_capacity(64); + buf.extend_from_slice(&[0, 0, 0, 0, kind]); + buf.extend_from_slice(&tag.to_le_bytes()); + Self { buf } + } + + pub fn u8(&mut self, v: u8) -> &mut Self { + self.buf.push(v); + self + } + + pub fn u16(&mut self, v: u16) -> &mut Self { + self.buf.extend_from_slice(&v.to_le_bytes()); + self + } + + pub fn u32(&mut self, v: u32) -> &mut Self { + self.buf.extend_from_slice(&v.to_le_bytes()); + self + } + + pub fn u64(&mut self, v: u64) -> &mut Self { + self.buf.extend_from_slice(&v.to_le_bytes()); + self + } + + /// A string; one longer than a string can be is cut short. + pub fn bytes(&mut self, v: &[u8]) -> &mut Self { + let v = &v[..v.len().min(usize::from(u16::MAX))]; + self.u16(u16::try_from(v.len()).unwrap_or(u16::MAX)); + self.buf.extend_from_slice(v); + self + } + + pub fn qid(&mut self, q: Qid) -> &mut Self { + self.u8(q.kind).u32(q.version).u64(q.path) + } + + /// Data after its count. + pub fn data(&mut self, v: &[u8]) -> &mut Self { + self.u32(u32::try_from(v.len()).unwrap_or(u32::MAX)); + self.buf.extend_from_slice(v); + self + } + + /// Raw bytes, already in the wire's format (`Rreaddir`'s entries). + pub fn raw(&mut self, v: &[u8]) -> &mut Self { + self.buf.extend_from_slice(v); + self + } + + pub fn finish(mut self) -> Vec { + let size = u32::try_from(self.buf.len()).unwrap_or(u32::MAX); + self.buf[..4].copy_from_slice(&size.to_le_bytes()); + self.buf + } +} + +/// `Rlerror`: the request failed with `errno`. +pub fn error(tag: u16, errno: i32) -> Vec { + let mut w = Writer::new(kind::RLERROR, tag); + w.u32(u32::try_from(errno).unwrap_or(libc::EIO as u32)); + w.finish() +} + +/// A directory entry as `Rreaddir` carries it: its qid, the offset of the +/// entry after it, its type (`DT_…`) and its name. +pub fn dirent(out: &mut Vec, qid: Qid, offset: u64, kind: u8, name: &[u8]) { + out.push(qid.kind); + out.extend_from_slice(&qid.version.to_le_bytes()); + out.extend_from_slice(&qid.path.to_le_bytes()); + out.extend_from_slice(&offset.to_le_bytes()); + out.push(kind); + let name = &name[..name.len().min(usize::from(u16::MAX))]; + out.extend_from_slice(&u16::try_from(name.len()).unwrap_or(u16::MAX).to_le_bytes()); + out.extend_from_slice(name); +} + +/// What a directory entry takes in `Rreaddir`. +pub fn dirent_len(name: &[u8]) -> usize { + 13 + 8 + 1 + 2 + name.len() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn replies_carry_their_size_and_strings_their_length() -> io::Result<()> { + let mut w = Writer::new(101, NOTAG); + w.u32(8192).bytes(b"9P2000.L"); + let reply = w.finish(); + assert_eq!( + &reply[..4], + &u32::try_from(reply.len()).unwrap_or(0).to_le_bytes() + ); + assert_eq!(reply[4], 101); + let mut r = Reader::new(&reply[5..]); + assert_eq!(r.u16()?, NOTAG); + assert_eq!(r.u32()?, 8192); + assert_eq!(r.bytes()?, b"9P2000.L"); + // A message cut short is refused, rather than read past its end. + assert!(r.u8().is_err()); + assert!(Reader::new(&[5, 0, b'a']).bytes().is_err()); + Ok(()) + } + + #[test] + fn directory_entries_are_as_long_as_they_say() { + let mut out = Vec::new(); + let qid = Qid { + kind: QTDIR, + version: 0, + path: 42, + }; + dirent(&mut out, qid, 7, 4, b"npm"); + assert_eq!(out.len(), dirent_len(b"npm")); + assert_eq!(out[0], QTDIR); + assert_eq!(&out[out.len() - 3..], b"npm"); + } +} diff --git a/crates/fctl-agent/src/vm/mod.rs b/crates/fctl-agent/src/vm/mod.rs index aef78fda..007266ed 100644 --- a/crates/fctl-agent/src/vm/mod.rs +++ b/crates/fctl-agent/src/vm/mod.rs @@ -13,18 +13,23 @@ //! vsock, as `docker exec` would, and bridges the VM's network to the //! host's `passt` ([`net`]). PID 1 itself only reaps the programs whose //! parents exit before them. +//! - **The project's package caches.** The host serves them over the +//! vsock (`fctl-agent share`, src/share), and asks `fctl-agent vm-mount` +//! to mount them at boot and after a snapshot's restore ([`mount`]). //! - **Unpacking an image.** The init mounts `/dev/vda`, an empty //! filesystem, and unpacks the layers the host sends onto it, as root, so //! that their owners and modes stay theirs ([`unpack`]), then powers off. //! An image's files never touch the host's filesystem. mod boot; +mod mount; mod net; mod netlink; mod serve; mod unpack; pub use boot::init; +pub use mount::mount; pub use serve::serve; /// What the init reports to the host's `hello`. diff --git a/crates/fctl-agent/src/vm/mount.rs b/crates/fctl-agent/src/vm/mount.rs new file mode 100644 index 00000000..36ed06e9 --- /dev/null +++ b/crates/fctl-agent/src/vm/mount.rs @@ -0,0 +1,85 @@ +//! `fctl-agent vm-mount`: mounts what the host shares on a vsock port (the +//! project's package caches, which `fctl-agent share` serves there) with +//! the kernel's 9p client, over the vsock connection itself (`trans=fd`), +//! as one user's files. The host runs it as root once the VM is up, and +//! again after a snapshot's restore, whose connections are gone. + +use crate::user::accounts as users; +use anyhow::{Context, Result}; +use nix::errno::Errno; +use nix::mount::{MntFlags, MsFlags, umount2}; +use std::os::fd::AsRawFd; +use std::path::Path; + +/// The largest message the VM's 9p client sends or asks for: a read or a +/// write of up to this much in one trip over the vsock. +const MSIZE: u32 = 512 * 1024; + +/// Mounts the host's share on `port` at `dir`, whose files are `user`'s +/// there (a name or a uid; unset, root's), in place of a mount an earlier +/// connection left. +pub fn mount(port: u32, dir: &Path, user: Option<&str>) -> Result<()> { + let user = users::find(user).map_err(anyhow::Error::msg)?; + if mounted(dir) { + umount2(dir, MntFlags::MNT_DETACH) + .with_context(|| format!("unmounting what {} had", dir.display()))?; + } + std::fs::create_dir_all(dir).with_context(|| format!("making {}", dir.display()))?; + let conn = vsock::VsockStream::connect_with_cid_port(vsock::VMADDR_CID_HOST, port) + .with_context(|| format!("connecting to the host's vsock port {port}"))?; + let fd = conn.as_raw_fd(); + // The kernel holds the connection once mounted; this process's copy of + // it goes as it exits. + let options = options(fd, user.uid, user.gid); + match nix::mount::mount( + Some("fctl-share"), + dir, + Some("9p"), + MsFlags::MS_NOSUID | MsFlags::MS_NODEV, + Some(options.as_str()), + ) { + Ok(()) => Ok(()), + Err(Errno::ENODEV) => anyhow::bail!( + "the VM's kernel has no 9p filesystem (CONFIG_9P_FS and CONFIG_NET_9P_FD), so it can't mount what the host shares at {}", + dir.display() + ), + Err(e) => { + Err(e).with_context(|| format!("mounting what the host shares at {}", dir.display())) + } + } +} + +/// 9p's options: over the connection `fd`, one attach for every user of the +/// VM (`access=any`), whose files the server says are `uid:gid`'s (its +/// `aname`), and the page cache only for files mapped into memory. +fn options(fd: i32, uid: u32, gid: u32) -> String { + format!( + "trans=fd,rfdno={fd},wfdno={fd},version=9p2000.L,msize={MSIZE},access=any,cache=mmap,aname={uid}:{gid}" + ) +} + +/// Whether something is mounted at `dir`. +fn mounted(dir: &Path) -> bool { + let Ok(info) = std::fs::read_to_string("/proc/self/mountinfo") else { + return false; + }; + let want = dir.to_string_lossy(); + info.lines() + .any(|line| line.split(' ').nth(4) == Some(want.as_ref())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mounts_over_the_connection_as_the_users_files() { + assert_eq!( + options(5, 1000, 1001), + "trans=fd,rfdno=5,wfdno=5,version=9p2000.L,msize=524288,access=any,cache=mmap,aname=1000:1001" + ); + // The root of this machine is mounted; a directory made now isn't. + assert!(mounted(Path::new("/"))); + assert!(!mounted(Path::new("/proc/self/fdinfo"))); + } +} diff --git a/crates/fctl-host/src/caches.rs b/crates/fctl-host/src/caches.rs index 1057ba3d..09aa202c 100644 --- a/crates/fctl-host/src/caches.rs +++ b/crates/fctl-host/src/caches.rs @@ -7,10 +7,11 @@ //! `fctl-cache-`, on the daemon's disk like its sandboxes. With //! Apple's `container`, they are a directory in the data directory, //! `caches/`, which sandboxes mount: a named volume there is an -//! ext4 image, which two running VMs must not share. The process driver's -//! agents use that directory directly. Sandboxes see the caches at -//! [`MOUNT`], and fctl-agent points the package managers there. Lima's VMs -//! get none. +//! ext4 image, which two running VMs must not share. Firecracker's VMs mount +//! that directory too, over 9P from `fctl-agent share`, which the host runs +//! beside each VM. The process driver's agents use it directly. Sandboxes +//! see the caches at [`MOUNT`], and fctl-agent points the package managers +//! there. Lima's VMs get none. //! //! `/caches.json` records when each project's caches were last //! used and measured, and which sandboxes were made with them: after a diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 8ba27b90..0fa329ca 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -18,6 +18,11 @@ //! them running ([`vm`]). //! - **The host runs programs** in the VM through its vsock, as `docker //! exec` would ([`vsock`]). +//! - **Package caches** are a directory of the host's for each project, as +//! with Apple's `container`, which `fctl-agent share` serves to each VM of +//! the project over its vsock, beside `passt`, and the VM's kernel mounts +//! with its 9p client (`fctl-agent vm-mount`): several sandboxes of a +//! project share them at once. pub mod assets; pub mod images; @@ -30,6 +35,7 @@ use super::{ SandboxInfo, SandboxSpec, attach_as_root, attach_script, ran_as_root, serve_as_root, serve_script, }; +use crate::caches::{self, Spot}; use crate::config::{FirecrackerConfig, HostConfig}; use crate::driver::ImageInfo; use anyhow::{Context, Result, bail}; @@ -745,6 +751,15 @@ impl FirecrackerDriver { let passt = self .passt() .context("passt is not installed: it gives the VMs their network")?; + let share = match &spec.cache { + Some(Spot::Dir(dir)) => Some(vm::Share { + agent: crate::agentbin::linux_agent(&self.host) + .await + .context("getting fctl-agent to serve the package caches")?, + dir: dir.clone(), + }), + _ => None, + }; let boot = Spec { kernel, initrd, @@ -767,14 +782,54 @@ impl FirecrackerDriver { cpus: spec.cpus, memory_mb: spec.memory_mb, network: true, + share: share.clone(), }; vm.start(&boot, &firecracker, Some(&passt)).await?; vm.wait_ready().await?; record.agent = Some(agent); self.save_record(&spec.name, &record)?; + if share.is_some() + && let Err(e) = self.mount_caches(&vm, &spec.name).await + { + log(format!( + "The package caches couldn't be mounted in {} ({e:#}), so this session's package managers keep their own downloads", + spec.name + )); + } Ok(sb) } + /// Mounts the project's package caches, which `fctl-agent share` serves + /// beside the VM, at [`caches::MOUNT`], as the image's user's files. + async fn mount_caches(&self, vm: &Vm, name: &str) -> Result<()> { + let image = self.exec_for(name, Vec::new()); + let mut argv: Vec = vec![ + AGENT_PATH.into(), + "vm-mount".into(), + "--port".into(), + fctl_proto::vm::SHARE_PORT.to_string(), + "--dir".into(), + caches::MOUNT.into(), + ]; + if let Some(user) = &image.user { + argv.extend(["--user".into(), user.clone()]); + } + let exec = Exec { + argv, + user: Some("root".into()), + cwd: Some("/".into()), + ..image + }; + let out = tokio::time::timeout(super::COMMAND_TIMEOUT, vsock::run(&vm.vsock(), exec, None)) + .await + .map_err(|_| anyhow::anyhow!("fctl-agent vm-mount didn't finish within a minute"))??; + if out.code != 0 { + let said = String::from_utf8_lossy(&out.stderr); + bail!("{}", said.trim().trim_start_matches("Error: ")); + } + Ok(()) + } + /// A new sandbox's directory and record, which come before its disk /// ([`make_disk`](Self::make_disk)), so that a disk is never without a /// record: a disk without one is a sandbox whose record something else @@ -1302,4 +1357,109 @@ mod tests { assert!(!d.list().await?.iter().any(|s| s.name == name)); result } + + /// The host and the VMs' configuration for the tests that boot VMs, as + /// [`boots_a_sandbox`] says, with the host's files in `data`. + fn vm_host(data: &Path) -> Result { + let agent = std::env::var("FCTL_TEST_FIRECRACKER_AGENT") + .context("FCTL_TEST_FIRECRACKER_AGENT isn't set")?; + let mut cfg = HostConfig { + data_dir: Some(data.to_owned()), + agent_bin: Some(agent.into()), + ..HostConfig::default() + }; + cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); + cfg.firecracker.disk_gb = 4; + Ok(cfg) + } + + /// Two sandboxes of a project at once share its package caches: what one + /// writes the other reads, as the image's user's files, and their locks + /// hold between them. Needs a kernel with 9p (the one hosts pull has it). + #[tokio::test] + #[ignore = "needs KVM, passt and a static fctl-agent"] + async fn sandboxes_of_a_project_share_its_package_caches() -> Result<()> { + use super::super::Driver; + let temp = tempfile::tempdir()?; + let data = std::env::var("FCTL_TEST_FIRECRACKER_DATA") + .map(PathBuf::from) + .unwrap_or_else(|_| temp.path().to_owned()); + let cfg = vm_host(&data)?; + let d = Driver::select("firecracker", &cfg).await?; + let log = |line: String| eprintln!("{line}"); + let project = format!("prj_test{}", hex::encode(fctl_domain::random_bytes::<4>())); + let spot = d.cache_spot(&project, &data).context("no caches")?; + let Spot::Dir(dir) = &spot else { + bail!("the firecracker driver keeps caches in a directory, not {spot}"); + }; + std::fs::create_dir_all(dir)?; + let image = std::env::var("FCTL_TEST_FIRECRACKER_IMAGE") + .unwrap_or_else(|_| "docker.io/library/debian:trixie-slim".into()); + let names: Vec = (0..2) + .map(|_| { + format!( + "fctl-test-{}", + hex::encode(fctl_domain::random_bytes::<4>()) + ) + }) + .collect(); + let spec = |name: &String| SandboxSpec { + name: name.clone(), + image: image.clone(), + fallback_image: None, + cpus: 1, + memory_mb: 512, + cache: Some(spot.clone()), + }; + let mut sandboxes = Vec::new(); + let result = async { + for name in &names { + sandboxes.push(d.ensure(&spec(name), &log).await?); + } + let (a, b) = (&sandboxes[0], &sandboxes[1]); + let mounted = d.exec(a, "grep ' /var/cache/fctl ' /proc/mounts").await?; + assert!(mounted.contains(" 9p "), "{mounted}"); + // One writes, the other reads, and the host has it. + d.exec( + a, + "mkdir -p /var/cache/fctl/npm && echo from-a > /var/cache/fctl/npm/index", + ) + .await?; + assert_eq!( + d.exec(b, "cat /var/cache/fctl/npm/index").await?, + "from-a\n" + ); + assert_eq!(std::fs::read_to_string(dir.join("npm/index"))?, "from-a\n"); + // The image's user's files (root's, in Debian's image). + let owner = d + .exec(b, "stat -c '%u:%g %a' /var/cache/fctl/npm/index") + .await?; + assert_eq!(owner.trim(), "0:0 644"); + // A lock one holds keeps the other waiting, as cargo's do. + d.spawn(a, "exec flock /var/cache/fctl/.package-cache sleep 30") + .await?; + tokio::time::sleep(Duration::from_secs(2)).await; + let busy = d + .exec( + b, + "flock -n /var/cache/fctl/.package-cache true && echo free || echo held", + ) + .await?; + assert_eq!(busy.trim(), "held"); + // A sandbox started again mounts them again. + d.stop(b).await?; + let b = d.ensure(&spec(&names[1]), &log).await?; + assert_eq!( + d.exec(&b, "cat /var/cache/fctl/npm/index").await?, + "from-a\n" + ); + Ok::<_, anyhow::Error>(()) + } + .await; + for name in &names { + d.remove(&d.handle(name)).await?; + } + let _ = std::fs::remove_dir_all(dir); + result + } } diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 196c96f0..8f9228e4 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -1,10 +1,11 @@ -//! A microVM's processes on the host: Firecracker, and `passt` for its -//! network. Both run in process groups of their own, so that restarting the -//! host (whose service stops only its main process) leaves them running. +//! A microVM's processes on the host: Firecracker, `passt` for its network, +//! and `fctl-agent share` for the project's package caches. They run in +//! process groups of their own, so that restarting the host (whose service +//! stops only its main process) leaves them running. use super::vsock; use anyhow::{Context, Result, anyhow, bail}; -use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX}; +use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX, SHARE_PORT}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::net::Ipv4Addr; @@ -54,6 +55,17 @@ pub struct Spec { pub memory_mb: u32, /// Whether the VM gets a network (`passt`). pub network: bool, + /// A directory of the host's that the VM mounts (`fctl-agent share`). + pub share: Option, +} + +/// A directory the host serves to a VM over its vsock ([`SHARE_PORT`]): the +/// project's package caches. +#[derive(Clone, Debug)] +pub struct Share { + /// The static fctl-agent, which serves it (`fctl-agent share`). + pub agent: PathBuf, + pub dir: PathBuf, } /// A microVM's files: `dir` keeps its configuration, its console's log and @@ -112,6 +124,12 @@ impl Vm { self.run.join(format!("v.sock_{NET_PORT}")) } + /// Where `fctl-agent share` serves the VM's [`Share`]: what Firecracker + /// connects to when the VM connects to the host's [`SHARE_PORT`]. + pub fn share(&self) -> PathBuf { + self.run.join(format!("v.sock_{SHARE_PORT}")) + } + pub fn console(&self) -> PathBuf { self.dir.join("console.log") } @@ -175,6 +193,9 @@ impl Vm { let passt = passt.context("the VM needs passt for its network")?; self.start_passt(passt).await?; } + if let Some(share) = &spec.share { + self.start_share(share).await?; + } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; let console = std::fs::File::create(self.console())?; @@ -216,6 +237,32 @@ impl Vm { Ok(()) } + /// `fctl-agent share`, which serves `share`'s directory where the VM's + /// connections to [`SHARE_PORT`] come. + async fn start_share(&self, share: &Share) -> Result<()> { + let log = std::fs::File::create(self.dir.join("share.log"))?; + let mut cmd = std::process::Command::new(&share.agent); + cmd.arg("share") + .arg("--dir") + .arg(&share.dir) + .arg("--socket") + .arg(self.share()) + .stdin(Stdio::null()) + .stdout(log.try_clone()?) + .stderr(log); + spawn_detached(&mut cmd, &self.pid_file("share")) + .with_context(|| format!("starting {} share", share.agent.display()))?; + let until = Instant::now() + Duration::from_secs(10); + while !self.share().exists() { + if Instant::now() > until || self.pid("share").is_none() { + let said = std::fs::read_to_string(self.dir.join("share.log")).unwrap_or_default(); + bail!("fctl-agent share did not start: {}", said.trim()); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + Ok(()) + } + /// Firecracker's configuration for `spec`. pub fn config(&self, spec: &Spec) -> Value { let drives: Vec = spec @@ -344,7 +391,7 @@ impl Vm { /// Kills the VM's processes. pub async fn kill(&self) { - for what in ["firecracker", "passt"] { + for what in ["firecracker", "passt", "share"] { if let Some(pid) = self.pid(what) { let _ = crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await; let until = Instant::now() + Duration::from_secs(5); @@ -546,6 +593,7 @@ pub fn unpack_spec(kernel: PathBuf, initrd: PathBuf, name: &str, rootfs: &Path) cpus: 2, memory_mb: 1024, network: false, + share: None, } } @@ -581,6 +629,7 @@ mod tests { cpus: 64, memory_mb: 4096, network: true, + share: None, }; let c = vm.config(&spec); assert_eq!( @@ -834,8 +883,8 @@ mod tests { Ok(()) } - /// Stand-ins: a `passt` that makes its socket's path and waits, and a - /// Firecracker that waits. + /// Stand-ins: a `passt` that makes its socket's path and waits (which + /// stands in for `fctl-agent share` too), and a Firecracker that waits. #[tokio::test] async fn starting_again_stops_what_the_last_boot_left() -> Result<()> { use crate::driver::fake::write_script; @@ -852,11 +901,17 @@ mod tests { let spec = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); let spec = Spec { network: true, + share: Some(Share { + agent: passt.clone(), + dir: dir.path().to_owned(), + }), ..spec }; vm.start(&spec, &firecracker, Some(&passt)).await?; let first_passt = vm.pid("passt"); - assert!(first_passt.is_some() && vm.running()); + let first_share = vm.pid("share"); + assert!(first_passt.is_some() && first_share.is_some() && vm.running()); + assert!(vm.share().exists()); // Firecracker ends by itself (its VM powered off), and passt stays. if let Some(pid) = vm.pid("firecracker") { crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await?; @@ -876,11 +931,15 @@ mod tests { first_passt.is_some_and(|p| !alive(p)), "the first passt still runs" ); - assert!(vm.pid("passt").is_some() && vm.running()); + assert!( + first_share.is_some_and(|p| !alive(p)), + "the first share still runs" + ); + assert!(vm.pid("passt").is_some() && vm.pid("share").is_some() && vm.running()); // A start that fails leaves nothing running. let missing = dir.path().join("no-firecracker"); assert!(vm.start(&spec, &missing, Some(&passt)).await.is_err()); - assert!(vm.pid("passt").is_none() && !vm.running()); + assert!(vm.pid("passt").is_none() && vm.pid("share").is_none() && !vm.running()); Ok(()) } } diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 35369d89..a39c83c3 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -575,10 +575,10 @@ impl Driver { /// Where `project`'s package caches are with this driver: a Docker /// volume, or a directory in `data_dir`, which Apple's `container` - /// mounts and the process driver's agents use. `None` with Lima and - /// Firecracker, whose VMs share no files with the host, and for a - /// directory that Apple's `container` can't mount, whose path has a - /// comma. + /// mounts, Firecracker's VMs mount from `fctl-agent share` and the + /// process driver's agents use. `None` with Lima, whose VMs share no + /// files with the host, and for a directory that Apple's `container` + /// can't mount, whose path has a comma. pub fn cache_spot(&self, project: &str, data_dir: &Path) -> Option { let dir = caches::dir(data_dir, project); match self { @@ -586,8 +586,8 @@ impl Driver { Some(Spot::Volume(caches::volume(project))) } Self::Container(_) => (!dir.to_string_lossy().contains(',')).then_some(Spot::Dir(dir)), - Self::Process(_) => Some(Spot::Dir(dir)), - Self::Firecracker(_) | Self::Lima(_) => None, + Self::Process(_) | Self::Firecracker(_) => Some(Spot::Dir(dir)), + Self::Lima(_) => None, } } @@ -603,8 +603,10 @@ impl Driver { pub async fn caches(&self, data_dir: &Path) -> Result> { match self { Self::Container(d) if d.flavor_name() == "docker" => d.cache_volumes().await, - Self::Container(_) | Self::Process(_) => Ok(caches::dirs(data_dir)), - Self::Firecracker(_) | Self::Lima(_) => Ok(Vec::new()), + Self::Container(_) | Self::Process(_) | Self::Firecracker(_) => { + Ok(caches::dirs(data_dir)) + } + Self::Lima(_) => Ok(Vec::new()), } } diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 7a254cf4..aa4cc47b 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -11,7 +11,8 @@ //! //! The VM itself reaches the host's [`NET_PORT`], where the host's `passt` //! takes its network: Ethernet frames, each after its length (4 bytes, big -//! endian), as passt reads them from QEMU. +//! endian), as passt reads them from QEMU; and its [`SHARE_PORT`], where the +//! host serves the project's package caches over 9P2000.L. //! //! A host may be one version ahead of the init of a VM that was running //! when it updated, so requests only gain optional fields, and an init @@ -26,6 +27,10 @@ pub const PORT: u32 = 1024; /// The vsock port of the host's network for the VM (`passt`). pub const NET_PORT: u32 = 1025; +/// The vsock port where the host serves the project's package caches, over +/// 9P2000.L (`fctl-agent share`), which `fctl-agent vm-mount` mounts. +pub const SHARE_PORT: u32 = 1026; + /// The VM's network, as the host's `passt` gives it: the VM's address and /// prefix, the gateway, and the address that forwards DNS queries to the /// host's resolver. diff --git a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md index b2a3cede..4202ce33 100644 --- a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md +++ b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md @@ -79,8 +79,11 @@ microVM of its own. token and any Claude token kept on the host, as a container escape can with Docker. Running Firecracker through its jailer, as another user in a chroot, needs a host that runs as root, and is for later. -- Firecracker's VMs share no filesystem with the host, so they get no - package caches, as Lima's don't. +- Firecracker's VMs share no filesystem with the host. Package caches + come from a 9P server the host runs beside each VM on its vsock + (`fctl-agent share`), which the VM's kernel mounts: Firecracker has no + virtio-fs or virtio-9p, and the kernel hyperstructure/sandbox publishes + has 9p with its fd transport for it, from 6.18.59-1. - An image's first pull takes longer than Docker's (it unpacks in a VM), and each image takes all its size on disk: images share no layers. - A VM holds the memory its guest has touched, but for what its balloon diff --git a/docs/architecture.md b/docs/architecture.md index 63e378a2..377578ed 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3479,9 +3479,10 @@ in `firecracker/` in the host's data directory. the user's in `/tmp` (sockets' paths are limited to about 100 bytes). A VM's console goes to `console.log` in its directory. -The VMs share no files with the host, so they get no -[package caches](#package-caches). Firecracker runs as the host's user, -without its jailer, which needs root: a VM escape would run as that user. +The VMs share no filesystem with the host: they mount a project's +[package caches](#package-caches) from a file server beside each VM. +Firecracker runs as the host's user, without its jailer, which needs root: +a VM escape would run as that user. ### Package caches @@ -3499,11 +3500,22 @@ and the host checks. Apple's `container`, a directory in the host's data directory, `caches/`, that each sandbox bind-mounts: Apple's named volumes are ext4 images, which two running VMs must not mount at once. - Both appear at `/var/cache/fctl`. The process driver's agents use the - directory where it is, and Firecracker's and Lima's VMs get none: they - share no files with the host. The mount is made with + Firecracker's VMs mount that directory too, though Firecracker has no + shared filesystem: the host runs `fctl-agent share` beside each VM, as + it runs `passt`, a 9P2000.L server of the directory on the VM's vsock + (port 1026), and once the VM is up, `fctl-agent vm-mount` in it mounts + the connection with the kernel's 9p client (`trans=fd`), which several + VMs of a project do at once. The server takes nothing but the + directory's files: it walks one name at a time without following + symlinks, opens only files and directories, makes neither devices nor + setuid files, and holds locks as the host's (`F_OFD_SETLK`), so two + VMs' cargo runs wait for each other; the VM sees the files as its image + user's. All three appear at `/var/cache/fctl`. The process driver's + agents use the directory where it is, and Lima's VMs get none: they + share no files with the host. Docker's and Apple's mounts are made with the sandbox, so a sandbox made before its project turned caches on gets - none until the session's next one. Docker makes a new volume's root + none until the session's next one; a Firecracker VM mounts them as it + boots. Docker makes a new volume's root root's, so the host gives it to the image's user (`id -u` in the sandbox, then `chown` as root) as it creates the sandbox. - **In the sandbox.** The host passes the directory and the limit to diff --git a/docs/cli.md b/docs/cli.md index a835b666..f765cc1f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -879,8 +879,9 @@ fctl host install --driver firecracker The host downloads Firecracker and the VMs' kernel itself, and pulls images without Docker: a short-lived VM unpacks each, so its first pull -takes a little longer than Docker's. Its sandboxes get no package caches -and it builds no images; projects' own images run as with Docker. +takes a little longer than Docker's. Its sandboxes mount their project's +package caches from the host over their vsock, and it builds no images; +projects' own images run as with Docker. [Architecture](architecture.md#firecracker) has the details. Sessions start from their project's image or, without one, the host's: From c93b5a8368b2ece23ad7891ea0cf1a8ca8984d02 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:20:04 +0000 Subject: [PATCH 14/26] fix(host): link a Firecracker VM's network from the host, which Ubuntu's passt takes On Ubuntu 24.04 no Firecracker VM got a network: passt's AppArmor profile there refuses to accept the connection Firecracker makes for the VM (accept4 fails with EACCES, and nothing is logged), so the VM's frames waited in passt's backlog. CI's x86_64 runners showed it. Now the VM's init listens on its vsock port 1025, and the host, once the VM is up, connects to it and hands passt the connection with --fd, which passt reads without accepting anything. passt exits when the VM closes the connection, as it stops, rather than linger until the next start, and the host links a running VM again when its passt is gone. The test's diagnostics that found it (passt under strace, its trace and capture) are gone; on a failure it still says what passt, the VM's console and its network say. --- .github/workflows/ci.yml | 9 +- crates/fctl-agent/src/vm/net.rs | 55 +++- .../fctl-host/src/driver/firecracker/mod.rs | 114 ++----- crates/fctl-host/src/driver/firecracker/vm.rs | 290 +++++++++++++----- crates/fctl-proto/src/vm.rs | 10 +- docs/architecture.md | 16 +- 6 files changed, 305 insertions(+), 189 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3fe69c6..e181f00e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,7 +129,7 @@ jobs: run: | sudo chmod 666 /dev/kvm sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends passt e2fsprogs strace + sudo apt-get install -y --no-install-recommends passt e2fsprogs # What confines passt, which runs as the host's user. sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" rustup target add x86_64-unknown-linux-musl @@ -137,15 +137,8 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent - FCTL_TEST_FIRECRACKER_PASST_DEBUG: /tmp/passt.pcap run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - - name: What AppArmor and the kernel said - if: failure() - # journald takes the kernel's audit records, AppArmor's among them. - run: | - sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | grep -v STATUS | tail -60 - sudo dmesg | tail -30 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-agent/src/vm/net.rs b/crates/fctl-agent/src/vm/net.rs index 254e8c8a..74173f35 100644 --- a/crates/fctl-agent/src/vm/net.rs +++ b/crates/fctl-agent/src/vm/net.rs @@ -1,7 +1,8 @@ //! The VM's network: a TAP device, `eth0`, whose frames travel over the //! vsock to the host's `passt`, which carries them to the network as the //! host's own connections. The host needs no bridge, TAP or root for it, -//! and each VM's network is its own. +//! and each VM's network is its own. The host makes the link: it connects +//! to the VM's port, and passt takes over its connection. use super::netlink; use fctl_proto::vm::{ADDRESS, GATEWAY, MTU, NET_PORT, PREFIX}; @@ -10,13 +11,20 @@ use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_tun::Tun; -use tokio_vsock::{OwnedReadHalf, OwnedWriteHalf, VMADDR_CID_HOST, VsockAddr, VsockStream}; +use tokio_vsock::{ + OwnedReadHalf, OwnedWriteHalf, VMADDR_CID_ANY, VMADDR_CID_HOST, VsockAddr, VsockListener, + VsockStream, +}; /// The longest frame: the MTU, an Ethernet header and a VLAN tag. const MAX_FRAME: usize = MTU as usize + 18; -/// Brings the network up and keeps it linked to the host, connecting again -/// when the link closes (the host restarts `passt`, say). +/// Brings the network up and takes the host's link to it: the host connects +/// to the VM's [`NET_PORT`] once the VM is up and hands the connection to +/// `passt`, which a connection of passt's own would need to accept (and +/// Ubuntu's AppArmor profile for passt refuses that, from Firecracker). A +/// newer link takes the place of the one before (the host started passt +/// again, after a snapshot's restore, say). pub async fn run() { if let Err(e) = netlink::ask(&netlink::link_up_message(1)) { tracing::warn!("bringing the loopback up: {e}"); @@ -28,19 +36,38 @@ pub async fn run() { return; } }; - let mut wait = Duration::from_secs(1); + let listener = match VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, NET_PORT)) { + Ok(listener) => listener, + Err(e) => { + tracing::error!("the VM has no network: listening on the vsock: {e}"); + return; + } + }; + let mut link: Option> = None; loop { - match VsockStream::connect(VsockAddr::new(VMADDR_CID_HOST, NET_PORT)).await { - Ok(stream) => { - tracing::info!("the network is linked to the host"); - wait = Duration::from_secs(1); - let e = forward(&tap, stream).await; - tracing::warn!("the network's link to the host closed: {e}"); + let (stream, peer) = match listener.accept().await { + Ok(accepted) => accepted, + Err(e) => { + tracing::warn!("taking the host's link to the network: {e}"); + tokio::time::sleep(Duration::from_secs(1)).await; + continue; } - Err(e) => tracing::debug!("linking the network to the host: {e}"), + }; + // Only the host, not a program in the VM through the vsock's + // loopback, which would see the VM's frames. + if peer.cid() != VMADDR_CID_HOST { + tracing::warn!("refused a network link from vsock CID {}", peer.cid()); + continue; + } + if let Some(old) = link.take() { + old.abort(); } - tokio::time::sleep(wait).await; - wait = (wait * 2).min(Duration::from_secs(10)); + tracing::info!("the network is linked to the host"); + let tap = tap.clone(); + link = Some(tokio::spawn(async move { + let e = forward(&tap, stream).await; + tracing::warn!("the network's link to the host closed: {e}"); + })); } } diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 915a00a7..03278d05 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -13,9 +13,9 @@ //! and starting it again boots from it. //! - **The VM** boots the kernel with fctl-agent as its init //! ([`assets::initrd`]); Firecracker and `passt`, which gives the VM its -//! network over the vsock without a TAP device or root on the host, run -//! in process groups of their own, so that restarting the host leaves -//! them running ([`vm`]). +//! network over a vsock connection the host makes once the VM is up, +//! without a TAP device or root on the host, run in process groups of +//! their own, so that restarting the host leaves them running ([`vm`]). //! - **The host runs programs** in the VM through its vsock, as `docker //! exec` would ([`vsock`]). @@ -631,7 +631,7 @@ impl FirecrackerDriver { remove_stale(&self.root.join("unpacking")); let vm = Vm::new(self.root.join("unpacking").join(&name))?; let spec = vm::unpack_spec(kernel, initrd, &name, rootfs); - vm.start(&spec, &firecracker, None).await?; + vm.start(&spec, &firecracker).await?; let result = async { vm.wait_ready().await?; let within = @@ -708,6 +708,14 @@ impl FirecrackerDriver { let socket = vm.vsock(); let answers = tokio::time::timeout(Duration::from_secs(10), vsock::hello(&socket)); if matches!(answers.await, Ok(Ok(_))) { + // Its passt exited, or was stopped: the VM gets another. + if !vm.linked() { + log(format!("Linking the network of {} again", spec.name)); + let passt = self + .passt() + .context("passt is not installed: it gives the VMs their network")?; + vm.link_network(&passt).await?; + } return Ok(sb); } log(format!( @@ -768,8 +776,12 @@ impl FirecrackerDriver { memory_mb: spec.memory_mb, network: true, }; - vm.start(&boot, &firecracker, Some(&passt)).await?; + vm.start(&boot, &firecracker).await?; vm.wait_ready().await?; + if let Err(e) = vm.link_network(&passt).await { + vm.kill().await; + return Err(e); + } record.agent = Some(agent); self.save_record(&spec.name, &record)?; Ok(sb) @@ -1168,99 +1180,26 @@ mod tests { async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { let dir = data.join("firecracker/sandboxes").join(&sb.name); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); - let passt = read("passt.pid").trim().parse::().ok().map(|pid| { - let proc = - |f: &str| std::fs::read_to_string(format!("/proc/{pid}/{f}")).unwrap_or_default(); - let fds = std::fs::read_dir(format!("/proc/{pid}/fd")) - .map(|d| { - d.flatten() - .filter_map(|e| std::fs::read_link(e.path()).ok()) - .map(|l| l.display().to_string()) - .collect::>() - }) - .unwrap_or_default(); - // passt makes itself undumpable: root sees the rest, where sudo - // asks for no password (as on CI's runners). - let sudo = |args: &[&str]| { - std::process::Command::new("sudo") - .arg("-n") - .args(args) - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) - .unwrap_or_default() - }; - let p = pid.to_string(); - format!( - "{}\n{}\nfds: {fds:?}\nas root: fds {}\nsyscall {}\nstack {}\nsockets: {}", - proc("cmdline").replace('\0', " "), - proc("status") - .lines() - .filter(|l| l.starts_with("State")) - .collect::(), - sudo(&["ls", "-l", &format!("/proc/{p}/fd")]), - sudo(&["cat", &format!("/proc/{p}/syscall")]), - sudo(&["cat", &format!("/proc/{p}/stack")]), - sudo(&["ss", "-xanp"]) - .lines() - .filter(|l| l.contains("v.sock") - || l.contains("passt") - || l.contains("firecracker")) - .collect::>() - .join("\n") - ) - }); - // Its capture, where the test asked for one (debug_passt). - let frames = std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG") - .and_then(|pcap| std::fs::read(pcap).ok()) - .map(|pcap| pcap_summary(&pcap)); + let passt = read("passt.pid") + .trim() + .parse::() + .ok() + .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) + .map(|cmdline| cmdline.replace('\0', " ")); let vm = d .exec( sb, - "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; - let strace = std::fs::read_to_string("/tmp/passt.strace").unwrap_or_default(); format!( - "passt: {passt:?}\npasst's syscalls:\n{strace}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", + "passt runs: {passt:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), read("console.log").trim(), vm.unwrap_or_else(|e| format!("{e:#}")) ) } - /// The frames in a pcap file, each as its length and first bytes. - fn pcap_summary(pcap: &[u8]) -> Vec { - let mut frames = Vec::new(); - let mut at = 24; - while let Some(header) = pcap.get(at..at + 16) { - let len = u32::from_le_bytes([header[8], header[9], header[10], header[11]]) as usize; - let frame = pcap.get(at + 16..at + 16 + len).unwrap_or_default(); - frames.push(format!( - "{len}: {}", - hex::encode(&frame[..frame.len().min(42)]) - )); - at += 16 + len; - } - frames - } - - /// passt with its debug log and a capture of its frames, in place of the - /// host's: a script that runs it so, which - /// `FCTL_TEST_FIRECRACKER_PASST_DEBUG` asks for, naming the capture's - /// file (in /tmp, where Ubuntu's AppArmor profile lets passt write). - fn debug_passt(dir: &Path) -> Result { - let passt = find_program("passt").context("passt is not installed")?; - let script = dir.join("passt-debug"); - crate::driver::fake::write_script( - &script, - &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec strace -f -tt -e trace=accept4,accept,getsockopt,setsockopt,epoll_ctl -o /tmp/passt.strace {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", - passt.display() - ), - )?; - Ok(script) - } - /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1293,9 +1232,6 @@ mod tests { }; cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; - if std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG").is_some() { - cfg.firecracker.passt = Some(debug_passt(temp.path())?); - } let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; assert!(probed.available, "{probed:?}"); diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 196c96f0..d6e73ce2 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -106,12 +106,6 @@ impl Vm { self.run.join("v.sock") } - /// Where `passt` takes the VM's network: what Firecracker connects to - /// when the VM connects to the host's [`NET_PORT`]. - pub fn net(&self) -> PathBuf { - self.run.join(format!("v.sock_{NET_PORT}")) - } - pub fn console(&self) -> PathBuf { self.dir.join("console.log") } @@ -151,30 +145,27 @@ impl Vm { self.pid("firecracker").is_some() } - /// Starts `passt`, if the VM gets a network, and Firecracker, after - /// stopping what an earlier boot left: the `passt` of a VM that powered - /// off, say. What it started goes again when it fails. - pub async fn start(&self, spec: &Spec, firecracker: &Path, passt: Option<&Path>) -> Result<()> { + /// Whether the VM's `passt` runs, which takes its network. + pub fn linked(&self) -> bool { + self.pid("passt").is_some() + } + + /// Starts Firecracker, after stopping what an earlier boot left: the + /// `passt` of a VM that powered off, say. What it started goes again + /// when it fails. A VM that gets a network gets it once it is up + /// ([`link_network`](Self::link_network)). + pub async fn start(&self, spec: &Spec, firecracker: &Path) -> Result<()> { self.kill().await; - let started = self.start_processes(spec, firecracker, passt).await; + let started = self.start_processes(spec, firecracker).await; if started.is_err() { self.kill().await; } started } - async fn start_processes( - &self, - spec: &Spec, - firecracker: &Path, - passt: Option<&Path>, - ) -> Result<()> { + async fn start_processes(&self, spec: &Spec, firecracker: &Path) -> Result<()> { std::fs::create_dir_all(&self.dir)?; std::fs::create_dir_all(&self.run)?; - if spec.network { - let passt = passt.context("the VM needs passt for its network")?; - self.start_passt(passt).await?; - } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; let console = std::fs::File::create(self.console())?; @@ -192,23 +183,36 @@ impl Vm { Ok(()) } - /// `passt`, which takes the VM's frames at [`Vm::net`] and makes them - /// connections of the host's: the VM gets [`ADDRESS`], the gateway and - /// a DNS forwarder, and reaches neither the host's loopback nor other - /// VMs. Nothing reaches the VM from outside. - async fn start_passt(&self, passt: &Path) -> Result<()> { + /// Links the VM's network to a `passt` of its own, once the VM is up: + /// connects to the VM's [`NET_PORT`] and hands passt the connection + /// (`--fd`), which makes the VM's frames connections of the host's. The + /// VM gets [`ADDRESS`] and the gateway, and reaches neither the host's + /// loopback nor other VMs; nothing reaches it from outside. passt exits + /// when the VM closes the connection, as it stops. passt could take the + /// VM's connection on a socket of its own, but Ubuntu's AppArmor profile + /// for it refuses one from Firecracker (`accept` fails, EACCES). A link + /// made before goes: its passt took a connection that a restored + /// snapshot, say, has lost. + pub async fn link_network(&self, passt: &Path) -> Result<()> { + self.kill_one("passt").await; + let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; + let ready = self.run.join("passt.pid"); + let _ = std::fs::remove_file(&ready); let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net())) - .stdin(Stdio::null()) + cmd.args(passt_args(&ready)) + .stdin(Stdio::from(std::os::fd::OwnedFd::from(conn))) .stdout(log.try_clone()?) .stderr(log); spawn_detached(&mut cmd, &self.pid_file("passt")) .with_context(|| format!("starting {}", passt.display()))?; + // passt writes its pid as it is about to take frames, and exits + // when it can't. let until = Instant::now() + Duration::from_secs(10); - while !self.net().exists() { + while !ready.exists() { if Instant::now() > until || self.pid("passt").is_none() { let said = std::fs::read_to_string(self.dir.join("passt.log")).unwrap_or_default(); + self.kill_one("passt").await; bail!("passt did not start: {}", said.trim()); } tokio::time::sleep(Duration::from_millis(20)).await; @@ -216,6 +220,27 @@ impl Vm { Ok(()) } + /// A connection to `port` in the VM, through Firecracker's vsock + /// socket, once something there takes it, within `within`. + async fn connect_port( + &self, + port: u32, + within: Duration, + ) -> Result { + let until = Instant::now() + within; + loop { + let socket = self.vsock(); + let tried = tokio::task::spawn_blocking(move || connect_raw(&socket, port)).await?; + match tried { + Ok(conn) => return Ok(conn), + Err(e) if Instant::now() > until || !self.running() => { + return Err(e.context(format!("linking the VM's network (vsock port {port})"))); + } + Err(_) => tokio::time::sleep(Duration::from_millis(100)).await, + } + } + } + /// Firecracker's configuration for `spec`. pub fn config(&self, spec: &Spec) -> Value { let drives: Vec = spec @@ -345,18 +370,23 @@ impl Vm { /// Kills the VM's processes. pub async fn kill(&self) { for what in ["firecracker", "passt"] { - if let Some(pid) = self.pid(what) { - let _ = crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await; - let until = Instant::now() + Duration::from_secs(5); - while self.pid(what).is_some() && Instant::now() < until { - tokio::time::sleep(Duration::from_millis(50)).await; - } - } - let _ = std::fs::remove_file(self.pid_file(what)); + self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); } + /// Kills the VM's process `what`, if it runs. + async fn kill_one(&self, what: &str) { + if let Some(pid) = self.pid(what) { + let _ = crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await; + let until = Instant::now() + Duration::from_secs(5); + while self.pid(what).is_some() && Instant::now() < until { + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + let _ = std::fs::remove_file(self.pid_file(what)); + } + /// Stops the VM and removes its files. pub async fn remove(&self) -> Result<()> { self.stop().await; @@ -430,17 +460,20 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`: the -/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 -/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which -/// came later. -fn passt_args(socket: &Path) -> Vec { +/// The arguments of `passt` for a VM whose link is its input, and which +/// writes its pid to `pid` (in the VM's directory of sockets, whose path +/// tells it from other processes): the options of passt's releases since +/// 2022, which Ubuntu 24.04 and Debian 12 have. The VM names itself, so +/// passt's DHCP needs no `--hostname`, which came later. +fn passt_args(pid: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ "--foreground".into(), "--quiet".into(), - "--socket".into(), - socket.display().to_string(), + "--fd".into(), + "0".into(), + "--pid".into(), + pid.display().to_string(), "--address".into(), Ipv4Addr::from(ADDRESS).to_string(), "--netmask".into(), @@ -454,6 +487,48 @@ fn passt_args(socket: &Path) -> Vec { ] } +/// How long a VM that is up may take to take its network's link: its +/// init listens as it starts. +const LINK_TIMEOUT: Duration = Duration::from_secs(10); + +/// Connects to `port` in the VM whose vsock socket is `socket` (`CONNECT`, +/// then Firecracker's `OK`), reading no byte past Firecracker's answer: +/// what follows is the VM's, for whoever takes the connection. +fn connect_raw(socket: &Path, port: u32) -> Result { + use std::io::{Read, Write}; + let mut conn = std::os::unix::net::UnixStream::connect(socket) + .with_context(|| format!("connecting to {}", socket.display()))?; + conn.set_read_timeout(Some(Duration::from_secs(5)))?; + // Firecracker closes the connection when nothing in the VM takes it, + // which may come as a reset. + let refused = || anyhow::anyhow!("nothing in the VM takes connections on port {port} yet"); + let gone = |e: std::io::Error| match e.kind() { + std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::BrokenPipe => refused(), + _ => e.into(), + }; + conn.write_all(format!("CONNECT {port}\n").as_bytes()) + .map_err(gone)?; + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + while line.len() < 64 { + if conn.read(&mut byte).map_err(gone)? == 0 { + return Err(refused()); + } + if byte[0] == b'\n' { + break; + } + line.push(byte[0]); + } + if !line.starts_with(b"OK ") { + bail!( + "Firecracker answered {:?} to a connection to port {port}", + String::from_utf8_lossy(&line) + ); + } + conn.set_read_timeout(None)?; + Ok(conn) +} + /// The nameservers a VM asks, which passt reaches as the host does: as /// Docker gives its containers, the host's own, but for those on its /// loopback, which the VM can't reach, and where only those are left @@ -598,16 +673,15 @@ mod tests { assert_eq!(c["machine-config"]["vcpu_count"], 32); assert_eq!(c["machine-config"]["mem_size_mib"], 4096); assert_eq!(c["vsock"]["uds_path"], "/tmp/fctl-ada/vm-0123/v.sock"); - assert_eq!(vm.net(), PathBuf::from("/tmp/fctl-ada/vm-0123/v.sock_1025")); Ok(()) } #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/passt.pid")).join(" "); assert_eq!( args, - "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" + "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0/passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } @@ -834,38 +908,87 @@ mod tests { Ok(()) } - /// Stand-ins: a `passt` that makes its socket's path and waits, and a - /// Firecracker that waits. + /// Says a stand-in's connections are to close. + type Closer = std::sync::Arc; + /// What a stand-in's connections read. + type Seen = std::sync::Arc>>; + + /// A stand-in for Firecracker's vsock socket at `socket`: each + /// connection asking for `CONNECT 1025` gets `OK` and stays open until + /// `close` says otherwise; the VM's side keeps what it reads in `got`. + /// Anything else is closed at once, as when nothing in the VM listens. + fn vsock_stand_in(socket: &Path) -> Result<(Closer, Seen)> { + use std::io::{BufRead, Write}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + std::fs::create_dir_all(socket.parent().context("no parent")?)?; + let listener = std::os::unix::net::UnixListener::bind(socket)?; + let close = Arc::new(AtomicBool::new(false)); + let got = Arc::new(Mutex::new(Vec::new())); + let (closing, seen) = (close.clone(), got.clone()); + std::thread::spawn(move || { + for conn in listener.incoming().flatten() { + let mut reader = std::io::BufReader::new(&conn); + let mut line = String::new(); + if reader.read_line(&mut line).is_err() || line != format!("CONNECT {NET_PORT}\n") { + continue; + } + let mut w = &conn; + // The VM's first frame comes with Firecracker's answer. + let _ = w.write_all(b"OK 1073741824\n\0\0\0\x02hi"); + let (closing, seen) = (closing.clone(), seen.clone()); + std::thread::spawn(move || { + let _ = conn.set_read_timeout(Some(Duration::from_millis(50))); + let mut buf = [0u8; 64]; + while !closing.load(Ordering::Relaxed) { + if let Ok(n) = std::io::Read::read(&mut &conn, &mut buf) + && let Ok(mut g) = seen.lock() + { + g.extend_from_slice(&buf[..n]); + } + } + }); + } + }); + Ok((close, got)) + } + + /// The host links a VM's network once it is up: passt gets the + /// connection, with nothing of it read, a link made again takes the + /// first one's place, passt exits as the VM goes, and a start that + /// fails leaves nothing running. Stand-ins: a Firecracker that waits, + /// and a passt that writes its pid where it's asked and echoes its + /// input. #[tokio::test] - async fn starting_again_stops_what_the_last_boot_left() -> Result<()> { + async fn links_the_vms_network_once_it_is_up() -> Result<()> { use crate::driver::fake::write_script; + use std::sync::atomic::Ordering; let dir = tempfile::tempdir()?; let passt = dir.path().join("passt"); - // Without `exec`, so that their command lines keep the sockets. + // Without `exec`, so that its command line keeps the VM's path. write_script( &passt, - "#!/bin/sh\nfor a; do [ \"$prev\" = --socket ] && touch \"$a\"; prev=$a; done\nsleep 60\n", + "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && echo $$ > \"$a\"; prev=$a; done\ncat >&0\n", )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; let vm = Vm::new(dir.path().join("fctl-ses-x"))?; let spec = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); - let spec = Spec { - network: true, - ..spec - }; - vm.start(&spec, &firecracker, Some(&passt)).await?; - let first_passt = vm.pid("passt"); - assert!(first_passt.is_some() && vm.running()); - // Firecracker ends by itself (its VM powered off), and passt stays. - if let Some(pid) = vm.pid("firecracker") { - crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await?; - } - while vm.running() { + vm.start(&spec, &firecracker).await?; + assert!(vm.running() && !vm.linked()); + let (close, got) = vsock_stand_in(&vm.vsock())?; + vm.link_network(&passt).await?; + let first = vm.pid("passt"); + assert!(vm.linked()); + // passt got the VM's first frame, which came with Firecracker's + // answer, and sent it back. + let until = Instant::now() + Duration::from_secs(5); + while got.lock().map(|g| g.clone()).unwrap_or_default() != b"\0\0\0\x02hi" { + assert!(Instant::now() < until, "passt didn't get the VM's frame"); tokio::time::sleep(Duration::from_millis(20)).await; } - assert_eq!(vm.pid("passt"), first_passt); - vm.start(&spec, &firecracker, Some(&passt)).await?; + // Linked again: the first passt goes. + vm.link_network(&passt).await?; let alive = |pid: u32| { std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| { !s.rsplit_once(')') @@ -873,14 +996,41 @@ mod tests { }) }; assert!( - first_passt.is_some_and(|p| !alive(p)), + first.is_some_and(|p| !alive(p)), "the first passt still runs" ); - assert!(vm.pid("passt").is_some() && vm.running()); + assert!(vm.linked() && vm.pid("passt") != first); + // The VM goes, and its passt with it. + close.store(true, Ordering::Relaxed); + let until = Instant::now() + Duration::from_secs(5); + while vm.linked() { + assert!(Instant::now() < until, "passt outlived its link"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + // Nothing in the VM takes the link: it fails, and says why. + let other = Vm::new(dir.path().join("fctl-ses-y"))?; + std::fs::create_dir_all(&other.run)?; + let refusing = std::os::unix::net::UnixListener::bind(other.vsock())?; + std::thread::spawn(move || { + for conn in refusing.incoming().flatten() { + drop(conn); + } + }); + let e = other + .connect_port(NET_PORT, Duration::from_millis(300)) + .await + .err() + .map(|e| format!("{e:#}")); + assert!( + e.as_deref() + .is_some_and(|e| e.contains("nothing in the VM takes connections")), + "{e:?}" + ); // A start that fails leaves nothing running. let missing = dir.path().join("no-firecracker"); - assert!(vm.start(&spec, &missing, Some(&passt)).await.is_err()); - assert!(vm.pid("passt").is_none() && !vm.running()); + assert!(vm.start(&spec, &missing).await.is_err()); + assert!(!vm.linked() && !vm.running()); + let _ = std::fs::remove_dir_all(&other.run); Ok(()) } } diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 7a254cf4..2eaf39f4 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -9,9 +9,10 @@ //! exits; after an [`Request::Unpack`], the layers' bytes one after the //! other, then a second [`Reply`]. //! -//! The VM itself reaches the host's [`NET_PORT`], where the host's `passt` -//! takes its network: Ethernet frames, each after its length (4 bytes, big -//! endian), as passt reads them from QEMU. +//! The host connects to the VM's [`NET_PORT`] too, once the VM is up, and +//! hands the connection to a `passt` of the VM's own, which takes its +//! network: Ethernet frames, each after its length (4 bytes, big endian), +//! as passt reads them from QEMU. //! //! A host may be one version ahead of the init of a VM that was running //! when it updated, so requests only gain optional fields, and an init @@ -23,7 +24,8 @@ use serde_with::skip_serializing_none; /// The vsock port the init serves requests on. pub const PORT: u32 = 1024; -/// The vsock port of the host's network for the VM (`passt`). +/// The vsock port where the VM takes the host's link to its network +/// (`passt`). pub const NET_PORT: u32 = 1025; /// The VM's network, as the host's `passt` gives it: the VM's address and diff --git a/docs/architecture.md b/docs/architecture.md index 63e378a2..f3a06d23 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3468,10 +3468,18 @@ in `firecracker/` in the host's data directory. - **Network.** The VM's `eth0` is a TAP device inside the VM, with `10.0.2.15/24`, whose frames `vm-serve` carries over the vsock to a `passt` of the VM's own on the host, which turns them into the host's - own connections. The host has no bridge, TAP device or firewall rule for - it. A VM reaches the internet and the host's network as a Docker - container does, but neither other VMs nor the host's loopback, and - nothing reaches it from outside; DNS goes to the host's resolver. + own connections. The host makes the link once the VM is up: it connects + to the VM's vsock port 1025 and hands passt the connection (`--fd`), so + that passt exits as the VM does; passt can't take Firecracker's + connection on a socket of its own where Ubuntu's AppArmor profile for it + applies (`accept` fails). The host has no bridge, TAP device or firewall + rule for it. A VM reaches the internet and the host's network as a + Docker container does, but neither other VMs nor the host's loopback, + and nothing reaches it from outside. It asks the host's nameservers, as + a Docker container does: those in `/etc/resolv.conf` but for any on the + loopback, and where only those are left (systemd-resolved's + `127.0.0.53`), the servers systemd-resolved asks; with none, passt's + forwarder to the host's resolver. - **Processes.** Firecracker and `passt` run in process groups of their own, as the process driver's agents do, so restarting or updating the host leaves them running; the host finds a VM's processes by the ids it From 6076b121d37a86178d23e29ac9295726f7b46364 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:24:47 +0000 Subject: [PATCH 15/26] fix(host): count passt as linked once it writes its pid, not once it makes the file passt makes its pid's file as it reads its options and writes the pid only once it has set itself up, so a passt that failed in between left the VM without a network while the host took it as linked. The host now waits for the pid; the test's stand-in passt makes the file first, as passt does, and one that fails then gets no link. --- crates/fctl-host/src/driver/firecracker/vm.rs | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index d6e73ce2..e364cd5d 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -206,10 +206,13 @@ impl Vm { .stderr(log); spawn_detached(&mut cmd, &self.pid_file("passt")) .with_context(|| format!("starting {}", passt.display()))?; - // passt writes its pid as it is about to take frames, and exits - // when it can't. + // passt makes its pid's file as it reads its options, writes its + // pid there once it has set itself up and is about to take frames, + // and exits when it can't. + let has_pid = + || std::fs::read_to_string(&ready).is_ok_and(|p| p.trim().parse::().is_ok()); let until = Instant::now() + Duration::from_secs(10); - while !ready.exists() { + while !has_pid() { if Instant::now() > until || self.pid("passt").is_none() { let said = std::fs::read_to_string(self.dir.join("passt.log")).unwrap_or_default(); self.kill_one("passt").await; @@ -965,10 +968,20 @@ mod tests { use std::sync::atomic::Ordering; let dir = tempfile::tempdir()?; let passt = dir.path().join("passt"); - // Without `exec`, so that its command line keeps the VM's path. + // As passt: its pid's file is made at once and written once it is + // set up. Without `exec`, so that its command line keeps the VM's + // path. + let stand_in = |then: &str| { + format!( + "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && pid=$a; prev=$a; done\n: > \"$pid\"\nsleep 0.3\n{then}\n" + ) + }; + write_script(&passt, &stand_in("echo $$ > \"$pid\"\ncat >&0"))?; + // One that fails as it sets itself up. + let failing = dir.path().join("failing-passt"); write_script( - &passt, - "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && echo $$ > \"$a\"; prev=$a; done\ncat >&0\n", + &failing, + &stand_in("echo 'No routable interface' >&2; exit 1"), )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; @@ -977,6 +990,13 @@ mod tests { vm.start(&spec, &firecracker).await?; assert!(vm.running() && !vm.linked()); let (close, got) = vsock_stand_in(&vm.vsock())?; + // A passt that fails once it has made its pid's file: no link. + let e = vm.link_network(&failing).await.err().map(|e| e.to_string()); + assert_eq!( + e.as_deref(), + Some("passt did not start: No routable interface") + ); + assert!(!vm.linked()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 2adf05430ffee31afd92bf2a5966870cb64ddb07 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:29:32 +0000 Subject: [PATCH 16/26] feat(host): boot Firecracker VMs with the kernel that has 9p (6.18.59-1) hyperstructure/sandbox#15 publishes it; the VMs mount their project's package caches with its 9p client. --- crates/fctl-host/src/driver/firecracker/assets.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/assets.rs b/crates/fctl-host/src/driver/firecracker/assets.rs index 393efee7..ab7cff0b 100644 --- a/crates/fctl-host/src/driver/firecracker/assets.rs +++ b/crates/fctl-host/src/driver/firecracker/assets.rs @@ -24,8 +24,9 @@ const FIRECRACKER_ARCHIVES: [(&str, &str); 2] = [ /// The kernel VMs boot unless `host.toml` names another: Firecracker's /// guest configuration for Linux 6.18, built and published by -/// hyperstructure/sandbox, as `/vmlinux` in an image. -pub const KERNEL_IMAGE: &str = "ghcr.io/hyperstructure/sandbox-kernel:6.18.59"; +/// hyperstructure/sandbox, as `/vmlinux` in an image. From `6.18.59-1` it +/// has 9p, with which VMs mount their project's package caches. +pub const KERNEL_IMAGE: &str = "ghcr.io/hyperstructure/sandbox-kernel:6.18.59-1"; /// Where the release archive of Firecracker `version` is. fn firecracker_url(version: &str, arch: &str) -> String { From 299b3de60f7d2dcb7e8a9bbc52cbbb5b837fc51f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:44:40 +0000 Subject: [PATCH 17/26] fix(host): keep Firecracker VMs' caches through lock modes, lost servers and full fd tables - A write lock on a file the VM opened to read failed (fcntl's locks take a file open for writing), as flock -x on one does: the server now takes a file's locks on it opened again for reading and writing, where the host's user may. - A server out of file descriptors returned from its loop and exited, and nothing served the VM again. It now refuses that connection, pauses after errors, serves at most 16 connections, and the host serves a running VM again, which mounts the new server, when its server is gone. - A server that couldn't start failed the VM's start. The host now serves the caches once the VM is up, as it links its network, and a failure only costs the session its caches, which its log says. - The test that checks a lock between two VMs held its lock's program only until the host dropped its handle, which stopped it: it passed or failed by timing. - cli.md, sandbox-images.md and security.md say Firecracker's VMs get the caches, and how the server keeps to their directory. --- crates/fctl-agent/src/share/mod.rs | 75 +++++++++++++++---- crates/fctl-agent/src/share/tests.rs | 19 ++++- .../fctl-host/src/driver/firecracker/mod.rs | 61 ++++++++++----- crates/fctl-host/src/driver/firecracker/vm.rs | 42 ++++++----- docs/cli.md | 10 +-- docs/sandbox-images.md | 7 +- docs/security.md | 11 ++- 7 files changed, 161 insertions(+), 64 deletions(-) diff --git a/crates/fctl-agent/src/share/mod.rs b/crates/fctl-agent/src/share/mod.rs index 697db0e6..61b3b436 100644 --- a/crates/fctl-agent/src/share/mod.rs +++ b/crates/fctl-agent/src/share/mod.rs @@ -54,6 +54,9 @@ pub const MAX_MSIZE: u32 = 1024 * 1024; /// server's. const MAX_FIDS: usize = 1 << 16; +/// The most connections served at once: the VM's mount makes one. +const MAX_CONNECTIONS: usize = 16; + /// The protocol, the one the Linux client asks for first. const VERSION: &[u8] = b"9P2000.L"; @@ -114,20 +117,39 @@ pub fn serve(dir: &Path, socket: &Path) -> Result<()> { let listener = UnixListener::bind(socket).with_context(|| format!("listening on {}", socket.display()))?; tracing::info!("serving {} on {}", dir.display(), socket.display()); + let serving = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + // A failure here costs a connection, never the server: the VM's mount + // would fail with it. + let pause = || std::thread::sleep(std::time::Duration::from_millis(100)); for conn in listener.incoming() { let conn = match conn { Ok(conn) => conn, Err(e) => { tracing::warn!("taking a connection: {e}"); + pause(); + continue; + } + }; + if serving.load(std::sync::atomic::Ordering::Relaxed) >= MAX_CONNECTIONS { + tracing::warn!("refused a connection: {MAX_CONNECTIONS} are served already"); + continue; + } + let root = match root.try_clone() { + Ok(root) => root, + Err(e) => { + tracing::warn!("refused a connection: {e}"); + pause(); continue; } }; - let root = root.try_clone()?; + let serving = serving.clone(); + serving.fetch_add(1, std::sync::atomic::Ordering::Relaxed); std::thread::spawn(move || { let mut session = Session::new(root); if let Err(e) = session.run(conn) { tracing::debug!("a connection ended: {e}"); } + serving.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); }); } Ok(()) @@ -169,6 +191,10 @@ struct Fid { fd: OwnedFd, kind: Kind, open: Option, + /// The file opened for its locks, which `fcntl` takes only on a file + /// open for writing (write locks) or reading (read locks), whatever + /// the client opened it for. + locks: Option, /// A directory's entries, read when the client reads it from the start. entries: Vec<(Vec, Qid, u8)>, /// An extended attribute's: it has none, so it reads as nothing. @@ -181,6 +207,7 @@ impl Fid { fd, kind, open: None, + locks: None, entries: Vec::new(), xattr: false, } @@ -319,6 +346,31 @@ impl Session { Ok(&f.fd) } + /// The file `fid`'s locks are taken on: the file the client opened, + /// opened again for reading and writing, where the host's user may, so + /// that a write lock on a file the client opened to read holds, as + /// `flock` on one does. + fn locks(&mut self, fid: u32) -> io::Result<&File> { + let f = self.fid_mut(fid)?; + if f.kind != Kind::File { + return fail(libc::EBADF); + } + if f.locks.is_none() { + let Some(open) = &f.open else { + return fail(libc::EBADF); + }; + let locks = File::options() + .read(true) + .write(true) + .open(reopen_path(&f.fd)) + .or_else(|_| open.try_clone())?; + f.locks = Some(locks); + } + f.locks + .as_ref() + .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF)) + } + fn insert(&mut self, fid: u32, f: Fid) -> io::Result<()> { if self.fids.len() >= MAX_FIDS && !self.fids.contains_key(&fid) { return fail(libc::EMFILE); @@ -512,19 +564,13 @@ impl Session { Ok(reply(t).finish()) } kind::TLOCK => { - let f = self.fid(r.u32()?)?; + let fid = r.u32()?; let kind = r.u8()?; let _flags = r.u32()?; let start = r.u64()?; let length = r.u64()?; - let file = f - .open - .as_ref() - .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; - let status = match nix::fcntl::fcntl( - file, - FcntlArg::F_OFD_SETLK(&flock(kind, start, length)?), - ) { + let fl = flock(kind, start, length)?; + let status = match nix::fcntl::fcntl(self.locks(fid)?, FcntlArg::F_OFD_SETLK(&fl)) { Ok(_) => lock::SUCCESS, Err(Errno::EAGAIN | Errno::EACCES) => lock::BLOCKED, Err(_) => lock::ERROR, @@ -534,18 +580,15 @@ impl Session { Ok(w.finish()) } kind::TGETLOCK => { - let f = self.fid(r.u32()?)?; + let fid = r.u32()?; let kind = r.u8()?; let start = r.u64()?; let length = r.u64()?; let proc_id = r.u32()?; let client = r.bytes()?; - let file = f - .open - .as_ref() - .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; let mut fl = flock(kind, start, length)?; - nix::fcntl::fcntl(file, FcntlArg::F_OFD_GETLK(&mut fl)).map_err(errno)?; + nix::fcntl::fcntl(self.locks(fid)?, FcntlArg::F_OFD_GETLK(&mut fl)) + .map_err(errno)?; let mut w = reply(t); if i32::from(fl.l_type) == libc::F_UNLCK { w.u8(lock::UNLCK) diff --git a/crates/fctl-agent/src/share/tests.rs b/crates/fctl-agent/src/share/tests.rs index f48e6773..a25bfd37 100644 --- a/crates/fctl-agent/src/share/tests.rs +++ b/crates/fctl-agent/src/share/tests.rs @@ -356,9 +356,10 @@ fn locks_hold_between_vms() -> anyhow::Result<()> { std::fs::write(dir.path().join(".package-cache"), b"")?; let mut a = Client::new(dir.path())?; let mut b = Client::new(dir.path())?; - for c in [&mut a, &mut b] { + // As flock's: whatever the file is open for, on either side. + for (c, mode) in [(&mut a, RDONLY), (&mut b, RDWR)] { assert_eq!(c.walk(0, 1, &[b".package-cache"]), Ok(1)); - assert!(c.lopen(1, RDWR).is_ok()); + assert!(c.lopen(1, mode).is_ok()); } assert_eq!(a.lock(1, lock::WRLCK), Ok(lock::SUCCESS)); assert_eq!(b.lock(1, lock::WRLCK), Ok(lock::BLOCKED)); @@ -430,6 +431,20 @@ fn serves_on_a_unix_socket() -> anyhow::Result<()> { assert_eq!(reply[4], kind::TVERSION + 1); assert_eq!(&reply[7..11], &MAX_MSIZE.to_le_bytes()); assert_eq!(&reply[13..], b"9P2000.L"); + // As many connections as it serves at once; the next is refused. + let mut others = Vec::new(); + for _ in 1..MAX_CONNECTIONS { + let mut other = UnixStream::connect(&socket)?; + let mut w = Writer::new(kind::TVERSION, wire::NOTAG); + w.u32(8192).bytes(b"9P2000.L"); + other.write_all(&w.finish())?; + let mut reply = vec![0u8; 4 + 1 + 2 + 4 + 2 + 8]; + other.read_exact(&mut reply)?; + others.push(other); + } + let mut refused = UnixStream::connect(&socket)?; + let mut nothing = Vec::new(); + assert_eq!(refused.read_to_end(&mut nothing)?, 0); // A message larger than any the server takes ends the connection. conn.write_all(&(MAX_MSIZE * 2).to_le_bytes())?; let mut rest = Vec::new(); diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 2b9ba16e..a4c06aec 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -722,6 +722,14 @@ impl FirecrackerDriver { .context("passt is not installed: it gives the VMs their network")?; vm.link_network(&passt).await?; } + // Its server of the package caches is gone: another, which + // the VM mounts in place of the mount the old one left. + if let Some(share) = self.share_of(spec).await? + && !vm.sharing() + { + log(format!("Serving the package caches of {} again", spec.name)); + self.share_caches(&vm, &spec.name, &share, log).await; + } return Ok(sb); } log(format!( @@ -759,15 +767,7 @@ impl FirecrackerDriver { let passt = self .passt() .context("passt is not installed: it gives the VMs their network")?; - let share = match &spec.cache { - Some(Spot::Dir(dir)) => Some(vm::Share { - agent: crate::agentbin::linux_agent(&self.host) - .await - .context("getting fctl-agent to serve the package caches")?, - dir: dir.clone(), - }), - _ => None, - }; + let share = self.share_of(spec).await?; let boot = Spec { kernel, initrd, @@ -790,7 +790,6 @@ impl FirecrackerDriver { cpus: spec.cpus, memory_mb: spec.memory_mb, network: true, - share: share.clone(), }; vm.start(&boot, &firecracker).await?; vm.wait_ready().await?; @@ -800,15 +799,40 @@ impl FirecrackerDriver { } record.agent = Some(agent); self.save_record(&spec.name, &record)?; - if share.is_some() - && let Err(e) = self.mount_caches(&vm, &spec.name).await - { + if let Some(share) = &share { + self.share_caches(&vm, &spec.name, share, log).await; + } + Ok(sb) + } + + /// What `spec`'s VM is served of the host's: its project's package + /// caches, which `fctl-agent share` serves. + async fn share_of(&self, spec: &SandboxSpec) -> Result> { + let Some(Spot::Dir(dir)) = &spec.cache else { + return Ok(None); + }; + let agent = crate::agentbin::linux_agent(&self.host) + .await + .context("getting fctl-agent to serve the package caches")?; + Ok(Some(vm::Share { + agent, + dir: dir.clone(), + })) + } + + /// Serves `share` to the VM, which is up, and mounts it there. Without + /// it, the session runs on without package caches, and its log says so. + async fn share_caches(&self, vm: &Vm, name: &str, share: &vm::Share, log: Log<'_>) { + let shared = async { + vm.serve_share(share).await?; + self.mount_caches(vm, name).await + } + .await; + if let Err(e) = shared { log(format!( - "The package caches couldn't be mounted in {} ({e:#}), so this session's package managers keep their own downloads", - spec.name + "The package caches couldn't be mounted in {name} ({e:#}), so this session's package managers keep their own downloads" )); } - Ok(sb) } /// Mounts the project's package caches, which `fctl-agent share` serves @@ -1449,7 +1473,9 @@ mod tests { .await?; assert_eq!(owner.trim(), "0:0 644"); // A lock one holds keeps the other waiting, as cargo's do. - d.spawn(a, "exec flock /var/cache/fctl/.package-cache sleep 30") + // Its program runs while the host holds it. + let holder = d + .spawn(a, "exec flock /var/cache/fctl/.package-cache sleep 30") .await?; tokio::time::sleep(Duration::from_secs(2)).await; let busy = d @@ -1459,6 +1485,7 @@ mod tests { ) .await?; assert_eq!(busy.trim(), "held"); + drop(holder); // A sandbox started again mounts them again. d.stop(b).await?; let b = d.ensure(&spec(&names[1]), &log).await?; diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 303e98ed..2f28155c 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -55,8 +55,6 @@ pub struct Spec { pub memory_mb: u32, /// Whether the VM gets a network (`passt`). pub network: bool, - /// A directory of the host's that the VM mounts (`fctl-agent share`). - pub share: Option, } /// A directory the host serves to a VM over its vsock ([`SHARE_PORT`]): the @@ -184,9 +182,6 @@ impl Vm { async fn start_processes(&self, spec: &Spec, firecracker: &Path) -> Result<()> { std::fs::create_dir_all(&self.dir)?; std::fs::create_dir_all(&self.run)?; - if let Some(share) = &spec.share { - self.start_share(share).await?; - } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; let console = std::fs::File::create(self.console())?; @@ -244,9 +239,17 @@ impl Vm { Ok(()) } - /// `fctl-agent share`, which serves `share`'s directory where the VM's - /// connections to [`SHARE_PORT`] come. - async fn start_share(&self, share: &Share) -> Result<()> { + /// Whether `fctl-agent share` serves the VM a directory. + pub fn sharing(&self) -> bool { + self.pid("share").is_some() + } + + /// Starts `fctl-agent share`, which serves `share`'s directory where the + /// VM's connections to [`SHARE_PORT`] come, in place of one that served + /// it before. + pub async fn serve_share(&self, share: &Share) -> Result<()> { + self.kill_one("share").await; + let _ = std::fs::remove_file(self.share()); let log = std::fs::File::create(self.dir.join("share.log"))?; let mut cmd = std::process::Command::new(&share.agent); cmd.arg("share") @@ -671,7 +674,6 @@ pub fn unpack_spec(kernel: PathBuf, initrd: PathBuf, name: &str, rootfs: &Path) cpus: 2, memory_mb: 1024, network: false, - share: None, } } @@ -707,7 +709,6 @@ mod tests { cpus: 64, memory_mb: 4096, network: true, - share: None, }; let c = vm.config(&spec); assert_eq!( @@ -1041,16 +1042,19 @@ mod tests { "#!/bin/sh\nfor a; do [ \"$prev\" = --socket ] && touch \"$a\"; prev=$a; done\nsleep 60\n", )?; let vm = Vm::new(dir.path().join("fctl-ses-x"))?; - let spec = Spec { - share: Some(Share { - agent: share, - dir: dir.path().to_owned(), - }), - ..unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")) - }; + let spec = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); vm.start(&spec, &firecracker).await?; - assert!(vm.running() && !vm.linked()); - assert!(vm.pid("share").is_some() && vm.share().exists()); + assert!(vm.running() && !vm.linked() && !vm.sharing()); + let share = Share { + agent: share, + dir: dir.path().to_owned(), + }; + vm.serve_share(&share).await?; + let first_share = vm.pid("share"); + assert!(vm.sharing() && vm.share().exists()); + // Served again: the first server goes. + vm.serve_share(&share).await?; + assert!(vm.sharing() && vm.pid("share") != first_share); let (close, got) = vsock_stand_in(&vm.vsock())?; // A passt that fails once it has made its pid's file: no link. let e = vm.link_network(&failing).await.err().map(|e| e.to_string()); diff --git a/docs/cli.md b/docs/cli.md index f765cc1f..8edcb06d 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -401,11 +401,11 @@ comes with its own), so a setup script like `npm ci` or `cargo fetch` gets only what is new. The runner keeps them for the project up to its owner's limit, 10 GiB unless `host.toml` says otherwise, empties them past it, and removes them two weeks after a session last used them ([Hosts](#hosts)). -Sessions get them on runners with the Docker or Apple container driver -(and the process driver), not Firecracker or Lima, and review agents never -do. A session -in a sandbox made before the project turned them on gets them in its next -sandbox. +Sessions get them on runners with the Docker, Apple container or +Firecracker driver (and the process driver), not Lima, and review agents +never do. A session in a sandbox made before the project turned them on +gets them in its next sandbox, but with Firecracker, whose VMs mount them +as they boot. ### Ticket trackers diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md index 789aa64b..aa5dc2e9 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -142,9 +142,10 @@ checks every build for it: managed, so packages go into a virtual environment (`uv venv`, `python3 -m venv`). -In projects that share package caches, the Docker and Apple container -drivers mount the project's caches at `/var/cache/fctl`, over whatever an -image has there, and fctl-agent points the package managers there, for the +In projects that share package caches, the Docker, Apple container and +Firecracker drivers mount the project's caches at `/var/cache/fctl`, over +whatever an image has there (Firecracker's VMs over 9P, as the image's +user's files), and fctl-agent points the package managers there, for the setup script and for Claude: `npm_config_cache`, `pnpm_config_store_dir` and `pnpm_config_cache_dir` (pnpm 11; pnpm 9 and 10 get theirs in `~/.config/pnpm/rc`), `COREPACK_HOME`, `YARN_CACHE_FOLDER` and diff --git a/docs/security.md b/docs/security.md index 96dd5206..9975e1bb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -219,8 +219,15 @@ its VM, and nothing outside it except through these channels: - **Firecracker VMs** have a kernel of their own, as Apple's and Lima's do, where a Docker container shares the host's: a kernel bug in the - sandbox stays there. They share no files with the host, and the host - runs what it runs in them through their vsock, not SSH. Firecracker runs + sandbox stays there. They share no filesystem with the host, and the host + runs what it runs in them through their vsock, not SSH. In projects that + share package caches, the host serves the project's cache directory to + each of its VMs over 9P on the vsock (`fctl-agent share`, a process of + the host's user beside each VM), which anything in the VM can reach: the + server walks one name at a time without following symlinks, refuses `.`, + `..` and names with `/`, opens only files and directories, and makes + neither devices nor setuid files, so the VM reaches nothing of the + host's but that directory, which its sandbox mounts anyway. Firecracker runs as the host's user, with its seccomp filters but without its jailer, which needs root: a VM escape would run as that user, who can read the runner's token, as a container escape can with Docker. Their images From 4536f7642fdb560136a70a8ff8fe2221862cce6f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:49:28 +0000 Subject: [PATCH 18/26] fix(host): serve a Firecracker VM's caches again after any failure, and never fail its start for them - A running VM's start fetched the static fctl-agent before it checked whether its share ran, so a fetch that failed failed a healthy VM's start; the host now checks first, and a failure costs only the caches. - A server that didn't make its socket in time, or whose mount failed, stayed, so the VM never got its caches until it stopped; the host now stops it, and the next start serves them again. - A session that panicked kept its connection's slot, and a thread the system refused ended the server; the slot now goes back however the session ends, and a refused thread costs that connection. --- crates/fctl-agent/src/share/mod.rs | 40 ++++++++++++++----- crates/fctl-agent/src/share/tests.rs | 21 ++++++++++ .../fctl-host/src/driver/firecracker/mod.rs | 22 ++++++---- crates/fctl-host/src/driver/firecracker/vm.rs | 6 +++ 4 files changed, 73 insertions(+), 16 deletions(-) diff --git a/crates/fctl-agent/src/share/mod.rs b/crates/fctl-agent/src/share/mod.rs index 61b3b436..3e1516b4 100644 --- a/crates/fctl-agent/src/share/mod.rs +++ b/crates/fctl-agent/src/share/mod.rs @@ -142,19 +142,41 @@ pub fn serve(dir: &Path, socket: &Path) -> Result<()> { continue; } }; - let serving = serving.clone(); - serving.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - std::thread::spawn(move || { - let mut session = Session::new(root); - if let Err(e) = session.run(conn) { - tracing::debug!("a connection ended: {e}"); - } - serving.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); - }); + let slot = Slot::take(&serving); + let spawned = std::thread::Builder::new() + .name("share".into()) + .spawn(move || { + // Given back however the session ends, a panic too. + let _slot = slot; + let mut session = Session::new(root); + if let Err(e) = session.run(conn) { + tracing::debug!("a connection ended: {e}"); + } + }); + if let Err(e) = spawned { + tracing::warn!("refused a connection: {e}"); + pause(); + } } Ok(()) } +/// One of the connections [`serve`] serves at once, given back as it goes. +struct Slot(std::sync::Arc); + +impl Slot { + fn take(serving: &std::sync::Arc) -> Self { + serving.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Self(serving.clone()) + } +} + +impl Drop for Slot { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + /// The client may hold a fid for each file it has in use, each an open /// file here: as many as the system lets this process have. fn raise_open_files() { diff --git a/crates/fctl-agent/src/share/tests.rs b/crates/fctl-agent/src/share/tests.rs index a25bfd37..cf5e1fa6 100644 --- a/crates/fctl-agent/src/share/tests.rs +++ b/crates/fctl-agent/src/share/tests.rs @@ -451,3 +451,24 @@ fn serves_on_a_unix_socket() -> anyhow::Result<()> { assert_eq!(conn.read_to_end(&mut rest)?, 0); Ok(()) } + +/// A connection that ends, a session that panics too, takes up no more of +/// the connections the server serves at once. +#[test] +fn a_connection_gives_its_slot_back_however_it_ends() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + let serving = Arc::new(AtomicUsize::new(0)); + let slot = Slot::take(&serving); + let other = Slot::take(&serving); + assert_eq!(serving.load(Ordering::Relaxed), 2); + let panicked = std::thread::spawn(move || { + let _slot = slot; + panic!("a session that panics"); + }) + .join(); + assert!(panicked.is_err()); + assert_eq!(serving.load(Ordering::Relaxed), 1); + drop(other); + assert_eq!(serving.load(Ordering::Relaxed), 0); +} diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index a4c06aec..f65d7399 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -722,13 +722,19 @@ impl FirecrackerDriver { .context("passt is not installed: it gives the VMs their network")?; vm.link_network(&passt).await?; } - // Its server of the package caches is gone: another, which - // the VM mounts in place of the mount the old one left. - if let Some(share) = self.share_of(spec).await? - && !vm.sharing() - { + // Its server of the package caches is gone, or never got + // going: another, which the VM mounts in place of the mount + // the old one left. + if matches!(spec.cache, Some(Spot::Dir(_))) && !vm.sharing() { log(format!("Serving the package caches of {} again", spec.name)); - self.share_caches(&vm, &spec.name, &share, log).await; + match self.share_of(spec).await { + Ok(Some(share)) => self.share_caches(&vm, &spec.name, &share, log).await, + Ok(None) => {} + Err(e) => log(format!( + "The package caches couldn't be served to {} ({e:#}), so this session's package managers keep their own downloads", + spec.name + )), + } } return Ok(sb); } @@ -821,7 +827,8 @@ impl FirecrackerDriver { } /// Serves `share` to the VM, which is up, and mounts it there. Without - /// it, the session runs on without package caches, and its log says so. + /// it, the session runs on without package caches, and its log says so; + /// no server stays, so that the VM's next start serves them again. async fn share_caches(&self, vm: &Vm, name: &str, share: &vm::Share, log: Log<'_>) { let shared = async { vm.serve_share(share).await?; @@ -829,6 +836,7 @@ impl FirecrackerDriver { } .await; if let Err(e) = shared { + vm.stop_share().await; log(format!( "The package caches couldn't be mounted in {name} ({e:#}), so this session's package managers keep their own downloads" )); diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 2f28155c..cf3e0f24 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -266,6 +266,7 @@ impl Vm { while !self.share().exists() { if Instant::now() > until || self.pid("share").is_none() { let said = std::fs::read_to_string(self.dir.join("share.log")).unwrap_or_default(); + self.stop_share().await; bail!("fctl-agent share did not start: {}", said.trim()); } tokio::time::sleep(Duration::from_millis(20)).await; @@ -273,6 +274,11 @@ impl Vm { Ok(()) } + /// Stops `fctl-agent share`, if it serves the VM. + pub async fn stop_share(&self) { + self.kill_one("share").await; + } + /// A connection to `port` in the VM, through Firecracker's vsock /// socket, once something there takes it, within `within`. async fn connect_port( From 3babf1e2daa29a1afba8da883c46a10c80dae307 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:30:51 +0000 Subject: [PATCH 19/26] fix(host): write passt's pid where it can as root, and boot a sandbox as root in CI passt opens its pid file as it starts, as root but for its capabilities on a host that runs as root, then becomes nobody: it can write only in a directory root owns, and, under Ubuntu's AppArmor profile, only under /tmp or home. Its pid now goes beside the VM's socket directory, in the host's user's directory in /tmp, which both allow, and CI boots a sandbox as root too. --- .github/workflows/ci.yml | 7 ++++ crates/fctl-host/src/driver/firecracker/vm.rs | 38 +++++++++++++------ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e181f00e..ffe980f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,6 +139,13 @@ jobs: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + - name: Boot a sandbox on a host that runs as root + env: + FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + run: | + bin=$(cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + sudo env "FCTL_TEST_FIRECRACKER_AGENT=$FCTL_TEST_FIRECRACKER_AGENT" "FCTL_TEST_FIRECRACKER_DATA=$RUNNER_TEMP/root" \ + "$bin" driver::firecracker::tests::boots_a_sandbox --ignored --nocapture # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index e364cd5d..f372ae97 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -63,6 +63,9 @@ pub struct Spec { pub struct Vm { pub dir: PathBuf, pub run: PathBuf, + /// What tells the VM's processes from others': the start of the + /// SHA-256 of `dir`, which names `run` too. + pub key: String, } /// Where VMs' sockets go: a directory of this user's in /tmp, private. @@ -95,7 +98,7 @@ impl Vm { pub fn new(dir: PathBuf) -> Result { let key = hex::encode(&Sha256::digest(dir.display().to_string().as_bytes())[..8]); let run = socket_base()?.join(format!("vm-{key}")); - Ok(Self { dir, run }) + Ok(Self { dir, run, key }) } pub fn api(&self) -> PathBuf { @@ -133,10 +136,12 @@ impl Vm { let ours = self.run.display().to_string(); // A kernel thread, which may take the id too, has no executable. let starting = cmdline.is_empty() && std::fs::read_link(format!("/proc/{pid}/exe")).is_ok(); + // passt has its pid's file beside `run`, named by this VM's key. let mine = starting - || cmdline - .split(|b| *b == 0) - .any(|arg| String::from_utf8_lossy(arg).starts_with(&ours)); + || cmdline.split(|b| *b == 0).any(|arg| { + let arg = String::from_utf8_lossy(arg); + arg.starts_with(&ours) || arg.contains(&self.key) + }); (mine && !zombie).then_some(pid) } @@ -196,7 +201,7 @@ impl Vm { pub async fn link_network(&self, passt: &Path) -> Result<()> { self.kill_one("passt").await; let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; - let ready = self.run.join("passt.pid"); + let ready = self.passt_pid(); let _ = std::fs::remove_file(&ready); let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); @@ -376,6 +381,16 @@ impl Vm { self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); + let _ = std::fs::remove_file(self.passt_pid()); + } + + /// Where passt writes its pid: beside `run`, in the host's user's + /// directory in /tmp, where passt's AppArmor profile lets it write, and + /// where it can as it starts on a host that runs as root, as root but + /// for its capabilities, which it drops first. + fn passt_pid(&self) -> PathBuf { + self.run + .with_file_name(format!("vm-{}.passt.pid", self.key)) } /// Kills the VM's process `what`, if it runs. @@ -464,10 +479,10 @@ fn response(buf: &[u8]) -> Result> { } /// The arguments of `passt` for a VM whose link is its input, and which -/// writes its pid to `pid` (in the VM's directory of sockets, whose path -/// tells it from other processes): the options of passt's releases since -/// 2022, which Ubuntu 24.04 and Debian 12 have. The VM names itself, so -/// passt's DHCP needs no `--hostname`, which came later. +/// writes its pid to `pid` (whose path tells it from other processes): the +/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 +/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which +/// came later. On a host that runs as root, passt runs as nobody. fn passt_args(pid: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ @@ -636,6 +651,7 @@ mod tests { let vm = Vm { dir: PathBuf::from("/data/firecracker/sandboxes/fctl-ses-1"), run: PathBuf::from("/tmp/fctl-ada/vm-0123"), + key: "0123".into(), }; let spec = Spec { kernel: "/k/vmlinux".into(), @@ -681,10 +697,10 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/passt.pid")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0.passt.pid")).join(" "); assert_eq!( args, - "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0/passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" + "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0.passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } From 53e91cd98d3347e2910d32d2755245bd28ff7100 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:35:02 +0000 Subject: [PATCH 20/26] ci: find the test binary to run as root without cargo's colours, and clear passt's pid when a link fails --- .github/workflows/ci.yml | 3 ++- crates/fctl-host/src/driver/firecracker/vm.rs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ffe980f5..9b3d9fda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,7 +143,8 @@ jobs: env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | - bin=$(cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + bin=$(CARGO_TERM_COLOR=never cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + test -x "$bin" sudo env "FCTL_TEST_FIRECRACKER_AGENT=$FCTL_TEST_FIRECRACKER_AGENT" "FCTL_TEST_FIRECRACKER_DATA=$RUNNER_TEMP/root" \ "$bin" driver::firecracker::tests::boots_a_sandbox --ignored --nocapture diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index f372ae97..0c9fd4a3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -403,6 +403,9 @@ impl Vm { } } let _ = std::fs::remove_file(self.pid_file(what)); + if what == "passt" { + let _ = std::fs::remove_file(self.passt_pid()); + } } /// Stops the VM and removes its files. @@ -1012,7 +1015,7 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked()); + assert!(!vm.linked() && !vm.passt_pid().exists()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 9080e50ad42f4334d42cb035f998dc093abfbebc Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:44:17 +0000 Subject: [PATCH 21/26] fix(host): write passt's pid in /tmp as root, under a name no one can make first Ubuntu's passt of 2024 drops to nobody before it opens its pid's file, and later ones open it as root without capabilities: on a host that runs as root, only /tmp lets both write. The name has a random part, recorded in the VM's directory. --- crates/fctl-host/src/driver/firecracker/vm.rs | 56 ++++++++++++++----- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 0c9fd4a3..5367c16f 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -201,8 +201,7 @@ impl Vm { pub async fn link_network(&self, passt: &Path) -> Result<()> { self.kill_one("passt").await; let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; - let ready = self.passt_pid(); - let _ = std::fs::remove_file(&ready); + let ready = self.new_passt_pid()?; let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); cmd.args(passt_args(&ready)) @@ -381,16 +380,44 @@ impl Vm { self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); - let _ = std::fs::remove_file(self.passt_pid()); } - /// Where passt writes its pid: beside `run`, in the host's user's - /// directory in /tmp, where passt's AppArmor profile lets it write, and - /// where it can as it starts on a host that runs as root, as root but - /// for its capabilities, which it drops first. - fn passt_pid(&self) -> PathBuf { - self.run - .with_file_name(format!("vm-{}.passt.pid", self.key)) + /// Where passt writes its pid, the path naming this VM's key, which + /// tells passt from other processes; recorded in the VM's directory. + /// Beside `run`, in the host's user's directory in /tmp, where passt's + /// AppArmor profile lets it write. On a host that runs as root, passt + /// opens it as nobody (passt of 2024) or as root without its + /// capabilities (later ones), which only /tmp itself lets write: there + /// its name has a random part no one else could make first. + fn new_passt_pid(&self) -> Result { + if let Some(old) = self.passt_pid() { + let _ = std::fs::remove_file(old); + } + let pid = if nix::unistd::geteuid().is_root() { + PathBuf::from(format!( + "/tmp/fctl-passt-{}-{}.pid", + self.key, + hex::encode(fctl_domain::random_bytes::<8>()) + )) + } else { + self.run + .with_file_name(format!("vm-{}.passt.pid", self.key)) + }; + std::fs::create_dir_all(&self.dir)?; + std::fs::write( + self.dir.join("passt.pid-file"), + pid.as_os_str().as_encoded_bytes(), + )?; + Ok(pid) + } + + /// Where passt writes its pid ([`new_passt_pid`](Self::new_passt_pid)). + fn passt_pid(&self) -> Option { + let path = std::fs::read_to_string(self.dir.join("passt.pid-file")).ok()?; + let path = PathBuf::from(path.trim()); + let name = path.file_name()?.to_string_lossy().into_owned(); + // Only what this VM named so: nothing else of the host's goes. + (name.contains(&self.key) && name.ends_with(".pid")).then_some(path) } /// Kills the VM's process `what`, if it runs. @@ -403,8 +430,11 @@ impl Vm { } } let _ = std::fs::remove_file(self.pid_file(what)); - if what == "passt" { - let _ = std::fs::remove_file(self.passt_pid()); + if what == "passt" + && let Some(pid) = self.passt_pid() + { + let _ = std::fs::remove_file(pid); + let _ = std::fs::remove_file(self.dir.join("passt.pid-file")); } } @@ -1015,7 +1045,7 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked() && !vm.passt_pid().exists()); + assert!(!vm.linked() && vm.passt_pid().is_none_or(|p| !p.exists())); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 0ad0dd0fed3c27907005362ca4118ef53c89889d Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:54:05 +0000 Subject: [PATCH 22/26] test(host): check that a failed link removes the pid's file passt was told A failed link now forgets where passt's pid went, so the test reads the path from the stand-in, which says where it was told to write. --- crates/fctl-host/src/driver/firecracker/vm.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 5367c16f..e43e70d3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -1026,11 +1026,16 @@ mod tests { ) }; write_script(&passt, &stand_in("echo $$ > \"$pid\"\ncat >&0"))?; - // One that fails as it sets itself up. + // One that fails as it sets itself up, and tells where its pid's + // file was. let failing = dir.path().join("failing-passt"); + let told = dir.path().join("failing-passt.told"); write_script( &failing, - &stand_in("echo 'No routable interface' >&2; exit 1"), + &stand_in(&format!( + "echo \"$pid\" > '{}'\necho 'No routable interface' >&2; exit 1", + told.display() + )), )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; @@ -1045,7 +1050,9 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked() && vm.passt_pid().is_none_or(|p| !p.exists())); + let made = PathBuf::from(std::fs::read_to_string(&told)?.trim()); + assert!(made.is_absolute(), "{made:?}"); + assert!(!vm.linked() && !made.exists() && vm.passt_pid().is_none()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 5d72ba96fca47f14a8ec3e043743e76e48ebe53a Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:26:51 +0000 Subject: [PATCH 23/26] fix(agent): allow the link count's conversion, which aarch64 needs and x86_64 doesn't --- crates/fctl-agent/src/share/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/fctl-agent/src/share/mod.rs b/crates/fctl-agent/src/share/mod.rs index 3e1516b4..ed8c8a7d 100644 --- a/crates/fctl-agent/src/share/mod.rs +++ b/crates/fctl-agent/src/share/mod.rs @@ -532,13 +532,16 @@ impl Session { let f = self.fid(r.u32()?)?; let _mask = r.u64()?; let st = stat_of(&f.fd)?; + // `st_nlink` is a u32 on aarch64 and a u64 on x86_64. + #[allow(clippy::useless_conversion)] + let nlink = u64::from(st.st_nlink); let mut w = reply(t); w.u64(GETATTR_BASIC) .qid(qid(&st)) .u32(st.st_mode) .u32(self.owner.0) .u32(self.owner.1) - .u64(u64::from(st.st_nlink)) + .u64(nlink) .u64(st.st_rdev) .u64(u64::try_from(st.st_size).unwrap_or(0)) .u64(u64::try_from(st.st_blksize).unwrap_or(4096)) From bb99da288a426dcc731917b68e68ce3c2bea839a Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sat, 7 Nov 2026 00:01:01 +0000 Subject: [PATCH 24/26] fix(host): bind a jailed VM's cache socket where its path stays short, and link it into the jail Under a long data directory, the cache server's socket in a jail's chroot passed the 108 bytes a socket's path may have, so jailed sessions ran without caches. The server now listens in the VM's socket directory, which is on the jail's filesystem, and the host links that socket into the chroot, given to the jail's user, in place of whatever the jail put there. The security docs' caches threat model names Firecracker's. --- crates/fctl-host/src/driver/firecracker/vm.rs | 71 ++++++++++++------- docs/architecture.md | 5 +- docs/security.md | 4 +- 3 files changed, 52 insertions(+), 28 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 82984449..2527ce46 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -194,15 +194,12 @@ impl Vm { /// Where `fctl-agent share` serves the VM's [`Share`]: what Firecracker /// connects to when the VM connects to the host's [`SHARE_PORT`]. - /// Where the VM's connections to [`SHARE_PORT`] come: beside its vsock - /// socket, or in its chroot for a jailed VM, whose Firecracker connects - /// there. + /// Where the cache server listens for the VM's connections to + /// [`SHARE_PORT`]: beside its vsock socket, under `run`, short as + /// sockets' paths must be. A jailed VM's Firecracker connects in its + /// chroot, where the host links the socket ([`serve_share`](Self::serve_share)). pub fn share(&self) -> PathBuf { - let name = format!("v.sock_{SHARE_PORT}"); - match self.jail() { - Some((root, _)) => root.join(name), - None => self.run.join(name), - } + self.run.join(format!("v.sock_{SHARE_PORT}")) } /// The chroot of this VM's jail and the jail's uid, when it runs in one. @@ -526,11 +523,23 @@ impl Vm { } tokio::time::sleep(Duration::from_millis(20)).await; } - // A jailed Firecracker connects as the jail's user, which needs the - // socket to be its own; not following a link the jail put there. - if let Some((_, uid)) = self.jail() { - std::os::unix::fs::lchown(self.share(), Some(uid), Some(uid)) - .context("giving the cache server's socket to the VM's jail")?; + // A jailed Firecracker connects in its chroot, as the jail's user: + // the socket, given to that user, is linked there (`run` is on the + // chroot's filesystem, beside it), in place of what the jail put + // there, which a link replaces without following. + if let Some((root, uid)) = self.jail() { + let given = async { + std::os::unix::fs::lchown(self.share(), Some(uid), Some(uid))?; + let inside = root.join(format!("v.sock_{SHARE_PORT}")); + let _ = std::fs::remove_file(&inside); + std::fs::hard_link(self.share(), &inside)?; + Ok::<_, std::io::Error>(()) + } + .await; + if let Err(e) = given { + self.stop_share().await; + return Err(e).context("giving the cache server's socket to the VM's jail"); + } } Ok(()) } @@ -1464,44 +1473,56 @@ mod tests { Ok(()) } - /// A jailed VM's Firecracker connects to the cache server from its - /// chroot, as the jail's user: the server listens there, on a socket - /// of that user's. + /// A jailed VM's Firecracker connects to the cache server in its chroot, + /// as the jail's user: the server listens under `run`, whose path is + /// short whatever the data directory's, and the host links its socket + /// into the chroot, given to that user. #[tokio::test] async fn a_jailed_vms_caches_are_served_in_its_jail() -> Result<()> { use crate::driver::fake::write_script; + use std::os::unix::fs::MetadataExt; let dir = tempfile::tempdir()?; let agent = dir.path().join("fctl-agent"); write_script( &agent, "#!/bin/sh\nfor a; do [ \"$prev\" = --socket ] && touch \"$a\"; prev=$a; done\nsleep 60\n", )?; - let jails = dir.path().join("jail"); + // A data directory with a long path, as a jail's sockets can't have. + let jails = dir.path().join("a".repeat(60)).join("jail"); let vm = Vm::new(dir.path().join("fctl-ses-j"))?.with_jails(jails.clone()); std::fs::create_dir_all(&vm.dir)?; - assert_eq!(vm.share(), vm.run.join(format!("v.sock_{SHARE_PORT}"))); - // The jail `make_jail` leaves, here with this user's uid, which only - // root could make another's. + // The jail `make_jail` and `start_jailed` leave, here with this + // user's uid, which only root could make another's. let jail = jails.join("firecracker-v1.17.0").join(&vm.key); std::fs::create_dir_all(jail.join("root"))?; + std::fs::create_dir_all(jail.join("run"))?; + std::fs::create_dir_all(vm.run.parent().context("no parent")?)?; + let _ = std::fs::remove_file(&vm.run); + std::os::unix::fs::symlink(jail.join("run"), &vm.run)?; let uid = nix::unistd::geteuid().as_raw(); let lent = Lent { uid, writable: Vec::new(), }; std::fs::write(jail.join("jail.json"), serde_json::to_vec(&lent)?)?; + // What the jail put where the link goes. + let inside = jail.join("root").join(format!("v.sock_{SHARE_PORT}")); + std::os::unix::fs::symlink("/etc/passwd", &inside)?; let share = Share { agent, dir: dir.path().to_owned(), }; vm.serve_share(&share).await?; - assert_eq!( - vm.share(), - jail.join("root").join(format!("v.sock_{SHARE_PORT}")) - ); - assert!(vm.sharing() && vm.share().exists()); + assert!(vm.share().starts_with(&vm.run)); + assert!(vm.share().as_os_str().len() < 100); + assert!(vm.sharing()); + let linked = std::fs::symlink_metadata(&inside)?; + assert!(linked.is_file()); + assert_eq!(linked.ino(), std::fs::metadata(vm.share())?.ino()); + assert_eq!(linked.uid(), uid); vm.stop_share().await; assert!(!vm.sharing()); + std::fs::remove_file(&vm.run)?; Ok(()) } diff --git a/docs/architecture.md b/docs/architecture.md index e7eff87f..95e52c52 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3541,8 +3541,9 @@ and a filesystem that allows device files (it makes `/dev/kvm` in the chroot): without either, the driver isn't ready and says what to change. `passt` runs outside the jail and drops to `nobody` itself; its pid's file goes in `/tmp` under a name with a random part. A jailed VM's cache -server listens in its chroot, where Firecracker connects for the VM, on a -socket given to the jail's user. +server listens in the VM's socket directory, whose path stays short, and +the host links that socket, given to the jail's user, into the chroot, +where Firecracker connects for the VM. ### Package caches diff --git a/docs/security.md b/docs/security.md index 2151c11e..f40ec1f2 100644 --- a/docs/security.md +++ b/docs/security.md @@ -488,7 +488,9 @@ its VM, and nothing outside it except through these channels: - **Package caches.** In a project that shares them (`fctl projects set --package-caches on`), its sessions on a runner share what their package managers download, in a Docker volume or, with Apple's `container`, a - directory on the Mac that each sandbox mounts. Anything a session runs + directory on the Mac that each sandbox mounts, or, with Firecracker, a + directory on the runner that the host serves to each VM over 9P. + Anything a session runs can change what they hold, and the project's later sessions on that runner build with it: package managers check a download against a lockfile's hashes as they fetch it, but most don't check again what is From 9f6194056fce65935f22e7df56aaf66e4206fc4b Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sat, 7 Nov 2026 00:04:37 +0000 Subject: [PATCH 25/26] docs(host): say once, in share's doc comment, where Firecracker connects to the cache server --- crates/fctl-host/src/driver/firecracker/vm.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 2527ce46..2bcab05e 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -192,12 +192,11 @@ impl Vm { self.run.join("v.sock") } - /// Where `fctl-agent share` serves the VM's [`Share`]: what Firecracker - /// connects to when the VM connects to the host's [`SHARE_PORT`]. - /// Where the cache server listens for the VM's connections to - /// [`SHARE_PORT`]: beside its vsock socket, under `run`, short as - /// sockets' paths must be. A jailed VM's Firecracker connects in its - /// chroot, where the host links the socket ([`serve_share`](Self::serve_share)). + /// Where `fctl-agent share` serves the VM's [`Share`], for the VM's + /// connections to the host's [`SHARE_PORT`]: beside its vsock socket, + /// under `run`, short as sockets' paths must be. Firecracker connects + /// here, or, for a jailed VM, at a link of it that the host puts in the + /// chroot ([`serve_share`](Self::serve_share)). pub fn share(&self) -> PathBuf { self.run.join(format!("v.sock_{SHARE_PORT}")) } From 48c260a74cb12e68cd259daa17a182b4f9616b15 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Sat, 7 Nov 2026 00:14:33 +0000 Subject: [PATCH 26/26] fix(host): serve and mount a resumed VM's package caches again With snapshots (#431), a stopped sandbox resumes with its cache mount on a connection whose server stopped with the VM, so its package managers got 'Connection reset by peer'. A resume now serves the caches again and the VM mounts them in place of the old mount, as a running VM whose server is gone gets. docs/cli.md says that Firecracker keeps its caches in the same directory as Apple's container. --- .../fctl-host/src/driver/firecracker/mod.rs | 41 ++++++++++++------- docs/cli.md | 7 ++-- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index ce687a53..2fdf8464 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1037,20 +1037,7 @@ impl FirecrackerDriver { .context("passt is not installed: it gives the VMs their network")?; vm.link_network(&passt).await?; } - // Its server of the package caches is gone, or never got - // going: another, which the VM mounts in place of the mount - // the old one left. - if matches!(spec.cache, Some(Spot::Dir(_))) && !vm.sharing() { - log(format!("Serving the package caches of {} again", spec.name)); - match self.share_of(spec).await { - Ok(Some(share)) => self.share_caches(&vm, &spec.name, &share, log).await, - Ok(None) => {} - Err(e) => log(format!( - "The package caches couldn't be served to {} ({e:#}), so this session's package managers keep their own downloads", - spec.name - )), - } - } + self.serve_caches_again(&vm, spec, log).await; return Ok(sb); } log(format!( @@ -1068,7 +1055,12 @@ impl FirecrackerDriver { && !self.resized(&vm, spec, log) { match self.resume_saved(&vm, &spec.name, &saved, log).await { - Ok(()) => return Ok(sb), + Ok(()) => { + // Its server of the caches stopped with the VM, whose + // mount resumed with a connection that is gone. + self.serve_caches_again(&vm, spec, log).await; + return Ok(sb); + } Err(e) => log(format!( "{} couldn't resume where it stopped ({e:#}), so it starts again from its disk", spec.name @@ -1170,6 +1162,25 @@ impl FirecrackerDriver { })) } + /// Serves the package caches to a running VM whose server of them is + /// gone (it stopped with the VM whose state the VM resumed, say) or + /// never got going: another, which the VM mounts in place of the mount + /// the old one left. + async fn serve_caches_again(&self, vm: &Vm, spec: &SandboxSpec, log: Log<'_>) { + if !matches!(spec.cache, Some(Spot::Dir(_))) || vm.sharing() { + return; + } + log(format!("Serving the package caches of {} again", spec.name)); + match self.share_of(spec).await { + Ok(Some(share)) => self.share_caches(vm, &spec.name, &share, log).await, + Ok(None) => {} + Err(e) => log(format!( + "The package caches couldn't be served to {} ({e:#}), so this session's package managers keep their own downloads", + spec.name + )), + } + } + /// Serves `share` to the VM, which is up, and mounts it there. Without /// it, the session runs on without package caches, and its log says so; /// no server stays, so that the VM's next start serves them again. diff --git a/docs/cli.md b/docs/cli.md index bed3cc2a..e790de7c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -995,9 +995,10 @@ has, and run `fctl host restart` after changing either. For projects that share package caches (`fctl projects set --package-caches on`), the host keeps what their sessions' package managers download: with Docker in a volume per project, -`fctl-cache-`, and with Apple's `container` in a directory of -its data directory, `caches/`, that its sandboxes mount at -`/var/cache/fctl`. The sweep that removes stopped sandboxes, when the host +`fctl-cache-`, and with Apple's `container` and Firecracker in +a directory of its data directory, `caches/`, that its +sandboxes mount at `/var/cache/fctl` (Firecracker's over 9P on their +vsock). The sweep that removes stopped sandboxes, when the host starts and every hour, looks after them too: - It measures the caches that a session used since they were last