1use 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);
26static ENABLED: AtomicBool = AtomicBool::new(false);
28static SIGS: Mutex<Vec<Signal>> = Mutex::new(Vec::new());
29static HND_WAKER: AtomicWaker = AtomicWaker::new();
30static PANIC_WAKER: OnceLock<mpsc::SyncSender<()>> = OnceLock::new();
33
34#[derive(Clone, Debug)]
36pub enum Signal {
37 Hup,
39 Int,
41 Term,
43 Quit,
45 Panic(PanicSource),
47}
48
49#[derive(Clone, Debug)]
51pub enum PanicSource {
52 Sig(&'static str),
58 App(Arc<str>, Backtrace),
60}
61
62pub 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
87pub fn is_enabled() -> bool {
92 CUR_SYS.lock().is_some()
93}
94
95type Registration = MutexGuard<'static, Option<System>>;
96
97fn 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
118fn 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
140fn handle_signal(sig: Signal) {
144 SIGS.lock().push(sig);
145 HND_WAKER.wake();
146}
147
148#[cfg(target_family = "unix")]
149static 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")]
156pub(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 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 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")]
209pub(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 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")]
227pub(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 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")]
255pub(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")]
295pub(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 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 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 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"))]
347pub(crate) fn enable_fatal_signals() {}
349
350#[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 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 unsafe {
402 if libc::getpid() == *pid {
404 let _ = libc::write(write.as_raw_fd(), byte.as_ptr().cast(), 1);
405 }
406 }
407 }
408
409 let prev = prev
412 .get()
413 .copied()
414 .unwrap_or_else(|| SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty()));
415 unsafe {
417 let _ = signal::sigaction(sig, &prev);
418 }
419 Errno::set_raw(errno);
420}
421
422pub(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 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;