use std::future::Future;
use std::io::BufWriter;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::PathBuf;
use std::pin::Pin;
use futures_io::AsyncRead;
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, check_gc_anchors};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::{
ImageTemp, clone_image_temp_blocking, discard_image_temp, link_image_blocking,
write_image_stream_temp, 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,
}
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) {
let Some(image) = self.image.take() else {
return;
};
match self.txn.staging_fd().try_clone_to_owned() {
Ok(staging) => {
ostrya_rt::unblock(move || discard_image_temp(staging.as_fd(), &image.temp)).await;
}
Err(_) => self.image = Some(image),
}
}
}
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()
}
}
impl Drop for StagedComposefsImage<'_> {
fn drop(&mut self) {
if let Some(image) = self.image.take() {
discard_image_temp(self.txn.staging_fd(), &image.temp);
}
}
}
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(),
)
.await?;
image_digest(dir).await
}
pub async fn build_composefs_image(&self, root: &RepoTree) -> 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.repo().config().fsverity()?;
let dir = composefs_model(
ObjectSource::Staged(self),
root,
ComposefsOptions::RECORDED.verity.into(),
)
.await?;
let staging = self.staging_fd().try_clone_to_owned()?;
let image = ostrya_rt::unblock(move || {
write_image_temp_blocking(staging.as_fd(), &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)?;
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(&tree).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_fd().try_clone_to_owned()?;
let temp = image
.image
.take()
.expect("a staged composefs image holds its file until attached");
let mode = self.repo().mode();
let key = *commit;
let outcome =
ostrya_rt::unblock(move || link_image_blocking(staging.as_fd(), temp, &key, mode))
.await?;
self.record_image(*commit, outcome)?;
Ok(result)
}
async fn image_state(
&self,
commit: &Checksum,
key: &[u8; 32],
) -> Result<Option<ComposefsImageAdd>> {
if self.is_staged(commit, ObjectType::ComposefsImage) {
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),
})
}
pub(crate) async fn import_composefs_image(
&self,
src: &Repo,
commit: &Checksum,
) -> Result<Option<u64>> {
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.repo().config().fsverity()?;
let staging = self.staging_fd().try_clone_to_owned()?;
let src = src.clone();
let key = *commit;
let image = ostrya_rt::unblock(move || {
clone_image_temp_blocking(
staging.as_fd(),
src.objects_fd(),
src.mode(),
&key,
fsync && per_object_fsync,
verity,
)
})
.await?;
let Some(image) = image else {
return Ok(None);
};
let size = image.size;
let staged = StagedComposefsImage {
txn: self,
digest: image.digest,
image: Some(image),
};
self.attach_composefs_image(commit, staged).await?;
Ok(Some(size))
}
pub(crate) async fn stage_composefs_image_from<R: AsyncRead + Unpin>(
&self,
commit: &Checksum,
reader: R,
buf: &mut Vec<u8>,
) -> Result<ComposefsImageAdd> {
let image = write_image_stream_temp(self, reader, buf).await?;
let staged = StagedComposefsImage {
txn: self,
digest: image.digest,
image: Some(image),
};
self.attach_composefs_image(commit, staged).await
}
pub(crate) async fn stage_composefs_image_keyed<R: AsyncRead + Unpin>(
&self,
commit: &Checksum,
key: &[u8; 32],
reader: R,
buf: &mut Vec<u8>,
) -> Result<ComposefsImageAdd> {
let image = write_image_stream_temp(self, reader, buf).await?;
let staged = StagedComposefsImage {
txn: self,
digest: image.digest,
image: Some(image),
};
self.attach_keyed(commit, key, staged).await
}
#[cfg(feature = "receive")]
pub(crate) async fn stage_composefs_image_unchecked<R: AsyncRead + Unpin>(
&self,
commit: &Checksum,
reader: R,
buf: &mut Vec<u8>,
) -> Result<[u8; 32]> {
let image = write_image_stream_temp(self, reader, buf).await?;
let digest = image.digest;
let staging = self.staging_fd().try_clone_to_owned()?;
let mode = self.repo().mode();
let key = *commit;
let outcome =
ostrya_rt::unblock(move || link_image_blocking(staging.as_fd(), image, &key, mode))
.await?;
self.record_image(*commit, outcome)?;
Ok(digest)
}
}
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).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 dir = self
.composefs_commit_model(&commit_obj, ComposefsOptions::RECORDED.verity.into())
.await?;
let fs_verity = 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)?;
check_gc_anchors(self.config(), [&commit_obj.metadata])?;
let bytes = commit_obj.serialize()?;
txn.write_metadata(ObjectType::Commit, None, &bytes).await
}
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("objects").join(loose_path(
commit,
ObjectType::ComposefsImage,
self.mode(),
))
}
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(StoredImage {
mut file,
len,
sealed,
}) = open_stored_image_blocking(&repo, &commit)?
else {
return Err(Error::ObjectNotFound {
checksum: commit,
ty: ObjectType::ComposefsImage,
});
};
let actual = match crate::file::sealed_digest(file.as_fd(), len, sealed) {
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) async fn open_composefs_image(
&self,
commit: &Checksum,
) -> Result<Option<(std::fs::File, u64)>> {
let repo = self.clone();
let commit = *commit;
ostrya_rt::unblock(move || {
let image = open_stored_image_blocking(&repo, &commit)?;
Ok(image.map(|image| (image.file, image.len)))
})
.await
}
}
struct StoredImage {
file: std::fs::File,
len: u64,
sealed: bool,
}
fn open_stored_image_blocking(repo: &Repo, commit: &Checksum) -> Result<Option<StoredImage>> {
let Some(file) = open_image_blocking(repo, commit)? else {
return Ok(None);
};
let stat = rustix::fs::statx(
&file,
"",
rustix::fs::AtFlags::EMPTY_PATH,
rustix::fs::StatxFlags::SIZE,
)?;
Ok(Some(StoredImage {
file,
len: stat.stx_size,
sealed: crate::file::is_sealed(&stat),
}))
}
fn open_image_blocking(repo: &Repo, commit: &Checksum) -> Result<Option<std::fs::File>> {
use rustix::fs::{FileType, Mode, OFlags};
let path = loose_path(commit, ObjectType::ComposefsImage, repo.mode());
let mut flags = OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW;
if repo.is_strict() {
flags |= OFlags::NONBLOCK | OFlags::NOCTTY;
}
let fd = match rustix::fs::openat(repo.objects_fd(), path.as_str(), flags, Mode::empty()) {
Ok(fd) => fd,
Err(rustix::io::Errno::NOENT) => return Ok(None),
Err(e) => return Err(e.into()),
};
if repo.is_strict()
&& FileType::from_raw_mode(rustix::fs::fstat(&fd)?.st_mode) != FileType::RegularFile
{
return Err(Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"the composefs image is not a regular file",
)));
}
Ok(Some(std::fs::File::from(fd)))
}
pub(crate) fn stored_image_digest_blocking(
repo: &Repo,
commit: &Checksum,
) -> Result<Option<[u8; 32]>> {
let Some(mut file) = open_image_blocking(repo, commit)? else {
return Ok(None);
};
Ok(Some(image_file_digest(&mut 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
.as_variant()
.filter(|(ty, _)| ty.signature() == DIGEST_SIGNATURE)
.and_then(|(_, value)| value.as_bytes())
.and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
.map(Some)
.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,
) -> Result<Directory> {
let mut dir = build_directory(
source,
*root.dirtree_checksum(),
*root.dirmeta_checksum(),
digests,
)
.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(
source: ObjectSource<'_>,
dirtree: Checksum,
dirmeta: Checksum,
digests: Digests,
) -> TreeFuture<'_> {
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).await?;
dir.children.insert(name.into_bytes(), node);
}
for (name, subtree, submeta) in tree.dirs {
let sub = build_directory(source, subtree, submeta, digests).await?;
dir.children.insert(name.into_bytes(), Node::Directory(sub));
}
Ok(dir)
})
}
async fn file_node(
source: ObjectSource<'_>,
checksum: &Checksum,
digests: Digests,
) -> 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).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) -> Result<[u8; 32]> {
use futures_lite::AsyncReadExt;
if let Some(digest) = file.kernel_fs_verity() {
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]);
}
Ok(hasher.finalize())
}
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()
}