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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! Implementation of IPC
use std::io::{ErrorKind, IoSlice, IoSliceMut};
use std::marker::PhantomData;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::net::UnixDatagram;
use std::os::unix::prelude::{AsRawFd, FromRawFd, RawFd};
use std::path::Path;
use std::time::Duration;

use anyhow::Error;
use nix::cmsg_space;
use nix::errno::Errno;
use nix::sys::socket::{
    recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, ControlMessageOwned, MsgFlags,
    SockFlag, SockType,
};
use polling::{Event, Events, Poller};
use serde::{Deserialize, Serialize};

use crate::error::{ResultExt, SystemError, TypedResult};

#[derive(Debug)]
/// Internal data type for the IPC sender
pub struct IpcSender<T> {
    socket: UnixDatagram,
    _p: PhantomData<T>,
}

#[derive(Debug)]
/// Internal data type for the IPC receiver
pub struct IpcReceiver<T> {
    socket: UnixDatagram,
    _p: PhantomData<T>,
}

impl<T> IpcSender<T>
where
    T: Serialize,
{
    /// Sends value alongside the IpcSender
    /// This fails if the resource is temporarily not available.
    pub fn try_send(&self, value: &T) -> TypedResult<()> {
        self.socket
            .send(bincode::serialize(value).typ(SystemError::Panic)?.as_ref())
            .typ(SystemError::Panic)?;
        Ok(())
    }

    /// Try sending value alongside the IpcSender for a certain duration
    pub fn try_send_timeout(&self, _value: &T, _duration: Duration) -> TypedResult<bool> {
        todo!()
    }
}

impl<T> IpcReceiver<T>
where
    T: for<'de> Deserialize<'de> + Serialize,
{
    /// Reads a single instance of T from the IpcReceiver
    pub fn try_recv(&self) -> TypedResult<Option<T>> {
        let mut buffer = vec![0; 65507];
        let len = match self.socket.recv(&mut buffer) {
            Ok(len) => len,
            Err(e) if e.kind() != ErrorKind::TimedOut => {
                return Err(Error::from(e)).typ(SystemError::Panic)
            }
            _ => return Ok(None),
        };

        // Serialize the received data into T
        bincode::deserialize(&buffer[0..len])
            .map(|r| Some(r))
            .typ(SystemError::Panic)
    }

    /// Reads a single instance of T from the IpcReceiver but fail after
    /// duration
    pub fn try_recv_timeout(&self, duration: Duration) -> TypedResult<Option<T>> {
        let poller = Poller::new().typ(SystemError::Panic)?;
        unsafe {
            poller
                .add(&self.socket, Event::readable(42))
                .typ(SystemError::Panic)?;
        }
        let poll_res = poller.wait(&mut Events::new(), Some(duration));
        if let Err(_) | Ok(0) = poll_res {
            return Ok(None);
        }

        self.try_recv()
    }
}

pub fn bind_receiver<T>(path: &Path) -> TypedResult<IpcReceiver<T>> {
    let socket = UnixDatagram::bind(path).typ(SystemError::Panic)?;
    socket.set_nonblocking(true).typ(SystemError::Panic)?;
    Ok(IpcReceiver::from(socket))
}

pub fn connect_sender<T>(path: &Path) -> TypedResult<IpcSender<T>> {
    let socket = UnixDatagram::unbound().typ(SystemError::Panic)?;
    socket.connect(path).typ(SystemError::Panic)?;
    socket.set_nonblocking(true).typ(SystemError::Panic)?;
    Ok(IpcSender::from(socket))
}

impl<T> AsRawFd for IpcSender<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.socket.as_raw_fd()
    }
}

impl<T> AsRawFd for IpcReceiver<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.socket.as_raw_fd()
    }
}

impl<T> AsFd for IpcSender<T> {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.socket.as_fd()
    }
}

impl<T> AsFd for IpcReceiver<T> {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.socket.as_fd()
    }
}

impl<T> From<UnixDatagram> for IpcReceiver<T> {
    fn from(value: UnixDatagram) -> Self {
        Self {
            socket: value,
            _p: PhantomData,
        }
    }
}

impl<T> From<UnixDatagram> for IpcSender<T> {
    fn from(value: UnixDatagram) -> Self {
        Self {
            socket: value,
            _p: PhantomData,
        }
    }
}

impl<T> From<OwnedFd> for IpcSender<T> {
    fn from(value: OwnedFd) -> Self {
        Self {
            socket: UnixDatagram::from(value),
            _p: PhantomData,
        }
    }
}

