use std::borrow::Cow;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
pub const GLOBAL_DIR_SUFFIX: &str = "__XLDIR__";
pub const SLASH_SEPARATOR: &str = "/";
pub const GLOBAL_DIR_SUFFIX_WITH_SLASH: &str = "__XLDIR__/";
#[inline]
pub fn is_separator(c: u8) -> bool {
c == b'/' || (cfg!(target_os = "windows") && c == b'\\')
}
pub fn has_suffix(s: &str, suffix: &str) -> bool {
if cfg!(target_os = "windows") {
s.to_lowercase().ends_with(&suffix.to_lowercase())
} else {
s.ends_with(suffix)
}
}
pub fn encode_dir_object_ref(object: &str) -> Cow<'_, str> {
if has_suffix(object, SLASH_SEPARATOR) {
Cow::Owned(format!("{}{}", object.trim_end_matches(SLASH_SEPARATOR), GLOBAL_DIR_SUFFIX))
} else {
Cow::Borrowed(object)
}
}
pub fn encode_dir_object(object: &str) -> String {
encode_dir_object_ref(object).into_owned()
}
pub fn is_dir_object(object: &str) -> bool {
let obj = encode_dir_object(object);
obj.ends_with(GLOBAL_DIR_SUFFIX)
}
pub fn decode_dir_object(object: &str) -> String {
if has_suffix(object, GLOBAL_DIR_SUFFIX) {
format!("{}{}", object.trim_end_matches(GLOBAL_DIR_SUFFIX), SLASH_SEPARATOR)
} else {
object.to_string()
}
}
pub fn retain_slash(s: &str) -> String {
if s.is_empty() {
return s.to_string();
}
if s.ends_with(SLASH_SEPARATOR) {
s.to_string()
} else {
format!("{s}{SLASH_SEPARATOR}")
}
}
pub fn strings_has_prefix_fold(s: &str, prefix: &str) -> bool {
if s.starts_with(prefix) {
return true;
}
s.get(..prefix.len())
.is_some_and(|s_prefix| s_prefix.eq_ignore_ascii_case(prefix))
}
pub fn has_prefix(s: &str, prefix: &str) -> bool {
if cfg!(target_os = "windows") {
return strings_has_prefix_fold(s, prefix);
}
s.starts_with(prefix)
}
pub fn path_join<P: AsRef<Path>>(elem: &[P]) -> PathBuf {
let trailing_slash = !elem.is_empty()
&& elem.last().is_some_and(|last| {
let s = last.as_ref().to_string_lossy();
s.ends_with(SLASH_SEPARATOR) || (cfg!(target_os = "windows") && s.ends_with('\\'))
});
let len = elem.iter().map(|s| s.as_ref().to_string_lossy().len()).sum::<usize>() + elem.len();
let mut dst = String::with_capacity(len);
let mut added = 0;
for e in elem {
let s = e.as_ref().to_string_lossy();
if added > 0 || !s.is_empty() {
if added > 0 {
dst.push_str(SLASH_SEPARATOR);
}
dst.push_str(&s);
added += s.len();
}
}
if path_needs_clean(dst.as_bytes()) {
let mut clean_path = clean(&dst);
if trailing_slash {
clean_path.push_str(SLASH_SEPARATOR);
}
return clean_path.into();
}
if trailing_slash {
dst.push_str(SLASH_SEPARATOR);
}
dst.into()
}
pub fn path_join_buf(elements: &[&str]) -> String {
let trailing_slash = !elements.is_empty()
&& elements
.last()
.is_some_and(|last| last.ends_with(SLASH_SEPARATOR) || (cfg!(target_os = "windows") && last.ends_with('\\')));
let len = elements.iter().map(|s| s.len()).sum::<usize>() + elements.len();
let mut dst = String::with_capacity(len);
let mut added = 0;
for e in elements {
if added > 0 || !e.is_empty() {
if added > 0 {
dst.push_str(SLASH_SEPARATOR);
}
dst.push_str(e);
added += e.len();
}
}
if path_needs_clean(dst.as_bytes()) {
let mut clean_path = clean(&dst);
if trailing_slash {
clean_path.push_str(SLASH_SEPARATOR);
}
return clean_path;
}
if trailing_slash {
dst.push_str(SLASH_SEPARATOR);
}
dst
}
fn path_needs_clean(path: &[u8]) -> bool {
if path.is_empty() {
return true;
}
if cfg!(target_os = "windows") && path.contains(&b'\\') {
return true;
}
let rooted = path[0] == b'/';
let n = path.len();
let (mut r, mut w) = if rooted { (1, 1) } else { (0, 0) };
while r < n {
match path[r] {
b if b > 127 => {
return true;
}
b'/' => {
return true;
}
b'.' => {
if r + 1 == n || path[r + 1] == b'/' {
return true;
}
if r + 1 < n && path[r + 1] == b'.' && (r + 2 == n || path[r + 2] == b'/') {
return true;
}
if r + 1 == n {
return true;
}
w += 1;
r += 1;
}
_ => {
if (rooted && w != 1) || (!rooted && w != 0) {
w += 1;
}
while r < n && path[r] != b'/' {
if cfg!(target_os = "windows") && path[r] == b'\\' {
return true;
}
w += 1;
r += 1;
}
if r < n - 1 && path[r] == b'/' {
r += 1;
}
}
}
}
if w == 0 {
return true;
}
false
}
pub fn path_to_bucket_object_with_base_path(base_path: &str, path: &str) -> (String, String) {
let mut p = path;
if cfg!(target_os = "windows") {
if strings_has_prefix_fold(p, base_path) {
p = &p[base_path.len()..];
}
} else if p.starts_with(base_path) {
p = &p[base_path.len()..];
}
while let Some(c) = p.chars().next() {
if is_separator(c as u8) {
p = &p[c.len_utf8()..];
} else {
break;
}
}
let idx = if cfg!(target_os = "windows") {
p.find(['/', '\\'])
} else {
p.find('/')
};
match idx {
Some(i) => {
let bucket = &p[..i];
let object = &p[i + 1..];
let bucket = if cfg!(target_os = "windows") {
bucket.replace('\\', "/")
} else {
bucket.to_string()
};
let object = if cfg!(target_os = "windows") {
object.replace('\\', "/")
} else {
object.to_string()
};
(bucket, object)
}
None => {
let bucket = if cfg!(target_os = "windows") {
p.replace('\\', "/")
} else {
p.to_string()
};
(bucket, "".to_string())
}
}
}
pub fn path_to_bucket_object(s: &str) -> (String, String) {
path_to_bucket_object_with_base_path("", s)
}
pub fn base_dir_from_prefix(prefix: &str) -> String {
let mut base_dir = dir(prefix);
if base_dir == "." || base_dir == "./" || base_dir == "/" {
base_dir = "".to_owned();
}
let has_separator = if cfg!(target_os = "windows") {
prefix.contains(['/', '\\'])
} else {
prefix.contains('/')
};
if !has_separator {
base_dir = "".to_owned();
}
if !base_dir.is_empty() && !base_dir.ends_with(SLASH_SEPARATOR) {
base_dir.push_str(SLASH_SEPARATOR);
}
base_dir
}
pub struct LazyBuf {
s: String,
buf: Option<Vec<u8>>,
w: usize,
}
impl LazyBuf {
pub fn new(s: String) -> Self {
LazyBuf { s, buf: None, w: 0 }
}
pub fn index(&self, i: usize) -> u8 {
if let Some(ref buf) = self.buf {
buf[i]
} else {
self.s.as_bytes()[i]
}
}
pub fn append(&mut self, c: u8) {
if self.buf.is_none() {
if self.w < self.s.len() && self.s.as_bytes()[self.w] == c {
self.w += 1;
return;
}
let mut new_buf = vec![0; self.s.len()];
new_buf[..self.w].copy_from_slice(&self.s.as_bytes()[..self.w]);
self.buf = Some(new_buf);
}
if let Some(ref mut buf) = self.buf {
buf[self.w] = c;
self.w += 1;
}
}
pub fn string(&self) -> String {
if let Some(ref buf) = self.buf {
String::from_utf8(buf[..self.w].to_vec()).unwrap()
} else {
self.s[..self.w].to_string()
}
}
}
pub fn clean(path: &str) -> String {
if path.is_empty() {
return ".".to_string();
}
let rooted = path.starts_with('/') || (cfg!(target_os = "windows") && path.starts_with('\\'));
let n = path.len();
let mut out = LazyBuf::new(path.to_string());
let mut r = 0;
let mut dotdot = 0;
if rooted {
out.append(b'/');
r = 1;
dotdot = 1;
}
while r < n {
let c = path.as_bytes()[r];
if is_separator(c) {
r += 1;
} else if c == b'.' && (r + 1 == n || is_separator(path.as_bytes()[r + 1])) {
r += 1;
} else if c == b'.'
&& (r + 1 < n && path.as_bytes()[r + 1] == b'.')
&& (r + 2 == n || is_separator(path.as_bytes()[r + 2]))
{
r += 2;
if out.w > dotdot {
out.w -= 1;
while out.w > dotdot && out.index(out.w) != b'/' {
out.w -= 1;
}
} else if !rooted {
if out.w > 0 {
out.append(b'/');
}
out.append(b'.');
out.append(b'.');
dotdot = out.w;
}
} else {
if (rooted && out.w != 1) || (!rooted && out.w != 0) {
out.append(b'/');
}
while r < n {
let c = path.as_bytes()[r];
if is_separator(c) {
break;
}
out.append(c);
r += 1;
}
}
}
if out.w == 0 {
return ".".to_string();
}
out.string()
}
pub fn split(path: &str) -> (&str, &str) {
let idx = if cfg!(target_os = "windows") {
path.rfind(['/', '\\'])
} else {
path.rfind('/')
};
if let Some(i) = idx {
return (&path[..i + 1], &path[i + 1..]);
}
(path, "")
}
pub fn dir(path: &str) -> String {
let (a, _) = split(path);
clean(a)
}
pub fn trim_etag(etag: &str) -> String {
etag.trim_matches('"').to_string()
}
fn contains_parent_dir_component(path: &str) -> bool {
path.split(['/', '\\']).any(|component| component == "..")
}
pub fn validate_extract_relative_path(path: &str) -> Result<(), String> {
let p = Path::new(path);
if p.components()
.any(|c| matches!(c, Component::Prefix(_) | Component::RootDir | Component::ParentDir))
|| contains_parent_dir_component(p.to_string_lossy().as_ref())
{
return Err("archive entry path must stay within the target bucket".to_string());
}
Ok(())
}
pub fn normalize_extract_entry_key(path: &str, prefix: Option<&str>, is_dir: bool) -> Result<String, String> {
validate_extract_relative_path(path)?;
let path = path.trim_matches('/');
let mut key = match prefix {
Some(prefix) if !path.is_empty() => format!("{prefix}/{path}"),
Some(prefix) => prefix.to_string(),
None => path.to_string(),
};
if is_dir && !key.ends_with('/') {
key.push('/');
}
validate_extract_relative_path(&key)?;
Ok(key)
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
#[test]
fn encode_dir_object_ref_borrows_objects_and_encodes_directories() {
let object = "prefix/object";
let encoded = encode_dir_object_ref(object);
assert!(matches!(encoded, Cow::Borrowed(value) if value == object));
let encoded = encode_dir_object_ref("prefix/directory/");
assert!(matches!(encoded, Cow::Owned(ref value) if value == "prefix/directory__XLDIR__"));
assert_eq!(encode_dir_object("prefix/directory/"), encoded);
}
#[test]
fn test_trim_etag() {
assert_eq!(trim_etag("\"abc123\""), "abc123");
assert_eq!(trim_etag("abc123"), "abc123");
assert_eq!(trim_etag(""), "");
assert_eq!(trim_etag("\"\""), "");
assert_eq!(trim_etag("\"2c7ab85a893283e98c931e9511add182\""), "2c7ab85a893283e98c931e9511add182");
assert_eq!(trim_etag("\"098f6bcd4621d373cade4e832627b4f6-2\""), "098f6bcd4621d373cade4e832627b4f6-2");
}
#[test]
fn test_base_dir_from_prefix() {
let a = "da/";
let result = base_dir_from_prefix(a);
assert!(!result.is_empty());
}
#[test]
fn test_clean() {
assert_eq!(clean(""), ".");
assert_eq!(clean("abc"), "abc");
assert_eq!(clean("abc/def"), "abc/def");
assert_eq!(clean("a/b/c"), "a/b/c");
assert_eq!(clean("."), ".");
assert_eq!(clean(".."), "..");
assert_eq!(clean("../.."), "../..");
assert_eq!(clean("../../abc"), "../../abc");
assert_eq!(clean("/abc"), "/abc");
assert_eq!(clean("/"), "/");
assert_eq!(clean("abc/"), "abc");
assert_eq!(clean("abc/def/"), "abc/def");
assert_eq!(clean("a/b/c/"), "a/b/c");
assert_eq!(clean("./"), ".");
assert_eq!(clean("../"), "..");
assert_eq!(clean("../../"), "../..");
assert_eq!(clean("/abc/"), "/abc");
assert_eq!(clean("abc//def//ghi"), "abc/def/ghi");
assert_eq!(clean("//abc"), "/abc");
assert_eq!(clean("///abc"), "/abc");
assert_eq!(clean("//abc//"), "/abc");
assert_eq!(clean("abc//"), "abc");
assert_eq!(clean("abc/./def"), "abc/def");
assert_eq!(clean("/./abc/def"), "/abc/def");
assert_eq!(clean("abc/."), "abc");
assert_eq!(clean("abc/./../def"), "def");
assert_eq!(clean("abc//./../def"), "def");
assert_eq!(clean("abc/../../././../def"), "../../def");
assert_eq!(clean("abc/def/ghi/../jkl"), "abc/def/jkl");
assert_eq!(clean("abc/def/../ghi/../jkl"), "abc/jkl");
assert_eq!(clean("abc/def/.."), "abc");
assert_eq!(clean("abc/def/../.."), ".");
assert_eq!(clean("/abc/def/../.."), "/");
assert_eq!(clean("abc/def/../../.."), "..");
assert_eq!(clean("/abc/def/../../.."), "/");
assert_eq!(clean("abc/def/../../../ghi/jkl/../../../mno"), "../../mno");
}
#[test]
fn test_path_needs_clean() {
struct PathTest {
path: &'static str,
result: &'static str,
}
let cleantests = vec![
PathTest { path: "", result: "." },
PathTest {
path: "abc",
result: "abc",
},
PathTest {
path: "abc/def",
result: "abc/def",
},
PathTest {
path: "a/b/c",
result: "a/b/c",
},
PathTest { path: ".", result: "." },
PathTest {
path: "..",
result: "..",
},
PathTest {
path: "../..",
result: "../..",
},
PathTest {
path: "../../abc",
result: "../../abc",
},
PathTest {
path: "/abc",
result: "/abc",
},
PathTest {
path: "/abc/def",
result: "/abc/def",
},
PathTest { path: "/", result: "/" },
PathTest {
path: "abc/",
result: "abc",
},
PathTest {
path: "abc/def/",
result: "abc/def",
},
PathTest {
path: "a/b/c/",
result: "a/b/c",
},
PathTest { path: "./", result: "." },
PathTest {
path: "../",
result: "..",
},
PathTest {
path: "../../",
result: "../..",
},
PathTest {
path: "/abc/",
result: "/abc",
},
PathTest {
path: "abc//def//ghi",
result: "abc/def/ghi",
},
PathTest {
path: "//abc",
result: "/abc",
},
PathTest {
path: "///abc",
result: "/abc",
},
PathTest {
path: "//abc//",
result: "/abc",
},
PathTest {
path: "abc//",
result: "abc",
},
PathTest {
path: "abc/./def",
result: "abc/def",
},
PathTest {
path: "/./abc/def",
result: "/abc/def",
},
PathTest {
path: "abc/.",
result: "abc",
},
PathTest {
path: "abc/def/ghi/../jkl",
result: "abc/def/jkl",
},
PathTest {
path: "abc/def/../ghi/../jkl",
result: "abc/jkl",
},
PathTest {
path: "abc/def/..",
result: "abc",
},
PathTest {
path: "abc/def/../..",
result: ".",
},
PathTest {
path: "/abc/def/../..",
result: "/",
},
PathTest {
path: "abc/def/../../..",
result: "..",
},
PathTest {
path: "/abc/def/../../..",
result: "/",
},
PathTest {
path: "abc/def/../../../ghi/jkl/../../../mno",
result: "../../mno",
},
PathTest {
path: "abc/./../def",
result: "def",
},
PathTest {
path: "abc//./../def",
result: "def",
},
PathTest {
path: "abc/../../././../def",
result: "../../def",
},
];
for test in cleantests {
let want = test.path != test.result;
let got = path_needs_clean(test.path.as_bytes());
if want && !got {
panic!("input: {:?}, want {}, got {}", test.path, want, got);
}
assert_eq!(clean(test.path), test.result);
}
}
#[test]
fn test_path_join() {
let result = path_join::<&str>(&[]);
assert_eq!(result, PathBuf::from("."));
let result = path_join(&[PathBuf::from("abc")]);
assert_eq!(result, PathBuf::from("abc"));
let result = path_join(&[PathBuf::from("/abc")]);
assert_eq!(result, PathBuf::from("/abc"));
let result = path_join(&[PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")]);
assert_eq!(result, PathBuf::from("a/b/c"));
let result = path_join(&[PathBuf::from("/a"), PathBuf::from("b"), PathBuf::from("c")]);
assert_eq!(result, PathBuf::from("/a/b/c"));
let result = path_join(&[PathBuf::from("a"), PathBuf::from("."), PathBuf::from("b")]);
assert_eq!(result, PathBuf::from("a/b"));
let result = path_join(&[
PathBuf::from("a"),
PathBuf::from("b"),
PathBuf::from(".."),
PathBuf::from("c"),
]);
assert_eq!(result, PathBuf::from("a/c"));
let result = path_join(&[PathBuf::from("a//b"), PathBuf::from("c")]);
assert_eq!(result, PathBuf::from("a/b/c"));
let result = path_join(&[PathBuf::from("a"), PathBuf::from("b/")]);
assert_eq!(result, PathBuf::from("a/b/"));
let result = path_join(&[PathBuf::from("a"), PathBuf::from(""), PathBuf::from("b")]);
assert_eq!(result, PathBuf::from("a/b"));
let result = path_join(&[PathBuf::from("/a"), PathBuf::from("/b"), PathBuf::from("c")]);
assert_eq!(result, PathBuf::from("/a/b/c"));
let result = path_join(&[
PathBuf::from("a"),
PathBuf::from(".."),
PathBuf::from("b"),
PathBuf::from("."),
PathBuf::from("c"),
]);
assert_eq!(result, PathBuf::from("b/c"));
}
#[test]
#[cfg(target_os = "windows")]
fn test_windows_paths() {
assert_eq!(clean("a\\b\\c"), "a/b/c");
assert_eq!(clean("a\\b/c"), "a/b/c");
assert_eq!(clean("a\\.\\b"), "a/b");
assert_eq!(clean("a\\b\\..\\c"), "a/c");
assert_eq!(clean("\\a\\b"), "/a/b");
assert_eq!(clean("a\\\\b"), "a/b");
let result = path_join(&[PathBuf::from("a"), PathBuf::from("b\\c")]);
assert_eq!(result, PathBuf::from("a/b/c"));
let result = path_join(&[PathBuf::from("a"), PathBuf::from("b\\")]);
assert_eq!(result, PathBuf::from("a/b/"));
assert!(path_needs_clean(b"a\\b"));
let (bucket, object) = path_to_bucket_object_with_base_path("C:\\tmp", "C:\\tmp\\bucket\\object");
assert_eq!(bucket, "bucket");
assert_eq!(object, "object");
let (bucket, object) = path_to_bucket_object_with_base_path("c:\\tmp", "C:\\tmp\\bucket\\object");
assert_eq!(bucket, "bucket");
assert_eq!(object, "object");
}
#[test]
#[cfg(target_os = "windows")]
fn test_path_to_bucket_object_with_base_path_handles_unicode_without_panicking() {
let (bucket, object) = path_to_bucket_object_with_base_path(
"D:\\Github\\rustfs\\target\\volumes\\test1",
"s3-test-bucket/中文/日本語/한글-9cd5599a-f8eb-4e24-9df7-32ecd8d8ad1f",
);
assert_eq!(bucket, "s3-test-bucket");
assert_eq!(object, "中文/日本語/한글-9cd5599a-f8eb-4e24-9df7-32ecd8d8ad1f");
}
proptest! {
#[test]
fn clean_is_idempotent(input in any::<String>()) {
let once = clean(&input);
let twice = clean(&once);
prop_assert_eq!(twice, once);
}
#[test]
fn clean_output_has_no_redundant_current_dir_or_empty_segments(input in any::<String>()) {
let cleaned = clean(&input);
prop_assert!(!cleaned.contains("//"), "clean output should not contain doubled separators");
prop_assert!(!cleaned.contains("/./"), "clean output should not contain embedded current-dir segments");
prop_assert!(!cleaned.ends_with("/."), "clean output should not end with a current-dir segment");
if cleaned != "/" {
prop_assert!(
!cleaned.ends_with('/') || cleaned.is_empty(),
"clean output should not preserve a trailing slash"
);
}
}
}
#[test]
fn test_validate_extract_relative_path_accepts_safe_paths() {
assert!(validate_extract_relative_path("file.txt").is_ok());
assert!(validate_extract_relative_path("dir/file.txt").is_ok());
assert!(validate_extract_relative_path("a/b/c").is_ok());
assert!(validate_extract_relative_path("").is_ok());
}
#[test]
fn test_validate_extract_relative_path_rejects_traversal() {
assert!(validate_extract_relative_path("../escape.txt").is_err());
assert!(validate_extract_relative_path("dir/../../../escape.txt").is_err());
assert!(validate_extract_relative_path("/absolute/path").is_err());
assert!(validate_extract_relative_path("dir/..").is_err());
assert!(validate_extract_relative_path("..").is_err());
}
#[test]
fn test_normalize_extract_entry_key_basic() {
assert_eq!(normalize_extract_entry_key("file.txt", None, false).unwrap(), "file.txt");
assert_eq!(normalize_extract_entry_key("file.txt", Some("prefix"), false).unwrap(), "prefix/file.txt");
assert_eq!(normalize_extract_entry_key("dir", None, true).unwrap(), "dir/");
assert_eq!(normalize_extract_entry_key("", Some("prefix"), false).unwrap(), "prefix");
}
#[test]
fn test_normalize_extract_entry_key_rejects_traversal() {
assert!(normalize_extract_entry_key("../escape.txt", None, false).is_err());
assert!(normalize_extract_entry_key("file.txt", Some("../bad"), false).is_err());
assert!(normalize_extract_entry_key("/absolute", None, false).is_err());
}
}