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 miniz_oxide::deflate::core::CompressorOxide;
use miniz_oxide::deflate::stream::deflate;
use miniz_oxide::{DataFormat, MZError, MZFlush, MZStatus};
use ostrya_core::filehdr::frame;
use ostrya_core::{
Checksum, ContentHasher, 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 DEFLATE_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) = ostrya_rt::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,
mut 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) = ostrya_rt::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?;
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;
}
write_all(&mut 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,
});
}
flush(&mut file).await?;
let std_file = file.into_std().await;
self.stage_regular(
checksum,
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
}
}
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) 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,
false,
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_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))
}
pub(crate) fn publish_blocking(
repo_fd: BorrowedFd<'_>,
objects_fd: BorrowedFd<'_>,
staging_fd: BorrowedFd<'_>,
objects: &[(String, String)],
fsync: bool,
repo_mode: RepoMode,
) -> 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, 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)?;
}
rustix::fs::fsync(objects_fd)?;
}
Ok(())
}
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}"
)))
}
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 DeflateSink<W> {
inner: W,
compressor: Box<CompressorOxide>,
out: Vec<u8>,
sent: usize,
filled: usize,
syncing: bool,
flushed: bool,
done: bool,
}
impl<W> DeflateSink<W> {
fn new(inner: W, level: u8) -> DeflateSink<W> {
let mut compressor = Box::<CompressorOxide>::default();
compressor.set_format_and_level(DataFormat::Raw, level);
DeflateSink {
inner,
compressor,
out: vec![0u8; DEFLATE_CHUNK],
sent: 0,
filled: 0,
syncing: false,
flushed: true,
done: false,
}
}
fn into_inner(self) -> W {
self.inner
}
}
impl<W: AsyncWrite + Unpin> DeflateSink<W> {
fn poll_drain(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
while self.sent < self.filled {
let n = std::task::ready!(
Pin::new(&mut self.inner).poll_write(cx, &self.out[self.sent..self.filled])
)?;
if n == 0 {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::WriteZero,
"write returned zero",
)));
}
self.sent += n;
}
self.sent = 0;
self.filled = 0;
Poll::Ready(Ok(()))
}
fn poll_step(
&mut self,
cx: &mut Context<'_>,
input: &[u8],
flush: MZFlush,
) -> Poll<io::Result<(usize, usize, bool)>> {
std::task::ready!(self.poll_drain(cx))?;
let res = deflate(&mut self.compressor, input, &mut self.out, flush);
self.filled = res.bytes_written;
let end = match res.status {
Ok(MZStatus::StreamEnd) => true,
Ok(_) | Err(MZError::Buf) => false,
Err(e) => {
return Poll::Ready(Err(io::Error::other(format!(
"the DEFLATE encoder failed: {e:?}"
))));
}
};
Poll::Ready(Ok((res.bytes_consumed, res.bytes_written, end)))
}
}
impl<W: AsyncWrite + Unpin> AsyncWrite for DeflateSink<W> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
if buf.is_empty() {
return Poll::Ready(Ok(0));
}
let me = self.get_mut();
loop {
let (taken, produced, _) = std::task::ready!(me.poll_step(cx, buf, MZFlush::None))?;
me.flushed = false;
me.syncing = false;
if taken > 0 {
return Poll::Ready(Ok(taken));
}
if produced == 0 {
return Poll::Ready(Err(io::Error::other(
"the DEFLATE encoder took no input and produced no output",
)));
}
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let me = self.get_mut();
while !me.flushed {
let flush = if me.syncing {
MZFlush::None
} else {
MZFlush::Sync
};
let (_, produced, _) = std::task::ready!(me.poll_step(cx, &[], flush))?;
me.syncing = true;
if produced == 0 {
me.flushed = true;
me.syncing = false;
}
}
std::task::ready!(me.poll_drain(cx))?;
Pin::new(&mut me.inner).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let me = self.get_mut();
while !me.done {
let (_, _, end) = std::task::ready!(me.poll_step(cx, &[], MZFlush::Finish))?;
me.done = end;
}
std::task::ready!(me.poll_drain(cx))?;
Pin::new(&mut me.inner).poll_flush(cx)
}
}
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();
}
}
#[cfg(test)]
mod deflate_tests {
use std::collections::BTreeSet;
use super::{Checksum, DEFLATE_CHUNK, DeflateSink, archive_level, close, flush, write_all};
use ostrya_rt::block_on;
use sha2::{Digest, Sha256};
const GOLDEN: [&str; 9] = [
"a1fd96479b110a51c3b9c333da0ff6879cd295fc27a98b48c88b70a0ea558bb4",
"7964fd5c5e4ffb18bf953852b31704681eaf7a4590d488a01be5f213978c0876",
"e5ff230c2f7715f8883cbd5c19ee1255f165c7e25fc886516c290b0d246954a0",
"7ae743a6aa5027a1ef08604f6c0a4e6062d39f73879dd0789780aca2e8027932",
"95b7d927a18b71b941598bf6411029653910307881528355a5b18cccfd3dea0a",
"b9b31232e8e4458ff831e1de64ba695c0c07b630215e2ce01d372fa2fd8bbcc3",
"8436585ce3c3eea757ab9d5020de4b41c3f32ac29fdd8b5c02ec8ec51df9067d",
"c1bc0d4abcb002a3e15241b86c7f200ddc4c71ff30752a7ce933755433ceb88c",
"b6ddd39fc7e629dfcc81b42ba9706eb6e4e46cd4f90527d3e1ccda0d072faca7",
];
const GOLDEN_FLUSHED: &str = "009e2fd466deb6af8f1828281fccd0a7be5fef1356215f1eaa10708a86caa4b3";
fn xorshift(state: &mut u32) -> u32 {
*state ^= *state << 13;
*state ^= *state >> 17;
*state ^= *state << 5;
*state
}
fn golden_payload() -> Vec<u8> {
const BLOCK: usize = DEFLATE_CHUNK / 2;
let mut out = Vec::with_capacity(3 * BLOCK);
let mut state: u32 = 0x1234_5678;
for _ in 0..BLOCK / 16 {
let word = xorshift(&mut state);
for k in 0..16 {
out.push(b'A' + ((word >> (2 * k)) & 3) as u8);
}
}
for _ in 0..2 * BLOCK {
out.push((xorshift(&mut state) >> 24) as u8);
}
out
}
fn encode(data: &[u8], zlib_level: i64, chunk: usize) -> Vec<u8> {
block_on(async {
let mut sink = DeflateSink::new(Vec::new(), archive_level(zlib_level));
for part in data.chunks(chunk) {
write_all(&mut sink, part).await.unwrap();
}
close(&mut sink).await.unwrap();
sink.into_inner()
})
}
fn encode_with_a_flush(data: &[u8]) -> Vec<u8> {
block_on(async {
let mut sink = DeflateSink::new(Vec::new(), archive_level(6));
let (head, tail) = data.split_at(data.len() / 2);
write_all(&mut sink, head).await.unwrap();
flush(&mut sink).await.unwrap();
write_all(&mut sink, tail).await.unwrap();
close(&mut sink).await.unwrap();
sink.into_inner()
})
}
fn hash(bytes: &[u8]) -> String {
Checksum::from_bytes(Sha256::digest(bytes).into()).to_hex()
}
#[test]
fn deflate_output_matches_the_golden_hashes() {
let data = golden_payload();
assert!(
data.len() > DEFLATE_CHUNK,
"the payload spans more than one chunk"
);
assert_eq!(
GOLDEN.iter().collect::<BTreeSet<_>>().len(),
GOLDEN.len(),
"each level reaches its own bytes"
);
for (i, &want) in GOLDEN.iter().enumerate() {
let level = i as i64 + 1;
let out = encode(&data, level, 1);
assert!(
out.len() > DEFLATE_CHUNK,
"level {level}: output spans more than one chunk"
);
for chunk in [4093, data.len()] {
assert_eq!(
encode(&data, level, chunk),
out,
"level {level}, {chunk}-byte writes"
);
}
assert_eq!(hash(&out), want, "DEFLATE level {level} output hash");
}
let flushed = hash(&encode_with_a_flush(&data));
assert_eq!(
flushed, GOLDEN_FLUSHED,
"DEFLATE level 6 output hash after a flush"
);
assert_ne!(
flushed, GOLDEN[5],
"a flush ends the DEFLATE block, so it reaches the output"
);
}
}