use std::io::Read;
use std::path::Path;
use super::extract::FilePlan;
use super::extract::PrePass;
use super::extract::SevenZTarget;
use super::write::FileWrite;
use super::write::lstat_dest;
use super::write::refuse_undecoded_target_in;
use super::write::write_file_direct;
use super::write::write_file_with_permit;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::formats::common;
use crate::formats::occupant::KeptOccupant;
use crate::formats::occupant::OccupantAction;
use crate::formats::occupant::ReplacePermit;
use crate::formats::occupant::replaces_symlink;
use crate::formats::output_root::OutputRoot;
use crate::formats::pinned_dir::Leaf;
use crate::formats::pinned_dir::VettedDir;
use crate::formats::source_fault::ReadFaults;
use crate::formats::target::Admission;
use crate::formats::target::ExtractTarget;
use crate::formats::target::FileRequest;
use crate::formats::target::HostParent;
use crate::formats::target::HostTarget;
use crate::formats::target::Tally;
use crate::security::admitted::EntrySize;
use crate::security::admitted::ValidatedFile;
use crate::security::admitted::ValidatedHardlink;
use crate::security::context::ValidationContext;
use crate::security::fs_view::HostFs;
use crate::security::fs_view::Occupant;
use crate::security::hardlink::HardlinkTarget;
use crate::security::validator::EntryPath;
use crate::security::validator::Gated;
use crate::security::validator::ValidatorCore;
use crate::selection::EntryShape;
use crate::types::DestDir;
use crate::types::SafePath;
use crate::types::SafeSymlink;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DestOccupancy {
Vacant,
RegularFile,
Symlink,
Directory,
}
impl DestOccupancy {
fn of(occupant: Option<Occupant>) -> Self {
match occupant {
None => Self::Vacant,
Some(Occupant::File) => Self::RegularFile,
Some(Occupant::Symlink) => Self::Symlink,
Some(Occupant::Directory) => Self::Directory,
}
}
fn probe(parent: &VettedDir, leaf: Leaf<'_>) -> std::io::Result<Self> {
parent.probe(leaf).map(Self::of)
}
fn probe_path(dest_path: &Path) -> std::io::Result<Self> {
Ok(Self::of(
lstat_dest(dest_path)?.map(|meta| meta.file_type().into()),
))
}
const fn occupant(self) -> Option<Occupant> {
match self {
Self::Vacant => None,
Self::RegularFile => Some(Occupant::File),
Self::Symlink => Some(Occupant::Symlink),
Self::Directory => Some(Occupant::Directory),
}
}
const fn is_occupied(self) -> bool {
!matches!(self, Self::Vacant)
}
fn kept_symlink(self) -> Option<KeptOccupant> {
(cfg!(unix) && self == Self::Symlink).then_some(KeptOccupant::Symlink)
}
fn replace_mode(self, permit: ReplacePermit) -> std::result::Result<WriteMode, KeptOccupant> {
if let Some(kept) = self.kept_symlink() {
return Err(kept);
}
match self {
Self::Vacant => Ok(WriteMode::CreateNew),
Self::Directory => Err(KeptOccupant::Directory),
Self::RegularFile | Self::Symlink => Ok(WriteMode::ReplaceRegular(permit)),
}
}
}
#[derive(Debug)]
enum WriteMode {
CreateNew,
ReplaceRegular(ReplacePermit),
}
#[derive(Debug)]
pub(super) struct SevenZAdmittedFile {
file: ValidatedFile<HostParent>,
write_mode: WriteMode,
parent: VettedDir,
}
pub(super) struct SevenZHostTarget<'a> {
inner: HostTarget<'a>,
}
impl<'a> SevenZHostTarget<'a> {
pub(super) fn create<'o>(
output: impl Into<OutputRoot<'o>>,
config: &'a SecurityConfig,
) -> Result<Self> {
Ok(Self {
inner: HostTarget::create(output, config)?,
})
}
}
impl ExtractTarget for SevenZHostTarget<'_> {
type AdmittedFile = SevenZAdmittedFile;
type Parent = HostParent;
fn validate_file(
&mut self,
request: FileRequest<'_>,
tally: &mut Tally<'_>,
) -> Result<Admission<SevenZAdmittedFile>> {
let pending = match tally.admission(self.inner.screen_file(request)?, request.path)? {
Admission::Admit(pending) => pending,
Admission::Skipped(skipped) => return Ok(Admission::Skipped(skipped)),
};
let safe_path = pending.path().clone();
let (parent, leaf) = self
.inner
.dirs()
.ensure_parent(self.inner.root(), &safe_path)?;
let parent = parent.into_owned()?;
let occupancy = DestOccupancy::probe(&parent, leaf)?;
let write_mode = if occupancy.is_occupied() {
let root = self.inner.root();
let action = tally.options.existing_files.on_occupant(
EntryShape::File,
|| Ok(occupancy.occupant()),
|| {
root.created()
.created_here(&parent, leaf, safe_path.as_path())
},
|| common::destination_occupied(root.dest().as_path(), safe_path.as_path()),
)?;
match action {
OccupantAction::Skip => {
self.inner.charge_skipped()?;
return tally
.record_duplicate_skip(safe_path.as_path())
.map(Admission::Skipped);
}
OccupantAction::Replace(permit) => {
occupancy.replace_mode(permit).map_err(|kept| {
common::kept_refusal_at(kept, &parent, leaf, safe_path.as_path(), root)
})?
}
}
} else {
WriteMode::CreateNew
};
let file = self.inner.admit_file(pending)?;
Ok(Admission::Admit(SevenZAdmittedFile {
file,
write_mode,
parent,
}))
}
fn validate_directory(
&mut self,
path: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafePath<HostParent>>> {
self.inner.validate_directory(path, size, tally)
}
fn validate_symlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<SafeSymlink<HostParent>>> {
self.inner.validate_symlink(path, target, size, tally)
}
fn validate_hardlink(
&mut self,
path: &Path,
target: &Path,
size: EntrySize,
tally: &mut Tally<'_>,
) -> Result<Admission<ValidatedHardlink<HostParent>>> {
self.inner.validate_hardlink(path, target, size, tally)
}
fn finish_scan(&mut self) -> Result<()> {
self.inner.finish_scan()
}
fn directory(&mut self, path: &SafePath<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
self.inner.directory(path, tally)
}
fn file<R: Read>(
&mut self,
reader: &mut R,
faults: ReadFaults<'_>,
admitted: SevenZAdmittedFile,
tally: &mut Tally<'_>,
) -> Result<()> {
let SevenZAdmittedFile {
file,
write_mode,
parent,
} = admitted;
let (path, permit, _mode) = file.into_parts();
let (_, leaf) = Leaf::split(path.as_path())?;
let (copy_buffer, marking) = self.inner.copy_buffer_and_marking();
let written = match write_mode {
WriteMode::CreateNew => write_file_direct(
reader,
faults,
&parent,
leaf,
FileWrite {
copy_buffer,
permit,
marking,
progress: &mut *tally.progress,
},
)?,
WriteMode::ReplaceRegular(replace) => write_file_with_permit(
reader,
faults,
&parent,
leaf,
replace,
FileWrite {
copy_buffer,
permit,
marking,
progress: &mut *tally.progress,
},
)?,
};
self.inner.root().created().note(
tally.options.existing_files,
&parent,
leaf,
path.as_path(),
);
tally.record_file(written)
}
fn symlink(&mut self, symlink: &SafeSymlink<HostParent>, tally: &mut Tally<'_>) -> Result<()> {
self.inner.symlink(symlink, tally)
}
fn hardlink(
&mut self,
link: &SafePath<HostParent>,
target: &HardlinkTarget,
counted: crate::security::quota::EntryCount,
tally: &mut Tally<'_>,
) -> Result<()> {
self.inner.hardlink(link, target, counted, tally)
}
}
struct HostPrePass<'a> {
core: ValidatorCore<'a>,
dest: &'a DestDir,
config: &'a SecurityConfig,
options: SinkOptions,
}
impl PrePass for HostPrePass<'_> {
fn validate_path(
&mut self,
path: &Path,
shape: EntryShape,
) -> Result<Gated<EntryPath<SafePath>>> {
let ctx: ValidationContext<HostFs> = self.core.context();
self.core
.route_entry_in(path, shape, self.dest, &HostFs, &ctx)
}
fn directory(&mut self, _landing: &SafePath) -> Result<()> {
Ok(())
}
fn symlink(&mut self, link: &SafePath, file: &sevenz_rust2::ArchiveEntry) -> Result<()> {
common::require_symlink_creation()?;
refuse_undecoded_target_in(link, file, self.dest, self.config, &HostFs)
}
fn file(&mut self, safe_path: &SafePath) -> Result<FilePlan> {
let dest_path = self.dest.join(safe_path);
let occupancy = DestOccupancy::probe_path(&dest_path)?;
if occupancy.is_occupied() {
let action = self.options.existing_files.on_occupant(
EntryShape::File,
|| Ok(occupancy.occupant()),
|| false,
|| common::destination_occupied(self.dest.as_path(), safe_path.as_path()),
)?;
if matches!(action, OccupantAction::Skip) {
return Ok(FilePlan::Skip);
}
}
if occupancy.kept_symlink().is_some() {
return Err(replaces_symlink(safe_path.as_path()));
}
Ok(FilePlan::Reserve)
}
fn charge_skipped(&mut self) -> Result<()> {
self.core.charge_skipped()
}
fn reserve_symlink(&mut self, size: u64) -> Result<()> {
self.core.reserve_symlink(size)
}
fn reserve_file(&mut self, size: u64) -> Result<()> {
self.core.reserve_file(size).map(drop)
}
}
impl SevenZTarget for SevenZHostTarget<'_> {
fn with_pre_pass(
&self,
config: &SecurityConfig,
options: SinkOptions,
run: &mut dyn FnMut(&mut dyn PrePass) -> Result<()>,
) -> Result<()> {
let mut pre = HostPrePass {
core: ValidatorCore::new(config),
dest: self.inner.dest(),
config,
options,
};
run(&mut pre)
}
}