use std::{
io::{self, Write as _},
path::{Path, PathBuf},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use cap_std::fs::{Dir, File as CapFile, Metadata};
use super::{
DirectoryHandles, EntryId, FileOpenMode, entry_capability, metadata_is_link,
remove_directory_error, remove_file_or_symlink,
};
use crate::ExtractError;
#[derive(Clone, Copy, Eq, PartialEq)]
pub(super) enum BufferedFileReplacement {
Disallowed,
Allowed,
ExpectedFile,
}
pub(super) enum BufferedError {
Collision,
RemoveDirectory(io::Error),
Filesystem {
operation: &'static str,
source: io::Error,
},
}
pub(super) struct BufferedFile {
pub(super) entry: EntryId,
pub(super) parent: EntryId,
pub(super) path: Arc<str>,
pub(super) executable: bool,
pub(super) contents: Vec<u8>,
pub(super) replacement: BufferedFileReplacement,
}
pub(super) enum BufferedOperation {
Directory {
entry: EntryId,
parent: EntryId,
path: Arc<str>,
end: usize,
},
File(BufferedFile),
}
pub(super) struct BufferedBatchResult {
pub(super) handles: DirectoryHandles,
pub(super) buffers: Vec<Vec<u8>>,
pub(super) error: Option<(PathBuf, BufferedError)>,
}
impl BufferedError {
fn filesystem(operation: &'static str, source: io::Error) -> Self {
Self::Filesystem { operation, source }
}
pub(super) fn into_extract<E>(self, path: PathBuf) -> ExtractError<E> {
match self {
Self::Collision => ExtractError::PathCollision { path },
Self::RemoveDirectory(source) => remove_directory_error(path, source),
Self::Filesystem { operation, source } => {
ExtractError::filesystem(operation, path, source)
}
}
}
}
pub(super) fn write_buffered_files(
root: Arc<Dir>,
mut handles: DirectoryHandles,
operations: Vec<BufferedOperation>,
cancellation: &AtomicBool,
) -> BufferedBatchResult {
let mut buffers = Vec::new();
let mut error = None;
for operation in operations {
let execute = error.is_none() && !cancellation.load(Ordering::Acquire);
match operation {
BufferedOperation::Directory {
entry,
parent,
path,
end,
} => {
if execute {
let path = Path::new(&path[..end]);
let (directory, relative_path) =
entry_capability(&root, &handles, path, parent);
match create_parent(directory, relative_path) {
Ok(opened) => {
handles.insert(entry, parent, Arc::new(opened));
}
Err(source) => error = Some((path.to_path_buf(), source)),
}
}
}
BufferedOperation::File(file) => {
if execute {
handles.remove(file.entry);
let path = Path::new(file.path.as_ref());
let (directory, relative_path) =
entry_capability(&root, &handles, path, file.parent);
if let Err(source) = write_buffered_file(
directory,
relative_path,
file.executable,
&file.contents,
file.replacement,
) {
error = Some((path.to_path_buf(), source));
}
}
buffers.push(file.contents);
}
}
}
BufferedBatchResult {
handles,
buffers,
error,
}
}
fn create_parent(directory: &Dir, path: &Path) -> Result<Dir, BufferedError> {
if let Err(create_error) = directory.create_dir(path) {
if create_error.kind() != io::ErrorKind::AlreadyExists {
return Err(BufferedError::filesystem("create directory", create_error));
}
match directory.symlink_metadata(path) {
Ok(metadata) if metadata.is_dir() && !metadata_is_link(&metadata) => {}
Ok(_) => return Err(BufferedError::Collision),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Err(BufferedError::filesystem("create directory", create_error));
}
Err(error) => return Err(BufferedError::filesystem("inspect", error)),
}
}
directory
.open_dir(path)
.map_err(|source| BufferedError::filesystem("open directory", source))
}
pub(super) fn write_buffered_file(
directory: &Dir,
path: &Path,
executable: bool,
contents: &[u8],
replacement: BufferedFileReplacement,
) -> Result<(), BufferedError> {
let mode = FileOpenMode::CreateNew { executable };
if replacement == BufferedFileReplacement::ExpectedFile && directory.remove_file(path).is_ok() {
let file = mode
.open(directory, path)
.map_err(|source| BufferedError::filesystem("create file", source))?;
return write_buffered_contents(file, contents);
}
let create_error = match mode.open(directory, path) {
Ok(file) => return write_buffered_contents(file, contents),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => error,
Err(error) => return Err(BufferedError::filesystem("create file", error)),
};
let metadata = match directory.symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Err(BufferedError::filesystem("create file", create_error));
}
Err(error) => return Err(BufferedError::filesystem("inspect", error)),
};
if replacement == BufferedFileReplacement::Disallowed {
return Err(BufferedError::Collision);
}
remove_buffered_leaf(directory, path, &metadata)?;
let file = mode
.open(directory, path)
.map_err(|source| BufferedError::filesystem("create file", source))?;
write_buffered_contents(file, contents)
}
fn write_buffered_contents(mut file: CapFile, contents: &[u8]) -> Result<(), BufferedError> {
file.write_all(contents)
.map_err(|source| BufferedError::filesystem("write file", source))
}
fn remove_buffered_leaf(
directory: &Dir,
path: &Path,
metadata: &Metadata,
) -> Result<(), BufferedError> {
if metadata.is_dir() && !metadata_is_link(metadata) {
return directory
.remove_dir(path)
.map_err(BufferedError::RemoveDirectory);
}
remove_file_or_symlink(directory, path, metadata_is_link(metadata))
.map_err(|source| BufferedError::filesystem("remove file", source))
}