Skip to main content

oxinav_core/
archive.rs

1//! Archive support: recognising a supported format and keeping extraction
2//! inside its destination.
3//!
4//! Both decisions are pure functions over paths so they can be exercised
5//! without an archive on disk; the decoding itself lives behind the
6//! `Filesystem` trait.
7
8use std::path::{Component, Path, PathBuf};
9
10/// An archive format the viewer can extract.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ArchiveFormat {
13    Zip,
14    Tar,
15    TarGz,
16}
17
18impl ArchiveFormat {
19    /// How the format is named in messages.
20    pub const fn label(self) -> &'static str {
21        match self {
22            Self::Zip => "zip",
23            Self::Tar => "tar",
24            Self::TarGz => "tar.gz",
25        }
26    }
27}
28
29/// Recognise `path`'s archive format by name, or `None` when it is not one we
30/// extract.
31///
32/// Named rather than sniffed: the user picked this entry from a listing, so
33/// the extension is the thing they are going on, and a mismatch is better
34/// reported than silently worked around.
35pub fn detect_format(path: &Path) -> Option<ArchiveFormat> {
36    let name = path.file_name()?.to_string_lossy().to_lowercase();
37
38    // Ordered longest-first: `.tar.gz` must win over `.gz`.
39    if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
40        Some(ArchiveFormat::TarGz)
41    } else if name.ends_with(".tar") {
42        Some(ArchiveFormat::Tar)
43    } else if name.ends_with(".zip") {
44        Some(ArchiveFormat::Zip)
45    } else {
46        None
47    }
48}
49
50/// What an entry being packed is. Symlinks are their own kind because they
51/// are stored as links, never followed.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum EntryKind {
54    File,
55    Dir,
56    Symlink,
57}
58
59/// One entry to write into a new archive: the file on disk, and the name it
60/// gets inside the archive (relative to the directory being packed from).
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct ArchiveEntry {
63    pub source: PathBuf,
64    pub name: PathBuf,
65    pub kind: EntryKind,
66}
67
68/// The name to suggest for an archive of `selected` (entry names) taken from
69/// `cwd`: the entry's own name for one, the directory's name for several,
70/// always as a zip — the format most people can open.
71pub fn default_archive_name(selected: &[&str], cwd: &Path) -> String {
72    let stem = match selected {
73        [single] => (*single).to_string(),
74        _ => cwd
75            .file_name()
76            .map(|name| name.to_string_lossy().into_owned())
77            .unwrap_or_else(|| "archive".to_string()),
78    };
79    format!("{stem}.zip")
80}
81
82/// Where an archive entry should land, relative to the destination.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum EntryTarget {
85    /// Write it here, relative to the destination directory.
86    Within(PathBuf),
87    /// The archive's own root (`.` or `./`). GNU tar emits one as the first
88    /// entry of `tar -C dir .`; it names the destination itself and carries
89    /// nothing to write, so it is skipped rather than refused.
90    ArchiveRoot,
91    /// Points outside the destination and must not be written.
92    Escaping,
93}
94
95/// Decide where an archive entry may be written.
96///
97/// Archive entries are attacker-controlled: an entry named `../../.bashrc` or
98/// `/etc/passwd` would otherwise write clean outside the destination
99/// directory (the "zip slip" bug). Anything absolute, rooted, or reaching
100/// upwards is refused outright rather than clamped, so a hostile archive
101/// fails loudly instead of extracting somewhere unexpected.
102pub fn classify_entry_path(raw: &Path) -> EntryTarget {
103    let mut safe = PathBuf::new();
104
105    for component in raw.components() {
106        match component {
107            Component::Normal(part) => safe.push(part),
108            // `.` contributes nothing but is harmless.
109            Component::CurDir => {}
110            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
111                return EntryTarget::Escaping
112            }
113        }
114    }
115
116    if safe.as_os_str().is_empty() {
117        return EntryTarget::ArchiveRoot;
118    }
119    EntryTarget::Within(safe)
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn detects_each_supported_format() {
128        assert_eq!(
129            detect_format(Path::new("/a/x.zip")),
130            Some(ArchiveFormat::Zip)
131        );
132        assert_eq!(
133            detect_format(Path::new("/a/x.tar")),
134            Some(ArchiveFormat::Tar)
135        );
136        assert_eq!(
137            detect_format(Path::new("/a/x.tar.gz")),
138            Some(ArchiveFormat::TarGz)
139        );
140        assert_eq!(
141            detect_format(Path::new("/a/x.tgz")),
142            Some(ArchiveFormat::TarGz)
143        );
144    }
145
146    #[test]
147    fn default_name_for_one_entry_is_its_own() {
148        assert_eq!(
149            default_archive_name(&["report.pdf"], Path::new("/home/u")),
150            "report.pdf.zip"
151        );
152        assert_eq!(
153            default_archive_name(&["src"], Path::new("/home/u")),
154            "src.zip"
155        );
156    }
157
158    #[test]
159    fn default_name_for_several_is_the_directory() {
160        assert_eq!(
161            default_archive_name(&["a", "b", "c"], Path::new("/home/u/photos")),
162            "photos.zip"
163        );
164    }
165
166    #[test]
167    fn default_name_at_the_root_is_generic() {
168        assert_eq!(
169            default_archive_name(&["a", "b"], Path::new("/")),
170            "archive.zip"
171        );
172    }
173
174    #[test]
175    fn tar_gz_wins_over_tar() {
176        // `.tar.gz` also ends with neither `.tar` nor `.gz` alone; the
177        // longest-match ordering is what keeps it from decoding as plain tar.
178        assert_eq!(
179            detect_format(Path::new("bundle.tar.gz")),
180            Some(ArchiveFormat::TarGz)
181        );
182    }
183
184    #[test]
185    fn detection_ignores_case() {
186        assert_eq!(detect_format(Path::new("X.ZIP")), Some(ArchiveFormat::Zip));
187        assert_eq!(
188            detect_format(Path::new("X.Tar.GZ")),
189            Some(ArchiveFormat::TarGz)
190        );
191    }
192
193    #[test]
194    fn unsupported_names_are_not_archives() {
195        assert_eq!(detect_format(Path::new("notes.txt")), None);
196        assert_eq!(detect_format(Path::new("archive.rar")), None);
197        // A bare `.gz` is not a tar we can walk.
198        assert_eq!(detect_format(Path::new("blob.gz")), None);
199        assert_eq!(detect_format(Path::new("noextension")), None);
200    }
201
202    #[test]
203    fn ordinary_entry_paths_are_kept_relative() {
204        assert_eq!(
205            classify_entry_path(Path::new("src/main.rs")),
206            EntryTarget::Within(PathBuf::from("src/main.rs"))
207        );
208        assert_eq!(
209            classify_entry_path(Path::new("./src/./main.rs")),
210            EntryTarget::Within(PathBuf::from("src/main.rs"))
211        );
212    }
213
214    #[test]
215    fn the_archive_root_entry_is_not_an_escape() {
216        // `tar -C dir .` makes `./` its first entry. Refusing it would abort
217        // extraction of an entirely ordinary archive on entry one.
218        assert_eq!(
219            classify_entry_path(Path::new("./")),
220            EntryTarget::ArchiveRoot
221        );
222        assert_eq!(
223            classify_entry_path(Path::new(".")),
224            EntryTarget::ArchiveRoot
225        );
226        assert_eq!(classify_entry_path(Path::new("")), EntryTarget::ArchiveRoot);
227    }
228
229    #[test]
230    fn entries_escaping_upwards_are_refused() {
231        assert_eq!(
232            classify_entry_path(Path::new("../evil")),
233            EntryTarget::Escaping
234        );
235        assert_eq!(
236            classify_entry_path(Path::new("a/../../evil")),
237            EntryTarget::Escaping
238        );
239        assert_eq!(
240            classify_entry_path(Path::new("a/b/../c")),
241            EntryTarget::Escaping
242        );
243    }
244
245    #[test]
246    fn absolute_entries_are_refused() {
247        assert_eq!(
248            classify_entry_path(Path::new("/etc/passwd")),
249            EntryTarget::Escaping
250        );
251        assert_eq!(classify_entry_path(Path::new("/")), EntryTarget::Escaping);
252    }
253}