#[cfg(any(windows, test))]
use std::ffi::OsStr;
#[cfg(windows)]
use std::path::{Component, Prefix};
use std::{
fs, io,
path::{Path, PathBuf},
};
#[inline]
#[must_use]
pub fn simplified(path: &Path) -> &Path {
try_simplified(path).unwrap_or(path)
}
#[inline(always)]
pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
let path = path.as_ref();
#[cfg(not(windows))]
{
fs::canonicalize(path)
}
#[cfg(windows)]
{
canonicalize_win(path)
}
}
#[cfg(windows)]
fn canonicalize_win(path: &Path) -> io::Result<PathBuf> {
let real_path = fs::canonicalize(path)?;
Ok(try_simplified(&real_path).map(PathBuf::from).unwrap_or(real_path))
}
#[cfg_attr(not(windows), allow(unused))]
#[must_use]
pub fn is_simplified(path: &Path) -> bool {
#[cfg(windows)]
if let Some(Component::Prefix(prefix)) = path.components().next() {
return matches!(prefix.kind(), Prefix::Disk(..));
}
true
}
#[doc(hidden)]
pub use self::canonicalize as realpath;
#[cfg(any(windows, test))]
fn is_valid_filename(file_name: &OsStr) -> bool {
let s = match file_name.to_str() {
Some(s) => s,
None => return false,
};
if s.len() > 255 && s.encode_utf16().count() > 255 {
return false;
}
if s.is_empty() {
return false;
}
let byte_str = s.as_bytes();
if byte_str
.iter()
.any(|&c| matches!(c, 0..=31 | b'<' | b'>' | b':' | b'"' | b'/' | b'\\' | b'|' | b'?' | b'*'))
{
return false;
}
if matches!(byte_str.last(), Some(b' ' | b'.')) {
return false;
}
true
}
#[cfg(any(windows, test))]
fn is_reserved<P: AsRef<OsStr>>(file_name: P) -> bool {
let s = match file_name.as_ref().to_str() {
Some(s) => s,
None => return false, };
if s.is_empty() {
return false;
}
let stem = match s.find('.') {
Some(idx) => &s[..idx],
None => s,
};
let stem = stem.trim_end();
if stem.len() != 3 && stem.len() != 4 {
return false;
}
if stem.len() == 3 {
return stem.eq_ignore_ascii_case("CON")
|| stem.eq_ignore_ascii_case("PRN")
|| stem.eq_ignore_ascii_case("AUX")
|| stem.eq_ignore_ascii_case("NUL");
}
let (base, suffix) = stem.split_at(3);
if base.eq_ignore_ascii_case("COM") || base.eq_ignore_ascii_case("LPT") {
return suffix.chars().next().map(|c| c.is_ascii_digit() && c != '0').unwrap_or(false);
}
false
}
#[cfg(not(windows))]
#[inline]
const fn try_simplified(_path: &Path) -> Option<&Path> {
None
}
#[cfg(windows)]
fn try_simplified(path: &Path) -> Option<&Path> {
let mut components = path.components();
match components.next() {
Some(Component::Prefix(p)) => match p.kind() {
Prefix::VerbatimDisk(..) => {}
_ => return None, },
_ => return None, }
for component in components {
match component {
Component::RootDir => {}
Component::Normal(file_name) => {
if !is_valid_filename(file_name) || is_reserved(file_name) {
return None;
}
}
_ => return None, };
}
let s = path.to_str()?;
let simplified = &s[4..];
if simplified.len() > 260 && simplified.encode_utf16().count() > 260 {
return None;
}
Some(Path::new(simplified))
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;
use std::path::Path;
#[test]
fn test_reserved_names() {
let reserved = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
"con",
"Con",
"CON.txt",
"con.txt",
"CON .txt",
"con .txt",
"CON.tar.gz",
"con.",
"con .",
];
for name in reserved {
assert!(is_reserved(name), "Should be reserved: {}", name);
}
let not_reserved = [
"CON0", "COM0", "LPT0", "COM10", "LPT10", "CONsole", "PrNter", "NuLly", "not_con", "con_not", ".CON", "@CON",
"CONγ", "foo.con",
];
for name in not_reserved {
assert!(!is_reserved(name), "Should NOT be reserved: {}", name);
}
}
#[test]
fn test_valid_filename() {
let invalid = [
"",
".",
"..",
" ",
" .",
"foo ",
"foo.",
"foo/bar",
"foo\\bar",
"foo:bar",
"foo*bar",
"foo?bar",
"foo\"bar",
"foo<bar",
"foo>bar",
"foo|bar",
"foo\0bar",
"foo\x1fbar",
];
for name in invalid {
assert!(!is_valid_filename(OsStr::new(name)), "Should be invalid: {:?}", name);
}
let valid = [
"foo",
"foo.bar",
".foo",
"foo.bar.baz",
"foo bar",
"foo. bar", "δΈζ",
"π",
];
for name in valid {
assert!(is_valid_filename(OsStr::new(name)), "Should be valid: {:?}", name);
}
let long_name = "a".repeat(256);
assert!(!is_valid_filename(OsStr::new(&long_name)));
let ok_name = "a".repeat(255);
assert!(is_valid_filename(OsStr::new(&ok_name)));
}
#[test]
#[cfg(windows)]
fn test_simplified_windows() {
assert_eq!(simplified(Path::new(r"\\?\C:\Windows")), Path::new(r"C:\Windows"));
assert_eq!(simplified(Path::new(r"\\?\C:\CON")), Path::new(r"\\?\C:\CON"));
assert_eq!(simplified(Path::new(r"\\?\C:\aux.txt")), Path::new(r"\\?\C:\aux.txt"));
let long_path = format!(r"\\?\C:\{}", "a".repeat(300));
assert_eq!(simplified(Path::new(&long_path)), Path::new(&long_path));
let ok_path = format!(r"\\?\C:\{}", "a".repeat(200));
assert_eq!(simplified(Path::new(&ok_path)), Path::new(&ok_path[4..]));
assert_eq!(simplified(Path::new(r"C:\Windows")), Path::new(r"C:\Windows"));
assert_eq!(simplified(Path::new(r"\\server\share")), Path::new(r"\\server\share"));
assert_eq!(simplified(Path::new(r"\\.\C:\Windows")), Path::new(r"\\.\C:\Windows"));
}
#[test]
#[cfg(not(windows))]
fn test_simplified_unix() {
let p = Path::new("/tmp/foo");
assert_eq!(simplified(p), p);
}
#[test]
fn test_is_simplified() {
#[cfg(windows)]
{
assert!(is_simplified(Path::new(r"C:\Windows")));
assert!(is_simplified(Path::new(r"relative\path")));
assert!(!is_simplified(Path::new(r"\\?\C:\Windows")));
assert!(!is_simplified(Path::new(r"\\server\share")));
}
#[cfg(not(windows))]
{
assert!(is_simplified(Path::new("/tmp/foo")));
assert!(is_simplified(Path::new("relative/path")));
}
}
}