use std::ffi::{OsStr, OsString};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::Path;
use super::protocol::Errno;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Candidate {
Missing,
Directory,
NotExecutable,
Executable,
Failed(i32),
}
pub(crate) fn resolve(program: &OsStr, path: Option<&OsStr>) -> Result<Vec<OsString>, Errno> {
resolve_with(program, path, probe_fs)
}
pub(crate) fn resolve_with(
program: &OsStr,
path: Option<&OsStr>,
mut probe: impl FnMut(&Path) -> Candidate,
) -> Result<Vec<OsString>, Errno> {
let name = program.as_bytes();
if name.contains(&b'/') {
return Ok(vec![program.to_owned()]);
}
if name.is_empty() {
return Err(Errno(libc::ENOENT));
}
let default;
let path = match path {
Some(path) => path,
None => {
default = default_path();
&default
}
};
let mut candidates = Vec::new();
let mut remembered = false;
let mut decided = None;
for element in path.as_bytes().split(|&b| b == b':') {
if !element.starts_with(b"/") {
continue;
}
let mut candidate = element.to_vec();
candidate.push(b'/');
candidate.extend_from_slice(name);
let candidate = OsString::from_vec(candidate);
if decided.is_none() {
match probe(Path::new(&candidate)) {
Candidate::Executable => decided = Some(Ok(())),
Candidate::Failed(errno) => decided = Some(Err(Errno(errno))),
Candidate::Directory | Candidate::NotExecutable => remembered = true,
Candidate::Missing => {}
}
}
candidates.push(candidate);
}
match decided {
Some(Ok(())) => Ok(candidates),
Some(Err(errno)) => Err(errno),
None => Err(Errno(if remembered { libc::EACCES } else { libc::ENOENT })),
}
}
fn default_path() -> OsString {
let size = unsafe { libc::confstr(libc::_CS_PATH, std::ptr::null_mut(), 0) };
if size == 0 {
return OsString::new();
}
let mut buf = vec![0u8; size];
let written = unsafe { libc::confstr(libc::_CS_PATH, buf.as_mut_ptr().cast(), buf.len()) };
debug_assert_eq!(written, size, "confstr gave a different size the second time");
buf.truncate(size.saturating_sub(1));
OsString::from_vec(buf)
}
fn probe_fs(path: &Path) -> Candidate {
use rustix::fs::{accessat, stat, Access, AtFlags, FileType, CWD};
let stat = match stat(path) {
Ok(stat) => stat,
Err(e) => return classify(path, e.raw_os_error()),
};
if FileType::from_raw_mode(stat.st_mode) == FileType::Directory {
return Candidate::Directory;
}
match accessat(CWD, path, Access::EXEC_OK, AtFlags::EACCESS) {
Ok(()) => Candidate::Executable,
Err(e) => classify(path, e.raw_os_error()),
}
}
fn classify(path: &Path, errno: i32) -> Candidate {
match errno {
libc::ENOENT | libc::ENOTDIR | libc::ESTALE | libc::ENODEV | libc::ETIMEDOUT => Candidate::Missing,
libc::EACCES => Candidate::NotExecutable,
libc::ELOOP | libc::ENAMETOOLONG | libc::EIO => Candidate::Failed(errno),
other => {
log::warn!(
"the shim's search of {}: unexpected errno {other}; it ends the search",
path.display()
);
Candidate::Failed(other)
}
}
}
#[cfg(test)]
#[path = "program_path_tests.rs"]
mod program_path_tests;