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::Level;
use async_compression::futures::write::DeflateEncoder;
use futures_io::{AsyncRead, AsyncSeek, AsyncWrite};
use ostrya_core::filehdr::frame;
use ostrya_core::{Checksum, 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::error::{Error, Result};
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 FIXED_MODE: u32 = 0o644;
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(),
}
}
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: SYMLINK_MODE,
symlink_target: target.to_owned(),
xattrs: self.xattrs.clone(),
}
}
}
#[derive(Debug)]
pub(crate) enum TempKind {
Anonymous,
Named(String),
}
pub struct ContentWriter<'txn> {
txn: &'txn Transaction,
hasher: Sha256,
uncompressed: u64,
header: FileHeader,
expected: Option<Checksum>,
temp: TempKind,
sink: Sink,
}
enum Sink {
Plain(RtFile),
Archive(DeflateEncoder<NoClose<RtFile>>),
}
impl ContentWriter<'_> {
pub async fn finish(self) -> Result<Checksum> {
let ContentWriter {
txn,
hasher,
uncompressed,
header,
expected,
temp,
sink,
} = 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().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, uncompressed)
.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 = 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) = ostrya_rt::unblock(move || open_temp(staging.as_fd())).await?;
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(DeflateEncoder::with_quality(NoClose::new(file), level))
} else {
Sink::Plain(file)
};
Ok(ContentWriter {
txn: self,
hasher,
uncompressed: 0,
header,
expected: expected.copied(),
temp,
sink,
})
}
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 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 = 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_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
}
}
fn archive_level(zlib_level: i64) -> Level {
Level::Precise(zlib_level.clamp(1, 9) as i32)
}
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)))
}
}
}
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) struct StageOutcome {
pub(crate) deduped: bool,
pub(crate) on_disk_size: u64,
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));
}
apply_content_metadata(file.as_fd(), ctx.mode, header)?;
if ctx.fsync && ctx.per_object_fsync {
rustix::fs::fsync(file.as_fd())?;
}
let on_disk_size = size_of(file.as_fd())?;
let staging_name = flat_name(checksum, ObjectType::File, ctx.mode);
materialize(ctx.staging_fd, &file, &temp, &staging_name)?;
drop(file);
Ok(StageOutcome {
deduped: false,
on_disk_size,
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,
)?
}
RepoMode::Archive => {
let body = frame(&header.serialize_archive(0)?)?;
stage_named_regular(staging_fd, &staging_name, &body, FIXED_MODE, None, do_fsync)?
}
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,
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.per_object_fsync,
)?;
Ok(StageOutcome {
deduped: false,
on_disk_size,
unpacked: 0,
staging_name,
dest,
})
}
pub(crate) fn publish_blocking(
repo_fd: BorrowedFd<'_>,
objects_fd: BorrowedFd<'_>,
staging_fd: BorrowedFd<'_>,
objects: &[(String, String)],
fsync: bool,
) -> Result<()> {
if fsync {
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)?;
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)?;
}
rustix::fs::fsync(objects_fd)?;
}
Ok(())
}
fn ensure_fanout(objects_fd: BorrowedFd<'_>, fanout: &str) -> Result<()> {
match rustix::fs::mkdirat(objects_fd, fanout, Mode::from_raw_mode(0o777)) {
Ok(()) | Err(rustix::io::Errno::EXIST) => Ok(()),
Err(e) => Err(e.into()),
}
}
fn dedup(dest: String) -> StageOutcome {
StageOutcome {
deduped: true,
on_disk_size: 0,
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_metadata(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)))?;
rustix::fs::fchmod(fd, Mode::from_raw_mode(perm))?;
for (name, value) in header.xattrs.iter() {
set_inode_xattr(fd, name, value)?;
}
}
RepoMode::BareUser => {
rustix::fs::fchmod(fd, Mode::from_raw_mode((perm & 0o775) | 0o400))?;
set_ostreemeta(fd, header)?;
}
RepoMode::BareUserShared => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(FIXED_MODE))?;
set_ostreemeta(fd, header)?;
}
RepoMode::BareUserOnly => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(perm & 0o755))?;
}
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 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,
) -> 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())?;
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 materialize(
staging_fd: BorrowedFd<'_>,
file: &std::fs::File,
temp: &TempKind,
staging_name: &str,
) -> Result<()> {
match temp {
TempKind::Anonymous => {
let proc_path = format!("/proc/self/fd/{}", file.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 NoClose<W> {
inner: W,
}
impl<W> NoClose<W> {
fn new(inner: W) -> NoClose<W> {
NoClose { inner }
}
fn into_inner(self) -> W {
self.inner
}
}
impl<W: AsyncWrite + Unpin> AsyncWrite for NoClose<W> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
}
}
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
}
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>>();
};