//! POSIX signal notifications. //! //! This crate keeps unsafe signal-handler wiring behind a small channel-based //! API. The installed handler only writes the signal number into a nonblocking //! pipe, and a normal Rust thread turns those bytes into typed notifications. use std::fs::File; use std::io::{self, Read}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::sync::Mutex; use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::mpsc; use std::thread; /// File descriptor not currently connected to signal delivery. const NO_FD: RawFd = -1; /// Whether this process already has a rustik signal registration. static INSTALLED: Mutex = Mutex::new(false); /// Nonblocking pipe write end used by the signal handler. static WRITE_FD: AtomicI32 = AtomicI32::new(NO_FD); /// Operating system signal. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Signal { /// `SIGINT`. Interrupt, /// `SIGTERM`. Terminate, /// `SIGHUP`. Hangup, /// `SIGWINCH`. WindowChanged, } impl Signal { /// Returns this signal's platform number. fn number(self) -> libc::c_int { match self { Self::Interrupt => libc::SIGINT, Self::Terminate => libc::SIGTERM, Self::Hangup => libc::SIGHUP, Self::WindowChanged => libc::SIGWINCH, } } /// Returns the signal represented by a platform number. fn from_number(number: libc::c_int) -> Option { match number { libc::SIGINT => Some(Self::Interrupt), libc::SIGTERM => Some(Self::Terminate), libc::SIGHUP => Some(Self::Hangup), libc::SIGWINCH => Some(Self::WindowChanged), _ => None, } } /// Installs the crate's signal handler and returns a guard that restores /// the default disposition on drop. fn install_handler(self) -> io::Result { let handler = handle_signal as *const () as libc::sighandler_t; // SAFETY: `handler` is the crate's signal handler for `self.number()`. if unsafe { libc::signal(self.number(), handler) } == libc::SIG_ERR { return Err(io::Error::last_os_error()); } Ok(InstalledHandler(self)) } } /// Guard that restores the default disposition for its signal on drop. struct InstalledHandler(Signal); impl Drop for InstalledHandler { fn drop(&mut self) { // SAFETY: restores the default disposition for a known signal. unsafe { libc::signal(self.0.number(), libc::SIG_DFL) }; } } /// Installed signal notification stream. pub struct Signals { /// Handlers that uninstall themselves on drop. installed: Vec, /// Signal receiver. receiver: mpsc::Receiver, /// Pipe write end kept alive until signal handlers are uninstalled. _write_fd: OwnedFd, } impl Signals { /// Installs signal handlers and returns a typed notification stream. pub fn install(signals: &[Signal]) -> io::Result { // Mutex poison only happens if a previous `install` panicked mid-setup // (e.g. OOM in `thread::spawn`); fall through to the same exclusivity // check rather than surfacing a separate error. let mut guard = INSTALLED.lock().unwrap_or_else(|e| e.into_inner()); if *guard { return Err(io::Error::new( io::ErrorKind::AlreadyExists, "signal handling is already installed", )); } let (read_fd, write_fd) = pipe()?; set_close_on_exec(read_fd.as_raw_fd())?; set_close_on_exec(write_fd.as_raw_fd())?; set_nonblocking(write_fd.as_raw_fd())?; WRITE_FD.store(write_fd.as_raw_fd(), Ordering::SeqCst); let installed = signals .iter() .copied() .map(Signal::install_handler) .collect::>>() .inspect_err(|_| WRITE_FD.store(NO_FD, Ordering::SeqCst))?; let (tx, receiver) = mpsc::channel(); thread::spawn(move || read_signals(read_fd, tx)); *guard = true; Ok(Self { installed, _write_fd: write_fd, receiver, }) } /// Receives the next signal notification. pub fn recv(&self) -> Result { self.receiver.recv() } /// Receives the next signal notification before the timeout expires. pub fn recv_timeout( &self, timeout: std::time::Duration, ) -> Result { self.receiver.recv_timeout(timeout) } } impl Drop for Signals { fn drop(&mut self) { WRITE_FD.store(NO_FD, Ordering::SeqCst); // Each `InstalledHandler` restores the default disposition on drop. self.installed.clear(); if let Ok(mut installed) = INSTALLED.lock() { *installed = false; } } } /// Handles an OS signal. extern "C" fn handle_signal(signal: libc::c_int) { // SAFETY: `errno_location` returns the thread-local errno pointer for this // platform. let location = unsafe { errno_location() }; // SAFETY: the pointer is valid for reading and writing the current thread's errno. let errno = unsafe { *location }; let fd = WRITE_FD.load(Ordering::Relaxed); if fd != NO_FD { let byte = [signal as u8]; // SAFETY: `write` is async-signal-safe, and the byte buffer is valid for // the duration of the call. unsafe { let _ = libc::write(fd, byte.as_ptr().cast(), byte.len()); } } // SAFETY: the pointer is valid for reading and writing the current thread's errno. unsafe { *location = errno; } } /// Platform accessor for this thread's `errno` storage. #[cfg(any(target_os = "linux", target_os = "android"))] use libc::__errno_location as errno_location; /// Platform accessor for this thread's `errno` storage. #[cfg(any( target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly" ))] use libc::__error as errno_location; /// Reads signal bytes and forwards typed notifications. fn read_signals(read_fd: OwnedFd, tx: mpsc::Sender) { let mut file = File::from(read_fd); let mut bytes = [0_u8; 128]; loop { let len = match file.read(&mut bytes) { Ok(0) => break, Ok(n) => n, Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, Err(_) => break, }; for &byte in &bytes[..len] { let Some(signal) = Signal::from_number(i32::from(byte)) else { continue; }; if tx.send(signal).is_err() { return; } } } } /// Creates a pipe. fn pipe() -> io::Result<(OwnedFd, OwnedFd)> { let mut fds = [NO_FD; 2]; // SAFETY: `fds` points to two file descriptor slots for libc to initialize. if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 { Err(io::Error::last_os_error()) } else { // SAFETY: successful `pipe` initializes both file descriptors, and // `OwnedFd` takes responsibility for closing them. unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) } } } /// Sets `FD_CLOEXEC` on a file descriptor. /// /// `FD_CLOEXEC` is the only fd-level flag POSIX defines, so a plain `F_SETFD` /// is enough — no read-modify-write needed. fn set_close_on_exec(fd: RawFd) -> io::Result<()> { // SAFETY: `F_SETFD` with a known integer flag value. if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { return Err(io::Error::last_os_error()); } Ok(()) } /// Adds `O_NONBLOCK` to a file descriptor's status flags. fn set_nonblocking(fd: RawFd) -> io::Result<()> { // SAFETY: `F_GETFL` takes no third argument; `F_SETFL` takes the flag bitmask. let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 { return Err(io::Error::last_os_error()); } Ok(()) } #[cfg(test)] mod tests { use std::sync::Mutex; use std::time::Duration; use super::*; static TEST_LOCK: Mutex<()> = Mutex::new(()); #[test] fn signal_channel_receives_window_change() { let _guard = TEST_LOCK.lock().unwrap(); let signals = Signals::install(&[Signal::WindowChanged]).unwrap(); // SAFETY: raising SIGWINCH for the current process exercises the handler // installed by this test. assert_eq!(unsafe { libc::raise(libc::SIGWINCH) }, 0); assert_eq!( signals.recv_timeout(Duration::from_secs(1)).unwrap(), Signal::WindowChanged ); } #[test] fn signal_registration_is_exclusive_until_dropped() { let _guard = TEST_LOCK.lock().unwrap(); let signals = Signals::install(&[Signal::WindowChanged]).unwrap(); let Err(error) = Signals::install(&[Signal::WindowChanged]) else { panic!("second signal install should fail"); }; assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); drop(signals); let _signals = Signals::install(&[Signal::WindowChanged]).unwrap(); } }