tokio_unix_ipc/
bootstrap.rs

1use std::fs;
2use std::io;
3use std::os::unix::prelude::RawFd;
4use std::path::{Path, PathBuf};
5use tokio::sync::Mutex;
6
7use tokio::net::UnixListener;
8
9use crate::raw_channel::RawSender;
10
11/// A bootstrap helper.
12///
13/// This creates a unix socket that is linked to the file system so
14/// that a [`Receiver`](struct.Receiver.html) can connect to it.  It
15/// lets you send one or more messages to the connected receiver.
16///
17/// The bootstrapper lets you send both to raw and typed receivers
18/// on the other side. To send to a raw one use the
19/// [`send_raw`](Self::send_raw) method.
20#[derive(Debug)]
21pub struct Bootstrapper {
22    listener: UnixListener,
23    sender: Mutex<Option<RawSender>>,
24    path: PathBuf,
25}
26
27impl Bootstrapper {
28    /// Creates a bootstrapper at a random socket in `/tmp`.
29    pub fn new() -> io::Result<Bootstrapper> {
30        use rand::{thread_rng, RngCore};
31        use std::time::{SystemTime, UNIX_EPOCH};
32
33        let mut dir = std::env::temp_dir();
34        let mut rng = thread_rng();
35        let now = SystemTime::now();
36        dir.push(format!(
37            ".rust-unix-ipc.{}-{}.sock",
38            now.duration_since(UNIX_EPOCH).unwrap().as_secs(),
39            rng.next_u64(),
40        ));
41        Bootstrapper::bind(&dir)
42    }
43
44    /// Creates a bootstrapper at a specific socket path.
45    pub fn bind<P: AsRef<Path>>(p: P) -> io::Result<Bootstrapper> {
46        fs::remove_file(&p).ok();
47        let listener = UnixListener::bind(&p)?;
48        Ok(Bootstrapper {
49            listener,
50            sender: Mutex::new(None),
51            path: p.as_ref().to_path_buf(),
52        })
53    }
54
55    /// Returns the path of the socket.
56    pub fn path(&self) -> &Path {
57        &self.path
58    }
59
60    /// Sends a raw value into the boostrapper.
61    ///
62    /// This can be called multiple times to send more than one value
63    /// into the inner socket. On the other side a
64    /// [`RawReceiver`](crate::RawReceiver) must be used.
65    pub async fn send_raw(&self, data: &[u8], fds: &[RawFd]) -> io::Result<usize> {
66        if self.sender.lock().await.is_none() {
67            let (sock, _) = self.listener.accept().await?;
68            let sender = RawSender::from_std(sock.into_std()?)?;
69            *self.sender.lock().await = Some(sender);
70        }
71        let guard = self.sender.lock().await;
72
73        guard.as_ref().unwrap().send(data, fds).await
74    }
75
76    /// Sends a value into the boostrapper.
77    ///
78    /// This can be called multiple times to send more than one value
79    /// into the inner socket.  On the other side a correctly typed
80    /// [`Receiver`](crate::Receiver) must be used.
81    ///
82    /// This requires the `serde` feature.
83    #[cfg(feature = "serde")]
84    pub async fn send<T: serde_::Serialize + serde_::de::DeserializeOwned>(
85        &self,
86        data: T,
87    ) -> io::Result<()> {
88        // replicate the logic from the typed sender with the dummy
89        // bool here.
90        let (bytes, fds) = crate::serde::serialize((data, true))?;
91        self.send_raw(&bytes, &fds).await.map(|_| ())
92    }
93}
94
95impl Drop for Bootstrapper {
96    fn drop(&mut self) {
97        fs::remove_file(&self.path).ok();
98    }
99}