use std::ffi::OsString;
use std::io::{Read as _, Write as _};
use std::os::unix::net::UnixStream;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use nix::sys::signal::{SigSet, Signal};
use rustix::event::{PollFd, PollFlags};
const ROOT_FLAG: &str = "--cosca-signal-tree-root";
const LEAF_FLAG: &str = "--cosca-signal-tree-leaf";
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
Reporting,
ThenTerm,
}
impl Mode {
fn name(self) -> &'static str {
match self {
Mode::Reporting => "reporting",
Mode::ThenTerm => "then-term",
}
}
fn parse(name: &str) -> Mode {
[Mode::Reporting, Mode::ThenTerm]
.into_iter()
.find(|mode| mode.name() == name)
.unwrap_or_else(|| die(&format!("no mode {name:?}")))
}
fn signals(self) -> &'static [Signal] {
match self {
Mode::Reporting => &[Signal::SIGHUP, Signal::SIGTERM, Signal::SIGUSR1, Signal::SIGUSR2],
Mode::ThenTerm => &[Signal::SIGUSR1, Signal::SIGTERM],
}
}
fn ends_on(self, signal: Signal) -> bool {
match self {
Mode::Reporting => true,
Mode::ThenTerm => signal == Signal::SIGTERM,
}
}
}
#[derive(Clone, Copy)]
enum Role {
Root,
Leaf,
}
impl Role {
fn name(self) -> &'static str {
match self {
Role::Root => "root",
Role::Leaf => "leaf",
}
}
}
pub(crate) fn run_if_requested() {
let args: Vec<OsString> = std::env::args_os().collect();
let role = match args.get(1) {
Some(flag) if flag == ROOT_FLAG => Role::Root,
Some(flag) if flag == LEAF_FLAG => Role::Leaf,
_ => return,
};
let mode = args
.get(2)
.and_then(|mode| mode.to_str())
.unwrap_or_else(|| die(&format!("no mode in {args:?}")));
run(role, Mode::parse(mode))
}
pub(crate) fn argv(mode: Mode) -> [&'static str; 2] {
[ROOT_FLAG, mode.name()]
}
const SETUP_FAILED: i32 = 101;
fn die(message: &str) -> ! {
_ = writeln!(std::io::stderr(), "signal tree: {message}");
std::process::exit(SETUP_FAILED)
}
struct Seen {
flags: Vec<(Signal, Arc<AtomicBool>)>,
wake: UnixStream,
}
fn register_handlers(mode: Mode) -> Seen {
let (wake, write) = UnixStream::pair().unwrap_or_else(|e| die(&format!("socketpair: {e}")));
wake.set_nonblocking(true)
.unwrap_or_else(|e| die(&format!("make the wake pipe non-blocking: {e}")));
let flags = mode
.signals()
.iter()
.map(|&signal| {
let flag = Arc::new(AtomicBool::new(false));
let number = signal as libc::c_int;
signal_hook::flag::register(number, Arc::clone(&flag))
.unwrap_or_else(|e| die(&format!("register the flag of {signal}: {e}")));
let write = write
.try_clone()
.unwrap_or_else(|e| die(&format!("duplicate the wake pipe: {e}")));
signal_hook::low_level::pipe::register(number, write)
.unwrap_or_else(|e| die(&format!("register the wake pipe of {signal}: {e}")));
(signal, flag)
})
.collect();
Seen { flags, wake }
}
fn change_mask(how: libc::c_int, mode: Mode) {
let mut set = SigSet::empty();
for &signal in mode.signals() {
set.add(signal);
}
let rc = unsafe { libc::pthread_sigmask(how, set.as_ref(), std::ptr::null_mut()) };
if rc != 0 {
die(&format!("pthread_sigmask: {}", std::io::Error::from_raw_os_error(rc)));
}
}
fn blocks(signal: Signal) -> bool {
let mut current = std::mem::MaybeUninit::uninit();
let rc = unsafe { libc::pthread_sigmask(libc::SIG_BLOCK, std::ptr::null(), current.as_mut_ptr()) };
if rc != 0 {
die(&format!("pthread_sigmask: {}", std::io::Error::from_raw_os_error(rc)));
}
unsafe { libc::sigismember(current.as_ptr(), signal as libc::c_int) == 1 }
}
fn run(role: Role, mode: Mode) -> ! {
let seen = match role {
Role::Root => {
change_mask(libc::SIG_BLOCK, mode);
let seen = register_handlers(mode);
let mut leaf = start_leaf(mode);
std::thread::Builder::new()
.name("reaper".to_owned())
.spawn(move || {
let status = leaf.wait().unwrap_or_else(|e| die(&format!("wait for the leaf: {e}")));
if status.code() == Some(SETUP_FAILED) {
die("the leaf could not set itself up");
}
})
.unwrap_or_else(|e| die(&format!("start the reaper thread: {e}")));
change_mask(libc::SIG_UNBLOCK, mode);
seen
}
Role::Leaf => {
let seen = register_handlers(mode);
change_mask(libc::SIG_UNBLOCK, mode);
report("r\n");
seen
}
};
debug_assert!(
mode.signals().iter().all(|&signal| !blocks(signal)),
"the main thread of a signal tree member must not block the mode's signals"
);
serve(role, mode, &seen)
}
fn serve(role: Role, mode: Mode, seen: &Seen) -> ! {
let stdin = rustix::stdio::stdin();
let flags = rustix::fs::fcntl_getfl(stdin).unwrap_or_else(|e| die(&format!("fcntl(F_GETFL) on the stdin: {e}")));
rustix::fs::fcntl_setfl(stdin, flags | rustix::fs::OFlags::NONBLOCK)
.unwrap_or_else(|e| die(&format!("fcntl(F_SETFL) on the stdin: {e}")));
loop {
let mut fds = [
PollFd::new(&stdin, PollFlags::IN),
PollFd::new(&seen.wake, PollFlags::IN),
];
crate::wait::poll_ready(&mut fds).unwrap_or_else(|e| die(&format!("poll: {e}")));
let stdin_ready = !fds[0].revents().is_empty();
empty_wake_pipe(seen);
report_seen(role, mode, seen);
if stdin_ready && stdin_ended(stdin) {
empty_wake_pipe(seen);
report_seen(role, mode, seen);
report(&format!("{} eof\n", role.name()));
std::process::exit(0);
}
}
}
fn stdin_ended(stdin: rustix::fd::BorrowedFd<'_>) -> bool {
let mut buf = [0u8; 256];
match rustix::io::retry_on_intr(|| rustix::io::read(stdin, &mut buf)) {
Ok(0) => true,
Ok(_) => false,
Err(rustix::io::Errno::AGAIN) => false,
Err(e) => die(&format!("read the stdin: {e}")),
}
}
fn empty_wake_pipe(seen: &Seen) {
let mut buf = [0u8; 256];
loop {
match (&seen.wake).read(&mut buf) {
Ok(0) => die("the wake pipe closed"),
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => return,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => die(&format!("read the wake pipe: {e}")),
}
}
}
fn report_seen(role: Role, mode: Mode, seen: &Seen) {
for (signal, flag) in &seen.flags {
if flag.swap(false, Ordering::SeqCst) {
report_signal(role, mode, *signal);
}
}
}
#[expect(
clippy::disallowed_methods,
reason = "this process is single-threaded here: nothing else forks, so there is no lock to hold"
)]
fn start_leaf(mode: Mode) -> std::process::Child {
let exe = std::env::current_exe().unwrap_or_else(|e| die(&format!("current_exe: {e}")));
crate::test_reexec::command(exe)
.args([LEAF_FLAG, mode.name()])
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.spawn()
.unwrap_or_else(|e| die(&format!("spawn the leaf: {e}")))
}
fn report_signal(role: Role, mode: Mode, signal: Signal) {
report(&format!("{} {}\n", role.name(), signal.as_str()));
if mode.ends_on(signal) {
std::process::exit(0);
}
}
fn report(line: &str) {
let mut out = std::io::stdout().lock();
match out.write_all(line.as_bytes()).and_then(|()| out.flush()) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => std::process::exit(0),
Err(e) => die(&format!("write {line:?} to the stdout: {e}")),
}
}