use std::collections::HashMap;
use std::future::Future;
use std::io::BufWriter;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::PathBuf;
use std::pin::Pin;
use ostrya_composefs::{
Content, Directory, Error as WriterError, FsVerityHasher, Image, Metadata, Node, Regular,
Symlink, build_image, write_image_to, write_image_unhashed_to,
};
use ostrya_core::{
Checksum, Commit, DirMeta, DirTree, ObjectType, RepoMode, Type, Value, Xattrs, loose_path,
};
use crate::commit::append_dict_entry;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::image_store;
use crate::read::CommitState;
use crate::related::{self, RelatedField};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::{ImageTemp, link_image_blocking, write_image_temp_blocking};
const INJECTED_DIRS: [&str; 5] = ["boot", "etc", "sysroot", "usr", "var"];
const INJECTED_DIR_MODE: u32 = 0o040755;
const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";
const DIGEST_SIGNATURE: &str = "ay";
pub(crate) const DIGEST_CHUNK: usize = 128 * 1024;
const XATTR_ENTRY_COST: usize = 7;
const MAX_XATTR_TOTAL: usize = 32755;
const MAX_XATTR_NAME: usize = u8::MAX as usize;
const BACKING_MODE: RepoMode = RepoMode::BareUser;
type TreeFuture<'a> = Pin<Box<dyn Future<Output = Result<Directory>> + Send + 'a>>;
#[derive(Clone, Copy)]
enum ObjectSource<'a> {
Repo(&'a Repo),
Staged(&'a Transaction),
}
impl ObjectSource<'_> {
async fn dirtree(&self, checksum: &Checksum) -> Result<DirTree> {
match self {
ObjectSource::Repo(repo) => repo.load_dirtree(checksum).await,
ObjectSource::Staged(txn) => txn.load_dirtree_staged_first(checksum).await,
}
}
async fn dirmeta(&self, checksum: &Checksum) -> Result<DirMeta> {
match self {
ObjectSource::Repo(repo) => repo.load_dirmeta(checksum).await,
ObjectSource::Staged(txn) => txn.load_dirmeta_staged_first(checksum).await,
}
}
async fn file(&self, checksum: &Checksum, measure: bool) -> Result<FileObject> {
match self {
ObjectSource::Repo(repo) => repo.load_file_with(checksum, measure).await,
ObjectSource::Staged(txn) => txn.load_file_staged_first_with(checksum, measure).await,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerityPolicy {
#[default]
Computed,
Disabled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ComposefsOptions {
pub verity: VerityPolicy,
}
impl ComposefsOptions {
pub const RECORDED: ComposefsOptions = ComposefsOptions {
verity: VerityPolicy::Computed,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Digests {
Computed,
Sealed,
Disabled,
}
#[derive(Default)]
struct VerityCache {
digests: HashMap<Checksum, [u8; 32]>,
#[cfg(test)]
hashed: usize,
}
impl From<VerityPolicy> for Digests {
fn from(policy: VerityPolicy) -> Digests {
match policy {
VerityPolicy::Computed => Digests::Computed,
VerityPolicy::Disabled => Digests::Disabled,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageAdd {
Added,
AlreadyValid,
Replaced,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageState {
Valid,
Absent,
NoKey,
Mismatch {
expected: [u8; 32],
actual: [u8; 32],
},
}
pub struct StagedComposefsImage<'txn> {
txn: &'txn Transaction,
image: Option<ImageTemp>,
digest: [u8; 32],
}
impl StagedComposefsImage<'_> {
pub fn digest(&self) -> &[u8; 32] {
&self.digest
}
}
impl StagedComposefsImage<'_> {
async fn discard(mut self) {
if let Some(image) = self.image.take() {
ostrya_rt::unblock(move || drop(image)).await;
}
}
}
impl std::fmt::Debug for StagedComposefsImage<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StagedComposefsImage")
.field("digest", &digest_hex(&self.digest))
.finish_non_exhaustive()
}
}
pub(crate) enum RecordedBuildError {
Key(Error),
Mismatch(Error),
Other(Error),
}
impl From<Error> for RecordedBuildError {
fn from(e: Error) -> RecordedBuildError {
RecordedBuildError::Other(e)
}
}
impl From<RecordedBuildError> for Error {
fn from(e: RecordedBuildError) -> Error {
match e {
RecordedBuildError::Key(e)
| RecordedBuildError::Mismatch(e)
| RecordedBuildError::Other(e) => e,
}
}
}
impl Transaction {
pub async fn composefs_digest(&self, root: &RepoTree) -> Result<[u8; 32]> {
let dir = composefs_model(
ObjectSource::Staged(self),
root,
ComposefsOptions::RECORDED.verity.into(),
&mut VerityCache::default(),
)
.await?;
image_digest(dir).await
}
pub async fn build_composefs_image(&self, root: &RepoTree) -> Result<StagedComposefsImage<'_>> {
self.build_composefs_image_with(root, &mut VerityCache::default())
.await
}
async fn build_composefs_image_with(
&self,
root: &RepoTree,
cache: &mut VerityCache,
) -> Result<StagedComposefsImage<'_>> {
if self.repo().mode() == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
let (fsync, per_object_fsync) = self.fsync_flags()?;
let verity = self.verity().await?;
let dir = composefs_model(
ObjectSource::Staged(self),
root,
ComposefsOptions::RECORDED.verity.into(),
cache,
)
.await?;
let staging = self.staging_dir().clone();
let image = self
.unblock(move || {
write_image_temp_blocking(&staging, &dir, fsync && per_object_fsync, verity)
})
.await?;
Ok(StagedComposefsImage {
txn: self,
digest: image.digest,
image: Some(image),
})
}
pub async fn attach_composefs_image(
&self,
commit: &Checksum,
image: StagedComposefsImage<'_>,
) -> Result<ComposefsImageAdd> {
if !std::ptr::eq(image.txn, self) {
image.discard().await;
return Err(Error::InvalidInput(
"the composefs image comes from another transaction".into(),
));
}
let key = async {
let commit_obj = self.load_commit_staged_first(commit).await?;
require_recorded_digest(&commit_obj, commit)
}
.await;
match key {
Ok(key) => self.attach_keyed(commit, &key, image).await,
Err(e) => {
image.discard().await;
Err(e)
}
}
}
async fn attach_keyed(
&self,
commit: &Checksum,
key: &[u8; 32],
image: StagedComposefsImage<'_>,
) -> Result<ComposefsImageAdd> {
let checked = match check_image_digest(commit, key, &image) {
Ok(()) => self.image_state(commit, key).await,
Err(e) => Err(e),
};
self.finish_attach(commit, checked, image).await
}
pub async fn write_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageAdd> {
let commit_obj = self.load_commit_staged_first(commit).await?;
let key = require_recorded_digest(&commit_obj, commit)?;
self.write_keyed_image(commit, commit_obj, &key, &mut VerityCache::default())
.await
}
pub(crate) async fn build_recorded_images(&self) -> Result<()> {
self.build_recorded_images_classified()
.await
.map_err(Error::from)
}
pub(crate) async fn build_recorded_images_classified(
&self,
) -> std::result::Result<(), RecordedBuildError> {
self.build_recorded_with(&mut VerityCache::default()).await
}
async fn build_recorded_with(
&self,
cache: &mut VerityCache,
) -> std::result::Result<(), RecordedBuildError> {
let commits = self.take_complete();
if commits.is_empty() || !self.repo().config().generate_composefs()? {
return Ok(());
}
for commit in &commits {
if self.is_image_staged(commit) {
continue;
}
if !self.is_staged(commit, ObjectType::Commit)
&& self.repo().commit_state(commit).await? != CommitState::Partial
{
continue;
}
let commit_obj = self.load_commit_staged_first(commit).await?;
let key = recorded_digest(&commit_obj).map_err(|e| {
RecordedBuildError::Key(match e {
Error::InvalidFormat(message) => {
Error::InvalidFormat(format!("commit {commit}: {message}"))
}
e => e,
})
})?;
let Some(key) = key else {
continue;
};
self.write_keyed_image(commit, commit_obj, &key, cache)
.await
.map_err(|e| match e {
e @ Error::ComposefsDigestMismatch { .. } => RecordedBuildError::Mismatch(e),
e => RecordedBuildError::Other(e),
})?;
}
Ok(())
}
async fn write_keyed_image(
&self,
commit: &Checksum,
commit_obj: Commit,
key: &[u8; 32],
cache: &mut VerityCache,
) -> Result<ComposefsImageAdd> {
let Some(result) = self.image_state(commit, key).await? else {
return Ok(ComposefsImageAdd::AlreadyValid);
};
let tree = RepoTree::from_parts(
self.repo().clone(),
commit_obj.root_dirtree,
commit_obj.root_dirmeta,
);
let image = self.build_composefs_image_with(&tree, cache).await?;
let checked = check_image_digest(commit, key, &image).map(|()| Some(result));
self.finish_attach(commit, checked, image).await
}
async fn finish_attach(
&self,
commit: &Checksum,
checked: Result<Option<ComposefsImageAdd>>,
mut image: StagedComposefsImage<'_>,
) -> Result<ComposefsImageAdd> {
let result = match checked {
Ok(Some(result)) => result,
Ok(None) => {
image.discard().await;
return Ok(ComposefsImageAdd::AlreadyValid);
}
Err(e) => {
image.discard().await;
return Err(e);
}
};
let staging = self.staging_dir().clone();
let temp = image
.image
.take()
.expect("a staged composefs image holds its file until attached");
let key = *commit;
let outcome = self
.unblock(move || link_image_blocking(&staging, temp, &key))
.await?;
self.record_image(*commit, outcome)?;
Ok(result)
}
async fn image_state(
&self,
commit: &Checksum,
key: &[u8; 32],
) -> Result<Option<ComposefsImageAdd>> {
if self.is_image_staged(commit) {
return Ok(None);
}
Ok(match self.repo().stored_image_digest(commit).await {
Ok(None) => Some(ComposefsImageAdd::Added),
Ok(Some(digest)) if digest == *key => None,
Ok(Some(_)) | Err(Error::Io(_)) => Some(ComposefsImageAdd::Replaced),
Err(e) => return Err(e),
})
}
}
impl Repo {
pub async fn export_composefs(
&self,
commit: &Checksum,
opts: &ComposefsOptions,
) -> Result<Image> {
let dir = self
.composefs_export_model(commit, opts.verity.into())
.await?;
ostrya_rt::unblock(move || build_image(&dir))
.await
.map_err(writer_error)
}
pub async fn export_composefs_to(
&self,
commit: &Checksum,
opts: &ComposefsOptions,
out: BorrowedFd<'_>,
) -> Result<[u8; 32]> {
let dir = self
.composefs_export_model(commit, opts.verity.into())
.await?;
let fd = out.try_clone_to_owned()?;
ostrya_rt::unblock(move || write_image_to_fd(&dir, fd))
.await
.map_err(writer_error)
}
#[doc(hidden)]
pub async fn export_composefs_for_mount(
&self,
commit: &Checksum,
verity: VerityPolicy,
out: BorrowedFd<'_>,
max_size: u64,
) -> Result<u64> {
let digests = match verity {
VerityPolicy::Computed => Digests::Sealed,
VerityPolicy::Disabled => Digests::Disabled,
};
let dir = self.composefs_export_model(commit, digests).await?;
let fd = out.try_clone_to_owned()?;
ostrya_rt::unblock(move || {
let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
write_image_unhashed_to(&dir, &mut out, max_size)
})
.await
.map_err(writer_error)
}
async fn composefs_export_model(
&self,
commit: &Checksum,
digests: Digests,
) -> Result<Directory> {
let (commit_obj, _) = self.load_commit(commit).await?;
self.composefs_commit_model(&commit_obj, digests).await
}
async fn composefs_commit_model(
&self,
commit_obj: &Commit,
digests: Digests,
) -> Result<Directory> {
let tree = RepoTree::from_parts(
self.clone(),
commit_obj.root_dirtree,
commit_obj.root_dirmeta,
);
composefs_model(
ObjectSource::Repo(self),
&tree,
digests,
&mut VerityCache::default(),
)
.await
}
pub async fn commit_add_composefs_metadata(
&self,
txn: &Transaction,
commit: &Checksum,
) -> Result<Checksum> {
let (mut commit_obj, _) = self.load_commit(commit).await?;
if commit_obj.metadata.dict_get(COMPOSEFS_DIGEST_KEY).is_some() {
return Err(Error::InvalidFormat(format!(
"commit already carries {COMPOSEFS_DIGEST_KEY}"
)));
}
let deps = related::checked_entries(
RelatedField::Dependencies,
Some(*commit),
related::entries_of(&commit_obj.related),
)?;
related::check_order(Some(*commit), deps.iter().map(|(name, _)| name.as_str()))?;
related::check_dependencies(txn, Some(*commit), &deps).await?;
let image = if self.config().generate_composefs()? {
let tree = RepoTree::from_parts(
self.clone(),
commit_obj.root_dirtree,
commit_obj.root_dirmeta,
);
Some(txn.build_composefs_image(&tree).await?)
} else {
None
};
let fs_verity = match &image {
Some(image) => *image.digest(),
None => {
let dir = self
.composefs_commit_model(&commit_obj, ComposefsOptions::RECORDED.verity.into())
.await?;
image_digest(dir).await?
}
};
let digest_type = Type::parse(DIGEST_SIGNATURE).map_err(ostrya_core::Error::from)?;
let value = Value::variant(digest_type, Value::Bytes(fs_verity.to_vec()));
append_dict_entry(&mut commit_obj.metadata, COMPOSEFS_DIGEST_KEY, value)?;
let bytes = commit_obj.serialize()?;
let new = txn.write_metadata(ObjectType::Commit, None, &bytes).await?;
match image {
Some(image) if txn.is_staged(&new, ObjectType::Commit) => {
txn.attach_composefs_image(&new, image).await?;
}
Some(image) => image.discard().await,
None => {}
}
Ok(new)
}
pub async fn add_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageAdd> {
let txn = self.transaction().await?;
let result = txn.write_composefs_image(commit).await?;
txn.commit().await?;
Ok(result)
}
pub fn composefs_image_path(&self, commit: &Checksum) -> PathBuf {
self.path()
.join(image_store::IMAGE_DIR)
.join(image_store::rel_path(commit))
}
pub async fn has_composefs_image(&self, commit: &Checksum) -> Result<bool> {
let repo = self.clone();
let commit = *commit;
ostrya_rt::unblock(move || Ok(image_store::open_blocking(&repo, &commit)?.is_some())).await
}
pub async fn check_composefs_image(&self, commit: &Checksum) -> Result<ComposefsImageState> {
let bytes = self.load_object_bytes(ObjectType::Commit, commit).await?;
let commit_obj = Commit::parse(&bytes)?;
let Some(expected) = recorded_digest(&commit_obj)? else {
return Ok(ComposefsImageState::NoKey);
};
Ok(match self.stored_image_digest(commit).await? {
None => ComposefsImageState::Absent,
Some(actual) if actual == expected => ComposefsImageState::Valid,
Some(actual) => ComposefsImageState::Mismatch { expected, actual },
})
}
pub async fn open_composefs_image_checked(
&self,
commit: &Checksum,
) -> Result<(std::fs::File, u64)> {
let bytes = self.load_object_bytes(ObjectType::Commit, commit).await?;
let commit_obj = Commit::parse(&bytes)?;
let expected = require_recorded_digest(&commit_obj, commit)?;
let repo = self.clone();
let commit = *commit;
ostrya_rt::unblock(move || {
use std::io::{Seek, SeekFrom};
let Some(crate::repo_fs::Opened { mut file, stat }) =
image_store::open_blocking(&repo, &commit)?
else {
return Err(Error::ComposefsImageNotFound { commit });
};
let len = stat.size;
let kernel = stat
.verity
.then(|| crate::repo_fs::verity_digest(file.as_fd(), len))
.flatten();
let actual = match kernel {
Some(digest) => digest,
None => {
let digest = image_file_digest(&mut file)?;
file.seek(SeekFrom::Start(0))?;
digest
}
};
if actual != expected {
return Err(Error::ComposefsDigestMismatch {
commit,
expected,
actual,
});
}
Ok((file, len))
})
.await
}
pub(crate) async fn stored_image_digest(&self, commit: &Checksum) -> Result<Option<[u8; 32]>> {
let repo = self.clone();
let commit = *commit;
ostrya_rt::unblock(move || stored_image_digest_blocking(&repo, &commit)).await
}
}
pub(crate) fn stored_image_digest_blocking(
repo: &Repo,
commit: &Checksum,
) -> Result<Option<[u8; 32]>> {
let Some(mut opened) = image_store::open_blocking(repo, commit)? else {
return Ok(None);
};
Ok(Some(image_file_digest(&mut opened.file)?))
}
pub(crate) fn image_file_digest(file: &mut std::fs::File) -> std::io::Result<[u8; 32]> {
use std::io::Read;
let mut hasher = FsVerityHasher::new();
let mut buf = vec![0u8; DIGEST_CHUNK];
loop {
match file.read(&mut buf) {
Ok(0) => break,
Ok(n) => hasher.update(&buf[..n]),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(hasher.finalize())
}
pub(crate) fn recorded_digest(commit: &Commit) -> Result<Option<[u8; 32]>> {
let Some(entry) = commit.metadata.dict_get(COMPOSEFS_DIGEST_KEY) else {
return Ok(None);
};
entry_digest(entry).map(Some)
}
#[cfg(feature = "receive")]
pub(crate) fn entries_digest(entries: &[(String, Vec<u8>)]) -> Result<Option<[u8; 32]>> {
let Some((_, bytes)) = entries.iter().find(|(key, _)| key == COMPOSEFS_DIGEST_KEY) else {
return Ok(None);
};
let entry = ostrya_core::from_bytes(&Type::Variant, bytes).map_err(ostrya_core::Error::from)?;
entry_digest(&entry).map(Some)
}
fn entry_digest(entry: &Value) -> Result<[u8; 32]> {
entry
.as_variant()
.filter(|(ty, _)| ty.signature() == DIGEST_SIGNATURE)
.and_then(|(_, value)| value.as_bytes())
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
.ok_or_else(|| {
Error::InvalidFormat(format!(
"the value of {COMPOSEFS_DIGEST_KEY} is not a variant of type \
{DIGEST_SIGNATURE} with 32 bytes"
))
})
}
fn require_recorded_digest(commit_obj: &Commit, commit: &Checksum) -> Result<[u8; 32]> {
recorded_digest(commit_obj)?.ok_or_else(|| {
Error::InvalidInput(format!(
"commit {commit} does not carry {COMPOSEFS_DIGEST_KEY}, so it has no composefs image"
))
})
}
fn check_image_digest(
commit: &Checksum,
key: &[u8; 32],
image: &StagedComposefsImage<'_>,
) -> Result<()> {
if image.digest != *key {
return Err(Error::ComposefsDigestMismatch {
commit: *commit,
expected: *key,
actual: image.digest,
});
}
Ok(())
}
pub(crate) fn digest_hex(digest: &[u8; 32]) -> String {
use std::fmt::Write;
digest
.iter()
.fold(String::with_capacity(64), |mut out, byte| {
let _ = write!(out, "{byte:02x}");
out
})
}
async fn composefs_model(
source: ObjectSource<'_>,
root: &RepoTree,
digests: Digests,
cache: &mut VerityCache,
) -> Result<Directory> {
let mut dir = build_directory(
source,
*root.dirtree_checksum(),
*root.dirmeta_checksum(),
digests,
cache,
)
.await?;
inject_top_level_dirs(&mut dir);
Ok(dir)
}
fn write_image_to_fd(dir: &Directory, fd: OwnedFd) -> std::result::Result<[u8; 32], WriterError> {
let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
write_image_to(dir, &mut out)
}
async fn image_digest(dir: Directory) -> Result<[u8; 32]> {
ostrya_rt::unblock(move || write_image_to(&dir, &mut std::io::sink()))
.await
.map_err(writer_error)
}
pub(crate) fn writer_error(err: WriterError) -> Error {
match err {
WriterError::Unsupported(msg) => Error::Unsupported(msg),
WriterError::Io(err) => Error::Io(err),
}
}
fn build_directory<'a>(
source: ObjectSource<'a>,
dirtree: Checksum,
dirmeta: Checksum,
digests: Digests,
cache: &'a mut VerityCache,
) -> TreeFuture<'a> {
Box::pin(async move {
let meta = source.dirmeta(&dirmeta).await?;
let mut dir = Directory::new(dirmeta_to_metadata(&meta)?);
let tree = source.dirtree(&dirtree).await?;
for (name, checksum) in tree.files {
let node = file_node(source, &checksum, digests, &mut *cache).await?;
dir.children.insert(name.into_bytes(), node);
}
for (name, subtree, submeta) in tree.dirs {
let sub = build_directory(source, subtree, submeta, digests, &mut *cache).await?;
dir.children.insert(name.into_bytes(), Node::Directory(sub));
}
Ok(dir)
})
}
async fn file_node(
source: ObjectSource<'_>,
checksum: &Checksum,
digests: Digests,
cache: &mut VerityCache,
) -> Result<Node> {
let file = source.file(checksum, digests != Digests::Disabled).await?;
let meta = file_to_metadata(&file)?;
match &file.kind {
FileKind::Symlink { target } => Ok(Node::Symlink(Symlink {
meta,
target: target.clone().into_bytes(),
})),
FileKind::Regular { size } => {
let content = if *size == 0 {
Content::Empty
} else {
let digest = match digests {
Digests::Computed => Some(content_fs_verity(&file, cache).await?),
Digests::Sealed => Some(file.kernel_fs_verity().ok_or_else(|| {
Error::Unsupported(format!(
"the file object {checksum} has no fs-verity seal with SHA-256, \
4096-byte blocks, and no salt"
))
})?),
Digests::Disabled => None,
};
Content::Backed {
size: *size,
redirect: format!("/{}", loose_path(checksum, ObjectType::File, BACKING_MODE)),
verity: digest,
}
};
Ok(Node::Regular(Regular { meta, content }))
}
}
}
async fn content_fs_verity(file: &FileObject, cache: &mut VerityCache) -> Result<[u8; 32]> {
use futures_lite::AsyncReadExt;
if let Some(digest) = file.kernel_fs_verity() {
return Ok(digest);
}
if let Some(digest) = cache.digests.get(file.checksum()) {
return Ok(*digest);
}
let mut reader = file.reader().await?;
let mut hasher = FsVerityHasher::new();
let mut buf = vec![0u8; DIGEST_CHUNK];
loop {
let n = reader.read(&mut buf).await.map_err(Error::Io)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
let digest = hasher.finalize();
cache.digests.insert(*file.checksum(), digest);
#[cfg(test)]
{
cache.hashed += 1;
}
Ok(digest)
}
fn inject_top_level_dirs(root: &mut Directory) {
for name in INJECTED_DIRS {
let key = name.as_bytes().to_vec();
root.children.entry(key).or_insert_with(|| {
Node::Directory(Directory::new(Metadata {
mode: INJECTED_DIR_MODE,
uid: 0,
gid: 0,
mtime: (0, 0),
xattrs: Vec::new(),
}))
});
}
}
fn dirmeta_to_metadata(dirmeta: &DirMeta) -> Result<Metadata> {
Ok(Metadata {
mode: dirmeta.mode,
uid: dirmeta.uid,
gid: dirmeta.gid,
mtime: (0, 0),
xattrs: xattrs_to_model(&dirmeta.xattrs)?,
})
}
fn file_to_metadata(file: &FileObject) -> Result<Metadata> {
Ok(Metadata {
mode: file.mode,
uid: file.uid,
gid: file.gid,
mtime: (0, 0),
xattrs: xattrs_to_model(&file.xattrs)?,
})
}
fn xattrs_to_model(xattrs: &Xattrs) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
let mut spent = 0usize;
xattrs
.iter()
.map(|(name, value)| {
let name = name.strip_suffix(&[0]).unwrap_or(name).to_vec();
if name.len() > MAX_XATTR_NAME {
return Err(Error::Unsupported(format!(
"xattr {} is {} bytes long, above the {MAX_XATTR_NAME} \
bytes a composefs image states a name in",
String::from_utf8_lossy(&name),
name.len(),
)));
}
spent += XATTR_ENTRY_COST + name.len() + value.len();
if spent > MAX_XATTR_TOTAL {
return Err(Error::Unsupported(format!(
"xattr {} takes the inode to {spent} bytes of extended \
attributes, above the {MAX_XATTR_TOTAL} bytes a composefs \
image holds",
String::from_utf8_lossy(&name),
)));
}
Ok((name, value.to_vec()))
})
.collect()
}
#[cfg(test)]
mod tests {
use std::os::fd::AsFd;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use ostrya_core::{Checksum, RepoMode, Type, Value};
use ostrya_rt::block_on;
use super::{COMPOSEFS_DIGEST_KEY, ComposefsImageState, VerityCache};
use crate::{CommitOptions, CreateOptions, MutableTree, Repo, Transaction};
struct Scratch {
path: PathBuf,
}
impl Scratch {
fn new(tag: &str) -> Scratch {
let path = std::env::temp_dir().join(format!(
"ostrya-composefs-{tag}-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
Scratch { path }
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn write_file(dir: &Path, name: &str, bytes: &[u8]) {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
}
async fn keyed_commit(txn: &Transaction, base: &Path, timestamp: u64) -> Checksum {
let mut mtree = MutableTree::new();
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("src"), &mut mtree, None)
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let digest = txn.composefs_digest(&root).await.unwrap();
let metadata = Value::Array(vec![Value::Tuple(vec![
Value::Str(COMPOSEFS_DIGEST_KEY.to_owned()),
Value::variant(Type::parse("ay").unwrap(), Value::Bytes(digest.to_vec())),
])]);
txn.write_commit(
CommitOptions {
timestamp: Some(timestamp),
metadata: Some(metadata),
..CommitOptions::default()
},
&root,
)
.await
.unwrap()
}
#[test]
fn one_build_pass_hashes_each_unsealed_object_one_time() {
let scratch = Scratch::new("verity-cache");
let root = scratch.path.join("repo");
block_on(async {
drop(
Repo::create(&root, CreateOptions::new(RepoMode::BareUser))
.await
.unwrap(),
);
let cfg = root.join("config");
let mut text = std::fs::read_to_string(&cfg).unwrap();
text.push_str("[ex-integrity]\nfsverity=no\n[ex-ostrya]\ngenerate-composefs=true\n");
std::fs::write(&cfg, text).unwrap();
let repo = Repo::open(&root).await.unwrap();
let big: Vec<u8> = (0..9000).map(|i| i as u8).collect();
let first = scratch.path.join("first");
let src = first.join("src");
std::fs::create_dir_all(&src).unwrap();
write_file(&src, "a", b"shared bytes\n");
write_file(&src, "b", b"shared bytes\n");
write_file(&src, "big", &big);
write_file(&src, "empty", b"");
let second = scratch.path.join("second");
let src = second.join("src");
std::fs::create_dir_all(&src).unwrap();
write_file(&src, "a", b"shared bytes\n");
write_file(&src, "new", b"new bytes\n");
write_file(&src, "empty", b"");
let txn = repo.transaction().await.unwrap();
let one = keyed_commit(&txn, &first, 1).await;
let two = keyed_commit(&txn, &second, 2).await;
let mut cache = VerityCache::default();
if let Err(e) = txn.build_recorded_with(&mut cache).await {
panic!("{}", crate::Error::from(e));
}
assert_eq!(cache.hashed, 3);
txn.commit().await.unwrap();
for commit in [one, two] {
assert_eq!(
repo.check_composefs_image(&commit).await.unwrap(),
ComposefsImageState::Valid
);
}
});
}
}