Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
367
akode-rs/exec-server/src/no_follow/mod.rs
Normal file
367
akode-rs/exec-server/src/no_follow/mod.rs
Normal file
@@ -0,0 +1,367 @@
|
||||
use crate::FileMetadata;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
#[cfg(windows)]
|
||||
use std::time::SystemTime;
|
||||
#[cfg(windows)]
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
#[cfg(unix)]
|
||||
use unix as imp;
|
||||
#[cfg(windows)]
|
||||
use windows as imp;
|
||||
|
||||
fn invalid_output(reason: &'static str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, reason)
|
||||
}
|
||||
|
||||
/// A destination bound before sandboxed tools run. Only ordinary path-based files are truncated.
|
||||
pub struct BoundOutput {
|
||||
file: std::fs::File,
|
||||
destination: Destination,
|
||||
}
|
||||
|
||||
enum Destination {
|
||||
Path(std::path::PathBuf),
|
||||
Stream { is_stdout: bool },
|
||||
}
|
||||
|
||||
impl BoundOutput {
|
||||
pub fn open(path: &Path) -> io::Result<Self> {
|
||||
// Check raw syntax before absolute() or components() discards directory markers.
|
||||
let bytes = path.as_os_str().as_encoded_bytes();
|
||||
let leaf = bytes
|
||||
.rsplit(|b| *b == b'/' || (cfg!(windows) && *b == b'\\'))
|
||||
.next();
|
||||
if matches!(leaf, None | Some(b"" | b"." | b"..")) {
|
||||
return Err(invalid_output("output must name a file"));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if bytes.eq_ignore_ascii_case(b"NUL") || bytes.eq_ignore_ascii_case(br"\\.\NUL") {
|
||||
return Ok(Self {
|
||||
file: windows::open_null_output()?,
|
||||
destination: Destination::Stream { is_stdout: false },
|
||||
});
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if let Some(output) = unix::inherited_output(path)? {
|
||||
return Ok(output);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let path = unix::output_path(path)?;
|
||||
#[cfg(windows)]
|
||||
let path = std::path::absolute(path)?;
|
||||
let file = imp::open_output(&path)?;
|
||||
if file.metadata()?.is_file() {
|
||||
imp::reject_multiple_links(&file)?;
|
||||
}
|
||||
Ok(Self {
|
||||
file,
|
||||
destination: Destination::Path(path),
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the caller explicitly selected the inherited standard output stream.
|
||||
pub fn is_stdout(&self) -> bool {
|
||||
matches!(self.destination, Destination::Stream { is_stdout: true })
|
||||
}
|
||||
|
||||
pub fn write(mut self, contents: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
if let Destination::Path(path) = &self.destination {
|
||||
imp::verify_output_path(&self.file, path)?;
|
||||
if self.file.metadata()?.is_file() {
|
||||
imp::reject_multiple_links(&self.file)?;
|
||||
self.file.set_len(0)?;
|
||||
}
|
||||
}
|
||||
self.file.write_all(contents)?;
|
||||
// A caller may reopen the pathname after a successful exit. Detect a visible swap.
|
||||
if let Destination::Path(path) = &self.destination {
|
||||
imp::verify_output_path(&self.file, path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_file(path: &Path) -> io::Result<std::fs::File> {
|
||||
imp::open_file_sync(path)
|
||||
}
|
||||
|
||||
pub(crate) async fn write_file(path: &Path, contents: Vec<u8>) -> io::Result<()> {
|
||||
imp::write_file(path.to_path_buf(), contents).await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
|
||||
imp::metadata(path.to_path_buf()).await
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
|
||||
imp::metadata(path.to_path_buf())
|
||||
.await
|
||||
.map(|metadata| FileMetadata {
|
||||
is_directory: metadata.is_dir(),
|
||||
is_file: metadata.is_file(),
|
||||
is_symlink: false,
|
||||
size: metadata.len(),
|
||||
created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
|
||||
modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn system_time_to_unix_ms(time: SystemTime) -> i64 {
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
.ok()
|
||||
.and_then(|duration| i64::try_from(duration.as_millis()).ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) async fn create_directory(path: &Path, recursive: bool) -> io::Result<()> {
|
||||
imp::create_directory(path.to_path_buf(), recursive).await
|
||||
}
|
||||
|
||||
pub(crate) async fn remove(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
|
||||
imp::remove(path.to_path_buf(), recursive, force).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod output_tests {
|
||||
//! Exercise the destination as a caller of the final-message writer.
|
||||
use super::BoundOutput;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn regular_output_is_truncated_only_when_written() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("message");
|
||||
fs::write(&path, "old message")?;
|
||||
let output = BoundOutput::open(&path)?;
|
||||
assert_eq!(fs::read_to_string(&path)?, "old message");
|
||||
output.write(b"new")?;
|
||||
assert_eq!(fs::read_to_string(&path)?, "new");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rejects_added_links_and_replaced_paths_before_writing() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("message");
|
||||
fs::write(&path, "new")?;
|
||||
let output = BoundOutput::open(&path)?;
|
||||
let alias = dir.path().join("alias");
|
||||
fs::hard_link(&path, &alias)?;
|
||||
assert!(BoundOutput::open(&alias).is_err());
|
||||
assert!(output.write(b"overwritten").is_err());
|
||||
assert_eq!(fs::read(&alias)?, b"new");
|
||||
fs::remove_file(&alias)?;
|
||||
let output = BoundOutput::open(&path)?;
|
||||
fs::rename(&path, &alias)?;
|
||||
fs::write(&path, "replacement")?;
|
||||
assert!(output.write(b"overwritten").is_err());
|
||||
assert_eq!(fs::read(&path)?, b"replacement");
|
||||
assert_eq!(fs::read(&alias)?, b"new");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_output_binds_the_chosen_stream_until_write() -> std::io::Result<()> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION;
|
||||
use windows_sys::Win32::Storage::FileSystem::DELETE;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let base = dir.path().join("message");
|
||||
fs::write(&base, "base")?;
|
||||
let fs_name = super::windows::filesystem_name(&fs::File::open(&base)?)?;
|
||||
let ntfs = fs_name.eq_ignore_ascii_case("NTFS");
|
||||
let sibling = dir.path().join("message:sibling");
|
||||
if ntfs {
|
||||
fs::write(&sibling, "keep")?;
|
||||
let alias = dir.path().join("alias");
|
||||
fs::hard_link(&base, &alias)?;
|
||||
assert!(BoundOutput::open(&base).is_err());
|
||||
fs::remove_file(alias)?;
|
||||
}
|
||||
let names: &[&str] = if ntfs {
|
||||
&[
|
||||
"message",
|
||||
"message::$DATA",
|
||||
"message:answer",
|
||||
"message:answer:$DATA",
|
||||
]
|
||||
} else {
|
||||
&["message"]
|
||||
};
|
||||
for name in names {
|
||||
let path = dir.path().join(name);
|
||||
fs::write(&base, "base")?;
|
||||
fs::write(&path, "previous contents")?;
|
||||
let open_for_rename = || fs::OpenOptions::new().access_mode(DELETE).open(&path);
|
||||
let rename_handle = open_for_rename()?;
|
||||
assert!(
|
||||
matches!(BoundOutput::open(&path), Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32))
|
||||
);
|
||||
drop(rename_handle);
|
||||
|
||||
let output = BoundOutput::open(&path)?;
|
||||
assert!(
|
||||
matches!(open_for_rename(), Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32))
|
||||
);
|
||||
output.write(b"done")?;
|
||||
assert_eq!(fs::read(&path)?, b"done");
|
||||
drop(open_for_rename()?);
|
||||
if name.starts_with("message:answer") {
|
||||
assert_eq!(fs::read(&base)?, b"base");
|
||||
}
|
||||
if ntfs {
|
||||
assert_eq!(fs::read(&sibling)?, b"keep");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn nul_discards_output_without_accepting_other_devices() -> std::io::Result<()> {
|
||||
for name in ["NUL", "nul", r"\\.\NUL"] {
|
||||
BoundOutput::open(name.as_ref())?.write(b"discarded")?;
|
||||
}
|
||||
assert!(BoundOutput::open(r"\\.\CON".as_ref()).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn unavailable_full_ids_use_directory_entries_only_on_fat_volumes() -> std::io::Result<()> {
|
||||
use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("message");
|
||||
let output = BoundOutput::open(&path)?;
|
||||
let other = dir.path().join("other");
|
||||
fs::write(&other, "other")?;
|
||||
// Legacy IDs on a ReFS temp volume are not a valid stand-in for FAT directory entries.
|
||||
let host = super::windows::filesystem_name(&output.file)?;
|
||||
let legacy_fixture = ["NTFS", "FAT", "FAT32", "exFAT"]
|
||||
.iter()
|
||||
.any(|name| host.eq_ignore_ascii_case(name));
|
||||
let verify = |candidate: &std::path::Path, volume: &str, named: Option<&str>| {
|
||||
super::windows::verify_output_path_with(
|
||||
&output.file,
|
||||
candidate,
|
||||
|_| {
|
||||
Err(std::io::Error::from_raw_os_error(
|
||||
ERROR_INVALID_PARAMETER as i32,
|
||||
))
|
||||
},
|
||||
|file| {
|
||||
if std::ptr::eq(file, &output.file) {
|
||||
return Ok(volume.to_owned());
|
||||
}
|
||||
named
|
||||
.map(str::to_owned)
|
||||
.ok_or(std::io::ErrorKind::Unsupported.into())
|
||||
},
|
||||
)
|
||||
};
|
||||
for volume in ["FAT", "FAT32", "exFAT"] {
|
||||
// Reaching the second volume query proves the first one selected the fallback.
|
||||
assert!(
|
||||
matches!(verify(&path, volume, None), Err(e) if e.kind() == std::io::ErrorKind::Unsupported)
|
||||
);
|
||||
if legacy_fixture {
|
||||
verify(&path, volume, Some(volume))?;
|
||||
assert!(verify(&other, volume, Some(volume)).is_err());
|
||||
}
|
||||
}
|
||||
for (bound, named) in [("ReFS", "exFAT"), ("exFAT", "ReFS")] {
|
||||
assert!(
|
||||
matches!(verify(&path, bound, Some(named)), Err(e) if e.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32))
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
#[ignore = "requires AKODE_TEST_EXFAT_DIR on a writable exFAT volume"]
|
||||
fn writes_on_exfat() -> anyhow::Result<()> {
|
||||
let dir = tempfile::tempdir_in(std::env::var("AKODE_TEST_EXFAT_DIR")?)?;
|
||||
let path = dir.path().join("message");
|
||||
fs::write(&path, "previous message")?;
|
||||
assert!(
|
||||
super::windows::filesystem_name(&fs::File::open(&path)?)?.eq_ignore_ascii_case("exFAT")
|
||||
);
|
||||
BoundOutput::open(&path)?.write(b"done")?;
|
||||
assert_eq!(fs::read(&path)?, b"done");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn output_only_accepts_leading_parent_components() -> std::io::Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
fs::create_dir_all(dir.path().join("a/b"))?;
|
||||
let path = dir.path().join("a/b/../../message");
|
||||
assert!(
|
||||
matches!(BoundOutput::open(&path), Err(e) if e.kind() == std::io::ErrorKind::InvalidInput)
|
||||
);
|
||||
assert!(!dir.path().join("message").exists());
|
||||
let mut expected = std::env::current_dir()?;
|
||||
expected.pop();
|
||||
assert_eq!(
|
||||
super::unix::output_path("./../message".as_ref())?,
|
||||
expected.join("message")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writes_fifo_device_and_inherited_pipe() -> anyhow::Result<()> {
|
||||
use std::io::Read;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let fifo = dir.path().join("pipe");
|
||||
assert!(
|
||||
std::process::Command::new("mkfifo")
|
||||
.arg(&fifo)
|
||||
.status()?
|
||||
.success()
|
||||
);
|
||||
let mut reader = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NONBLOCK)
|
||||
.open(&fifo)?;
|
||||
BoundOutput::open(&fifo)?.write(b"fifo")?;
|
||||
let mut buf = [0; 4];
|
||||
reader.read_exact(&mut buf)?;
|
||||
assert_eq!(buf, *b"fifo");
|
||||
BoundOutput::open(std::path::Path::new("/dev/null"))?.write(b"device")?;
|
||||
let stdout = BoundOutput::open(std::path::Path::new("/dev/stdout"))?;
|
||||
assert!(stdout.is_stdout());
|
||||
let read_only = rustix::io::dup(&reader)?;
|
||||
let alias = format!("/dev/fd/{}", read_only.as_raw_fd());
|
||||
assert!(
|
||||
matches!(BoundOutput::open(alias.as_ref()), Err(e) if e.kind() == std::io::ErrorKind::InvalidInput)
|
||||
);
|
||||
let writer = fs::OpenOptions::new().write(true).open(&fifo)?;
|
||||
// Match the inheritable pipe descriptor passed by shell process substitution.
|
||||
let inherited = rustix::io::dup(&writer)?;
|
||||
let alias = format!("/dev/fd/{}", inherited.as_raw_fd());
|
||||
BoundOutput::open(alias.as_ref())?.write(b"pipe")?;
|
||||
reader.read_exact(&mut buf)?;
|
||||
assert_eq!(buf, *b"pipe");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
432
akode-rs/exec-server/src/no_follow/unix.rs
Normal file
432
akode-rs/exec-server/src/no_follow/unix.rs
Normal file
@@ -0,0 +1,432 @@
|
||||
use crate::FileMetadata;
|
||||
use rustix::fs::AtFlags;
|
||||
use rustix::fs::Mode;
|
||||
use rustix::fs::OFlags;
|
||||
use rustix::fs::Stat;
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustix::fs::Statx;
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustix::fs::StatxFlags;
|
||||
use rustix::fs::fstat;
|
||||
use rustix::fs::mkdirat;
|
||||
use rustix::fs::open;
|
||||
use rustix::fs::openat;
|
||||
use rustix::fs::statat;
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustix::fs::statx;
|
||||
use rustix::fs::unlinkat;
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::PATH
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::from_bits_retain(libc::O_SEARCH as u32)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::RDONLY
|
||||
}
|
||||
|
||||
fn components(path: &Path) -> io::Result<Vec<OsString>> {
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute path",
|
||||
));
|
||||
}
|
||||
path.components()
|
||||
.filter_map(|component| match component {
|
||||
Component::RootDir => None,
|
||||
Component::Normal(component) => Some(Ok(component.to_os_string())),
|
||||
Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
|
||||
Some(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require a normalized path",
|
||||
)))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn root() -> io::Result<OwnedFd> {
|
||||
open(
|
||||
"/",
|
||||
directory_access_flags() | OFlags::DIRECTORY | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)
|
||||
}
|
||||
|
||||
fn open_directory(parent: &OwnedFd, name: &std::ffi::OsStr) -> io::Result<OwnedFd> {
|
||||
openat(
|
||||
parent,
|
||||
name,
|
||||
directory_access_flags() | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)
|
||||
}
|
||||
|
||||
fn parent(path: &Path) -> io::Result<(OwnedFd, OsString)> {
|
||||
let mut components = components(path)?;
|
||||
let leaf = components
|
||||
.pop()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path must name an entry"))?;
|
||||
let mut directory = root()?;
|
||||
for component in components {
|
||||
directory = open_directory(&directory, &component)?;
|
||||
}
|
||||
Ok((directory, leaf))
|
||||
}
|
||||
|
||||
pub(super) fn inherited_output(path: &Path) -> io::Result<Option<super::BoundOutput>> {
|
||||
use std::os::fd::FromRawFd;
|
||||
let name = path.to_str().unwrap_or_default();
|
||||
let fd = match name {
|
||||
"/dev/stdout" => libc::STDOUT_FILENO,
|
||||
"/dev/stderr" => libc::STDERR_FILENO,
|
||||
_ => {
|
||||
let number = name
|
||||
.strip_prefix("/dev/fd/")
|
||||
.or_else(|| name.strip_prefix("/proc/self/fd/"));
|
||||
let Some(fd) = number
|
||||
.filter(|s| s.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|s| s.parse().ok())
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
fd
|
||||
}
|
||||
};
|
||||
// Only caller-supplied descriptors may be selected, including shell process substitution.
|
||||
// SAFETY: fcntl validates the integer descriptor; F_DUPFD_CLOEXEC returns a new owned fd.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
|
||||
if flags < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if flags & libc::FD_CLOEXEC != 0 {
|
||||
return Err(super::invalid_output("output descriptor is not inherited"));
|
||||
}
|
||||
let copy = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
|
||||
if copy < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let file = unsafe { std::fs::File::from_raw_fd(copy) };
|
||||
let access = rustix::fs::fcntl_getfl(&file)? & OFlags::ACCMODE;
|
||||
if !matches!(access, OFlags::WRONLY | OFlags::RDWR) {
|
||||
return Err(super::invalid_output("output descriptor is not writable"));
|
||||
}
|
||||
Ok(Some(super::BoundOutput {
|
||||
file,
|
||||
destination: super::Destination::Stream {
|
||||
is_stdout: fd == libc::STDOUT_FILENO,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn reject_multiple_links(file: &std::fs::File) -> io::Result<()> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if file.metadata()?.nlink() > 1 {
|
||||
return Err(super::invalid_output("output has multiple hard links"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn output_path(path: &Path) -> io::Result<PathBuf> {
|
||||
// Resolve leading ".." against the caller's cwd, never against a movable directory fd.
|
||||
let mut suffix = path.strip_prefix(".").unwrap_or(path);
|
||||
let mut base = if suffix.is_absolute() {
|
||||
PathBuf::new()
|
||||
} else {
|
||||
std::env::current_dir()?
|
||||
};
|
||||
while let Ok(rest) = suffix.strip_prefix("..") {
|
||||
base.pop();
|
||||
suffix = rest;
|
||||
}
|
||||
let path = base.join(suffix);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
// Expand one known root link only. Never canonicalize its target or the caller's suffix.
|
||||
if let Some(physical) = ["tmp", "var", "etc"].into_iter().find_map(|name| {
|
||||
let root = Path::new("/").join(name);
|
||||
let suffix = path.strip_prefix(&root).ok()?;
|
||||
let expected = Path::new("private").join(name);
|
||||
(std::fs::read_link(root).ok()? == expected)
|
||||
.then(|| Path::new("/").join(expected).join(suffix))
|
||||
}) {
|
||||
return Ok(physical);
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
pub(super) fn verify_output_path(file: &std::fs::File, path: &Path) -> io::Result<()> {
|
||||
let (dir, leaf) = parent(path)?;
|
||||
let named = statat(dir, leaf, AtFlags::SYMLINK_NOFOLLOW)?;
|
||||
let bound = fstat(file)?;
|
||||
if (named.st_dev, named.st_ino) != (bound.st_dev, bound.st_ino) {
|
||||
return Err(super::invalid_output("output path was replaced"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn open_output(path: &Path) -> io::Result<std::fs::File> {
|
||||
let (directory, leaf) = parent(path)?;
|
||||
let file = open_writable(&directory, &leaf)?;
|
||||
if !file.metadata()?.is_file() {
|
||||
let flags = rustix::fs::fcntl_getfl(&file)?;
|
||||
rustix::fs::fcntl_setfl(&file, flags & !OFlags::NONBLOCK)?;
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
// Opening the leaf must not truncate it or hang on a FIFO without a reader.
|
||||
fn open_writable(directory: &OwnedFd, leaf: &std::ffi::OsStr) -> io::Result<std::fs::File> {
|
||||
let file = openat(
|
||||
directory,
|
||||
leaf,
|
||||
OFlags::WRONLY
|
||||
| OFlags::CREATE
|
||||
| OFlags::NOFOLLOW
|
||||
| OFlags::CLOEXEC
|
||||
| OFlags::NOCTTY
|
||||
| OFlags::NONBLOCK,
|
||||
Mode::from_raw_mode(0o666),
|
||||
)?;
|
||||
Ok(std::fs::File::from(file))
|
||||
}
|
||||
|
||||
fn open_entry_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let (parent, leaf) = parent(path)?;
|
||||
let file = openat(
|
||||
&parent,
|
||||
leaf,
|
||||
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
Ok(std::fs::File::from(file))
|
||||
}
|
||||
|
||||
pub(super) fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let file = open_entry_sync(path)?;
|
||||
if !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path is not a regular file",
|
||||
));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (directory, leaf) = parent(&path)?;
|
||||
let mut file = open_writable(&directory, &leaf)?;
|
||||
if !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path is not a regular file",
|
||||
));
|
||||
}
|
||||
file.set_len(0)?;
|
||||
file.write_all(&contents)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn metadata_sync(path: &Path) -> io::Result<FileMetadata> {
|
||||
let components = components(path)?;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let (parent, leaf, flags) = if components.is_empty() {
|
||||
(root()?, OsString::new(), AtFlags::EMPTY_PATH)
|
||||
} else {
|
||||
let (parent, leaf) = parent(path)?;
|
||||
(parent, leaf, AtFlags::SYMLINK_NOFOLLOW)
|
||||
};
|
||||
let metadata = statx(
|
||||
&parent,
|
||||
&leaf,
|
||||
flags,
|
||||
StatxFlags::BASIC_STATS | StatxFlags::BTIME,
|
||||
);
|
||||
match metadata {
|
||||
Ok(metadata) => file_metadata_linux(metadata),
|
||||
Err(error) if error == rustix::io::Errno::NOSYS || error == rustix::io::Errno::PERM => {
|
||||
let metadata = if components.is_empty() {
|
||||
fstat(&parent)
|
||||
} else {
|
||||
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW)
|
||||
}
|
||||
.map_err(io::Error::from)?;
|
||||
file_metadata(metadata, /*created_at_ms*/ 0)
|
||||
}
|
||||
Err(error) => Err(io::Error::from(error)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
if components.is_empty() {
|
||||
let root = root()?;
|
||||
let metadata = fstat(&root).map_err(io::Error::from)?;
|
||||
let created_at_ms = created_at_ms(&metadata);
|
||||
file_metadata(metadata, created_at_ms)
|
||||
} else {
|
||||
let (parent, leaf) = parent(path)?;
|
||||
let metadata =
|
||||
statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)?;
|
||||
let created_at_ms = created_at_ms(&metadata);
|
||||
file_metadata(metadata, created_at_ms)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn file_metadata_linux(metadata: Statx) -> io::Result<FileMetadata> {
|
||||
let kind = u32::from(metadata.stx_mode) & libc::S_IFMT;
|
||||
if kind == libc::S_IFLNK {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a symbolic link",
|
||||
));
|
||||
}
|
||||
let created_at_ms = if metadata.stx_mask & StatxFlags::BTIME.bits() == 0 {
|
||||
0
|
||||
} else {
|
||||
unix_time_ms(metadata.stx_btime.tv_sec, metadata.stx_btime.tv_nsec)
|
||||
};
|
||||
Ok(FileMetadata {
|
||||
is_directory: kind == libc::S_IFDIR,
|
||||
is_file: kind == libc::S_IFREG,
|
||||
is_symlink: false,
|
||||
size: metadata.stx_size,
|
||||
created_at_ms,
|
||||
modified_at_ms: unix_time_ms(metadata.stx_mtime.tv_sec, metadata.stx_mtime.tv_nsec),
|
||||
})
|
||||
}
|
||||
|
||||
fn file_metadata(metadata: Stat, created_at_ms: i64) -> io::Result<FileMetadata> {
|
||||
let kind = metadata.st_mode & libc::S_IFMT;
|
||||
if kind == libc::S_IFLNK {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a symbolic link",
|
||||
));
|
||||
}
|
||||
Ok(FileMetadata {
|
||||
is_directory: kind == libc::S_IFDIR,
|
||||
is_file: kind == libc::S_IFREG,
|
||||
is_symlink: false,
|
||||
size: u64::try_from(metadata.st_size).unwrap_or(0),
|
||||
created_at_ms,
|
||||
modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
fn created_at_ms(metadata: &Stat) -> i64 {
|
||||
unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
|
||||
fn created_at_ms(_metadata: &Stat) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn unix_time_ms(seconds: i64, nanoseconds: impl TryInto<i64>) -> i64 {
|
||||
let nanoseconds = nanoseconds.try_into().unwrap_or_default();
|
||||
seconds
|
||||
.saturating_mul(1_000)
|
||||
.saturating_add(nanoseconds / 1_000_000)
|
||||
}
|
||||
|
||||
pub(super) async fn metadata(path: PathBuf) -> io::Result<FileMetadata> {
|
||||
tokio::task::spawn_blocking(move || metadata_sync(&path))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let components = components(&path)?;
|
||||
if components.is_empty() && !recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"directory already exists",
|
||||
));
|
||||
}
|
||||
let mut directory = root()?;
|
||||
for (index, component) in components.iter().enumerate() {
|
||||
let is_leaf = index + 1 == components.len();
|
||||
if !recursive && is_leaf {
|
||||
mkdirat(&directory, component, Mode::from_raw_mode(0o777))
|
||||
.map_err(io::Error::from)?;
|
||||
return Ok(());
|
||||
}
|
||||
match open_directory(&directory, component) {
|
||||
Ok(next) => directory = next,
|
||||
Err(error) if recursive && error.kind() == io::ErrorKind::NotFound => {
|
||||
match mkdirat(&directory, component, Mode::from_raw_mode(0o777)) {
|
||||
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
|
||||
Err(error) => return Err(io::Error::from(error)),
|
||||
}
|
||||
directory = open_directory(&directory, component)?;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"recursive no-follow removal is unsupported",
|
||||
));
|
||||
}
|
||||
let (parent, leaf) = match parent(&path) {
|
||||
Ok(value) => value,
|
||||
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let metadata = match statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if force && error == rustix::io::Errno::NOENT => return Ok(()),
|
||||
Err(error) => return Err(io::Error::from(error)),
|
||||
};
|
||||
let kind = metadata.st_mode & libc::S_IFMT;
|
||||
if kind == libc::S_IFLNK {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a symbolic link",
|
||||
));
|
||||
}
|
||||
let flags = if kind == libc::S_IFDIR {
|
||||
AtFlags::REMOVEDIR
|
||||
} else {
|
||||
AtFlags::empty()
|
||||
};
|
||||
unlinkat(&parent, leaf, flags).map_err(io::Error::from)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
535
akode-rs/exec-server/src/no_follow/windows.rs
Normal file
535
akode-rs/exec-server/src/no_follow/windows.rs
Normal file
@@ -0,0 +1,535 @@
|
||||
use crate::regular_file;
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::mem::size_of;
|
||||
use std::mem::size_of_val;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::path::Prefix;
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::Foundation::NTSTATUS;
|
||||
use windows_sys::Win32::Foundation::OBJ_CASE_INSENSITIVE;
|
||||
use windows_sys::Win32::Foundation::OBJ_DONT_REPARSE;
|
||||
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
|
||||
use windows_sys::Win32::Foundation::UNICODE_STRING;
|
||||
use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;
|
||||
use windows_sys::Win32::Security::SecurityIdentification;
|
||||
use windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;
|
||||
use windows_sys::Win32::Storage::FileSystem::DELETE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ID_INFO;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
|
||||
use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo;
|
||||
use windows_sys::Win32::Storage::FileSystem::FileIdInfo;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandleEx;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetVolumeInformationByHandleW;
|
||||
use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle;
|
||||
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
|
||||
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
|
||||
|
||||
#[path = "windows_volume_fallback.rs"]
|
||||
mod volume_fallback;
|
||||
|
||||
const SHARE_ALL: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
|
||||
const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
|
||||
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
|
||||
const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
|
||||
const FILE_OPEN: u32 = 1;
|
||||
const FILE_CREATE: u32 = 2;
|
||||
const FILE_OPEN_IF: u32 = 3;
|
||||
const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;
|
||||
const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;
|
||||
const SECURITY_STATIC_TRACKING: u8 = 0;
|
||||
|
||||
#[repr(C)]
|
||||
struct ObjectAttributes {
|
||||
length: u32,
|
||||
root_directory: HANDLE,
|
||||
object_name: *const UNICODE_STRING,
|
||||
attributes: u32,
|
||||
security_descriptor: *const c_void,
|
||||
security_quality_of_service: *const c_void,
|
||||
}
|
||||
|
||||
#[link(name = "ntdll")]
|
||||
unsafe extern "system" {
|
||||
fn NtCreateFile(
|
||||
file_handle: *mut HANDLE,
|
||||
desired_access: u32,
|
||||
object_attributes: *const ObjectAttributes,
|
||||
io_status_block: *mut IO_STATUS_BLOCK,
|
||||
allocation_size: *const i64,
|
||||
file_attributes: u32,
|
||||
share_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
ea_buffer: *const c_void,
|
||||
ea_length: u32,
|
||||
) -> NTSTATUS;
|
||||
}
|
||||
|
||||
fn nt_path(path: &Path) -> io::Result<Vec<u16>> {
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute path",
|
||||
));
|
||||
}
|
||||
|
||||
let (prefix, source_offset) = match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::Disk(_) => ("\\??\\", 0),
|
||||
Prefix::VerbatimDisk(_) => ("\\??\\", 4),
|
||||
Prefix::UNC(_, _) => ("\\??\\UNC\\", 2),
|
||||
Prefix::VerbatimUNC(_, _) => ("\\??\\UNC\\", 8),
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require a local disk or UNC path",
|
||||
));
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute Windows path",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut result: Vec<u16> = OsStr::new(prefix).encode_wide().collect();
|
||||
result.extend(
|
||||
path.as_os_str()
|
||||
.encode_wide()
|
||||
.skip(source_offset)
|
||||
.map(|unit| {
|
||||
if unit == b'/' as u16 {
|
||||
b'\\' as u16
|
||||
} else {
|
||||
unit
|
||||
}
|
||||
}),
|
||||
);
|
||||
result.push(0);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn open_handle(
|
||||
path: &Path,
|
||||
desired_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
) -> io::Result<OwnedHandle> {
|
||||
open_handle_with_sharing(
|
||||
path,
|
||||
desired_access,
|
||||
create_disposition,
|
||||
create_options,
|
||||
SHARE_ALL,
|
||||
)
|
||||
}
|
||||
|
||||
fn open_handle_with_sharing(
|
||||
path: &Path,
|
||||
desired_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
share_access: u32,
|
||||
) -> io::Result<OwnedHandle> {
|
||||
let mut name = nt_path(path)?;
|
||||
if let Some(handle) = open_nt_handle(
|
||||
&mut name,
|
||||
/*root_directory*/ None,
|
||||
desired_access,
|
||||
create_disposition,
|
||||
create_options,
|
||||
OBJ_DONT_REPARSE,
|
||||
share_access,
|
||||
)? {
|
||||
return Ok(handle);
|
||||
}
|
||||
|
||||
// Windows 10 also rejects the DOS drive alias itself. Only for drive-letter
|
||||
// paths, open its verified volume root and keep strict checks below it.
|
||||
if matches!(path.components().next(), Some(Component::Prefix(prefix))
|
||||
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)))
|
||||
{
|
||||
return volume_fallback::open_relative_to_volume(
|
||||
&mut name,
|
||||
desired_access,
|
||||
create_disposition,
|
||||
create_options,
|
||||
share_access,
|
||||
);
|
||||
}
|
||||
Err(reparse_error())
|
||||
}
|
||||
|
||||
fn reparse_error() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, "path contains a reparse point")
|
||||
}
|
||||
|
||||
/// Returns `None` only for the native reparse status; other errors propagate.
|
||||
fn open_nt_handle(
|
||||
path: &mut [u16],
|
||||
root_directory: Option<&OwnedHandle>,
|
||||
desired_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
attributes: u32,
|
||||
share_access: u32,
|
||||
) -> io::Result<Option<OwnedHandle>> {
|
||||
let maximum_length = u16::try_from(size_of_val(path))
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
|
||||
let object_name = UNICODE_STRING {
|
||||
Length: maximum_length - size_of::<u16>() as u16,
|
||||
MaximumLength: maximum_length,
|
||||
Buffer: path.as_mut_ptr(),
|
||||
};
|
||||
let security_quality_of_service = SECURITY_QUALITY_OF_SERVICE {
|
||||
Length: size_of::<SECURITY_QUALITY_OF_SERVICE>() as u32,
|
||||
ImpersonationLevel: SecurityIdentification,
|
||||
ContextTrackingMode: SECURITY_STATIC_TRACKING,
|
||||
EffectiveOnly: true,
|
||||
};
|
||||
let object_attributes = ObjectAttributes {
|
||||
length: size_of::<ObjectAttributes>() as u32,
|
||||
root_directory: root_directory.map_or(ptr::null_mut(), AsRawHandle::as_raw_handle),
|
||||
object_name: &object_name,
|
||||
attributes: OBJ_CASE_INSENSITIVE | attributes,
|
||||
security_descriptor: ptr::null(),
|
||||
security_quality_of_service: (&raw const security_quality_of_service).cast(),
|
||||
};
|
||||
let mut io_status_block = IO_STATUS_BLOCK {
|
||||
Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
|
||||
Information: 0,
|
||||
};
|
||||
let mut handle = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
NtCreateFile(
|
||||
&mut handle,
|
||||
desired_access | SYNCHRONIZE_ACCESS,
|
||||
&object_attributes,
|
||||
&mut io_status_block,
|
||||
ptr::null(),
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
share_access,
|
||||
create_disposition,
|
||||
create_options | FILE_SYNCHRONOUS_IO_NONALERT,
|
||||
ptr::null(),
|
||||
/*ea_length*/ 0,
|
||||
)
|
||||
};
|
||||
if status == STATUS_REPARSE_POINT_ENCOUNTERED {
|
||||
return Ok(None);
|
||||
}
|
||||
if status < 0 {
|
||||
let code = unsafe { RtlNtStatusToDosError(status) };
|
||||
return Err(io::Error::from_raw_os_error(code as i32));
|
||||
}
|
||||
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::other(
|
||||
"NtCreateFile returned an invalid filesystem handle",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Some(unsafe { OwnedHandle::from_raw_handle(handle) }))
|
||||
}
|
||||
|
||||
fn open_entry(path: &Path) -> io::Result<std::fs::File> {
|
||||
let handle = open_handle(
|
||||
path,
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_OPEN,
|
||||
/*create_options*/ 0,
|
||||
)?;
|
||||
Ok(std::fs::File::from(handle))
|
||||
}
|
||||
|
||||
pub(super) fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let handle = open_handle(path, FILE_GENERIC_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE)?;
|
||||
let file = std::fs::File::from(handle);
|
||||
validate_regular_file(&file, path)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn validate_regular_file(file: &std::fs::File, path: &Path) -> io::Result<()> {
|
||||
if !regular_file::is_disk_file(file) || !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path `{}` is not a file", path.display()),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn file_information(file: &std::fs::File) -> io::Result<BY_HANDLE_FILE_INFORMATION> {
|
||||
let mut info = std::mem::MaybeUninit::uninit();
|
||||
// SAFETY: the file owns the handle and a successful call initializes info.
|
||||
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(unsafe { info.assume_init() })
|
||||
}
|
||||
|
||||
pub(super) fn reject_multiple_links(file: &std::fs::File) -> io::Result<()> {
|
||||
if file_information(file)?.nNumberOfLinks > 1 {
|
||||
return Err(super::invalid_output("output has multiple hard links"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn file_identity(file: &std::fs::File) -> io::Result<(u64, [u8; 16])> {
|
||||
// ReFS requires the full 128-bit identifier to distinguish files on the same volume.
|
||||
let mut info = std::mem::MaybeUninit::<FILE_ID_INFO>::uninit();
|
||||
// SAFETY: the open handle is valid and FileIdInfo fills this exact structure on success.
|
||||
if unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
file.as_raw_handle(),
|
||||
FileIdInfo,
|
||||
info.as_mut_ptr().cast(),
|
||||
size_of::<FILE_ID_INFO>() as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let info = unsafe { info.assume_init() };
|
||||
// A filesystem may report success with an all-zero ID when it cannot identify the file.
|
||||
if info.FileId.Identifier == [0; 16] {
|
||||
return Err(super::invalid_output(
|
||||
"filesystem did not provide an output file ID",
|
||||
));
|
||||
}
|
||||
Ok((info.VolumeSerialNumber, info.FileId.Identifier))
|
||||
}
|
||||
|
||||
pub(super) fn verify_output_path(file: &std::fs::File, path: &Path) -> io::Result<()> {
|
||||
verify_output_path_with(file, path, file_identity, filesystem_name)
|
||||
}
|
||||
|
||||
pub(super) fn verify_output_path_with(
|
||||
file: &std::fs::File,
|
||||
path: &Path,
|
||||
file_id: impl Fn(&std::fs::File) -> io::Result<(u64, [u8; 16])>,
|
||||
volume_name: impl Fn(&std::fs::File) -> io::Result<String>,
|
||||
) -> io::Result<()> {
|
||||
let current = open_entry(path)?;
|
||||
let same = match file_id(file) {
|
||||
Ok(id) => id == file_id(¤t)?,
|
||||
Err(error) => {
|
||||
let is_fat = |name: String| {
|
||||
["FAT", "FAT32", "exFAT"]
|
||||
.iter()
|
||||
.any(|fs| name.eq_ignore_ascii_case(fs))
|
||||
};
|
||||
if !is_fat(volume_name(file)?) || !is_fat(volume_name(¤t)?) {
|
||||
return Err(error);
|
||||
}
|
||||
same_fat_file(file, ¤t)?
|
||||
}
|
||||
};
|
||||
if !same {
|
||||
return Err(super::invalid_output("output path was replaced"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn filesystem_name(file: &std::fs::File) -> io::Result<String> {
|
||||
let mut name = [0u16; 32];
|
||||
// SAFETY: only the filesystem name is requested, in the supplied writable buffer.
|
||||
if unsafe {
|
||||
GetVolumeInformationByHandleW(
|
||||
file.as_raw_handle(),
|
||||
ptr::null_mut(),
|
||||
/*nvolumenamesize*/ 0,
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
ptr::null_mut(),
|
||||
name.as_mut_ptr(),
|
||||
name.len() as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let name = name.split(|unit| *unit == 0).next().unwrap_or_default();
|
||||
Ok(String::from_utf16_lossy(name))
|
||||
}
|
||||
|
||||
fn same_fat_file(file: &std::fs::File, current: &std::fs::File) -> io::Result<bool> {
|
||||
// The bound output denies delete sharing, so its FAT directory slot cannot be recycled.
|
||||
let id = |file| -> io::Result<_> {
|
||||
let info = file_information(file)?;
|
||||
if info.nFileIndexHigh == 0 && info.nFileIndexLow == 0 {
|
||||
return Err(super::invalid_output(
|
||||
"filesystem did not provide an output file ID",
|
||||
));
|
||||
}
|
||||
Ok((
|
||||
info.dwVolumeSerialNumber,
|
||||
info.nFileIndexHigh,
|
||||
info.nFileIndexLow,
|
||||
))
|
||||
};
|
||||
Ok(id(file)? == id(current)?)
|
||||
}
|
||||
|
||||
pub(super) fn open_null_output() -> io::Result<std::fs::File> {
|
||||
// Use the kernel null device directly so no user-controlled DOS alias is followed.
|
||||
let mut name: Vec<_> = r"\Device\Null".encode_utf16().chain([0]).collect();
|
||||
let handle = open_nt_handle(
|
||||
&mut name,
|
||||
/*root_directory*/ None,
|
||||
FILE_WRITE_DATA,
|
||||
FILE_OPEN,
|
||||
/*create_options*/ 0,
|
||||
OBJ_DONT_REPARSE,
|
||||
SHARE_ALL,
|
||||
)?
|
||||
.ok_or_else(reparse_error)?;
|
||||
Ok(handle.into())
|
||||
}
|
||||
|
||||
fn open_writable_regular_file(path: &Path, share_access: u32) -> io::Result<std::fs::File> {
|
||||
let handle = open_handle_with_sharing(
|
||||
path,
|
||||
FILE_READ_ATTRIBUTES | FILE_WRITE_DATA,
|
||||
FILE_OPEN_IF,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
share_access,
|
||||
)?;
|
||||
let file = std::fs::File::from(handle);
|
||||
validate_regular_file(&file, path)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
pub(super) fn open_output(path: &Path) -> io::Result<std::fs::File> {
|
||||
if matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
|
||||
&& path.as_os_str().as_encoded_bytes().contains(&b'/')
|
||||
{
|
||||
return Err(super::invalid_output("invalid verbatim output path"));
|
||||
}
|
||||
// Full file IDs identify the base file, not a particular data stream. Keep the
|
||||
// selected stream bound from the first open, including the unnamed default stream.
|
||||
let file = open_writable_regular_file(path, FILE_SHARE_READ | FILE_SHARE_WRITE)?;
|
||||
// Fail before starting a turn if this filesystem cannot verify the output.
|
||||
verify_output_path(&file, path)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = open_writable_regular_file(&path, SHARE_ALL)?;
|
||||
file.set_len(0)?;
|
||||
file.write_all(&contents)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn metadata(path: PathBuf) -> io::Result<std::fs::Metadata> {
|
||||
tokio::task::spawn_blocking(move || open_entry(&path)?.metadata())
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn create_directory_sync(path: &Path, recursive: bool) -> io::Result<()> {
|
||||
if !recursive {
|
||||
open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut current = PathBuf::new();
|
||||
for component in path.components() {
|
||||
current.push(component.as_os_str());
|
||||
if matches!(component, Component::Normal(_)) {
|
||||
open_or_create_directory(¤t)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_or_create_directory(path: &Path) -> io::Result<()> {
|
||||
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
|
||||
open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE)?;
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || create_directory_sync(&path, recursive))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
|
||||
if recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"recursive no-follow removal is unsupported",
|
||||
));
|
||||
}
|
||||
|
||||
let metadata = match open_entry(path).and_then(|file| file.metadata()) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let create_options = if metadata.is_dir() {
|
||||
FILE_DIRECTORY_FILE
|
||||
} else {
|
||||
FILE_NON_DIRECTORY_FILE
|
||||
};
|
||||
let handle = open_handle(path, DELETE, FILE_OPEN, create_options)?;
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
|
||||
let result = unsafe {
|
||||
SetFileInformationByHandle(
|
||||
handle.as_raw_handle(),
|
||||
FileDispositionInfo,
|
||||
(&raw const disposition).cast(),
|
||||
size_of::<FILE_DISPOSITION_INFO>() as u32,
|
||||
)
|
||||
};
|
||||
if result == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
drop(handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || remove_sync(&path, recursive, force))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_tests.rs"]
|
||||
mod tests;
|
||||
146
akode-rs/exec-server/src/no_follow/windows_tests.rs
Normal file
146
akode-rs/exec-server/src/no_follow/windows_tests.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use windows_sys::Win32::Foundation::ERROR_PIPE_LISTENING;
|
||||
use windows_sys::Win32::Foundation::GetLastError;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
|
||||
use windows_sys::Win32::System::Pipes::ConnectNamedPipe;
|
||||
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_NOWAIT;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
|
||||
|
||||
#[test]
|
||||
fn relative_volume_opens_files_and_rejects_junctions() -> io::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let real = std::fs::canonicalize(temp.path())?;
|
||||
let open = |path: &Path, access, disposition, options| {
|
||||
volume_fallback::open_relative_to_volume(
|
||||
&mut nt_path(path)?,
|
||||
access,
|
||||
disposition,
|
||||
options,
|
||||
SHARE_ALL,
|
||||
)
|
||||
};
|
||||
let existing = real.join("existing.txt");
|
||||
std::fs::File::from(open(
|
||||
&existing,
|
||||
FILE_WRITE_DATA,
|
||||
FILE_CREATE,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
)?)
|
||||
.write_all(b"updated")?;
|
||||
let file = std::fs::File::from(open(
|
||||
&existing,
|
||||
FILE_GENERIC_READ,
|
||||
FILE_OPEN,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
)?);
|
||||
assert_eq!(file.metadata()?.len(), 7);
|
||||
|
||||
let drive_root = existing.ancestors().last().expect("absolute path root");
|
||||
let root = std::fs::File::from(open(
|
||||
drive_root,
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_OPEN,
|
||||
FILE_DIRECTORY_FILE,
|
||||
)?);
|
||||
assert!(root.metadata()?.is_dir());
|
||||
|
||||
let junction_parent = tempfile::tempdir()?;
|
||||
let junction = junction_parent.path().join("junction");
|
||||
let result = std::process::Command::new("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.arg(&junction)
|
||||
.arg(&real)
|
||||
.output()?;
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
for (path, disposition, options) in [
|
||||
(junction.clone(), FILE_OPEN, FILE_DIRECTORY_FILE),
|
||||
(
|
||||
junction.join("existing.txt"),
|
||||
FILE_OPEN,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
),
|
||||
(
|
||||
junction.join("blocked.txt"),
|
||||
FILE_CREATE,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
),
|
||||
] {
|
||||
let error = open(&path, FILE_READ_ATTRIBUTES, disposition, options)
|
||||
.expect_err("a junction must never be traversed");
|
||||
assert_eq!(error.to_string(), "path contains a reparse point");
|
||||
}
|
||||
assert!(!real.join("blocked.txt").exists());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_root_validation_rejects_devices_and_subdirectories() {
|
||||
for (path, expected) in [
|
||||
(r"\Device\HarddiskVolume1\", true),
|
||||
(r"\Device\HarddiskVolume123\", true),
|
||||
(r"\Device\HarddiskVolume\", false),
|
||||
(r"\Device\HarddiskVolume1", false),
|
||||
(r"\Device\HarddiskVolume1\workspace\", false),
|
||||
(r"\Device\HarddiskVolume1x\", false),
|
||||
(r"\Device\NamedPipe\", false),
|
||||
(r"\Device\Mup\", false),
|
||||
(r"\Device\CdRom0\", false),
|
||||
] {
|
||||
let path = OsStr::new(path).encode_wide().collect::<Vec<_>>();
|
||||
assert_eq!(volume_fallback::is_local_volume_root(&path), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_open_rejects_named_pipes_before_connecting() {
|
||||
let pipe_name = format!("codex-no-follow-{}", uuid::Uuid::new_v4());
|
||||
let server_path = PathBuf::from(format!(r"\\.\pipe\{pipe_name}"));
|
||||
let client_path = PathBuf::from(format!(r"\\localhost\pipe\{pipe_name}"));
|
||||
let wide_path = server_path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let pipe = unsafe {
|
||||
CreateNamedPipeW(
|
||||
wide_path.as_ptr(),
|
||||
PIPE_ACCESS_DUPLEX,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT,
|
||||
/*nmaxinstances*/ 1,
|
||||
/*noutbuffersize*/ 1,
|
||||
/*ninbuffersize*/ 1,
|
||||
/*ndefaulttimeout*/ 1_000,
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(pipe, INVALID_HANDLE_VALUE);
|
||||
let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe) };
|
||||
|
||||
// A DOS drive alias could target a pipe; the root open must reject a pipe
|
||||
// before obtaining a client connection, even before final-path validation.
|
||||
let mut pipe_root: Vec<_> = format!(r"\Device\NamedPipe\{pipe_name}\")
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
assert!(volume_fallback::open_volume_root(&mut pipe_root).is_err());
|
||||
|
||||
let error = open_handle(
|
||||
&client_path,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
|
||||
FILE_OPEN,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
)
|
||||
.expect_err("strict native open should reject named pipes");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
assert_eq!(error.to_string(), "path contains a reparse point");
|
||||
assert_eq!(unsafe { ConnectNamedPipe(pipe, ptr::null_mut()) }, 0);
|
||||
assert_eq!(unsafe { GetLastError() }, ERROR_PIPE_LISTENING);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Retry drive-letter opens from a verified physical volume root when strict NT opens reject
|
||||
//! the DOS alias. The root must be a local directory; all path components below it stay no-follow.
|
||||
|
||||
use super::*;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_TRAVERSE;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
|
||||
use windows_sys::Win32::Storage::FileSystem::VOLUME_NAME_NT;
|
||||
|
||||
const FILE_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const DOS_DRIVE_ROOT_LEN: usize = r"\??\C:\".len();
|
||||
|
||||
pub(super) fn open_relative_to_volume(
|
||||
name: &mut [u16],
|
||||
desired_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
share_access: u32,
|
||||
) -> io::Result<OwnedHandle> {
|
||||
let mut root_name = name[..DOS_DRIVE_ROOT_LEN].to_vec();
|
||||
root_name.push(0);
|
||||
let root = open_volume_root(&mut root_name)?;
|
||||
open_nt_handle(
|
||||
&mut name[DOS_DRIVE_ROOT_LEN..],
|
||||
Some(&root),
|
||||
desired_access,
|
||||
create_disposition,
|
||||
create_options,
|
||||
OBJ_DONT_REPARSE,
|
||||
share_access,
|
||||
)?
|
||||
.ok_or_else(reparse_error)
|
||||
}
|
||||
|
||||
pub(super) fn open_volume_root(name: &mut [u16]) -> io::Result<OwnedHandle> {
|
||||
let handle = open_nt_handle(
|
||||
name,
|
||||
/*root_directory*/ None,
|
||||
FILE_READ_ATTRIBUTES | FILE_TRAVERSE,
|
||||
FILE_OPEN,
|
||||
FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
|
||||
/*attributes*/ 0,
|
||||
SHARE_ALL,
|
||||
)?
|
||||
.ok_or_else(reparse_error)?;
|
||||
let root = std::fs::File::from(handle);
|
||||
let metadata = root.metadata()?;
|
||||
if !metadata.is_dir() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
|
||||
return Err(reparse_error());
|
||||
}
|
||||
|
||||
let mut name = [0u16; 128];
|
||||
let length = unsafe {
|
||||
GetFinalPathNameByHandleW(
|
||||
root.as_raw_handle(),
|
||||
name.as_mut_ptr(),
|
||||
name.len() as u32,
|
||||
VOLUME_NAME_NT,
|
||||
)
|
||||
} as usize;
|
||||
if length == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if length >= name.len() || !is_local_volume_root(&name[..length]) {
|
||||
return Err(reparse_error());
|
||||
}
|
||||
Ok(root.into())
|
||||
}
|
||||
|
||||
pub(super) fn is_local_volume_root(name: &[u16]) -> bool {
|
||||
String::from_utf16(name).is_ok_and(|name| {
|
||||
name.strip_prefix(r"\Device\HarddiskVolume")
|
||||
.and_then(|suffix| suffix.strip_suffix('\\'))
|
||||
.is_some_and(|number| !number.is_empty() && number.bytes().all(|b| b.is_ascii_digit()))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user