use std::ffi::OsStr;
use std::io::Read;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use ostrya_core::{KeyFile, RepoMode};
use rustix::fs::FileType;
use rustix::io::Errno;
use crate::config::{
EX_OSTRYA, REMOTES_CONFIG_DIR, RemoteFile, RepoConfig, remote_group, remote_group_name,
};
use crate::error::{Error, Result, io_error};
use crate::repo::{MAX_CONFIG_SIZE, RemotesDir};
use crate::repo_fs::{
FsError, FsResultExt, Named, Publish, Published, Reason, ensure_named_dir, list_fd, open_named,
put_named, remove_named,
};
const SUFFIX: &[u8] = b".conf";
pub(crate) fn from_key(config: &RepoConfig) -> Result<Option<RemotesDir>> {
let Some(value) = config.keyfile().get_string(EX_OSTRYA, REMOTES_CONFIG_DIR)? else {
return Ok(None);
};
if value.is_empty() {
return Err(Error::InvalidFormat(format!(
"[{EX_OSTRYA}] {REMOTES_CONFIG_DIR} is empty"
)));
}
if value.contains('\0') {
return Err(Error::InvalidFormat(format!(
"[{EX_OSTRYA}] {REMOTES_CONFIG_DIR} holds a NUL byte"
)));
}
let path = PathBuf::from(value);
if path.is_absolute() {
return Ok(Some(RemotesDir::Path(path)));
}
if path.components().any(|c| c == Component::ParentDir) {
return Err(Error::InvalidFormat(format!(
"[{EX_OSTRYA}] {REMOTES_CONFIG_DIR} {} has a `..` component, which a relative path \
in a config cannot have",
path.display()
)));
}
Ok(Some(RemotesDir::InRepo(path)))
}
pub(crate) fn read_remotes(
config: RepoConfig,
repo_fd: BorrowedFd<'_>,
dir: &RemotesDir,
) -> Result<RepoConfig> {
open_for_write(config, repo_fd, dir, false).map(|(config, _)| config)
}
pub(crate) fn open_for_write<'a>(
config: RepoConfig,
repo_fd: BorrowedFd<'a>,
dir: &'a RemotesDir,
fsync: bool,
) -> Result<(RepoConfig, DirWriter<'a>)> {
let repo_mode = config.mode();
let fd = open_dir(repo_fd, dir)?;
let config = match &fd {
Some(fd) => config.with_remote_files(display_base(dir), read_files(fd.as_fd(), dir)?)?,
None => config,
};
Ok((
config,
DirWriter {
repo_fd,
dir,
fd,
fsync,
repo_mode,
},
))
}
pub(crate) fn config_remote_names(keyfile: &KeyFile) -> Vec<String> {
keyfile
.groups()
.filter_map(remote_group_name)
.map(str::to_owned)
.collect()
}
pub(crate) fn check_config_remotes(
repo_fd: BorrowedFd<'_>,
dir: Option<&RemotesDir>,
names: &[String],
) -> Result<()> {
let Some(dir) = dir else {
return Ok(());
};
let Some(fd) = open_dir(repo_fd, dir)? else {
return Ok(());
};
let files = read_files(fd.as_fd(), dir)?;
for name in names {
let group = remote_group(name);
if files.iter().any(|file| file.keyfile.has_group(&group)) {
return Err(Error::RemoteExists(name.clone()));
}
}
Ok(())
}
fn locate<'a>(repo_fd: BorrowedFd<'a>, dir: &'a RemotesDir) -> (BorrowedFd<'a>, &'a Path) {
match dir {
RemotesDir::Path(path) => (rustix::fs::CWD, path.as_path()),
RemotesDir::InRepo(path) => (repo_fd, path.as_path()),
RemotesDir::Fd(fd) => (fd.as_fd(), Path::new(".")),
}
}
fn display_base(dir: &RemotesDir) -> &Path {
match dir {
RemotesDir::Path(path) | RemotesDir::InRepo(path) => path,
RemotesDir::Fd(_) => Path::new(""),
}
}
pub(crate) fn entry<'a>(
repo_fd: BorrowedFd<'a>,
dir: &'a RemotesDir,
name: &Path,
) -> (BorrowedFd<'a>, PathBuf, PathBuf) {
let (base, at) = locate(repo_fd, dir);
if name.as_os_str().is_empty() {
return (base, PathBuf::new(), PathBuf::new());
}
(base, at.join(name), display_base(dir).join(name))
}
fn open_dir(repo_fd: BorrowedFd<'_>, dir: &RemotesDir) -> Result<Option<OwnedFd>> {
let (base, at) = locate(repo_fd, dir);
open_named(base, at, Named::Dir)
.optional()
.map_err(|err| fs_error(at, err))
}
fn read_files(dir_fd: BorrowedFd<'_>, dir: &RemotesDir) -> Result<Vec<RemoteFile>> {
let at = match dir {
RemotesDir::Fd(_) => Path::new("."),
_ => display_base(dir),
};
let mut entries = list_fd(dir_fd).map_err(|err| fs_error(at, err))?;
entries.retain(|entry| entry.name.ends_with(SUFFIX));
entries.sort_unstable_by(|a, b| a.name.cmp(&b.name));
let mut files = Vec::new();
for entry in &entries {
let name = OsStr::from_bytes(&entry.name);
let display = display_base(dir).join(name);
if let Some(file) = read_file(dir_fd, name, entry.file_type, &display)? {
files.push(file);
}
}
Ok(files)
}
fn read_file(
dir: BorrowedFd<'_>,
name: &OsStr,
file_type: FileType,
display: &Path,
) -> Result<Option<RemoteFile>> {
if !matches!(file_type, FileType::RegularFile | FileType::Symlink) {
return Ok(None);
}
let fd = match open_named(dir, Path::new(name), Named::File) {
Ok(fd) => fd,
Err(
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotRegular(_),
..
},
) => return Ok(None),
Err(FsError::Invalid {
reason: Reason::NotDirectory,
..
}) => return Err(io_error(display, Errno::NOTDIR)),
Err(err) => return Err(fs_error(display, err)),
};
let Some(name) = name.to_str() else {
return Err(Error::InvalidFormat(format!(
"{}: the file name is not valid UTF-8",
display.display()
)));
};
let mut bytes = Vec::with_capacity(8 * 1024);
std::fs::File::from(fd)
.take(MAX_CONFIG_SIZE + 1)
.read_to_end(&mut bytes)
.map_err(|err| io_error(display, err))?;
if bytes.len() as u64 > MAX_CONFIG_SIZE {
return Err(Error::InvalidFormat(format!(
"{} exceeds the {MAX_CONFIG_SIZE}-byte size cap",
display.display()
)));
}
let text = std::str::from_utf8(&bytes).map_err(|_| {
Error::InvalidFormat(format!(
"{}: the content is not valid UTF-8",
display.display()
))
})?;
let keyfile = KeyFile::parse(text)
.map_err(|err| Error::InvalidFormat(format!("{}: {err}", display.display())))?;
Ok(Some(RemoteFile {
name: name.to_owned(),
keyfile,
}))
}
pub(crate) struct DirWriter<'a> {
repo_fd: BorrowedFd<'a>,
dir: &'a RemotesDir,
fd: Option<OwnedFd>,
fsync: bool,
repo_mode: RepoMode,
}
impl DirWriter<'_> {
fn path(&self, file: &str) -> PathBuf {
display_base(self.dir).join(file)
}
pub(crate) fn check_size(&self, file: &str, bytes: &[u8]) -> Result<()> {
if bytes.len() as u64 > MAX_CONFIG_SIZE {
return Err(Error::InvalidFormat(format!(
"{} exceeds the {MAX_CONFIG_SIZE}-byte size cap",
self.path(file).display()
)));
}
Ok(())
}
pub(crate) fn put(&self, file: &str, bytes: &[u8], how: Publish) -> Result<()> {
self.check_size(file, bytes)?;
let created;
let dir_fd = match &self.fd {
Some(fd) => fd.as_fd(),
None => {
let (base, at) = locate(self.repo_fd, self.dir);
let in_repo = matches!(self.dir, RemotesDir::InRepo(_));
created = ensure_named_dir(base, at, in_repo, self.repo_mode, self.fsync)
.map_err(|err| fs_error(at, err))?;
created.as_fd()
}
};
let path = self.path(file);
match put_named(dir_fd, file, bytes, how, self.fsync) {
Ok(Published::Created) => Ok(()),
Ok(Published::Existed) => Err(io_error(&path, Errno::EXIST)),
Err(err) => Err(fs_error(&path, err)),
}
}
pub(crate) fn remove(&self, file: &str) -> Result<()> {
let removed = match &self.fd {
Some(fd) => remove_named(fd.as_fd(), file, self.fsync),
None => Err(FsError::Absent {
path: file.to_owned(),
}),
};
removed.map_err(|err| fs_error(&self.path(file), err))
}
}
fn fs_error(display: &Path, err: FsError) -> Error {
match err {
FsError::Io(err) => io_error(display, err),
FsError::Invalid { reason, .. } => {
Error::InvalidFormat(format!("{} {reason}", display.display()))
}
FsError::Absent { .. } => Error::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{} does not exist", display.display()),
)),
FsError::Exists => io_error(display, Errno::EXIST),
}
}
#[cfg(test)]
mod tests {
use super::*;
const CORE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
fn key(extra: &str) -> Result<Option<RemotesDir>> {
from_key(&RepoConfig::parse(&format!("{CORE}{extra}")).unwrap())
}
#[test]
fn the_key_gives_a_path_an_in_repo_value_or_a_refusal() {
assert!(key("").unwrap().is_none());
assert!(matches!(
key("[ex-ostrya]\nremotes-config-dir=/etc/remotes.d\n").unwrap(),
Some(RemotesDir::Path(p)) if p == Path::new("/etc/remotes.d")
));
assert!(matches!(
key("[ex-ostrya]\nremotes-config-dir=remotes.d\n").unwrap(),
Some(RemotesDir::InRepo(p)) if p == Path::new("remotes.d")
));
assert!(matches!(
key("[ex-ostrya]\nremotes-config-dir=\\sa b\n").unwrap(),
Some(RemotesDir::InRepo(p)) if p == Path::new(" a b")
));
for empty in ["remotes-config-dir=\n", "remotes-config-dir= \n"] {
let err = key(&format!("[ex-ostrya]\n{empty}")).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m.contains("empty")),
"{err}"
);
}
let err = key("[ex-ostrya]\nremotes-config-dir=a\0b\n").unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m.contains("NUL")),
"{err}"
);
let err = key("[ex-ostrya]\nremotes-config-dir=a\\qb\n").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
}
}