use std::fs::File;
use std::io::BufWriter;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use crate::ArchiveError;
use crate::EntryPosition;
use crate::ExistingFiles;
use crate::ExtractionReport;
use crate::Malformation;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::Skip;
use crate::SkipKind;
pub(crate) use crate::SpecialFile;
use crate::Violation;
use crate::copy::CopyBuffer;
use crate::copy::CopyError;
use crate::copy::copy_cancellable;
use crate::error::QuotaResource;
use crate::formats::dir_walker::DirWalker;
use crate::formats::occupant::KeptOccupant;
use crate::formats::occupant::OccupantAction;
use crate::formats::occupant::ReplacePermit;
use crate::formats::occupant::kept_occupant_refusal;
use crate::formats::occupant::replaces_symlink;
use crate::formats::pinned_dir::Leaf;
use crate::formats::pinned_dir::PendingMode;
use crate::formats::pinned_dir::PinnedRoot;
use crate::formats::pinned_dir::TempFileGuard;
use crate::formats::pinned_dir::TempLeaf;
use crate::formats::pinned_dir::VettedDir;
use crate::formats::source_fault::ReadFaults;
use crate::mark::MarkRun;
use crate::security::fs_view::HostFs;
#[cfg(unix)]
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::Occupant;
use crate::security::fs_view::PathModel;
use crate::security::fs_view::blocked_parent_error;
use crate::security::permissions::SanitizedMode;
use crate::security::quota::QuotaPermit;
use crate::selection::EntryShape;
use crate::types::DestDir;
use crate::types::SafePath;
use crate::types::SafeSymlink;
use crate::types::dest_dir::ProbePath;
use crate::types::safe_path::ParentCheck;
pub(crate) fn open_archive(path: &Path) -> Result<File> {
File::open(path).map_err(|error| crate::creation::source::source_error(path, error))
}
pub(crate) struct EntryCompleteGuard<'a> {
progress: &'a mut dyn ProgressCallback,
path: &'a std::path::Path,
fired: bool,
}
impl<'a> EntryCompleteGuard<'a> {
pub(crate) fn try_start(
progress: &'a mut dyn ProgressCallback,
path: &'a std::path::Path,
position: EntryPosition,
) -> Result<Self> {
if progress.is_cancelled() {
return Err(ArchiveError::Cancelled);
}
progress.on_entry_start(path, position);
Ok(Self {
progress,
path,
fired: false,
})
}
pub(crate) fn progress_mut(&mut self) -> &mut dyn ProgressCallback {
self.progress
}
pub(crate) fn complete(mut self) {
self.fired = true;
self.progress.on_entry_complete(self.path);
}
}
impl Drop for EntryCompleteGuard<'_> {
fn drop(&mut self) {
if !self.fired {
self.progress.on_entry_complete(self.path);
}
}
}
#[inline]
#[must_use]
pub(crate) fn normalize_entry_name(name: &str) -> String {
if name.contains('\\') {
name.replace('\\', "/")
} else {
name.to_owned()
}
}
#[must_use]
pub(crate) fn encrypted_archive_error() -> ArchiveError {
Violation::EncryptedArchive.into()
}
#[inline]
pub(crate) fn checked_add_bytes(total: u64, n: u64) -> Result<u64> {
total.checked_add(n).ok_or(ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow,
})
}
#[inline]
pub(crate) fn checked_add_count(total: usize, n: usize) -> Result<usize> {
total.checked_add(n).ok_or(ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow,
})
}
pub(crate) fn record_skip(
report: &mut ExtractionReport,
kind: SkipKind,
path: &Path,
) -> Result<()> {
report.skipped.record(Skip::new(kind, path))
}
pub(crate) fn record_duplicate_skip(report: &mut ExtractionReport, path: &Path) -> Result<()> {
record_skip(report, SkipKind::Duplicate, path)
}
#[must_use]
pub(crate) fn is_extension_allowed(path: &Path, config: &SecurityConfig) -> bool {
config.is_extension_allowed(path.extension().and_then(|e| e.to_str()))
}
pub(crate) fn check_entry_name_limits(
model: PathModel,
path: &Path,
regular_file: bool,
config: &SecurityConfig,
) -> std::io::Result<()> {
if regular_file && !is_extension_allowed(path, config) {
return Ok(());
}
model.check_name_lengths(path)
}
#[expect(
clippy::too_many_arguments,
reason = "arguments are threaded through from the caller; a parameter struct adds indirection"
)]
#[inline]
pub(crate) fn extract_file_with_permit<R: Read, P: ParentCheck>(
reader: &mut R,
faults: ReadFaults<'_>,
safe_path: &SafePath<P>,
mode: Option<SanitizedMode>,
permit: QuotaPermit,
root: &PinnedRoot,
report: &mut ExtractionReport,
copy_buffer: &mut CopyBuffer,
dirs: DirWalker,
options: SinkOptions,
progress: &mut dyn ProgressCallback,
) -> Result<()> {
let duplicates = options.existing_files;
let (parent, leaf) = dirs.ensure_parent(root, safe_path)?;
let expected_size = permit.into_bytes();
checked_add_bytes(report.bytes_written, expected_size)?;
let marking = root.marking();
let timing = ModeTiming::of(marking);
let Some(OutputSlot {
file: output_file,
pending,
written_at,
}) = open_output_slot(
&parent,
leaf,
safe_path.as_path(),
mode,
duplicates,
root,
timing,
)?
else {
return record_duplicate_skip(report, safe_path.as_path());
};
let guard = written_at.guard(&parent, leaf);
let mut buffered_writer = BufWriter::with_capacity(64 * 1024, output_file);
let bytes_written = copy_cancellable(
reader,
&mut buffered_writer,
copy_buffer,
Some(expected_size),
&mut *progress,
)
.map_err(|error| faults.classify(error))?;
buffered_writer.flush()?;
drop(finish_written(buffered_writer, pending, marking)?);
let replaced = matches!(written_at, WrittenAt::Temp(..));
commit_output(&parent, written_at, leaf, safe_path.as_path())?;
if replaced {
root.created()
.note(duplicates, &parent, leaf, safe_path.as_path());
}
guard.persist();
record_file_written(report, progress, bytes_written)
}
pub(crate) fn record_file_written(
report: &mut ExtractionReport,
progress: &mut dyn ProgressCallback,
written: u64,
) -> Result<()> {
report.files_extracted = checked_add_count(report.files_extracted, 1)?;
report.bytes_written = checked_add_bytes(report.bytes_written, written)?;
if written > 0 {
progress.on_bytes_written(written);
}
Ok(())
}
pub(crate) const MAX_TEMP_FILE_CREATE_ATTEMPTS: u32 = 8;
pub(crate) fn create_temp_sibling(
dir: &VettedDir,
entry: Leaf<'_>,
mode: Option<SanitizedMode>,
replace: &ReplacePermit,
next_candidate: impl FnMut() -> TempLeaf,
) -> std::io::Result<(TempLeaf, File)> {
create_temp_sibling_with(
dir,
entry,
mode,
ModeTiming::AtCreate,
replace,
next_candidate,
)
.map(|(temp, file, _)| (temp, file))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ModeTiming {
AtCreate,
AfterMark,
}
pub(crate) fn create_temp_sibling_with(
dir: &VettedDir,
entry: Leaf<'_>,
mode: Option<SanitizedMode>,
timing: ModeTiming,
_replace: &ReplacePermit,
mut next_candidate: impl FnMut() -> TempLeaf,
) -> std::io::Result<(TempLeaf, File, PendingMode)> {
for _ in 0..MAX_TEMP_FILE_CREATE_ATTEMPTS {
let candidate = next_candidate();
match create_file(dir, candidate.as_leaf(), mode, timing) {
Ok((file, pending)) => return Ok((candidate, file, pending)),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
}
Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
crate::IoContext::new(
"failed to create a unique temp file",
format!(
"{} after {MAX_TEMP_FILE_CREATE_ATTEMPTS} attempts",
crate::path_text(Path::new(entry.as_os_str()))
),
),
))
}
enum WrittenAt {
Final,
Temp(TempLeaf, ReplacePermit),
}
impl WrittenAt {
fn guard<'d>(&self, dir: &'d VettedDir, final_name: Leaf<'_>) -> TempFileGuard<'d> {
match self {
Self::Final => TempFileGuard::new(dir, final_name),
Self::Temp(temp, _) => TempFileGuard::for_temp(dir, temp.clone()),
}
}
}
impl ModeTiming {
pub(crate) const fn of(marking: Option<&MarkRun>) -> Self {
if marking.is_some() {
Self::AfterMark
} else {
Self::AtCreate
}
}
}
pub(crate) fn create_file(
dir: &VettedDir,
leaf: Leaf<'_>,
mode: Option<SanitizedMode>,
timing: ModeTiming,
) -> std::io::Result<(File, PendingMode)> {
let (file, pending) = dir.create_new_deferred(leaf, mode)?;
match timing {
ModeTiming::AfterMark => Ok((file, pending)),
ModeTiming::AtCreate => {
pending.apply(&file)?;
Ok((file, PendingMode::applied()))
}
}
}
pub(crate) fn seal_output(
file: &File,
pending: PendingMode,
marking: Option<&MarkRun>,
) -> std::io::Result<()> {
if let Some(run) = marking {
run.mark_file(file);
}
pending.apply(file)
}
pub(crate) fn finish_written(
writer: BufWriter<File>,
pending: PendingMode,
marking: Option<&MarkRun>,
) -> std::io::Result<File> {
let file = writer
.into_inner()
.map_err(std::io::IntoInnerError::into_error)?;
seal_output(&file, pending, marking)?;
Ok(file)
}
struct OutputSlot {
file: File,
pending: PendingMode,
written_at: WrittenAt,
}
fn open_output_slot(
dir: &VettedDir,
leaf: Leaf<'_>,
rel: &Path,
mode: Option<SanitizedMode>,
duplicates: ExistingFiles,
root: &PinnedRoot,
timing: ModeTiming,
) -> Result<Option<OutputSlot>> {
match create_file(dir, leaf, mode, timing) {
Ok((file, pending)) => {
root.created().note_file(duplicates, &file, dir, leaf, rel);
Ok(Some(OutputSlot {
file,
pending,
written_at: WrittenAt::Final,
}))
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let action = duplicates.on_occupant(
EntryShape::File,
|| dir.probe(leaf),
|| root.created().created_here(dir, leaf, rel),
|| destination_occupied(root.dest().as_path(), rel),
)?;
let OccupantAction::Replace(permit) = action else {
return Ok(None);
};
refuse_non_file_occupant(dir, leaf, rel, root)?;
let (temp, file, pending) =
create_temp_sibling_with(dir, leaf, mode, timing, &permit, TempLeaf::next)
.map_err(|e| replace_error(rel, &e))?;
Ok(Some(OutputSlot {
file,
pending,
written_at: WrittenAt::Temp(temp, permit),
}))
}
Err(e) => Err(name_occupant_on_open_error(dir, leaf, rel, root, e)),
}
}
pub(crate) fn destination_occupied(destination: &Path, rel: &Path) -> ArchiveError {
ArchiveError::DestinationOccupied {
destination: Some(destination.to_path_buf()),
conflicts: Box::new([rel.to_path_buf()]),
by: crate::OccupiedBy::Existing,
}
}
pub(crate) fn occupied_without_destination(rel: &Path) -> ArchiveError {
ArchiveError::DestinationOccupied {
destination: None,
conflicts: Box::new([rel.to_path_buf()]),
by: crate::OccupiedBy::Existing,
}
}
fn commit_output(dir: &VettedDir, written_at: WrittenAt, leaf: Leaf<'_>, rel: &Path) -> Result<()> {
if let WrittenAt::Temp(temp, permit) = written_at {
dir.replace_entry(&temp, leaf, permit)
.map_err(|e| replace_error(rel, &e))?;
}
Ok(())
}
fn replace_error(rel: &Path, err: &std::io::Error) -> std::io::Error {
std::io::Error::new(
err.kind(),
crate::IoContext::new(
"cannot replace the existing file",
format!("{}: {err}", crate::path_text(rel)),
),
)
}
fn refuse_non_file_occupant(
dir: &VettedDir,
leaf: Leaf<'_>,
rel: &Path,
root: &PinnedRoot,
) -> Result<()> {
let kept = dir.probe(leaf).ok().flatten().and_then(KeptOccupant::of);
kept.map_or(Ok(()), |kept| {
Err(kept_refusal_at(kept, dir, leaf, rel, root))
})
}
pub(crate) fn kept_refusal_at(
kept: KeptOccupant,
dir: &VettedDir,
leaf: Leaf<'_>,
rel: &Path,
root: &PinnedRoot,
) -> ArchiveError {
kept_occupant_refusal(
kept,
rel,
|| root.created().created_here(dir, leaf, rel),
|| destination_occupied(root.dest().as_path(), rel),
)
}
pub(crate) fn create_directory<P: ParentCheck>(
safe_path: &SafePath<P>,
root: &PinnedRoot,
report: &mut ExtractionReport,
dirs: DirWalker,
) -> Result<()> {
check_directory_occupant(
&root.dest().probe(safe_path.as_path()),
safe_path.as_path(),
root.dest(),
)?;
dirs.ensure_dir(root, safe_path)?;
report.directories_created = report.directories_created.saturating_add(1);
Ok(())
}
pub(crate) fn check_directory_occupant(
probe: &ProbePath,
rel: &Path,
dest: &DestDir,
) -> Result<()> {
let file_type = match probe.lstat() {
Ok(metadata) => metadata.file_type(),
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidFilename
) =>
{
return Ok(());
}
Err(e) => {
return Err(blocked_parent_error(&HostFs, dest, rel).unwrap_or_else(|| e.into()));
}
};
if file_type.is_dir() {
return Ok(());
}
if file_type.is_symlink() {
return probe
.lands_in_dir(dest)
.ok_or_else(|| replaces_symlink(rel));
}
Err(file_occupant_error(rel).into())
}
#[cfg_attr(
not(unix),
expect(
unused_variables,
reason = "only the Unix path reads the entry, the handles and the options"
)
)]
#[cfg_attr(
not(unix),
expect(
clippy::needless_pass_by_ref_mut,
reason = "only the Unix path updates the counters; the signature is shared"
)
)]
pub(crate) fn create_symlink<P: ParentCheck>(
safe_symlink: &SafeSymlink<P>,
root: &PinnedRoot,
report: &mut ExtractionReport,
dirs: DirWalker,
options: SinkOptions,
) -> Result<()> {
#[cfg(unix)]
{
let duplicates = options.existing_files;
let target_path = safe_symlink.target_path();
let (parent, leaf) = dirs.ensure_parent(root, safe_symlink.link())?;
if let Some(existing) = parent.probe(leaf)? {
let link_path = safe_symlink.link().as_path();
let action = duplicates.on_occupant(
EntryShape::Link(LinkKind::Symlink),
|| Ok(Some(existing)),
|| root.created().created_here(&parent, leaf, link_path),
|| destination_occupied(root.dest().as_path(), link_path),
)?;
let OccupantAction::Replace(permit) = action else {
return record_duplicate_skip(report, link_path);
};
match existing {
Occupant::Symlink => {
if parent.read_link(leaf)? == target_path {
return record_duplicate_skip(report, link_path);
}
return Err(kept_refusal_at(
KeptOccupant::Symlink,
&parent,
leaf,
link_path,
root,
));
}
Occupant::Directory => {
return Err(kept_refusal_at(
KeptOccupant::Directory,
&parent,
leaf,
link_path,
root,
));
}
Occupant::File => parent.remove_occupant(leaf, permit)?,
}
}
parent.symlink(target_path, leaf)?;
root.created()
.note(duplicates, &parent, leaf, safe_symlink.link().as_path());
report.symlinks_created = report.symlinks_created.saturating_add(1);
Ok(())
}
#[cfg(not(unix))]
{
require_symlink_creation()
}
}
pub(crate) fn file_occupant_error(rel: &Path) -> std::io::Error {
std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
Occupant::File.refusal(rel),
)
}
fn name_occupant_on_open_error(
dir: &VettedDir,
leaf: Leaf<'_>,
rel: &Path,
root: &PinnedRoot,
err: std::io::Error,
) -> ArchiveError {
refused_occupant(dir, leaf, &err).map_or(ArchiveError::Io(err), |kept| {
kept_refusal_at(kept, dir, leaf, rel, root)
})
}
fn refused_occupant(dir: &VettedDir, leaf: Leaf<'_>, err: &std::io::Error) -> Option<KeptOccupant> {
use std::io::ErrorKind;
let occupant = dir.probe(leaf).ok()??;
let dir_refusal = err.kind() == ErrorKind::IsADirectory
|| (cfg!(not(unix)) && err.kind() == ErrorKind::PermissionDenied);
let symlink_refusal = if cfg!(unix) {
is_filesystem_loop_error(err)
} else {
err.kind() == ErrorKind::AlreadyExists
};
match occupant {
Occupant::Directory if dir_refusal => Some(KeptOccupant::Directory),
Occupant::Symlink if symlink_refusal => Some(KeptOccupant::Symlink),
Occupant::Directory | Occupant::Symlink | Occupant::File => None,
}
}
pub(crate) fn require_symlink_creation() -> Result<()> {
cfg!(unix).ok_or_else(|| Violation::SymlinksUnsupported.into())
}
const S_IFMT: u32 = 0o17_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UnixFileType {
Regular,
Directory,
Symlink,
Special(SpecialFile),
Undefined(u8),
}
impl UnixFileType {
pub(crate) fn from_mode(mode: u32) -> Option<Self> {
match mode & S_IFMT {
0 => None,
0o10_0000 => Some(Self::Regular),
0o04_0000 => Some(Self::Directory),
0o12_0000 => Some(Self::Symlink),
0o01_0000 => Some(Self::Special(SpecialFile::Fifo)),
0o02_0000 => Some(Self::Special(SpecialFile::CharDevice)),
0o06_0000 => Some(Self::Special(SpecialFile::BlockDevice)),
0o14_0000 => Some(Self::Special(SpecialFile::Socket)),
bits => Some(Self::Undefined(u8::try_from(bits >> 12).unwrap_or(u8::MAX))),
}
}
}
pub(crate) const MAX_STORED_SYMLINK_TARGET: u64 =
crate::security::fs_view::MAX_SYMLINK_TARGET_BYTES as u64;
pub(crate) fn check_symlink_target_size(size: u64) -> Result<()> {
if size > MAX_STORED_SYMLINK_TARGET {
return Err(symlink_target_too_large(size));
}
Ok(())
}
pub(crate) fn symlink_target_too_large(size: u64) -> ArchiveError {
Violation::LinkTargetTooLarge {
size,
max: MAX_STORED_SYMLINK_TARGET,
}
.into()
}
pub(crate) fn symlink_target_from_bytes(target_bytes: &[u8]) -> Result<PathBuf> {
let target_str = std::str::from_utf8(target_bytes)
.map_err(|_| ArchiveError::from(Malformation::SymlinkTargetNotUtf8))?;
Ok(PathBuf::from(target_str))
}
#[cfg(any(unix, target_os = "wasi"))]
pub(crate) fn errno_is(error: &std::io::Error, set: &[rustix::io::Errno]) -> bool {
rustix::io::Errno::from_io_error(error).is_some_and(|errno| set.contains(&errno))
}
#[must_use]
pub(crate) fn is_filesystem_loop_error(error: &std::io::Error) -> bool {
#[cfg(unix)]
{
errno_is(error, &[rustix::io::Errno::LOOP])
}
#[cfg(not(unix))]
{
let _ = error;
false
}
}
fn hardlink_target_changed(error: CopyError) -> ArchiveError {
match error {
CopyError::Overrun { .. } | CopyError::Short { .. } => {
Violation::HardlinkTargetChanged.into()
}
other => other.into(),
}
}
pub(crate) fn copy_file_content_with_permit(
mut from: File,
to: &mut File,
copy_buffer: &mut CopyBuffer,
permit: QuotaPermit,
progress: &mut dyn ProgressCallback,
) -> Result<u64> {
copy_cancellable(
&mut from,
to,
copy_buffer,
Some(permit.into_bytes()),
progress,
)
.map_err(hardlink_target_changed)
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use crate::ArchiveError;
use crate::ExtractionReport;
use crate::Malformation;
use crate::NoopProgress;
use crate::SecurityConfig;
use crate::copy::CopyBuffer;
use crate::formats::source_fault::ReadFamily;
use crate::formats::source_fault::SourceTap;
use crate::security::RawMode;
use crate::security::fs_view::normalized_display;
use crate::security::permissions::sanitize_permissions;
use crate::security::quota::QuotaTracker;
use std::assert_matches;
use std::io::Cursor;
use std::path::PathBuf;
use tempfile::TempDir;
#[cfg(any(unix, target_os = "wasi"))]
#[test]
fn errno_is_matches_only_the_listed_codes() {
use rustix::io::Errno;
let error = |errno: Errno| std::io::Error::from_raw_os_error(errno.raw_os_error());
let all = [
Errno::NOENT,
Errno::NOTDIR,
Errno::LOOP,
Errno::ACCESS,
Errno::NOTSUP,
Errno::INVAL,
Errno::BADF,
Errno::MFILE,
Errno::NFILE,
Errno::NOMEM,
];
for listed in all {
for observed in all {
assert_eq!(
errno_is(&error(observed), &[listed]),
observed == listed,
"{observed:?} against {listed:?}"
);
}
assert!(errno_is(&error(listed), &all));
assert!(!errno_is(&error(listed), &[]));
}
assert!(!errno_is(&std::io::Error::other("no code"), &all));
assert_eq!(
errno_is(&error(Errno::OPNOTSUPP), &[Errno::NOTSUP]),
Errno::OPNOTSUPP == Errno::NOTSUP,
"equal on Linux, distinct on macOS"
);
}
fn sanitized(mode: u32) -> SanitizedMode {
let config = SecurityConfig::default();
sanitize_permissions(RawMode::new(mode), &config)
}
fn test_walker() -> DirWalker {
DirWalker::new(&SecurityConfig::default())
}
fn pinned(dest: &DestDir) -> PinnedRoot {
PinnedRoot::open(dest.clone()).expect("open destination")
}
fn create_file_with_mode(path: &Path, mode: Option<SanitizedMode>) -> std::io::Result<File> {
let parent = pinned(&DestDir::new(path.parent().expect("parent")).expect("dest"));
let (_, leaf) = Leaf::split(Path::new(path.file_name().expect("name"))).expect("leaf");
parent.dir().reopen()?.create_new(leaf, mode)
}
#[test]
fn normalize_entry_name_turns_backslashes_into_slashes_only() {
assert_eq!(normalize_entry_name("foo\\bar\\baz.txt"), "foo/bar/baz.txt");
assert_eq!(normalize_entry_name("plain/path.txt"), "plain/path.txt");
}
#[test]
fn file_occupant_error_names_the_entry_and_the_occupant() {
let rel = Path::new("a/b");
let err = file_occupant_error(rel);
assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists);
assert_eq!(
err.to_string(),
format!(
"refusing to replace the existing file at {}",
normalized_display(rel)
)
);
}
#[cfg(unix)]
#[test]
fn replace_refusals_of_names_differing_in_invalid_bytes_differ() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let io = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
let message =
|bytes: &[u8]| replace_error(Path::new(OsStr::from_bytes(bytes)), &io).to_string();
let (a, b) = (message(b"caf\xe9"), message(b"caf\xe8"));
assert_ne!(a, b);
assert!(!a.contains('\u{FFFD}'), "{a}");
let occupant =
|bytes: &[u8]| file_occupant_error(Path::new(OsStr::from_bytes(bytes))).to_string();
assert_ne!(occupant(b"caf\xe9"), occupant(b"caf\xe8"));
}
#[test]
fn open_error_is_renamed_only_when_it_matches_the_occupant() {
use std::io::Error;
use std::io::ErrorKind;
let temp = TempDir::new().expect("temp dir");
std::fs::create_dir(temp.path().join("d")).expect("mkdir");
let root = pinned(&DestDir::new(temp.path()).expect("dest"));
let dir = root.dir();
let leaf = |name: &'static str| Leaf::split(Path::new(name)).expect("leaf").1;
let refused = Error::from(ErrorKind::IsADirectory);
assert_matches!(
refused_occupant(dir, leaf("d"), &refused),
Some(KeptOccupant::Directory)
);
let unrelated = Error::from(ErrorKind::Other);
assert_matches!(refused_occupant(dir, leaf("d"), &unrelated), None);
assert_matches!(refused_occupant(dir, leaf("gone"), &refused), None);
#[cfg(unix)]
{
std::os::unix::fs::symlink("t", temp.path().join("l")).expect("symlink");
let loop_err = Error::from_raw_os_error(libc::ELOOP);
assert_matches!(
refused_occupant(dir, leaf("l"), &loop_err),
Some(KeptOccupant::Symlink)
);
assert_matches!(refused_occupant(dir, leaf("l"), &unrelated), None);
let too_many_files = Error::from_raw_os_error(libc::EMFILE);
assert_matches!(refused_occupant(dir, leaf("l"), &too_many_files), None);
}
}
fn make_directory(
dest: &DestDir,
name: &str,
allow_symlinks: bool,
) -> crate::Result<ExtractionReport> {
let config = SecurityConfig::default().with_allow_symlinks(allow_symlinks);
let safe_path = SafePath::validate(&PathBuf::from(name), dest, &config).expect("safe path");
let mut report = ExtractionReport::default();
create_directory(
&safe_path,
&pinned(dest),
&mut report,
DirWalker::new(&config),
)
.map(|()| report)
}
#[test]
fn test_create_directory_over_a_file_names_the_entry() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
std::fs::write(temp.path().join("x"), b"f").expect("write file");
let err = make_directory(&dest, "x/", false).expect_err("must be refused");
assert_matches!(&err, ArchiveError::Io(e) if e.kind() == std::io::ErrorKind::AlreadyExists);
assert!(
err.to_string()
.contains("refusing to replace the existing file at x"),
"{err}"
);
assert!(temp.path().join("x").is_file());
}
#[test]
fn test_create_directory_over_an_existing_directory_is_idempotent() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
std::fs::create_dir(temp.path().join("d")).expect("create dir");
make_directory(&dest, "d", false).expect("existing directory is accepted");
make_directory(&dest, "d", false).expect("repeated directory entry is accepted");
}
#[cfg(unix)]
#[test]
fn test_create_directory_over_a_dangling_symlink_is_refused() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
std::os::unix::fs::symlink("t", temp.path().join("x")).expect("create symlink");
let err = make_directory(&dest, "x/", false).expect_err("must be refused");
assert!(
err.to_string()
.contains("refusing to replace the existing symlink at x"),
"{err}"
);
assert!(!temp.path().join("t").exists());
}
#[cfg(unix)]
#[test]
fn test_create_directory_over_a_symlink_to_a_directory_inside_dest_is_accepted() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
std::fs::create_dir(temp.path().join("real")).expect("create dir");
std::os::unix::fs::symlink("real", temp.path().join("x")).expect("create symlink");
make_directory(&dest, "x", true).expect("in-dest directory link accepted");
let err = make_directory(&dest, "x", false).expect_err("refused when symlinks are off");
assert_matches!(err, ArchiveError::SecurityViolation { .. });
}
#[test]
fn test_extract_file_with_permit_integer_overflow_check() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
report.bytes_written = u64::MAX - 100;
let config = SecurityConfig::default();
let permit = QuotaTracker::new()
.reserve(200, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("test.txt"), &dest, &config)
.expect("path should be valid");
let mut reader = Cursor::new(b"test data");
let result = extract_file_with_permit(
&mut reader,
ReadFaults::new(ReadFamily::Tar, None),
&safe_path,
Some(sanitized(0o644)),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default(),
&mut NoopProgress,
);
assert!(result.is_err());
assert_matches!(
result.unwrap_err(),
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow
}
);
assert!(
!temp.path().join("test.txt").exists(),
"overflow-rejected entry must not touch the filesystem"
);
}
#[test]
fn test_extract_file_with_permit_files_skipped_overflow_check() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
report.skipped = crate::Skips::with_saturated_count(crate::SkipKind::Duplicate);
let config = SecurityConfig::default();
let permit = QuotaTracker::new()
.reserve(200, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("test.txt"), &dest, &config)
.expect("path should be valid");
std::fs::write(temp.path().join("test.txt"), b"existing").expect("failed to seed file");
let mut reader = Cursor::new(b"test data");
let result = extract_file_with_permit(
&mut reader,
ReadFaults::new(ReadFamily::Tar, None),
&safe_path,
Some(sanitized(0o644)),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default(),
&mut NoopProgress,
);
assert!(result.is_err());
assert_matches!(
result.unwrap_err(),
ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow
}
);
}
#[test]
fn test_extract_file_with_permit_forged_size_aborts_and_cleans_up() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
let config = SecurityConfig::default();
let permit = QuotaTracker::new()
.reserve(50, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("bomb.txt"), &dest, &config)
.expect("path should be valid");
let real_data = vec![0x41u8; 200 * 1024];
let mut reader = Cursor::new(&real_data);
let result = extract_file_with_permit(
&mut reader,
ReadFaults::new(ReadFamily::Tar, None),
&safe_path,
Some(sanitized(0o644)),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default(),
&mut NoopProgress,
);
assert_matches!(
result,
Err(ArchiveError::SecurityViolation { .. }),
"streaming past the declared size must abort with a security error, got: {result:?}"
);
assert!(
!temp.path().join("bomb.txt").exists(),
"aborted extraction must not leave a partial or oversized file on disk"
);
}
#[test]
fn test_extract_file_with_permit_undersized_stream_cleans_up() {
for family in [ReadFamily::Zip, ReadFamily::SevenZ, ReadFamily::Tar] {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
let config = SecurityConfig::default();
let permit = QuotaTracker::new()
.reserve(1000, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("short.txt"), &dest, &config)
.expect("path should be valid");
let mut reader = Cursor::new(b"too short");
let tap = SourceTap::default();
let result = extract_file_with_permit(
&mut reader,
ReadFaults::new(family, Some(&tap)),
&safe_path,
Some(sanitized(0o644)),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default(),
&mut NoopProgress,
);
match family {
ReadFamily::Tar => assert_matches!(
result,
Err(ArchiveError::InvalidArchive(
Malformation::TarEntryTruncated {
declared: 1000,
actual: 9
}
)),
"a TAR entry short of its header size is a truncated archive: {result:?}"
),
_ => assert_matches!(
result,
Err(ArchiveError::SecurityViolation { .. }),
"{family:?}: actual size short of declared size must be rejected, got: \
{result:?}"
),
}
assert!(
!temp.path().join("short.txt").exists(),
"{family:?}: rejected entry must not leave a truncated file on disk"
);
}
}
#[test]
fn test_extract_file_with_permit_force_overwrite_forged_size_keeps_destination() {
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
std::fs::write(temp.path().join("target.txt"), b"pre-existing content")
.expect("failed to seed file");
let config = SecurityConfig::default();
let permit = QuotaTracker::new()
.reserve(50, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("target.txt"), &dest, &config)
.expect("path should be valid");
let real_data = vec![0x41u8; 200 * 1024];
let mut reader = Cursor::new(&real_data);
let result = extract_file_with_permit(
&mut reader,
ReadFaults::new(ReadFamily::Tar, None),
&safe_path,
Some(sanitized(0o644)),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default().with_existing_files(crate::ExistingFiles::Overwrite),
&mut NoopProgress,
);
assert_matches!(result, Err(ArchiveError::SecurityViolation { .. }));
assert_eq!(
std::fs::read(temp.path().join("target.txt")).expect("read target"),
b"pre-existing content"
);
let leftovers = std::fs::read_dir(temp.path()).expect("read dir").count();
assert_eq!(leftovers, 1, "no temp file may remain after an abort");
}
#[test]
fn failed_commit_names_the_entry_and_guard_removes_the_temp_file() {
let temp = TempDir::new().expect("failed to create temp dir");
let written = temp.path().join(".exarch-tmp-test");
std::fs::write(&written, b"data").expect("failed to seed temp file");
let occupied = temp.path().join("d");
std::fs::create_dir(&occupied).expect("failed to create dir");
std::fs::write(occupied.join("child"), b"x").expect("failed to seed child");
let root = pinned(&DestDir::new(temp.path()).expect("dest"));
let dir = root.dir();
let leaf = Leaf::split(Path::new("d")).expect("leaf").1;
let written_at = WrittenAt::Temp(
TempLeaf::named(".exarch-tmp-test"),
ReplacePermit::for_test(),
);
let guard = written_at.guard(dir, leaf);
let err = commit_output(dir, written_at, leaf, Path::new("d")).unwrap_err();
drop(guard);
assert!(
err.to_string()
.contains("cannot replace the existing file: d"),
"{err}"
);
assert!(!written.exists(), "temp file must be removed");
assert!(occupied.join("child").exists());
}
#[test]
fn hardlink_copy_fails_closed_when_the_target_changes_size() {
let temp = TempDir::new().expect("temp dir");
let config = SecurityConfig::default();
let source = temp.path().join("source");
std::fs::write(&source, vec![b'x'; 100_000]).expect("seed source");
for (charged, ok) in [(100_000u64, true), (10, false), (200_000, false)] {
let permit = QuotaTracker::new()
.reserve(charged, &config)
.expect("reservation");
let to = temp.path().join(format!("copy-{charged}"));
let result = copy_file_content_with_permit(
File::open(&source).expect("open source"),
&mut File::create(&to).expect("create copy"),
&mut CopyBuffer::new(),
permit,
&mut NoopProgress,
);
if ok {
assert_eq!(result.expect("exact length copies"), 100_000);
} else {
let err = result.expect_err("a changed length must fail");
assert_matches!(&err, ArchiveError::SecurityViolation { .. });
assert!(err.to_string().contains("hardlink target changed"), "{err}");
}
}
}
#[cfg(unix)]
#[test]
fn test_create_file_with_mode_0o644() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("test_0o644.txt");
let file =
create_file_with_mode(&file_path, Some(sanitized(0o644))).expect("should create file");
drop(file);
assert!(file_path.exists(), "file should exist");
let metadata = std::fs::metadata(&file_path).expect("should read metadata");
let mode = metadata.permissions().mode();
let permission_bits = mode & 0o777;
assert_eq!(
permission_bits, 0o644,
"file should have permissions 0o644, got 0o{permission_bits:o}"
);
}
#[cfg(unix)]
#[test]
fn test_create_file_with_mode_0o755() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("test_0o755.txt");
let file =
create_file_with_mode(&file_path, Some(sanitized(0o755))).expect("should create file");
drop(file);
assert!(file_path.exists(), "file should exist");
let metadata = std::fs::metadata(&file_path).expect("should read metadata");
let mode = metadata.permissions().mode();
let permission_bits = mode & 0o777;
assert_eq!(
permission_bits, 0o755,
"file should have permissions 0o755, got 0o{permission_bits:o}"
);
}
#[cfg(unix)]
#[test]
fn test_create_file_with_mode_0o600() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("test_0o600.txt");
let file =
create_file_with_mode(&file_path, Some(sanitized(0o600))).expect("should create file");
drop(file);
assert!(file_path.exists(), "file should exist");
let metadata = std::fs::metadata(&file_path).expect("should read metadata");
let mode = metadata.permissions().mode();
let permission_bits = mode & 0o777;
assert_eq!(
permission_bits, 0o600,
"file should have permissions 0o600, got 0o{permission_bits:o}"
);
}
#[test]
fn test_create_file_with_mode_none() {
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("test_none.txt");
let file = create_file_with_mode(&file_path, None).expect("should create file");
drop(file);
assert!(file_path.exists(), "file should exist");
}
#[cfg(unix)]
#[test]
fn test_create_file_with_mode_none_unix() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("test_none_unix.txt");
let file = create_file_with_mode(&file_path, None).expect("should create file");
drop(file);
assert!(file_path.exists(), "file should exist");
let metadata = std::fs::metadata(&file_path).expect("should read metadata");
let mode = metadata.permissions().mode();
let permission_bits = mode & 0o777;
assert_ne!(
permission_bits, 0,
"file should have non-zero permissions with mode=None"
);
}
#[cfg(unix)]
#[test]
fn test_extract_file_permissions_bypass_umask() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let mut report = ExtractionReport::default();
let mut copy_buffer = CopyBuffer::new();
let dirs = test_walker();
let config = SecurityConfig::default();
let sanitized_mode = sanitize_permissions(RawMode::new(0o777), &config);
let permit = QuotaTracker::new()
.reserve(7, &config)
.expect("reservation should succeed");
let safe_path = SafePath::validate(&PathBuf::from("perm_test.txt"), &dest, &config)
.expect("path should be valid");
let mut reader = Cursor::new(b"content");
extract_file_with_permit(
&mut reader,
ReadFaults::new(ReadFamily::Tar, None),
&safe_path,
Some(sanitized_mode),
permit,
&pinned(&dest),
&mut report,
&mut copy_buffer,
dirs,
SinkOptions::default(),
&mut NoopProgress,
)
.expect("extraction should succeed");
let extracted = temp.path().join("perm_test.txt");
assert!(extracted.exists(), "file should exist");
let metadata = std::fs::metadata(&extracted).expect("should read metadata");
let permission_bits = metadata.permissions().mode() & 0o777;
assert_eq!(
permission_bits, 0o775,
"extracted file must have exact sanitized mode 0o775, got 0o{permission_bits:o}; \
umask may have incorrectly reduced permissions"
);
}
#[cfg(unix)]
#[test]
#[allow(unsafe_code)]
fn test_create_file_with_mode_bypasses_strict_umask() {
use std::os::unix::fs::PermissionsExt;
let temp = TempDir::new().expect("failed to create temp dir");
let file_path = temp.path().join("strict_umask_test.txt");
let previous_umask = unsafe { libc::umask(0o077) };
let result = create_file_with_mode(&file_path, Some(sanitized(0o755)));
unsafe { libc::umask(previous_umask) };
let file = result.expect("should create file under strict umask");
drop(file);
let metadata = std::fs::metadata(&file_path).expect("should read metadata");
let permission_bits = metadata.permissions().mode() & 0o777;
assert_eq!(
permission_bits, 0o755,
"file must have exact mode 0o755 despite strict umask 0o077; \
got 0o{permission_bits:o} — set_permissions bypass not working"
);
}
#[test]
#[cfg(unix)]
fn test_duplicate_symlink_unchanged_or_refused_when_skip_disabled() {
use crate::types::SafeSymlink;
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let config = SecurityConfig::default().with_allow_symlinks(true);
std::fs::write(temp.path().join("target.txt"), b"data").expect("write target");
let link_safe_path =
SafePath::validate(&PathBuf::from("link.txt"), &dest, &config).expect("safe path");
let safe_symlink =
SafeSymlink::validate(&link_safe_path, Path::new("target.txt"), &dest, &config)
.expect("safe symlink");
let mut report = ExtractionReport::default();
let dirs = test_walker();
create_symlink(
&safe_symlink,
&pinned(&dest),
&mut report,
dirs,
SinkOptions::default().with_existing_files(crate::ExistingFiles::Overwrite),
)
.expect("first create_symlink should succeed");
assert_eq!(report.symlinks_created, 1);
let unchanged = report.symlinks_created;
create_symlink(
&safe_symlink,
&pinned(&dest),
&mut report,
dirs,
SinkOptions::default().with_existing_files(crate::ExistingFiles::Overwrite),
)
.expect("an identical link is an unchanged duplicate");
assert_eq!(report.symlinks_created, unchanged);
assert_eq!(report.files_skipped(), 1);
std::fs::write(temp.path().join("other.txt"), b"data").expect("write other");
let other_safe_symlink =
SafeSymlink::validate(&link_safe_path, Path::new("other.txt"), &dest, &config)
.expect("safe symlink");
let err = create_symlink(
&other_safe_symlink,
&pinned(&dest),
&mut report,
dirs,
SinkOptions::default().with_existing_files(crate::ExistingFiles::Overwrite),
)
.expect_err("a link with another target must not be replaced");
assert_matches!(
&err,
ArchiveError::SecurityViolation {
kind: Violation::ReplacesSymlink { rel },
} if &**rel == "link.txt",
"{err:?}"
);
assert_eq!(report.symlinks_created, 1);
assert_eq!(
std::fs::read_link(temp.path().join("link.txt")).expect("link kept"),
Path::new("target.txt")
);
}
#[test]
#[cfg(unix)]
fn test_symlink_replaces_existing_file_when_skip_disabled() {
use crate::types::SafeSymlink;
let temp = TempDir::new().expect("failed to create temp dir");
let dest = DestDir::new(temp.path().to_path_buf()).expect("failed to create dest");
let config = SecurityConfig::default().with_allow_symlinks(true);
std::fs::write(temp.path().join("target.txt"), b"data").expect("write target");
std::fs::write(temp.path().join("link.txt"), b"old").expect("write file");
let link_safe_path =
SafePath::validate(&PathBuf::from("link.txt"), &dest, &config).expect("safe path");
let safe_symlink =
SafeSymlink::validate(&link_safe_path, Path::new("target.txt"), &dest, &config)
.expect("safe symlink");
let mut report = ExtractionReport::default();
create_symlink(
&safe_symlink,
&pinned(&dest),
&mut report,
test_walker(),
SinkOptions::default().with_existing_files(crate::ExistingFiles::Overwrite),
)
.expect("a file is replaced");
assert_eq!(report.symlinks_created, 1);
assert!(temp.path().join("link.txt").is_symlink());
}
#[test]
fn test_record_file_written_counts_bytes_and_reports_progress_once() {
struct Bytes(Vec<u64>);
impl ProgressCallback for Bytes {
fn on_entry_start(&mut self, _: &Path, _position: crate::EntryPosition) {}
fn on_bytes_written(&mut self, bytes: u64) {
self.0.push(bytes);
}
fn on_entry_complete(&mut self, _: &Path) {}
fn on_complete(&mut self) {}
}
let mut report = ExtractionReport::default();
let mut progress = Bytes(Vec::new());
record_file_written(&mut report, &mut progress, 7).unwrap();
record_file_written(&mut report, &mut progress, 0).unwrap();
assert_eq!(report.files_extracted, 2);
assert_eq!(report.bytes_written, 7);
assert_eq!(progress.0, vec![7], "an empty file reports no bytes");
}
#[test]
fn test_record_file_written_refuses_a_counter_overflow() {
let mut report = ExtractionReport {
bytes_written: u64::MAX,
..ExtractionReport::default()
};
let result = record_file_written(&mut report, &mut crate::NoopProgress, 1);
assert_matches!(
result,
Err(ArchiveError::QuotaExceeded {
resource: QuotaResource::IntegerOverflow
})
);
}
#[test]
fn test_record_skip_counts_by_kind_and_keeps_the_path() {
let mut report = ExtractionReport::default();
record_duplicate_skip(&mut report, Path::new("a/b")).expect("count duplicate");
record_skip(
&mut report,
SkipKind::ExtensionNotAllowed,
Path::new("c.exe"),
)
.expect("count extension skip");
record_duplicate_skip(&mut report, Path::new("d")).expect("count duplicate");
assert_eq!(report.files_skipped(), 3);
assert_eq!(report.skipped.count(SkipKind::Duplicate), 2);
assert_eq!(report.skipped.count(SkipKind::ExtensionNotAllowed), 1);
let paths: Vec<_> = report.skipped.sample().iter().map(|s| &s.path).collect();
assert_eq!(
paths,
[Path::new("a/b"), Path::new("c.exe"), Path::new("d")]
);
}
#[test]
fn test_entry_complete_guard_panicking_callback_fires_once() {
use std::panic::AssertUnwindSafe;
use std::panic::catch_unwind;
struct Panicking(u32);
impl ProgressCallback for Panicking {
fn on_entry_start(&mut self, _: &Path, _position: crate::EntryPosition) {}
fn on_bytes_written(&mut self, _: u64) {}
fn on_entry_complete(&mut self, _: &Path) {
self.0 += 1;
panic!("callback panic");
}
fn on_complete(&mut self) {}
}
let mut progress = Panicking(0);
let path = PathBuf::from("f");
let outcome = catch_unwind(AssertUnwindSafe(|| {
EntryCompleteGuard::try_start(
&mut progress,
&path,
crate::EntryPosition::at_index(0, crate::EntryTotal::Known(1)),
)
.unwrap()
.complete();
}));
assert!(outcome.is_err());
assert_eq!(progress.0, 1, "Drop must not fire the callback again");
}
}
#[cfg(all(test, unix))]
mod refuse_probe_tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::formats::pinned_dir::support::leaf;
use std::assert_matches;
use tempfile::TempDir;
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
fn open(root: &PinnedRoot, name: &str) -> Result<Option<()>> {
open_output_slot(
root.dir(),
leaf(name),
Path::new(name),
None,
ExistingFiles::Refuse,
root,
ModeTiming::AtCreate,
)
.map(|slot| slot.map(drop))
}
fn assert_untouched(dir: &Path, expected: &[(&str, &str)]) {
let listed: Vec<_> = expected
.iter()
.map(|(name, _)| (*name).to_string())
.collect();
assert_eq!(names(dir), listed, "no temp file, no rename");
for (name, content) in expected {
assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), *content);
}
}
#[test]
fn a_file_the_run_made_but_the_record_lacks_is_refused() {
let temp = TempDir::new().unwrap();
let root = PinnedRoot::open_for_test(temp.path()).unwrap();
std::fs::write(temp.path().join("f"), "ours").unwrap();
let outcome = open(&root, "f");
assert_matches!(outcome, Err(ArchiveError::DestinationOccupied { .. }));
assert_untouched(temp.path(), &[("f", "ours")]);
}
#[test]
fn a_file_the_run_made_is_refused_once_the_record_is_saturated() {
let temp = TempDir::new().unwrap();
let root = PinnedRoot::open_for_test(temp.path()).unwrap();
std::fs::write(temp.path().join("f"), "ours").unwrap();
root.created()
.note(ExistingFiles::Refuse, root.dir(), leaf("f"), Path::new("f"));
root.created().saturate();
let outcome = open(&root, "f");
assert_matches!(outcome, Err(ArchiveError::DestinationOccupied { .. }));
assert_untouched(temp.path(), &[("f", "ours")]);
}
#[test]
fn a_foreign_occupant_the_record_vouches_for_is_skipped() {
let temp = TempDir::new().unwrap();
let root = PinnedRoot::open_for_test(temp.path()).unwrap();
std::fs::write(temp.path().join("f"), "ours").unwrap();
root.created()
.note(ExistingFiles::Refuse, root.dir(), leaf("f"), Path::new("f"));
std::fs::hard_link(temp.path().join("f"), temp.path().join("g")).unwrap();
let outcome = open(&root, "g");
assert_matches!(outcome, Ok(None));
assert_untouched(temp.path(), &[("f", "ours"), ("g", "ours")]);
}
#[test]
fn a_foreign_occupant_the_record_does_not_know_is_refused() {
let temp = TempDir::new().unwrap();
let root = PinnedRoot::open_for_test(temp.path()).unwrap();
std::fs::write(temp.path().join("f"), "ours").unwrap();
root.created()
.note(ExistingFiles::Refuse, root.dir(), leaf("f"), Path::new("f"));
std::fs::rename(temp.path().join("f"), temp.path().join("kept")).unwrap();
std::fs::write(temp.path().join("f"), "foreign").unwrap();
let outcome = open(&root, "f");
assert_matches!(outcome, Err(ArchiveError::DestinationOccupied { .. }));
assert_untouched(temp.path(), &[("f", "foreign"), ("kept", "ours")]);
}
#[test]
fn a_foreign_occupant_with_a_recorded_identity_is_skipped_never_written() {
let temp = TempDir::new().unwrap();
let root = PinnedRoot::open_for_test(temp.path()).unwrap();
std::fs::write(temp.path().join("f"), "foreign").unwrap();
let reused = root.dir().identity(leaf("f")).unwrap().unwrap();
root.created().insert_identity_for_test(reused);
let outcome = open(&root, "f");
assert_matches!(outcome, Ok(None));
assert_untouched(temp.path(), &[("f", "foreign")]);
}
}