Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
357 lines
15 KiB
Rust
357 lines
15 KiB
Rust
//! The sealed KAR archive, made by the service itself (no helper process, no Python).
|
|
//!
|
|
//! `leleka run` copies the archive once into an irrevocably sealed `memfd` and keeps it for its whole life, so an
|
|
//! engine restart does not copy 55 GB again. The engine refuses anything but a regular, unlinked file of the
|
|
//! pinned length with `WRITE | GROW | SHRINK | SEAL` seals (`InheritedKarArchive::open`). The descriptor is
|
|
//! `CLOEXEC` in the supervisor and reaches only the engine: the supervisor hands a duplicate to `leleka
|
|
//! exec-inherit` as standard input, and that shim moves it to a descriptor number >= 3 without close-on-exec and
|
|
//! `exec`s the engine, which reopens it through `/proc/self/fd/N`.
|
|
#[cfg(target_os = "linux")]
|
|
pub use linux::*;
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn seal_file(
|
|
_path: &std::path::Path,
|
|
_expect_bytes: Option<u64>,
|
|
_progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<std::fs::File, String> {
|
|
Err("sealed memfd archives require Linux".into())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn seal_file_with_identity(
|
|
_path: &std::path::Path,
|
|
_expect_bytes: Option<u64>,
|
|
_progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
std::fs::File,
|
|
Option<leleka_model_format::verify_stamp::FileIdentity>,
|
|
),
|
|
String,
|
|
> {
|
|
Err("sealed memfd archives require Linux".into())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn check_inherited_archive(_fd: u32, _expect_bytes: u64) -> Result<(), String> {
|
|
Err("inherited descriptors require Linux".into())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn open_inherited(_fd: u32) -> Result<std::fs::File, String> {
|
|
Err("inherited descriptors require Linux".into())
|
|
}
|
|
|
|
#[cfg(not(target_os = "linux"))]
|
|
pub fn exec_inherit(_args: &[String]) -> Result<std::convert::Infallible, String> {
|
|
Err("exec-inherit requires Linux".into())
|
|
}
|
|
|
|
pub const PLACEHOLDER: &str = "{FD}";
|
|
|
|
/// Replace every `{FD}` in `args`.
|
|
pub fn substitute(args: &[String], number: i32) -> Vec<String> {
|
|
args.iter()
|
|
.map(|arg| arg.replace(PLACEHOLDER, &number.to_string()))
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod linux {
|
|
use super::substitute;
|
|
use leleka_model_format::verify_stamp::FileIdentity;
|
|
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
|
|
use std::{
|
|
convert::Infallible,
|
|
fs::File,
|
|
os::{
|
|
fd::{AsFd, IntoRawFd},
|
|
unix::{fs::FileExt, process::CommandExt},
|
|
},
|
|
path::Path,
|
|
process::Command,
|
|
sync::{
|
|
Mutex,
|
|
atomic::{AtomicU64, AtomicUsize, Ordering},
|
|
},
|
|
};
|
|
|
|
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
|
|
SealFlags::WRITE.bits()
|
|
| SealFlags::GROW.bits()
|
|
| SealFlags::SHRINK.bits()
|
|
| SealFlags::SEAL.bits(),
|
|
);
|
|
/// Bytes per positional read/write of the parallel fill.
|
|
const COPY_CHUNK: usize = 32 << 20;
|
|
|
|
/// Copy `path` into a new sealed, close-on-exec memfd. `expect_bytes` pins the exact length. `progress` gets
|
|
/// (copied, total) about every 4 GiB.
|
|
pub fn seal_file(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<File, String> {
|
|
seal_file_with_identity(path, expect_bytes, progress).map(|(file, _)| file)
|
|
}
|
|
|
|
/// As [`seal_file`], copying with several threads (positional reads and writes of disjoint 32 MiB ranges into
|
|
/// a memfd of the final size, so a 55 GB fill runs at memory bandwidth instead of one core's `read`+`write`
|
|
/// loop), and returning the identity of the source file when it is a stable one. The identity is taken from the
|
|
/// opened file before the first byte and again after the last; a source that changed while it was copied is
|
|
/// refused, so the identity describes exactly the bytes that are in the memfd.
|
|
pub fn seal_file_with_identity(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<(File, Option<FileIdentity>), String> {
|
|
let source =
|
|
File::open(path).map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
|
let metadata = source
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect the archive: {e}"))?;
|
|
if !metadata.is_file() {
|
|
return Err("the archive must be a regular file".into());
|
|
}
|
|
if let Some(expected) = expect_bytes
|
|
&& metadata.len() != expected
|
|
{
|
|
return Err(format!(
|
|
"the archive has {} bytes, expected {expected}",
|
|
metadata.len()
|
|
));
|
|
}
|
|
let identity_before = FileIdentity::of(&metadata);
|
|
let fd = memfd_create(
|
|
"leleka-sealed-archive",
|
|
MemfdFlags::ALLOW_SEALING | MemfdFlags::CLOEXEC,
|
|
)
|
|
.map_err(|e| format!("memfd_create failed: {e}"))?;
|
|
let memory = File::from(fd);
|
|
let total = metadata.len();
|
|
// The final size first (before the GROW seal exists), so that workers write disjoint ranges.
|
|
memory
|
|
.set_len(total)
|
|
.map_err(|e| format!("cannot size the memfd (out of memory?): {e}"))?;
|
|
let workers = std::thread::available_parallelism()
|
|
.map_or(4, |n| n.get())
|
|
.clamp(2, 8);
|
|
let next = AtomicU64::new(0);
|
|
let copied = AtomicU64::new(0);
|
|
let finished = AtomicUsize::new(0);
|
|
let failure: Mutex<Option<String>> = Mutex::new(None);
|
|
std::thread::scope(|scope| {
|
|
for _ in 0..workers {
|
|
scope.spawn(|| {
|
|
let mut buffer = vec![0u8; COPY_CHUNK];
|
|
loop {
|
|
if failure.lock().is_ok_and(|f| f.is_some()) {
|
|
break;
|
|
}
|
|
let offset = next.fetch_add(COPY_CHUNK as u64, Ordering::Relaxed);
|
|
if offset >= total {
|
|
break;
|
|
}
|
|
let count = (total - offset).min(COPY_CHUNK as u64) as usize;
|
|
let step = source
|
|
.read_exact_at(&mut buffer[..count], offset)
|
|
.map_err(|e| format!("read failed at {offset}: {e}"))
|
|
.and_then(|()| {
|
|
memory.write_all_at(&buffer[..count], offset).map_err(|e| {
|
|
format!("write to memfd failed (out of memory?): {e}")
|
|
})
|
|
});
|
|
match step {
|
|
Ok(()) => {
|
|
copied.fetch_add(count as u64, Ordering::Relaxed);
|
|
}
|
|
Err(message) => {
|
|
if let Ok(mut f) = failure.lock() {
|
|
f.get_or_insert(message);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
finished.fetch_add(1, Ordering::Release);
|
|
});
|
|
}
|
|
let mut reported = 0u64;
|
|
while finished.load(Ordering::Acquire) < workers {
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
let now = copied.load(Ordering::Relaxed);
|
|
if now - reported >= 4 << 30 {
|
|
reported = now;
|
|
progress(now, total);
|
|
}
|
|
}
|
|
});
|
|
if let Some(message) = failure.into_inner().ok().flatten() {
|
|
return Err(message);
|
|
}
|
|
if copied.load(Ordering::Relaxed) != total {
|
|
return Err("the archive changed while it was being copied".into());
|
|
}
|
|
let identity_after = source.metadata().ok().and_then(|m| FileIdentity::of(&m));
|
|
if identity_before != identity_after {
|
|
return Err("the archive changed while it was being copied".into());
|
|
}
|
|
fcntl_add_seals(&memory, SEALS).map_err(|e| format!("sealing failed: {e}"))?;
|
|
if !fcntl_get_seals(&memory)
|
|
.map_err(|e| format!("cannot read seals: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err("the kernel did not apply every seal".into());
|
|
}
|
|
progress(total, total);
|
|
Ok((memory, identity_before))
|
|
}
|
|
|
|
/// A descriptor inherited from the parent (a holder, for example), reopened through `/proc/self/fd/N` as an
|
|
/// independent read-only description. The original number stays open and untouched.
|
|
pub fn open_inherited(fd: u32) -> Result<File, String> {
|
|
if !(3..=1_048_576).contains(&fd) {
|
|
return Err("an inherited descriptor must be 3 or higher".into());
|
|
}
|
|
File::open(format!("/proc/self/fd/{fd}"))
|
|
.map_err(|e| format!("descriptor {fd} is not open in this process: {e}"))
|
|
}
|
|
|
|
/// The descriptor the parent passed with `--kar-fd` must be what the engine will accept: a regular, unlinked
|
|
/// file of the pinned length with every seal. Checked here so that the mistake surfaces before an engine start.
|
|
pub fn check_inherited_archive(fd: u32, expect_bytes: u64) -> Result<(), String> {
|
|
use std::os::unix::fs::MetadataExt;
|
|
let file = open_inherited(fd)?;
|
|
let meta = file
|
|
.metadata()
|
|
.map_err(|e| format!("cannot inspect descriptor {fd}: {e}"))?;
|
|
if !meta.is_file() || meta.nlink() != 0 || meta.len() != expect_bytes {
|
|
return Err(format!(
|
|
"descriptor {fd} is not an unlinked regular file of {expect_bytes} bytes (it has {} bytes, {} links)",
|
|
meta.len(),
|
|
meta.nlink()
|
|
));
|
|
}
|
|
if !fcntl_get_seals(&file)
|
|
.map_err(|e| format!("cannot read the seals of descriptor {fd}: {e}"))?
|
|
.contains(SEALS)
|
|
{
|
|
return Err(format!(
|
|
"descriptor {fd} lacks the WRITE, GROW, SHRINK and SEAL seals"
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `leleka exec-inherit -- COMMAND ARG...`: standard input is the sealed archive. Move it to a descriptor
|
|
/// number >= 3 (inheritable), give the command `/dev/null` as standard input, replace `{FD}` and `exec`.
|
|
pub fn exec_inherit(args: &[String]) -> Result<Infallible, String> {
|
|
let command = match args.split_first() {
|
|
Some((separator, rest)) if separator == "--" && !rest.is_empty() => rest,
|
|
_ => return Err(
|
|
"usage: leleka exec-inherit -- COMMAND ARG... ({FD} marks the sealed descriptor)"
|
|
.into(),
|
|
),
|
|
};
|
|
let stdin = std::io::stdin();
|
|
let moved = rustix::io::dup(stdin.as_fd())
|
|
.map_err(|e| format!("cannot duplicate standard input: {e}"))?;
|
|
let devnull = File::open("/dev/null").map_err(|e| format!("cannot open /dev/null: {e}"))?;
|
|
rustix::stdio::dup2_stdin(&devnull)
|
|
.map_err(|e| format!("cannot replace standard input: {e}"))?;
|
|
let number = moved.into_raw_fd();
|
|
if number < 3 {
|
|
return Err("the sealed descriptor landed on a standard stream".into());
|
|
}
|
|
let arguments = substitute(&command[1..], number);
|
|
let error = Command::new(&command[0]).args(arguments).exec();
|
|
Err(format!("cannot execute {:?}: {error}", command[0]))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::Write;
|
|
use std::os::unix::fs::MetadataExt;
|
|
|
|
#[test]
|
|
fn seal_is_exact_sealed_unlinked_and_cloexec() {
|
|
let path = std::env::temp_dir().join(format!("leleka-sealed-{}", std::process::id()));
|
|
let payload: Vec<u8> = (0..300_000u32).map(|n| (n % 251) as u8).collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let mut calls = Vec::new();
|
|
let mut sealed = seal_file(&path, Some(payload.len() as u64), &mut |a, b| {
|
|
calls.push((a, b))
|
|
})
|
|
.unwrap();
|
|
let meta = sealed.metadata().unwrap();
|
|
assert!(meta.is_file() && meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
assert!(sealed.write(b"x").is_err() && sealed.set_len(1).is_err());
|
|
assert!(
|
|
rustix::io::fcntl_getfd(&sealed)
|
|
.unwrap()
|
|
.contains(rustix::io::FdFlags::CLOEXEC)
|
|
);
|
|
assert_eq!(
|
|
calls.last(),
|
|
Some(&(payload.len() as u64, payload.len() as u64))
|
|
);
|
|
// A descriptor reopened through /proc keeps the properties the engine checks.
|
|
let number = std::os::fd::AsRawFd::as_raw_fd(&sealed) as u32;
|
|
let reopened = open_inherited(number).unwrap();
|
|
let meta = reopened.metadata().unwrap();
|
|
assert!(meta.nlink() == 0 && meta.len() == payload.len() as u64);
|
|
assert!(seal_file(&path, Some(1), &mut |_, _| {}).is_err());
|
|
assert!(open_inherited(1).is_err());
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn parallel_fill_is_byte_exact_across_chunks_and_reports_the_source_identity() {
|
|
let path = std::env::temp_dir().join(format!("leleka-fill-{}", std::process::id()));
|
|
// Three full chunks and a ragged tail, with a pattern that differs per chunk.
|
|
let size = COPY_CHUNK * 3 + 4097;
|
|
let payload: Vec<u8> = (0..size)
|
|
.map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8))
|
|
.collect();
|
|
std::fs::write(&path, &payload).unwrap();
|
|
let (sealed, identity) =
|
|
seal_file_with_identity(&path, Some(size as u64), &mut |_, _| {}).unwrap();
|
|
let identity = identity.expect("a regular file has an identity");
|
|
assert_eq!(identity.size, size as u64);
|
|
let mut copy = vec![0u8; size];
|
|
sealed.read_exact_at(&mut copy, 0).unwrap();
|
|
assert!(
|
|
copy == payload,
|
|
"the memfd must equal the source byte for byte"
|
|
);
|
|
assert!(fcntl_get_seals(&sealed).unwrap().contains(SEALS));
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn exec_inherit_needs_a_command() {
|
|
assert!(exec_inherit(&[]).is_err());
|
|
assert!(exec_inherit(&["--".into()]).is_err());
|
|
assert!(exec_inherit(&["cmd".into()]).is_err());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn placeholder_substitution() {
|
|
let args = vec![
|
|
"--kar-archive-fd".to_owned(),
|
|
"{FD}".to_owned(),
|
|
"x{FD}y".to_owned(),
|
|
];
|
|
assert_eq!(substitute(&args, 7), ["--kar-archive-fd", "7", "x7y"]);
|
|
}
|
|
}
|