Debian Codegraph @

third_party/rust/neqo-udp/src/lib.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![expect(
8 clippy::missing_errors_doc,
9 reason = "Functions simply delegate to tokio and quinn-udp."
10 )]
11
12 use std::{
13 array,
14 io::{self, IoSliceMut},
15 iter,
16 net::SocketAddr,
17 slice::{self, ChunksMut},
18 };
19
20 use log::{log_enabled, Level};
21 use neqo_common::{qdebug, qtrace, Datagram, IpTos};
22 use quinn_udp::{EcnCodepoint, RecvMeta, Transmit, UdpSocketState};
23
24 /// Receive buffer size
25 ///
26 /// Fits a maximum size UDP datagram, or, on platforms with segmentation
27 /// offloading, multiple smaller datagrams.
28 const RECV_BUF_SIZE: usize = u16::MAX as usize;
29
30 /// The number of buffers to pass to the OS on [`Socket::recv`].
31 ///
32 /// Platforms without segmentation offloading, i.e. platforms not able to read
33 /// multiple datagrams into a single buffer, can benefit from using multiple
34 /// buffers instead.
35 ///
36 /// Platforms with segmentation offloading have not shown performance
37 /// improvements when additionally using multiple buffers.
38 ///
39 /// - Linux/Android: use segmentation offloading via GRO
40 /// - Windows: use segmentation offloading via URO (caveat see <https://github.com/quinn-rs/quinn/issues/2041>)
41 /// - Apple: no segmentation offloading available, use multiple buffers
42 #[cfg(not(all(apple, feature = "fast-apple-datapath")))]
43 const NUM_BUFS: usize = 1;
44 #[cfg(all(apple, feature = "fast-apple-datapath"))]
45 // Value approximated based on neqo-bin "Download" benchmark only.
46 const NUM_BUFS: usize = 16;
47
48 /// A UDP receive buffer.
49 pub struct RecvBuf(Vec<Vec<u8>>);
50
51 impl RecvBuf {
52 #[must_use]
53 pub fn new() -> Self {
54 Self(vec![vec![0; RECV_BUF_SIZE]; NUM_BUFS])
55 }
56 }
57
58 impl Default for RecvBuf {
59 fn default() -> Self {
60 Self::new()
61 }
62 }
63
64 pub fn send_inner(
65 state: &UdpSocketState,
66 socket: quinn_udp::UdpSockRef<'_>,
67 d: &Datagram,
68 ) -> io::Result<()> {
69 let transmit = Transmit {
70 destination: d.destination(),
71 ecn: EcnCodepoint::from_bits(Into::<u8>::into(d.tos())),
72 contents: d,
73 segment_size: None,
74 src_ip: None,
75 };
76
77 state.try_send(socket, &transmit)?;
78
79 qtrace!(
80 "sent {} bytes from {} to {}",
81 d.len(),
82 d.source(),
83 d.destination()
84 );
85
86 Ok(())
87 }
88
89 #[cfg(unix)]
90 use std::os::fd::AsFd as SocketRef;
91 #[cfg(windows)]
92 use std::os::windows::io::AsSocket as SocketRef;
93
94 #[expect(clippy::missing_panics_doc, reason = "OK here.")]
95 pub fn recv_inner<'a>(
96 local_address: SocketAddr,
97 state: &UdpSocketState,
98 socket: impl SocketRef,
99 recv_buf: &'a mut RecvBuf,
100 ) -> Result<DatagramIter<'a>, io::Error> {
101 let mut metas = [RecvMeta::default(); NUM_BUFS];
102 let mut iovs: [IoSliceMut; NUM_BUFS] = {
103 let mut bufs = recv_buf.0.iter_mut().map(|b| IoSliceMut::new(b));
104 array::from_fn(|_| bufs.next().expect("NUM_BUFS elements"))
105 };
106
107 let n = state.recv((&socket).into(), &mut iovs, &mut metas)?;
108
109 if log_enabled!(Level::Trace) {
110 for meta in metas.iter().take(n) {
111 qtrace!(
112 "received {} bytes from {} to {local_address} in {} segments",
113 meta.len,
114 meta.addr,
115 if meta.stride == 0 {
116 0
117 } else {
118 meta.len.div_ceil(meta.stride)
119 }
120 );
121 }
122 }
123
124 Ok(DatagramIter {
125 current_buffer: None,
126 remaining_buffers: metas.into_iter().zip(recv_buf.0.iter_mut()).take(n),
127 local_address,
128 })
129 }
130
131 pub struct DatagramIter<'a> {
132 /// The current buffer, containing zero or more datagrams, each sharing the
133 /// same [`RecvMeta`].
134 current_buffer: Option<(RecvMeta, ChunksMut<'a, u8>)>,
135 /// Remaining buffers, each containing zero or more datagrams, one
136 /// [`RecvMeta`] per buffer.
137 remaining_buffers:
138 iter::Take<iter::Zip<array::IntoIter<RecvMeta, NUM_BUFS>, slice::IterMut<'a, Vec<u8>>>>,
139 /// The local address of the UDP socket used to receive the datagrams.
140 local_address: SocketAddr,
141 }
142
143 impl<'a> Iterator for DatagramIter<'a> {
144 type Item = Datagram<&'a mut [u8]>;
145
146 fn next(&mut self) -> Option<Self::Item> {
147 loop {
148 // Return the next datagram in the current buffer, if any.
149 if let Some((meta, d)) = self
150 .current_buffer
151 .as_mut()
152 .and_then(|(meta, ds)| ds.next().map(|d| (meta, d)))
153 {
154 return Some(Datagram::from_slice(
155 meta.addr,
156 self.local_address,
157 meta.ecn.map(|n| IpTos::from(n as u8)).unwrap_or_default(),
158 d,
159 ));
160 }
161
162 // There are no more datagrams in the current buffer. Try promoting
163 // one of the remaining buffers, if any, to be the current buffer.
164 let Some((meta, buf)) = self.remaining_buffers.next() else {
165 // Handled all buffers. No more datagrams. Iterator is empty.
166 return None;
167 };
168
169 // Ignore empty datagrams.
170 if meta.len == 0 || meta.stride == 0 {
171 qdebug!(
172 "ignoring empty datagram from {} to {} len {} stride {}",
173 meta.addr,
174 self.local_address,
175 meta.len,
176 meta.stride
177 );
178 continue;
179 }
180
181 // Got another buffer. Let's chunk it into datagrams and return the
182 // first datagram in the next loop iteration.
183 self.current_buffer = Some((meta, buf[0..meta.len].chunks_mut(meta.stride)));
184 }
185 }
186 }
187
188 /// A wrapper around a UDP socket, sending and receiving [`Datagram`]s.
189 pub struct Socket<S> {
190 state: UdpSocketState,
191 inner: S,
192 }
193
194 impl<S: SocketRef> Socket<S> {
195 /// Create a new [`Socket`] given a raw file descriptor managed externally.
196 pub fn new(socket: S) -> Result<Self, io::Error> {
197 Ok(Self {
198 state: UdpSocketState::new((&socket).into())?,
199 inner: socket,
200 })
201 }
202
203 /// Send a [`Datagram`] on the given [`Socket`].
204 pub fn send(&self, d: &Datagram) -> io::Result<()> {
205 send_inner(&self.state, (&self.inner).into(), d)
206 }
207
208 /// Receive a batch of [`Datagram`]s on the given [`Socket`], each
209 /// set with the provided local address.
210 pub fn recv<'a>(
211 &self,
212 local_address: SocketAddr,
213 recv_buf: &'a mut RecvBuf,
214 ) -> Result<DatagramIter<'a>, io::Error> {
215 recv_inner(local_address, &self.state, &self.inner, recv_buf)
216 }
217 }
218
219 #[cfg(test)]
220 mod tests {
221 use std::env;
222
223 use neqo_common::{IpTosDscp, IpTosEcn};
224
225 use super::*;
226
227 fn socket() -> Result<Socket<std::net::UdpSocket>, io::Error> {
228 let socket = Socket::new(std::net::UdpSocket::bind("127.0.0.1:0")?)?;
229 // Reverse non-blocking flag set by `UdpSocketState` to make the test non-racy.
230 socket.inner.set_nonblocking(false)?;
231 Ok(socket)
232 }
233
234 #[test]
235 fn handle_empty_datagram() -> Result<(), io::Error> {
236 // quinn-udp doesn't support sending emtpy datagrams across all
237 // platforms. Use `std` socket instead. See also
238 // <https://github.com/quinn-rs/quinn/pull/2123>.
239 let sender = std::net::UdpSocket::bind("127.0.0.1:0")?;
240 let receiver = socket()?;
241 let receiver_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
242
243 sender.send_to(&[], receiver.inner.local_addr()?)?;
244 let mut recv_buf = RecvBuf::new();
245 let mut datagrams = receiver.recv(receiver_addr, &mut recv_buf)?;
246
247 assert_eq!(datagrams.next(), None);
248
249 Ok(())
250 }
251
252 #[test]
253 fn datagram_tos() -> Result<(), io::Error> {
254 let sender = socket()?;
255 let receiver = socket()?;
256 let receiver_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
257
258 let datagram = Datagram::new(
259 sender.inner.local_addr()?,
260 receiver.inner.local_addr()?,
261 IpTos::from((IpTosDscp::Le, IpTosEcn::Ect1)),
262 b"Hello, world!".to_vec(),
263 );
264
265 sender.send(&datagram)?;
266
267 let mut recv_buf = RecvBuf::new();
268 let mut received_datagrams = receiver
269 .recv(receiver_addr, &mut recv_buf)
270 .expect("receive to succeed");
271
272 // Assert that the ECN is correct.
273 // On Android API level <= 25 the IPv4 `IP_TOS` control message is
274 // not supported and thus ECN bits can not be received.
275 if cfg!(target_os = "android")
276 && env::var("API_LEVEL")
277 .ok()
278 .and_then(|v| v.parse::<u32>().ok())
279 .expect("API_LEVEL environment variable to be set on Android")
280 <= 25
281 {
282 assert_eq!(
283 IpTosEcn::default(),
284 IpTosEcn::from(received_datagrams.next().unwrap().tos())
285 );
286 } else {
287 assert_eq!(
288 IpTosEcn::from(datagram.tos()),
289 IpTosEcn::from(received_datagrams.next().unwrap().tos())
290 );
291 }
292 Ok(())
293 }
294
295 /// Expect [`Socket::recv`] to handle multiple [`Datagram`]s on GRO read.
296 #[test]
297 #[cfg_attr(
298 not(any(target_os = "linux", target_os = "windows")),
299 ignore = "GRO not available"
300 )]
301 fn many_datagrams_through_gro() -> Result<(), io::Error> {
302 const SEGMENT_SIZE: usize = 128;
303
304 let sender = socket()?;
305 let receiver = socket()?;
306 let receiver_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
307
308 // `neqo_udp::Socket::send` does not yet
309 // (https://github.com/mozilla/neqo/issues/1693) support GSO. Use
310 // `quinn_udp` directly.
311 let max_gso_segments = sender.state.max_gso_segments();
312 let msg = vec![0xAB; SEGMENT_SIZE * max_gso_segments];
313 let transmit = Transmit {
314 destination: receiver.inner.local_addr()?,
315 ecn: EcnCodepoint::from_bits(Into::<u8>::into(IpTos::from((
316 IpTosDscp::Le,
317 IpTosEcn::Ect1,
318 )))),
319 contents: &msg,
320 segment_size: Some(SEGMENT_SIZE),
321 src_ip: None,
322 };
323 sender.state.try_send((&sender.inner).into(), &transmit)?;
324
325 // Allow for one GSO sendmmsg to result in multiple GRO recvmmsg.
326 let mut num_received = 0;
327 let mut recv_buf = RecvBuf::new();
328 while num_received < max_gso_segments {
329 receiver
330 .recv(receiver_addr, &mut recv_buf)
331 .expect("receive to succeed")
332 .for_each(|d| {
333 assert_eq!(
334 SEGMENT_SIZE,
335 d.len(),
336 "Expect received datagrams to have same length as sent datagrams"
337 );
338 num_received += 1;
339 });
340 }
341
342 Ok(())
343 }
344 }