Skip to main content

elfpak_core/
paths.rs

1//! Lexical path handling.
2//!
3//! Logical paths are interpreted relative to a source or output root, never
4//! passed directly to the host OS.
5
6use std::path::{Component, Path, PathBuf};
7
8/// Normalize a path into an absolute logical path.
9pub fn normalize_absolute(path: &Path) -> PathBuf {
10    let mut out = PathBuf::from("/");
11    for component in path.components() {
12        match component {
13            Component::RootDir | Component::Prefix(_) => {}
14            Component::CurDir => {}
15            Component::ParentDir => {
16                out.pop();
17            }
18            Component::Normal(part) => out.push(part),
19        }
20    }
21    out
22}
23
24/// Join a logical absolute path onto a real directory, refusing anything that
25/// would land outside of it.
26pub fn join_under(base: &Path, logical: &Path) -> PathBuf {
27    let normalized = normalize_absolute(logical);
28    let relative = normalized
29        .strip_prefix("/")
30        .expect("normalized logical paths are absolute");
31    let joined = base.join(relative);
32    // Containment is checked here, and again by the caller before it writes.
33    assert!(joined.starts_with(base));
34    joined
35}
36
37/// Absolute parent directory of a logical path (`/` for top-level entries).
38pub fn logical_parent(path: &Path) -> PathBuf {
39    assert!(path.is_absolute());
40    path.parent()
41        .map(Path::to_path_buf)
42        .unwrap_or_else(|| PathBuf::from("/"))
43}
44
45/// Every ancestor directory of a logical path, shallowest first, excluding `/`.
46pub fn ancestor_dirs(path: &Path) -> Vec<PathBuf> {
47    assert!(path.is_absolute());
48
49    let mut dirs = Vec::new();
50    let mut current = PathBuf::from("/");
51    let parent = logical_parent(path);
52    for component in parent.components() {
53        if let Component::Normal(part) = component {
54            current.push(part);
55            dirs.push(current.clone());
56        }
57    }
58    dirs
59}
60
61/// Render bytes as lowercase hex (used for digests).
62pub fn hex(bytes: &[u8]) -> String {
63    let mut s = String::with_capacity(bytes.len() * 2);
64    for byte in bytes {
65        // A nibble is always a valid hex digit, so neither `from_digit` can fail.
66        s.push(char::from_digit(u32::from(byte >> 4), 16).expect("a nibble is one hex digit"));
67        s.push(char::from_digit(u32::from(byte & 0xf), 16).expect("a nibble is one hex digit"));
68    }
69    s
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn normalizes_dot_and_parent_components() {
78        assert_eq!(
79            normalize_absolute(Path::new("/a/./b/../c")),
80            Path::new("/a/c")
81        );
82        assert_eq!(
83            normalize_absolute(Path::new("/../../etc")),
84            Path::new("/etc")
85        );
86        assert_eq!(normalize_absolute(Path::new("a/b")), Path::new("/a/b"));
87    }
88
89    #[test]
90    fn join_under_cannot_escape_the_base() {
91        let base = Path::new("/out");
92        assert_eq!(
93            join_under(base, Path::new("/etc/passwd")),
94            Path::new("/out/etc/passwd")
95        );
96        assert_eq!(
97            join_under(base, Path::new("/../../etc")),
98            Path::new("/out/etc")
99        );
100        assert_eq!(join_under(base, Path::new("/")), Path::new("/out"));
101    }
102
103    #[test]
104    fn ancestors_are_listed_shallowest_first() {
105        assert_eq!(
106            ancestor_dirs(Path::new("/usr/lib/x86_64-linux-gnu/libc.so.6")),
107            vec![
108                PathBuf::from("/usr"),
109                PathBuf::from("/usr/lib"),
110                PathBuf::from("/usr/lib/x86_64-linux-gnu"),
111            ]
112        );
113        assert!(ancestor_dirs(Path::new("/libc.so.6")).is_empty());
114    }
115
116    #[test]
117    fn hex_is_lowercase_and_padded() {
118        assert_eq!(hex(&[0x00, 0x0f, 0xff]), "000fff");
119    }
120}