use core::convert::Infallible;
use std::io;
use std::os::fd::{AsRawFd as _, IntoRawFd as _};
use std::path::Path;
use std::time::Duration;
use shep_core::paths::ShepPaths;
use shep_handover::{Arrival, BootError, HandOverError, Verdict};
pub use shep_handover::{exec_target, record_launch_path};
use super::blob::{Handover, OLDEST_READABLE, VERSION, reads_version};
use crate::sys::OpenFd;
pub const HANDOVER_ENV: &str = "SHEP_HANDOVER";
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
pub fn hand_over(blob: &Handover, paths: &ShepPaths) -> Result<Infallible, HandOverError> {
hand_over_tuned(blob, paths, |handover| {
handover.probe_timeout(PROBE_TIMEOUT)
})
}
fn hand_over_tuned(
blob: &Handover,
paths: &ShepPaths,
tune: impl for<'a> FnOnce(
shep_handover::Handover<'a, Handover>,
) -> shep_handover::Handover<'a, Handover>,
) -> Result<Infallible, HandOverError> {
let mut open = Vec::new();
for number in blob.carried_fds() {
let fd = OpenFd::new(number).map_err(|source| HandOverError::Descriptor {
key: number.to_string(),
source: io::Error::new(io::ErrorKind::InvalidInput, source),
})?;
open.push((number.to_string(), fd));
}
let mut handover = shep_handover::Handover::new(blob).blob_dir(&paths.run);
for (key, fd) in &open {
handover = handover.carry(key.clone(), fd);
}
tune(handover).exec(&|_: &Path| Verdict::Carryable)
}
pub fn arrive() -> Result<Option<Arrival<Handover>>, BootError> {
shep_handover::boot::<Handover>()
}
pub fn claim(arrival: Arrival<Handover>) -> io::Result<Handover> {
let Arrival {
state: mut blob,
mut fds,
} = arrival;
let mut problem = (!reads_version(blob.version)).then(|| {
format!(
"the handover blob is format version {}, and this shep implements versions \
{OLDEST_READABLE} to {VERSION}",
blob.version
)
});
for number in blob.named_fds() {
match fds.take(&number.to_string()) {
Some(carried) => {
let owned = carried.into_owned_fd();
if owned.as_raw_fd() != number {
problem.get_or_insert_with(|| {
format!(
"the descriptor carried as '{number}' arrived as {}",
owned.as_raw_fd()
)
});
}
let _ = owned.into_raw_fd();
}
None => {
problem.get_or_insert_with(|| {
format!("the blob names descriptor {number}, which was not carried under it")
});
}
}
}
for socket in blob.listeners.iter_mut().flatten() {
let number = socket.fd();
socket.unclaimed = match fds.take(&number.to_string()) {
Some(carried) => {
let owned = carried.into_owned_fd();
let arrived = owned.as_raw_fd() == number;
if arrived {
let _ = owned.into_raw_fd();
}
!arrived
}
None => true,
};
}
problem.map_or(Ok(blob), |problem| {
Err(io::Error::new(io::ErrorKind::InvalidData, problem))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::entry::ProcessEntry;
use crate::handover::fixtures::entry_fixture;
use crate::handover::{CarriedFds, CarriedSheep};
use shep_handover::Carried;
use std::path::PathBuf;
#[test]
fn the_exec_target_exists_and_is_a_file() {
let p = exec_target().unwrap();
assert!(p.is_file(), "{}", p.display());
}
const SELFTEST_HOME: &str = "SHEP_HANDOVER_SELFTEST";
const SELFTEST_NAME: &str = "handover::exec::tests::a_flock_crosses_the_exec_and_is_claimed";
fn handover_with_fds(
entry: &ProcessEntry,
listener_fd: std::os::fd::RawFd,
pidfile_fd: std::os::fd::RawFd,
fds: CarriedFds,
) -> Handover {
Handover {
version: VERSION,
sheep: vec![CarriedSheep::from_entry(
entry, 7, fds, false, None, false, None,
)],
listener_fd,
pidfile_fd,
next_id: 9,
next_deadline: 5,
next_action_stamp: 2,
reloads: Some(Vec::new()),
listeners: None,
}
}
fn selftest_paths(home: &Path) -> ShepPaths {
let home = home.display().to_string();
let paths = ShepPaths::resolve(
&|key| (key == "SHEP_HOME").then(|| home.clone()),
Path::new("/nonexistent"),
);
std::fs::create_dir_all(&paths.run).unwrap();
paths
}
#[test]
fn a_flock_crosses_the_exec_and_is_claimed() {
if let Some(arrival) = arrive().expect("a successor can arrive") {
successor_stage(arrival);
}
if let Some(home) = std::env::var_os(SELFTEST_HOME) {
exec_stage(Path::new(&home));
}
let dir = tempfile::tempdir().unwrap();
let out = std::process::Command::new(std::env::current_exe().unwrap())
.arg(SELFTEST_NAME)
.arg("--exact")
.arg("--nocapture")
.env(SELFTEST_HOME, dir.path())
.env_remove(HANDOVER_ENV)
.env_remove(shep_handover::HANDOVER_ENV)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
out.status.success(),
"{stdout}{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(
stdout.contains("running 1 test"),
"the child ran no test, so `{SELFTEST_NAME}` is not where this test lives any more; \
`--exact` needs the full path and nothing updates it automatically: {stdout}"
);
assert!(stdout.contains("adopted: hello"), "{stdout}");
}
fn exec_stage(home: &Path) -> ! {
use std::io::Write as _;
let paths = selftest_paths(home);
let (reader, mut writer) = std::io::pipe().unwrap();
writer.write_all(b"hello").unwrap();
drop(writer);
let listener = tempfile::tempfile().unwrap();
let pidfile = tempfile::tempfile().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
listener.as_raw_fd(),
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: Some(reader.as_raw_fd()),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
dog_link: None,
pty: None,
},
);
let err = hand_over(&blob, &paths).unwrap_err();
panic!("the exec should not have returned: {err}");
}
fn successor_stage(arrival: Arrival<Handover>) -> ! {
let blob = claim(arrival).expect("the flock is claimed");
let fd = blob.sheep[0].fds.out_pipe.expect("a carried stdout pipe");
let mut buf = [0_u8; 16];
let read = nix::unistd::read(fd, &mut buf).expect("the carried descriptor is open");
println!("adopted: {}", String::from_utf8_lossy(&buf[..read]));
std::process::exit(0);
}
#[test]
fn a_descriptor_the_blob_names_and_this_image_does_not_have_is_refused_before_the_exec() {
let dir = tempfile::tempdir().unwrap();
let paths = selftest_paths(dir.path());
let pidfile = tempfile::tempfile().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
9_999,
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
dog_link: None,
pty: None,
},
);
let err = hand_over(&blob, &paths).unwrap_err();
assert!(
matches!(&err, HandOverError::Descriptor { key, .. } if key == "9999"),
"{err}"
);
assert!(std::fs::read_dir(&paths.run).unwrap().next().is_none());
}
struct FiveKinds {
listener: std::fs::File,
pidfile: std::fs::File,
out_log: std::fs::File,
stdin: std::io::PipeWriter,
channel: std::os::unix::net::UnixStream,
_peers: (std::io::PipeReader, std::os::unix::net::UnixStream),
}
impl FiveKinds {
fn new() -> Self {
let (child_end, stdin) = std::io::pipe().unwrap();
let (channel, child_channel) = std::os::unix::net::UnixStream::pair().unwrap();
Self {
listener: tempfile::tempfile().unwrap(),
pidfile: tempfile::tempfile().unwrap(),
out_log: tempfile::tempfile().unwrap(),
stdin,
channel,
_peers: (child_end, child_channel),
}
}
fn all(&self) -> [std::os::fd::BorrowedFd<'_>; 5] {
use std::os::fd::AsFd as _;
[
self.listener.as_fd(),
self.pidfile.as_fd(),
self.out_log.as_fd(),
self.stdin.as_fd(),
self.channel.as_fd(),
]
}
fn blob(&self) -> Handover {
handover_with_fds(
&entry_fixture(|_| {}),
self.listener.as_raw_fd(),
self.pidfile.as_raw_fd(),
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: Some(self.out_log.as_raw_fd()),
err_log: None,
stdin: Some(self.stdin.as_raw_fd()),
channel: Some(self.channel.as_raw_fd()),
dog_link: None,
pty: None,
},
)
}
}
fn is_close_on_exec(fd: std::os::fd::BorrowedFd<'_>) -> bool {
use nix::fcntl::{FcntlArg, FdFlag, fcntl};
let flags = fcntl(std::os::fd::AsRawFd::as_raw_fd(&fd), FcntlArg::F_GETFD).unwrap();
FdFlag::from_bits_retain(flags).contains(FdFlag::FD_CLOEXEC)
}
#[test]
fn the_blob_names_the_listener_the_pidfile_and_each_sheeps_descriptors() {
let kinds = FiveKinds::new();
let mut named: Vec<_> = kinds.blob().named_fds().collect();
named.sort_unstable();
let mut expected = kinds.all().map(|fd| std::os::fd::AsRawFd::as_raw_fd(&fd));
expected.sort_unstable();
assert_eq!(named, expected);
}
fn failed_handover(kinds: &FiveKinds, paths: &ShepPaths, target: &Path) -> HandOverError {
hand_over_tuned(&kinds.blob(), paths, |handover| {
handover.target(target).unprobed()
})
.unwrap_err()
}
fn failed_exec_sandbox() -> (tempfile::TempDir, ShepPaths, PathBuf, FiveKinds) {
let dir = tempfile::tempdir().unwrap();
let paths = selftest_paths(dir.path());
let target = dir.path().join("not-a-binary");
std::fs::write(&target, "this will never execute").unwrap();
let kinds = FiveKinds::new();
(dir, paths, target, kinds)
}
#[test]
fn a_failed_exec_leaves_no_blob_behind() {
let (_dir, paths, target, kinds) = failed_exec_sandbox();
let err = failed_handover(&kinds, &paths, &target);
assert!(
std::fs::read_dir(&paths.run).unwrap().next().is_none(),
"a failed exec left a blob behind: {err}"
);
}
#[test]
fn a_failed_exec_makes_every_descriptor_close_on_exec_again() {
let (_dir, paths, target, kinds) = failed_exec_sandbox();
for fd in kinds.all() {
assert!(is_close_on_exec(fd), "the daemon opens everything so");
}
let err = failed_handover(&kinds, &paths, &target);
assert!(matches!(err, HandOverError::Exec(_)), "{err}");
for fd in kinds.all() {
assert!(
is_close_on_exec(fd),
"a handover that failed left a descriptor open to every child: {err}"
);
}
}
#[test]
fn an_arrival_that_carried_nothing_is_refused_by_the_numbers_the_blob_names() {
let pidfile = tempfile::tempfile().unwrap();
let listener = tempfile::tempfile().unwrap();
let blob = handover_with_fds(
&entry_fixture(|_| {}),
listener.as_raw_fd(),
pidfile.as_raw_fd(),
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
dog_link: None,
pty: None,
},
);
let err = claim(Arrival {
state: blob,
fds: Carried::default(),
})
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("which was not carried"), "{err}");
}
#[test]
fn a_blob_in_a_version_this_image_does_not_implement_is_refused() {
let mut blob = handover_with_fds(
&entry_fixture(|_| {}),
-1,
-1,
CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
dog_link: None,
pty: None,
},
);
blob.version = VERSION + 1;
blob.sheep.clear();
let err = claim(Arrival {
state: blob,
fds: Carried::default(),
})
.unwrap_err();
assert!(err.to_string().contains("versions 1 to 2"), "{err}");
}
#[test]
fn the_blobs_format_is_its_version() {
use shep_handover::State as _;
assert_eq!(Handover::FORMAT, VERSION);
assert!(Handover::reads(VERSION));
assert!(Handover::reads(OLDEST_READABLE));
assert!(!Handover::reads(OLDEST_READABLE - 1));
assert!(!Handover::reads(VERSION + 1));
}
}