Skip to main content

crumbkit_process/
forward.rs

1//! Stops every live child group when the tool itself receives SIGINT,
2//! SIGTERM or SIGHUP, runs the tool's clean-ups, and then takes the
3//! signal's default action. It exists on Unix with the `forward` feature.
4//!
5//! [`install`] starts one thread for the life of the process. When a
6//! signal arrives, the thread:
7//!
8//! 1. takes the registry's lock and holds it until the process ends, so no
9//!    new child starts;
10//! 2. sends the received signal, then SIGCONT, to every listed group, and
11//!    to a listed child that moved to another group;
12//! 3. waits up to [`FORWARD_GRACE`] until every listed child has exited;
13//! 4. sends SIGKILL to every listed group;
14//! 5. runs each clean-up that [`clean_up`] registered;
15//! 6. takes the signal's default action, which ends the tool as the signal
16//!    would have.
17//!
18//! A run lists its child while it holds the registry's lock around the
19//! start, when the child leads a group of its own
20//! ([`Scope::Group`](crate::Scope::Group)). The run unlists it under the
21//! same lock before it reaps it, so the forwarder never signals a process
22//! id that another process may have taken.
23//!
24//! The forwarder must be the only handler that ends the tool on SIGINT,
25//! SIGTERM or SIGHUP. A tool that keeps crumbkit-usage's log beside the
26//! forwarder starts it with `start_under(forward::clean_up)`, so the log
27//! starts no signal thread. The line is the first clean-up only when
28//! `start_under` runs before anything else registers one. Plain
29//! `start` beside [`install`] leaves two handlers that each end the tool,
30//! and neither crate can detect that (ADR-0179).
31//!
32//! A tool that hands the terminal to a child with crumbkit-child calls
33//! [`handed_over`] just before the hand-over, so Ctrl-C ends only the child.
34//!
35//! ```no_run
36//! fn remove_lock_file() {}
37//!
38//! crumbkit_process::forward::clean_up(remove_lock_file);
39//! crumbkit_process::forward::install()?;
40//! # Ok::<(), std::io::Error>(())
41//! ```
42
43use std::io;
44use std::process::Child;
45use std::sync::atomic::{AtomicBool, Ordering};
46use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
47use std::thread::Builder;
48use std::time::{Duration, Instant};
49
50use rustix::process::{Pid, Signal as Raw};
51use signal_hook::consts::{SIGHUP, SIGINT, SIGTERM};
52use signal_hook::iterator::Signals;
53
54use crate::sys;
55
56#[cfg(test)]
57mod tests;
58
59/// How long the forwarder waits for the listed children to exit after it
60/// sends them the tool's signal, before it sends SIGKILL.
61pub const FORWARD_GRACE: Duration = Duration::from_secs(1);
62
63/// How long the forwarder sleeps between checks on the listed children.
64const CHECK: Duration = Duration::from_millis(10);
65
66/// The live children that lead a group of their own, by process id.
67static LISTED: Mutex<Vec<Pid>> = Mutex::new(Vec::new());
68
69/// The functions that the forwarder runs before the tool ends.
70static CLEAN_UPS: Mutex<Vec<fn()>> = Mutex::new(Vec::new());
71
72/// Whether a child has taken the terminal, which [`handed_over`] records.
73static HANDED_OVER: AtomicBool = AtomicBool::new(false);
74
75/// Whether the forwarder's thread started, which [`install`] decides once.
76static INSTALLED: OnceLock<Result<(), io::ErrorKind>> = OnceLock::new();
77
78/// Starts the thread that forwards SIGINT, SIGTERM and SIGHUP to every
79/// live child group. A second call does nothing and returns the result of
80/// the first.
81///
82/// The thread stays for the life of the process, because removing a
83/// signal-hook handler does not restore the signal's default action. The
84/// handler replaces an inherited disposition that ignores SIGINT or SIGHUP,
85/// as `nohup` sets, because no safe API reads that disposition.
86///
87/// # Errors
88///
89/// Returns the operating system's error kind when the handlers cannot be
90/// installed or the thread cannot start.
91pub fn install() -> io::Result<()> {
92    match INSTALLED.get_or_init(start) {
93        Ok(()) => Ok(()),
94        Err(kind) => Err(io::Error::new(
95            *kind,
96            "cannot start the thread that forwards signals",
97        )),
98    }
99}
100
101/// Registers `clean_up` to run when the forwarder has stopped the listed
102/// groups and before the tool ends. The clean-ups run in the order that
103/// they were registered, each function is kept once, and a clean-up that
104/// panics does not stop the others. A clean-up that never returns stops the
105/// later ones, so a tool that must write crumbkit-usage's line calls
106/// `start_under(forward::clean_up)` before it registers anything else.
107///
108/// A clean-up must not start a run with
109/// [`Scope::Group`](crate::Scope::Group), or wait for a thread that runs
110/// one. The forwarder holds the list's lock while the clean-ups run, and
111/// such a run waits for that lock forever, so the tool never ends. A run
112/// with [`Scope::Child`](crate::Scope::Child) takes no lock.
113pub fn clean_up(clean_up: fn()) {
114    let mut clean_ups = CLEAN_UPS.lock().unwrap_or_else(PoisonError::into_inner);
115    if !clean_ups
116        .iter()
117        .any(|kept| std::ptr::fn_addr_eq(*kept, clean_up))
118    {
119        clean_ups.push(clean_up);
120    }
121}
122
123/// Tells the forwarder that a child is about to take the terminal. From now
124/// until the tool ends, the forwarder drops SIGINT, as crumbkit-child ignores
125/// it on Unix (ADR-0042, ADR-0179), so Ctrl-C reaches only the child.
126/// SIGTERM and SIGHUP still reach the listed groups as before. The child
127/// that takes the terminal is not on the forwarder's list, so a SIGTERM or
128/// SIGHUP sent to the tool during a hand-over ends the tool and leaves that
129/// child on the terminal.
130///
131/// A tool that hands over the terminal beside the forwarder calls this just
132/// before `crumbkit_child::hand_over`.
133pub fn handed_over() {
134    HANDED_OVER.store(true, Ordering::SeqCst);
135}
136
137/// Installs the handlers and starts the forwarder's thread.
138fn start() -> Result<(), io::ErrorKind> {
139    let mut signals = Signals::new([SIGINT, SIGTERM, SIGHUP]).map_err(|error| error.kind())?;
140    Builder::new()
141        .name("crumbkit-process forward".to_owned())
142        .spawn(move || {
143            // RUST-10: `forward` never returns, so a second signal during
144            // the grace or the clean-ups is never read, and nothing bounds a
145            // clean-up. A `register_conditional_default` on a flag set after
146            // the SIGKILL step replaces this if a tool reports a hung
147            // clean-up.
148            for raw in signals.forever() {
149                if raw == SIGINT && HANDED_OVER.load(Ordering::SeqCst) {
150                    continue;
151                }
152                forward(raw);
153            }
154        })
155        .map(drop)
156        .map_err(|error| error.kind())
157}
158
159/// Stops every listed group on the signal `raw`, runs the clean-ups, and
160/// ends the tool as `raw` would have.
161fn forward(raw: i32) {
162    // The lock stays held until the tool ends, so no child starts after the
163    // signal and no listed child is reaped while the forwarder signals it.
164    let listed = listed_children();
165    if let Some(signal) = Raw::from_named_raw(raw) {
166        signal_each(&listed, signal);
167    }
168    let until = Instant::now().checked_add(FORWARD_GRACE);
169    while until.is_some_and(|until| Instant::now() < until)
170        && listed
171            .iter()
172            .any(|pid| !sys::has_exited(*pid).unwrap_or(true))
173    {
174        std::thread::sleep(CHECK);
175    }
176    signal_each(&listed, Raw::KILL);
177    let clean_ups = CLEAN_UPS
178        .lock()
179        .unwrap_or_else(PoisonError::into_inner)
180        .clone();
181    for clean_up in clean_ups {
182        // A clean-up that panics must not keep the tool from ending as the
183        // signal says.
184        let _ = std::panic::catch_unwind(clean_up);
185    }
186    // For SIGINT, SIGTERM and SIGHUP this call does not return: it restores
187    // the default action and raises the signal, and falls back to `abort`.
188    // The lock on the list is therefore never released to a later run.
189    let _ = signal_hook::low_level::emulate_default_handler(raw);
190}
191
192/// Sends `signal` to each group of `listed`. A refusal is skipped, because
193/// the SIGKILL that follows still applies.
194fn signal_each(listed: &[Pid], signal: Raw) {
195    for pid in listed {
196        let _ = sys::signal_group(*pid, signal);
197    }
198}
199
200/// Starts a child with `spawn` while it holds the registry's lock, and
201/// lists the child when it starts.
202pub(crate) fn listed(spawn: impl FnOnce() -> io::Result<Child>) -> io::Result<Child> {
203    let mut listed = listed_children();
204    let child = spawn()?;
205    listed.push(Pid::from_child(&child));
206    Ok(child)
207}
208
209/// Unlists the child `pid` and reaps it with `reap`, both under the
210/// registry's lock.
211pub(crate) fn unlisted<T>(pid: Pid, reap: impl FnOnce() -> T) -> T {
212    let mut listed = listed_children();
213    listed.retain(|listed| *listed != pid);
214    reap()
215}
216
217/// Returns the locked list. Each change is a single push or retain, so a
218/// panic while the lock was held cannot leave it half changed.
219fn listed_children() -> MutexGuard<'static, Vec<Pid>> {
220    LISTED.lock().unwrap_or_else(PoisonError::into_inner)
221}