Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

2.3 KB
Raw Blame
// ©AngelaMos | 2026
// interrupt.rs

use std::io;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use signal_hook::consts::{SIGINT, SIGTERM};

// B5, measured: with the default disposition lisdex dies of SIGINT the instant a campaign is
// interrupted and `harvest` never runs. On a real campaign that lost five crash files already on
// disk and left the campaign row stranded at `fuzzing`, with no command able to read them back.
//
// Registered through signal-hook rather than `libc::signal` so this crate holds no `unsafe`: the
// workspace denies it outright and there is not one exemption anywhere in the tree, which is a
// claim worth more than the few lines it would have saved here.
#[derive(Debug, Clone)]
pub struct Interrupt {
    flag: Arc<AtomicBool>,
}

impl Interrupt {
    // Arming twice is harmless: signal-hook keeps a list of actions per signal, and both would
    // set the same flag.
    pub fn arm() -> Result<Self, io::Error> {
        let flag = Arc::new(AtomicBool::new(false));
        for signal in [SIGINT, SIGTERM] {
            signal_hook::flag::register(signal, Arc::clone(&flag))?;
        }
        Ok(Self { flag })
    }

    #[must_use]
    pub fn raised(&self) -> bool {
        self.flag.load(Ordering::SeqCst)
    }

    // Raising the flag by hand is the only way to test the wait loop's interrupted path without
    // signalling the test runner itself, which would take the whole suite down with it.
    #[cfg(test)]
    pub fn raise_for_test(&self) {
        self.flag.store(true, Ordering::SeqCst);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // The flag has to start clear, or a campaign would decide it had been interrupted before it
    // ever ran and stop at its first poll.
    #[test]
    fn an_armed_interrupt_starts_clear() {
        let interrupt = Interrupt::arm().expect("registering a handler");
        assert!(!interrupt.raised());
    }

    // Clones share one flag, which is what lets the runner hand a copy to its wait loop while
    // the caller keeps one to report with.
    #[test]
    fn a_clone_observes_the_same_flag() {
        let interrupt = Interrupt::arm().expect("registering a handler");
        let copy = interrupt.clone();
        interrupt.flag.store(true, Ordering::SeqCst);
        assert!(copy.raised(), "a clone must not carry its own flag");
    }
}