diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f97d4c0d..c33343fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -146,7 +146,8 @@ jobs: 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 + "$bin" driver::firecracker::tests::boots_a_sandbox driver::firecracker::tests::sandboxes_of_a_project_share_its_package_caches \ + --ignored --nocapture --test-threads 1 # Jails lend disks to their users, which only root can. sudo "$bin" driver::firecracker::vm::tests::stale_jails_go --exact --nocapture # Whiteouts kept as overlayfs reads them, for images that lie over diff --git a/Cargo.lock b/Cargo.lock index aabab70c..38e11bd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -542,6 +542,7 @@ dependencies = [ "fctl-proto", "flate2", "hex", + "libc", "nix", "serde", "serde_json", diff --git a/crates/fctl-agent/Cargo.toml b/crates/fctl-agent/Cargo.toml index b477ded1..1d771c75 100644 --- a/crates/fctl-agent/Cargo.toml +++ b/crates/fctl-agent/Cargo.toml @@ -27,6 +27,7 @@ tracing-subscriber.workspace = true [target.'cfg(target_os = "linux")'.dependencies] flate2.workspace = true hex.workspace = true +libc.workspace = true nix = { workspace = true, features = ["hostname", "mount", "net", "reboot", "resource", "socket", "time"] } sha2.workspace = true tar.workspace = true 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..ed8c8a7d --- /dev/null +++ b/crates/fctl-agent/src/share/mod.rs @@ -0,0 +1,984 @@ +//! `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 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"; + +/// `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()); + 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 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() { + 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, + /// 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. + xattr: bool, +} + +impl Fid { + fn new(fd: OwnedFd, kind: Kind) -> Self { + Self { + fd, + kind, + open: None, + locks: 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) + } + + /// 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); + } + 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)?; + // `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(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 fid = r.u32()?; + let kind = r.u8()?; + let _flags = r.u32()?; + let start = r.u64()?; + let length = r.u64()?; + 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, + }; + let mut w = reply(t); + w.u8(status); + Ok(w.finish()) + } + kind::TGETLOCK => { + 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 mut fl = flock(kind, start, length)?; + 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) + .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..cf5e1fa6 --- /dev/null +++ b/crates/fctl-agent/src/share/tests.rs @@ -0,0 +1,474 @@ +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())?; + // 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, mode).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"); + // 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(); + 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-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/assets.rs b/crates/fctl-host/src/driver/firecracker/assets.rs index 1cd80d2e..075782da 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 { diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index bf2bd697..2fdf8464 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -18,6 +18,11 @@ //! 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`]). +//! - **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; mod builds; @@ -32,6 +37,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}; @@ -1031,6 +1037,7 @@ impl FirecrackerDriver { .context("passt is not installed: it gives the VMs their network")?; vm.link_network(&passt).await?; } + self.serve_caches_again(&vm, spec, log).await; return Ok(sb); } log(format!( @@ -1048,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 @@ -1092,6 +1104,7 @@ impl FirecrackerDriver { let passt = self .passt() .context("passt is not installed: it gives the VMs their network")?; + let share = self.share_of(spec).await?; let boot = Spec { kernel, initrd, @@ -1128,9 +1141,94 @@ impl FirecrackerDriver { } record.agent = Some(agent); self.save_record(&spec.name, &record)?; + 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 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. + 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 { + 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" + )); + } + } + + /// 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 @@ -2287,6 +2385,114 @@ mod tests { 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. + // 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 + .exec( + b, + "flock -n /var/cache/fctl/.package-cache true && echo free || echo held", + ) + .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?; + 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 + } + /// Builds an image from a Dockerfile with BuildKit in a VM, and boots a /// sandbox from it: its files, modes, user, environment and working /// directory as the Dockerfile says. As [`boots_a_sandbox`] says. diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 9710ce1b..1ceaf749 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::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; @@ -61,6 +62,15 @@ pub struct Spec { pub network: bool, } +/// 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 /// the processes' ids; `run`, a short path (unix sockets' paths are /// limited to about 100 bytes), its sockets. @@ -186,6 +196,24 @@ impl Vm { self.run.join("v.sock") } + /// 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}")) + } + + /// The chroot of this VM's jail and the jail's uid, when it runs in one. + fn jail(&self) -> Option<(PathBuf, u32)> { + self.jail_dirs().into_iter().find_map(|dir| { + let lent: Lent = + serde_json::from_slice(&std::fs::read(dir.join("jail.json")).ok()?).ok()?; + Some((dir.join("root"), lent.uid)) + }) + } + pub fn console(&self) -> PathBuf { self.dir.join("console.log") } @@ -466,6 +494,64 @@ impl Vm { Ok(()) } + /// 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") + .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(); + self.stop_share().await; + bail!("fctl-agent share did not start: {}", said.trim()); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + // 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(()) + } + + /// 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( @@ -712,7 +798,7 @@ impl Vm { /// Kills the VM's processes. pub async fn kill(&self) { - for what in ["firecracker", "passt"] { + for what in ["firecracker", "passt", "share"] { self.kill_one(what).await; } // A link to its jail, as an earlier fctl made, or its own directory. @@ -1509,6 +1595,59 @@ mod tests { Ok(()) } + /// 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", + )?; + // 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)?; + // 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!(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(()) + } + #[test] fn a_vm_runs_only_while_its_process_does() -> Result<()> { let dir = tempfile::tempdir()?; @@ -1830,10 +1969,26 @@ mod tests { )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; + // fctl-agent share, which makes its socket and waits. + let share = dir.path().join("fctl-agent"); + write_script( + &share, + "#!/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 = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); vm.start(&spec, &firecracker, None).await?; - assert!(vm.running() && !vm.linked()); + 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, // though an earlier passt's pid is where this one's goes. @@ -1903,7 +2058,7 @@ mod tests { // A start that fails leaves nothing running. let missing = dir.path().join("no-firecracker"); assert!(vm.start(&spec, &missing, None).await.is_err()); - assert!(!vm.linked() && !vm.running()); + assert!(!vm.linked() && !vm.running() && vm.pid("share").is_none()); let _ = std::fs::remove_dir_all(&other.run); Ok(()) } diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index ca3075ee..200b4272 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -582,10 +582,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 { @@ -593,8 +593,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, } } @@ -610,8 +610,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 9fad03f9..33d91954 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -12,7 +12,8 @@ //! 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. +//! as passt reads them from QEMU. The VM reaches the host's [`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 @@ -28,6 +29,10 @@ pub const PORT: u32 = 1024; /// (`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 37216679..9563eb7e 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 @@ -85,8 +85,11 @@ microVM of its own. session #802, a host that runs as root does, unless `host.toml` sets `jailer = false`: each VM as a user of its own, in a chroot and a cgroup of its own.) -- 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. (Since session #802, an image whose layers start with another's keeps diff --git a/docs/architecture.md b/docs/architecture.md index fb672466..a79e2b2d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3535,9 +3535,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, -so a VM escape would run as that user. A host that runs as root runs +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, so a VM escape would run as that +user. A host that runs as root runs each VM through Firecracker's jailer instead (`[firecracker] jailer`, true unless set otherwise; the jailer comes with the pinned release, or sits beside the Firecracker `host.toml` names, as `jailer` or as the @@ -3559,7 +3560,10 @@ or crashed left, go before the next VM starts. The jailer needs cgroup v2 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. +file goes in `/tmp` under a name with a random part. A jailed VM's cache +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 @@ -3577,11 +3581,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 0b31ad18..e790de7c 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 @@ -886,8 +886,9 @@ runs each VM through Firecracker's jailer, as a user of its own in a chroot, unless `jailer = false` in `host.toml`'s `[firecracker]`; that needs cgroup v2 and a data directory on a filesystem that allows device files, and `fctl host doctor` says when either is missing. Its sandboxes -get no package caches, and it builds projects' images with BuildKit in a -VM of each project's own; projects' own images run as with Docker. +mount their project's package caches from the host over their vsock, and +it builds projects' images with BuildKit in a VM of each project's own; +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: @@ -994,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 diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md index be3a67b1..6e6efb73 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -145,9 +145,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 2e09e3fb..f40ec1f2 100644 --- a/docs/security.md +++ b/docs/security.md @@ -219,10 +219,17 @@ 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 - with its seccomp filters, as the host's user: a VM escape would run as - that user, who can read the runner's token, as a container escape can + 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 with its seccomp filters, as the host's user: a VM escape would run + as that user, who can read the runner's token, as a container escape can with Docker. A host that runs as root runs each VM through Firecracker's jailer instead (unless `host.toml` sets `jailer = false`): as a user of its own, which no other running VM and nothing else on the machine runs @@ -230,8 +237,8 @@ its VM, and nothing outside it except through these channels: in a cgroup of its own, so that an escape reaches neither the host's files nor another VM's. The host reaches the VM's sockets through links of its own, so a jail can't send it to another VM's, and takes the VM's - disk back from the jail's user when it stops. Their images unpack in a VM of their own, so a crafted - layer can't reach the host's filesystem. + disk back from the jail's user when it stops. Their images unpack in a + VM of their own, so a crafted layer can't reach the host's filesystem. - **fctl-agent** runs as root in the sandbox, and Claude and everything it runs as the image's user, so that the agent's commands can't stop @@ -481,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