use std::fs::File;
use std::io::Read;
use std::path::Path;
use super::zip_reuse::Retained;
use crate::ArchiveError;
use crate::ExtractionReport;
use crate::Malformation;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::SkipKind;
use crate::copy::CopyBuffer;
use crate::formats::occupant::OccupantAction;
use crate::formats::occupant::OccupantPolicy;
use crate::formats::occupant::OccupiedSite;
use crate::formats::occupant::refuse_hardlink_replace;
use crate::mark::MarkRun;
use crate::security::RawMode;
use crate::security::admitted::EntrySize;
use crate::security::admitted::PendingFile;
use crate::security::admitted::ValidatedFile;
use crate::security::admitted::ValidatedHardlink;
use crate::security::context::ValidationContext;
use crate::security::fs_view::FsView;
use crate::security::fs_view::LinkBase;
use crate::security::fs_view::LinkKind;
use crate::security::fs_view::Occupant;
use crate::security::fs_view::PinnedHostFs;
use crate::security::hardlink::HardlinkTarget;
use crate::security::hardlink::hardlink_target_missing;
use crate::security::permissions::CreateMode;
use crate::security::permissions::sanitize_permissions;
use crate::security::quota::EntryCount;
use crate::security::validator::Gated;
use crate::security::validator::ValidatorCore;
use crate::selection::EntryShape;
use crate::types::SafePath;
use crate::types::SafeSymlink;
use crate::types::safe_path::ParentCheck;
#[cfg(not(any(unix, target_os = "wasi")))]
use crate::types::safe_path::Resolved;
#[cfg(any(unix, target_os = "wasi"))]
use crate::types::safe_path::Walked;
use super::common;
use super::dir_walker::DirWalker;
use super::output_root::OutputRoot;
use super::pinned_dir::PinnedRoot;
use super::pinned_dir::TempFileGuard;
use super::source_fault::ReadFaults;
pub(crate) struct Tally<'a> {
pub(crate) report: &'a mut ExtractionReport,
pub(crate) options: SinkOptions,
pub(crate) progress: &'a mut dyn ProgressCallback,
}
impl Tally<'_> {
pub(crate) fn record_duplicate_skip(&mut self, path: &Path) -> Result<SkipRecorded> {
common::record_duplicate_skip(self.report, path)?;
Ok(SkipRecorded(()))
}
pub(crate) fn record_skip(&mut self, kind: SkipKind, path: &Path) -> Result<SkipRecorded> {
common::record_skip(self.report, kind, path)?;
Ok(SkipRecorded(()))
}
pub(crate) fn admission<A>(&mut self, gated: Gated<A>, path: &Path) -> Result<Admission<A>> {
match gated {
Gated::Admit(admitted) => Ok(Admission::Admit(admitted)),
Gated::Skip(kind) => self.record_skip(kind, path).map(Admission::Skipped),
}
}
pub(crate) fn record_file(&mut self, written: u64) -> Result<()> {
common::record_file_written(self.report, self.progress, written)
}
}
#[derive(Debug)]
pub(crate) struct SkipRecorded(());
#[derive(Debug, Clone, Copy)]
pub(crate) struct FileRequest<'p> {
pub(crate) path: &'p Path,
pub(crate) size: EntrySize,
pub(crate) mode: Option<RawMode>,
}
#[derive(Debug)]
pub(crate) enum Admission<A> {
Admit(A),
Skipped(SkipRecorded),
}
impl<A> Admission<A> {
#[cfg(all(test, unix))]
pub(crate) fn into_admitted(self) -> A {
match self {
Self::Admit(admitted) => admitted,
Self::Skipped(_) => panic!("the entry was skipped"),
}
}
}
#[cfg(all(test, unix))]
pub(crate) fn with_tally<R>(f: impl FnOnce(&mut Tally<'_>) -> R) -> R {
let mut report = ExtractionReport::new();
let mut progress = crate::NoopProgress;
let mut tally = Tally {
report: &mut report,
options: SinkOptions::default(),
progress: &mut progress,
};
f(&mut tally)
}
#[cfg(any(unix, target_os = "wasi"))]
pub(crate) type HostParent = Walked;
#[cfg(not(any(unix, target_os = "wasi")))]
pub(crate) type HostParent = Resolved;
pub(crate) trait ExtractTarget {
type Parent: ParentCheck;
type AdmittedFile;
fn validate_file(
&mut self,
request: FileRequest<'_>,
tally: &mut Tally<'_>,
) -> Result<Admission<Self::AdmittedFile>>;
fn validate_directory(
&mut self,
path: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafePath<Self::Parent>>>;
fn validate_symlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafeSymlink<Self::Parent>>>;
fn validate_hardlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<ValidatedHardlink<Self::Parent>>>;
fn directory(&mut self, path: &SafePath<Self::Parent>, tally: &mut Tally<'_>) -> Result<()>;
fn file<R: Read>(
&mut self,
reader: &mut R,
faults: ReadFaults<'_>,
admitted: Self::AdmittedFile,
tally: &mut Tally<'_>,
) -> Result<()>;
fn file_retained(
&mut self,
retained: Retained<'_>,
faults: ReadFaults<'_>,
admitted: Self::AdmittedFile,
tally: &mut Tally<'_>,
) -> Result<()> {
match retained {
Retained::Bytes(bytes) => self.file(&mut bytes.as_slice(), faults, admitted, tally),
Retained::Spooled(mut reader) => self.file(&mut reader, faults, admitted, tally),
}
}
fn symlink(&mut self, symlink: &SafeSymlink<Self::Parent>, tally: &mut Tally<'_>)
-> Result<()>;
fn finish_scan(&mut self) -> Result<()>;
fn hardlink(
&mut self,
link: &SafePath<Self::Parent>,
target: &HardlinkTarget,
counted: EntryCount,
tally: &mut Tally<'_>,
) -> Result<()>;
}
#[derive(Debug)]
pub(crate) enum Sealed {
Skipped(SkipRecorded),
Selected,
}
pub(crate) trait SealedRoute: ExtractTarget {
fn route_sealed(
&mut self,
path: &Path,
shape: EntryShape,
tally: &mut Tally<'_>,
) -> Result<Sealed>;
}
impl Sealed {
pub(crate) fn of<A>(gated: Gated<A>, path: &Path, tally: &mut Tally<'_>) -> Result<Self> {
Ok(match tally.admission(gated, path)? {
Admission::Skipped(skipped) => Self::Skipped(skipped),
Admission::Admit(_) => Self::Selected,
})
}
}
#[cfg(any(unix, target_os = "wasi"))]
pub(super) fn host_context<'r, V: FsView>(
core: &ValidatorCore<'_>,
root: &'r PinnedRoot,
) -> ValidationContext<'r, V, HostParent> {
core.context::<V>().with_walker(root.backs_parent_probe())
}
#[cfg(not(any(unix, target_os = "wasi")))]
pub(super) fn host_context<'r, V: FsView>(
core: &ValidatorCore<'_>,
_root: &'r PinnedRoot,
) -> ValidationContext<'r, V, HostParent> {
core.context::<V>().deferring_leaf_symlink()
}
pub(crate) struct HostTarget<'a> {
root: PinnedRoot,
dirs: DirWalker<'a>,
copy_buffer: CopyBuffer,
core: ValidatorCore<'a>,
config: &'a SecurityConfig,
}
impl<'a> HostTarget<'a> {
pub(crate) fn create<'o>(
output: impl Into<OutputRoot<'o>>,
config: &'a SecurityConfig,
) -> Result<Self> {
Ok(Self {
root: PinnedRoot::open_output(output.into())?,
dirs: DirWalker::new(config),
copy_buffer: CopyBuffer::new(),
core: ValidatorCore::new(config),
config,
})
}
pub(super) const fn root(&self) -> &PinnedRoot {
&self.root
}
pub(super) fn copy_buffer_and_marking(&mut self) -> (&mut CopyBuffer, Option<&MarkRun>) {
(&mut self.copy_buffer, self.root.marking())
}
pub(super) const fn dirs(&self) -> DirWalker<'a> {
self.dirs
}
pub(super) fn screen_file(
&mut self,
request: FileRequest<'_>,
) -> Result<Gated<PendingFile<HostParent>>> {
let ctx = host_context(&self.core, &self.root);
self.core.screen_file_path_in(
request.path,
request.size,
request.mode,
self.root.dest(),
&PinnedHostFs::new(&self.root),
&ctx,
)
}
pub(super) fn charge_skipped(&mut self) -> Result<()> {
self.core.charge_skipped()
}
pub(super) fn admit_file(
&mut self,
pending: PendingFile<HostParent>,
) -> Result<ValidatedFile<HostParent>> {
self.core.admit_file(pending)
}
}
impl SealedRoute for HostTarget<'_> {
fn route_sealed(
&mut self,
path: &Path,
shape: EntryShape,
tally: &mut Tally<'_>,
) -> Result<Sealed> {
let ctx = host_context(&self.core, &self.root);
let gated = self.core.route_entry_in(
path,
shape,
self.root.dest(),
&PinnedHostFs::new(&self.root),
&ctx,
)?;
Sealed::of(gated, path, tally)
}
}
impl ExtractTarget for HostTarget<'_> {
type AdmittedFile = ValidatedFile<HostParent>;
type Parent = HostParent;
fn validate_file(
&mut self,
request: FileRequest<'_>,
tally: &mut Tally<'_>,
) -> Result<Admission<ValidatedFile<HostParent>>> {
match tally.admission(self.screen_file(request)?, request.path)? {
Admission::Admit(pending) => self.admit_file(pending).map(Admission::Admit),
Admission::Skipped(skipped) => Ok(Admission::Skipped(skipped)),
}
}
fn validate_directory(
&mut self,
path: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafePath<HostParent>>> {
let ctx = host_context(&self.core, &self.root);
let gated = self.core.validate_directory_in(
path,
size,
self.root.dest(),
&PinnedHostFs::new(&self.root),
&ctx,
)?;
tally.admission(gated, path)
}
fn validate_symlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafeSymlink<HostParent>>> {
let ctx = host_context(&self.core, &self.root);
let gated = self.core.validate_symlink_in(
path,
target,
size,
self.root.dest(),
&PinnedHostFs::new(&self.root),
&ctx,
)?;
tally.admission(gated.map(|validated| validated.symlink), path)
}
fn validate_hardlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<ValidatedHardlink<HostParent>>> {
let ctx = host_context(&self.core, &self.root);
let gated = self.core.validate_hardlink_in(
path,
target,
size,
self.root.dest(),
&PinnedHostFs::new(&self.root),
&ctx,
)?;
tally.admission(gated, path)
}
fn finish_scan(&mut self) -> Result<()> {
self.core.finish_selection()
}
fn directory(&mut self, path: &SafePath<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
common::create_directory(
path,
&self.root,
tally.report,
self.dirs,
OccupantPolicy::of(tally.options),
)
}
fn file<R: Read>(
&mut self,
reader: &mut R,
faults: ReadFaults<'_>,
admitted: ValidatedFile<HostParent>,
tally: &mut Tally<'_>,
) -> Result<()> {
let (path, permit, mode) = admitted.into_parts();
common::extract_file_with_permit(
reader,
faults,
&path,
&self.root,
tally.report,
self.dirs,
tally.options,
common::FileWrite {
copy_buffer: &mut self.copy_buffer,
permit,
mode,
progress: tally.progress,
},
)
}
fn symlink(&mut self, symlink: &SafeSymlink<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
common::create_symlink(symlink, &self.root, tally.report, self.dirs, tally.options)
}
fn hardlink(
&mut self,
link: &SafePath<HostParent>,
target: &HardlinkTarget,
counted: EntryCount,
tally: &mut Tally<'_>,
) -> Result<()> {
self.core
.require_unambiguous_target(link.as_path(), target.as_path())?;
let OpenedTarget {
file: target_file,
len: target_size,
mode: target_mode,
} = self.open_hardlink_target(link, target)?;
let link_mode = target_mode
.map(|mode| CreateMode::Exact(sanitize_permissions(RawMode::new(mode), self.config)));
let (link_dir, link_leaf) = self.dirs.ensure_parent(&self.root, link)?;
let marking = self.root.marking();
let (link_file, pending) = match common::create_file(
&link_dir,
link_leaf,
link_mode,
common::ModeTiming::of(marking),
) {
Ok(created) => created,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let action = OccupantPolicy::of(tally.options).on_occupant(
EntryShape::Link(LinkKind::Hardlink),
link.as_path(),
|| link_dir.probe(link_leaf),
|| {
self.root
.created()
.maker(&link_dir, link_leaf, link.as_path())
},
OccupiedSite::Host(&self.root),
)?;
return match action {
OccupantAction::Skip => {
common::record_duplicate_skip(tally.report, link.as_path())
}
OccupantAction::Replace(permit) => {
let found = link_dir.probe(link_leaf)?;
Err(refuse_hardlink_replace(
permit,
found,
link.as_path(),
|| {
self.root.created().created_here(
&link_dir,
link_leaf,
link.as_path(),
)
},
OccupiedSite::Host(&self.root),
))
}
};
}
Err(e) => return Err(ArchiveError::Io(e)),
};
self.root
.created()
.note_file(&link_file, &link_dir, link_leaf, link.as_path());
let cleanup_guard = TempFileGuard::new(&link_dir, link_leaf);
let permit = self.core.charge_hardlink(counted, target_size)?;
let bytes_copied = {
let mut link_file = link_file;
let copied = common::copy_file_content_with_permit(
target_file,
&mut link_file,
&mut self.copy_buffer,
permit,
&mut *tally.progress,
)?;
common::seal_output(&link_file, pending, marking)?;
copied
};
cleanup_guard.persist();
tally.record_file(bytes_copied)
}
}
impl HostTarget<'_> {
fn open_hardlink_target(
&self,
link: &SafePath<HostParent>,
target: &HardlinkTarget,
) -> Result<OpenedTarget> {
let file = if target.has_parent_dir() {
self.open_through_symlink(link, target)?
} else {
self.open_direct(link, target)?
};
let meta = file.metadata()?;
if !meta.is_file() {
return Err(ArchiveError::from(Malformation::HardlinkTargetNotRegular {
target: target.as_path().to_path_buf(),
}));
}
#[cfg(unix)]
let mode = {
use std::os::unix::fs::PermissionsExt;
Some(meta.permissions().mode() & 0o7777)
};
#[cfg(not(unix))]
let mode = None;
Ok(OpenedTarget {
len: meta.len(),
mode,
file,
})
}
fn open_direct(&self, link: &SafePath<HostParent>, target: &HardlinkTarget) -> Result<File> {
let missing = || hardlink_target_missing(target.as_path());
let (dir, leaf) = match self.dirs.open_parent(&self.root, target.as_path()) {
Ok(opened) => opened,
Err(_) if self.has_symlink_parent(target) => {
return self.open_through_symlink(link, target);
}
Err(err) => return Err(not_found_as(err, missing)),
};
match dir.open_read(leaf) {
Ok(file) => Ok(file),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(missing()),
Err(e) => match dir.probe(leaf) {
Ok(Some(Occupant::Symlink)) => self.open_through_symlink(link, target),
_ => Err(ArchiveError::Io(e)),
},
}
}
fn has_symlink_parent(&self, target: &HardlinkTarget) -> bool {
target.parent_probes(self.root.dest()).any(|parent| {
parent
.lstat()
.is_ok_and(|meta| meta.file_type().is_symlink())
})
}
fn open_through_symlink(
&self,
link: &SafePath<HostParent>,
target: &HardlinkTarget,
) -> Result<File> {
let missing = || hardlink_target_missing(target.as_path());
if !target.probe_under(self.root.dest()).exists() {
return Err(missing());
}
let escape = || ArchiveError::HardlinkEscape {
path: link.as_path().to_path_buf(),
};
let dest = self.root.dest();
let resolved = PinnedHostFs::new(&self.root)
.resolve_link_target(
link.as_path(),
target.as_path(),
LinkBase::Destination,
dest,
)
.map_err(|_| escape())?;
let inside = resolved
.strip_prefix(dest.as_path())
.map_err(|_| escape())?;
let (dir, leaf) = self
.dirs
.open_resolved_parent(&self.root, inside)
.map_err(|e| not_found_as(e, missing))?;
match dir.open_read(leaf) {
Ok(file) => Ok(file),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(missing()),
Err(e) => Err(ArchiveError::Io(e)),
}
}
}
struct OpenedTarget {
file: File,
len: u64,
mode: Option<u32>,
}
fn not_found_as(err: ArchiveError, missing: impl FnOnce() -> ArchiveError) -> ArchiveError {
match err {
ArchiveError::Io(e) if e.kind() == std::io::ErrorKind::NotFound => missing(),
other => other,
}
}
#[cfg(all(test, unix))]
#[expect(clippy::unwrap_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
use crate::security::Uncompressed;
use std::assert_matches;
fn config() -> SecurityConfig {
SecurityConfig::default()
.with_allow_symlinks(true)
.with_allow_hardlinks(true)
}
fn replaced_destination<'a>(
temp: &tempfile::TempDir,
config: &'a SecurityConfig,
held: impl FnOnce(&Path),
decoy: impl FnOnce(&Path),
) -> HostTarget<'a> {
let dest = temp.path().join("dest");
std::fs::create_dir(&dest).unwrap();
held(&dest);
let target = HostTarget::create(&dest, config).unwrap();
std::fs::rename(&dest, temp.path().join("moved")).unwrap();
std::fs::create_dir(&dest).unwrap();
decoy(&dest);
target
}
fn size() -> EntrySize {
EntrySize::new(Uncompressed(0), None)
}
fn escaping_link(dest: &Path) {
std::os::unix::fs::symlink("..", dest.join("up")).unwrap();
}
#[test]
fn a_symlink_is_judged_by_the_held_destination_not_its_path() {
let config = config();
let temp = tempfile::TempDir::new().unwrap();
let mut target = replaced_destination(&temp, &config, escaping_link, |_| {});
let refused = with_tally(|tally| {
target.validate_symlink(Path::new("l"), Path::new("up/x"), size(), tally)
});
assert_matches!(
refused,
Err(ArchiveError::SymlinkEscape { .. }),
"{refused:?}"
);
let temp = tempfile::TempDir::new().unwrap();
let mut target = replaced_destination(&temp, &config, |_| {}, escaping_link);
let accepted = with_tally(|tally| {
target.validate_symlink(Path::new("l"), Path::new("up/x"), size(), tally)
});
assert_matches!(accepted, Ok(_), "{accepted:?}");
}
#[test]
fn a_hardlink_is_judged_by_the_held_destination_not_its_path() {
let config = config();
let temp = tempfile::TempDir::new().unwrap();
let mut target = replaced_destination(&temp, &config, escaping_link, |_| {});
let refused = with_tally(|tally| {
target.validate_hardlink(Path::new("h"), Path::new("up/x"), size(), tally)
});
assert_matches!(
refused,
Err(ArchiveError::HardlinkEscape { .. }),
"{refused:?}"
);
let temp = tempfile::TempDir::new().unwrap();
let mut target = replaced_destination(&temp, &config, |_| {}, escaping_link);
let accepted = with_tally(|tally| {
target.validate_hardlink(Path::new("h"), Path::new("up/x"), size(), tally)
});
assert_matches!(accepted, Ok(_), "{accepted:?}");
}
#[test]
fn a_hardlink_source_is_opened_through_the_held_destination_not_its_path() {
use std::io::Read as _;
let config = config();
let temp = tempfile::TempDir::new().unwrap();
let mut target = replaced_destination(
&temp,
&config,
|dest| {
std::fs::create_dir_all(dest.join("a/b")).unwrap();
std::os::unix::fs::symlink("a/b", dest.join("s")).unwrap();
std::fs::write(dest.join("a/f2"), b"held").unwrap();
},
|dest| {
std::fs::create_dir(dest.join("s")).unwrap();
std::fs::write(dest.join("f2"), b"decoy").unwrap();
},
);
let validated = with_tally(|tally| {
target.validate_hardlink(Path::new("h"), Path::new("s/../f2"), size(), tally)
})
.unwrap()
.into_admitted();
let opened = target
.open_hardlink_target(&validated.link, &validated.target)
.unwrap();
let mut content = String::new();
let mut file = opened.file;
file.read_to_string(&mut content).unwrap();
assert_eq!(content, "held");
}
}