async_signal/
pipe.rs

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
//! A signal notifier that uses an asynchronous pipe.

use crate::Signal;

use async_io::Async;
use futures_core::ready;
use futures_io::AsyncRead;

use std::io::{self, prelude::*};
use std::mem;
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
use std::os::unix::net::UnixStream;
use std::pin::Pin;
use std::task::{Context, Poll};

const BUFFER_LEN: usize = mem::size_of::<std::os::raw::c_int>();

/// The notifier that uses an asynchronous pipe.
#[derive(Debug)]
pub(super) struct Notifier {
    /// The read end of the signal pipe.
    read: Async<UnixStream>,

    /// The write end of the signal pipe.
    write: UnixStream,
}

impl Notifier {
    /// Create a new signal notifier.
    pub(super) fn new() -> io::Result<Self> {
        let (read, write) = UnixStream::pair()?;
        let read = Async::new(read)?;
        write.set_nonblocking(true)?;

        Ok(Self { read, write })
    }

    /// Add a signal to the notifier.
    ///
    /// Returns a closure to be passed to signal-hook.
    pub(super) fn add_signal(
        &mut self,
        signal: Signal,
    ) -> io::Result<impl Fn() + Send + Sync + 'static> {
        let number = signal.number();
        let write = self.write.try_clone()?;

        Ok(move || {
            // SAFETY: to_ne_bytes() and write() are both signal safe.
            let bytes = number.to_ne_bytes();
            let _ = (&write).write(&bytes);
        })
    }

    /// Remove a signal from the notifier.
    pub(super) fn remove_signal(&mut self, _signal: Signal) -> io::Result<()> {
        Ok(())
    }

    /// Get the next signal.
    pub(super) fn poll_next(&self, cx: &mut Context<'_>) -> Poll<io::Result<Signal>> {
        let mut buffer = [0; BUFFER_LEN];
        let mut buffer_len = 0;

        // Read into the buffer.
        loop {
            if buffer_len >= BUFFER_LEN {
                break;
            }

            // Try to fill up the entire buffer.
            let buf_range = buffer_len..BUFFER_LEN;
            let res = ready!(Pin::new(&mut &self.read).poll_read(cx, &mut buffer[buf_range]));

            match res {
                Ok(0) => return Poll::Ready(Err(io::Error::from(io::ErrorKind::UnexpectedEof))),
                Ok(n) => buffer_len += n,
                Err(e) => return Poll::Ready(Err(e)),
            }
        }

        // Convert the buffer into a signal number.
        let number = std::os::raw::c_int::from_ne_bytes(buffer);

        // Convert the signal number into a signal.
        let signal = match Signal::from_number(number) {
            Some(signal) => signal,
            None => return Poll::Ready(Err(io::Error::from(io::ErrorKind::InvalidData))),
        };

        // Return the signal.
        Poll::Ready(Ok(signal))
    }
}

impl AsRawFd for Notifier {
    fn as_raw_fd(&self) -> RawFd {
        self.read.as_raw_fd()
    }
}

impl AsFd for Notifier {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.read.as_fd()
    }
}