use std::{
fs::{self, File, OpenOptions},
io,
os::windows::fs::MetadataExt,
path::{Path, PathBuf},
};
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum DaemonPathError {
#[error(transparent)]
SocketPathTooLong(#[from] rho_protocol::SocketPathTooLong),
#[error("rho daemon directory {path} is not a directory; remove it and retry")]
NotADirectory { path: PathBuf },
#[error("could not prepare rho daemon directory {path}: {message}")]
Io { path: PathBuf, message: String },
#[error("could not read {path}: {message}")]
Unreadable { path: PathBuf, message: String },
#[error(
"rho daemon pipe {path} was created by another user; find the process that holds it, end it, and let the next client start the daemon"
)]
ForeignPipe { path: PathBuf },
}
impl DaemonPathError {
pub(crate) fn is_unreadable(&self) -> bool {
match self {
Self::Io { .. } | Self::Unreadable { .. } => true,
Self::SocketPathTooLong(_) | Self::NotADirectory { .. } | Self::ForeignPipe { .. } => {
false
}
}
}
}
pub(crate) fn create_private_dir(path: &Path) -> io::Result<()> {
fs::create_dir_all(path)
}
pub(in crate::daemon) fn prepare_private_dir(path: &Path) -> Result<(), DaemonPathError> {
let io_error = |error: io::Error| DaemonPathError::Io {
path: path.to_path_buf(),
message: error.to_string(),
};
match create_private_dir(path) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(io_error(error)),
}
let metadata = fs::symlink_metadata(path).map_err(io_error)?;
if !metadata.is_dir() || metadata.is_symlink() {
return Err(DaemonPathError::NotADirectory {
path: path.to_path_buf(),
});
}
Ok(())
}
pub(in crate::daemon) fn open_lock_file(path: &Path) -> io::Result<File> {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
}
pub(in crate::daemon) fn open_log_file(path: &Path) -> io::Result<File> {
OpenOptions::new().create(true).append(true).open(path)
}
pub(crate) fn sync_dir(_path: &Path) -> io::Result<()> {
Ok(())
}
pub(crate) fn create_private_file(path: &Path) -> io::Result<File> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FileIdentity {
created: u64,
modified: u64,
size: u64,
}
impl FileIdentity {
pub(crate) fn of(metadata: &fs::Metadata) -> Self {
Self {
created: metadata.creation_time(),
modified: metadata.last_write_time(),
size: metadata.file_size(),
}
}
}
pub(crate) const REPLACEABLE_WHILE_RUNNING: bool = false;
pub(in crate::daemon) fn running_identity() -> Option<FileIdentity> {
None
}