use std::ffi::OsStr;
use std::fs::File;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use khive_fs::directory_walk::{
read_link_at, walk_to_directory, AncestorLinkCondition, AncestorLinkPolicy,
AncestorLinkRefusal, AncestorWalkEndpoint, BudgetExhausted, LinkContext, LinkPolicy,
ANCESTOR_LINK_BUDGET,
};
use khive_fs::fd_relative::open_dir_at;
#[cfg(test)]
use khive_fs::fd_relative::stat_at;
struct MirrorAncestorLinks {
shared: AncestorLinkPolicy,
}
impl MirrorAncestorLinks {
fn new() -> Self {
Self {
shared: AncestorLinkPolicy::new(AncestorWalkEndpoint::FinalTarget),
}
}
}
impl LinkPolicy for MirrorAncestorLinks {
fn before_follow(&mut self, ctx: &LinkContext<'_>) -> std::io::Result<()> {
if let Err(error) = self.shared.before_follow(ctx) {
let final_component = error
.get_ref()
.and_then(|inner| inner.downcast_ref::<AncestorLinkRefusal>())
.is_some_and(|refusal| refusal.condition == AncestorLinkCondition::FinalComponent);
if final_component {
return Err(match open_dir_at(ctx.parent, ctx.name) {
Err(error) => error,
Ok(_) => std::io::Error::from_raw_os_error(libc::ELOOP),
});
}
return Err(error);
}
Ok(())
}
fn after_read(&mut self, ctx: &LinkContext<'_>) -> std::io::Result<()> {
let target_length = read_link_length(ctx.parent, ctx.name)?;
if target_length == 0 || target_length == libc::PATH_MAX as usize {
return Err(std::io::Error::other(
"mirror source root ancestor symlink target is empty or too long",
));
}
self.shared.after_read(ctx)
}
}
fn read_link_length(parent: &File, name: &OsStr) -> std::io::Result<usize> {
match read_link_at(parent, name) {
Ok(target) => Ok(target.as_os_str().as_bytes().len()),
Err(error)
if error.kind() == std::io::ErrorKind::InvalidData
&& error.raw_os_error().is_none() =>
{
Err(std::io::Error::other(
"mirror source root ancestor symlink target is empty or too long",
))
}
Err(error) => Err(error),
}
}
fn root_walk_error(error: std::io::Error) -> std::io::Error {
if error
.get_ref()
.is_some_and(|inner| inner.is::<AncestorLinkRefusal>())
{
return error;
}
let budget_spent = error
.get_ref()
.is_some_and(|inner| inner.is::<BudgetExhausted>());
if budget_spent {
return std::io::Error::other("mirror source root exceeds the ancestor symlink limit");
}
if error.kind() == std::io::ErrorKind::InvalidInput && error.raw_os_error().is_none() {
return std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"mirror source root contains a NUL byte",
);
}
error
}
fn open_root_with<P: LinkPolicy>(root: &Path, policy: &mut P) -> std::io::Result<Vec<File>> {
let walked = walk_to_directory(root, policy, ANCESTOR_LINK_BUDGET);
walked.map_err(root_walk_error)
}
pub(super) fn open_source_root(root: &Path) -> std::io::Result<Vec<File>> {
let mut policy = MirrorAncestorLinks::new();
open_root_with(root, &mut policy)
}
#[cfg(test)]
#[path = "root_walk_tests.rs"]
mod tests;