Skip to main content

netlink_sys/
smol.rs

1// SPDX-License-Identifier: MIT
2
3use std::{
4    io,
5    os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, RawFd},
6    task::{Context, Poll},
7};
8
9use async_io::Async;
10
11use futures_util::ready;
12
13use log::trace;
14
15use crate::{AsyncSocket, Socket, SocketAddr};
16
17/// An I/O object representing a Netlink socket.
18pub struct SmolSocket(Async<Socket>);
19
20impl FromRawFd for SmolSocket {
21    unsafe fn from_raw_fd(fd: RawFd) -> Self {
22        let socket = Socket::from_raw_fd(fd);
23        socket.set_non_blocking(true).unwrap();
24        SmolSocket(Async::new(socket).unwrap())
25    }
26}
27
28impl AsRawFd for SmolSocket {
29    fn as_raw_fd(&self) -> RawFd {
30        self.0.get_ref().as_raw_fd()
31    }
32}
33
34impl AsFd for SmolSocket {
35    fn as_fd(&self) -> BorrowedFd<'_> {
36        self.0.get_ref().as_fd()
37    }
38}
39
40// async_io::Async<..>::{read,write}_with[_mut] functions try IO first,
41// and only register context if it would block.
42// replicate this in these poll functions:
43impl SmolSocket {
44    fn poll_write_with<F, R>(
45        &self,
46        cx: &mut Context<'_>,
47        mut op: F,
48    ) -> Poll<io::Result<R>>
49    where
50        F: FnMut(&Self) -> io::Result<R>,
51    {
52        loop {
53            match op(self) {
54                Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
55                res => return Poll::Ready(res),
56            }
57            // try again if writable now, otherwise come back later:
58            ready!(self.0.poll_writable(cx))?;
59        }
60    }
61
62    fn poll_read_with<F, R>(
63        &self,
64        cx: &mut Context<'_>,
65        mut op: F,
66    ) -> Poll<io::Result<R>>
67    where
68        F: FnMut(&Self) -> io::Result<R>,
69    {
70        loop {
71            match op(self) {
72                Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
73                res => return Poll::Ready(res),
74            }
75            // try again if readable now, otherwise come back later:
76            ready!(self.0.poll_readable(cx))?;
77        }
78    }
79}
80
81impl AsyncSocket for SmolSocket {
82    fn socket_ref(&self) -> &Socket {
83        self.0.get_ref()
84    }
85
86    /// Mutable access to underyling [`Socket`]
87    fn socket_mut(&mut self) -> &mut Socket {
88        unsafe { self.0.get_mut() }
89    }
90
91    fn new(protocol: isize) -> io::Result<Self> {
92        let socket = Socket::new(protocol)?;
93        Ok(Self(Async::new(socket)?))
94    }
95
96    fn poll_send(
97        &self,
98        cx: &mut Context<'_>,
99        buf: &[u8],
100    ) -> Poll<io::Result<usize>> {
101        self.poll_write_with(cx, |this| this.socket_ref().send(buf, 0))
102    }
103
104    fn poll_send_to(
105        &self,
106        cx: &mut Context<'_>,
107        buf: &[u8],
108        addr: &SocketAddr,
109    ) -> Poll<io::Result<usize>> {
110        self.poll_write_with(cx, |this| this.socket_ref().send_to(buf, addr, 0))
111    }
112
113    fn poll_recv<B>(
114        &self,
115        cx: &mut Context<'_>,
116        buf: &mut B,
117    ) -> Poll<io::Result<()>>
118    where
119        B: bytes::BufMut,
120    {
121        self.poll_read_with(cx, |this| {
122            this.socket_ref().recv(buf, 0).map(|_len| ())
123        })
124    }
125
126    fn poll_recv_from<B>(
127        &self,
128        cx: &mut Context<'_>,
129        buf: &mut B,
130    ) -> Poll<io::Result<SocketAddr>>
131    where
132        B: bytes::BufMut,
133    {
134        self.poll_read_with(cx, |this| {
135            let x = this.socket_ref().recv_from(buf, 0);
136            trace!("poll_recv_from: {:?}", x);
137            x.map(|(_len, addr)| addr)
138        })
139    }
140
141    fn poll_recv_from_full(
142        &self,
143        cx: &mut Context<'_>,
144    ) -> Poll<io::Result<(Vec<u8>, SocketAddr)>> {
145        self.poll_read_with(cx, |this| this.socket_ref().recv_from_full())
146    }
147}