use std::{fs, io, path::Path, path::PathBuf};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use crate::errors::{
DomainError, ERROR_FILE_ALREADY_EXISTS, ERROR_NOT_DIRECTORY, ERROR_PATH_DENIED,
ERROR_READ_FAILED, ERROR_WRITE_FAILED,
};
use super::validate::ValidatedToolPath;
pub(crate) fn resolve_existing_path<'a>(
path: &'a ValidatedToolPath,
roots: impl IntoIterator<Item = &'a PathBuf>,
) -> Result<Option<PathBuf>, DomainError> {
for (anchor, components) in path.anchors(roots) {
if let Some(resolved) = walk_existing_path(&anchor, components, path.denies_symlinks())? {
return Ok(Some(resolved));
}
}
Ok(None)
}
fn walk_existing_path(
anchor: &Path,
components: &[String],
deny_symlinks: bool,
) -> Result<Option<PathBuf>, DomainError> {
let mut current = anchor.to_path_buf();
for component in components {
current.push(component);
let metadata = match fs::symlink_metadata(¤t) {
Ok(metadata) => metadata,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(_) => {
return Err(DomainError::new(
ERROR_READ_FAILED,
"could not inspect workspace path",
));
}
};
if deny_symlinks && metadata.file_type().is_symlink() {
return Err(DomainError::new(
ERROR_PATH_DENIED,
"workspace path uses a symlink",
));
}
}
Ok(Some(current))
}
#[derive(Debug)]
pub(crate) enum NewWorkspacePath {
Missing(PathBuf),
Existing,
}
pub(crate) fn resolve_new_file_path<'a>(
path: &'a ValidatedToolPath,
roots: impl IntoIterator<Item = &'a PathBuf>,
) -> Result<NewWorkspacePath, DomainError> {
for (anchor, components) in path.anchors(roots) {
if let Some(outcome) = walk_new_path(&anchor, components, path.denies_symlinks())? {
return Ok(outcome);
}
}
Err(DomainError::new(
ERROR_READ_FAILED,
"could not resolve workspace file path",
))
}
fn walk_new_path(
anchor: &Path,
components: &[String],
deny_symlinks: bool,
) -> Result<Option<NewWorkspacePath>, DomainError> {
let last_index = components.len().saturating_sub(1);
let target = components
.iter()
.fold(anchor.to_path_buf(), |mut path, component| {
path.push(component);
path
});
let mut current = anchor.to_path_buf();
for (index, component) in components.iter().enumerate() {
current.push(component);
let metadata = match fs::symlink_metadata(¤t) {
Ok(metadata) => metadata,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(Some(NewWorkspacePath::Missing(target)));
}
Err(_) => {
return Err(DomainError::new(
ERROR_READ_FAILED,
"could not inspect workspace path",
));
}
};
if deny_symlinks && metadata.file_type().is_symlink() {
return Err(DomainError::new(
ERROR_PATH_DENIED,
"workspace path uses a symlink",
));
}
if index < last_index && !metadata.is_dir() {
return Err(DomainError::new(
ERROR_NOT_DIRECTORY,
"workspace path parent is not a directory",
));
}
if index == last_index {
return Ok(Some(NewWorkspacePath::Existing));
}
}
Ok(None)
}
pub(crate) fn open_file_for_read(path: &Path) -> Result<fs::File, DomainError> {
open_file_for_read_impl(path).map_err(|error| {
if is_symlink_open_error(&error) {
DomainError::new(ERROR_PATH_DENIED, "workspace path uses a symlink")
} else {
DomainError::new(ERROR_READ_FAILED, "could not open workspace file")
}
})
}
pub(crate) fn open_file_for_patch(path: &Path) -> Result<fs::File, DomainError> {
open_file_for_patch_impl(path).map_err(|error| {
if is_symlink_open_error(&error) {
DomainError::new(ERROR_PATH_DENIED, "workspace path uses a symlink")
} else {
DomainError::new(
ERROR_WRITE_FAILED,
"could not open workspace file for patching",
)
}
})
}
pub(crate) fn open_file_for_patch_create_new(path: &Path) -> Result<fs::File, DomainError> {
create_patch_parent_directories(path)?;
open_file_for_patch_create_new_impl(path).map_err(|error| {
if is_symlink_open_error(&error) {
DomainError::new(ERROR_PATH_DENIED, "workspace path uses a symlink")
} else if error.kind() == io::ErrorKind::AlreadyExists {
DomainError::new(ERROR_FILE_ALREADY_EXISTS, "workspace file already exists")
} else {
DomainError::new(ERROR_WRITE_FAILED, "could not create workspace file")
}
})
}
fn create_patch_parent_directories(path: &Path) -> Result<(), DomainError> {
let parent = path.parent().ok_or_else(|| {
DomainError::new(
ERROR_WRITE_FAILED,
"could not determine workspace file parent directory",
)
})?;
let mut current = PathBuf::new();
for component in parent.components() {
current.push(component);
if matches!(
component,
std::path::Component::Prefix(_) | std::path::Component::RootDir
) {
continue;
}
match fs::symlink_metadata(¤t) {
Ok(metadata) => validate_patch_parent_metadata(&metadata)?,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
match fs::create_dir(¤t) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
let metadata = fs::symlink_metadata(¤t).map_err(|_| {
DomainError::new(
ERROR_WRITE_FAILED,
"could not inspect workspace file parent directory",
)
})?;
validate_patch_parent_metadata(&metadata)?;
}
Err(_) => {
return Err(DomainError::new(
ERROR_WRITE_FAILED,
"could not create workspace file parent directories",
));
}
}
}
Err(_) => {
return Err(DomainError::new(
ERROR_WRITE_FAILED,
"could not inspect workspace file parent directory",
));
}
}
}
Ok(())
}
fn validate_patch_parent_metadata(metadata: &fs::Metadata) -> Result<(), DomainError> {
if metadata.file_type().is_symlink() {
return Err(DomainError::new(
ERROR_PATH_DENIED,
"workspace path uses a symlink",
));
}
if !metadata.is_dir() {
return Err(DomainError::new(
ERROR_NOT_DIRECTORY,
"workspace file parent is not a directory",
));
}
Ok(())
}
#[cfg(unix)]
fn open_file_for_read_impl(path: &Path) -> io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
options.open(path)
}
#[cfg(not(unix))]
fn open_file_for_read_impl(path: &Path) -> io::Result<fs::File> {
fs::File::open(path)
}
#[cfg(unix)]
fn open_file_for_patch_impl(path: &Path) -> io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options
.read(true)
.write(true)
.create(false)
.truncate(false)
.custom_flags(libc::O_NOFOLLOW);
options.open(path)
}
#[cfg(not(unix))]
fn open_file_for_patch_impl(path: &Path) -> io::Result<fs::File> {
fs::OpenOptions::new()
.read(true)
.write(true)
.create(false)
.truncate(false)
.open(path)
}
#[cfg(unix)]
fn open_file_for_patch_create_new_impl(path: &Path) -> io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options
.read(true)
.write(true)
.create_new(true)
.custom_flags(libc::O_NOFOLLOW);
options.open(path)
}
#[cfg(not(unix))]
fn open_file_for_patch_create_new_impl(path: &Path) -> io::Result<fs::File> {
fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(path)
}
#[cfg(unix)]
fn is_symlink_open_error(error: &io::Error) -> bool {
error.raw_os_error() == Some(libc::ELOOP)
}
#[cfg(not(unix))]
fn is_symlink_open_error(_: &io::Error) -> bool {
false
}