375 lines
15 KiB
Rust
375 lines
15 KiB
Rust
//! The Linux sealing of the KAR archive: a sealed memfd, the sparse extent copy and the exec of the engine.
|
|
|
|
use super::substitute;
|
|
use leleka_model_format::{kar::Extent, 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::{AtomicBool, AtomicU64, Ordering},
|
|
},
|
|
};
|
|
|
|
pub const SEALS: SealFlags = SealFlags::from_bits_truncate(
|
|
SealFlags::WRITE.bits()
|
|
| SealFlags::GROW.bits()
|
|
| SealFlags::SHRINK.bits()
|
|
| SealFlags::SEAL.bits(),
|
|
);
|
|
/// Block size the tests use to cover several blocks and a ragged tail.
|
|
#[cfg(test)]
|
|
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`], 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> {
|
|
seal_file_report(path, expect_bytes, progress).map(|(file, identity, _)| (file, identity))
|
|
}
|
|
|
|
/// As [`seal_file_with_identity`], also returning how the file was read (strategy, bytes, time) for the log.
|
|
pub fn seal_file_report(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
String,
|
|
> {
|
|
seal_ranges(path, expect_bytes, None, progress)
|
|
}
|
|
|
|
/// A **sparse** sealed memfd: the final length of the archive, but only `extents` are copied; every byte outside them is
|
|
/// a hole (no page is allocated, a read returns zeros). File offsets are identical to the archive's, so a reader needs no
|
|
/// change. The extents must be sorted, disjoint, page-aligned at the start and inside the archive. The memfd is sealed
|
|
/// like the full one, but it is NOT the archive: the engine verifies it against the pinned digest of the extents
|
|
/// (`VerifiedKarPleArtifact::verify_sparse`), never against the archive's SHA-256, and the identity returned here must not be
|
|
/// used to record a verification stamp of the archive.
|
|
pub fn seal_extents(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: &[Extent],
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<(File, Option<FileIdentity>), String> {
|
|
seal_extents_report(path, expect_bytes, extents, progress)
|
|
.map(|(file, identity, _)| (file, identity))
|
|
}
|
|
|
|
/// As [`seal_extents`], also returning how the file was read.
|
|
pub fn seal_extents_report(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: &[Extent],
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
String,
|
|
> {
|
|
seal_ranges(path, expect_bytes, Some(extents), progress)
|
|
}
|
|
|
|
fn check_extents(extents: &[Extent], total: u64) -> Result<(), String> {
|
|
let mut previous_end = 0;
|
|
for (i, e) in extents.iter().enumerate() {
|
|
if e.len == 0
|
|
|| e.offset % leleka_model_format::kar::EXTENT_ALIGN != 0
|
|
|| e.offset < previous_end
|
|
|| e.offset.checked_add(e.len).is_none_or(|end| end > total)
|
|
{
|
|
return Err(format!(
|
|
"extent {i} ({}+{}) is empty, unaligned, out of order or outside the {total}-byte archive",
|
|
e.offset, e.len
|
|
));
|
|
}
|
|
previous_end = e.end();
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn seal_ranges(
|
|
path: &Path,
|
|
expect_bytes: Option<u64>,
|
|
extents: Option<&[Extent]>,
|
|
progress: &mut dyn FnMut(u64, u64),
|
|
) -> Result<
|
|
(
|
|
File,
|
|
Option<FileIdentity>,
|
|
leleka_model_format::bulk_read::Report,
|
|
),
|
|
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 total = metadata.len();
|
|
let whole = [Extent::new(0, total)];
|
|
let ranges: &[Extent] = match extents {
|
|
Some(extents) => {
|
|
check_extents(extents, total)?;
|
|
extents
|
|
}
|
|
None => &whole,
|
|
};
|
|
let want: u64 = ranges.iter().map(|r| r.len).sum();
|
|
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 report: Mutex<Option<leleka_model_format::bulk_read::Report>> = Mutex::new(None);
|
|
// 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}"))?;
|
|
// Large blocks on many threads (O_DIRECT where the file system allows it): the device sees a deep queue
|
|
// instead of one 128 KiB readahead window at a time, and what is copied never enters the page cache, so the
|
|
// memfd is the only copy of it in RAM (a sparse copy reads each of its extents the same way and nothing else).
|
|
let plan = leleka_model_format::bulk_read::Plan::from_env();
|
|
let copied = AtomicU64::new(0);
|
|
let finished = AtomicBool::new(false);
|
|
let failure: Mutex<Option<String>> = Mutex::new(None);
|
|
std::thread::scope(|scope| {
|
|
scope.spawn(|| {
|
|
// Set on every exit, a panic included, so that the progress loop below ends.
|
|
struct Finished<'a>(&'a AtomicBool);
|
|
impl Drop for Finished<'_> {
|
|
fn drop(&mut self) {
|
|
self.0.store(true, Ordering::Release);
|
|
}
|
|
}
|
|
let _finished = Finished(&finished);
|
|
let mut strategy = None;
|
|
let mut elapsed = std::time::Duration::ZERO;
|
|
for range in ranges {
|
|
let outcome = leleka_model_format::bulk_read::for_each_chunk(
|
|
&source,
|
|
range.offset,
|
|
range.len,
|
|
plan,
|
|
|offset, data| {
|
|
memory.write_all_at(data, offset).map_err(|e| {
|
|
std::io::Error::other(format!(
|
|
"write to memfd failed (out of memory?): {e}"
|
|
))
|
|
})?;
|
|
copied.fetch_add(data.len() as u64, Ordering::Relaxed);
|
|
Ok(())
|
|
},
|
|
);
|
|
match outcome {
|
|
Ok(done) => {
|
|
strategy = Some(done.strategy);
|
|
elapsed += done.elapsed;
|
|
}
|
|
Err(e) => {
|
|
if let Ok(mut f) = failure.lock() {
|
|
f.get_or_insert(format!("read failed: {e}"));
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
// No extents at all is a valid (empty) sparse copy: nothing was read.
|
|
let strategy = strategy.unwrap_or(leleka_model_format::bulk_read::Strategy::Plain);
|
|
if let Ok(mut slot) = report.lock() {
|
|
*slot = Some(leleka_model_format::bulk_read::Report {
|
|
strategy,
|
|
bytes: want,
|
|
elapsed,
|
|
});
|
|
}
|
|
});
|
|
let mut reported = 0u64;
|
|
while !finished.load(Ordering::Acquire) {
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
let now = copied.load(Ordering::Relaxed);
|
|
if now - reported >= 4 << 30 {
|
|
reported = now;
|
|
progress(now, want);
|
|
}
|
|
}
|
|
});
|
|
if let Some(message) = failure.into_inner().ok().flatten() {
|
|
return Err(message);
|
|
}
|
|
if copied.load(Ordering::Relaxed) != want {
|
|
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(want, want);
|
|
let report = report
|
|
.into_inner()
|
|
.ok()
|
|
.flatten()
|
|
.ok_or("the archive copy did not report")?;
|
|
Ok((memory, identity_before, report))
|
|
}
|
|
|
|
/// 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]))
|
|
}
|
|
|
|
/// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...`: copy the archive (or only the extents
|
|
/// the serve path reads) into a sealed memfd and replace this process with COMMAND, which inherits the descriptor (every `{FD}` in
|
|
/// its arguments is the number). The Rust form of `leleka-seal-exec`, with the sparse copy. Nothing is verified here: the engine
|
|
/// verifies the memfd it is given (the archive SHA-256, or with `--sparse-ple` the pinned digest of the extents).
|
|
pub fn seal_exec(args: &[String]) -> Result<Infallible, String> {
|
|
let plan = super::parse_seal_exec(args)?;
|
|
let started = std::time::Instant::now();
|
|
let mut progress = |done: u64, total: u64| {
|
|
eprintln!(
|
|
"leleka seal-exec: {:.1} of {:.1} GiB",
|
|
done as f64 / 1073741824.0,
|
|
total as f64 / 1073741824.0
|
|
);
|
|
};
|
|
let (memory, extents) = if plan.sparse_ple {
|
|
let expect = plan
|
|
.expect_bytes
|
|
.ok_or("--sparse-ple needs --expect-bytes (the pinned archive length)")?;
|
|
let extents = super::archive_serve_extents(&plan.file, expect)?;
|
|
let (memory, _) = seal_extents(&plan.file, Some(expect), &extents, &mut progress)?;
|
|
(memory, Some(extents))
|
|
} else {
|
|
(
|
|
seal_file(&plan.file, plan.expect_bytes, &mut progress)?,
|
|
None,
|
|
)
|
|
};
|
|
let moved = rustix::io::dup(memory.as_fd())
|
|
.map_err(|e| format!("cannot duplicate the sealed descriptor: {e}"))?;
|
|
let number = moved.into_raw_fd();
|
|
if number < 3 {
|
|
return Err("the sealed descriptor landed on a standard stream".into());
|
|
}
|
|
let length = memory.metadata().map(|m| m.len()).unwrap_or(0);
|
|
eprintln!(
|
|
"leleka seal-exec: sealed memfd fd={number} bytes={length}{} in {:.1}s",
|
|
extents.as_ref().map_or(String::new(), |e| format!(
|
|
" (SPARSE: {} extents, {:.3} GiB held, the rest is a hole)",
|
|
e.len(),
|
|
leleka_model_format::kar::extents_bytes(e) as f64 / 1073741824.0
|
|
)),
|
|
started.elapsed().as_secs_f64()
|
|
);
|
|
let arguments = substitute(&plan.command[1..], number);
|
|
let error = Command::new(&plan.command[0]).args(arguments).exec();
|
|
Err(format!("cannot execute {:?}: {error}", plan.command[0]))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|