impl<T> From<OwnedFd> for IpcReceiver<T> {
    fn from(value: OwnedFd) -> Self {
        Self {
            socket: UnixDatagram::from(value),
            _p: PhantomData,
        }
    }
}

impl<T> FromRawFd for IpcSender<T> {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self {
            socket: UnixDatagram::from_raw_fd(fd),
            _p: PhantomData,
        }
    }
}

impl<T> FromRawFd for IpcReceiver<T> {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self {
            socket: UnixDatagram::from_raw_fd(fd),
            _p: PhantomData,
        }
    }
}

/// Creates a pair of sockets that are meant for passing file descriptors to
/// partitions.
pub fn io_pair<T>() -> TypedResult<(IoSender<T>, IoReceiver<T>)> {
    let (tx, rx) = socketpair(
        AddressFamily::Unix,
        SockType::Datagram,
        None,
        SockFlag::empty(),
    )
    .typ(SystemError::Panic)?;
    Ok((IoSender::from(tx), IoReceiver::from(rx)))
}

#[derive(Debug)]
/// Internal data type for the IO resource sender
pub struct IoSender<T> {
    socket: UnixDatagram,
    _p: PhantomData<T>,
}

impl<T> IoSender<T>
where
    T: AsRawFd,
{
    /// Sends a resource to the receiving socket.
    pub fn try_send(&self, resource: impl AsRawFd) -> TypedResult<()> {
        let fds = [resource.as_raw_fd()];
        let cmsg = [ControlMessage::ScmRights(&fds)];
        let buffer = [0u8; 1];
        let iov = [IoSlice::new(buffer.as_slice())];
        let io_fd = self.socket.as_raw_fd();
        sendmsg::<()>(io_fd, &iov, &cmsg, MsgFlags::empty(), None).typ(SystemError::Panic)?;
        Ok(())
    }
}

impl<T> IoReceiver<T>
where
    T: FromRawFd,
{
    /// Returns the next available IO resource.
    /// Returns `None`, if no further resources can be read from the socket.
    ///
    /// # Safety
    /// Only safe if `T` matches the type of the file descriptor.
    pub unsafe fn try_receive(&self) -> TypedResult<Option<T>> {
        let mut cmsg = cmsg_space!(RawFd);
        let mut iobuf = [0u8; 1];
        let mut iov = [IoSliceMut::new(&mut iobuf)];
        let io_fd = self.socket.as_raw_fd();
        match recvmsg::<()>(io_fd, &mut iov, Some(&mut cmsg), MsgFlags::MSG_DONTWAIT) {
            Ok(msg) => {
                if let Some(ControlMessageOwned::ScmRights(fds)) =
                    msg.cmsgs().typ(SystemError::Panic)?.next()
                {
                    if let &[raw_fd] = fds.as_slice() {
                        let sock = unsafe { T::from_raw_fd(raw_fd) };
                        return Ok(Some(sock));
                    }
                }
                Ok(None)
            }
            // This should never block since the socket is only written to before the partition
            // starts.
            Err(e) if e != Errno::EAGAIN && e != Errno::EINTR => {
                Err(Error::from(e)).typ(SystemError::Panic)
            }
            _ => Ok(None),
        }
    }
}

#[derive(Debug)]
/// Internal data type for the IO resource sender
pub struct IoReceiver<T> {
    socket: UnixDatagram,
    _p: PhantomData<T>,
}

impl<T> AsRawFd for IoSender<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.socket.as_raw_fd()
    }
}

impl<T> AsRawFd for IoReceiver<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.socket.as_raw_fd()
    }
}

impl<T> From<OwnedFd> for IoSender<T> {
    fn from(value: OwnedFd) -> Self {
        Self {
            socket: UnixDatagram::from(value),
            _p: PhantomData,
        }
    }
}

impl<T> From<OwnedFd> for IoReceiver<T> {
    fn from(value: OwnedFd) -> Self {
        Self {
            socket: UnixDatagram::from(value),
            _p: PhantomData,
        }
    }
}

impl<T> FromRawFd for IoSender<T> {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self {
            socket: UnixDatagram::from_raw_fd(fd),
            _p: PhantomData,
        }
    }
}

impl<T> FromRawFd for IoReceiver<T> {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self {
            socket: UnixDatagram::from_raw_fd(fd),
            _p: PhantomData,
        }
    }
}