git_policy_cli/signal_relay.rs
1//! What:
2//! Catching `SIGINT`, `SIGTERM`, `SIGHUP` and `SIGQUIT` while the wrapper waits for a Git child,
3//! relaying a signal to that child only when a process sent it,
4//! and reporting how the child ended.
5//! `SignalGuard` owns the handlers for its lifetime and restores the previous dispositions on drop.
6//! Why:
7//! A wrapper that dies on a signal leaves its commit transaction for recovery and Git running;
8//! one that catches the signal can end Git, release its locks and remove the transaction first.
9//! A signal from the terminal already reached Git as part of the foreground process group,
10//! so relaying it again would deliver it twice.
11//!
12//! In TS you'd write (pseudocode):
13//! ```ts
14//! process.once('SIGTERM', () => { if (!fromTerminal) child.kill('SIGTERM'); });
15//! ```
16//!
17//! Integration (for the commit path and wrapped commands):
18//! ```ts
19//! // const guard = SignalGuard.install(); const outcome = guard.runChild(command); // cleanup; then exit(exitCode(outcome))
20//! ```
21//!
22//! Limits:
23//! Handlers are process-wide, so one guard may be active at a time;
24//! `SA_RESTART` keeps other system calls from failing with `EINTR`.
25//! Only Linux reads the child's exit without reaping it, so the PID is cleared before reaping there;
26//! elsewhere a signal that arrives in the instant between the child's exit and its reaping
27//! could reach a recycled PID.
28
29/// What:
30/// The typed reason a second signal guard is refused while one is active.
31/// Why:
32/// Callers that wait for the guard to be free must recognize this refusal by its type, not by its wording
33/// (issue 1346).
34///
35/// In TS you'd write (pseudocode):
36/// ```ts
37/// class SignalGuardActiveError extends Error {}
38/// ```
39#[derive(Debug)]
40pub struct SignalGuardActive;
41
42/// The wording of the refusal.
43impl std::fmt::Display for SignalGuardActive {
44 /// Writes the wording of the refusal.
45 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 return formatter.write_str("a signal guard is already active in this process");
47 }
48}
49
50impl std::error::Error for SignalGuardActive {}
51
52/// What:
53/// Whether an installation failure is the refusal of a second guard.
54/// Why:
55/// Only this refusal clears by itself when the other holder lets go; every other failure is final.
56///
57/// In TS you'd write (pseudocode):
58/// ```ts
59/// error instanceof SignalGuardActiveError
60/// ```
61pub fn is_guard_active_refusal(error: &io::Error) -> bool {
62 return error
63 .get_ref()
64 .is_some_and(|inner| { return inner.is::<SignalGuardActive>(); });
65}
66
67/// `c_int` is the C integer type signal numbers and status codes use.
68#[cfg(unix)]
69use std::ffi::c_int;
70/// `io` is the input and output error type the spawn and wait calls return.
71use std::io;
72/// `Command` builds the child, and `ExitStatus` is how it ended.
73use std::process::{Command, ExitStatus};
74
75/// The Git child's end, with the exit-code mapping the wrapper's exit uses.
76use super::forwarding::ChildOutcome;
77
78/// What:
79/// Whether the kernel recorded a signal as sent by a process rather than by the terminal or the kernel.
80/// Why:
81/// `si_code` values `SI_USER`, `SI_QUEUE` and (Linux) `SI_TKILL` come from `kill`, `sigqueue` and `tkill`;
82/// a terminal interrupt carries `SI_KERNEL`.
83///
84/// In TS you'd write (pseudocode):
85/// ```ts
86/// const fromProcess = info.si_code === SI_USER || info.si_code === SI_QUEUE;
87/// ```
88#[cfg(unix)]
89pub fn is_process_sender(code: c_int) -> bool {
90 return PROCESS_SENDER_CODES.contains(&code);
91}
92
93/// Sender codes that mean a process sent the signal, on Linux.
94#[cfg(target_os = "linux")]
95const PROCESS_SENDER_CODES: [c_int; 3] = [libc::SI_USER, libc::SI_QUEUE, libc::SI_TKILL];
96
97/// Sender codes that mean a process sent the signal, on other Unix systems.
98#[cfg(all(unix, not(target_os = "linux")))]
99const PROCESS_SENDER_CODES: [c_int; 2] = [libc::SI_USER, libc::SI_QUEUE];
100
101/// What:
102/// The signals the guard catches and relays.
103/// Why:
104/// The four signals that end an interactive or service wrapper in the incumbent's contract.
105///
106/// In TS you'd write (pseudocode):
107/// ```ts
108/// const CAUGHT = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'] as const;
109/// ```
110#[cfg(unix)]
111pub const RELAYED_SIGNALS: [c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
112
113/// What:
114/// PID of the Git child being waited for, or zero when none is.
115/// Why:
116/// The handler runs asynchronously, so it can only read state through atomics.
117#[cfg(unix)]
118static CHILD_PID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
119
120/// What:
121/// One slot per relayed signal, holding a signal number that has not been relayed yet, or zero.
122/// Why:
123/// A signal that arrives before the child exists is relayed as soon as its PID is recorded.
124#[cfg(unix)]
125static PENDING: [std::sync::atomic::AtomicI32; 4] =
126 [const { std::sync::atomic::AtomicI32::new(0) }; 4];
127
128/// What:
129/// Whether a guard is installed in this process.
130/// Why:
131/// Handlers and their saved dispositions are process-wide, so two guards would overwrite each other's record.
132#[cfg(unix)]
133static GUARD_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
134
135/// What:
136/// The first three fields of `siginfo_t` on every Unix system: signal number, error number and code.
137/// Why:
138/// The C struct's fields differ in name and union layout across systems; these three share one layout,
139/// and reading them through this view avoids the platform accessors.
140#[cfg(unix)]
141#[repr(C)]
142struct SignalHeader {
143 /// Signal number.
144 signal: c_int,
145 /// Error number, unused here.
146 error: c_int,
147 /// Sender code, `SI_USER` for `kill` and so on.
148 code: c_int,
149}
150
151/// What:
152/// The handler for each relayed signal.
153/// Why:
154/// Relaying inside the handler delivers the signal at once, even while the wrapper is blocked in a wait,
155/// where a flag would not wake it;
156/// `kill` is async-signal-safe, and the handler touches only atomics and `kill`.
157///
158/// In TS you'd write (pseudocode):
159/// ```ts
160/// process.on('SIGTERM', (info) => { if (info.fromProcess) child.kill('SIGTERM'); });
161/// ```
162#[cfg(unix)]
163extern "C" fn relay_handler(
164 signal: c_int,
165 info: *mut libc::siginfo_t,
166 _context: *mut std::ffi::c_void,
167) {
168 if info.is_null() {
169 return;
170 }
171 // SAFETY: with `SA_SIGINFO` the kernel passes a valid `siginfo_t`; its first three fields are the header.
172 let code: c_int = unsafe { (*info.cast::<SignalHeader>()).code };
173 if !is_process_sender(code) {
174 return;
175 }
176 let Some(slot) = RELAYED_SIGNALS.iter().position(|candidate| return *candidate == signal) else {
177 return;
178 };
179 PENDING[slot].store(signal, std::sync::atomic::Ordering::SeqCst);
180 relay_pending();
181}
182
183/// What:
184/// Send every pending signal to the recorded child, claiming each slot so it is sent once.
185/// Why:
186/// Both the handler and the waiting code call this; the atomic swap decides which one sends a given signal.
187///
188/// In TS you'd write (pseudocode):
189/// ```ts
190/// for (const signal of pending.drain()) child.kill(signal);
191/// ```
192#[cfg(unix)]
193fn relay_pending() {
194 let pid: i32 = CHILD_PID.load(std::sync::atomic::Ordering::SeqCst);
195 if pid <= 0 {
196 return;
197 }
198 for slot in &PENDING {
199 let signal: c_int = slot.swap(0, std::sync::atomic::Ordering::SeqCst);
200 if signal != 0 {
201 // SAFETY: `kill` sends one signal to a PID this module recorded; a failure is ignored because the child may have ended.
202 unsafe { libc::kill(pid, signal) };
203 }
204 }
205}
206
207/// What:
208/// Install one relaying handler, returning the disposition it replaced.
209/// A signal the parent ignores stays ignored, so `None` is returned and nothing is saved.
210/// Why:
211/// Git inherits ignored signals, so replacing an ignore with a handler would change Git's environment.
212///
213/// In TS you'd write (pseudocode):
214/// ```ts
215/// if (process.listenerCount(signal) === 0) install(signal);
216/// ```
217#[cfg(unix)]
218fn install_one(signal: c_int) -> io::Result<Option<libc::sigaction>> {
219 // SAFETY: a zeroed `sigaction` is a valid starting value; every field used below is set first.
220 let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
221 // SAFETY: as above; `previous` receives the current disposition.
222 let mut previous: libc::sigaction = unsafe { std::mem::zeroed() };
223 // SAFETY: a null new action only reads the current disposition into `previous`.
224 let read: c_int = unsafe { libc::sigaction(signal, std::ptr::null(), &mut previous) };
225 if read != 0 {
226 return Err(io::Error::last_os_error());
227 }
228 if previous.sa_sigaction == libc::SIG_IGN {
229 return Ok(None);
230 }
231 action.sa_sigaction = relay_handler as *const () as libc::sighandler_t;
232 action.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART;
233 // SAFETY: `sigemptyset` initializes the mask in place.
234 unsafe { libc::sigemptyset(&mut action.sa_mask) };
235 // SAFETY: `action` is fully initialized; the old disposition is written to `previous`.
236 let set: c_int = unsafe { libc::sigaction(signal, &action, &mut previous) };
237 if set != 0 {
238 return Err(io::Error::last_os_error());
239 }
240 return Ok(Some(previous));
241}
242
243/// What:
244/// Put back each saved disposition.
245/// Why:
246/// Restoring is the drop's job and also the rollback when an installation fails midway.
247///
248/// In TS you'd write (pseudocode):
249/// ```ts
250/// for (const [signal, previous] of saved) process.removeListener(signal, previous);
251/// ```
252#[cfg(unix)]
253fn restore(saved: &[(c_int, libc::sigaction)]) {
254 for (signal, previous) in saved {
255 // SAFETY: `previous` is a disposition this module read earlier; restoring it reads no memory.
256 unsafe { libc::sigaction(*signal, previous, std::ptr::null_mut()) };
257 }
258}
259
260/// What:
261/// Wait for the child to exit without reaping it, so its PID still names it.
262/// Why:
263/// Clearing the recorded PID before reaping stops a relay to a PID that the system may have reused.
264/// `waitid` with `WNOWAIT` reports the exit and leaves the child waitable.
265///
266/// In TS you'd write (pseudocode):
267/// ```ts
268/// await waitForExitWithoutReaping(pid);
269/// ```
270#[cfg(target_os = "linux")]
271fn wait_without_reaping(pid: libc::pid_t) -> io::Result<()> {
272 loop {
273 // SAFETY: `waitid` writes into the zeroed buffer this function owns, and only for a child it names.
274 let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
275 // SAFETY: `P_PID` names one child; `WEXITED | WNOWAIT` only observes its exit.
276 let result: c_int = unsafe {
277 libc::waitid(
278 libc::P_PID,
279 libc::id_t::try_from(pid).unwrap_or(0),
280 &mut info,
281 libc::WEXITED | libc::WNOWAIT,
282 )
283 };
284 if result == 0 {
285 return Ok(());
286 }
287 let error: io::Error = io::Error::last_os_error();
288 match error.raw_os_error() {
289 Some(libc::EINTR) => continue,
290 Some(libc::ECHILD) => return Ok(()),
291 _ => return Err(error),
292 }
293 }
294}
295
296/// What:
297/// Non-Linux Unix placeholder for the wait that leaves the child unreaped.
298/// Why:
299/// `waitid` is not in the `libc` crate for these systems; the window it closes is documented on the module.
300#[cfg(all(unix, not(target_os = "linux")))]
301fn wait_without_reaping(_pid: libc::pid_t) -> io::Result<()> {
302 return Ok(());
303}
304
305/// What:
306/// Owns the relaying handlers for its lifetime.
307/// Install one guard, run the Git child through it, then drop it after cleanup.
308/// Why:
309/// Dropping it restores the previous dispositions, so a signal after cleanup behaves as it did before.
310///
311/// In TS you'd write (pseudocode):
312/// ```ts
313/// using guard = SignalGuard.install(); const outcome = await guard.runChild(command);
314/// ```
315#[cfg(unix)]
316#[must_use = "the handlers last only while the guard lives"]
317pub struct SignalGuard {
318 /// Dispositions to restore on drop, one per signal that was replaced.
319 saved: Vec<(c_int, libc::sigaction)>,
320}
321
322/// Methods over an installed guard.
323#[cfg(unix)]
324impl SignalGuard {
325 /// What:
326 /// Install the relaying handlers.
327 /// Fails when another guard is already active in this process.
328 /// Why:
329 /// The handlers are process-wide, so a second guard would record the first one's handler as the old disposition.
330 ///
331 /// In TS you'd write (pseudocode):
332 /// ```ts
333 /// static install(): SignalGuard // throws when already installed
334 /// ```
335 pub fn install() -> io::Result<Self> {
336 if GUARD_ACTIVE
337 .compare_exchange(
338 false,
339 true,
340 std::sync::atomic::Ordering::SeqCst,
341 std::sync::atomic::Ordering::SeqCst,
342 )
343 .is_err()
344 {
345 return Err(io::Error::other(SignalGuardActive));
346 }
347 // `mut` lets each installed disposition be recorded as it is replaced.
348 let mut saved: Vec<(c_int, libc::sigaction)> = Vec::with_capacity(RELAYED_SIGNALS.len());
349 for signal in RELAYED_SIGNALS {
350 match install_one(signal) {
351 Ok(Some(previous)) => saved.push((signal, previous)),
352 Ok(None) => {}
353 Err(error) => {
354 restore(&saved);
355 GUARD_ACTIVE.store(false, std::sync::atomic::Ordering::SeqCst);
356 return Err(error);
357 }
358 }
359 }
360 return Ok(Self { saved });
361 }
362
363 /// What:
364 /// Start `command`, wait for it while relaying signals, and return how it ended.
365 /// The guard does not exit the process; the caller releases its locks and removes its state, then exits.
366 /// Why:
367 /// Signals that arrived before the child started are relayed as soon as it has a PID.
368 ///
369 /// In TS you'd write (pseudocode):
370 /// ```ts
371 /// async runChild(command: SpawnOptions): Promise<ChildOutcome>
372 /// ```
373 pub fn run_child(&self, command: &mut Command) -> io::Result<ChildOutcome> {
374 return run_relayed(command);
375 }
376}
377
378/// Spawns the child, then relays any signal that was caught before the child existed.
379///
380/// A handler that runs before the spawn keeps its signal in `PENDING` and finds no child.
381/// The PID is published before the drain, so that signal is relayed here, not lost.
382#[cfg(unix)]
383fn run_relayed(command: &mut Command) -> io::Result<ChildOutcome> {
384 let mut child: std::process::Child = command.spawn()?;
385 let pid: libc::pid_t = libc::pid_t::try_from(child.id())
386 .map_err(|error| return io::Error::other(error))?;
387 CHILD_PID.store(pid, std::sync::atomic::Ordering::SeqCst);
388 relay_pending();
389 let waited: io::Result<()> = wait_without_reaping(pid);
390 CHILD_PID.store(0, std::sync::atomic::Ordering::SeqCst);
391 let status: ExitStatus = child.wait()?;
392 waited?;
393 return Ok(super::forwarding::outcome_of(status));
394}
395
396/// Restore the previous dispositions and release the process-wide slot.
397#[cfg(unix)]
398impl Drop for SignalGuard {
399 /// What:
400 /// Restore the saved dispositions and clear the active flag.
401 /// Why:
402 /// The next guard, or the process default after the guard, must see the original handlers.
403 ///
404 /// In TS you'd write (pseudocode):
405 /// ```ts
406 /// [Symbol.dispose]() { restore(saved); }
407 /// ```
408 fn drop(&mut self) {
409 restore(&self.saved);
410 GUARD_ACTIVE.store(false, std::sync::atomic::Ordering::SeqCst);
411 }
412}
413
414/// What:
415/// Non-Unix guard: no signal relay exists, so the child runs and the wrapper waits.
416/// Why:
417/// Callers keep one API; Windows ends a console child differently and is not covered by these controls.
418// UNTESTED ON WINDOWS: no gate compiles or runs this branch (the crate does not build for Windows; README, Requirements).
419#[cfg(not(unix))]
420pub struct SignalGuard;
421
422/// Methods over the non-Unix guard.
423// UNTESTED ON WINDOWS: no gate compiles or runs this branch (the crate does not build for Windows; README, Requirements).
424#[cfg(not(unix))]
425impl SignalGuard {
426 /// What:
427 /// Return a guard that relays nothing.
428 /// Why:
429 /// Keeps the call site identical on every platform.
430 ///
431 /// In TS you'd write (pseudocode):
432 /// ```ts
433 /// static install(): SignalGuard
434 /// ```
435 pub fn install() -> io::Result<Self> {
436 return Ok(Self);
437 }
438
439 /// What:
440 /// Start `command` and wait for it.
441 /// Why:
442 /// Without relaying, the wait is the whole job.
443 ///
444 /// In TS you'd write (pseudocode):
445 /// ```ts
446 /// async runChild(command): Promise<ChildOutcome>
447 /// ```
448 pub fn run_child(&self, command: &mut Command) -> io::Result<ChildOutcome> {
449 let mut child: std::process::Child = command.spawn()?;
450 let status: ExitStatus = child.wait()?;
451 return Ok(super::forwarding::outcome_of(status));
452 }
453}
454
455/// Signal controls live beside the guard.
456#[cfg(test)]
457#[path = "signal_relay_tests.rs"]
458mod tests;