use std::borrow::Cow;
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashSet;
use std::num::NonZeroU64;
use std::num::NonZeroUsize;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::Admit;
use crate::ArchiveError;
use crate::ConfigProblem;
use crate::ConfigSetting;
use crate::Result;
use crate::SkipKind;
use crate::Violation;
use crate::pattern::EntryPattern;
use crate::pattern::PatternList;
use crate::pattern::normalized;
use crate::security::fs_view::LinkKind;
use crate::security::validator::NodeKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StripComponents(NonZeroUsize);
impl StripComponents {
pub fn new(count: NonZeroU64, max_path_depth: NonZeroUsize) -> Result<Self> {
usize::try_from(count.get())
.ok()
.filter(|count| *count <= max_path_depth.get())
.and_then(NonZeroUsize::new)
.map(Self)
.ok_or_else(|| ArchiveError::InvalidConfiguration {
setting: ConfigSetting::StripComponents,
problem: ConfigProblem::TooLarge {
max: u64::try_from(max_path_depth.get()).unwrap_or(u64::MAX),
},
})
}
#[must_use]
pub const fn get(self) -> NonZeroUsize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum PathRewrite {
#[default]
Keep,
Strip(StripComponents),
Flatten,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EntrySelection {
include: PatternList,
exclude: PatternList,
rewrite: PathRewrite,
}
impl EntrySelection {
#[must_use]
pub fn is_default(&self) -> bool {
self.include.is_empty() && self.exclude.is_empty() && self.rewrite == PathRewrite::Keep
}
#[must_use]
pub fn include(&self) -> &[EntryPattern] {
self.include.as_slice()
}
#[must_use]
pub fn exclude(&self) -> &[EntryPattern] {
self.exclude.as_slice()
}
#[must_use]
pub const fn rewrite(&self) -> PathRewrite {
self.rewrite
}
#[must_use]
pub fn with_include(mut self, pattern: EntryPattern) -> Self {
self.include = std::mem::take(&mut self.include).pushed(pattern);
self
}
#[must_use]
pub fn with_exclude(mut self, pattern: EntryPattern) -> Self {
self.exclude = std::mem::take(&mut self.exclude).pushed(pattern);
self
}
#[must_use]
pub const fn with_rewrite(mut self, rewrite: PathRewrite) -> Self {
self.rewrite = rewrite;
self
}
#[must_use]
pub const fn with_strip(mut self, strip: Option<StripComponents>) -> Self {
self.rewrite = match (strip, self.rewrite) {
(Some(strip), _) => PathRewrite::Strip(strip),
(None, PathRewrite::Flatten) => PathRewrite::Flatten,
(None, _) => PathRewrite::Keep,
};
self
}
#[must_use]
pub const fn with_flatten(mut self, flatten: bool) -> Self {
self.rewrite = match (flatten, self.rewrite) {
(true, _) => PathRewrite::Flatten,
(false, PathRewrite::Flatten) => PathRewrite::Keep,
(false, rewrite) => rewrite,
};
self
}
#[must_use]
pub fn with_include_list(mut self, patterns: Vec<EntryPattern>) -> Self {
self.include = patterns.into();
self
}
#[must_use]
pub fn with_exclude_list(mut self, patterns: Vec<EntryPattern>) -> Self {
self.exclude = patterns.into();
self
}
pub(crate) fn decide(
&self,
original: &Path,
shape: EntryShape,
hits: Option<&IncludeHits>,
) -> Result<Decision> {
let normalized = normalized(original);
let path = normalized.as_deref();
if !self.record_includes(path, hits) || self.exclude.any_match(path) {
return Ok(Decision::Skip(SkipKind::NotSelected));
}
Ok(match (self.rewrite, shape) {
(PathRewrite::Keep, _) => Decision::Extract(Placement::Unchanged),
(PathRewrite::Strip(strip), _) => {
let kept: PathBuf = original.components().skip(strip.get().get()).collect();
Decision::rewritten(kept)
}
(PathRewrite::Flatten, EntryShape::File) => {
Decision::rewritten(original.file_name().map_or_default(PathBuf::from))
}
(PathRewrite::Flatten, EntryShape::Directory) => Decision::Skip(SkipKind::StrippedAway),
(PathRewrite::Flatten, EntryShape::Link(kind)) => {
return Err(Violation::LinkUnderFlatten {
kind,
name: crate::path_text(original).into(),
}
.into());
}
})
}
pub(crate) fn lexical_landing<'a>(
&self,
raw: &'a Path,
kind: NodeKind,
) -> Option<Cow<'a, Path>> {
if self.is_default() {
return Some(Cow::Borrowed(raw));
}
let normal: PathBuf = raw
.components()
.filter(|component| matches!(component, Component::Normal(_)))
.collect();
let shape = match kind {
NodeKind::Directory => EntryShape::Directory,
NodeKind::NonDirectory => EntryShape::File,
};
match self.decide(&normal, shape, None) {
Ok(Decision::Extract(Placement::Unchanged)) | Err(_) => Some(Cow::Owned(normal)),
Ok(Decision::Extract(Placement::Rewritten(rewritten))) => Some(Cow::Owned(rewritten.0)),
Ok(Decision::Skip(_)) => None,
}
}
fn record_includes(&self, path: Option<&[u8]>, hits: Option<&IncludeHits>) -> bool {
if self.include.is_empty() {
return true;
}
let Some(hits) = hits else {
return self.include.any_match(path);
};
let mut included = false;
hits.with_scratch(|scratch| {
self.include.matching(path, scratch, |index| {
included = true;
hits.record(index);
});
});
included
}
pub(crate) fn require_includes_matched<'a>(
&self,
entries: impl IntoIterator<Item = &'a Path>,
) -> Result<()> {
if self.include.is_empty() {
return Ok(());
}
let hits = IncludeHits::of(self);
for raw in entries {
let normal: PathBuf = raw
.components()
.filter(|component| matches!(component, Component::Normal(_)))
.collect();
self.record_includes(normalized(&normal).as_deref(), Some(&hits));
}
hits.require_all_matched(self)
}
pub(crate) fn mapped_link_target<'t>(
&self,
link: &Path,
target: &'t Path,
absolute: Admit,
) -> Result<Cow<'t, Path>> {
match self.map_link_target(target, absolute)? {
TargetMapping::Unchanged => Ok(Cow::Borrowed(target)),
TargetMapping::Mapped(mapped) => Ok(Cow::Owned(mapped)),
TargetMapping::NotExtracted => Err(target_not_extracted(link, target)),
}
}
pub(crate) fn map_link_target(&self, target: &Path, absolute: Admit) -> Result<TargetMapping> {
if self.is_default() {
return Ok(TargetMapping::Unchanged);
}
let mut root = PathBuf::new();
let mut normalized = PathBuf::new();
for component in target.components() {
match component {
Component::Normal(name) => normalized.push(name),
Component::ParentDir => {
return Err(ArchiveError::PathTraversal {
path: target.to_path_buf(),
});
}
Component::RootDir | Component::Prefix(_) if !absolute.is_allowed() => {
root.push(component.as_os_str());
}
Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
}
}
if normalized.is_empty() {
return Ok(TargetMapping::Unchanged);
}
Ok(match self.decide(&normalized, EntryShape::File, None)? {
Decision::Skip(_) if !root.is_empty() => TargetMapping::Unchanged,
Decision::Skip(_) => TargetMapping::NotExtracted,
Decision::Extract(Placement::Unchanged) => TargetMapping::Mapped(root.join(normalized)),
Decision::Extract(Placement::Rewritten(rewritten)) => {
TargetMapping::Mapped(root.join(rewritten.0))
}
})
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct SelectionRun<'a> {
pub selection: &'a EntrySelection,
pub hits: Option<&'a IncludeHits>,
}
impl SelectionRun<'_> {
pub(crate) fn decide(&self, original: &Path, shape: EntryShape) -> Result<Decision> {
self.selection.decide(original, shape, self.hits)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EntryShape {
Directory,
File,
Link(LinkKind),
}
impl EntryShape {
pub(crate) const fn node_kind(self) -> NodeKind {
match self {
Self::Directory => NodeKind::Directory,
Self::File | Self::Link(_) => NodeKind::NonDirectory,
}
}
}
#[derive(Debug)]
pub(crate) enum Decision {
Extract(Placement),
Skip(SkipKind),
}
impl Decision {
fn rewritten(kept: PathBuf) -> Self {
if kept.is_empty() {
Self::Skip(SkipKind::StrippedAway)
} else {
Self::Extract(Placement::Rewritten(Rewritten(kept)))
}
}
}
#[derive(Debug)]
pub(crate) enum Placement {
Unchanged,
Rewritten(Rewritten),
}
#[derive(Debug)]
pub(crate) struct Rewritten(PathBuf);
impl Rewritten {
pub(crate) fn as_path(&self) -> &Path {
&self.0
}
}
#[derive(Debug)]
pub(crate) enum TargetMapping {
Unchanged,
Mapped(PathBuf),
NotExtracted,
}
#[derive(Debug)]
pub(crate) struct IncludeHits {
matched: Box<[Cell<bool>]>,
scratch: RefCell<Vec<usize>>,
}
impl IncludeHits {
pub(crate) fn of(selection: &EntrySelection) -> Self {
Self {
matched: selection
.include()
.iter()
.map(|_| Cell::new(false))
.collect(),
scratch: RefCell::default(),
}
}
fn with_scratch(&self, body: impl FnOnce(&mut Vec<usize>)) {
let mut scratch = self.scratch.take();
body(&mut scratch);
self.scratch.replace(scratch);
}
fn record(&self, index: usize) {
if let Some(slot) = self.matched.get(index) {
slot.set(true);
}
}
pub(crate) fn require_all_matched(&self, selection: &EntrySelection) -> Result<()> {
let unmatched: Box<[EntryPattern]> = selection
.include()
.iter()
.zip(self.matched.iter())
.filter(|(_, hit)| !hit.get())
.map(|(pattern, _)| pattern.clone())
.collect();
unmatched.is_empty().ok_or(ArchiveError::UnmatchedInclude {
patterns: unmatched,
})
}
}
#[derive(Debug, Default)]
pub(crate) struct LandingClaims {
seen: RefCell<HashSet<PathBuf>>,
ambiguous: RefCell<HashSet<PathBuf>>,
}
impl LandingClaims {
pub(crate) fn claim(&self, selection: &EntrySelection, landing: &Path) {
if selection.rewrite == PathRewrite::Keep {
return;
}
let mut seen = self.seen.borrow_mut();
if !seen.insert(landing.to_path_buf()) {
self.ambiguous.borrow_mut().insert(landing.to_path_buf());
}
}
pub(crate) fn require_unambiguous(&self, link: &Path, target: &Path) -> Result<()> {
if self.ambiguous.borrow().contains(target) {
return Err(Violation::HardlinkTargetAmbiguous {
link: crate::path_text(link).into(),
target: crate::path_text(target).into(),
}
.into());
}
Ok(())
}
}
fn target_not_extracted(link: &Path, target: &Path) -> ArchiveError {
Violation::HardlinkTargetNotExtracted {
link: crate::path_text(link).into(),
target: crate::path_text(target).into(),
}
.into()
}
#[cfg(test)]
mod tests {
use std::assert_matches;
use super::*;
use crate::non_zero;
fn pattern(text: &str) -> EntryPattern {
EntryPattern::parse_for(ConfigSetting::EntryInclude, text).unwrap()
}
fn decide(selection: &EntrySelection, path: &str) -> Decision {
selection
.decide(Path::new(path), EntryShape::File, None)
.unwrap()
}
fn skipped(decision: &Decision) -> Option<SkipKind> {
match decision {
Decision::Skip(kind) => Some(*kind),
Decision::Extract(_) => None,
}
}
fn landing(decision: Decision) -> Option<PathBuf> {
match decision {
Decision::Extract(Placement::Rewritten(rewritten)) => Some(rewritten.0),
_ => None,
}
}
#[test]
fn default_selects_everything_unchanged() {
let selection = EntrySelection::default();
assert!(selection.is_default());
assert_matches!(
decide(&selection, "a/b"),
Decision::Extract(Placement::Unchanged)
);
}
#[test]
fn include_selects_a_subtree_and_nothing_else() {
let selection = EntrySelection::default().with_include(pattern("a/b"));
assert!(skipped(&decide(&selection, "a/b/c.txt")).is_none());
assert!(skipped(&decide(&selection, "a/b")).is_none());
assert_eq!(
skipped(&decide(&selection, "a/d.txt")),
Some(SkipKind::NotSelected)
);
}
#[test]
fn exclude_always_wins_over_include() {
let selection = EntrySelection::default()
.with_include(pattern("src"))
.with_exclude(pattern("src/generated"));
assert!(skipped(&decide(&selection, "src/main.rs")).is_none());
assert_eq!(
skipped(&decide(&selection, "src/generated/x.rs")),
Some(SkipKind::NotSelected)
);
}
#[test]
fn bare_name_matches_a_component_at_any_depth() {
let selection = EntrySelection::default().with_exclude(pattern("docs"));
assert!(skipped(&decide(&selection, "top/docs/a")).is_some());
assert!(skipped(&decide(&selection, "top/doc/a")).is_none());
}
#[test]
fn matching_is_case_sensitive() {
let selection = EntrySelection::default().with_include(pattern("README"));
assert!(skipped(&decide(&selection, "readme")).is_some());
assert!(skipped(&decide(&selection, "README")).is_none());
}
#[test]
fn strip_removes_leading_components_and_skips_what_runs_out() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let selection = EntrySelection::default().with_rewrite(PathRewrite::Strip(strip));
assert_eq!(
landing(decide(&selection, "top/src/main.rs")),
Some(PathBuf::from("src/main.rs"))
);
for exhausted in ["top", "README"] {
assert_eq!(
skipped(&decide(&selection, exhausted)),
Some(SkipKind::StrippedAway)
);
}
assert_eq!(
skipped(&decide(&selection, "")),
Some(SkipKind::StrippedAway)
);
}
#[test]
fn selection_matches_before_stripping() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let selection = EntrySelection::default()
.with_include(pattern("top/src"))
.with_rewrite(PathRewrite::Strip(strip));
assert_eq!(
landing(decide(&selection, "top/src/a")),
Some(PathBuf::from("src/a"))
);
assert_eq!(
skipped(&decide(&selection, "src/a")),
Some(SkipKind::NotSelected)
);
}
#[test]
fn strip_and_flatten_builders_set_one_rewrite_without_disturbing_the_other() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let stripped = EntrySelection::default().with_strip(Some(strip));
let flattened = EntrySelection::default().with_flatten(true);
assert_eq!(stripped.rewrite(), PathRewrite::Strip(strip));
assert_eq!(flattened.rewrite(), PathRewrite::Flatten);
assert_eq!(
flattened.clone().with_strip(None).rewrite(),
PathRewrite::Flatten
);
assert_eq!(
stripped.clone().with_flatten(false).rewrite(),
PathRewrite::Strip(strip)
);
assert_eq!(stripped.with_strip(None).rewrite(), PathRewrite::Keep);
assert_eq!(flattened.with_flatten(false).rewrite(), PathRewrite::Keep);
}
#[test]
fn the_list_builders_replace_a_list_and_keep_the_rewrite() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let selection = EntrySelection::default()
.with_include(pattern("old"))
.with_exclude(pattern("old"))
.with_rewrite(PathRewrite::Strip(strip))
.with_include_list(vec![pattern("a"), pattern("b")])
.with_exclude_list(Vec::new());
assert_eq!(selection.include(), [pattern("a"), pattern("b")]);
assert!(selection.exclude().is_empty());
assert_eq!(selection.rewrite(), PathRewrite::Strip(strip));
}
#[test]
fn strip_count_is_bounded_by_the_path_depth() {
assert!(StripComponents::new(non_zero!(32), non_zero!(32)).is_ok());
let refused = StripComponents::new(non_zero!(33), non_zero!(32));
assert_matches!(
refused,
Err(ArchiveError::InvalidConfiguration {
setting: ConfigSetting::StripComponents,
problem: ConfigProblem::TooLarge { max: 32 },
})
);
}
#[test]
fn include_hits_report_every_pattern_that_matched_nothing() {
let selection = EntrySelection::default()
.with_include(pattern("a"))
.with_include(pattern("b"))
.with_exclude(pattern("a"));
let hits = IncludeHits::of(&selection);
selection
.decide(Path::new("a"), EntryShape::File, Some(&hits))
.unwrap();
let Err(ArchiveError::UnmatchedInclude { patterns }) = hits.require_all_matched(&selection)
else {
panic!("pattern b matched nothing");
};
assert_eq!(patterns.len(), 1);
assert_eq!(patterns[0].to_string(), "b");
}
#[test]
fn a_nested_scratch_use_gets_its_own_empty_buffer() {
let hits = IncludeHits::of(&EntrySelection::default());
hits.with_scratch(|outer| {
outer.push(1);
hits.with_scratch(|inner| {
assert!(inner.is_empty());
inner.push(2);
});
assert_eq!(outer.as_slice(), [1]);
});
}
#[test]
fn link_target_maps_through_the_same_rules() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let selection = EntrySelection::default()
.with_exclude(pattern("hidden"))
.with_rewrite(PathRewrite::Strip(strip));
assert_matches!(
selection.map_link_target(Path::new("./top/orig"), Admit::Refuse).unwrap(),
TargetMapping::Mapped(path) if path == Path::new("orig")
);
assert_matches!(
selection
.map_link_target(Path::new("top"), Admit::Refuse)
.unwrap(),
TargetMapping::NotExtracted
);
assert_matches!(
selection
.map_link_target(Path::new("top/hidden/x"), Admit::Refuse)
.unwrap(),
TargetMapping::NotExtracted
);
assert_matches!(
selection.map_link_target(Path::new("top/../x"), Admit::Refuse),
Err(ArchiveError::PathTraversal { .. })
);
assert_matches!(
selection
.map_link_target(Path::new("/abs"), Admit::Refuse)
.unwrap(),
TargetMapping::Unchanged,
"a refused absolute target stays for the validator to refuse"
);
assert_matches!(
selection
.map_link_target(Path::new("/abs"), Admit::Allow)
.unwrap(),
TargetMapping::NotExtracted
);
assert_matches!(
selection
.map_link_target(Path::new("/"), Admit::Refuse)
.unwrap(),
TargetMapping::Unchanged
);
}
#[test]
fn absolute_link_target_is_relocated_only_where_absolute_paths_are_admitted() {
let strip = StripComponents::new(non_zero!(1), non_zero!(32)).unwrap();
let selection = EntrySelection::default()
.with_include(pattern("top"))
.with_rewrite(PathRewrite::Strip(strip));
assert_matches!(
selection.map_link_target(Path::new("/top/orig"), Admit::Allow).unwrap(),
TargetMapping::Mapped(path) if path == Path::new("orig")
);
assert_matches!(
selection
.map_link_target(Path::new("/other/orig"), Admit::Allow)
.unwrap(),
TargetMapping::NotExtracted
);
assert_matches!(
selection.map_link_target(Path::new("/top/../x"), Admit::Allow),
Err(ArchiveError::PathTraversal { .. })
);
assert_matches!(
selection.map_link_target(Path::new("/top/orig"), Admit::Refuse).unwrap(),
TargetMapping::Mapped(path) if path == Path::new("/orig")
);
}
}