blob: f49bd5ea3b3c985b1ae9d5845437e93548ed0189 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
use std::path::{Component, Path, PathBuf};
use anyhow::{bail, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootfsPath(PathBuf);
impl RootfsPath {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
if path.as_os_str().is_empty() || path.is_absolute() {
bail!("rootfs path must be a non-empty relative path: {}", path.display());
}
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::Normal(component) => normalized.push(component),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
bail!("rootfs path cannot escape the rootfs: {}", path.display());
}
}
}
Ok(Self(normalized))
}
pub fn as_path(&self) -> &Path {
&self.0
}
}
pub fn relative_symlink_is_safe(link_parent: &Path, target: &Path) -> bool {
if target.is_absolute() {
return false;
}
let mut depth = link_parent.components().count();
for component in target.components() {
match component {
Component::Normal(_) | Component::CurDir => {}
Component::ParentDir => {
if depth == 0 {
return false;
}
depth -= 1;
}
Component::RootDir | Component::Prefix(_) => return false,
}
}
true
}
|