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/// Where an archive entry should land, relative to the destination.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum EntryTarget {
53    /// Write it here, relative to the destination directory.
54    Within(PathBuf),
55    /// The archive's own root (`.` or `./`). GNU tar emits one as the first
56    /// entry of `tar -C dir .`; it names the destination itself and carries
57    /// nothing to write, so it is skipped rather than refused.
58    ArchiveRoot,
59    /// Points outside the destination and must not be written.
60    Escaping,
61}
62
63/// Decide where an archive entry may be written.
64///
65/// Archive entries are attacker-controlled: an entry named `../../.bashrc` or
66/// `/etc/passwd` would otherwise write clean outside the destination
67/// directory (the "zip slip" bug). Anything absolute, rooted, or reaching
68/// upwards is refused outright rather than clamped, so a hostile archive
69/// fails loudly instead of extracting somewhere unexpected.
70pub fn classify_entry_path(raw: &Path) -> EntryTarget {
71    let mut safe = PathBuf::new();
72
73    for component in raw.components() {
74        match component {
75            Component::Normal(part) => safe.push(part),
76            // `.` contributes nothing but is harmless.
77            Component::CurDir => {}
78            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
79                return EntryTarget::Escaping
80            }
81        }
82    }
83
84    if safe.as_os_str().is_empty() {
85        return EntryTarget::ArchiveRoot;
86    }
87    EntryTarget::Within(safe)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn detects_each_supported_format() {
96        assert_eq!(
97            detect_format(Path::new("/a/x.zip")),
98            Some(ArchiveFormat::Zip)
99        );
100        assert_eq!(
101            detect_format(Path::new("/a/x.tar")),
102            Some(ArchiveFormat::Tar)
103        );
104        assert_eq!(
105            detect_format(Path::new("/a/x.tar.gz")),
106            Some(ArchiveFormat::TarGz)
107        );
108        assert_eq!(
109            detect_format(Path::new("/a/x.tgz")),
110            Some(ArchiveFormat::TarGz)
111        );
112    }
113
114    #[test]
115    fn tar_gz_wins_over_tar() {
116        // `.tar.gz` also ends with neither `.tar` nor `.gz` alone; the
117        // longest-match ordering is what keeps it from decoding as plain tar.
118        assert_eq!(
119            detect_format(Path::new("bundle.tar.gz")),
120            Some(ArchiveFormat::TarGz)
121        );
122    }
123
124    #[test]
125    fn detection_ignores_case() {
126        assert_eq!(detect_format(Path::new("X.ZIP")), Some(ArchiveFormat::Zip));
127        assert_eq!(
128            detect_format(Path::new("X.Tar.GZ")),
129            Some(ArchiveFormat::TarGz)
130        );
131    }
132
133    #[test]
134    fn unsupported_names_are_not_archives() {
135        assert_eq!(detect_format(Path::new("notes.txt")), None);
136        assert_eq!(detect_format(Path::new("archive.rar")), None);
137        // A bare `.gz` is not a tar we can walk.
138        assert_eq!(detect_format(Path::new("blob.gz")), None);
139        assert_eq!(detect_format(Path::new("noextension")), None);
140    }
141
142    #[test]
143    fn ordinary_entry_paths_are_kept_relative() {
144        assert_eq!(
145            classify_entry_path(Path::new("src/main.rs")),
146            EntryTarget::Within(PathBuf::from("src/main.rs"))
147        );
148        assert_eq!(
149            classify_entry_path(Path::new("./src/./main.rs")),
150            EntryTarget::Within(PathBuf::from("src/main.rs"))
151        );
152    }
153
154    #[test]
155    fn the_archive_root_entry_is_not_an_escape() {
156        // `tar -C dir .` makes `./` its first entry. Refusing it would abort
157        // extraction of an entirely ordinary archive on entry one.
158        assert_eq!(
159            classify_entry_path(Path::new("./")),
160            EntryTarget::ArchiveRoot
161        );
162        assert_eq!(
163            classify_entry_path(Path::new(".")),
164            EntryTarget::ArchiveRoot
165        );
166        assert_eq!(classify_entry_path(Path::new("")), EntryTarget::ArchiveRoot);
167    }
168
169    #[test]
170    fn entries_escaping_upwards_are_refused() {
171        assert_eq!(
172            classify_entry_path(Path::new("../evil")),
173            EntryTarget::Escaping
174        );
175        assert_eq!(
176            classify_entry_path(Path::new("a/../../evil")),
177            EntryTarget::Escaping
178        );
179        assert_eq!(
180            classify_entry_path(Path::new("a/b/../c")),
181            EntryTarget::Escaping
182        );
183    }
184
185    #[test]
186    fn absolute_entries_are_refused() {
187        assert_eq!(
188            classify_entry_path(Path::new("/etc/passwd")),
189            EntryTarget::Escaping
190        );
191        assert_eq!(classify_entry_path(Path::new("/")), EntryTarget::Escaping);
192    }
193}