Add new `rustik-signals` crate

fff10911841b5831be455aaa16b145ec7ab93bfd
Implements simple POSIX signal handling.
Alexis Sellier committed ago 1 parent d6b25b6c
Cargo.lock +8 -0
132 132
dependencies = [
133 133
 "microserde",
134 134
 "onig-regset",
135 135
]
136 136
137 +
[[package]]
138 +
name = "rustik-signals"
139 +
version = "0.1.0"
140 +
dependencies = [
141 +
 "libc",
142 +
]
143 +
137 144
[[package]]
138 145
name = "rustik-tui"
139 146
version = "0.1.0"
140 147
dependencies = [
141 148
 "rustik-tui-core",
149 156
150 157
[[package]]
151 158
name = "rustik-tui-termion"
152 159
version = "0.1.0"
153 160
dependencies = [
161 +
 "rustik-signals",
154 162
 "rustik-tui-core",
155 163
 "termion",
156 164
]
157 165
158 166
[[package]]
Cargo.toml +4 -1
1 1
[workspace]
2 2
members = [
3 3
  "crates/diff",
4 4
  "crates/highlight",
5 +
  "crates/signals",
5 6
  "crates/tui",
6 7
  "crates/tui-core",
7 8
  "crates/tui-termion",
8 9
  "crates/tui-widgets"
9 10
]
37 38
version = "0.1.0"
38 39
edition = "2024"
39 40
license = "MIT"
40 41
41 42
[workspace.dependencies]
43 +
libc = { version = "0.2" }
42 44
onig = { package = "onig-regset", version = "6.7.0", default-features = false }
43 45
serde = { package = "microserde", version = "0.2.0" }
44 -
termion = "4"
46 +
termion = { version = "4" }
45 47
rustik-highlight = { path = "crates/highlight", version = "0.1.0" }
46 48
rustik-diff = { path = "crates/diff", version = "0.1.0" }
49 +
rustik-signals = { path = "crates/signals", version = "0.1.0" }
47 50
rustik-tui = { path = "crates/tui", version = "0.1.0" }
48 51
rustik-tui-core = { path = "crates/tui-core", version = "0.1.0" }
49 52
rustik-tui-widgets = { path = "crates/tui-widgets", version = "0.1.0" }
50 53
rustik-tui-termion = { path = "crates/tui-termion", version = "0.1.0" }
51 54
crates/signals/Cargo.toml added +14 -0
1 +
[package]
2 +
name = "rustik-signals"
3 +
description = "Small POSIX signal bridge for rustik terminal tools."
4 +
documentation = "https://docs.rs/rustik-signals"
5 +
homepage = "https://crates.io/crates/rustik-signals"
6 +
version.workspace = true
7 +
edition.workspace = true
8 +
license.workspace = true
9 +
10 +
[dependencies]
11 +
libc.workspace = true
12 +
13 +
[lints]
14 +
workspace = true
crates/signals/src/lib.rs added +284 -0
1 +
//! POSIX signal notifications.
2 +
//!
3 +
//! This crate keeps unsafe signal-handler wiring behind a small channel-based
4 +
//! API. The installed handler only writes the signal number into a nonblocking
5 +
//! pipe, and a normal Rust thread turns those bytes into typed notifications.
6 +
7 +
use std::fs::File;
8 +
use std::io::{self, Read};
9 +
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
10 +
use std::sync::Mutex;
11 +
use std::sync::atomic::{AtomicI32, Ordering};
12 +
use std::sync::mpsc;
13 +
use std::thread;
14 +
15 +
/// File descriptor not currently connected to signal delivery.
16 +
const NO_FD: RawFd = -1;
17 +
/// Whether this process already has a rustik signal registration.
18 +
static INSTALLED: Mutex<bool> = Mutex::new(false);
19 +
/// Nonblocking pipe write end used by the signal handler.
20 +
static WRITE_FD: AtomicI32 = AtomicI32::new(NO_FD);
21 +
22 +
/// Operating system signal.
23 +
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
24 +
pub enum Signal {
25 +
    /// `SIGINT`.
26 +
    Interrupt,
27 +
    /// `SIGTERM`.
28 +
    Terminate,
29 +
    /// `SIGHUP`.
30 +
    Hangup,
31 +
    /// `SIGWINCH`.
32 +
    WindowChanged,
33 +
}
34 +
35 +
impl Signal {
36 +
    /// Returns this signal's platform number.
37 +
    fn number(self) -> libc::c_int {
38 +
        match self {
39 +
            Self::Interrupt => libc::SIGINT,
40 +
            Self::Terminate => libc::SIGTERM,
41 +
            Self::Hangup => libc::SIGHUP,
42 +
            Self::WindowChanged => libc::SIGWINCH,
43 +
        }
44 +
    }
45 +
46 +
    /// Returns the signal represented by a platform number.
47 +
    fn from_number(number: libc::c_int) -> Option<Self> {
48 +
        match number {
49 +
            libc::SIGINT => Some(Self::Interrupt),
50 +
            libc::SIGTERM => Some(Self::Terminate),
51 +
            libc::SIGHUP => Some(Self::Hangup),
52 +
            libc::SIGWINCH => Some(Self::WindowChanged),
53 +
            _ => None,
54 +
        }
55 +
    }
56 +
57 +
    /// Installs the crate's signal handler and returns a guard that restores
58 +
    /// the default disposition on drop.
59 +
    fn install_handler(self) -> io::Result<InstalledHandler> {
60 +
        let handler = handle_signal as *const () as libc::sighandler_t;
61 +
        // SAFETY: `handler` is the crate's signal handler for `self.number()`.
62 +
        if unsafe { libc::signal(self.number(), handler) } == libc::SIG_ERR {
63 +
            return Err(io::Error::last_os_error());
64 +
        }
65 +
        Ok(InstalledHandler(self))
66 +
    }
67 +
}
68 +
69 +
/// Guard that restores the default disposition for its signal on drop.
70 +
struct InstalledHandler(Signal);
71 +
72 +
impl Drop for InstalledHandler {
73 +
    fn drop(&mut self) {
74 +
        // SAFETY: restores the default disposition for a known signal.
75 +
        unsafe { libc::signal(self.0.number(), libc::SIG_DFL) };
76 +
    }
77 +
}
78 +
79 +
/// Installed signal notification stream.
80 +
pub struct Signals {
81 +
    /// Handlers that uninstall themselves on drop.
82 +
    installed: Vec<InstalledHandler>,
83 +
    /// Signal receiver.
84 +
    receiver: mpsc::Receiver<Signal>,
85 +
    /// Pipe write end kept alive until signal handlers are uninstalled.
86 +
    _write_fd: OwnedFd,
87 +
}
88 +
89 +
impl Signals {
90 +
    /// Installs signal handlers and returns a typed notification stream.
91 +
    pub fn install(signals: &[Signal]) -> io::Result<Self> {
92 +
        // Mutex poison only happens if a previous `install` panicked mid-setup
93 +
        // (e.g. OOM in `thread::spawn`); fall through to the same exclusivity
94 +
        // check rather than surfacing a separate error.
95 +
        let mut guard = INSTALLED.lock().unwrap_or_else(|e| e.into_inner());
96 +
        if *guard {
97 +
            return Err(io::Error::new(
98 +
                io::ErrorKind::AlreadyExists,
99 +
                "signal handling is already installed",
100 +
            ));
101 +
        }
102 +
        let (read_fd, write_fd) = pipe()?;
103 +
        set_close_on_exec(read_fd.as_raw_fd())?;
104 +
        set_close_on_exec(write_fd.as_raw_fd())?;
105 +
        set_nonblocking(write_fd.as_raw_fd())?;
106 +
107 +
        WRITE_FD.store(write_fd.as_raw_fd(), Ordering::SeqCst);
108 +
        let installed = signals
109 +
            .iter()
110 +
            .copied()
111 +
            .map(Signal::install_handler)
112 +
            .collect::<io::Result<Vec<_>>>()
113 +
            .inspect_err(|_| WRITE_FD.store(NO_FD, Ordering::SeqCst))?;
114 +
115 +
        let (tx, receiver) = mpsc::channel();
116 +
        thread::spawn(move || read_signals(read_fd, tx));
117 +
        *guard = true;
118 +
119 +
        Ok(Self {
120 +
            installed,
121 +
            _write_fd: write_fd,
122 +
            receiver,
123 +
        })
124 +
    }
125 +
126 +
    /// Receives the next signal notification.
127 +
    pub fn recv(&self) -> Result<Signal, mpsc::RecvError> {
128 +
        self.receiver.recv()
129 +
    }
130 +
131 +
    /// Receives the next signal notification before the timeout expires.
132 +
    pub fn recv_timeout(
133 +
        &self,
134 +
        timeout: std::time::Duration,
135 +
    ) -> Result<Signal, mpsc::RecvTimeoutError> {
136 +
        self.receiver.recv_timeout(timeout)
137 +
    }
138 +
}
139 +
140 +
impl Drop for Signals {
141 +
    fn drop(&mut self) {
142 +
        WRITE_FD.store(NO_FD, Ordering::SeqCst);
143 +
        // Each `InstalledHandler` restores the default disposition on drop.
144 +
        self.installed.clear();
145 +
        if let Ok(mut installed) = INSTALLED.lock() {
146 +
            *installed = false;
147 +
        }
148 +
    }
149 +
}
150 +
151 +
/// Handles an OS signal.
152 +
extern "C" fn handle_signal(signal: libc::c_int) {
153 +
    // SAFETY: `errno_location` returns the thread-local errno pointer for this
154 +
    // platform.
155 +
    let location = unsafe { errno_location() };
156 +
    // SAFETY: the pointer is valid for reading and writing the current thread's errno.
157 +
    let errno = unsafe { *location };
158 +
159 +
    let fd = WRITE_FD.load(Ordering::Relaxed);
160 +
    if fd != NO_FD {
161 +
        let byte = [signal as u8];
162 +
        // SAFETY: `write` is async-signal-safe, and the byte buffer is valid for
163 +
        // the duration of the call.
164 +
        unsafe {
165 +
            let _ = libc::write(fd, byte.as_ptr().cast(), byte.len());
166 +
        }
167 +
    }
168 +
    // SAFETY: the pointer is valid for reading and writing the current thread's errno.
169 +
    unsafe {
170 +
        *location = errno;
171 +
    }
172 +
}
173 +
174 +
/// Platform accessor for this thread's `errno` storage.
175 +
#[cfg(any(target_os = "linux", target_os = "android"))]
176 +
use libc::__errno_location as errno_location;
177 +
178 +
/// Platform accessor for this thread's `errno` storage.
179 +
#[cfg(any(
180 +
    target_os = "macos",
181 +
    target_os = "ios",
182 +
    target_os = "freebsd",
183 +
    target_os = "netbsd",
184 +
    target_os = "openbsd",
185 +
    target_os = "dragonfly"
186 +
))]
187 +
use libc::__error as errno_location;
188 +
189 +
/// Reads signal bytes and forwards typed notifications.
190 +
fn read_signals(read_fd: OwnedFd, tx: mpsc::Sender<Signal>) {
191 +
    let mut file = File::from(read_fd);
192 +
    let mut bytes = [0_u8; 128];
193 +
194 +
    loop {
195 +
        let len = match file.read(&mut bytes) {
196 +
            Ok(0) => break,
197 +
            Ok(n) => n,
198 +
            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
199 +
            Err(_) => break,
200 +
        };
201 +
        for &byte in &bytes[..len] {
202 +
            let Some(signal) = Signal::from_number(i32::from(byte)) else {
203 +
                continue;
204 +
            };
205 +
            if tx.send(signal).is_err() {
206 +
                return;
207 +
            }
208 +
        }
209 +
    }
210 +
}
211 +
212 +
/// Creates a pipe.
213 +
fn pipe() -> io::Result<(OwnedFd, OwnedFd)> {
214 +
    let mut fds = [NO_FD; 2];
215 +
    // SAFETY: `fds` points to two file descriptor slots for libc to initialize.
216 +
    if unsafe { libc::pipe(fds.as_mut_ptr()) } == -1 {
217 +
        Err(io::Error::last_os_error())
218 +
    } else {
219 +
        // SAFETY: successful `pipe` initializes both file descriptors, and
220 +
        // `OwnedFd` takes responsibility for closing them.
221 +
        unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) }
