use core::fmt;
use std::collections::BTreeMap;
use std::io;
use std::path::{Path, PathBuf};
use tokio::sync::{mpsc, oneshot};
use shep_core::signals::OperatorSignal;
use crate::channel::{ChildMessage, ShepherdMessage};
use crate::privilege::Credentials;
#[cfg(unix)]
pub use crate::handover::reap::AdoptedReaper;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExitOutcome {
pub code: Option<i32>,
pub signal: Option<i32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopSignal {
Term,
Int,
Quit,
Usr2,
Kill,
}
impl StopSignal {
#[must_use]
pub fn as_raw(self) -> i32 {
match self {
Self::Term => 15,
Self::Int => 2,
Self::Quit => 3,
Self::Usr2 => 12,
Self::Kill => 9,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogLine {
pub err: bool,
pub line: String,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum LogCtl {
Reopen {
done: oneshot::Sender<Result<(), ReopenError>>,
},
Flush {
done: oneshot::Sender<Result<(), FlushError>>,
},
#[cfg(unix)]
ReportFds {
done: oneshot::Sender<crate::handover::CarriedFds>,
},
#[cfg(unix)]
Resume,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReopenError {
pub message: String,
}
impl fmt::Display for ReopenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "could not reopen {}", self.message)
}
}
impl core::error::Error for ReopenError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlushError {
pub message: String,
}
impl fmt::Display for FlushError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "could not flush {}", self.message)
}
}
impl core::error::Error for FlushError {}
#[cfg_attr(windows, allow(dead_code))]
pub(crate) const SYMLINK_REFUSED: &str = "refusing to follow a symlink at this log path; shep \
opens log files with O_NOFOLLOW, so point out_file/err_file at the real file";
pub(crate) async fn open_log_path(
options: &mut tokio::fs::OpenOptions,
path: &Path,
) -> io::Result<tokio::fs::File> {
#[cfg(unix)]
options.custom_flags(nix::libc::O_NOFOLLOW);
options.open(path).await.map_err(name_the_symlink)
}
#[cfg(unix)]
fn name_the_symlink(error: io::Error) -> io::Error {
if error.raw_os_error() == Some(nix::libc::ELOOP) {
io::Error::new(error.kind(), SYMLINK_REFUSED)
} else {
error
}
}
#[cfg(not(unix))]
fn name_the_symlink(error: io::Error) -> io::Error {
error
}
pub(crate) fn check_log_ancestry(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
check_log_ancestry_as(path, crate::server::daemon_uid())
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
#[cfg(unix)]
const ROOT_UID: u32 = 0;
#[cfg(unix)]
const WORLD_WRITABLE: u32 = 0o002;
#[cfg(unix)]
static WARNED_LOOSE_LOG_PATHS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashSet<PathBuf>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
#[cfg(unix)]
fn check_log_ancestry_as(path: &Path, daemon_uid: u32) -> io::Result<()> {
let Some(loose) = loose_ancestor(path, daemon_uid) else {
return Ok(());
};
if daemon_uid == ROOT_UID {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"refusing to open a log file below {}, which {}; a shepherd running as root \
writes only below directories its own user owns",
loose.path.display(),
loose.reason,
),
));
}
let first_time = WARNED_LOOSE_LOG_PATHS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(path.to_path_buf());
if first_time {
tracing::warn!(
path = %path.display(),
ancestor = %loose.path.display(),
reason = %loose.reason,
"log path sits below a directory another local user could redirect; a shepherd \
running as root would refuse to open it"
);
}
Ok(())
}
#[cfg(unix)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct LooseAncestor {
path: PathBuf,
reason: LooseReason,
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LooseReason {
ForeignOwner(u32),
WorldWritable,
}
#[cfg(unix)]
impl fmt::Display for LooseReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ForeignOwner(uid) => write!(f, "is owned by uid {uid}"),
Self::WorldWritable => f.write_str("is world-writable"),
}
}
}
#[cfg(unix)]
fn loose_ancestor(path: &Path, daemon_uid: u32) -> Option<LooseAncestor> {
use std::os::unix::fs::MetadataExt as _;
path.parent()?
.ancestors()
.filter_map(|ancestor| Some((ancestor, std::fs::symlink_metadata(ancestor).ok()?)))
.find_map(|(ancestor, meta)| {
let reason = if meta.uid() != daemon_uid && meta.uid() != ROOT_UID {
LooseReason::ForeignOwner(meta.uid())
} else if meta.is_dir() && meta.mode() & WORLD_WRITABLE != 0 {
LooseReason::WorldWritable
} else {
return None;
};
Some(LooseAncestor {
path: ancestor.to_path_buf(),
reason,
})
})
}
#[derive(Debug)]
pub struct ProcIo {
pub logs: mpsc::Receiver<LogLine>,
pub from_child: mpsc::Receiver<ChildMessage>,
pub to_child: mpsc::Sender<ShepherdMessage>,
pub log_ctl: mpsc::Sender<LogCtl>,
pub to_stdin: mpsc::Sender<StdinWrite>,
}
#[derive(Debug)]
pub struct StdinWrite {
pub line: String,
pub done: oneshot::Sender<Result<(), RunnerError>>,
}
pub trait RunningProcess: Send + 'static {
fn pid(&self) -> u32;
fn wait(&mut self) -> impl core::future::Future<Output = ExitOutcome> + Send;
fn signal(&mut self, sig: StopSignal) -> Result<(), RunnerError>;
fn signal_process(&mut self, sig: OperatorSignal) -> Result<(), RunnerError> {
let _ = sig;
Err(RunnerError::SignalFailed(
"this runner cannot signal a single process".to_string(),
))
}
fn kill_tree(&mut self) -> Result<(), RunnerError>;
}
pub trait ProcessRunner: Send + Sync + 'static {
type Proc: RunningProcess;
fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError>;
#[must_use]
fn preflight(&self, spec: &SpawnSpec) -> Preflight {
let _ = spec;
Preflight::Unknown
}
#[cfg(unix)]
fn adopt(&self, spec: AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
let _ = spec;
Err(RunnerError::AdoptFailed(
"this runner cannot adopt a process it did not spawn".to_string(),
))
}
}
#[cfg(unix)]
#[derive(Debug)]
pub struct AdoptSpec {
pub pid: u32,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub out_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub err_pipe: Option<tokio::net::unix::pipe::Receiver>,
pub out_log: Option<tokio::fs::File>,
pub err_log: Option<tokio::fs::File>,
pub stdin_pipe: Option<tokio::net::unix::pipe::Sender>,
pub channel: Option<tokio::net::UnixStream>,
pub reaper: std::sync::Arc<AdoptedReaper>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preflight {
Unknown,
Impossible(String),
Doubtful(String),
}
#[derive(Clone, PartialEq, Eq)]
pub struct SpawnSpec {
pub name: String,
pub program: String,
pub args: Vec<String>,
pub cwd: Option<PathBuf>,
pub env: BTreeMap<String, String>,
pub out_file: PathBuf,
pub err_file: PathBuf,
pub channel: bool,
pub stdin: bool,
pub credentials: Option<Credentials>,
}
impl fmt::Debug for SpawnSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SpawnSpec")
.field("name", &self.name)
.field("program", &self.program)
.field("args", &format_args!("<{} args>", self.args.len()))
.field("cwd", &self.cwd)
.field("env", &format_args!("<{} vars>", self.env.len()))
.finish_non_exhaustive()
}
}
fn missing_directory(path: &Path) -> Option<&'static str> {
match std::fs::metadata(path) {
Ok(meta) if meta.is_dir() => None,
Ok(_) => Some("exists but is not a directory"),
Err(err) if err.kind() == io::ErrorKind::NotFound => Some("does not exist yet"),
Err(_) => None,
}
}
#[must_use]
pub(crate) fn cwd_advisory(cwd: &Path) -> Option<String> {
#[cfg(windows)]
{
if let Some(reason) = windows_name_advisory(cwd) {
return Some(format!("{} {reason}", cwd.display()));
}
}
let reason = missing_directory(cwd)?;
Some(format!("{} {reason}", cwd.display()))
}
#[must_use]
pub(crate) fn log_path_advisory(path: &Path) -> Option<String> {
#[cfg(windows)]
{
if let Some(reason) = windows_name_advisory(path) {
return Some(format!("{} {reason}", path.display()));
}
}
if matches!(std::fs::metadata(path), Ok(meta) if meta.is_dir()) {
return Some(format!("{} is a directory, not a log file", path.display()));
}
let parent = path.parent().filter(|p| !p.as_os_str().is_empty())?;
let reason = missing_directory(parent)?;
Some(format!("{} {reason}", parent.display()))
}
#[cfg(windows)]
#[must_use]
fn windows_name_advisory(path: &Path) -> Option<String> {
use std::os::windows::ffi::OsStrExt as _;
const ILLEGAL: &[char] = &['<', '>', ':', '"', '|', '?', '*'];
const RESERVED: &[&str] = &[
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
"COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
const MAX_PATH: usize = 260;
let length = path.as_os_str().encode_wide().count();
if length >= MAX_PATH {
return Some(format!(
"is {length} characters, at or over Windows' {MAX_PATH}-character default limit"
));
}
for component in path.components() {
let std::path::Component::Normal(part) = component else {
continue;
};
let Some(name) = part.to_str() else {
continue;
};
if let Some(bad) = name.chars().find(|c| ILLEGAL.contains(c)) {
return Some(format!("contains `{bad}`, which Windows refuses in a path"));
}
if let Some(control) = name.chars().find(|&c| (c as u32) < 0x20) {
return Some(format!(
"contains U+{:04X}, a control character Windows refuses in a path",
control as u32
));
}
let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
if RESERVED
.iter()
.any(|reserved| reserved.eq_ignore_ascii_case(stem))
{
return Some(format!("names `{name}`, a reserved Windows device name"));
}
}
None
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunnerError {
SpawnFailed(String),
SignalFailed(String),
WriteFailed(String),
AdoptFailed(String),
}
impl fmt::Display for RunnerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SpawnFailed(msg) => write!(f, "process spawn failed: {msg}"),
Self::SignalFailed(msg) => write!(f, "signal delivery failed: {msg}"),
Self::WriteFailed(msg) => write!(f, "stdin write failed: {msg}"),
Self::AdoptFailed(msg) => write!(f, "process adoption failed: {msg}"),
}
}
}
impl core::error::Error for RunnerError {}
#[cfg(all(test, unix))]
mod tests {
use std::os::unix::fs::PermissionsExt as _;
use super::*;
use crate::testing::capture_logs;
const FOREIGN_UID: u32 = 65_432;
fn me() -> u32 {
nix::unistd::geteuid().as_raw()
}
fn log_path_under(dir: &tempfile::TempDir, mode: u32) -> (PathBuf, PathBuf) {
let parent = dir.path().join("logs");
std::fs::create_dir(&parent).unwrap();
std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(mode)).unwrap();
let log = parent.join("web-0-out.log");
(parent, log)
}
#[test]
fn the_nearest_loose_ancestor_is_the_one_reported() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o777);
assert_eq!(
loose_ancestor(&log, me()),
Some(LooseAncestor {
path: parent,
reason: LooseReason::WorldWritable,
})
);
}
#[test]
fn an_ancestor_owned_by_another_user_is_loose_however_tight_its_mode() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o700);
let (daemon_uid, owner) = if me() == ROOT_UID {
std::os::unix::fs::chown(&parent, Some(FOREIGN_UID), None).unwrap();
(ROOT_UID, FOREIGN_UID)
} else {
(me() + 1, me())
};
assert_eq!(
loose_ancestor(&log, daemon_uid),
Some(LooseAncestor {
path: parent,
reason: LooseReason::ForeignOwner(owner),
})
);
}
#[test]
fn a_symlinked_component_is_judged_as_the_link_not_as_its_target() {
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("logs");
std::os::unix::fs::symlink("/usr", &link).unwrap();
let log = link.join("web-0-out.log");
let loose = loose_ancestor(&log, me() + 1).expect("a foreign-owned component is loose");
assert_eq!(
loose.path,
link,
"the link itself must be judged, not what it resolves to: blaming {} means the \
walk followed it",
loose.path.display()
);
}
#[test]
fn a_root_shepherd_refuses_where_an_unprivileged_one_warns_once() {
let dir = tempfile::tempdir().unwrap();
let (parent, log) = log_path_under(&dir, 0o777);
let refused = check_log_ancestry_as(&log, ROOT_UID)
.expect_err("a root shepherd must not open a log below a loose ancestor");
assert_eq!(refused.kind(), io::ErrorKind::PermissionDenied);
assert!(
refused.to_string().contains(&parent.display().to_string()),
"the refusal must name the ancestor an operator has to fix: {refused}"
);
let unprivileged = me() + 1;
let rendered = capture_logs(|| {
assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
assert_eq!(check_log_ancestry_as(&log, unprivileged).ok(), Some(()));
});
assert_eq!(
rendered.matches("log path sits below").count(),
1,
"an unprivileged shepherd warns once per path, not once per open: {rendered}"
);
}
#[test]
fn debug_redacts_env_values_and_args() {
let mut spec = SpawnSpec {
name: "web".to_string(),
program: "./srv".to_string(),
args: vec!["--token=sk-live-abc".to_string(), "--port=8080".to_string()],
cwd: None,
env: BTreeMap::new(),
out_file: PathBuf::from("/tmp/web-out.log"),
err_file: PathBuf::from("/tmp/web-err.log"),
channel: false,
stdin: false,
credentials: None,
};
spec.env.insert(
"DATABASE_URL".to_string(),
"postgres://user:hunter2@db".to_string(),
);
spec.env
.insert("API_KEY".to_string(), "sk-live-abc".to_string());
assert_eq!(
format!("{spec:?}"),
"SpawnSpec { name: \"web\", program: \"./srv\", args: <2 args>, cwd: None, \
env: <2 vars>, .. }"
);
}
}
#[cfg(test)]
mod path_advisory_tests {
use super::*;
#[test]
fn a_cwd_that_exists_gets_no_warning() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(cwd_advisory(dir.path()), None);
}
#[test]
fn a_cwd_that_does_not_exist_yet_is_named() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("not-created-yet");
let warning = cwd_advisory(&missing).expect("a missing cwd warns");
assert!(warning.contains("does not exist"), "{warning}");
assert!(
warning.contains(&missing.display().to_string()),
"names the path: {warning}"
);
}
#[test]
fn a_cwd_that_is_a_file_is_named() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("not-a-dir");
std::fs::write(&file, b"").unwrap();
let warning = cwd_advisory(&file).expect("a file where a directory is meant warns");
assert!(warning.contains("is not a directory"), "{warning}");
}
#[test]
fn a_log_path_whose_parent_exists_gets_no_warning() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("web-out.log");
assert_eq!(
log_path_advisory(&log),
None,
"the file itself need not exist yet; `open_log_path` creates it"
);
}
#[test]
fn a_log_path_whose_parent_does_not_exist_yet_is_named() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("not-created-yet").join("web-out.log");
let warning = log_path_advisory(&log).expect("a missing parent warns");
assert!(warning.contains("does not exist"), "{warning}");
}
#[test]
fn a_log_path_whose_parent_is_a_file_is_named() {
let dir = tempfile::tempdir().unwrap();
let parent = dir.path().join("not-a-directory");
std::fs::write(&parent, b"").unwrap();
let warning =
log_path_advisory(&parent.join("web-out.log")).expect("a parent that is a file warns");
assert!(
warning.contains("exists but is not a directory"),
"{warning}"
);
}
#[test]
fn a_log_path_that_is_already_a_directory_is_named() {
let dir = tempfile::tempdir().unwrap();
let warning =
log_path_advisory(dir.path()).expect("a directory where a file is meant warns");
assert!(
warning.contains("is a directory, not a log file"),
"{warning}"
);
}
}
#[cfg(all(test, windows))]
mod windows_advisory_tests {
use super::*;
#[test]
fn a_reserved_device_name_is_named_regardless_of_extension() {
let warning = windows_name_advisory(Path::new(r"C:\logs\CON.log"))
.expect("CON is reserved regardless of extension");
assert!(
warning.contains("reserved Windows device name"),
"{warning}"
);
}
#[test]
fn a_second_dot_takes_a_name_back_out_of_the_reserved_set() {
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\CON.my.txt")),
None,
"CON.my is not a device name"
);
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\NUL.my.log")),
None,
"NUL.my is not a device name"
);
assert!(
windows_name_advisory(Path::new(r"C:\logs\CON.txt")).is_some(),
"one dot still leaves CON reserved"
);
}
#[test]
fn the_path_limit_counts_utf16_units_not_bytes() {
let under = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(120));
assert_eq!(
windows_name_advisory(Path::new(&under)),
None,
"252 units is under the limit, though the same path is 492 bytes"
);
let over = format!(r"C:\logs\{}.log", "\u{1f411}".repeat(130));
let warning = windows_name_advisory(Path::new(&over)).expect("260 units is at the limit");
assert!(warning.contains("260-character"), "{warning}");
}
#[test]
fn a_control_character_is_named_by_code_point_and_c1_is_not() {
let warning = windows_name_advisory(Path::new("C:\\logs\\web\tout.log"))
.expect("a tab is refused anywhere in a Windows path");
assert!(warning.contains("U+0009"), "{warning}");
assert!(!warning.contains('\t'), "{warning}");
assert_eq!(
windows_name_advisory(Path::new("C:\\logs\\web\u{85}out.log")),
None,
"U+0085 is a C1 control that Windows accepts in a file name"
);
}
#[test]
fn an_ordinary_path_gets_no_warning() {
assert_eq!(
windows_name_advisory(Path::new(r"C:\logs\web-out.log")),
None
);
}
#[test]
fn an_illegal_character_is_named() {
let warning = windows_name_advisory(Path::new(r"C:\logs\web?out.log"))
.expect("`?` is refused anywhere in a Windows path");
assert!(warning.contains('?'), "{warning}");
}
#[test]
fn an_over_length_path_is_named() {
let long = format!(r"C:\{}", "a".repeat(300));
let warning =
windows_name_advisory(Path::new(&long)).expect("300 characters is over MAX_PATH");
assert!(warning.contains("260-character"), "{warning}");
}
}