use std::borrow::Cow;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::access::WriteProbe;
use crate::paths::extended;
pub trait Fs: Send + Sync {
fn root(&self) -> Option<&Path>;
fn exists(&self, path: &Path) -> bool;
fn is_dir(&self, path: &Path) -> bool;
fn read_to_string(&self, path: &Path) -> io::Result<String>;
fn read(&self, path: &Path) -> io::Result<Vec<u8>>;
fn file_size(&self, path: &Path) -> io::Result<u64> {
self.read(path).map(|bytes| bytes.len() as u64)
}
fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()>;
fn replace(&self, from: &Path, to: &Path) -> io::Result<()>;
fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
fn create_dir_all(&self, path: &Path) -> io::Result<()>;
fn create_private_dir_all(&self, path: &Path) -> io::Result<()>;
fn remove_file(&self, path: &Path) -> io::Result<()>;
fn is_regular_file(&self, path: &Path) -> bool;
fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()>;
fn remove_dir_all(&self, path: &Path) -> io::Result<()>;
fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
fn open_lock_file(&self, path: &Path) -> io::Result<File>;
fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
Ok(path.to_path_buf())
}
fn note_dependency(&self, _path: &Path) {}
fn write_probe(&self) -> Option<WriteProbe> {
None
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RealFs;
pub(crate) fn long(path: &Path) -> Cow<'_, Path> {
const LIMIT: usize = 248;
if cfg!(windows) && path.as_os_str().len() >= LIMIT {
extended(path)
} else {
Cow::Borrowed(path)
}
}
impl Fs for RealFs {
fn root(&self) -> Option<&Path> {
None
}
fn exists(&self, path: &Path) -> bool {
long(path).exists()
}
fn is_dir(&self, path: &Path) -> bool {
long(path).is_dir()
}
fn read_to_string(&self, path: &Path) -> io::Result<String> {
std::fs::read_to_string(long(path))
}
fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
std::fs::read(long(path))
}
fn file_size(&self, path: &Path) -> io::Result<u64> {
std::fs::metadata(long(path)).map(|meta| meta.len())
}
fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
std::fs::write(long(path), contents)
}
fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()> {
let path = long(path);
let like = like.map(long);
let mut options = File::options();
options.write(true).create_new(true);
if let Some(like) = &like {
platform::copy_open_options(&mut options, like)?;
}
let mut file = options.open(&path)?;
let written = (|| {
if let Some(like) = &like {
platform::copy_permissions(like, &path, &file)?;
}
file.write_all(contents)?;
file.sync_all()
})();
if written.is_err() {
drop(file);
let _ = std::fs::remove_file(&path);
}
written
}
fn replace(&self, from: &Path, to: &Path) -> io::Result<()> {
let to = long(to);
std::fs::rename(long(from), &to)?;
platform::sync_parent(&to)
}
fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
let path = long(path);
let mut options = File::options();
options.write(true).create(true).truncate(true);
platform::private_open_options(&mut options);
let mut file = options.open(&path)?;
platform::make_private(&path, &file)?;
file.write_all(contents)?;
file.sync_all()
}
fn create_dir_all(&self, path: &Path) -> io::Result<()> {
std::fs::create_dir_all(long(path))
}
fn create_private_dir_all(&self, path: &Path) -> io::Result<()> {
let path = long(path);
std::fs::create_dir_all(&path)?;
platform::make_private_dir(&path)
}
fn remove_file(&self, path: &Path) -> io::Result<()> {
std::fs::remove_file(long(path))
}
fn is_regular_file(&self, path: &Path) -> bool {
std::fs::symlink_metadata(long(path)).is_ok_and(|meta| meta.file_type().is_file())
}
fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()> {
let path = long(path);
if !std::fs::symlink_metadata(&path)?.file_type().is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a regular file",
));
}
let mut file = File::options().write(true).open(&path)?;
let mut left = file.metadata()?.len();
let zeros = [0u8; 64 * 1024];
while left > 0 {
let chunk = usize::try_from(left).map_or(zeros.len(), |left| left.min(zeros.len()));
file.write_all(&zeros[..chunk])?;
left -= chunk as u64;
}
file.sync_all()
}
fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
std::fs::remove_dir_all(long(path))
}
fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
let mut entries = std::fs::read_dir(long(path))?
.map(|entry| entry.map(|entry| path.join(entry.file_name())))
.collect::<io::Result<Vec<_>>>()?;
entries.sort();
Ok(entries)
}
fn open_lock_file(&self, path: &Path) -> io::Result<File> {
File::options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(long(path))
}
fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
std::fs::canonicalize(long(path))
}
fn write_probe(&self) -> Option<WriteProbe> {
Some(Arc::new(crate::access::probe))
}
}
#[cfg(unix)]
mod platform {
use std::fs::{File, OpenOptions, Permissions};
use std::io;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::Path;
pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
let mode = std::fs::metadata(like)?.permissions().mode();
options.mode(mode & 0o7777);
Ok(())
}
pub fn copy_permissions(like: &Path, _path: &Path, file: &File) -> io::Result<()> {
let mode = std::fs::metadata(like)?.permissions().mode();
file.set_permissions(Permissions::from_mode(mode & 0o7777))
}
pub fn private_open_options(options: &mut OpenOptions) {
options.mode(0o600);
}
pub fn make_private(_path: &Path, file: &File) -> io::Result<()> {
file.set_permissions(Permissions::from_mode(0o600))
}
pub fn make_private_dir(path: &Path) -> io::Result<()> {
std::fs::set_permissions(path, Permissions::from_mode(0o700))
}
pub fn sync_parent(path: &Path) -> io::Result<()> {
match path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
Some(dir) => File::open(dir)?.sync_all(),
None => Ok(()),
}
}
}
#[cfg(windows)]
mod platform {
use std::fs::{File, OpenOptions};
use std::io;
use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
use std::path::Path;
use windows_permissions::constants::{AceFlags, SeObjectType, SecurityInformation};
use windows_permissions::{LocalBox, SecurityDescriptor, wrappers};
const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4 | 0x20 | 0x2000;
pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
let attributes = std::fs::metadata(like)?.file_attributes() & KEPT_ATTRIBUTES;
options.attributes(attributes);
Ok(())
}
pub fn copy_permissions(like: &Path, path: &Path, _file: &File) -> io::Result<()> {
let sd = wrappers::GetNamedSecurityInfo(
like.as_os_str(),
SeObjectType::SE_FILE_OBJECT,
SecurityInformation::Dacl,
)?;
let sddl = sd.as_sddl()?.to_string_lossy().into_owned();
let protected = dacl_flags(&sddl).contains('P');
let Some(dacl) = sd.dacl() else {
return Ok(());
};
let explicit = (0..dacl.len())
.filter_map(|index| dacl.get_ace(index))
.any(|ace| !ace.flags().contains(AceFlags::Inherited));
if !protected && !explicit {
return Ok(());
}
let protection = if protected {
SecurityInformation::ProtectedDacl
} else {
SecurityInformation::UnprotectedDacl
};
wrappers::SetNamedSecurityInfo(
path.as_os_str(),
SeObjectType::SE_FILE_OBJECT,
SecurityInformation::Dacl | protection,
None,
None,
Some(dacl),
None,
)
}
fn dacl_flags(sddl: &str) -> String {
let Some(start) = sddl.find("D:") else {
return String::new();
};
let rest = &sddl[start + 2..];
let end = rest.find('(').unwrap_or(rest.len());
rest[..end].replace("AI", "").replace("AR", "")
}
pub fn private_open_options(_options: &mut OpenOptions) {}
pub fn make_private(path: &Path, _file: &File) -> io::Result<()> {
owner_only(path, false)
}
pub fn make_private_dir(path: &Path) -> io::Result<()> {
owner_only(path, true)
}
fn owner_only(path: &Path, dir: bool) -> io::Result<()> {
let sd = wrappers::GetNamedSecurityInfo(
path.as_os_str(),
SeObjectType::SE_FILE_OBJECT,
SecurityInformation::Owner,
)?;
let owner = sd
.owner()
.ok_or_else(|| io::Error::other("the file has no owner"))?;
let inherit = if dir { "OICI" } else { "" };
let sddl = format!("D:P(A;{inherit};FA;;;{owner})");
let private: LocalBox<SecurityDescriptor> = sddl.parse()?;
let dacl = private
.dacl()
.ok_or_else(|| io::Error::other("the private DACL did not parse"))?;
wrappers::SetNamedSecurityInfo(
path.as_os_str(),
SeObjectType::SE_FILE_OBJECT,
SecurityInformation::Dacl | SecurityInformation::ProtectedDacl,
None,
None,
Some(dacl),
None,
)
}
pub fn sync_parent(_path: &Path) -> io::Result<()> {
Ok(())
}
}