use ostrya_core::{Checksum, Commit, DirMeta, DirTree, ObjectType, Value, Xattrs};
use async_compression::futures::bufread::DeflateDecoder;
use crate::composefs::{
ComposefsEntryFn, ComposefsOptions, DIGEST_CHUNK, digest_hex, image_file_digest,
recorded_digest,
};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject, Payload};
use crate::inflate::BufSource;
use crate::read::CommitState;
use crate::related::{self, RelationField};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::FileMeta;
pub const COMPOSEFS_RELATION: &str = "composefs";
const IMAGE_FILE: &str = "root.cfs";
const IMAGE_SUBJECT: &str = "composefs image";
const IMAGE_PERM: u32 = 0o400;
const ROOT_DIR_MODE: u32 = 0o040755;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageSource {
Attachment,
Supplement,
}
impl std::fmt::Display for ComposefsImageSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
ComposefsImageSource::Attachment => "attachment",
ComposefsImageSource::Supplement => "supplement",
})
}
}
#[derive(Debug)]
pub struct ComposefsImage {
pub file: std::fs::File,
pub size: u64,
pub source: ComposefsImageSource,
pub commit: Checksum,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsSupplementAdd {
Valid {
image: Checksum,
},
Written {
image: Checksum,
replaced: Option<Checksum>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ComposefsImageDefect {
Absent,
Partial,
NoImageFile,
NotRegular,
ExtraEntry(String),
DigestMismatch {
expected: [u8; 32],
actual: [u8; 32],
},
}
impl std::fmt::Display for ComposefsImageDefect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ComposefsImageDefect::Absent => f.write_str(related::ABSENT_REASON),
ComposefsImageDefect::Partial => f.write_str(related::PARTIAL_REASON),
ComposefsImageDefect::NoImageFile => write!(f, "whose tree holds no /{IMAGE_FILE}"),
ComposefsImageDefect::NotRegular => {
write!(f, "whose /{IMAGE_FILE} is not a regular file")
}
ComposefsImageDefect::ExtraEntry(name) => {
write!(f, "whose tree holds the entry {name} next to /{IMAGE_FILE}")
}
ComposefsImageDefect::DigestMismatch { expected, actual } => write!(
f,
"whose /{IMAGE_FILE} has the fs-verity digest {}, and the commit records {}",
digest_hex(actual),
digest_hex(expected)
),
}
}
}
impl Transaction {
pub async fn write_composefs_commit(
&self,
root: &RepoTree,
filter: Option<ComposefsEntryFn<'_>>,
) -> Result<(Checksum, [u8; 32])> {
let meta = FileMeta::regular(0, 0, IMAGE_PERM);
let (image, digest) = self
.write_composefs_content(root, &ComposefsOptions::RECORDED, filter, &meta)
.await?;
let root_dirmeta = self
.write_dirmeta(&DirMeta {
uid: 0,
gid: 0,
mode: ROOT_DIR_MODE,
xattrs: Xattrs::empty(),
})
.await?;
let tree = DirTree {
files: vec![(IMAGE_FILE.to_owned(), image)],
dirs: Vec::new(),
};
let root_dirtree = self
.write_metadata(ObjectType::DirTree, None, &tree.serialize()?)
.await?;
let commit = Commit {
metadata: Value::Array(Vec::new()),
parent: None,
related: Vec::new(),
subject: IMAGE_SUBJECT.to_owned(),
body: String::new(),
timestamp: 0,
root_dirtree,
root_dirmeta,
};
let checksum = self
.write_metadata(ObjectType::Commit, None, &commit.serialize()?)
.await?;
Ok((checksum, digest))
}
}
impl Repo {
pub async fn open_composefs_image(&self, commit: &Checksum) -> Result<Option<ComposefsImage>> {
if self.mode().is_archive() {
return Err(archive_refusal());
}
let repo = self.clone();
let key = *commit;
ostrya_rt::unblock(move || {
let Some(named) = repo.named_image_blocking(&key)? else {
return Ok(None);
};
let (file, size) =
repo.check_raw_image_blocking(&key, named.source, &named.image, named.key)?;
Ok(Some(ComposefsImage {
file,
size,
source: named.source,
commit: named.image,
}))
})
.await
}
pub async fn add_composefs_supplement(
&self,
commit: &Checksum,
) -> Result<ComposefsSupplementAdd> {
let txn = self.transaction().await?;
let (result, was_partial) = match self.stage_composefs_supplement(&txn, commit).await {
Ok(staged) => staged,
Err(e) => {
txn.abort().await?;
return Err(e);
}
};
let ComposefsSupplementAdd::Written { image, .. } = result else {
txn.abort().await?;
return Ok(result);
};
let fsync = txn.fsync_flags()?.0;
txn.commit().await?;
if was_partial {
let failed = self.remove_partial_markers(vec![image], fsync).await?;
if let Some((_, e)) = failed.into_iter().next() {
return Err(e);
}
}
Ok(result)
}
async fn stage_composefs_supplement(
&self,
txn: &Transaction,
commit: &Checksum,
) -> Result<(ComposefsSupplementAdd, bool)> {
let repo = self.clone();
let read_commit = *commit;
let read = ostrya_rt::unblock(move || repo.supplement_state_blocking(&read_commit)).await?;
let replaced = match read.state {
SupplementState::Valid(image) => {
return Ok((ComposefsSupplementAdd::Valid { image }, false));
}
SupplementState::Build { replaced } => replaced,
};
let root = RepoTree::from_parts(self.clone(), read.root_dirtree, read.root_dirmeta);
let (image, digest) = txn.write_composefs_commit(&root, None).await?;
if let Some(expected) = read.key
&& expected != digest
{
return Err(Error::ComposefsDigestMismatch {
commit: *commit,
expected,
actual: digest,
});
}
let was_partial = self.commit_state(&image).await? == CommitState::Partial;
txn.add_supplement(commit, COMPOSEFS_RELATION, &image)?;
Ok((
ComposefsSupplementAdd::Written { image, replaced },
was_partial,
))
}
fn supplement_state_blocking(&self, commit: &Checksum) -> Result<SupplementRead> {
let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
let parsed = Commit::parse(&bytes)?;
let key = recorded_digest(&parsed)?;
let mut replaced = None;
if let Some((source, image)) = self.named_entry_blocking(commit, &bytes)? {
if source == ComposefsImageSource::Attachment {
return Err(Error::InvalidInput(format!(
"commit {commit} names its composefs image commit {image} as an \
attachment; a supplement is not written"
)));
}
match self.check_composefs_commit_blocking(commit, source, &image, key) {
Ok(_) => {
return Ok(SupplementRead {
root_dirtree: parsed.root_dirtree,
root_dirmeta: parsed.root_dirmeta,
key,
state: SupplementState::Valid(image),
});
}
Err(Error::InvalidComposefsImage { .. }) => replaced = Some(image),
Err(e) => return Err(e),
}
}
Ok(SupplementRead {
root_dirtree: parsed.root_dirtree,
root_dirmeta: parsed.root_dirmeta,
key,
state: SupplementState::Build { replaced },
})
}
fn named_image_blocking(&self, commit: &Checksum) -> Result<Option<NamedImage>> {
let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
let Some((source, image)) = self.named_entry_blocking(commit, &bytes)? else {
return Ok(None);
};
let key = recorded_digest(&Commit::parse(&bytes)?)?;
Ok(Some(NamedImage { source, image, key }))
}
fn named_entry_blocking(
&self,
commit: &Checksum,
bytes: &[u8],
) -> Result<Option<(ComposefsImageSource, Checksum)>> {
let attachments = related::checked_entries(
RelationField::Attachments,
Some(*commit),
related::parse_attachments(bytes)?,
)?;
if let Some(image) = composefs_entry(commit, RelationField::Attachments, &attachments)? {
return Ok(Some((ComposefsImageSource::Attachment, image)));
}
let detached = self.read_supplement_dict_blocking(commit)?;
let supplements = related::supplements(detached.as_ref())
.map_err(|reason| Error::InvalidRelations {
commit: Some(*commit),
field: RelationField::Supplements,
reason,
})?
.map(|entries| {
related::checked_entries(RelationField::Supplements, Some(*commit), entries)
})
.transpose()?
.unwrap_or_default();
Ok(
composefs_entry(commit, RelationField::Supplements, &supplements)?
.map(|image| (ComposefsImageSource::Supplement, image)),
)
}
fn check_composefs_commit_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
key: Option<[u8; 32]>,
) -> Result<Option<(std::fs::File, u64)>> {
if !self.mode().is_archive() {
return self
.check_raw_image_blocking(commit, relation, image, key)
.map(Some);
}
let (object, payload) = self.image_file_blocking(commit, relation, image, false)?;
let Some(expected) = key else {
return Ok(None);
};
let Some((file, len)) = payload else {
return Err(no_payload(&object));
};
let actual = inflated_digest_blocking(file, len)?;
check_digest(&expected, &actual)
.map_err(|defect| invalid_image(commit, relation, image, defect))?;
Ok(None)
}
fn check_raw_image_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
key: Option<[u8; 32]>,
) -> Result<(std::fs::File, u64)> {
use std::io::{Seek, SeekFrom};
let (object, payload) = self.image_file_blocking(commit, relation, image, key.is_some())?;
let Some((mut file, size)) = payload else {
return Err(no_payload(&object));
};
let Some(expected) = key else {
return Ok((file, size));
};
let actual = match object.kernel_fs_verity() {
Some(digest) => digest,
None => {
let digest = image_file_digest(&mut file)?;
file.seek(SeekFrom::Start(0))?;
digest
}
};
check_digest(&expected, &actual)
.map_err(|defect| invalid_image(commit, relation, image, defect))?;
Ok((file, size))
}
fn image_file_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
measure: bool,
) -> Result<(FileObject, Option<Payload>)> {
let invalid = |defect| invalid_image(commit, relation, image, defect);
let Some(bytes) = self.held_object_bytes_blocking(ObjectType::Commit, image)? else {
return Err(invalid(ComposefsImageDefect::Absent));
};
if self.commit_state_blocking(image)? == CommitState::Partial {
return Err(invalid(ComposefsImageDefect::Partial));
}
let root = Commit::parse(&bytes)?.root_dirtree;
let tree = DirTree::parse(&self.load_object_bytes_blocking(ObjectType::DirTree, &root)?)?;
let file = image_entry(&tree).map_err(invalid)?;
let (object, payload) = self.open_file_blocking(&file, measure)?;
if !matches!(object.kind, FileKind::Regular { .. }) {
return Err(invalid(ComposefsImageDefect::NotRegular));
}
Ok((object, payload))
}
}
struct SupplementRead {
root_dirtree: Checksum,
root_dirmeta: Checksum,
key: Option<[u8; 32]>,
state: SupplementState,
}
enum SupplementState {
Valid(Checksum),
Build { replaced: Option<Checksum> },
}
struct NamedImage {
source: ComposefsImageSource,
image: Checksum,
key: Option<[u8; 32]>,
}
fn invalid_image(
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
defect: ComposefsImageDefect,
) -> Error {
Error::InvalidComposefsImage {
commit: *commit,
relation,
image: *image,
defect: Box::new(defect),
}
}
fn no_payload(object: &FileObject) -> Error {
Error::InvalidFormat(format!(
"the file object {} of /{IMAGE_FILE} has no payload",
object.checksum()
))
}
fn archive_refusal() -> Error {
Error::Unsupported(
"the lookup of a composefs image refuses an archive repository: it stores \
/root.cfs compressed, and a mount needs the raw image"
.into(),
)
}
fn composefs_entry(
commit: &Checksum,
field: RelationField,
entries: &[(String, Checksum)],
) -> Result<Option<Checksum>> {
let mut named = entries
.iter()
.filter(|(name, _)| name == COMPOSEFS_RELATION);
let first = named.next().map(|(_, checksum)| *checksum);
if named.next().is_some() {
return Err(Error::InvalidRelations {
commit: Some(*commit),
field,
reason: format!("two or more entries have the name {COMPOSEFS_RELATION}"),
});
}
Ok(first)
}
fn image_entry(tree: &DirTree) -> std::result::Result<Checksum, ComposefsImageDefect> {
let file = tree
.files
.iter()
.find(|(name, _)| name == IMAGE_FILE)
.map(|(_, checksum)| *checksum);
let dir = tree.dirs.iter().any(|(name, _, _)| name == IMAGE_FILE);
if file.is_none() && !dir {
return Err(ComposefsImageDefect::NoImageFile);
}
if dir {
return Err(ComposefsImageDefect::NotRegular);
}
let extra = tree
.files
.iter()
.map(|(name, _)| name)
.chain(tree.dirs.iter().map(|(name, _, _)| name))
.find(|name| *name != IMAGE_FILE);
if let Some(name) = extra {
return Err(ComposefsImageDefect::ExtraEntry(name.clone()));
}
Ok(file.expect("the tree holds the file root.cfs"))
}
fn check_digest(
expected: &[u8; 32],
actual: &[u8; 32],
) -> std::result::Result<(), ComposefsImageDefect> {
if actual == expected {
return Ok(());
}
Err(ComposefsImageDefect::DigestMismatch {
expected: *expected,
actual: *actual,
})
}
fn inflated_digest_blocking(file: std::fs::File, len: u64) -> Result<[u8; 32]> {
use futures_lite::AsyncReadExt;
let source = BufSource::with_len_hint(futures_lite::io::AssertAsync::new(file), len);
let mut decoder = DeflateDecoder::new(source);
let mut hasher = ostrya_composefs::FsVerityHasher::new();
let mut buf = vec![0u8; DIGEST_CHUNK];
futures_lite::future::block_on(async {
loop {
let n = decoder.read(&mut buf).await.map_err(Error::Io)?;
if n == 0 {
return Ok::<(), Error>(());
}
hasher.update(&buf[..n]);
}
})?;
Ok(hasher.finalize())
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
fn assert_send<T: Send>(_: &T) {}
assert_send_sync::<ComposefsImage>();
assert_send_sync::<ComposefsImageDefect>();
let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.open_composefs_image(commit));
let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.add_composefs_supplement(commit));
let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>| {
assert_send(&txn.write_composefs_commit(root, Some(filter)));
};
let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>, meta: &FileMeta| {
assert_send(&txn.write_composefs_content(
root,
&ComposefsOptions::RECORDED,
Some(filter),
meta,
));
};
};
#[cfg(test)]
mod tests {
use ostrya_core::{Checksum, DirMeta, DirTree, ObjectType, RepoMode, Xattrs};
use ostrya_rt::block_on;
use super::{ComposefsImageDefect, ComposefsImageSource, ROOT_DIR_MODE};
use crate::tree::RepoTree;
use crate::{CreateOptions, Error, FileMeta, Repo};
#[test]
fn the_check_hashes_the_inflated_image_in_archive_mode() {
let path = std::env::temp_dir().join(format!(
"ostrya-image-commit-archive-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&path);
block_on(async {
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let file = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"payload\n")
.await
.unwrap();
let dirmeta = txn
.write_dirmeta(&DirMeta {
uid: 0,
gid: 0,
mode: ROOT_DIR_MODE,
xattrs: Xattrs::empty(),
})
.await
.unwrap();
let tree = DirTree {
files: vec![("a".to_owned(), file)],
dirs: Vec::new(),
};
let dirtree = txn
.write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
.await
.unwrap();
let root = RepoTree::from_parts(repo.clone(), dirtree, dirmeta);
let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
txn.commit().await.unwrap();
let commit = Checksum::from_bytes([1; 32]);
let source = ComposefsImageSource::Supplement;
for key in [Some(&digest), None] {
let checked = repo
.check_composefs_commit_blocking(&commit, source, &image, key.copied())
.unwrap();
assert!(checked.is_none());
}
let wrong = [0x11; 32];
match repo
.check_composefs_commit_blocking(&commit, source, &image, Some(wrong))
.unwrap_err()
{
Error::InvalidComposefsImage { defect, .. } => assert_eq!(
*defect,
ComposefsImageDefect::DigestMismatch {
expected: wrong,
actual: digest,
}
),
other => panic!("expected InvalidComposefsImage, got {other:?}"),
}
});
let _ = std::fs::remove_dir_all(&path);
}
}