222 +
    }
223 +
}
224 +
225 +
/// Sets `FD_CLOEXEC` on a file descriptor.
226 +
///
227 +
/// `FD_CLOEXEC` is the only fd-level flag POSIX defines, so a plain `F_SETFD`
228 +
/// is enough — no read-modify-write needed.
229 +
fn set_close_on_exec(fd: RawFd) -> io::Result<()> {
230 +
    // SAFETY: `F_SETFD` with a known integer flag value.
231 +
    if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 {
232 +
        return Err(io::Error::last_os_error());
233 +
    }
234 +
    Ok(())
235 +
}
236 +
237 +
/// Adds `O_NONBLOCK` to a file descriptor's status flags.
238 +
fn set_nonblocking(fd: RawFd) -> io::Result<()> {
239 +
    // SAFETY: `F_GETFL` takes no third argument; `F_SETFL` takes the flag bitmask.
240 +
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
241 +
    if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
242 +
        return Err(io::Error::last_os_error());
243 +
    }
244 +
    Ok(())
245 +
}
246 +
247 +
#[cfg(test)]
248 +
#[allow(clippy::unwrap_used)]
249 +
mod tests {
250 +
    use std::sync::Mutex;
251 +
    use std::time::Duration;
252 +
253 +
    use super::*;
254 +
255 +
    static TEST_LOCK: Mutex<()> = Mutex::new(());
256 +
257 +
    #[test]
258 +
    fn signal_channel_receives_window_change() {
259 +
        let _guard = TEST_LOCK.lock().unwrap();
260 +
        let signals = Signals::install(&[Signal::WindowChanged]).unwrap();
261 +
262 +
        // SAFETY: raising SIGWINCH for the current process exercises the handler
263 +
        // installed by this test.
264 +
        assert_eq!(unsafe { libc::raise(libc::SIGWINCH) }, 0);
265 +
        assert_eq!(
266 +
            signals.recv_timeout(Duration::from_secs(1)).unwrap(),
267 +
            Signal::WindowChanged
268 +
        );
269 +
    }
270 +
271 +
    #[test]
272 +
    fn signal_registration_is_exclusive_until_dropped() {
273 +
        let _guard = TEST_LOCK.lock().unwrap();
274 +
        let signals = Signals::install(&[Signal::WindowChanged]).unwrap();
275 +
276 +
        let Err(error) = Signals::install(&[Signal::WindowChanged]) else {
277 +
            panic!("second signal install should fail");
278 +
        };
279 +
        assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
280 +
        drop(signals);
281 +
282 +
        let _signals = Signals::install(&[Signal::WindowChanged]).unwrap();
283 +
    }
284 +
}