use std::ffi::CString;
use std::future::poll_fn;
use std::io::{self, SeekFrom, Write};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::pin::Pin;
use std::sync::Arc;
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::{FileType, Mode, OFlags, XattrFlags};
use rustix::io::Errno;
use sha2::{Digest, Sha256};
use crate::config::Tristate;
use crate::error::{Error, Result};
use crate::read::object_path_error;
use crate::repo_fs::{
self, Cloned, FsError, Publish, Published, Reason, RepoDir, Stat, TempFile, TempLink,
};
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;
const PRIVATE_MODE: u32 = 0o400;
pub(crate) const COPY_CHUNK: usize = 64 * 1024;
#[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(NamedTemp),
}
#[derive(Debug)]
pub(crate) struct NamedTemp {
dir: Arc<OwnedFd>,
name: String,
armed: bool,
}
impl NamedTemp {
#[cfg(test)]
pub(crate) fn adopt(dir: Arc<OwnedFd>, name: String) -> NamedTemp {
NamedTemp {
dir,
name,
armed: true,
}
}
pub(crate) fn name(&self) -> &str {
&self.name
}
pub(crate) fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for NamedTemp {
fn drop(&mut self) {
if self.armed {
let _ = rustix::fs::unlinkat(
self.dir.as_fd(),
self.name.as_str(),
rustix::fs::AtFlags::empty(),
);
}
}
}
pub struct ContentWriter<'txn> {
txn: &'txn Transaction,
hasher: Sha256,
uncompressed: u64,
header: FileHeader,
expected: Option<Checksum>,
temp: TempFile,
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,
});
}
drop(file);
txn.stage_regular(checksum, header, temp, 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 (temp, mut file) = self.object_temp().await?;
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 (temp, mut file) = self.object_temp().await?;
write_all(&mut file, framed_header).await?;
feed_archive_payload(expected, header, declared, payload, buf, Some(&mut file)).await?;
flush(&mut file).await?;
drop(file);
self.stage_regular(*expected, header.clone(), temp, declared, true)
.await
}
async fn object_temp(&self) -> Result<(TempFile, RtFile)> {
let staging = self.staging_dir().clone();
let mut temp = self.unblock(move || TempFile::create(&staging)).await?;
let file = temp.file_mut().try_clone()?;
Ok((temp, RtFile::from(file)))
}
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> {
let checksum = self.check_metadata(ty, expected, bytes)?;
self.stage_metadata(checksum, ty, bytes.to_vec()).await
}
pub(crate) async fn write_metadata_owned(
&self,
ty: ObjectType,
expected: Option<&Checksum>,
bytes: Vec<u8>,
) -> Result<Checksum> {
let checksum = self.check_metadata(ty, expected, &bytes)?;
self.stage_metadata(checksum, ty, bytes).await
}
fn check_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,
});
}
Ok(checksum)
}
}
#[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
}
#[cfg(test)]
thread_local! {
pub(crate) static FORCE_NAMED_TEMP: std::cell::Cell<bool> =
const { std::cell::Cell::new(false) };
}
pub(crate) fn open_temp(dir: &Arc<OwnedFd>) -> Result<(OwnedFd, TempKind)> {
#[cfg(test)]
if FORCE_NAMED_TEMP.get() {
return open_named_temp(dir);
}
match rustix::fs::openat(
dir.as_fd(),
".",
OFlags::WRONLY | OFlags::TMPFILE | OFlags::CLOEXEC,
Mode::from_raw_mode(FIXED_MODE),
) {
Ok(fd) => Ok((fd, TempKind::Anonymous)),
Err(_) => open_named_temp(dir),
}
}
fn open_named_temp(dir: &Arc<OwnedFd>) -> Result<(OwnedFd, TempKind)> {
let name = temp_name();
let fd = rustix::fs::openat(
dir.as_fd(),
name.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(FIXED_MODE),
)?;
Ok((
fd,
TempKind::Named(NamedTemp {
dir: Arc::clone(dir),
name,
armed: true,
}),
))
}
pub(crate) fn probe_fresh_owner(staging: &RepoDir) -> Result<(u32, u32)> {
let mut temp = TempFile::create(staging)?;
let stat = repo_fs::stat_fd(temp.file_mut().as_fd())?;
Ok((stat.uid, stat.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: &'a RepoDir,
pub(crate) staging: &'a RepoDir,
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,
mut temp: TempFile,
unpacked: u64,
) -> Result<StageOutcome> {
let dest = loose_path(checksum, ObjectType::File, ctx.mode);
if ctx.objects.exists(&dest)? {
return Ok(dedup(dest));
}
let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
let stat = repo_fs::stat_fd(temp.file_mut().as_fd())?;
stage_new_content(ctx, header, temp, stat.mode, &staging_name)?;
Ok(StageOutcome {
deduped: false,
on_disk_size: stat.size,
blocks: Blocks::Written,
unpacked,
staging_name,
dest,
})
}
fn stage_new_content(
ctx: &StageCtx<'_>,
header: &FileHeader,
mut temp: TempFile,
create_mode: u32,
staging_name: &str,
) -> Result<()> {
apply_content_pre_seal(&mut temp, ctx.mode, ctx.verity, create_mode, header)?;
seal_temp(&mut temp, ctx.verity)?;
apply_content_post_seal(&mut temp, ctx.mode, header)?;
if ctx.fsync && ctx.per_object_fsync {
temp.sync()?;
}
temp.publish(ctx.staging, staging_name, Publish::KeepExisting, false)?;
Ok(())
}
pub(crate) fn stage_symlink_blocking(
ctx: &StageCtx<'_>,
checksum: &Checksum,
header: &FileHeader,
) -> Result<StageOutcome> {
let dest = loose_path(checksum, ObjectType::File, ctx.mode);
if ctx.objects.exists(&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 => {
let link = TempLink::create(ctx.staging, target)?;
link.set_owner(header.uid, header.gid)?;
for (name, value) in header.xattrs.iter() {
link.set_xattr(&xattr_name(name)?, value)?;
}
link.publish(ctx.staging, &staging_name, Publish::KeepExisting, false)?;
target.len() as u64
}
RepoMode::BareUserOnly => {
TempLink::create(ctx.staging, target)?.publish(
ctx.staging,
&staging_name,
Publish::KeepExisting,
false,
)?;
target.len() as u64
}
RepoMode::BareUser | RepoMode::BareUserShared => {
let mut content = target.clone().into_bytes();
content.push(0);
stage_named_regular(
ctx.staging,
&staging_name,
&content,
FIXED_MODE,
Some(&header.serialize_stat_metadata()?),
do_fsync,
ctx.verity,
)?
}
RepoMode::BareUserPrivate => {
let mut content = target.clone().into_bytes();
content.push(0);
let mut temp = TempFile::create(ctx.staging)?;
temp.file_mut().write_all(&content)?;
stage_new_content(ctx, header, temp, 0, &staging_name)?;
content.len() as u64
}
RepoMode::Archive => {
let body = frame(&header.serialize_archive(0)?)?;
stage_named_regular(
ctx.staging,
&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 ctx.objects.exists(&dest)? {
return Ok(dedup(dest));
}
let staging_name = flat_name(checksum, ty, ctx.mode);
let on_disk_size = stage_named_regular(
ctx.staging,
&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) fn stage_import_blocking(
ctx: &StageCtx<'_>,
src: &RepoDir,
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 ctx.objects.exists(&dest)? {
return Ok(Some(dedup(dest)));
}
let src_path = loose_path(checksum, ty, src_mode);
let staging_name = flat_name(checksum, ty, ctx.mode);
let object_error = |e: FsError| object_path_error(e, &src_path).into_object_error(checksum, ty);
if let Some(fresh_owner) = link_owner {
let link = repo_fs::link(src, &src_path, ctx.staging.as_fd(), &staging_name, false);
let linked_size = match link {
Ok(Published::Created) => {
let stat = ctx.staging.lstat(&staging_name)?;
let type_checked = check_leaf_type(&stat, ty, src_mode, &src_path);
let owned_as_written = (ty == ObjectType::File && ctx.mode == RepoMode::Bare)
|| (stat.uid, stat.gid) == fresh_owner;
if type_checked.is_ok() && owned_as_written {
Some(stat.size)
} else {
ctx.staging.remove_file(&staging_name, false)?;
type_checked?;
None
}
}
Ok(Published::Existed) => Some(ctx.staging.lstat(&staging_name)?.size),
Err(FsError::Io(e)) => {
link_refused(e, checksum, ty)?;
None
}
Err(e) => return Err(object_error(e)),
};
if let Some(on_disk_size) = linked_size {
return Ok(Some(StageOutcome {
deduped: false,
on_disk_size,
blocks: Blocks::Linked,
unpacked: 0,
staging_name,
dest,
}));
}
}
if ty == ObjectType::File {
return Ok(None);
}
let (on_disk_size, blocks) = clone_metadata(ctx, src, &src_path, &staging_name, checksum, ty)?;
Ok(Some(StageOutcome {
deduped: false,
on_disk_size,
blocks,
unpacked: 0,
staging_name,
dest,
}))
}
fn link_refused(e: io::Error, checksum: &Checksum, ty: ObjectType) -> Result<bool> {
match Errno::from_io_error(&e) {
Some(Errno::NOENT) => Err(Error::ObjectNotFound {
checksum: *checksum,
ty,
}),
Some(Errno::XDEV | Errno::MLINK | Errno::OPNOTSUPP | Errno::PERM) => Ok(false),
_ => Err(Error::Io(e)),
}
}
fn check_leaf_type(stat: &Stat, ty: ObjectType, src_mode: RepoMode, path: &str) -> Result<()> {
let reason = match stat.file_type {
FileType::RegularFile => return Ok(()),
FileType::Symlink
if ty == ObjectType::File
&& matches!(
src_mode,
RepoMode::Bare | RepoMode::BareUserOnly | RepoMode::BareSplitXattrs
) =>
{
return Ok(());
}
FileType::Symlink => Reason::Symlink,
other => Reason::NotRegular(other),
};
Err(FsError::Invalid {
path: format!("objects/{path}"),
reason,
}
.into())
}
pub(crate) fn stage_clone_content_blocking(
ctx: &StageCtx<'_>,
src: &RepoDir,
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 opened = src
.open_regular(&src_path)
.map_err(|e| e.into_object_error(checksum, ObjectType::File))?;
let mut temp = TempFile::create(ctx.staging)?;
let blocks = clone_into(&opened.file, &mut temp)?;
drop(opened);
let mut outcome = stage_content_blocking(ctx, checksum, header, temp, unpacked)?;
outcome.blocks = blocks;
Ok(outcome)
}
fn clone_into(src: &std::fs::File, temp: &mut TempFile) -> Result<Blocks> {
Ok(match repo_fs::clone_or_copy(src, temp.file_mut())? {
Cloned::Reflinked => Blocks::Reflinked,
Cloned::Copied => Blocks::Written,
})
}
fn clone_metadata(
ctx: &StageCtx<'_>,
src: &RepoDir,
src_path: &str,
staging_name: &str,
checksum: &Checksum,
ty: ObjectType,
) -> Result<(u64, Blocks)> {
let opened = src
.open_regular(src_path)
.map_err(|e| e.into_object_error(checksum, ty))?;
let mut temp = TempFile::create(ctx.staging)?;
let blocks = clone_into(&opened.file, &mut temp)?;
temp.set_mode(FIXED_MODE)?;
seal_temp(&mut temp, ctx.verity)?;
temp.publish(ctx.staging, staging_name, Publish::KeepExisting, false)?;
Ok((opened.stat.size, blocks))
}
pub(crate) fn publish_blocking(
root: &RepoDir,
objects: &RepoDir,
staging: &RepoDir,
staged: &[(String, String)],
syncfs: bool,
fsync: bool,
) -> Result<()> {
if syncfs {
root.syncfs()?;
}
let mut fanouts: Vec<&str> = Vec::new();
for (staging_name, dest) in staged {
let fanout = &dest[..2];
let (placed, _) =
rename_into_fanout(staging, staging_name, objects, dest, Publish::KeepExisting)?;
if placed == Published::Created && !fanouts.contains(&fanout) {
fanouts.push(fanout);
}
}
if fsync && !fanouts.is_empty() {
for fanout in &fanouts {
objects.sync_dir(fanout)?;
}
root.sync_dir("objects")?;
}
Ok(())
}
pub(crate) fn rename_into_fanout(
src: &RepoDir,
src_path: &str,
objects: &RepoDir,
dest: &str,
how: Publish,
) -> std::result::Result<(Published, bool), FsError> {
let fanout = &dest[..2];
match repo_fs::rename(src, src_path, objects, dest, how, false) {
Err(FsError::Absent { path }) if path.strip_prefix("objects/") == Some(fanout) => {
objects.ensure_dir(fanout, false)?;
let placed = repo_fs::rename(src, src_path, objects, dest, how, false)?;
Ok((placed, true))
}
other => other.map(|placed| (placed, false)),
}
}
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(
temp: &mut TempFile,
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
| RepoMode::BareUserPrivate
)
{
temp.set_mode(0o600)?;
}
match mode {
RepoMode::Bare => {}
RepoMode::BareUser | RepoMode::BareUserPrivate => {
set_ostreemeta(temp, header)?;
}
RepoMode::BareUserShared => {
temp.set_mode(FIXED_MODE)?;
set_ostreemeta(temp, header)?;
}
RepoMode::BareUserOnly => {}
RepoMode::Archive => {
temp.set_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(temp: &mut TempFile, mode: RepoMode, header: &FileHeader) -> Result<()> {
let perm = header.mode & PERM_MASK;
match mode {
RepoMode::Bare => {
temp.set_owner(header.uid, header.gid)?;
for (name, value) in header.xattrs.iter() {
temp.set_xattr(&xattr_name(name)?, value)?;
}
temp.set_mode(perm)?;
}
RepoMode::BareUser => {
temp.set_mode((perm & 0o775) | 0o400)?;
}
RepoMode::BareUserOnly => {
temp.set_mode(perm & 0o755)?;
}
RepoMode::BareUserPrivate => temp.set_mode(PRIVATE_MODE)?,
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(temp: &TempFile, header: &FileHeader) -> Result<()> {
let meta = header.serialize_stat_metadata()?;
temp.set_xattr(c"user.ostreemeta", &meta)?;
Ok(())
}
fn xattr_name(name: &[u8]) -> Result<CString> {
let name = name.strip_suffix(&[0]).unwrap_or(name);
std::str::from_utf8(name)
.map_err(|_| Error::InvalidFormat("xattr name is not valid UTF-8".into()))?;
CString::new(name).map_err(|_| Error::Io(Errno::INVAL.into()))
}
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: &RepoDir,
staging_name: &str,
content: &[u8],
perm: u32,
ostreemeta: Option<&[u8]>,
do_fsync: bool,
verity: Tristate,
) -> Result<u64> {
let mut temp = TempFile::create(staging)?;
temp.file_mut().write_all(content)?;
temp.set_mode(perm)?;
if let Some(meta) = ostreemeta {
temp.set_xattr(c"user.ostreemeta", meta)?;
}
if do_fsync {
temp.sync()?;
}
let size = content.len() as u64;
seal_temp(&mut temp, verity)?;
temp.publish(staging, staging_name, Publish::KeepExisting, false)?;
Ok(size)
}
fn seal_temp(temp: &mut TempFile, verity: Tristate) -> Result<bool> {
temp.seal(verity).map_err(|e| match e {
FsError::Io(e) if verity == Tristate::Yes => {
Error::Unsupported(format!("fsverity required but could not be enabled: {e}"))
}
other => other.into(),
})
}
pub(crate) fn probe_seal_blocking(root: &RepoDir) -> Result<bool> {
let mut temp = TempFile::create(root)?;
temp.file_mut().write_all(&[0])?;
match temp.seal(Tristate::Yes) {
Ok(sealed) => Ok(sealed),
Err(FsError::Io(_)) => Ok(false),
Err(e) => Err(e.into()),
}
}
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 super::{TempKind, open_named_temp};
use std::os::fd::OwnedFd;
use std::path::PathBuf;
use std::sync::Arc;
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"ostrya-{tag}-{}-{}",
std::process::id(),
super::unique()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn open_dir(dir: &std::path::Path) -> Arc<OwnedFd> {
Arc::new(std::fs::File::open(dir).unwrap().into())
}
#[test]
fn named_temp_removed_on_drop() {
let dir = scratch("named-temp-drop");
let (fd, kind) = open_named_temp(&open_dir(&dir)).unwrap();
let TempKind::Named(temp) = &kind else {
panic!("the helper gives a named temp, got {kind:?}");
};
let path = dir.join(temp.name());
assert!(path.exists(), "the named temp file exists");
drop((fd, kind));
let gone = !path.exists();
let _ = std::fs::remove_dir_all(&dir);
assert!(gone, "the drop removes the named temp file");
}
#[test]
fn named_temp_kept_after_rename_and_disarm() {
let dir = scratch("named-temp-keep");
let (fd, kind) = open_named_temp(&open_dir(&dir)).unwrap();
let TempKind::Named(mut temp) = kind else {
panic!("the helper gives a named temp, got {kind:?}");
};
let foreign = dir.join(temp.name());
std::fs::rename(&foreign, dir.join("target")).unwrap();
temp.disarm();
std::fs::write(&foreign, b"foreign").unwrap();
drop((fd, temp));
let target_kept = dir.join("target").exists();
let foreign_kept = foreign.exists();
let _ = std::fs::remove_dir_all(&dir);
assert!(target_kept, "the drop keeps the target");
assert!(
foreign_kept,
"the drop keeps the foreign file at the temp name"
);
}
}