1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//! Library for easier and safe Unix signal handling with async Stream.
//!
//! You can use this crate with any async runtime.

use std::collections::{HashMap, HashSet, VecDeque};
use std::convert::TryFrom;
use std::os::raw::c_int;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::task::Context;
use std::task::{Poll, Waker};

use futures_util::stream::Stream;
use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
use nix::Result;

use lazy_static::lazy_static;

lazy_static! {
    static ref ID_GEN: AtomicU64 = AtomicU64::new(0);
    static ref SIGNAL_SET: RwLock<HashMap<u64, Arc<Mutex<InnerSignals>>>> =
        RwLock::new(HashMap::new());
    static ref SIGNAL_RECORD: Mutex<HashMap<c_int, usize>> = Mutex::new(HashMap::new());
}

extern "C" fn handle(receive_signal: c_int) {
    let signal_map = SIGNAL_SET.read().unwrap();

    for (_, signal) in signal_map.iter() {
        let mut signal = signal.lock().unwrap();

        if signal.wants.contains(&receive_signal) {
            signal.queue.push_back(receive_signal);

            if let Some(waker) = signal.waker.take() {
                waker.wake();
            }
        }
    }
}

#[derive(Debug)]
struct InnerSignals {
    queue: VecDeque<c_int>,
    waker: Option<Waker>,
    wants: HashSet<c_int>,
}

impl InnerSignals {
    fn new(wants: HashSet<c_int>) -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self {
            queue: VecDeque::new(),
            waker: None,
            wants,
        }))
    }
}

/// Handle unix signal like `signal_hook::iterator::Signals`, receive signals
/// with `futures::stream::Stream`.
///
/// If multi `Signals` register a same signal, all of them will receive the signal.
///
/// If you drop all `Signals` which handle a signal like `SIGINT`, when process receive
/// this signal, will use system default handler.
///
/// # Notes:
/// You can't handle `SIGKILL` or `SIGSTOP`.
#[derive(Debug)]
pub struct Signals {
    id: u64,
    inner: Arc<Mutex<InnerSignals>>,
}

impl Drop for Signals {
    fn drop(&mut self) {
        let mut signal_set = SIGNAL_SET.write().unwrap();

        let mut signal_record = SIGNAL_RECORD.lock().unwrap();

        signal_set.remove(&self.id);

        let inner = self.inner.lock().unwrap();

        for drop_signal in inner.wants.iter() {
            let count = signal_record.get_mut(drop_signal).expect("must exist");

            if *count > 1 {
                *count -= 1;
                continue;
            }

            signal_record.remove(drop_signal);

            // no one wants to handle this signal, let default handler handle it.
            let default_handler = SigHandler::SigDfl;
            let default_action =
                SigAction::new(default_handler, SaFlags::SA_RESTART, SigSet::empty());

            unsafe {
                // TODO should I ignore error?
                let _ = sigaction(
                    Signal::try_from(*drop_signal).expect("checked"),
                    &default_action,
                );
            }
        }
    }
}

impl Signals {
    /// Creates the `Signals` structure, all signals will be registered.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_signals::Signals;
    /// use futures_util::StreamExt;
    /// use nix::sys;
    /// use nix::unistd;
    ///
    /// #[async_std::main]
    /// async fn main() {
    ///     let mut signals = Signals::new(vec![libc::SIGINT]).unwrap();
    ///
    ///     let pid = unistd::getpid();
    ///     sys::signal::kill(pid, Some(sys::signal::SIGINT)).unwrap();
    ///
    ///     let signal = signals.next().await.unwrap();
    ///
    ///     assert_eq!(signal, libc::SIGINT);
    /// }
    /// ```
    pub fn new<I: IntoIterator<Item = c_int>>(signals: I) -> Result<Signals> {
        let id = ID_GEN.fetch_add(1, Ordering::Relaxed);

        let mut signal_set = SIGNAL_SET.write().unwrap();

        let mut signal_record = SIGNAL_RECORD.lock().unwrap();

        let handler = SigHandler::Handler(handle);

        let action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty());

        let mut wants = HashSet::new();

        for signal in signals {
            // register handle
            unsafe {
                sigaction(Signal::try_from(signal)?, &action)?;
            }

            wants.insert(signal);

            // increase signal record count
            signal_record
                .entry(signal)
                .and_modify(|count| *count += 1)
                .or_insert(1);
        }

        let inner_signals = InnerSignals::new(wants);

        signal_set.insert(id, inner_signals.clone());

        Ok(Self {
            id,
            inner: inner_signals,
        })
    }

    /// Registers another signal to a created `Signals`.
    ///
    /// # Examples
    ///
    /// ```
    /// use async_signals::Signals;
    /// use futures_util::StreamExt;
    /// use nix::sys;
    /// use nix::unistd;
    ///
    /// #[async_std::main]
    /// async fn main() {
    ///     let mut signals = Signals::new(vec![libc::SIGHUP]).unwrap();
    ///
    ///     signals.add_signal(libc::SIGINT).unwrap();
    ///
    ///     let pid = unistd::getpid();
    ///     sys::signal::kill(pid, Some(sys::signal::SIGINT)).unwrap();
    ///
    ///     let signal = signals.next().await.unwrap();
    ///
    ///     assert_eq!(signal, libc::SIGINT);
    /// }
    /// ```
    #[inline]
    pub fn add_signal(&mut self, signal: c_int) -> Result<()> {
        let mut signal_record = SIGNAL_RECORD.lock().unwrap();

        let handler = SigHandler::Handler(handle);

        let action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty());

        // register handle
        unsafe {
            sigaction(Signal::try_from(signal)?, &action)?;
        }

        let mut inner = self.inner.lock().unwrap();

        inner.wants.insert(signal);

        // increase signal record count
        signal_record
            .entry(signal)
            .and_modify(|count| *count += 1)
            .or_insert(1);

        Ok(())
    }
}

impl Stream for Signals {
    type Item = c_int;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut inner = self.inner.lock().unwrap();

        if let Some(signal) = inner.queue.pop_front() {
            return Poll::Ready(Some(signal));
        }

        inner.waker.replace(cx.waker().clone());

        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use futures_util::StreamExt;
    use nix::sys;
    use nix::unistd;

    use super::*;

    #[async_std::test]
    async fn interrupt() {
        let mut signal = Signals::new(vec![libc::SIGINT]).unwrap();

        let pid = unistd::getpid();

        sys::signal::kill(pid, Some(sys::signal::SIGINT)).unwrap();

        let interrupt = signal.next().await.unwrap();

        assert_eq!(interrupt, libc::SIGINT);
    }

    #[async_std::test]
    async fn add_signal() {
        let mut signal = Signals::new(vec![libc::SIGHUP]).unwrap();

        signal.add_signal(libc::SIGINT).unwrap();

        let pid = unistd::getpid();

        sys::signal::kill(pid, Some(sys::signal::SIGINT)).unwrap();

        let interrupt = signal.next().await.unwrap();

        assert_eq!(interrupt, libc::SIGINT);
    }

    #[async_std::test]
    async fn multi_signals() {
        let mut signal1 = Signals::new(vec![libc::SIGINT]).unwrap();

        let mut signal2 = Signals::new(vec![libc::SIGINT]).unwrap();

        let pid = unistd::getpid();

        sys::signal::kill(pid, Some(sys::signal::SIGINT)).unwrap();

        assert_eq!(signal1.next().await.unwrap(), libc::SIGINT);

        assert_eq!(signal2.next().await.unwrap(), libc::SIGINT);
    }
}