Skip to main content

ntex_rt/
signals.rs

1//! Process-signal subscriptions and optional application-panic notifications.
2//!
3//! Enable handling with [`System::enable_signals`] or
4//! [`Builder::signals`](crate::Builder::signals). Only one system handles
5//! process signals at a time; subscriptions belong to the current system.
6//! Unix delivers hangup, interrupt, termination, and quit signals, plus
7//! best-effort fatal-signal notifications with
8//! [`Builder::fatal_signals`](crate::Builder::fatal_signals). Windows delivers
9//! Ctrl-C as [`Signal::Int`]. Application panics additionally require
10//! [`Builder::panic_handling`](crate::Builder::panic_handling).
11use std::sync::{Arc, OnceLock, atomic::AtomicBool, atomic::Ordering, mpsc};
12use std::{cell::RefCell, future::poll_fn, panic, task::Poll};
13
14use atomic_waker::AtomicWaker;
15use ntex_error::Backtrace;
16use parking_lot::{Mutex, MutexGuard};
17
18use crate::System;
19
20thread_local! {
21    static STOP: RefCell<Option<oneshot::Sender<()>>> = const { RefCell::new(None) };
22    static HANDLERS: RefCell<Vec<oneshot::Sender<Arc<[Signal]>>>> = RefCell::default();
23}
24
25static CUR_SYS: Mutex<Option<System>> = Mutex::new(None);
26// Mirrors `CUR_SYS`, the panic hook must not lock it.
27static ENABLED: AtomicBool = AtomicBool::new(false);
28static SIGS: Mutex<Vec<Signal>> = Mutex::new(Vec::new());
29static HND_WAKER: AtomicWaker = AtomicWaker::new();
30// The panic hook runs on the panicking thread, some runtimes (compio) abort
31// the process if a task is woken there. Panics are woken from a dedicated thread.
32static PANIC_WAKER: OnceLock<mpsc::SyncSender<()>> = OnceLock::new();
33
34/// Process and application signals delivered to the runtime.
35#[derive(Clone, Debug)]
36pub enum Signal {
37    /// A Unix hangup signal (`SIGHUP`).
38    Hup,
39    /// An interrupt signal (`SIGINT` on Unix, Ctrl-C on Windows).
40    Int,
41    /// A Unix termination signal (`SIGTERM`).
42    Term,
43    /// A Unix quit signal (`SIGQUIT`).
44    Quit,
45    /// An application panic or a best-effort fatal-signal notification.
46    Panic(PanicSource),
47}
48
49/// Source of a panic signal.
50#[derive(Clone, Debug)]
51pub enum PanicSource {
52    /// A `SIGSEGV` or `SIGABRT` signal was received.
53    ///
54    /// Requires [`Builder::fatal_signals`](crate::Builder::fatal_signals).
55    /// Delivery is best effort; a fatal fault can terminate the process before
56    /// the runtime or server handles this notification.
57    Sig(&'static str),
58    /// An application panic message and its captured, unresolved backtrace.
59    App(Arc<str>, Backtrace),
60}
61
62/// Registers interest in the next batch of signals.
63///
64/// The returned one-shot receiver handles one notification. Call this function
65/// again after each notification to continue receiving signals.
66///
67/// Registration is scheduled on the current system's primary arbiter. Each
68/// batch is broadcast to the subscriptions registered when it is dispatched;
69/// this is not a replayable signal history. This function does not enable signal
70/// handling, and subscriptions in a system that does not own signal handling
71/// do not receive process signals.
72///
73/// # Panics
74///
75/// Panics if no system is installed on the current thread.
76pub fn signal() -> oneshot::AsyncReceiver<Arc<[Signal]>> {
77    let (tx, rx) = oneshot::async_channel();
78    System::current().handle().spawn_detached(async move {
79        HANDLERS.with(|handlers| {
80            handlers.borrow_mut().push(tx);
81        });
82    });
83
84    rx
85}
86
87/// Returns whether any system currently owns process signal handling.
88///
89/// Unlike [`System::signals`], this is process-wide and does not require a
90/// current system.
91pub fn is_enabled() -> bool {
92    CUR_SYS.lock().is_some()
93}
94
95type Registration = MutexGuard<'static, Option<System>>;
96
97/// Registers the system as the signal handler.
98///
99/// Returns the lock guard, so handlers are installed before other systems
100/// can register or unregister.
101fn register_system(sys: &System) -> Option<Registration> {
102    let mut cur = CUR_SYS.lock();
103    if cur.is_some() {
104        None
105    } else {
106        *cur = Some(sys.clone());
107        ENABLED.store(true, Ordering::Release);
108
109        let (tx, rx) = oneshot::async_channel();
110        sys.handle().spawn_detached(signals(rx));
111        STOP.with(|stop| {
112            *stop.borrow_mut() = Some(tx);
113        });
114        Some(cur)
115    }
116}
117
118/// Unregisters the system if it handles signals.
119///
120/// Returns the lock guard, so handlers are removed before other systems
121/// can register.
122fn unregister_system(sys: &System) -> Option<Registration> {
123    let mut cur = CUR_SYS.lock();
124    if cur.as_ref().is_some_and(|cur| cur.id() == sys.id()) {
125        cur.take();
126        ENABLED.store(false, Ordering::Release);
127        sys.handle().spawn_detached(async move {
128            STOP.with(|stop| {
129                if let Some(tx) = stop.borrow_mut().take() {
130                    let _ = tx.send(());
131                }
132            });
133        });
134        Some(cur)
135    } else {
136        None
137    }
138}
139
140/// Queue signal and wake the system.
141///
142/// Must not be called from a signal handler.
143fn handle_signal(sig: Signal) {
144    SIGS.lock().push(sig);
145    HND_WAKER.wake();
146}
147
148#[cfg(target_family = "unix")]
149/// Signal delivery thread handle and `SIGUSR2` handler id.
150static SIG_HANDLERS: Mutex<(
151    Option<signal_hook::iterator::Handle>,
152    Option<signal_hook::SigId>,
153)> = Mutex::new((None, None));
154
155#[cfg(target_family = "unix")]
156/// Register signal handler.
157///
158/// Returns `false` if signals are handled by another system.
159pub(crate) fn start(sys: &System) -> bool {
160    if let Some(_registration) = register_system(sys) {
161        use signal_hook::consts::signal::{SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGUSR2};
162        use signal_hook::{iterator::Signals, low_level::register};
163
164        // signal handlers only write to a self-pipe, signals are
165        // dispatched from a regular thread
166        let handle = match Signals::new([SIGHUP, SIGINT, SIGTERM, SIGQUIT]) {
167            Ok(mut signals) => {
168                let handle = signals.handle();
169                let result = std::thread::Builder::new()
170                    .name("ntex-rt:signals".to_string())
171                    .spawn(move || {
172                        for sig in signals.forever() {
173                            handle_signal(match sig {
174                                SIGHUP => Signal::Hup,
175                                SIGINT => Signal::Int,
176                                SIGTERM => Signal::Term,
177                                SIGQUIT => Signal::Quit,
178                                _ => continue,
179                            });
180                        }
181                    });
182                match result {
183                    Ok(_) => Some(handle),
184                    Err(e) => {
185                        log::error!("Cannot start signal handling thread: {e:?}");
186                        None
187                    }
188                }
189            }
190            Err(e) => {
191                log::error!("Cannot install signal handlers: {e:?}");
192                None
193            }
194        };
195
196        // SAFETY: The callback only reads atomics and captures frames into the preallocated signal slot.
197        let usr2 = unsafe { register(SIGUSR2, || crate::watchdog::sig_usr2()) };
198        if usr2.is_err() {
199            log::error!("Cannot install signal handler for SIGUSR2");
200        }
201        *SIG_HANDLERS.lock() = (handle, usr2.ok());
202        true
203    } else {
204        false
205    }
206}
207
208#[cfg(target_family = "unix")]
209/// Unregister signal handler.
210pub(crate) fn stop(sys: &System) {
211    if let Some(_registration) = unregister_system(sys) {
212        let (handle, usr2) = std::mem::take(&mut *SIG_HANDLERS.lock());
213        if let Some(handle) = handle {
214            // the thread exits and unregisters handlers
215            handle.close();
216        }
217        if let Some(usr2) = usr2 {
218            signal_hook::low_level::unregister(usr2);
219        }
220    }
221}
222
223#[cfg(target_family = "windows")]
224static CTRLC_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
225
226#[cfg(target_family = "windows")]
227/// Register signal handler.
228///
229/// Signals are handled by oneshots, you have to re-register
230/// after each signal. Returns `false` if signals are handled by another system.
231pub(crate) fn start(sys: &System) -> bool {
232    use std::sync::atomic::Ordering;
233    static ONCE: std::sync::Once = std::sync::Once::new();
234
235    if let Some(_registration) = register_system(sys) {
236        // the handler cannot be removed, it ignores signals while disabled
237        ONCE.call_once(|| {
238            let result = ctrlc::set_handler(|| {
239                if CTRLC_ENABLED.load(Ordering::Acquire) {
240                    handle_signal(Signal::Int);
241                }
242            });
243            if let Err(e) = result {
244                log::error!("Cannot install Ctrl-C handler: {e:?}");
245            }
246        });
247        CTRLC_ENABLED.store(true, Ordering::Release);
248        true
249    } else {
250        false
251    }
252}
253
254#[cfg(target_family = "windows")]
255/// Unregister signal handler.
256pub(crate) fn stop(sys: &System) {
257    if let Some(_registration) = unregister_system(sys) {
258        CTRLC_ENABLED.store(false, std::sync::atomic::Ordering::Release);
259        log::info!("Signals handling is disabled");
260    }
261}
262
263async fn signals(rx: oneshot::AsyncReceiver<()>) {
264    let mut rx = std::pin::pin!(rx);
265
266    poll_fn(|cx| {
267        if rx.as_mut().poll(cx).is_ready() {
268            Poll::Ready(())
269        } else {
270            HND_WAKER.register(cx.waker());
271
272            let sigs = std::mem::take(&mut *SIGS.lock());
273            if !sigs.is_empty() {
274                let sigs: Arc<[Signal]> = Arc::from(sigs);
275
276                HANDLERS.with(|handlers| {
277                    for tx in handlers.borrow_mut().drain(..) {
278                        let _ = tx.send(sigs.clone());
279                    }
280                });
281            }
282
283            Poll::Pending
284        }
285    })
286    .await;
287}
288
289#[cfg(target_family = "unix")]
290static PREV_SIGSEGV: std::sync::OnceLock<nix::sys::signal::SigAction> = std::sync::OnceLock::new();
291#[cfg(target_family = "unix")]
292static PREV_SIGABRT: std::sync::OnceLock<nix::sys::signal::SigAction> = std::sync::OnceLock::new();
293
294#[cfg(target_family = "unix")]
295/// Installs the `SIGSEGV` and `SIGABRT` handlers, once per process.
296///
297/// Fatal signals are delivered as `Signal::Panic` only while signal
298/// handling is enabled.
299pub(crate) fn enable_fatal_signals() {
300    use nix::sys::signal;
301
302    static ONCE: std::sync::Once = std::sync::Once::new();
303
304    ONCE.call_once(|| {
305        if let Err(e) = start_fatal_signal_thread() {
306            log::error!("Cannot start fatal signal handling thread: {e:?}");
307        }
308
309        // Use u128 for alignment.
310        let buf = Vec::leak(vec![0u128; 4096]);
311        let stack = libc::stack_t {
312            ss_sp: buf.as_ptr() as *mut libc::c_void,
313            ss_flags: 0,
314            ss_size: std::mem::size_of_val(buf),
315        };
316        let mut old = libc::stack_t {
317            ss_sp: std::ptr::null_mut(),
318            ss_flags: 0,
319            ss_size: 0,
320        };
321        // SAFETY: The aligned alternate stack is leaked, and both stack descriptors are valid for this call.
322        let result = unsafe { libc::sigaltstack(&raw const stack, &raw mut old) };
323        if result != 0 {
324            log::error!("Cannot set signal stack");
325        }
326
327        let sig_action = signal::SigAction::new(
328            signal::SigHandler::Handler(sig_segv),
329            signal::SaFlags::SA_ONSTACK,
330            signal::SigSet::empty(),
331        );
332        // SAFETY: `sig_segv` has the signal-handler ABI and only uses signal-safe operations.
333        unsafe {
334            match signal::sigaction(signal::SIGSEGV, &sig_action) {
335                Ok(prev) => _ = PREV_SIGSEGV.set(prev),
336                Err(_) => log::error!("Cannot install signal handler for SIGSEGV"),
337            }
338            match signal::sigaction(signal::SIGABRT, &sig_action) {
339                Ok(prev) => _ = PREV_SIGABRT.set(prev),
340                Err(_) => log::error!("Cannot install signal handler for SIGABRT"),
341            }
342        }
343    });
344}
345
346#[cfg(not(target_family = "unix"))]
347/// Fatal signal handlers are only supported on Unix.
348pub(crate) fn enable_fatal_signals() {}
349
350// Both ends stay open for the process lifetime: a handler must never write to a
351// recycled descriptor or raise SIGPIPE if the delivery thread exits.
352#[cfg(target_family = "unix")]
353static FATAL_PIPE: OnceLock<(
354    libc::pid_t,
355    std::os::unix::net::UnixStream,
356    std::os::unix::net::UnixStream,
357)> = OnceLock::new();
358
359#[cfg(target_family = "unix")]
360fn start_fatal_signal_thread() -> std::io::Result<()> {
361    use std::{io::Read, os::unix::net::UnixStream};
362
363    let (read, write) = UnixStream::pair()?;
364    write.set_nonblocking(true)?;
365    // SAFETY: `getpid` takes no arguments and accesses no caller-provided memory.
366    let (_, read, _) = FATAL_PIPE.get_or_init(|| (unsafe { libc::getpid() }, read, write));
367    std::thread::Builder::new()
368        .name("ntex-rt:crashes".to_string())
369        .spawn(move || {
370            let mut read = read;
371            let mut byte = [0];
372            while read.read_exact(&mut byte).is_ok() {
373                let name = match byte[0] {
374                    b'A' => "SIGABRT",
375                    b'S' => "SIGSEGV",
376                    _ => continue,
377                };
378                if ENABLED.load(Ordering::Acquire) {
379                    handle_signal(Signal::Panic(PanicSource::Sig(name)));
380                }
381            }
382        })?;
383    Ok(())
384}
385
386#[cfg(target_family = "unix")]
387extern "C" fn sig_segv(v: i32) {
388    use std::os::fd::AsRawFd;
389
390    use nix::errno::Errno;
391    use nix::sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet};
392
393    let errno = Errno::last_raw();
394    let (sig, prev, byte) = if v == libc::SIGABRT {
395        (signal::SIGABRT, &PREV_SIGABRT, b"A")
396    } else {
397        (signal::SIGSEGV, &PREV_SIGSEGV, b"S")
398    };
399    if let Some((pid, _, write)) = FATAL_PIPE.get() {
400        // SAFETY: The process-lifetime descriptor and one-byte buffer remain valid; both calls are signal-safe.
401        unsafe {
402            // A forked child must not shut down its parent's server.
403            if libc::getpid() == *pid {
404                let _ = libc::write(write.as_raw_fd(), byte.as_ptr().cast(), 1);
405            }
406        }
407    }
408
409    // restore the previous handler, it handles the signal raised again by
410    // the faulting instruction or by `abort()`, otherwise the process never exits
411    let prev = prev
412        .get()
413        .copied()
414        .unwrap_or_else(|| SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty()));
415    // SAFETY: `prev` is a saved valid action or the default action; restoring it is signal-safe.
416    unsafe {
417        let _ = signal::sigaction(sig, &prev);
418    }
419    Errno::set_raw(errno);
420}
421
422/// Installs the panic hook, once per process.
423///
424/// The previous hook is called first. Panics are delivered as
425/// `Signal::Panic` only while signal handling is enabled.
426pub(crate) fn enable_panic_handling() {
427    static ONCE: std::sync::Once = std::sync::Once::new();
428
429    ONCE.call_once(|| {
430        let (tx, rx) = mpsc::sync_channel::<()>(1);
431        let result = std::thread::Builder::new()
432            .name("ntex-rt:panics".to_string())
433            .spawn(move || {
434                for () in rx {
435                    HND_WAKER.wake();
436                }
437            });
438        match result {
439            Ok(_) => _ = PANIC_WAKER.set(tx),
440            Err(e) => log::error!("Cannot start panic handling thread: {e:?}"),
441        }
442
443        let prev = panic::take_hook();
444        panic::set_hook(Box::new(move |panic_info| {
445            prev(panic_info);
446
447            if !ENABLED.load(Ordering::Acquire) {
448                return;
449            }
450
451            let info: Arc<str> = if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
452                Arc::from(s.to_string())
453            } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
454                Arc::from(s.clone())
455            } else {
456                Arc::from("panic")
457            };
458            let bt = if let Some(loc) = panic_info.location() {
459                let s = Box::new(loc.file().to_string());
460                let filename = Box::leak(s);
461                Backtrace::with_filename(filename)
462            } else {
463                Backtrace::new(panic::Location::caller())
464            };
465
466            SIGS.lock().push(Signal::Panic(PanicSource::App(info, bt)));
467            if let Some(tx) = PANIC_WAKER.get() {
468                // a pending wake covers this panic too
469                let _ = tx.try_send(());
470            }
471        }));
472    });
473}
474
475#[cfg(all(test, any(target_family = "windows", target_family = "unix")))]
476#[path = "../tests/unit/signals.rs"]
477mod tests;