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