use std::future::poll_fn;
use std::io::{self, SeekFrom};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::pin::Pin;
use std::task::{Context, Poll};
use async_compression::futures::write::DeflateDecoder;
use futures_io::{AsyncRead, AsyncSeek, AsyncWrite};
use ostrya_core::filehdr::frame;
use ostrya_core::{
Checksum, ContentHasher, DeflateSink, DirMeta, FileHeader, ObjectType, RepoMode, Xattrs,
loose_path,
};
use ostrya_rt::File as RtFile;
use rustix::fs::{AtFlags, Gid, Mode, OFlags, Uid, XattrFlags};
use sha2::{Digest, Sha256};
use crate::config::Tristate;
use crate::error::{Error, Result};
use crate::perm;
use crate::transaction::Transaction;
const S_IFREG: u32 = 0o100000;
const S_IFLNK: u32 = 0o120000;
const SYMLINK_MODE: u32 = S_IFLNK | 0o777;
const PERM_MASK: u32 = 0o7777;
const S_IFMT: u32 = 0o170000;
const CANONICAL_PERM_MASK: u32 = 0o755;
const FIXED_MODE: u32 = 0o644;
pub(crate) const COPY_CHUNK: usize = 64 * 1024;
const SEAL_ATTEMPTS: u32 = 50;
const SEAL_PAUSE: std::time::Duration = std::time::Duration::from_millis(1);
#[derive(Debug, Clone)]
pub struct FileMeta {
pub uid: u32,
pub gid: u32,
pub mode: u32,
pub xattrs: Xattrs,
}
impl FileMeta {
pub fn regular(uid: u32, gid: u32, perm: u32) -> FileMeta {
FileMeta {
uid,
gid,
mode: S_IFREG | (perm & PERM_MASK),
xattrs: Xattrs::empty(),
}
}
pub(crate) fn is_symlink(&self) -> bool {
self.mode & S_IFMT == S_IFLNK
}
pub(crate) fn regular_header(&self) -> FileHeader {
FileHeader {
uid: self.uid,
gid: self.gid,
mode: self.mode,
symlink_target: String::new(),
xattrs: self.xattrs.clone(),
}
}
fn symlink_header(&self, target: &str) -> FileHeader {
FileHeader {
uid: self.uid,
gid: self.gid,
mode: match self.mode & S_IFMT {
0 | S_IFREG => SYMLINK_MODE,
_ => self.mode,
},
symlink_target: target.to_owned(),
xattrs: self.xattrs.clone(),
}
}
}
pub(crate) fn canonical_header(mode: RepoMode, mut header: FileHeader) -> FileHeader {
if mode == RepoMode::BareUserOnly {
header.uid = 0;
header.gid = 0;
header.xattrs = Xattrs::empty();
if header.mode & S_IFMT != S_IFLNK {
header.mode = (header.mode & S_IFMT) | (header.mode & CANONICAL_PERM_MASK);
}
}
header
}
fn canonical_dirmeta(meta: &DirMeta) -> DirMeta {
DirMeta {
uid: 0,
gid: 0,
mode: (meta.mode & S_IFMT) | (meta.mode & CANONICAL_PERM_MASK),
xattrs: Xattrs::empty(),
}
}
#[derive(Debug)]
pub(crate) enum TempKind {
Anonymous,
Named(String),
}
struct PendingTemp<'a> {
staging_fd: BorrowedFd<'a>,
temp: Option<TempKind>,
}
impl<'a> PendingTemp<'a> {
fn new(staging_fd: BorrowedFd<'a>, temp: TempKind) -> PendingTemp<'a> {
PendingTemp {
staging_fd,
temp: Some(temp),
}
}
fn into_inner(mut self) -> TempKind {
self.temp
.take()
.expect("a pending temp holds its temp until handed on")
}
}
impl Drop for PendingTemp<'_> {
fn drop(&mut self) {
if let Some(temp) = &self.temp {
cleanup_temp(self.staging_fd, temp);
}
}
}
pub struct ContentWriter<'txn> {
txn: &'txn Transaction,
hasher: Sha256,
uncompressed: u64,
header: FileHeader,
expected: Option<Checksum>,
temp: PendingTemp<'txn>,
sink: Sink,
counted: bool,
}
enum Sink {
Plain(RtFile),
Archive(DeflateSink<RtFile>),
}
impl ContentWriter<'_> {
pub(crate) fn uncounted(mut self) -> Self {
self.counted = false;
self
}
pub async fn finish(self) -> Result<Checksum> {
let ContentWriter {
txn,
hasher,
uncompressed,
header,
expected,
temp,
sink,
counted,
} = self;
let file = match sink {
Sink::Plain(mut file) => {
flush(&mut file).await?;
file
}
Sink::Archive(mut enc) => {
close(&mut enc).await?;
let mut file = enc.into_inner();
seek(&mut file, SeekFrom::Start(8)).await?;
write_all(&mut file, &uncompressed.to_be_bytes()).await?;
flush(&mut file).await?;
file
}
};
let checksum = Checksum::from_bytes(hasher.finalize().into());
if let Some(expected) = expected
&& expected != checksum
{
return Err(Error::ChecksumMismatch {
expected,
actual: checksum,
});
}
let std_file = file.into_std().await;
txn.stage_regular(
checksum,
header,
std_file,
temp.into_inner(),
uncompressed,
counted,
)
.await
}
}
impl AsyncWrite for ContentWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let me = self.get_mut();
let n = match &mut me.sink {
Sink::Plain(file) => std::task::ready!(Pin::new(file).poll_write(cx, buf))?,
Sink::Archive(enc) => std::task::ready!(Pin::new(enc).poll_write(cx, buf))?,
};
me.hasher.update(&buf[..n]);
me.uncompressed += n as u64;
Poll::Ready(Ok(n))
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut self.get_mut().sink {
Sink::Plain(file) => Pin::new(file).poll_flush(cx),
Sink::Archive(enc) => Pin::new(enc).poll_flush(cx),
}
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.poll_flush(cx)
}
}
#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncWrite for ContentWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
AsyncWrite::poll_write(self, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_flush(self, cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_close(self, cx)
}
}
impl Transaction {
pub async fn content_writer(
&self,
expected: Option<&Checksum>,
meta: &FileMeta,
) -> Result<ContentWriter<'_>> {
let mode = self.repo().mode();
if mode == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
let header = canonical_header(mode, meta.regular_header());
let framed = frame(&header.serialize()?)?;
let mut hasher = Sha256::new();
hasher.update(&framed);
let staging = self.staging_fd().try_clone_to_owned()?;
let (fd, temp) = self.unblock(move || open_temp(staging.as_fd())).await?;
let temp = PendingTemp::new(self.staging_fd(), temp);
let mut file = RtFile::from(fd);
let sink = if mode.is_archive() {
let placeholder = frame(&header.serialize_archive(0)?)?;
write_all(&mut file, &placeholder).await?;
let level = archive_level(self.repo().config().zlib_level()?);
Sink::Archive(DeflateSink::new(file, level))
} else {
Sink::Plain(file)
};
Ok(ContentWriter {
txn: self,
hasher,
uncompressed: 0,
header,
expected: expected.copied(),
temp,
sink,
counted: true,
})
}
pub async fn write_content(
&self,
expected: Option<&Checksum>,
meta: &FileMeta,
reader: impl AsyncRead + Unpin,
) -> Result<Checksum> {
let mut writer = self.content_writer(expected, meta).await?;
copy_stream(reader, &mut writer).await?;
writer.finish().await
}
pub async fn write_regfile_inline(
&self,
expected: Option<&Checksum>,
meta: &FileMeta,
data: &[u8],
) -> Result<Checksum> {
let mut writer = self.content_writer(expected, meta).await?;
write_all(&mut writer, data).await?;
writer.finish().await
}
pub(crate) async fn write_archive_payload<R: AsyncRead + Unpin>(
&self,
expected: &Checksum,
header: &FileHeader,
framed_header: &[u8],
declared: u64,
payload: R,
buf: &mut Vec<u8>,
) -> Result<Checksum> {
if !self.repo().mode().is_archive() {
return Err(Error::Unsupported(
"write_archive_payload stores an archive-form payload; the destination is not \
archive"
.into(),
));
}
let staging = self.staging_fd().try_clone_to_owned()?;
let (fd, temp) = self.unblock(move || open_temp(staging.as_fd())).await?;
let temp = PendingTemp::new(self.staging_fd(), temp);
let mut file = RtFile::from(fd);
write_all(&mut file, framed_header).await?;
feed_archive_payload(expected, header, declared, payload, buf, Some(&mut file)).await?;
flush(&mut file).await?;
let std_file = file.into_std().await;
self.stage_regular(
*expected,
header.clone(),
std_file,
temp.into_inner(),
declared,
true,
)
.await
}
pub async fn write_symlink(
&self,
target: &str,
meta: &FileMeta,
expected: Option<&Checksum>,
) -> Result<Checksum> {
let mode = self.repo().mode();
if mode == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
let header = canonical_header(mode, meta.symlink_header(target));
let checksum = Checksum::from_bytes(Sha256::digest(frame(&header.serialize()?)?).into());
if let Some(expected) = expected
&& *expected != checksum
{
return Err(Error::ChecksumMismatch {
expected: *expected,
actual: checksum,
});
}
self.stage_symlink(checksum, header).await
}
pub async fn write_dirmeta(&self, meta: &DirMeta) -> Result<Checksum> {
let bytes = self.dirmeta_bytes(meta)?;
self.write_metadata(ObjectType::DirMeta, None, &bytes).await
}
fn dirmeta_bytes(&self, meta: &DirMeta) -> Result<Vec<u8>> {
Ok(if self.repo().mode() == RepoMode::BareUserOnly {
canonical_dirmeta(meta).serialize()?
} else {
meta.serialize()?
})
}
pub(crate) fn dirmeta_checksum(&self, meta: &DirMeta) -> Result<Checksum> {
let bytes = self.dirmeta_bytes(meta)?;
Ok(Checksum::from_bytes(Sha256::digest(&bytes).into()))
}
pub async fn write_metadata(
&self,
ty: ObjectType,
expected: Option<&Checksum>,
bytes: &[u8],
) -> Result<Checksum> {
if self.repo().mode() == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
if !ty.is_meta() {
return Err(Error::Unsupported(format!(
"write_metadata does not handle {ty:?} objects"
)));
}
let checksum = Checksum::from_bytes(Sha256::digest(bytes).into());
if let Some(expected) = expected
&& *expected != checksum
{
return Err(Error::ChecksumMismatch {
expected: *expected,
actual: checksum,
});
}
self.stage_metadata(checksum, ty, bytes.to_vec()).await
}
}
#[cfg(any(feature = "receive", feature = "s3"))]
pub(crate) async fn check_archive_payload<R: AsyncRead + Unpin>(
expected: &Checksum,
header: &FileHeader,
declared: u64,
payload: R,
buf: &mut Vec<u8>,
) -> Result<()> {
feed_archive_payload(expected, header, declared, payload, buf, None).await
}
async fn feed_archive_payload<R: AsyncRead + Unpin>(
expected: &Checksum,
header: &FileHeader,
declared: u64,
mut payload: R,
buf: &mut Vec<u8>,
mut file: Option<&mut RtFile>,
) -> Result<()> {
let mut inflate = DeflateDecoder::new(InflatedDigest::new(header, *expected, declared)?);
if buf.len() < COPY_CHUNK {
buf.resize(COPY_CHUNK, 0);
}
let mut trailing = false;
loop {
let n = read_some(&mut payload, buf).await?;
if n == 0 {
break;
}
if let Some(file) = file.as_deref_mut() {
write_all(file, &buf[..n]).await?;
}
if !trailing && write_up_to(&mut inflate, &buf[..n]).await? < n {
trailing = true;
}
}
if trailing {
return Err(Error::InvalidFormat(format!(
"content object {expected}: bytes follow the deflated payload"
)));
}
close(&mut inflate).await?;
let digest = inflate.into_inner();
if digest.seen != declared {
return Err(Error::InvalidFormat(format!(
"content object {expected}: the payload inflates to {} byte(s), not the \
{declared} its header declares",
digest.seen
)));
}
let checksum = digest.hasher.finish();
if checksum != *expected {
return Err(Error::ChecksumMismatch {
expected: *expected,
actual: checksum,
});
}
Ok(())
}
pub(crate) fn archive_level(zlib_level: i64) -> u8 {
zlib_level.clamp(1, 9) as u8
}
pub(crate) fn open_temp(staging_fd: BorrowedFd<'_>) -> Result<(OwnedFd, TempKind)> {
match rustix::fs::openat(
staging_fd,
".",
OFlags::WRONLY | OFlags::TMPFILE | OFlags::CLOEXEC,
Mode::from_raw_mode(FIXED_MODE),
) {
Ok(fd) => Ok((fd, TempKind::Anonymous)),
Err(_) => {
let name = temp_name();
let fd = rustix::fs::openat(
staging_fd,
name.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(FIXED_MODE),
)?;
Ok((fd, TempKind::Named(name)))
}
}
}
pub(crate) fn probe_fresh_owner(staging_fd: BorrowedFd<'_>) -> Result<(u32, u32)> {
let (fd, temp) = open_temp(staging_fd)?;
let stat = rustix::fs::fstat(&fd);
cleanup_temp(staging_fd, &temp);
let stat = stat?;
Ok((stat.st_uid, stat.st_gid))
}
fn temp_name() -> String {
format!(".ostrya-tmp-{}-{}", std::process::id(), unique())
}
pub(crate) fn unique() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
COUNTER.fetch_add(1, Ordering::Relaxed)
}
pub(crate) struct StageCtx<'a> {
pub(crate) objects_fd: BorrowedFd<'a>,
pub(crate) staging_fd: BorrowedFd<'a>,
pub(crate) mode: RepoMode,
pub(crate) fsync: bool,
pub(crate) per_object_fsync: bool,
pub(crate) sync_metadata: bool,
pub(crate) verity: Tristate,
}
#[derive(Clone, Copy)]
pub(crate) enum Blocks {
Written,
Linked,
Reflinked,
}
pub(crate) struct StageOutcome {
pub(crate) deduped: bool,
pub(crate) on_disk_size: u64,
pub(crate) blocks: Blocks,
pub(crate) unpacked: u64,
pub(crate) staging_name: String,
pub(crate) dest: String,
}
pub(crate) fn stage_content_blocking(
ctx: &StageCtx<'_>,
checksum: &Checksum,
header: &FileHeader,
file: std::fs::File,
temp: TempKind,
unpacked: u64,
) -> Result<StageOutcome> {
let dest = loose_path(checksum, ObjectType::File, ctx.mode);
if crate::object::object_exists(ctx.objects_fd, &dest)? {
cleanup_temp(ctx.staging_fd, &temp);
return Ok(dedup(dest));
}
let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
let stage = |file: std::fs::File| -> Result<u64> {
let stat = rustix::fs::fstat(file.as_fd())?;
apply_content_pre_seal(file.as_fd(), ctx.mode, ctx.verity, stat.st_mode, header)?;
let on_disk_size = stat.st_size.max(0) as u64;
let link_fd = if ctx.verity == Tristate::No {
OwnedFd::from(file)
} else {
let ro = reopen_ro(file.as_fd())?;
drop(file);
seal_regular(ro.as_fd(), ctx.verity)?;
ro
};
apply_content_post_seal(link_fd.as_fd(), ctx.mode, header)?;
if ctx.fsync && ctx.per_object_fsync {
rustix::fs::fsync(link_fd.as_fd())?;
}
materialize(ctx.staging_fd, link_fd.as_fd(), &temp, &staging_name)?;
Ok(on_disk_size)
};
let on_disk_size = stage(file).inspect_err(|_| cleanup_temp(ctx.staging_fd, &temp))?;
Ok(StageOutcome {
deduped: false,
on_disk_size,
blocks: Blocks::Written,
unpacked,
staging_name,
dest,
})
}
pub(crate) fn stage_symlink_blocking(
ctx: &StageCtx<'_>,
checksum: &Checksum,
header: &FileHeader,
) -> Result<StageOutcome> {
let staging_fd = ctx.staging_fd;
let dest = loose_path(checksum, ObjectType::File, ctx.mode);
if crate::object::object_exists(ctx.objects_fd, &dest)? {
return Ok(dedup(dest));
}
let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
let target = &header.symlink_target;
let do_fsync = ctx.fsync && ctx.per_object_fsync;
let on_disk_size = match ctx.mode {
RepoMode::Bare => {
if stage_symlink_inode(staging_fd, target, &staging_name)? {
rustix::fs::chownat(
staging_fd,
staging_name.as_str(),
Some(uid(header.uid)),
Some(gid(header.gid)),
AtFlags::SYMLINK_NOFOLLOW,
)?;
for (name, value) in header.xattrs.iter() {
set_link_xattr(staging_fd, &staging_name, name, value)?;
}
}
target.len() as u64
}
RepoMode::BareUserOnly => {
stage_symlink_inode(staging_fd, target, &staging_name)?;
target.len() as u64
}
RepoMode::BareUser | RepoMode::BareUserShared => {
let mut content = target.clone().into_bytes();
content.push(0);
stage_named_regular(
staging_fd,
&staging_name,
&content,
FIXED_MODE,
Some(&header.serialize_stat_metadata()?),
do_fsync,
ctx.verity,
)?
}
RepoMode::Archive => {
let body = frame(&header.serialize_archive(0)?)?;
stage_named_regular(
staging_fd,
&staging_name,
&body,
FIXED_MODE,
None,
do_fsync,
ctx.verity,
)?
}
RepoMode::BareSplitXattrs => {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
};
Ok(StageOutcome {
deduped: false,
on_disk_size,
blocks: Blocks::Written,
unpacked: target.len() as u64,
staging_name,
dest,
})
}
pub(crate) fn stage_metadata_blocking(
ctx: &StageCtx<'_>,
checksum: &Checksum,
ty: ObjectType,
bytes: &[u8],
) -> Result<StageOutcome> {
let dest = loose_path(checksum, ty, ctx.mode);
if crate::object::object_exists(ctx.objects_fd, &dest)? {
return Ok(dedup(dest));
}
let staging_name = flat_name(checksum, ty, ctx.mode);
let on_disk_size = stage_named_regular(
ctx.staging_fd,
&staging_name,
bytes,
FIXED_MODE,
None,
ctx.fsync && ctx.sync_metadata,
ctx.verity,
)?;
Ok(StageOutcome {
deduped: false,
on_disk_size,
blocks: Blocks::Written,
unpacked: 0,
staging_name,
dest,
})
}
pub(crate) struct ImageTemp {
pub(crate) fd: OwnedFd,
pub(crate) temp: TempKind,
pub(crate) digest: [u8; 32],
pub(crate) size: u64,
}
pub(crate) fn write_image_temp_blocking(
staging_fd: BorrowedFd<'_>,
dir: &ostrya_composefs::Directory,
do_fsync: bool,
verity: Tristate,
) -> Result<ImageTemp> {
let (fd, temp) = open_temp(staging_fd)?;
let pending = PendingTemp::new(staging_fd, temp);
let mut out =
std::io::BufWriter::with_capacity(crate::composefs::DIGEST_CHUNK, std::fs::File::from(fd));
let digest =
ostrya_composefs::write_image_to(dir, &mut out).map_err(crate::composefs::writer_error)?;
let file = out.into_inner().map_err(|e| Error::Io(e.into_error()))?;
rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(FIXED_MODE))?;
if do_fsync {
rustix::fs::fsync(file.as_fd())?;
}
let size = size_of(file.as_fd())?;
let fd = if verity == Tristate::No {
OwnedFd::from(file)
} else {
let ro = reopen_ro(file.as_fd())?;
drop(file);
seal_regular(ro.as_fd(), verity)?;
match ostrya_sys::measure_verity(ro.as_fd()) {
Ok(sealed) if sealed != digest => {
return Err(Error::InvalidFormat(format!(
"the fs-verity digest of the sealed composefs image is {}, and the \
writer computed {}",
crate::composefs::digest_hex(&sealed),
crate::composefs::digest_hex(&digest)
)));
}
Ok(_) => {}
Err(_) if verity == Tristate::Maybe => {}
Err(e) => return Err(Error::Io(e.into())),
}
ro
};
Ok(ImageTemp {
fd,
temp: pending.into_inner(),
digest,
size,
})
}
pub(crate) fn link_image_blocking(
staging_fd: BorrowedFd<'_>,
image: ImageTemp,
commit: &Checksum,
) -> Result<StageOutcome> {
let staging_name = crate::image_store::staging_name(commit);
materialize(staging_fd, image.fd.as_fd(), &image.temp, &staging_name)
.inspect_err(|_| cleanup_temp(staging_fd, &image.temp))?;
Ok(StageOutcome {
deduped: false,
on_disk_size: image.size,
blocks: Blocks::Written,
unpacked: 0,
staging_name,
dest: crate::image_store::rel_path(commit),
})
}
pub(crate) fn discard_image_temp(staging_fd: BorrowedFd<'_>, temp: &TempKind) {
cleanup_temp(staging_fd, temp);
}
pub(crate) fn stage_import_blocking(
ctx: &StageCtx<'_>,
src_objects_fd: BorrowedFd<'_>,
checksum: &Checksum,
ty: ObjectType,
src_mode: RepoMode,
link_owner: Option<(u32, u32)>,
) -> Result<Option<StageOutcome>> {
if ctx.mode == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
let dest = loose_path(checksum, ty, ctx.mode);
if crate::object::object_exists(ctx.objects_fd, &dest)? {
return Ok(Some(dedup(dest)));
}
let src_path = loose_path(checksum, ty, src_mode);
let staging_name = flat_name(checksum, ty, ctx.mode);
if let Some(fresh_owner) = link_owner {
let stat = match rustix::fs::statat(
src_objects_fd,
src_path.as_str(),
AtFlags::SYMLINK_NOFOLLOW,
) {
Ok(stat) => stat,
Err(rustix::io::Errno::NOENT) => {
return Err(Error::ObjectNotFound {
checksum: *checksum,
ty,
});
}
Err(e) => return Err(e.into()),
};
let owned_as_written = (ty == ObjectType::File && ctx.mode == RepoMode::Bare)
|| (stat.st_uid, stat.st_gid) == fresh_owner;
if owned_as_written {
match rustix::fs::linkat(
src_objects_fd,
src_path.as_str(),
ctx.staging_fd,
staging_name.as_str(),
AtFlags::empty(),
) {
Ok(()) | Err(rustix::io::Errno::EXIST) => {
return Ok(Some(StageOutcome {
deduped: false,
on_disk_size: stat.st_size.max(0) as u64,
blocks: Blocks::Linked,
unpacked: 0,
staging_name,
dest,
}));
}
Err(rustix::io::Errno::NOENT) => {
return Err(Error::ObjectNotFound {
checksum: *checksum,
ty,
});
}
Err(
rustix::io::Errno::XDEV
| rustix::io::Errno::MLINK
| rustix::io::Errno::OPNOTSUPP
| rustix::io::Errno::PERM,
) => {}
Err(e) => return Err(e.into()),
}
}
}
if ty == ObjectType::File {
return Ok(None);
}
let (on_disk_size, blocks) = clone_metadata(ctx, src_objects_fd, &src_path, &staging_name)?;
Ok(Some(StageOutcome {
deduped: false,
on_disk_size,
blocks,
unpacked: 0,
staging_name,
dest,
}))
}
pub(crate) fn stage_clone_content_blocking(
ctx: &StageCtx<'_>,
src_objects_fd: BorrowedFd<'_>,
checksum: &Checksum,
src_mode: RepoMode,
header: &FileHeader,
unpacked: u64,
) -> Result<StageOutcome> {
if ctx.mode == RepoMode::BareSplitXattrs {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
let src_path = loose_path(checksum, ObjectType::File, src_mode);
let src = match rustix::fs::openat(
src_objects_fd,
src_path.as_str(),
OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::empty(),
) {
Ok(src) => src,
Err(rustix::io::Errno::NOENT) => {
return Err(Error::ObjectNotFound {
checksum: *checksum,
ty: ObjectType::File,
});
}
Err(e) => return Err(e.into()),
};
let (file, temp, blocks) = clone_payload(ctx.staging_fd, src.as_fd())?;
let mut outcome = stage_content_blocking(ctx, checksum, header, file, temp, unpacked)?;
outcome.blocks = blocks;
Ok(outcome)
}
fn clone_payload(
staging_fd: BorrowedFd<'_>,
src: BorrowedFd<'_>,
) -> Result<(std::fs::File, TempKind, Blocks)> {
let (fd, temp) = open_temp(staging_fd)?;
let mut dst = std::fs::File::from(fd);
let copy = |dst: &mut std::fs::File| -> Result<Blocks> {
if rustix::fs::ioctl_ficlone(dst.as_fd(), src).is_ok() {
return Ok(Blocks::Reflinked);
}
let mut reader = std::fs::File::from(src.try_clone_to_owned()?);
std::io::copy(&mut reader, dst)?;
Ok(Blocks::Written)
};
match copy(&mut dst) {
Ok(blocks) => Ok((dst, temp, blocks)),
Err(e) => {
cleanup_temp(staging_fd, &temp);
Err(e)
}
}
}
fn clone_metadata(
ctx: &StageCtx<'_>,
src_dir: BorrowedFd<'_>,
src_path: &str,
staging_name: &str,
) -> Result<(u64, Blocks)> {
let src = rustix::fs::openat(
src_dir,
src_path,
OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::empty(),
)?;
let (dst, temp, blocks) = clone_payload(ctx.staging_fd, src.as_fd())?;
let apply = || -> Result<(u64, Blocks)> {
rustix::fs::fchmod(dst.as_fd(), Mode::from_raw_mode(FIXED_MODE))?;
let on_disk_size = size_of(dst.as_fd())?;
let link_fd = if ctx.verity == Tristate::No {
OwnedFd::from(dst)
} else {
let ro = reopen_ro(dst.as_fd())?;
drop(dst);
seal_regular(ro.as_fd(), ctx.verity)?;
ro
};
materialize(ctx.staging_fd, link_fd.as_fd(), &temp, staging_name)?;
Ok((on_disk_size, blocks))
};
apply().inspect_err(|_| cleanup_temp(ctx.staging_fd, &temp))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn publish_blocking(
repo_fd: BorrowedFd<'_>,
objects_fd: BorrowedFd<'_>,
staging_fd: BorrowedFd<'_>,
objects: &[(String, String)],
images: &[(String, String)],
syncfs: bool,
fsync: bool,
repo_mode: RepoMode,
) -> Result<()> {
if syncfs {
rustix::fs::syncfs(repo_fd)?;
}
let mut fanouts: Vec<String> = Vec::new();
for (staging_name, dest) in objects {
let fanout = &dest[..2];
ensure_fanout(objects_fd, fanout, repo_mode)?;
rustix::fs::renameat(staging_fd, staging_name.as_str(), objects_fd, dest.as_str())?;
if !fanouts.iter().any(|f| f == fanout) {
fanouts.push(fanout.to_owned());
}
}
if fsync {
for fanout in &fanouts {
let dir = rustix::fs::openat(
objects_fd,
fanout.as_str(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
rustix::fs::fsync(&dir)?;
}
if !objects.is_empty() {
rustix::fs::fsync(objects_fd)?;
}
}
crate::image_store::publish_blocking(repo_fd, staging_fd, images, fsync, repo_mode)
}
fn ensure_fanout(objects_fd: BorrowedFd<'_>, fanout: &str, repo_mode: RepoMode) -> Result<()> {
match rustix::fs::mkdirat(objects_fd, fanout, Mode::from_raw_mode(0o777)) {
Ok(()) => Ok(perm::force_created_dir(objects_fd, fanout, repo_mode)?),
Err(rustix::io::Errno::EXIST) => Ok(()),
Err(e) => Err(e.into()),
}
}
fn dedup(dest: String) -> StageOutcome {
StageOutcome {
deduped: true,
on_disk_size: 0,
blocks: Blocks::Written,
unpacked: 0,
staging_name: String::new(),
dest,
}
}
pub(crate) fn flat_name(checksum: &Checksum, ty: ObjectType, mode: RepoMode) -> String {
format!("{}.{}", checksum.to_hex(), ty.extension(mode))
}
fn apply_content_pre_seal(
fd: BorrowedFd<'_>,
mode: RepoMode,
verity: Tristate,
create_mode: u32,
header: &FileHeader,
) -> Result<()> {
if verity != Tristate::No
&& create_mode & 0o600 != 0o600
&& matches!(
mode,
RepoMode::Bare | RepoMode::BareUser | RepoMode::BareUserOnly
)
{
rustix::fs::fchmod(fd, Mode::from_raw_mode(0o600))?;
}
match mode {
RepoMode::Bare => {}
RepoMode::BareUser => {
set_ostreemeta(fd, header)?;
}
RepoMode::BareUserShared => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(FIXED_MODE))?;
set_ostreemeta(fd, header)?;
}
RepoMode::BareUserOnly => {}
RepoMode::Archive => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(FIXED_MODE))?;
}
RepoMode::BareSplitXattrs => {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
}
Ok(())
}
fn apply_content_post_seal(fd: BorrowedFd<'_>, mode: RepoMode, header: &FileHeader) -> Result<()> {
let perm = header.mode & PERM_MASK;
match mode {
RepoMode::Bare => {
rustix::fs::fchown(fd, Some(uid(header.uid)), Some(gid(header.gid)))?;
for (name, value) in header.xattrs.iter() {
set_inode_xattr(fd, name, value)?;
}
rustix::fs::fchmod(fd, Mode::from_raw_mode(perm))?;
}
RepoMode::BareUser => {
rustix::fs::fchmod(fd, Mode::from_raw_mode((perm & 0o775) | 0o400))?;
}
RepoMode::BareUserOnly => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(perm & 0o755))?;
}
RepoMode::BareUserShared | RepoMode::Archive => {}
RepoMode::BareSplitXattrs => {
return Err(Error::Unsupported(
"bare-split-xattrs is read-only; the port does not write it".into(),
));
}
}
Ok(())
}
fn set_ostreemeta(fd: BorrowedFd<'_>, header: &FileHeader) -> Result<()> {
let meta = header.serialize_stat_metadata()?;
rustix::fs::fsetxattr(fd, "user.ostreemeta", &meta, XattrFlags::empty())?;
Ok(())
}
pub(crate) fn set_inode_xattr(fd: BorrowedFd<'_>, name: &[u8], value: &[u8]) -> Result<()> {
let name = name.strip_suffix(&[0]).unwrap_or(name);
let name = std::str::from_utf8(name)
.map_err(|_| Error::InvalidFormat("xattr name is not valid UTF-8".into()))?;
rustix::fs::fsetxattr(fd, name, value, XattrFlags::empty())?;
Ok(())
}
pub(crate) fn set_link_xattr(
dir: BorrowedFd<'_>,
staging_name: &str,
name: &[u8],
value: &[u8],
) -> Result<()> {
let name = name.strip_suffix(&[0]).unwrap_or(name);
let name = std::str::from_utf8(name)
.map_err(|_| Error::InvalidFormat("xattr name is not valid UTF-8".into()))?;
let link = format!("/proc/self/fd/{}/{}", dir.as_raw_fd(), staging_name);
rustix::fs::lsetxattr(link.as_str(), name, value, XattrFlags::empty())?;
Ok(())
}
fn stage_named_regular(
staging_fd: BorrowedFd<'_>,
staging_name: &str,
content: &[u8],
perm: u32,
ostreemeta: Option<&[u8]>,
do_fsync: bool,
verity: Tristate,
) -> Result<u64> {
use std::io::Write;
let tmp = temp_name();
let fd = rustix::fs::openat(
staging_fd,
tmp.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(perm),
)?;
let mut file = std::fs::File::from(fd);
file.write_all(content)?;
file.flush()?;
rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(perm))?;
if let Some(meta) = ostreemeta {
rustix::fs::fsetxattr(file.as_fd(), "user.ostreemeta", meta, XattrFlags::empty())?;
}
if do_fsync {
rustix::fs::fsync(file.as_fd())?;
}
let size = size_of(file.as_fd())?;
if verity != Tristate::No {
let ro = match reopen_ro(file.as_fd()) {
Ok(ro) => ro,
Err(e) => {
let _ = rustix::fs::unlinkat(staging_fd, tmp.as_str(), AtFlags::empty());
return Err(e);
}
};
drop(file);
if let Err(e) = seal_regular(ro.as_fd(), verity) {
let _ = rustix::fs::unlinkat(staging_fd, tmp.as_str(), AtFlags::empty());
return Err(e);
}
} else {
drop(file);
}
match rustix::fs::renameat(staging_fd, tmp.as_str(), staging_fd, staging_name) {
Ok(()) => {}
Err(e) => {
let _ = rustix::fs::unlinkat(staging_fd, tmp.as_str(), AtFlags::empty());
return Err(e.into());
}
}
Ok(size)
}
fn reopen_ro(fd: BorrowedFd<'_>) -> Result<OwnedFd> {
let proc_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
Ok(rustix::fs::open(
proc_path.as_str(),
OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
)?)
}
fn seal_regular(fd: BorrowedFd<'_>, verity: Tristate) -> Result<()> {
let mut attempts = 0;
let err = loop {
attempts += 1;
match ostrya_sys::enable_verity(fd) {
Ok(()) => return Ok(()),
Err(rustix::io::Errno::TXTBSY) if attempts < SEAL_ATTEMPTS => {
std::thread::sleep(SEAL_PAUSE);
}
Err(e) => break e,
}
};
if verity == Tristate::Maybe {
return Ok(());
}
Err(Error::Unsupported(format!(
"fsverity required but could not be enabled: {err}"
)))
}
pub(crate) fn probe_seal_blocking(tmp_fd: BorrowedFd<'_>) -> Result<bool> {
let (fd, temp) = open_temp(tmp_fd)?;
let sealed = rustix::io::write(&fd, &[0])
.map_err(Error::from)
.and_then(|_| reopen_ro(fd.as_fd()))
.map(|ro| {
drop(fd);
seal_regular(ro.as_fd(), Tristate::Yes).is_ok()
});
cleanup_temp(tmp_fd, &temp);
sealed
}
fn materialize(
staging_fd: BorrowedFd<'_>,
link_fd: BorrowedFd<'_>,
temp: &TempKind,
staging_name: &str,
) -> Result<()> {
match temp {
TempKind::Anonymous => {
let proc_path = format!("/proc/self/fd/{}", link_fd.as_raw_fd());
match rustix::fs::linkat(
rustix::fs::CWD,
proc_path.as_str(),
staging_fd,
staging_name,
AtFlags::SYMLINK_FOLLOW,
) {
Ok(()) | Err(rustix::io::Errno::EXIST) => Ok(()),
Err(e) => Err(e.into()),
}
}
TempKind::Named(name) => {
rustix::fs::renameat(staging_fd, name.as_str(), staging_fd, staging_name)?;
Ok(())
}
}
}
fn stage_symlink_inode(
staging_fd: BorrowedFd<'_>,
target: &str,
staging_name: &str,
) -> Result<bool> {
match rustix::fs::symlinkat(target, staging_fd, staging_name) {
Ok(()) => Ok(true),
Err(rustix::io::Errno::EXIST) => Ok(false),
Err(e) => Err(e.into()),
}
}
fn cleanup_temp(staging_fd: BorrowedFd<'_>, temp: &TempKind) {
if let TempKind::Named(name) = temp {
let _ = rustix::fs::unlinkat(staging_fd, name.as_str(), AtFlags::empty());
}
}
fn size_of(fd: BorrowedFd<'_>) -> Result<u64> {
Ok(rustix::fs::fstat(fd)?.st_size.max(0) as u64)
}
fn uid(value: u32) -> Uid {
Uid::from_raw(value)
}
fn gid(value: u32) -> Gid {
Gid::from_raw(value)
}
struct InflatedDigest {
hasher: ContentHasher,
checksum: Checksum,
declared: u64,
seen: u64,
}
impl InflatedDigest {
fn new(header: &FileHeader, checksum: Checksum, declared: u64) -> Result<InflatedDigest> {
Ok(InflatedDigest {
hasher: ContentHasher::new(header)?,
checksum,
declared,
seen: 0,
})
}
}
impl AsyncWrite for InflatedDigest {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let me = self.get_mut();
me.seen += buf.len() as u64;
if me.seen > me.declared {
return Poll::Ready(Err(io::Error::other(Error::InvalidFormat(format!(
"content object {}: the payload outgrew the {} byte(s) its header declares",
me.checksum, me.declared
)))));
}
me.hasher.update(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
async fn write_all<W: AsyncWrite + Unpin>(w: &mut W, mut buf: &[u8]) -> io::Result<()> {
poll_fn(move |cx| {
while !buf.is_empty() {
match Pin::new(&mut *w).poll_write(cx, buf) {
Poll::Ready(Ok(0)) => {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"write returned zero",
)));
}
Poll::Ready(Ok(n)) => buf = &buf[n..],
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
Poll::Ready(Ok(()))
})
.await
}
async fn write_up_to<W: AsyncWrite + Unpin>(w: &mut W, buf: &[u8]) -> io::Result<usize> {
let mut written = 0;
while written < buf.len() {
match poll_fn(|cx| Pin::new(&mut *w).poll_write(cx, &buf[written..])).await {
Ok(0) => break,
Ok(n) => written += n,
Err(e) if written == 0 => return Err(e),
Err(_) => break,
}
}
Ok(written)
}
pub(crate) async fn flush<W: AsyncWrite + Unpin>(w: &mut W) -> io::Result<()> {
poll_fn(|cx| Pin::new(&mut *w).poll_flush(cx)).await
}
async fn close<W: AsyncWrite + Unpin>(w: &mut W) -> io::Result<()> {
poll_fn(|cx| Pin::new(&mut *w).poll_close(cx)).await
}
async fn seek<S: AsyncSeek + Unpin>(s: &mut S, pos: SeekFrom) -> io::Result<u64> {
poll_fn(|cx| Pin::new(&mut *s).poll_seek(cx, pos)).await
}
async fn read_some<R: AsyncRead + Unpin>(r: &mut R, buf: &mut [u8]) -> io::Result<usize> {
poll_fn(|cx| Pin::new(&mut *r).poll_read(cx, buf)).await
}
pub(crate) async fn copy_stream<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
mut reader: R,
writer: &mut W,
) -> io::Result<()> {
let mut buf = vec![0u8; COPY_CHUNK];
loop {
let n = read_some(&mut reader, &mut buf).await?;
if n == 0 {
break;
}
write_all(writer, &buf[..n]).await?;
}
Ok(())
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ContentWriter<'static>>();
assert_send_sync::<FileMeta>();
};
#[cfg(feature = "tokio")]
const _: fn() = || {
fn assert_tokio_write<T: ostrya_rt::tokio_io::AsyncWrite>() {}
assert_tokio_write::<ContentWriter<'static>>();
};
#[cfg(test)]
mod verity_tests {
use crate::{CreateOptions, FileMeta, Repo};
use ostrya_composefs::FsVerityHasher;
use ostrya_core::{ObjectType, RepoMode, loose_path};
use ostrya_rt::block_on;
use std::os::fd::AsFd;
#[test]
fn kernel_digest_matches_fsverity_hasher() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verity-measure-{}-{}",
std::process::id(),
super::unique()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let root = dir.join("repo");
let payload = b"fs-verity measure cross-check payload\n".repeat(300);
block_on(async {
drop(
Repo::create(&root, CreateOptions::new(RepoMode::BareUserShared))
.await
.unwrap(),
);
let cfg = root.join("config");
let mut text = std::fs::read_to_string(&cfg).unwrap();
text.push_str("[ex-integrity]\nfsverity=maybe\n");
std::fs::write(&cfg, text).unwrap();
let repo = Repo::open(&root).await.unwrap();
let txn = repo.transaction().await.unwrap();
let checksum = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), &payload)
.await
.unwrap();
txn.commit().await.unwrap();
let object = root.join("objects").join(loose_path(
&checksum,
ObjectType::File,
RepoMode::BareUserShared,
));
let file = std::fs::File::open(&object).unwrap();
match ostrya_sys::measure_verity(file.as_fd()) {
Ok(measured) => assert_eq!(
measured,
FsVerityHasher::hash(&payload),
"kernel-measured digest equals the FsVerityHasher digest"
),
Err(_) => eprintln!("skipping digest check: filesystem lacks fs-verity"),
}
});
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(test)]
mod temp_tests {
use std::os::fd::{AsFd, OwnedFd};
use super::{PendingTemp, TempKind, unique};
#[test]
fn a_pending_named_temp_is_removed_on_drop() {
let dir = std::env::temp_dir().join(format!(
"ostrya-pending-temp-{}-{}",
std::process::id(),
unique()
));
std::fs::create_dir_all(&dir).unwrap();
let dir_fd: OwnedFd = std::fs::File::open(&dir).unwrap().into();
for name in [".ostrya-tmp-dropped", ".ostrya-tmp-kept"] {
std::fs::write(dir.join(name), b"partial").unwrap();
}
drop(PendingTemp::new(
dir_fd.as_fd(),
TempKind::Named(".ostrya-tmp-dropped".to_owned()),
));
assert!(!dir.join(".ostrya-tmp-dropped").exists());
let kept = PendingTemp::new(
dir_fd.as_fd(),
TempKind::Named(".ostrya-tmp-kept".to_owned()),
);
assert!(matches!(kept.into_inner(), TempKind::Named(_)));
assert!(dir.join(".ostrya-tmp-kept").exists());
drop(PendingTemp::new(dir_fd.as_fd(), TempKind::Anonymous));
assert!(dir.join(".ostrya-tmp-kept").exists());
std::fs::remove_dir_all(&dir).unwrap();
}
}