Skip to main content

rtci_stream_driver/runtime/
tokio_runtime.rs

1//! [`TokioRuntime`] (feature `runtime-tokio`, on by default).
2
3use super::{
4    AsyncTcpListener, AsyncTcpStream, AsyncUdpSocket, BoxFuture, JoinHandle, MulticastConfig,
5    MulticastInterfaceSelector, RecvMeta, Runtime, TrafficClassMarker, Transmit,
6};
7use shared::stream::{DnsRecord, RecordKind};
8use socket2::SockRef;
9use std::future::Future;
10use std::io::{self, IoSliceMut};
11use std::net::SocketAddr;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::task::{Context, Poll, ready};
15use std::time::Instant;
16#[cfg(not(unix))]
17use tokio::io::ReadBuf;
18use tokio::runtime::Handle;
19
20/// The tokio runtime.
21///
22/// [`TokioRuntime::new`] uses the tokio runtime of the thread at each call, as `tokio::spawn`
23/// does: the driver must then be used inside one (a current-thread runtime on a thread that
24/// entered a network namespace keeps the sockets there). [`TokioRuntime::with_handle`] uses the
25/// runtime of `handle` from anywhere.
26#[derive(Debug, Clone, Default)]
27pub struct TokioRuntime {
28    handle: Option<Handle>,
29}
30
31impl TokioRuntime {
32    /// The tokio runtime the calling code runs in, at each call.
33    pub fn new() -> Self {
34        Self { handle: None }
35    }
36
37    /// The tokio runtime of `handle`.
38    pub fn with_handle(handle: Handle) -> Self {
39        Self {
40            handle: Some(handle),
41        }
42    }
43
44    fn enter(&self) -> Option<tokio::runtime::EnterGuard<'_>> {
45        self.handle.as_ref().map(Handle::enter)
46    }
47}
48
49#[derive(Debug)]
50struct TokioJoinHandle(tokio::task::JoinHandle<()>);
51
52impl JoinHandle for TokioJoinHandle {
53    fn abort(&self) {
54        self.0.abort();
55    }
56
57    fn is_finished(&self) -> bool {
58        self.0.is_finished()
59    }
60
61    fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()> {
62        Pin::new(&mut self.0).poll(cx).map(|_| ())
63    }
64}
65
66impl Runtime for TokioRuntime {
67    fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle> {
68        Box::new(TokioJoinHandle(match &self.handle {
69            Some(handle) => handle.spawn(future),
70            None => tokio::spawn(future),
71        }))
72    }
73
74    fn now(&self) -> Instant {
75        Instant::now()
76    }
77
78    fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()> {
79        let _guard = self.enter();
80        Box::pin(tokio::time::sleep_until(deadline.into()))
81    }
82
83    fn bind_udp(&self, local: SocketAddr) -> io::Result<Arc<dyn AsyncUdpSocket>> {
84        let _guard = self.enter();
85        TokioUdp::wrap(super::std_udp(local)?)
86    }
87
88    fn bind_udp_multicast(&self, config: &MulticastConfig) -> io::Result<Arc<dyn AsyncUdpSocket>> {
89        let _guard = self.enter();
90        TokioUdp::wrap(super::std_multicast(config)?)
91    }
92
93    fn listen_tcp(
94        &self,
95        local: SocketAddr,
96        reuse_address: bool,
97    ) -> io::Result<Arc<dyn AsyncTcpListener>> {
98        let _guard = self.enter();
99        let listener =
100            tokio::net::TcpListener::from_std(super::std_tcp_listener(local, reuse_address)?)?;
101        Ok(Arc::new(TokioListener(listener)))
102    }
103
104    fn connect_tcp(
105        &self,
106        local: SocketAddr,
107        remote: SocketAddr,
108        reuse_address: bool,
109    ) -> BoxFuture<'static, io::Result<Arc<dyn AsyncTcpStream>>> {
110        let _guard = self.enter();
111        let socket = super::std_tcp_bound(local, reuse_address)
112            .map(|socket| tokio::net::TcpSocket::from_std_stream(socket.into()));
113        Box::pin(async move {
114            let stream = socket?.connect(remote).await?;
115            stream.set_nodelay(true)?;
116            Ok(Arc::new(TokioTcp(stream)) as Arc<dyn AsyncTcpStream>)
117        })
118    }
119
120    fn resolve_host(
121        &self,
122        host: &str,
123        port: u16,
124    ) -> BoxFuture<'static, io::Result<Vec<SocketAddr>>> {
125        let host = host.to_owned();
126        Box::pin(async move {
127            Ok(tokio::net::lookup_host((host.as_str(), port))
128                .await?
129                .collect())
130        })
131    }
132
133    #[cfg(feature = "dns-records")]
134    fn resolve_family(
135        &self,
136        host: &str,
137        port: u16,
138        ipv6: bool,
139    ) -> Option<BoxFuture<'static, Vec<SocketAddr>>> {
140        let host = host.to_owned();
141        Some(Box::pin(async move {
142            crate::dns::addresses(&host, port, ipv6).await
143        }))
144    }
145
146    #[cfg(feature = "dns-records")]
147    fn resolve_records(&self, name: &str, kind: RecordKind) -> BoxFuture<'static, Vec<DnsRecord>> {
148        let name = name.to_owned();
149        Box::pin(async move { crate::dns::records(&name, kind).await })
150    }
151
152    #[cfg(not(feature = "dns-records"))]
153    fn resolve_records(&self, name: &str, kind: RecordKind) -> BoxFuture<'static, Vec<DnsRecord>> {
154        // No record lookup without `dns-records`: none, and the engine takes the host's
155        // addresses (RFC 5928 section 3).
156        let _ = (name, kind);
157        Box::pin(std::future::ready(Vec::new()))
158    }
159
160    fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>) {
161        match &self.handle {
162            Some(handle) => handle.block_on(future),
163            None => Handle::current().block_on(future),
164        }
165    }
166}
167
168#[derive(Debug)]
169struct TokioUdp {
170    socket: tokio::net::UdpSocket,
171    ipv6: bool,
172    marker: TrafficClassMarker,
173    interface: MulticastInterfaceSelector,
174}
175
176impl TokioUdp {
177    fn wrap(socket: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>> {
178        let ipv6 = socket.local_addr()?.is_ipv6();
179        // Best effort: where the system refuses, received datagrams carry no ECN.
180        let _ = super::enable_ecn_receive(SockRef::from(&socket), ipv6);
181        Ok(Arc::new(Self {
182            socket: tokio::net::UdpSocket::from_std(socket)?,
183            ipv6,
184            marker: TrafficClassMarker::default(),
185            interface: MulticastInterfaceSelector::default(),
186        }))
187    }
188}
189
190impl AsyncUdpSocket for TokioUdp {
191    fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>> {
192        // A multicast datagram leaves by the interface of its source (RFC 6762 section 14).
193        if let Err(e) = self.interface.apply(SockRef::from(&self.socket), transmit) {
194            return Poll::Ready(Err(e));
195        }
196        self.marker.apply(
197            SockRef::from(&self.socket),
198            self.ipv6,
199            transmit.traffic_class,
200        );
201        self.socket
202            .poll_send_to(cx, transmit.contents, transmit.destination)
203    }
204
205    fn poll_recv(
206        &self,
207        cx: &mut Context<'_>,
208        bufs: &mut [IoSliceMut<'_>],
209        meta: &mut [RecvMeta],
210    ) -> Poll<io::Result<usize>> {
211        let Some(buf) = bufs.first_mut() else {
212            return Poll::Ready(Ok(0));
213        };
214        // With the ECN field of each datagram (`recvmsg` and its TOS / Traffic Class control
215        // message, RFC 6679 section 7.2.1).
216        #[cfg(unix)]
217        loop {
218            ready!(self.socket.poll_recv_ready(cx))?;
219            match self.socket.try_io(tokio::io::Interest::READABLE, || {
220                super::recv_from_with_ecn(SockRef::from(&self.socket), buf)
221            }) {
222                Ok((len, addr, ecn)) => {
223                    meta[0] = RecvMeta {
224                        addr,
225                        len,
226                        stride: len,
227                        ecn,
228                        dst_ip: None,
229                    };
230                    return Poll::Ready(Ok(1));
231                }
232                Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
233                Err(e) => return Poll::Ready(Err(e)),
234            }
235        }
236        #[cfg(not(unix))]
237        let mut read = ReadBuf::new(buf);
238        #[cfg(not(unix))]
239        {
240            let addr = ready!(self.socket.poll_recv_from(cx, &mut read))?;
241            let len = read.filled().len();
242            meta[0] = RecvMeta {
243                addr,
244                len,
245                stride: len,
246                ecn: None,
247                dst_ip: None,
248            };
249            Poll::Ready(Ok(1))
250        }
251    }
252
253    fn local_addr(&self) -> io::Result<SocketAddr> {
254        self.socket.local_addr()
255    }
256
257    fn traffic_class(&self) -> io::Result<u32> {
258        crate::sockets::traffic_class(SockRef::from(&self.socket), self.ipv6)
259    }
260
261    fn unmarked(&self) -> bool {
262        self.marker.refused()
263    }
264
265    fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
266        super::set_dont_fragment(SockRef::from(&self.socket), self.ipv6, on)
267    }
268}
269
270#[derive(Debug)]
271struct TokioTcp(tokio::net::TcpStream);
272
273impl AsyncTcpStream for TokioTcp {
274    fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
275        loop {
276            ready!(self.0.poll_read_ready(cx))?;
277            match self.0.try_read(buf) {
278                Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
279                other => return Poll::Ready(other),
280            }
281        }
282    }
283
284    fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
285        loop {
286            ready!(self.0.poll_write_ready(cx))?;
287            match self.0.try_write(buf) {
288                Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
289                other => return Poll::Ready(other),
290            }
291        }
292    }
293
294    fn shutdown_write(&self) -> io::Result<()> {
295        SockRef::from(&self.0).shutdown(std::net::Shutdown::Write)
296    }
297
298    fn reset_on_close(&self) -> io::Result<()> {
299        super::reset_on_close(SockRef::from(&self.0))
300    }
301
302    fn set_traffic_class(&self, value: u8) -> io::Result<u32> {
303        let ipv6 = self.0.local_addr()?.is_ipv6();
304        super::set_and_read_traffic_class(SockRef::from(&self.0), ipv6, value)
305    }
306
307    fn local_addr(&self) -> io::Result<SocketAddr> {
308        self.0.local_addr()
309    }
310
311    fn peer_addr(&self) -> io::Result<SocketAddr> {
312        self.0.peer_addr()
313    }
314}
315
316#[derive(Debug)]
317struct TokioListener(tokio::net::TcpListener);
318
319impl AsyncTcpListener for TokioListener {
320    fn poll_accept(
321        &self,
322        cx: &mut Context<'_>,
323    ) -> Poll<io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>> {
324        let (stream, remote) = ready!(self.0.poll_accept(cx))?;
325        let _ = stream.set_nodelay(true);
326        Poll::Ready(Ok((Arc::new(TokioTcp(stream)), remote)))
327    }
328
329    fn local_addr(&self) -> io::Result<SocketAddr> {
330        self.0.local_addr()
331    }
332}